Search is not available for this dataset
qid
int64
1
74.7M
question
stringlengths
25
64.6k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
115k
response_k
stringlengths
3
61.5k
30,601,573
I got a school assignment which is an introduction to object-oriented programming. I'm really close to solving this problem, just having some problem with the syntax I guess. Perhaps some of you pros knows exactly what the problem is? Got my class here: ``` class CashRegister(): __taxRate = 0 __numProductsSold = 0 __totalRevenue = 0.0 __taxAmount = 0.0 __soldProducts = [] def __init__(self, taxRate): self.__taxRate = taxRate def getNumProductsSold(self): return self.__numProductsSold def getTotalRevenue(self): return self.__totalRevenue def getTaxAmount(self): return self.__taxAmount def getSoldProducts(self): return self.__soldProducts def addItem(self, product, price): self.__numProductsSold +=1 self.__totalRevenue += price self.__taxAmount += price * self.__taxRate self.__soldProducts.append(product) ``` and I'm trying to call it here: ``` import CashRegister def main(): testRegister = CashRegister(22) testProduct = "Mat" testRegister.addItem(testProduct, 23.99) print testRegister.getTotalRevenue () if __name__ == '__main__': main(); ``` Anyone spotting the problem? Getting error message as header says.
2015/06/02
[ "https://Stackoverflow.com/questions/30601573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4966169/" ]
The "CashRegister" class in the imported "CashRegister" module is accessed as `CashRegister.CashRegister`.
You need to tell your program which methods from `CashRegister` you want to use, so you have a few options: > > option 1 > > > ``` import CashRegister def main(): testRegister = CashRegister.CashRegister(22) testProduct = "Mat" testRegister.addItem(testProduct, 23.99) print testRegister.getTotalRevenue () if __name__ == '__main__': main(); ``` In option 1, you're telling the interpreter to not get confused about which `CashRegister` method you're wanting to call -- it's the one within the `CashRegister` class. > > option 2 > > > ``` from CashRegister import CashRegister def main(): testRegister = CashRegister(22) testProduct = "Mat" testRegister.addItem(testProduct, 23.99) print testRegister.getTotalRevenue () if __name__ == '__main__': main(); ``` In option 2, you're telling the interpreter that you're only importing `CashRegister`'s constructor from the class, and this should be assumed when you call `CashRegister` in the code. There's another option which is not necessary in *this* application, but would still work. It's better when you have many methods within a class. Here's that option. > > option 3 > > > ``` from CashRegister import * def main(): testRegister = CashRegister(22) testProduct = "Mat" testRegister.addItem(testProduct, 23.99) print testRegister.getTotalRevenue () if __name__ == '__main__': main(); ``` In option 3, you're telling the compiler that you want to bring *all* of the methods from the class into the scope of the program and you won't need to specify the owning class.
30,601,573
I got a school assignment which is an introduction to object-oriented programming. I'm really close to solving this problem, just having some problem with the syntax I guess. Perhaps some of you pros knows exactly what the problem is? Got my class here: ``` class CashRegister(): __taxRate = 0 __numProductsSold = 0 __totalRevenue = 0.0 __taxAmount = 0.0 __soldProducts = [] def __init__(self, taxRate): self.__taxRate = taxRate def getNumProductsSold(self): return self.__numProductsSold def getTotalRevenue(self): return self.__totalRevenue def getTaxAmount(self): return self.__taxAmount def getSoldProducts(self): return self.__soldProducts def addItem(self, product, price): self.__numProductsSold +=1 self.__totalRevenue += price self.__taxAmount += price * self.__taxRate self.__soldProducts.append(product) ``` and I'm trying to call it here: ``` import CashRegister def main(): testRegister = CashRegister(22) testProduct = "Mat" testRegister.addItem(testProduct, 23.99) print testRegister.getTotalRevenue () if __name__ == '__main__': main(); ``` Anyone spotting the problem? Getting error message as header says.
2015/06/02
[ "https://Stackoverflow.com/questions/30601573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4966169/" ]
Python makes no assumptions about the names of your classes from the names of your modules and it allows a module to hold multiple classes. You need to import your classes explicitly or reference them as members of the module object. By convention, module names are lower case and class names begin with an upper case letter. For example: ``` # mymodule.py class ClassOne(object): pass class ClassTwo(object): pass ``` in another file: ``` from mymodule import ClassOne, ClassTwo one = ClassOne() ``` or ``` import mymodule one = mymodule.ClassOne() ```
You need to tell your program which methods from `CashRegister` you want to use, so you have a few options: > > option 1 > > > ``` import CashRegister def main(): testRegister = CashRegister.CashRegister(22) testProduct = "Mat" testRegister.addItem(testProduct, 23.99) print testRegister.getTotalRevenue () if __name__ == '__main__': main(); ``` In option 1, you're telling the interpreter to not get confused about which `CashRegister` method you're wanting to call -- it's the one within the `CashRegister` class. > > option 2 > > > ``` from CashRegister import CashRegister def main(): testRegister = CashRegister(22) testProduct = "Mat" testRegister.addItem(testProduct, 23.99) print testRegister.getTotalRevenue () if __name__ == '__main__': main(); ``` In option 2, you're telling the interpreter that you're only importing `CashRegister`'s constructor from the class, and this should be assumed when you call `CashRegister` in the code. There's another option which is not necessary in *this* application, but would still work. It's better when you have many methods within a class. Here's that option. > > option 3 > > > ``` from CashRegister import * def main(): testRegister = CashRegister(22) testProduct = "Mat" testRegister.addItem(testProduct, 23.99) print testRegister.getTotalRevenue () if __name__ == '__main__': main(); ``` In option 3, you're telling the compiler that you want to bring *all* of the methods from the class into the scope of the program and you won't need to specify the owning class.
14,066,854
I want to convert date `2012-12-26` to `december 26, 2012` in iOS? I am using websrvice and the data comes in this format `1990-12-26`. I want to change this to `december 26, 2012` format. This is what I am doing: ``` lbl_Rightside.text = [rootElement stringValueForNode:@"date"]; NSLog(@"lbl_Rightside is %@",lbl_Rightside.text); [lbl_Rightside release]; ``` Getting date to this label on `1990-12-26`. Now I want to change date to `december 26, 2012` format. Any hints from experts would be very welcome.
2012/12/28
[ "https://Stackoverflow.com/questions/14066854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1903360/" ]
Check the official Apple documentation about [NSDateFormatter](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html). You should use this class to do this kind of formatting.
by using `NSDateFormatter` **NSString to NSDate** ``` NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; // this is imporant - we set our input date format to match our input string // if format doesn't match you'll get nil from your string, so be careful [dateFormatter setDateFormat:@"yyyy-MM-dd"]; NSDate *dateFromString = [[NSDate alloc] init]; dateFromString = [dateFormatter dateFromString:dateString]; [dateFormatter release]; ``` **NSDate convert to NSString:** ``` NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"MMMM dd, yyyy"]; NSString *strDate = [dateFormatter stringFromDate:[NSDate date]]; NSLog(@"%@", strDate); [dateFormatter release]; ```
14,066,854
I want to convert date `2012-12-26` to `december 26, 2012` in iOS? I am using websrvice and the data comes in this format `1990-12-26`. I want to change this to `december 26, 2012` format. This is what I am doing: ``` lbl_Rightside.text = [rootElement stringValueForNode:@"date"]; NSLog(@"lbl_Rightside is %@",lbl_Rightside.text); [lbl_Rightside release]; ``` Getting date to this label on `1990-12-26`. Now I want to change date to `december 26, 2012` format. Any hints from experts would be very welcome.
2012/12/28
[ "https://Stackoverflow.com/questions/14066854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1903360/" ]
you can use [NSDateFormatter](https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html) to do this kind of things. First 1. convert your date String to a date object using dateFromString: method. 2. from date convert to string you want using stringFromDate: method 3. Different format strings can be found [here](http://www.alexcurylo.com/blog/2009/01/29/nsdateformatter-formatting/). ``` NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; NSDate *orignalDate = [dateFormatter dateFromString:YOUR_ORIGINAL_STRING]; [dateFormatter setDateFormat:@"MMMM dd, yyyy"]; NSString *finalString = [dateFormatter stringFromDate:orignalDate]; [dateFormatter release]; //if not using ARC ```
Check the official Apple documentation about [NSDateFormatter](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html). You should use this class to do this kind of formatting.
14,066,854
I want to convert date `2012-12-26` to `december 26, 2012` in iOS? I am using websrvice and the data comes in this format `1990-12-26`. I want to change this to `december 26, 2012` format. This is what I am doing: ``` lbl_Rightside.text = [rootElement stringValueForNode:@"date"]; NSLog(@"lbl_Rightside is %@",lbl_Rightside.text); [lbl_Rightside release]; ``` Getting date to this label on `1990-12-26`. Now I want to change date to `december 26, 2012` format. Any hints from experts would be very welcome.
2012/12/28
[ "https://Stackoverflow.com/questions/14066854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1903360/" ]
Check the official Apple documentation about [NSDateFormatter](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html). You should use this class to do this kind of formatting.
Try to look at [**NSDateFormatter**](https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40003643) Class, ``` NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; // this is your input date format NSDate *newDate = [dateFormatter dateFromString:dateString];//converting string to date object ``` The format you are looking for is something like: ``` [dateFormatter setDateFormat:@"MMM dd,yyy"]; // setting new format NSLog(@"The date is = %@",[dateFormatter stringFromDate:newDate]) ```
14,066,854
I want to convert date `2012-12-26` to `december 26, 2012` in iOS? I am using websrvice and the data comes in this format `1990-12-26`. I want to change this to `december 26, 2012` format. This is what I am doing: ``` lbl_Rightside.text = [rootElement stringValueForNode:@"date"]; NSLog(@"lbl_Rightside is %@",lbl_Rightside.text); [lbl_Rightside release]; ``` Getting date to this label on `1990-12-26`. Now I want to change date to `december 26, 2012` format. Any hints from experts would be very welcome.
2012/12/28
[ "https://Stackoverflow.com/questions/14066854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1903360/" ]
you can use [NSDateFormatter](https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html) to do this kind of things. First 1. convert your date String to a date object using dateFromString: method. 2. from date convert to string you want using stringFromDate: method 3. Different format strings can be found [here](http://www.alexcurylo.com/blog/2009/01/29/nsdateformatter-formatting/). ``` NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; NSDate *orignalDate = [dateFormatter dateFromString:YOUR_ORIGINAL_STRING]; [dateFormatter setDateFormat:@"MMMM dd, yyyy"]; NSString *finalString = [dateFormatter stringFromDate:orignalDate]; [dateFormatter release]; //if not using ARC ```
by using `NSDateFormatter` **NSString to NSDate** ``` NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; // this is imporant - we set our input date format to match our input string // if format doesn't match you'll get nil from your string, so be careful [dateFormatter setDateFormat:@"yyyy-MM-dd"]; NSDate *dateFromString = [[NSDate alloc] init]; dateFromString = [dateFormatter dateFromString:dateString]; [dateFormatter release]; ``` **NSDate convert to NSString:** ``` NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"MMMM dd, yyyy"]; NSString *strDate = [dateFormatter stringFromDate:[NSDate date]]; NSLog(@"%@", strDate); [dateFormatter release]; ```
14,066,854
I want to convert date `2012-12-26` to `december 26, 2012` in iOS? I am using websrvice and the data comes in this format `1990-12-26`. I want to change this to `december 26, 2012` format. This is what I am doing: ``` lbl_Rightside.text = [rootElement stringValueForNode:@"date"]; NSLog(@"lbl_Rightside is %@",lbl_Rightside.text); [lbl_Rightside release]; ``` Getting date to this label on `1990-12-26`. Now I want to change date to `december 26, 2012` format. Any hints from experts would be very welcome.
2012/12/28
[ "https://Stackoverflow.com/questions/14066854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1903360/" ]
you can use [NSDateFormatter](https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html) to do this kind of things. First 1. convert your date String to a date object using dateFromString: method. 2. from date convert to string you want using stringFromDate: method 3. Different format strings can be found [here](http://www.alexcurylo.com/blog/2009/01/29/nsdateformatter-formatting/). ``` NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; NSDate *orignalDate = [dateFormatter dateFromString:YOUR_ORIGINAL_STRING]; [dateFormatter setDateFormat:@"MMMM dd, yyyy"]; NSString *finalString = [dateFormatter stringFromDate:orignalDate]; [dateFormatter release]; //if not using ARC ```
Try to look at [**NSDateFormatter**](https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40003643) Class, ``` NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd"]; // this is your input date format NSDate *newDate = [dateFormatter dateFromString:dateString];//converting string to date object ``` The format you are looking for is something like: ``` [dateFormatter setDateFormat:@"MMM dd,yyy"]; // setting new format NSLog(@"The date is = %@",[dateFormatter stringFromDate:newDate]) ```
42,354,598
I have an XML file which contains ![CDATA[]] data. Like this: ``` <link><![CDATA[https://google.de]]></link> ``` Now I heard that I can not modify ![CDATA[]] data or that they contains some special characters. But I do not remember anymore... That's the reason why I'am asking here. Can I change the values in ![CDATA[]] and if yes, how? I just want to append something like "?=dadc" on the link. **Edit:** My XML file structure (Want to edit the url): ``` <?xml version="1.0" encoding="UTF-8"?> <rss> <channel xmlns:g="http://base.google.com/ns/1.0" version="2.0"> <title>Google Eur English 1</title> <description/> <item> <title>Anno 2070</title> <g:image_link><![CDATA[http://cdn.kinguin.net/media/catalog/category/anno_8.jpg]]></g:image_link> <url><![CDATA[http://www.kinguin.net/category/4/anno-2070/?nosalesbooster=1&country_store=1&currency=EUR]]></url> <price><![CDATA[3.88 EUR]]></price> <platform>Uplay</platform> </item> </channel> </rss> ``` Greetings
2017/02/20
[ "https://Stackoverflow.com/questions/42354598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7547694/" ]
That is true for SimpleXML. CDATA Sections are a special kind of text nodes. They are actually here to make embedded parts more readable for humans. SimpleXML does not really handle XML nodes so you will have to let it convert them to standard text nodes. If you have a JS or HTML fragment in XML it is easier to read if the special characters like `<` are not escaped. And this is what CDATA sections are for (and some backwards compatibility for browsers). So to modify a CDATA section and keep it, you will have to use DOM. DOM actually knows about the different node types. Here is a small example: ``` $xml = '<link><![CDATA[https://google.de]]></link>'; $document = new DOMDocument(); $document->loadXml($xml); $xpath = new DOMXpath($document); foreach ($xpath->evaluate('//link/text()') as $linkValue) { $linkValue->data .= '?abc'; } echo $document->saveXml(); ``` Output: ``` <?xml version="1.0"?> <link><![CDATA[https://google.de?abc]]></link> ```
Fortunately yes!, check this: ``` $link = simplexml_load_string( '<link><![CDATA[Hello, world!]]></link>' ); echo (string)$link; ``` [PHP: How to handle <![CDATA[ with SimpleXMLElement?](https://stackoverflow.com/questions/2970602/php-how-to-handle-cdata-with-simplexmlelement) Regards, Idir
28,045,947
I have the following mysql query result: ``` +----+------------+-------------+ | id | title | lang | +----+------------+-------------- | 1 | ola1 | 1 | | 1 | hello1 | 2 | | 1 | bonjour1 | 3 | | 2 | ola2 | 1 | | 2 | bonjour2 | 3 | | 3 | hello3 | 2 | | 4 | bonjour4 | 3 | +----+------------+-------------+ ``` What I want is a group\_by query by id and that gives me for each id the title with a order of preference for lang field. Example: Result for lang preference order 1, 2, 3: ``` +----+------------+-------------+ | id | title | lang | +----+------------+-------------- | 1 | ola1 | 1 | | 2 | ola2 | 1 | | 3 | hello3 | 2 | | 4 | bonjour4 | 3 | +----+------------+-------------+ ``` Result for lang preference order 3, 2, 1: ``` +----+------------+-------------+ | id | title | lang | +----+------------+-------------- | 1 | bonjour1 | 3 | | 2 | bonjour2 | 3 | | 3 | hello3 | 2 | | 4 | bonjour4 | 3 | +----+------------+-------------+ ``` Thanks!
2015/01/20
[ "https://Stackoverflow.com/questions/28045947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1126167/" ]
It is either not possible, or, not with in my SQL skills to execute that in one query. I always end up using a temporary template and two SQL commands for these problems: (assuming that your table is called Table1 and the temporary table should be called tempTable) ``` SELECT Table1.id, Min(Table1.lang) AS Min_Of_lang INTO tempTable FROM Table1 GROUP BY Table1.id ORDER BY Table1.id; SELECT Table1.* FROM tempTable INNER JOIN Table1 ON (tempTable.MinOflang = Table1.lang) AND (tempTable.id = Table1.id); ``` The first command creates a new table (that overrides the current table if it exists). The second command uses the first table to produce the desired result set. To change from your first desired results table to the second, use Max instead of min in the first query. Somebody else may well have a more elegant solution than mine. Also, an extra SQL statement could be added to delete the temporary table.
This is a feature that is not defined in MySQL. The displayed value in a non-aggregated column is undetermined. [read more here (MySQL Documentation)](http://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html "read more here: MySQL documentation"). (Standard SQL doesn't allow to include non-aggregated columns when using GROUP BY, I guess this is one of the reasons). From your description of the what you want to do, you should simple SELECT all rows with the lang you are looking for ``` SELECT * FROM your_table WHERE lang = 1 ```
49,425,550
Hello I am trying to store the name of the player with the high score in the `sharedpreferences`. I want it to be the top 5 players. Now if I try to store an array in there I get the error: "Wrong 2nd argument type. Found '`java.lang.String[][]' required 'java.util.Set<java.lang.String>`'" ``` public static void setHighScore(Context context, String name, int score) { String[] player = new String[] {name, String.valueOf(score)}; String[][] highScores = new String[][] {player}; SharedPreferences.Editor editor = getPreferences(context).edit(); editor.putStringSet(PLAYER, highScores); editor.apply(); } ``` How can I store a name and a score of multiple players? Thanks in advance!
2018/03/22
[ "https://Stackoverflow.com/questions/49425550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9184161/" ]
Your error says explicitly that you need to pass a Set object to the function `putStringSet()`. As explained in the [documentation](https://developer.android.com/reference/android/content/SharedPreferences.Editor.html#putStringSet(java.lang.String,%20java.util.Set%3Cjava.lang.String%3E)). Reguarding to this, I think using SharedPreferences to store your HighScores is a bad idea. You will face different problems. **First choice :** Use the player name as key, use just `putString` as we put one value ``` public static void setHighScore(Context context, String name, int score) { Set<String> scoreSet = new HashSet<String>(); scoreSet.add(String.valueOf(score)); SharedPreferences.Editor editor = getPreferences(context).edit(); editor.putString(name, scoreSet); editor.apply(); } ``` This is a really bad implementation. Because it will be hard to retrieve your score since the key is the player name and will always change. **Second Choice :** Use only one key and store all the score in a Set ``` public static void setHighScore(Context context, String name, int score) { SharedPreferences prefs = getPreferences(context); Set<String> scoreSet = prefs.getStringSet("highScores"); //I use "highScores" as the key, but could be what you want // You need to create a function that find the lower scores and remove it removeLower(scoreSet); scoreSet.add(name + ":" + String.valueOf(score)); //need to define a pattern to separate name from score SharedPreferences.Editor editor = prefs.edit(); editor.putStringSet("highScores", scoreSet); editor.apply(); } ``` This is also not a good idea. Because you need to redefine a function to find the lower score and remove it. You also need to define a pattern to store name + score. Then you need to define a function to read scores to separate the name from the score. **Solution :** The good solution here is to use a database. Preferences are not design to stored data but preferences. Also a database will provides functionality to easily store/retrieve/order/etc your data. Have a look [here](https://developer.android.com/training/data-storage/room/index.html)
Convert your double dimension array to string and save the string in shared preference. **Here is the code** ``` private String twoDimensionalStringArrayToString(String[][] s) throws UnsupportedEncodingException, IOException { ByteArrayOutputStream bo = null; ObjectOutputStream so = null; Base64OutputStream b64 = null; try { bo = new ByteArrayOutputStream(); b64 = new Base64OutputStream(bo, Base64.DEFAULT); so = new ObjectOutputStream(b64); so.writeObject(s); return bo.toString("UTF-8"); } finally { if (bo != null) { bo.close(); } if (b64 != null) { b64.close(); } if (so != null) { so.close(); } } } ``` Save the string in Shared preference ``` prefsEditor.putString(PLAYLISTS, sb.toString()); ``` Check this post for further details [how to store 2dimensional array in shared preferences in android or serialize it](https://stackoverflow.com/questions/23261540/how-to-store-2dimensional-array-in-shared-preferences-in-android-or-serialize-it)
5,890,313
I am trying to query a database, but it seems to just load for an age and not do anything. It's a simple query and shouldnt take longer than a millisecond. ``` while($row = mysql_fetch_array(getWallPosts($userid))) { } ``` Now when I replace this code with: ``` echo mysql_num_rows(getWallPosts($userid)); ``` It just displays '1' in fact there's only one record in the DB and it's just a simple SELECT statement. Here's the getWallPosts function: ``` function getWallPosts($userid, $limit = "10") { $result = dbquery("SELECT * FROM commentpost WHERE userID = ".$userid." ORDER BY commentPostID DESC LIMIT 0, ".$limit); return $result; } ``` Also, when I put the SQL string that it's executing into MySQL's query browser. It takes no time at all. Any ideas?
2011/05/04
[ "https://Stackoverflow.com/questions/5890313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/522330/" ]
You appear to be looping indefinitely because you're retrieving a new set (one record) of data each time. ``` $result = getWallPosts($userid); while ($row = mysql_fetch_array($result)) { //printf($row[0]); } ```
You need to get the data once and loop through it. Your code is getting the data, running the loop and then getting the data again. Try: ``` $posts = getWallPosts($userid); while($row = mysql_fetch_array($posts)) { //Code to execute } ```
5,890,313
I am trying to query a database, but it seems to just load for an age and not do anything. It's a simple query and shouldnt take longer than a millisecond. ``` while($row = mysql_fetch_array(getWallPosts($userid))) { } ``` Now when I replace this code with: ``` echo mysql_num_rows(getWallPosts($userid)); ``` It just displays '1' in fact there's only one record in the DB and it's just a simple SELECT statement. Here's the getWallPosts function: ``` function getWallPosts($userid, $limit = "10") { $result = dbquery("SELECT * FROM commentpost WHERE userID = ".$userid." ORDER BY commentPostID DESC LIMIT 0, ".$limit); return $result; } ``` Also, when I put the SQL string that it's executing into MySQL's query browser. It takes no time at all. Any ideas?
2011/05/04
[ "https://Stackoverflow.com/questions/5890313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/522330/" ]
You appear to be looping indefinitely because you're retrieving a new set (one record) of data each time. ``` $result = getWallPosts($userid); while ($row = mysql_fetch_array($result)) { //printf($row[0]); } ```
Its an infinite loop. The expression in the while always executes so it will always be true.
5,890,313
I am trying to query a database, but it seems to just load for an age and not do anything. It's a simple query and shouldnt take longer than a millisecond. ``` while($row = mysql_fetch_array(getWallPosts($userid))) { } ``` Now when I replace this code with: ``` echo mysql_num_rows(getWallPosts($userid)); ``` It just displays '1' in fact there's only one record in the DB and it's just a simple SELECT statement. Here's the getWallPosts function: ``` function getWallPosts($userid, $limit = "10") { $result = dbquery("SELECT * FROM commentpost WHERE userID = ".$userid." ORDER BY commentPostID DESC LIMIT 0, ".$limit); return $result; } ``` Also, when I put the SQL string that it's executing into MySQL's query browser. It takes no time at all. Any ideas?
2011/05/04
[ "https://Stackoverflow.com/questions/5890313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/522330/" ]
You appear to be looping indefinitely because you're retrieving a new set (one record) of data each time. ``` $result = getWallPosts($userid); while ($row = mysql_fetch_array($result)) { //printf($row[0]); } ```
You're returning a new result set each time the while statement executes. You should call `getWallPosts` first, assign it to $results, and then loop over it.
5,890,313
I am trying to query a database, but it seems to just load for an age and not do anything. It's a simple query and shouldnt take longer than a millisecond. ``` while($row = mysql_fetch_array(getWallPosts($userid))) { } ``` Now when I replace this code with: ``` echo mysql_num_rows(getWallPosts($userid)); ``` It just displays '1' in fact there's only one record in the DB and it's just a simple SELECT statement. Here's the getWallPosts function: ``` function getWallPosts($userid, $limit = "10") { $result = dbquery("SELECT * FROM commentpost WHERE userID = ".$userid." ORDER BY commentPostID DESC LIMIT 0, ".$limit); return $result; } ``` Also, when I put the SQL string that it's executing into MySQL's query browser. It takes no time at all. Any ideas?
2011/05/04
[ "https://Stackoverflow.com/questions/5890313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/522330/" ]
You need to get the data once and loop through it. Your code is getting the data, running the loop and then getting the data again. Try: ``` $posts = getWallPosts($userid); while($row = mysql_fetch_array($posts)) { //Code to execute } ```
Its an infinite loop. The expression in the while always executes so it will always be true.
5,890,313
I am trying to query a database, but it seems to just load for an age and not do anything. It's a simple query and shouldnt take longer than a millisecond. ``` while($row = mysql_fetch_array(getWallPosts($userid))) { } ``` Now when I replace this code with: ``` echo mysql_num_rows(getWallPosts($userid)); ``` It just displays '1' in fact there's only one record in the DB and it's just a simple SELECT statement. Here's the getWallPosts function: ``` function getWallPosts($userid, $limit = "10") { $result = dbquery("SELECT * FROM commentpost WHERE userID = ".$userid." ORDER BY commentPostID DESC LIMIT 0, ".$limit); return $result; } ``` Also, when I put the SQL string that it's executing into MySQL's query browser. It takes no time at all. Any ideas?
2011/05/04
[ "https://Stackoverflow.com/questions/5890313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/522330/" ]
You need to get the data once and loop through it. Your code is getting the data, running the loop and then getting the data again. Try: ``` $posts = getWallPosts($userid); while($row = mysql_fetch_array($posts)) { //Code to execute } ```
You're returning a new result set each time the while statement executes. You should call `getWallPosts` first, assign it to $results, and then loop over it.
35,765,687
While we use any method from the interface it asks us to override all unimplemented method. also we are using '@Override' annotation while implementing the method. Does it really called overriding ? because interface contains only method definition(no executable code). The interface is say, ``` public interface ITestListener extends ITestNGListener { void onTestStart(ITestResult result); public void onTestSuccess(ITestResult result); public void onTestFailure(ITestResult result); public void onTestSkipped(ITestResult result); public void onTestFailedButWithinSuccessPercentage(ITestResult result); } ``` and the implementing class is ``` public class TestNGTestBase implements ITestListener{ @Override public void onTestStart(ITestResult result) { //xyz } @Override public void onTestSuccess(ITestResult result) { /// xyz} @Override public void onTestSkipped(ITestResult result) { } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) { // TODO Auto-generated method stub }} ``` also why is this mandatory to override all the methods in the interface ?
2016/03/03
[ "https://Stackoverflow.com/questions/35765687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4810731/" ]
Yes the method is overriding from the superclass. This notation would create a compile time error if the method signature of any of these methods would change. Overriding is a feature that is available while using Inheritance. It is used when a class that extends from another class wants to use most of the feature of the parent class and wants to implement specific functionality in certain cases.
@Overriding ensures the method is a correct override and gives compile time error if its not a valid override. It is not mandatory to override all methods of an interface in a class,you need to declare the class "abstract" in this scenario. But if you want a concrete class(which can be instantiated) to implement an interface,you will need to implement all methods of your interface in this concrete class
16,435,122
**activity\_main.xml** ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" tools:context=".MainActivity" > <fragment android:id="@+id/fragment1" android:name="sithi.test.fragmenttest.Fragment1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> ``` **fragment1.xml** ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" android:onClick="btnClick1" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" /> </LinearLayout> ``` **ActivityMain.java** ``` public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } } ``` **Fragment1.java** ``` @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class Fragment1 extends Fragment { TextView tv; @Override public void onStart() { // TODO Auto-generated method stub super.onStart(); tv=(TextView)getView().findViewById(R.id.textView1); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // TODO Auto-generated method stub //inflater.inflate(resource, root, attachToRoot); return inflater.inflate(R.layout.fragment1, container, false); } public void btnClick1(View view) { tv.setText("dsdsdasda"); } } ``` I created xml files and classes like this but `btnClick1()` does not work in Android Fragment. It will getting an error when i clicking that button in the fragment. I have written that button click function inside the Fragment class.
2013/05/08
[ "https://Stackoverflow.com/questions/16435122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2361252/" ]
The way XML onClick is implemented is directed to Activities, not Fragments. The activity should own the `btnClick1` method, not a fragment.
You need to assign OnClickListener in fragment code to make it work. See Snicolas answer for the "why".
16,435,122
**activity\_main.xml** ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" tools:context=".MainActivity" > <fragment android:id="@+id/fragment1" android:name="sithi.test.fragmenttest.Fragment1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> ``` **fragment1.xml** ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" android:onClick="btnClick1" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" /> </LinearLayout> ``` **ActivityMain.java** ``` public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } } ``` **Fragment1.java** ``` @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class Fragment1 extends Fragment { TextView tv; @Override public void onStart() { // TODO Auto-generated method stub super.onStart(); tv=(TextView)getView().findViewById(R.id.textView1); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // TODO Auto-generated method stub //inflater.inflate(resource, root, attachToRoot); return inflater.inflate(R.layout.fragment1, container, false); } public void btnClick1(View view) { tv.setText("dsdsdasda"); } } ``` I created xml files and classes like this but `btnClick1()` does not work in Android Fragment. It will getting an error when i clicking that button in the fragment. I have written that button click function inside the Fragment class.
2013/05/08
[ "https://Stackoverflow.com/questions/16435122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2361252/" ]
The way XML onClick is implemented is directed to Activities, not Fragments. The activity should own the `btnClick1` method, not a fragment.
Since others have addressed setting onClick listener, let me add that if you have done so, and still getting the error check permissions required. For my case, the item on fragment was meant to open chat which requires microphone so it was not working until I added appropriate permissions in Manifest file.
16,435,122
**activity\_main.xml** ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" tools:context=".MainActivity" > <fragment android:id="@+id/fragment1" android:name="sithi.test.fragmenttest.Fragment1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> ``` **fragment1.xml** ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" android:onClick="btnClick1" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" /> </LinearLayout> ``` **ActivityMain.java** ``` public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } } ``` **Fragment1.java** ``` @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class Fragment1 extends Fragment { TextView tv; @Override public void onStart() { // TODO Auto-generated method stub super.onStart(); tv=(TextView)getView().findViewById(R.id.textView1); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // TODO Auto-generated method stub //inflater.inflate(resource, root, attachToRoot); return inflater.inflate(R.layout.fragment1, container, false); } public void btnClick1(View view) { tv.setText("dsdsdasda"); } } ``` I created xml files and classes like this but `btnClick1()` does not work in Android Fragment. It will getting an error when i clicking that button in the fragment. I have written that button click function inside the Fragment class.
2013/05/08
[ "https://Stackoverflow.com/questions/16435122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2361252/" ]
You need to assign OnClickListener in fragment code to make it work. See Snicolas answer for the "why".
Since others have addressed setting onClick listener, let me add that if you have done so, and still getting the error check permissions required. For my case, the item on fragment was meant to open chat which requires microphone so it was not working until I added appropriate permissions in Manifest file.
11,456,334
Why is the `Tags` property of `Book` empty after this code runs? ``` class Program { static void Main(string[] args) { List<Book> books = new List<Book>(); List<String> tags = new List<String> {"tag1", "tag2", "tag3"}; String title = "a title"; books.Add(new Book { Title = title, Author = "an author", Tags = tags }); Console.WriteLine("(" + title + ")"); Console.WriteLine((books[0]).Tags.Count()); title = String.Empty; tags.Clear(); Console.WriteLine("(" + title + ")"); Console.WriteLine((books[0]).Tags.Count()); } } ``` The code for `Book`: ``` public class Book { public String Title { get; set; } public String Author { get; set; } public List<String> Tags { get; set; } } ``` Running this code outputs ``` ("a title") 3 () 0 ``` Are `tags` and `title` being passed by reference here? Renaming the respective properties produces the same output. ### EDIT: I just realised that I meant for every `Console.WriteLine` statement to refer to the object, not just the tags one. I meant this: ``` Book aBook = books[0]; Console.WriteLine("(" + aBook.Title + ")"); Console.WriteLine(aBook.Tags.Count()); title = String.Empty; tags.Clear(); Console.WriteLine("(" + aBook.Title + ")"); Console.WriteLine(aBook.Tags.Count()); ``` which as expected, outputs: ``` ("a title") 3 ("a title") 0 ``` but since I made a mistake in my initial question, I'm leaving it as is since the parts of the answers that refer to `title` are referencing the original code.
2012/07/12
[ "https://Stackoverflow.com/questions/11456334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/869912/" ]
[`List<T>`](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) is a reference type, so yes, you get reference semantics here. You need to assign a *copy* of `tags` to the property if you want them to be independent. ``` Tags = new List<string>(tags); ```
The `Tags` property of your `Book` object refers **to the same object instance** as the list you created on your second line of code (`List<String> tags = new List<String> {"tag1", "tag2", "tag3"};`). When you wrote `Tags = tags`, you're actually saying that `Tags` *points* to the same instance that `tags`. That's why when you clear `tags`, `Tags` is cleared too as it's **the same object reference**.
11,456,334
Why is the `Tags` property of `Book` empty after this code runs? ``` class Program { static void Main(string[] args) { List<Book> books = new List<Book>(); List<String> tags = new List<String> {"tag1", "tag2", "tag3"}; String title = "a title"; books.Add(new Book { Title = title, Author = "an author", Tags = tags }); Console.WriteLine("(" + title + ")"); Console.WriteLine((books[0]).Tags.Count()); title = String.Empty; tags.Clear(); Console.WriteLine("(" + title + ")"); Console.WriteLine((books[0]).Tags.Count()); } } ``` The code for `Book`: ``` public class Book { public String Title { get; set; } public String Author { get; set; } public List<String> Tags { get; set; } } ``` Running this code outputs ``` ("a title") 3 () 0 ``` Are `tags` and `title` being passed by reference here? Renaming the respective properties produces the same output. ### EDIT: I just realised that I meant for every `Console.WriteLine` statement to refer to the object, not just the tags one. I meant this: ``` Book aBook = books[0]; Console.WriteLine("(" + aBook.Title + ")"); Console.WriteLine(aBook.Tags.Count()); title = String.Empty; tags.Clear(); Console.WriteLine("(" + aBook.Title + ")"); Console.WriteLine(aBook.Tags.Count()); ``` which as expected, outputs: ``` ("a title") 3 ("a title") 0 ``` but since I made a mistake in my initial question, I'm leaving it as is since the parts of the answers that refer to `title` are referencing the original code.
2012/07/12
[ "https://Stackoverflow.com/questions/11456334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/869912/" ]
[`List<T>`](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) is a reference type, so yes, you get reference semantics here. You need to assign a *copy* of `tags` to the property if you want them to be independent. ``` Tags = new List<string>(tags); ```
> > Are tags and title being passed by reference here? > > > Yes. However, the confusion (based on comments) appears to be due to the difference in how `Tags` and `Title` behave in your code. The difference in behavior between `Tags` and `Title` when you do: ``` title = String.Empty; tags.Clear(); ``` Is due to the fact that, in the first case, you're assigning a completely new instance to title. When you call `tags.Clear()`, however, you're *mutating the existing instance*, which is "shared" with the `Tags` property within `book[0]` (since `List<string>` is a class and has reference type semantics).
261,049
I have created a new Drupal 8 site with docker. I created it with composer and installed the `drupal/deploy` and `relaxedws/replicator` modules. The `drupal/deploy` module and all of its dependencies seem to be installed correctly, they show up in the `Extend` area of Drupal, and they seem to work properly. The `relaxedws/replicator` does not show up as expected. I expect to see it in the Web Services section of the Extend page in Drupal. The `relaxedws/replicator` module shows up on the file system in the `vendor` folder in the Drupal root. It seems like I'm missing something. Dockerfile: ``` FROM drupal:latest RUN apt-get update && apt-get install -y \ curl \ git \ mysql-client \ vim \ wget RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" && \ php composer-setup.php && \ mv composer.phar /usr/local/bin/composer && \ php -r "unlink('composer-setup.php');" RUN wget -O drush.phar https://github.com/drush-ops/drush-launcher/releases/download/0.4.2/drush.phar && \ chmod +x drush.phar && \ mv drush.phar /usr/local/bin/drush RUN rm -rf /var/www/html/* COPY apache-drupal.conf /etc/apache2/sites-enabled/000-default.conf WORKDIR /app RUN composer create-project drupal-composer/drupal-project:8.x-dev /app --stability dev --no-interaction RUN mkdir -p /app/config/sync RUN chown -R www-data:www-data /app/web RUN composer require relaxedws/replicator:dev-master RUN composer require drupal/deploy ``` Resulting `composer.json` ``` { "name": "drupal-composer/drupal-project", "description": "Project template for Drupal 8 projects with composer", "type": "project", "license": "GPL-2.0-or-later", "authors": [ { "name": "", "role": "" } ], "repositories": [ { "type": "composer", "url": "https://packages.drupal.org/8" } ], "require": { "composer/installers": "^1.2", "cweagans/composer-patches": "^1.6", "drupal-composer/drupal-scaffold": "^2.2", "drupal/console": "^1.0.2", "drupal/core": "~8.5.3", "drupal/deploy": "^1.0@beta", "drush/drush": "^9.0.0", "relaxedws/replicator": "dev-master", "vlucas/phpdotenv": "^2.4", "webflo/drupal-finder": "^1.0.0", "webmozart/path-util": "^2.3" }, "require-dev": { "webflo/drupal-core-require-dev": "~8.5.3" }, "conflict": { "drupal/drupal": "*" }, "minimum-stability": "dev", "prefer-stable": true, "config": { "sort-packages": true }, "autoload": { "classmap": [ "scripts/composer/ScriptHandler.php" ], "files": ["load.environment.php"] }, "scripts": { "drupal-scaffold": "DrupalComposer\\DrupalScaffold\\Plugin::scaffold", "pre-install-cmd": [ "DrupalProject\\composer\\ScriptHandler::checkComposerVersion" ], "pre-update-cmd": [ "DrupalProject\\composer\\ScriptHandler::checkComposerVersion" ], "post-install-cmd": [ "DrupalProject\\composer\\ScriptHandler::createRequiredFiles" ], "post-update-cmd": [ "DrupalProject\\composer\\ScriptHandler::createRequiredFiles" ] }, "extra": { "installer-paths": { "web/core": ["type:drupal-core"], "web/libraries/{$name}": ["type:drupal-library"], "web/modules/contrib/{$name}": ["type:drupal-module"], "web/profiles/contrib/{$name}": ["type:drupal-profile"], "web/themes/contrib/{$name}": ["type:drupal-theme"], "drush/contrib/{$name}": ["type:drupal-drush"] } } } ``` \*\* EDIT 1 I attempted the fix mentioned by @sonfd (and say thanks for the answer). I changed my `extra.installer-paths` to the following but the path for the installed package didn't change. ``` "extra": { "installer-paths": { "web/core": ["type:drupal-core"], "web/libraries/{$name}": ["type:drupal-library"], "web/modules/contrib/{$name}": ["type:drupal-module"], "web/profiles/contrib/{$name}": ["type:drupal-profile"], "web/themes/contrib/{$name}": ["type:drupal-theme"], "drush/contrib/{$name}": ["type:drupal-drush"], "web/modules/{$name}": ["relaxedws/replicator"] } } ```
2018/05/03
[ "https://drupal.stackexchange.com/questions/261049", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/85247/" ]
Composer installs things based on the informations in `extras.installer-paths` in your composer.json, or to the vendor directory by default. You can place the package anywhere you want by following the steps at [How do I install a package to a custom path for my framework?](https://getcomposer.org/doc/faqs/how-do-i-install-a-package-to-a-custom-path-for-my-framework.md). Basically you need to update your `extra.installer-paths` area to look something like: ``` "extra": { "installer-paths": { "web/core": ["type:drupal-core"], "web/libraries/{$name}": ["type:drupal-library"], "web/modules/contrib/{$name}": ["type:drupal-module"], "web/profiles/contrib/{$name}": ["type:drupal-profile"], "web/themes/contrib/{$name}": ["type:drupal-theme"], "drush/contrib/{$name}": ["type:drupal-drush"], "path/to/desirable/package/location": ["relaxedws/replicator"] } } ``` Note the additional line for `relaxedws/replicator` at the bottom. **Note:** I would `composer remove relaxedws/replicator` before updating the installer paths and then reinstall with `composer require relaxedws/replicator`. I don't think composer will move the package to the new location otherwise, but maybe it would with some form of a `composer update` command.
I found the answer to my problem. It didn't have to do with package placement, but package selection. I was not adding the correct package. As I stumbled and grumbled, the packagist website did not show the package I was looking for. `https://packagist.org/packages/?q=drupal%2Frelax&p=0` What helped me find it was getting a few packages incorrect when adding them with `composer require <some_non_existent_package_name>`. When you do this composer will offer suggestions as to what you might be looking for. I then used this to search for packages. In the end, the package I was actually looking for was called `drupal/relaxed`. The package I mentioned above in the question `relaxedws/replicator` is a prerequisite and not the actual Drupal package. `composer require drupal/relaxed` Back story: This was all in an effort to get Drupal 8 Deploy working. The documentation never points to installing this package. Hopefully this helps. <https://www.drupal.org/docs/8/modules/deploy/drupal-to-drupal-deployment-between-two-or-more-sites>
16,204,529
I have a JSON array created using Javascript. I stringify it before putting it into an input field and submit it with a HTML form. This is my output after decoding: var\_dump(json\_decode($\_POST['json']),true); outputs: ``` [{"Mid": "1", "cat": "6", "room": "21", "rate": "EURP", "adchexb": "2,2,1"}, {"Mid": "2", "cat": "3", "room": "12", "rate": "EURP", "adchexb": "2,1,1"}] ``` Then every time I try to access any property I get an error. I tried: ``` $jsonObj->Mid //gives "Trying to get property of non-object in..." $jsonObj[0]->Mis //error again. ``` Basically I need to extract each object in a `for` loop. Please help me figure out how to access or get all the object properties in loops. Thanks
2013/04/25
[ "https://Stackoverflow.com/questions/16204529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2317749/" ]
I'm assuming that `btnClassification_Click` is a method on your `static` user control, that is located on an instance of your `formMain`. Your problem is that in your `btnClassification_Click` method, you create a new instance of the `formMain` class instead of accessing the instance that your `static` user control is on. It looks like you've already publicly exposed `mainPanel` in the `formMain` class, so you just need to find the right instance of the `formMain` class to add your user control to. To do that, put this method in your `static` user control: ``` private Form GetParentForm() { Control current = this.Parent; while (current != null) { Form form = current as Form; if (form != null) { return form; } current = current.Parent; } return null; } ``` Then call this method from your event handler: ``` private void btnClassification_Click(object sender, EventArgs e) { classification control = new classification(); formMain main = (formMain)this.GetParentForm(); main.panelMain.Controls.Clear(); main.panelMain.Controls.Add(control); } ```
[Mark Hall's](https://stackoverflow.com/a/16205612/80274) answer is the best, however I wanted to add that you should not raise the event directly but first check that there are subscribers then raise the event. This will stop a null reference exception if no one has subscribed to the event yet. ``` public partial class UserControl1 : UserControl { public event EventHandler ClassificationClicked; public UserControl1() { InitializeComponent(); } private void btnClassification_Click(object sender, EventArgs e) { RaiseClassifactionClicked(); } private RaiseClassifactionClicked() { var tmp = ClassificationClicked; //This is added for thread safty if(tmp != null) //check to see if there are subscribers, if there are tmp will not be null tmp(this, EventArgs.Empty); //You don't need to pass along the sender and e, make your own here. } } ``` For more on the thread safty trick read [this post](http://blogs.msdn.com/b/ericlippert/archive/2009/04/29/events-and-races.aspx)
16,204,529
I have a JSON array created using Javascript. I stringify it before putting it into an input field and submit it with a HTML form. This is my output after decoding: var\_dump(json\_decode($\_POST['json']),true); outputs: ``` [{"Mid": "1", "cat": "6", "room": "21", "rate": "EURP", "adchexb": "2,2,1"}, {"Mid": "2", "cat": "3", "room": "12", "rate": "EURP", "adchexb": "2,1,1"}] ``` Then every time I try to access any property I get an error. I tried: ``` $jsonObj->Mid //gives "Trying to get property of non-object in..." $jsonObj[0]->Mis //error again. ``` Basically I need to extract each object in a `for` loop. Please help me figure out how to access or get all the object properties in loops. Thanks
2013/04/25
[ "https://Stackoverflow.com/questions/16204529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2317749/" ]
Personally I would create an Event on your UserControl and subscribe to it in your MainForm. In my opinion it is not proper for the UserControl to have knowledge of the Parent Form. Something like this: **Add event to your UserControl:** ``` public partial class UserControl1 : UserControl { public event EventHandler ClassificationClicked; public UserControl1() { InitializeComponent(); } private void btnClassification_Click(object sender, EventArgs e) { ClassificationClicked(sender, e); } } ``` **Subscribe to it in your MainForm** ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); userControl11.ClassificationClicked += new EventHandler(userControl11_ClassificationClicked); } void userControl11_ClassificationClicked(object sender, EventArgs e) { classification control = new classification(); panelMain.Controls.Clear(); panelMain.Controls.Add(control); } } ``` --- Edit based on Comment Stream. I would also make sure that your Usercontrols have unique names not just control, that way you can differentiate between them. ``` public partial class formMain : Form { Static staticControl; Classification classificationControl; public formMain() { InitializeComponent(); staticControl= new Static(); panelSide.Controls.Clear(); panelSide.Controls.Add(staticControl); staticControl.ClassificationClicked += new EventHandler(Static_ClassificationClicked); } void Static_ClassificationClicked(object sender, EventArgs e) { classificationControl = new classification(); panelMain.Controls.Clear(); panelMain.Controls.Add(classificationControl); } } ```
[Mark Hall's](https://stackoverflow.com/a/16205612/80274) answer is the best, however I wanted to add that you should not raise the event directly but first check that there are subscribers then raise the event. This will stop a null reference exception if no one has subscribed to the event yet. ``` public partial class UserControl1 : UserControl { public event EventHandler ClassificationClicked; public UserControl1() { InitializeComponent(); } private void btnClassification_Click(object sender, EventArgs e) { RaiseClassifactionClicked(); } private RaiseClassifactionClicked() { var tmp = ClassificationClicked; //This is added for thread safty if(tmp != null) //check to see if there are subscribers, if there are tmp will not be null tmp(this, EventArgs.Empty); //You don't need to pass along the sender and e, make your own here. } } ``` For more on the thread safty trick read [this post](http://blogs.msdn.com/b/ericlippert/archive/2009/04/29/events-and-races.aspx)
36,219,651
I had a piece of code commissioned earlier this week (cheaper to have an expert write it than for me to spend a week trying to!). However, when putting it use I've hit a bit of a snag. The macro looks at a name on one excel worksheet, matches it to a list of names and associated ID numbers on a different worksheet, then inserts the ID on the first worksheet. This was all fine until I started using it on real data. Here's some sample data (all of this information is in one cell...): WARHOL\*, Andy PETO, John F D3 GRECO, Emilio -20th C HASELTINE, William Stanley D3 DALI, Salvador D3 SOSNO, Sacha WEGMAN\*\*, WILLIAM One asterisk means it's a print, two a photograph, D3 a sculpture, and nothing a painting. When I run the code with this data, it sees \* as a wildcard, and so will always insert the ID of the first variation of the artist in the sheet. What I need is a way for the macro to not read it as a wildcard. I did some research, and found that inserting ~ before \* negates the wildcard properties. How would I make my code do this? I've discovered the main issue of having code written by someone else... You might not understand it! Here is the code: ``` Public Sub match_data() 'ctrl+r On Error GoTo errh Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim r1, r2, i, exc As Long Dim fp As Range Sheets("Data").Activate r1 = Cells(Rows.Count, "B").End(xlUp).Row r2 = Sheets("List").Cells(Sheets("List").Rows.Count, "B").End(xlUp).Row 'MsgBox r1 & r2 exc = 0 For i = 2 To r1 If Range("B" & i).Value <> "" Then With Sheets("List").Range("B2:B" & r2) Set fp = .Find(Range("B" & i).Value, LookIn:=xlValues, lookat:=xlWhole) If Not fp Is Nothing Then Range("B" & i).Interior.Color = xlNone Range("A" & i).Value = Sheets("List").Range("A" & fp.Row).Value Else Range("B" & i).Interior.Color = xlNone Range("B" & i).Interior.Color = vbYellow exc = exc + 1 End If End With End If Next i MsgBox "There are " & exc & " exceptions." errh: If Err.Number > 0 Then MsgBox Err.Description End If Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub ``` Oh also, I would need to do this for the list of names and ID's wouldn't I? If so, that only needs doing once, so if you could give me a hint about that too, I'd be so grateful! Thanks! PS I know the system we are using at the moment absolutely sucks (definitely not 3rd form normalised!), but we are fast running out of time and money, and need to get our product up and running ASAP! EDIT: To clarify, here is a pic of the spreadsheets I'm working with... Obviously in cells A14 and A15 I wanted the ID numbers 11 & 12 respectively [![Clarification](https://i.stack.imgur.com/LbDXE.png)](https://i.stack.imgur.com/LbDXE.png)
2016/03/25
[ "https://Stackoverflow.com/questions/36219651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6019131/" ]
Roundup: * Declaration of local variable `i` is missing ``` var i; ``` * Declaration of other used variables are over the function distributed. A better way is to declare the variables at top of the function. * [`Array#reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) needs for this task an `initialValue` as the second parameter. > > The first time the callback is called, `previousValue` and `currentValue` can be one of two values. If `initialValue` is provided in the call to reduce, then `previousValue` will be equal to `initialValue` and `currentValue` will be equal to the first value in the array. If no `initialValue` was provided, then `previousValue` will be equal to the first value in the array and `currentValue` will be equal to the second. > > > ```js function factorial(num) { var i, arrOfNum = [], result; for (i = 1; i <= num; i++) { // push all numbers to array arrOfNum.push(i); } // multiply each element of array result = arrOfNum.reduce(function (a, b) { return a * b; }, 1); document.write(num+'! = '+result + '<br>'); } factorial(0); factorial(1); factorial(2); factorial(5); factorial(8); ```
``` function factorial(n) { return Array.apply(0, Array(n)).reduce(function(x, y, z) { return x + x * z; //1+(1*0), 1+(1*1),2+(2*2), 6+(6*3), 24+(24*4), ... }, 1); } ``` [**DEMO**](https://jsfiddle.net/dipali_vasani/q4030u8v/)
36,219,651
I had a piece of code commissioned earlier this week (cheaper to have an expert write it than for me to spend a week trying to!). However, when putting it use I've hit a bit of a snag. The macro looks at a name on one excel worksheet, matches it to a list of names and associated ID numbers on a different worksheet, then inserts the ID on the first worksheet. This was all fine until I started using it on real data. Here's some sample data (all of this information is in one cell...): WARHOL\*, Andy PETO, John F D3 GRECO, Emilio -20th C HASELTINE, William Stanley D3 DALI, Salvador D3 SOSNO, Sacha WEGMAN\*\*, WILLIAM One asterisk means it's a print, two a photograph, D3 a sculpture, and nothing a painting. When I run the code with this data, it sees \* as a wildcard, and so will always insert the ID of the first variation of the artist in the sheet. What I need is a way for the macro to not read it as a wildcard. I did some research, and found that inserting ~ before \* negates the wildcard properties. How would I make my code do this? I've discovered the main issue of having code written by someone else... You might not understand it! Here is the code: ``` Public Sub match_data() 'ctrl+r On Error GoTo errh Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim r1, r2, i, exc As Long Dim fp As Range Sheets("Data").Activate r1 = Cells(Rows.Count, "B").End(xlUp).Row r2 = Sheets("List").Cells(Sheets("List").Rows.Count, "B").End(xlUp).Row 'MsgBox r1 & r2 exc = 0 For i = 2 To r1 If Range("B" & i).Value <> "" Then With Sheets("List").Range("B2:B" & r2) Set fp = .Find(Range("B" & i).Value, LookIn:=xlValues, lookat:=xlWhole) If Not fp Is Nothing Then Range("B" & i).Interior.Color = xlNone Range("A" & i).Value = Sheets("List").Range("A" & fp.Row).Value Else Range("B" & i).Interior.Color = xlNone Range("B" & i).Interior.Color = vbYellow exc = exc + 1 End If End With End If Next i MsgBox "There are " & exc & " exceptions." errh: If Err.Number > 0 Then MsgBox Err.Description End If Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub ``` Oh also, I would need to do this for the list of names and ID's wouldn't I? If so, that only needs doing once, so if you could give me a hint about that too, I'd be so grateful! Thanks! PS I know the system we are using at the moment absolutely sucks (definitely not 3rd form normalised!), but we are fast running out of time and money, and need to get our product up and running ASAP! EDIT: To clarify, here is a pic of the spreadsheets I'm working with... Obviously in cells A14 and A15 I wanted the ID numbers 11 & 12 respectively [![Clarification](https://i.stack.imgur.com/LbDXE.png)](https://i.stack.imgur.com/LbDXE.png)
2016/03/25
[ "https://Stackoverflow.com/questions/36219651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6019131/" ]
Roundup: * Declaration of local variable `i` is missing ``` var i; ``` * Declaration of other used variables are over the function distributed. A better way is to declare the variables at top of the function. * [`Array#reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) needs for this task an `initialValue` as the second parameter. > > The first time the callback is called, `previousValue` and `currentValue` can be one of two values. If `initialValue` is provided in the call to reduce, then `previousValue` will be equal to `initialValue` and `currentValue` will be equal to the first value in the array. If no `initialValue` was provided, then `previousValue` will be equal to the first value in the array and `currentValue` will be equal to the second. > > > ```js function factorial(num) { var i, arrOfNum = [], result; for (i = 1; i <= num; i++) { // push all numbers to array arrOfNum.push(i); } // multiply each element of array result = arrOfNum.reduce(function (a, b) { return a * b; }, 1); document.write(num+'! = '+result + '<br>'); } factorial(0); factorial(1); factorial(2); factorial(5); factorial(8); ```
Here's a fairly streamlined function that returns an array of all factors of 'n' You only need to look at candidates < sqrt(n) For those of you who don't know the | 0; bit when getting sqrt(n) is a faster equivalent of Math.floor() As factn is defined after some sanity checking the function will either return undefined or an array which is easy to check with something like if(factors = factorize(n) { success code } sorta structure There are improvements that can be made to this but they're complex and were beyond the requirements when I wrote it - specifically I used this to calculate CSS sprite sizes from a large image by using factorize on the x + y dimensions of an image then creating a third array of shared factors (which gives you a list of all the possible square sprite sizes). ``` function factorize(n) { n = Number(n); if(n) { if(n > 1) { var sqrtn = Math.sqrt(n) | 0; var factn = [1, n]; var ipos = 0; for(i = 2; i <= sqrtn; i++) { if((n % i) == 0) { ipos++; if((n / i) !== i) { factn.splice(ipos, 0, i, n / i); } else { factn.splice(ipos, 0, i); } } } } } return factn; } ```
36,219,651
I had a piece of code commissioned earlier this week (cheaper to have an expert write it than for me to spend a week trying to!). However, when putting it use I've hit a bit of a snag. The macro looks at a name on one excel worksheet, matches it to a list of names and associated ID numbers on a different worksheet, then inserts the ID on the first worksheet. This was all fine until I started using it on real data. Here's some sample data (all of this information is in one cell...): WARHOL\*, Andy PETO, John F D3 GRECO, Emilio -20th C HASELTINE, William Stanley D3 DALI, Salvador D3 SOSNO, Sacha WEGMAN\*\*, WILLIAM One asterisk means it's a print, two a photograph, D3 a sculpture, and nothing a painting. When I run the code with this data, it sees \* as a wildcard, and so will always insert the ID of the first variation of the artist in the sheet. What I need is a way for the macro to not read it as a wildcard. I did some research, and found that inserting ~ before \* negates the wildcard properties. How would I make my code do this? I've discovered the main issue of having code written by someone else... You might not understand it! Here is the code: ``` Public Sub match_data() 'ctrl+r On Error GoTo errh Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim r1, r2, i, exc As Long Dim fp As Range Sheets("Data").Activate r1 = Cells(Rows.Count, "B").End(xlUp).Row r2 = Sheets("List").Cells(Sheets("List").Rows.Count, "B").End(xlUp).Row 'MsgBox r1 & r2 exc = 0 For i = 2 To r1 If Range("B" & i).Value <> "" Then With Sheets("List").Range("B2:B" & r2) Set fp = .Find(Range("B" & i).Value, LookIn:=xlValues, lookat:=xlWhole) If Not fp Is Nothing Then Range("B" & i).Interior.Color = xlNone Range("A" & i).Value = Sheets("List").Range("A" & fp.Row).Value Else Range("B" & i).Interior.Color = xlNone Range("B" & i).Interior.Color = vbYellow exc = exc + 1 End If End With End If Next i MsgBox "There are " & exc & " exceptions." errh: If Err.Number > 0 Then MsgBox Err.Description End If Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub ``` Oh also, I would need to do this for the list of names and ID's wouldn't I? If so, that only needs doing once, so if you could give me a hint about that too, I'd be so grateful! Thanks! PS I know the system we are using at the moment absolutely sucks (definitely not 3rd form normalised!), but we are fast running out of time and money, and need to get our product up and running ASAP! EDIT: To clarify, here is a pic of the spreadsheets I'm working with... Obviously in cells A14 and A15 I wanted the ID numbers 11 & 12 respectively [![Clarification](https://i.stack.imgur.com/LbDXE.png)](https://i.stack.imgur.com/LbDXE.png)
2016/03/25
[ "https://Stackoverflow.com/questions/36219651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6019131/" ]
You already have a `for` loop, in which you can calculate the factorial at once, without array and reduce. ``` function factorial(num) { var result = 1; for(i = 2; i <= num; i++) { result *= i; } return result; } ```
You can use the following method that uses the recursion: ``` function factorize(num){ if(num === 0){ return 1 ; } else { return num = num * factorize(num-1); } } ```
36,219,651
I had a piece of code commissioned earlier this week (cheaper to have an expert write it than for me to spend a week trying to!). However, when putting it use I've hit a bit of a snag. The macro looks at a name on one excel worksheet, matches it to a list of names and associated ID numbers on a different worksheet, then inserts the ID on the first worksheet. This was all fine until I started using it on real data. Here's some sample data (all of this information is in one cell...): WARHOL\*, Andy PETO, John F D3 GRECO, Emilio -20th C HASELTINE, William Stanley D3 DALI, Salvador D3 SOSNO, Sacha WEGMAN\*\*, WILLIAM One asterisk means it's a print, two a photograph, D3 a sculpture, and nothing a painting. When I run the code with this data, it sees \* as a wildcard, and so will always insert the ID of the first variation of the artist in the sheet. What I need is a way for the macro to not read it as a wildcard. I did some research, and found that inserting ~ before \* negates the wildcard properties. How would I make my code do this? I've discovered the main issue of having code written by someone else... You might not understand it! Here is the code: ``` Public Sub match_data() 'ctrl+r On Error GoTo errh Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim r1, r2, i, exc As Long Dim fp As Range Sheets("Data").Activate r1 = Cells(Rows.Count, "B").End(xlUp).Row r2 = Sheets("List").Cells(Sheets("List").Rows.Count, "B").End(xlUp).Row 'MsgBox r1 & r2 exc = 0 For i = 2 To r1 If Range("B" & i).Value <> "" Then With Sheets("List").Range("B2:B" & r2) Set fp = .Find(Range("B" & i).Value, LookIn:=xlValues, lookat:=xlWhole) If Not fp Is Nothing Then Range("B" & i).Interior.Color = xlNone Range("A" & i).Value = Sheets("List").Range("A" & fp.Row).Value Else Range("B" & i).Interior.Color = xlNone Range("B" & i).Interior.Color = vbYellow exc = exc + 1 End If End With End If Next i MsgBox "There are " & exc & " exceptions." errh: If Err.Number > 0 Then MsgBox Err.Description End If Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub ``` Oh also, I would need to do this for the list of names and ID's wouldn't I? If so, that only needs doing once, so if you could give me a hint about that too, I'd be so grateful! Thanks! PS I know the system we are using at the moment absolutely sucks (definitely not 3rd form normalised!), but we are fast running out of time and money, and need to get our product up and running ASAP! EDIT: To clarify, here is a pic of the spreadsheets I'm working with... Obviously in cells A14 and A15 I wanted the ID numbers 11 & 12 respectively [![Clarification](https://i.stack.imgur.com/LbDXE.png)](https://i.stack.imgur.com/LbDXE.png)
2016/03/25
[ "https://Stackoverflow.com/questions/36219651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6019131/" ]
You can use the following method that uses the recursion: ``` function factorize(num){ if(num === 0){ return 1 ; } else { return num = num * factorize(num-1); } } ```
If you give `reduce` an initial value of `1`, everything will work fine even without an explicit check: ``` var result = arrOfNum.reduce(function(a,b){ return a * b; }, 1); ^^^ // PROVIDE EXPLICIT INITIAL VALUE TO REDUCE ```
36,219,651
I had a piece of code commissioned earlier this week (cheaper to have an expert write it than for me to spend a week trying to!). However, when putting it use I've hit a bit of a snag. The macro looks at a name on one excel worksheet, matches it to a list of names and associated ID numbers on a different worksheet, then inserts the ID on the first worksheet. This was all fine until I started using it on real data. Here's some sample data (all of this information is in one cell...): WARHOL\*, Andy PETO, John F D3 GRECO, Emilio -20th C HASELTINE, William Stanley D3 DALI, Salvador D3 SOSNO, Sacha WEGMAN\*\*, WILLIAM One asterisk means it's a print, two a photograph, D3 a sculpture, and nothing a painting. When I run the code with this data, it sees \* as a wildcard, and so will always insert the ID of the first variation of the artist in the sheet. What I need is a way for the macro to not read it as a wildcard. I did some research, and found that inserting ~ before \* negates the wildcard properties. How would I make my code do this? I've discovered the main issue of having code written by someone else... You might not understand it! Here is the code: ``` Public Sub match_data() 'ctrl+r On Error GoTo errh Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim r1, r2, i, exc As Long Dim fp As Range Sheets("Data").Activate r1 = Cells(Rows.Count, "B").End(xlUp).Row r2 = Sheets("List").Cells(Sheets("List").Rows.Count, "B").End(xlUp).Row 'MsgBox r1 & r2 exc = 0 For i = 2 To r1 If Range("B" & i).Value <> "" Then With Sheets("List").Range("B2:B" & r2) Set fp = .Find(Range("B" & i).Value, LookIn:=xlValues, lookat:=xlWhole) If Not fp Is Nothing Then Range("B" & i).Interior.Color = xlNone Range("A" & i).Value = Sheets("List").Range("A" & fp.Row).Value Else Range("B" & i).Interior.Color = xlNone Range("B" & i).Interior.Color = vbYellow exc = exc + 1 End If End With End If Next i MsgBox "There are " & exc & " exceptions." errh: If Err.Number > 0 Then MsgBox Err.Description End If Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub ``` Oh also, I would need to do this for the list of names and ID's wouldn't I? If so, that only needs doing once, so if you could give me a hint about that too, I'd be so grateful! Thanks! PS I know the system we are using at the moment absolutely sucks (definitely not 3rd form normalised!), but we are fast running out of time and money, and need to get our product up and running ASAP! EDIT: To clarify, here is a pic of the spreadsheets I'm working with... Obviously in cells A14 and A15 I wanted the ID numbers 11 & 12 respectively [![Clarification](https://i.stack.imgur.com/LbDXE.png)](https://i.stack.imgur.com/LbDXE.png)
2016/03/25
[ "https://Stackoverflow.com/questions/36219651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6019131/" ]
Roundup: * Declaration of local variable `i` is missing ``` var i; ``` * Declaration of other used variables are over the function distributed. A better way is to declare the variables at top of the function. * [`Array#reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) needs for this task an `initialValue` as the second parameter. > > The first time the callback is called, `previousValue` and `currentValue` can be one of two values. If `initialValue` is provided in the call to reduce, then `previousValue` will be equal to `initialValue` and `currentValue` will be equal to the first value in the array. If no `initialValue` was provided, then `previousValue` will be equal to the first value in the array and `currentValue` will be equal to the second. > > > ```js function factorial(num) { var i, arrOfNum = [], result; for (i = 1; i <= num; i++) { // push all numbers to array arrOfNum.push(i); } // multiply each element of array result = arrOfNum.reduce(function (a, b) { return a * b; }, 1); document.write(num+'! = '+result + '<br>'); } factorial(0); factorial(1); factorial(2); factorial(5); factorial(8); ```
Simply return the value 1 ``` function factorialize(num) { if (num < 1) return 1; //this line is added for(i = 1; i <= num; i++){ arrOfNum.push(i); } var result = arrOfNum.reduce(function(a,b){ return a * b; }); console.log(result); } ```
36,219,651
I had a piece of code commissioned earlier this week (cheaper to have an expert write it than for me to spend a week trying to!). However, when putting it use I've hit a bit of a snag. The macro looks at a name on one excel worksheet, matches it to a list of names and associated ID numbers on a different worksheet, then inserts the ID on the first worksheet. This was all fine until I started using it on real data. Here's some sample data (all of this information is in one cell...): WARHOL\*, Andy PETO, John F D3 GRECO, Emilio -20th C HASELTINE, William Stanley D3 DALI, Salvador D3 SOSNO, Sacha WEGMAN\*\*, WILLIAM One asterisk means it's a print, two a photograph, D3 a sculpture, and nothing a painting. When I run the code with this data, it sees \* as a wildcard, and so will always insert the ID of the first variation of the artist in the sheet. What I need is a way for the macro to not read it as a wildcard. I did some research, and found that inserting ~ before \* negates the wildcard properties. How would I make my code do this? I've discovered the main issue of having code written by someone else... You might not understand it! Here is the code: ``` Public Sub match_data() 'ctrl+r On Error GoTo errh Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim r1, r2, i, exc As Long Dim fp As Range Sheets("Data").Activate r1 = Cells(Rows.Count, "B").End(xlUp).Row r2 = Sheets("List").Cells(Sheets("List").Rows.Count, "B").End(xlUp).Row 'MsgBox r1 & r2 exc = 0 For i = 2 To r1 If Range("B" & i).Value <> "" Then With Sheets("List").Range("B2:B" & r2) Set fp = .Find(Range("B" & i).Value, LookIn:=xlValues, lookat:=xlWhole) If Not fp Is Nothing Then Range("B" & i).Interior.Color = xlNone Range("A" & i).Value = Sheets("List").Range("A" & fp.Row).Value Else Range("B" & i).Interior.Color = xlNone Range("B" & i).Interior.Color = vbYellow exc = exc + 1 End If End With End If Next i MsgBox "There are " & exc & " exceptions." errh: If Err.Number > 0 Then MsgBox Err.Description End If Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub ``` Oh also, I would need to do this for the list of names and ID's wouldn't I? If so, that only needs doing once, so if you could give me a hint about that too, I'd be so grateful! Thanks! PS I know the system we are using at the moment absolutely sucks (definitely not 3rd form normalised!), but we are fast running out of time and money, and need to get our product up and running ASAP! EDIT: To clarify, here is a pic of the spreadsheets I'm working with... Obviously in cells A14 and A15 I wanted the ID numbers 11 & 12 respectively [![Clarification](https://i.stack.imgur.com/LbDXE.png)](https://i.stack.imgur.com/LbDXE.png)
2016/03/25
[ "https://Stackoverflow.com/questions/36219651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6019131/" ]
You can use the following method that uses the recursion: ``` function factorize(num){ if(num === 0){ return 1 ; } else { return num = num * factorize(num-1); } } ```
``` function factorial(n) { return Array.apply(0, Array(n)).reduce(function(x, y, z) { return x + x * z; //1+(1*0), 1+(1*1),2+(2*2), 6+(6*3), 24+(24*4), ... }, 1); } ``` [**DEMO**](https://jsfiddle.net/dipali_vasani/q4030u8v/)
36,219,651
I had a piece of code commissioned earlier this week (cheaper to have an expert write it than for me to spend a week trying to!). However, when putting it use I've hit a bit of a snag. The macro looks at a name on one excel worksheet, matches it to a list of names and associated ID numbers on a different worksheet, then inserts the ID on the first worksheet. This was all fine until I started using it on real data. Here's some sample data (all of this information is in one cell...): WARHOL\*, Andy PETO, John F D3 GRECO, Emilio -20th C HASELTINE, William Stanley D3 DALI, Salvador D3 SOSNO, Sacha WEGMAN\*\*, WILLIAM One asterisk means it's a print, two a photograph, D3 a sculpture, and nothing a painting. When I run the code with this data, it sees \* as a wildcard, and so will always insert the ID of the first variation of the artist in the sheet. What I need is a way for the macro to not read it as a wildcard. I did some research, and found that inserting ~ before \* negates the wildcard properties. How would I make my code do this? I've discovered the main issue of having code written by someone else... You might not understand it! Here is the code: ``` Public Sub match_data() 'ctrl+r On Error GoTo errh Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim r1, r2, i, exc As Long Dim fp As Range Sheets("Data").Activate r1 = Cells(Rows.Count, "B").End(xlUp).Row r2 = Sheets("List").Cells(Sheets("List").Rows.Count, "B").End(xlUp).Row 'MsgBox r1 & r2 exc = 0 For i = 2 To r1 If Range("B" & i).Value <> "" Then With Sheets("List").Range("B2:B" & r2) Set fp = .Find(Range("B" & i).Value, LookIn:=xlValues, lookat:=xlWhole) If Not fp Is Nothing Then Range("B" & i).Interior.Color = xlNone Range("A" & i).Value = Sheets("List").Range("A" & fp.Row).Value Else Range("B" & i).Interior.Color = xlNone Range("B" & i).Interior.Color = vbYellow exc = exc + 1 End If End With End If Next i MsgBox "There are " & exc & " exceptions." errh: If Err.Number > 0 Then MsgBox Err.Description End If Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub ``` Oh also, I would need to do this for the list of names and ID's wouldn't I? If so, that only needs doing once, so if you could give me a hint about that too, I'd be so grateful! Thanks! PS I know the system we are using at the moment absolutely sucks (definitely not 3rd form normalised!), but we are fast running out of time and money, and need to get our product up and running ASAP! EDIT: To clarify, here is a pic of the spreadsheets I'm working with... Obviously in cells A14 and A15 I wanted the ID numbers 11 & 12 respectively [![Clarification](https://i.stack.imgur.com/LbDXE.png)](https://i.stack.imgur.com/LbDXE.png)
2016/03/25
[ "https://Stackoverflow.com/questions/36219651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6019131/" ]
You already have a `for` loop, in which you can calculate the factorial at once, without array and reduce. ``` function factorial(num) { var result = 1; for(i = 2; i <= num; i++) { result *= i; } return result; } ```
If you give `reduce` an initial value of `1`, everything will work fine even without an explicit check: ``` var result = arrOfNum.reduce(function(a,b){ return a * b; }, 1); ^^^ // PROVIDE EXPLICIT INITIAL VALUE TO REDUCE ```
36,219,651
I had a piece of code commissioned earlier this week (cheaper to have an expert write it than for me to spend a week trying to!). However, when putting it use I've hit a bit of a snag. The macro looks at a name on one excel worksheet, matches it to a list of names and associated ID numbers on a different worksheet, then inserts the ID on the first worksheet. This was all fine until I started using it on real data. Here's some sample data (all of this information is in one cell...): WARHOL\*, Andy PETO, John F D3 GRECO, Emilio -20th C HASELTINE, William Stanley D3 DALI, Salvador D3 SOSNO, Sacha WEGMAN\*\*, WILLIAM One asterisk means it's a print, two a photograph, D3 a sculpture, and nothing a painting. When I run the code with this data, it sees \* as a wildcard, and so will always insert the ID of the first variation of the artist in the sheet. What I need is a way for the macro to not read it as a wildcard. I did some research, and found that inserting ~ before \* negates the wildcard properties. How would I make my code do this? I've discovered the main issue of having code written by someone else... You might not understand it! Here is the code: ``` Public Sub match_data() 'ctrl+r On Error GoTo errh Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim r1, r2, i, exc As Long Dim fp As Range Sheets("Data").Activate r1 = Cells(Rows.Count, "B").End(xlUp).Row r2 = Sheets("List").Cells(Sheets("List").Rows.Count, "B").End(xlUp).Row 'MsgBox r1 & r2 exc = 0 For i = 2 To r1 If Range("B" & i).Value <> "" Then With Sheets("List").Range("B2:B" & r2) Set fp = .Find(Range("B" & i).Value, LookIn:=xlValues, lookat:=xlWhole) If Not fp Is Nothing Then Range("B" & i).Interior.Color = xlNone Range("A" & i).Value = Sheets("List").Range("A" & fp.Row).Value Else Range("B" & i).Interior.Color = xlNone Range("B" & i).Interior.Color = vbYellow exc = exc + 1 End If End With End If Next i MsgBox "There are " & exc & " exceptions." errh: If Err.Number > 0 Then MsgBox Err.Description End If Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub ``` Oh also, I would need to do this for the list of names and ID's wouldn't I? If so, that only needs doing once, so if you could give me a hint about that too, I'd be so grateful! Thanks! PS I know the system we are using at the moment absolutely sucks (definitely not 3rd form normalised!), but we are fast running out of time and money, and need to get our product up and running ASAP! EDIT: To clarify, here is a pic of the spreadsheets I'm working with... Obviously in cells A14 and A15 I wanted the ID numbers 11 & 12 respectively [![Clarification](https://i.stack.imgur.com/LbDXE.png)](https://i.stack.imgur.com/LbDXE.png)
2016/03/25
[ "https://Stackoverflow.com/questions/36219651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6019131/" ]
You already have a `for` loop, in which you can calculate the factorial at once, without array and reduce. ``` function factorial(num) { var result = 1; for(i = 2; i <= num; i++) { result *= i; } return result; } ```
Here's a fairly streamlined function that returns an array of all factors of 'n' You only need to look at candidates < sqrt(n) For those of you who don't know the | 0; bit when getting sqrt(n) is a faster equivalent of Math.floor() As factn is defined after some sanity checking the function will either return undefined or an array which is easy to check with something like if(factors = factorize(n) { success code } sorta structure There are improvements that can be made to this but they're complex and were beyond the requirements when I wrote it - specifically I used this to calculate CSS sprite sizes from a large image by using factorize on the x + y dimensions of an image then creating a third array of shared factors (which gives you a list of all the possible square sprite sizes). ``` function factorize(n) { n = Number(n); if(n) { if(n > 1) { var sqrtn = Math.sqrt(n) | 0; var factn = [1, n]; var ipos = 0; for(i = 2; i <= sqrtn; i++) { if((n % i) == 0) { ipos++; if((n / i) !== i) { factn.splice(ipos, 0, i, n / i); } else { factn.splice(ipos, 0, i); } } } } } return factn; } ```
36,219,651
I had a piece of code commissioned earlier this week (cheaper to have an expert write it than for me to spend a week trying to!). However, when putting it use I've hit a bit of a snag. The macro looks at a name on one excel worksheet, matches it to a list of names and associated ID numbers on a different worksheet, then inserts the ID on the first worksheet. This was all fine until I started using it on real data. Here's some sample data (all of this information is in one cell...): WARHOL\*, Andy PETO, John F D3 GRECO, Emilio -20th C HASELTINE, William Stanley D3 DALI, Salvador D3 SOSNO, Sacha WEGMAN\*\*, WILLIAM One asterisk means it's a print, two a photograph, D3 a sculpture, and nothing a painting. When I run the code with this data, it sees \* as a wildcard, and so will always insert the ID of the first variation of the artist in the sheet. What I need is a way for the macro to not read it as a wildcard. I did some research, and found that inserting ~ before \* negates the wildcard properties. How would I make my code do this? I've discovered the main issue of having code written by someone else... You might not understand it! Here is the code: ``` Public Sub match_data() 'ctrl+r On Error GoTo errh Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim r1, r2, i, exc As Long Dim fp As Range Sheets("Data").Activate r1 = Cells(Rows.Count, "B").End(xlUp).Row r2 = Sheets("List").Cells(Sheets("List").Rows.Count, "B").End(xlUp).Row 'MsgBox r1 & r2 exc = 0 For i = 2 To r1 If Range("B" & i).Value <> "" Then With Sheets("List").Range("B2:B" & r2) Set fp = .Find(Range("B" & i).Value, LookIn:=xlValues, lookat:=xlWhole) If Not fp Is Nothing Then Range("B" & i).Interior.Color = xlNone Range("A" & i).Value = Sheets("List").Range("A" & fp.Row).Value Else Range("B" & i).Interior.Color = xlNone Range("B" & i).Interior.Color = vbYellow exc = exc + 1 End If End With End If Next i MsgBox "There are " & exc & " exceptions." errh: If Err.Number > 0 Then MsgBox Err.Description End If Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub ``` Oh also, I would need to do this for the list of names and ID's wouldn't I? If so, that only needs doing once, so if you could give me a hint about that too, I'd be so grateful! Thanks! PS I know the system we are using at the moment absolutely sucks (definitely not 3rd form normalised!), but we are fast running out of time and money, and need to get our product up and running ASAP! EDIT: To clarify, here is a pic of the spreadsheets I'm working with... Obviously in cells A14 and A15 I wanted the ID numbers 11 & 12 respectively [![Clarification](https://i.stack.imgur.com/LbDXE.png)](https://i.stack.imgur.com/LbDXE.png)
2016/03/25
[ "https://Stackoverflow.com/questions/36219651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6019131/" ]
Roundup: * Declaration of local variable `i` is missing ``` var i; ``` * Declaration of other used variables are over the function distributed. A better way is to declare the variables at top of the function. * [`Array#reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) needs for this task an `initialValue` as the second parameter. > > The first time the callback is called, `previousValue` and `currentValue` can be one of two values. If `initialValue` is provided in the call to reduce, then `previousValue` will be equal to `initialValue` and `currentValue` will be equal to the first value in the array. If no `initialValue` was provided, then `previousValue` will be equal to the first value in the array and `currentValue` will be equal to the second. > > > ```js function factorial(num) { var i, arrOfNum = [], result; for (i = 1; i <= num; i++) { // push all numbers to array arrOfNum.push(i); } // multiply each element of array result = arrOfNum.reduce(function (a, b) { return a * b; }, 1); document.write(num+'! = '+result + '<br>'); } factorial(0); factorial(1); factorial(2); factorial(5); factorial(8); ```
If you give `reduce` an initial value of `1`, everything will work fine even without an explicit check: ``` var result = arrOfNum.reduce(function(a,b){ return a * b; }, 1); ^^^ // PROVIDE EXPLICIT INITIAL VALUE TO REDUCE ```
36,219,651
I had a piece of code commissioned earlier this week (cheaper to have an expert write it than for me to spend a week trying to!). However, when putting it use I've hit a bit of a snag. The macro looks at a name on one excel worksheet, matches it to a list of names and associated ID numbers on a different worksheet, then inserts the ID on the first worksheet. This was all fine until I started using it on real data. Here's some sample data (all of this information is in one cell...): WARHOL\*, Andy PETO, John F D3 GRECO, Emilio -20th C HASELTINE, William Stanley D3 DALI, Salvador D3 SOSNO, Sacha WEGMAN\*\*, WILLIAM One asterisk means it's a print, two a photograph, D3 a sculpture, and nothing a painting. When I run the code with this data, it sees \* as a wildcard, and so will always insert the ID of the first variation of the artist in the sheet. What I need is a way for the macro to not read it as a wildcard. I did some research, and found that inserting ~ before \* negates the wildcard properties. How would I make my code do this? I've discovered the main issue of having code written by someone else... You might not understand it! Here is the code: ``` Public Sub match_data() 'ctrl+r On Error GoTo errh Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim r1, r2, i, exc As Long Dim fp As Range Sheets("Data").Activate r1 = Cells(Rows.Count, "B").End(xlUp).Row r2 = Sheets("List").Cells(Sheets("List").Rows.Count, "B").End(xlUp).Row 'MsgBox r1 & r2 exc = 0 For i = 2 To r1 If Range("B" & i).Value <> "" Then With Sheets("List").Range("B2:B" & r2) Set fp = .Find(Range("B" & i).Value, LookIn:=xlValues, lookat:=xlWhole) If Not fp Is Nothing Then Range("B" & i).Interior.Color = xlNone Range("A" & i).Value = Sheets("List").Range("A" & fp.Row).Value Else Range("B" & i).Interior.Color = xlNone Range("B" & i).Interior.Color = vbYellow exc = exc + 1 End If End With End If Next i MsgBox "There are " & exc & " exceptions." errh: If Err.Number > 0 Then MsgBox Err.Description End If Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub ``` Oh also, I would need to do this for the list of names and ID's wouldn't I? If so, that only needs doing once, so if you could give me a hint about that too, I'd be so grateful! Thanks! PS I know the system we are using at the moment absolutely sucks (definitely not 3rd form normalised!), but we are fast running out of time and money, and need to get our product up and running ASAP! EDIT: To clarify, here is a pic of the spreadsheets I'm working with... Obviously in cells A14 and A15 I wanted the ID numbers 11 & 12 respectively [![Clarification](https://i.stack.imgur.com/LbDXE.png)](https://i.stack.imgur.com/LbDXE.png)
2016/03/25
[ "https://Stackoverflow.com/questions/36219651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6019131/" ]
You can use the following method that uses the recursion: ``` function factorize(num){ if(num === 0){ return 1 ; } else { return num = num * factorize(num-1); } } ```
Simply return the value 1 ``` function factorialize(num) { if (num < 1) return 1; //this line is added for(i = 1; i <= num; i++){ arrOfNum.push(i); } var result = arrOfNum.reduce(function(a,b){ return a * b; }); console.log(result); } ```
30,200,294
I am trying to figure out how to tokenize a StreamReader of a text file. I have been able to separate the lines, but now I am trying to figure out how to break down those lines by a tab delimiter as well. This is what I have so far. ``` string readContents; using (StreamReader streamReader = new StreamReader(@"File.txt")) { readContents = streamReader.ReadToEnd(); string[] lines = readContents.Split('\r'); foreach (string s in lines) { Console.WriteLine(s); } } Console.ReadLine(); ```
2015/05/12
[ "https://Stackoverflow.com/questions/30200294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4050877/" ]
> > Since `foo` is private, it can be accessed only through `getFoo()`, right? > > > In this case, `Outer` has access to it too, because `Inner` is a member of `Outer`. [6.6.1](http://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls-6.6.1) says: > > [If] the member or constructor is declared `private`, [then] access is permitted if and only if it occurs **within the body of the top level class** that encloses the declaration of the member or constructor. > > > Note that it's specified to be accessible within the body of the *top level* class that encloses the declaration. This means, for example: ``` class Outer { static class Foo { private Foo() {} private int i; } static class Bar {{ // Bar has access to Foo's // private members too new Foo().i = 2; }} } ``` Whether to use a getter or not is really a matter of taste. The important realization here is that outer classes have access to the private members of their nested classes. As a recommendation, I would personally say: * If the nested class is `private` (only the outer class has access to it), I wouldn't bother even giving it a getter unless the getter does a computation. It's arbitrary, and somebody else can come along and choose not to use it. If the styles are mixed, the code has a vagueness. (Do `inner.foo` and `inner.getFoo()` really do the same thing? We have to go waste time examining the `Inner` class to find out.) * But you could go through a getter anyway if that's the style you are comfortable with. * If the nested class isn't `private`, use the getter so the style is uniform. If you really want to hide the `private` members, even from the outer class, you can use a factory with a local or anonymous class: ``` interface Nested { Object getFoo(); } static Nested newNested(Object foo) { // NestedImpl has method scope, // so the outer class can't refer to it by name // e.g. even to cast to it class NestedImpl implements Nested { Object foo; NestedImpl(Object foo) { this.foo = foo; } @Override public Object getFoo() { return foo; } } return new NestedImpl(foo); } ``` --- As a pedantic note, your `static class Inner {}` is technically a *static nested class*, not an *inner class*. `class Inner {}` (without `static`) would be an inner class. This is [specifically defined](http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.5.1) to be so: > > The `static` keyword may modify the declaration of a member type `C` within the body of a non-inner class or interface `T`. **Its effect is to declare that `C` is not an inner class.** > > >
It all depends on your piece of code from where do you want to access that object. Since it is a static nested class, so you will be able to access your object from either ways. Refer to this link <http://www.javatpoint.com/static-nested-class> for better understanding of inner classes.
41,488,688
``` import shopify from base64 import b64encode #omitted the shopify key shopify.ShopifyResource.set_site(shop_url) path = "product.jpg" new_product = shopify.Product() new_product.title = "title" new_product.body_html = "This is a test" image = shopify.Image() with open(path, "rb") as f: filename = path.split("/")[-1:][0] #encoded = b64encode(f.read()) (I tried this one as well) encoded = f.read() image.attach_image(encoded, filename=filename) new_product.images = image new_product.save() ``` I tested both methods: * `encoded = b64encode(f.read())` * `encoded = f.read()` In both tests, the output was the same: The product was successfully created, however, with no image. I also noticed that the `image` returns `image(None)` and `new_products.images` returns `image(None)` as well.
2017/01/05
[ "https://Stackoverflow.com/questions/41488688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2397288/" ]
You were so close- the `new_product.images` attribute must be a *list* of `Image` instances, not an `Image` instance. Also, if you look at [the source](https://github.com/Shopify/shopify_python_api/blob/13074053cefdc6ceb6cddcf06c58d3401dfa82a3/shopify/resources/image.py#L25) of `attach_image()`, you can see they do the base64 encoding for you. ``` import shopify #omitted the shopify key shopify.ShopifyResource.set_site(shop_url) path = "product.jpg" new_product = shopify.Product() new_product.title = "title" new_product.body_html = "This is a test" image = shopify.Image() with open(path, "rb") as f: filename = path.split("/")[-1:][0] encoded = f.read() image.attach_image(encoded, filename=filename) new_product.images = [image] # Here's the change new_product.save() ```
self.fake("products/632910392/images", method='POST', body=self.load\_fixture('image'), headers={'Content-type': 'application/json'}) image = shopify.Image({'product\_id':632910392}) image.position = 1 binary\_in=base64.b64decode("R0lGODlhbgCMAPf/APbr48VySrxTO7IgKt2qmKQdJeK8lsFjROG5p/nz7Zg3MNmnd7Q1MLNVS9GId71hSJMZIuzTu4UtKbeEeakhKMl8U8WYjfr18YQaIbAf==") image.attach\_image(data=binary\_in, filename='ipod-nano.png') image.save()
3,696,893
I've got a circular dependency that recently came about because of a change in my application architecture. The application relies on a plugin manager that loads plugins via MEF. Everything up until worked fine, because it looked something like this: ``` // model.cs [Export("Model")] public class Model { public PluginManager PM { get; set; } [ImportingConstructor] public Model( [Import] PluginManager plugin_manager) { PM = plugin_manager; } } // pluginmanager.cs [Export(typeof(PluginManager))] public class PluginManager { [ImportMany(typeof(PluginInterface))] private IEnumerable<PluginInterface> Plugins { get; set; } } ``` and the plugins looked like this: ``` // myplugin.cs [Export(typeof(PluginInterface))] public class MyPlugin : PluginInterface { } ``` But now I've got a situation where I want all plugins to have the ability to query the PluginManager (or possibly any other object) via an interface to find out about other plugins in the system to find out about their capabilities. I "solved" this by adding another interface, let's call it PluginQueryInterface. I then had the **Model** implement this interface. ``` [Export("Model"))] [Export(typeof(PluginQueryInterface))] public class Model : PluginQueryInterface { // same as before } ``` and then the plugin signature would look like this: ``` // 1st possible implementation [Export(typeof(PluginInterface))] public class MyPlugin : PluginInterface { [Import(typeof(PluginQueryInterface))] public PluginQueryInterface QueryInterface { get; set; } public MyPlugin() {} } ``` **or this** ``` // 2nd possible implementation [Export(typeof(PluginInterface))] public class MyPlugin : PluginInterface { private PluginQueryInterface QueryInterface { get; set; } [ImportingConstructor] public MyPlugin( [Import] PluginQueryInterface query_interface) { QueryInterface = query_interface } } ``` The **2nd** implementation is pretty clearly a circular reference, because the plugins requires that the PluginQueryInterface be created before the plugin is created, but the PluginQueryInterface is the Model, which must import the PluginManager, which in turn needs all of the PluginInterfaces created... and I do get a MEF circular dependency error when I launch. The **1st** implementation doesn't seem like a circular reference to me. If the PluginQueryInterface is a property, then I thought it wouldn't be resolved **until it was used**. And it isn't used by the constructor at all. So why wouldn't the PluginManager merrily create all of my MyPlugins? I get the same MEF error in both cases. I have tried to solve this problem by then making the PluginManager implement the PluginQueryInterface, because a) it makes sense anyway and b) it's a [known way of dealing with circular dependencies](http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/) -- make the two interdependent classes instead depend on a third class. Now the problem is that I get a **different MEF error**! This is what it says: ``` GetExportedValue cannot be called before prerequisite import 'Company.App.PluginManager..ctor(Parameter="database_filepath", ContractName="PluginManager.filename")' has been set. ``` WTF? I set breakpoints in my code, and my exported value `PluginManager.filename` **has** been set before calling GetExportedValue. I am totally stumped. Any observations or suggestions would be greatly appreciated right now. I've been banging my head against the MEF-clad wall for hours trying to debug this problem. (updated) I didn't think about this earlier, but it could have been differences between plugins, so I deleted one of the two plugins, and now my application loads without MEF errors. I added it back, and it failed again. Then I deleted the other plugin, and it worked. So it looks like this is some other MEF error. It's almost as if it doesn't want me to load more than one plugin with a specific interface... but I am using ImportMany, and wouldn't that have manifested itself as a `CardinalityException` of some kind? **UPDATE** I don't understand this part of MEF, and hopefully someone here can explain what it's all about. After stepping into the code for some time, I found that my error stemmed from MEF removing import definitions after finding the value! ``` private bool TryGetImportValue(ImportDefinition definition, out object value) { lock (this._lock) { if (this._importValues.TryGetValue(definition, out value)) { this._importValues.Remove(definition); // this is the line that got me return true; } } value = null; return false; } ``` I've never had this problem before, and frankly I'm having a hard time understanding what I'm doing now with my imports and exports that has made this problem surface. I assume that I'm doing something that the MEF designers hadn't intended anyone to do. I *could* blindly comment out the `this._importValues.Remove(definition);`, but that couldn't possibly be right. My guess is that this will boil down to the MEF attributes I've used, but since the plugin that imports this value has a creation policy of `CreationPolicy.Shared`, why would I have a problem?
2010/09/12
[ "https://Stackoverflow.com/questions/3696893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/214071/" ]
You can use the mod(%) and divide(/) operator. N%10 would give you the last digit. N/10 (integer division) will remove the last digit. You can continue till you have no more digits.
use the modulo operation: ``` a % 10 to get the last digit a % 100 to get the last two digits. (a % 100) - (a % 10) to get the second last number etc. ```
3,696,893
I've got a circular dependency that recently came about because of a change in my application architecture. The application relies on a plugin manager that loads plugins via MEF. Everything up until worked fine, because it looked something like this: ``` // model.cs [Export("Model")] public class Model { public PluginManager PM { get; set; } [ImportingConstructor] public Model( [Import] PluginManager plugin_manager) { PM = plugin_manager; } } // pluginmanager.cs [Export(typeof(PluginManager))] public class PluginManager { [ImportMany(typeof(PluginInterface))] private IEnumerable<PluginInterface> Plugins { get; set; } } ``` and the plugins looked like this: ``` // myplugin.cs [Export(typeof(PluginInterface))] public class MyPlugin : PluginInterface { } ``` But now I've got a situation where I want all plugins to have the ability to query the PluginManager (or possibly any other object) via an interface to find out about other plugins in the system to find out about their capabilities. I "solved" this by adding another interface, let's call it PluginQueryInterface. I then had the **Model** implement this interface. ``` [Export("Model"))] [Export(typeof(PluginQueryInterface))] public class Model : PluginQueryInterface { // same as before } ``` and then the plugin signature would look like this: ``` // 1st possible implementation [Export(typeof(PluginInterface))] public class MyPlugin : PluginInterface { [Import(typeof(PluginQueryInterface))] public PluginQueryInterface QueryInterface { get; set; } public MyPlugin() {} } ``` **or this** ``` // 2nd possible implementation [Export(typeof(PluginInterface))] public class MyPlugin : PluginInterface { private PluginQueryInterface QueryInterface { get; set; } [ImportingConstructor] public MyPlugin( [Import] PluginQueryInterface query_interface) { QueryInterface = query_interface } } ``` The **2nd** implementation is pretty clearly a circular reference, because the plugins requires that the PluginQueryInterface be created before the plugin is created, but the PluginQueryInterface is the Model, which must import the PluginManager, which in turn needs all of the PluginInterfaces created... and I do get a MEF circular dependency error when I launch. The **1st** implementation doesn't seem like a circular reference to me. If the PluginQueryInterface is a property, then I thought it wouldn't be resolved **until it was used**. And it isn't used by the constructor at all. So why wouldn't the PluginManager merrily create all of my MyPlugins? I get the same MEF error in both cases. I have tried to solve this problem by then making the PluginManager implement the PluginQueryInterface, because a) it makes sense anyway and b) it's a [known way of dealing with circular dependencies](http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/) -- make the two interdependent classes instead depend on a third class. Now the problem is that I get a **different MEF error**! This is what it says: ``` GetExportedValue cannot be called before prerequisite import 'Company.App.PluginManager..ctor(Parameter="database_filepath", ContractName="PluginManager.filename")' has been set. ``` WTF? I set breakpoints in my code, and my exported value `PluginManager.filename` **has** been set before calling GetExportedValue. I am totally stumped. Any observations or suggestions would be greatly appreciated right now. I've been banging my head against the MEF-clad wall for hours trying to debug this problem. (updated) I didn't think about this earlier, but it could have been differences between plugins, so I deleted one of the two plugins, and now my application loads without MEF errors. I added it back, and it failed again. Then I deleted the other plugin, and it worked. So it looks like this is some other MEF error. It's almost as if it doesn't want me to load more than one plugin with a specific interface... but I am using ImportMany, and wouldn't that have manifested itself as a `CardinalityException` of some kind? **UPDATE** I don't understand this part of MEF, and hopefully someone here can explain what it's all about. After stepping into the code for some time, I found that my error stemmed from MEF removing import definitions after finding the value! ``` private bool TryGetImportValue(ImportDefinition definition, out object value) { lock (this._lock) { if (this._importValues.TryGetValue(definition, out value)) { this._importValues.Remove(definition); // this is the line that got me return true; } } value = null; return false; } ``` I've never had this problem before, and frankly I'm having a hard time understanding what I'm doing now with my imports and exports that has made this problem surface. I assume that I'm doing something that the MEF designers hadn't intended anyone to do. I *could* blindly comment out the `this._importValues.Remove(definition);`, but that couldn't possibly be right. My guess is that this will boil down to the MEF attributes I've used, but since the plugin that imports this value has a creation policy of `CreationPolicy.Shared`, why would I have a problem?
2010/09/12
[ "https://Stackoverflow.com/questions/3696893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/214071/" ]
You can use the mod(%) and divide(/) operator. N%10 would give you the last digit. N/10 (integer division) will remove the last digit. You can continue till you have no more digits.
Once you've divided by 100,000,000 and taken the integer value, you can then multiply this integer value back by 100,000,000 and subtract it from the ISBN. That effectively just takes off the left-most digit. So now, repeat with 10,000,000 - and so on. Example with 5 digits: ``` Start: 74325 74325/10000 and int = 7 (there's your first digit) 7 * 10000 = 70000 74325 - 70000 = 4325 4325/1000 and int = 4 (there's your next digit) 4 * 1000 = 4000 4325 - 4000 = 325 ``` and so on!
3,696,893
I've got a circular dependency that recently came about because of a change in my application architecture. The application relies on a plugin manager that loads plugins via MEF. Everything up until worked fine, because it looked something like this: ``` // model.cs [Export("Model")] public class Model { public PluginManager PM { get; set; } [ImportingConstructor] public Model( [Import] PluginManager plugin_manager) { PM = plugin_manager; } } // pluginmanager.cs [Export(typeof(PluginManager))] public class PluginManager { [ImportMany(typeof(PluginInterface))] private IEnumerable<PluginInterface> Plugins { get; set; } } ``` and the plugins looked like this: ``` // myplugin.cs [Export(typeof(PluginInterface))] public class MyPlugin : PluginInterface { } ``` But now I've got a situation where I want all plugins to have the ability to query the PluginManager (or possibly any other object) via an interface to find out about other plugins in the system to find out about their capabilities. I "solved" this by adding another interface, let's call it PluginQueryInterface. I then had the **Model** implement this interface. ``` [Export("Model"))] [Export(typeof(PluginQueryInterface))] public class Model : PluginQueryInterface { // same as before } ``` and then the plugin signature would look like this: ``` // 1st possible implementation [Export(typeof(PluginInterface))] public class MyPlugin : PluginInterface { [Import(typeof(PluginQueryInterface))] public PluginQueryInterface QueryInterface { get; set; } public MyPlugin() {} } ``` **or this** ``` // 2nd possible implementation [Export(typeof(PluginInterface))] public class MyPlugin : PluginInterface { private PluginQueryInterface QueryInterface { get; set; } [ImportingConstructor] public MyPlugin( [Import] PluginQueryInterface query_interface) { QueryInterface = query_interface } } ``` The **2nd** implementation is pretty clearly a circular reference, because the plugins requires that the PluginQueryInterface be created before the plugin is created, but the PluginQueryInterface is the Model, which must import the PluginManager, which in turn needs all of the PluginInterfaces created... and I do get a MEF circular dependency error when I launch. The **1st** implementation doesn't seem like a circular reference to me. If the PluginQueryInterface is a property, then I thought it wouldn't be resolved **until it was used**. And it isn't used by the constructor at all. So why wouldn't the PluginManager merrily create all of my MyPlugins? I get the same MEF error in both cases. I have tried to solve this problem by then making the PluginManager implement the PluginQueryInterface, because a) it makes sense anyway and b) it's a [known way of dealing with circular dependencies](http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/) -- make the two interdependent classes instead depend on a third class. Now the problem is that I get a **different MEF error**! This is what it says: ``` GetExportedValue cannot be called before prerequisite import 'Company.App.PluginManager..ctor(Parameter="database_filepath", ContractName="PluginManager.filename")' has been set. ``` WTF? I set breakpoints in my code, and my exported value `PluginManager.filename` **has** been set before calling GetExportedValue. I am totally stumped. Any observations or suggestions would be greatly appreciated right now. I've been banging my head against the MEF-clad wall for hours trying to debug this problem. (updated) I didn't think about this earlier, but it could have been differences between plugins, so I deleted one of the two plugins, and now my application loads without MEF errors. I added it back, and it failed again. Then I deleted the other plugin, and it worked. So it looks like this is some other MEF error. It's almost as if it doesn't want me to load more than one plugin with a specific interface... but I am using ImportMany, and wouldn't that have manifested itself as a `CardinalityException` of some kind? **UPDATE** I don't understand this part of MEF, and hopefully someone here can explain what it's all about. After stepping into the code for some time, I found that my error stemmed from MEF removing import definitions after finding the value! ``` private bool TryGetImportValue(ImportDefinition definition, out object value) { lock (this._lock) { if (this._importValues.TryGetValue(definition, out value)) { this._importValues.Remove(definition); // this is the line that got me return true; } } value = null; return false; } ``` I've never had this problem before, and frankly I'm having a hard time understanding what I'm doing now with my imports and exports that has made this problem surface. I assume that I'm doing something that the MEF designers hadn't intended anyone to do. I *could* blindly comment out the `this._importValues.Remove(definition);`, but that couldn't possibly be right. My guess is that this will boil down to the MEF attributes I've used, but since the plugin that imports this value has a creation policy of `CreationPolicy.Shared`, why would I have a problem?
2010/09/12
[ "https://Stackoverflow.com/questions/3696893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/214071/" ]
Once you've divided by 100,000,000 and taken the integer value, you can then multiply this integer value back by 100,000,000 and subtract it from the ISBN. That effectively just takes off the left-most digit. So now, repeat with 10,000,000 - and so on. Example with 5 digits: ``` Start: 74325 74325/10000 and int = 7 (there's your first digit) 7 * 10000 = 70000 74325 - 70000 = 4325 4325/1000 and int = 4 (there's your next digit) 4 * 1000 = 4000 4325 - 4000 = 325 ``` and so on!
use the modulo operation: ``` a % 10 to get the last digit a % 100 to get the last two digits. (a % 100) - (a % 10) to get the second last number etc. ```
10,881,883
I am trying to use `C# in javascript` like we are using it in `MVC Razor View` using `@ sign`, like suppose an `array name list` is passed to the `View` so we can access it in `View` like: **View** ``` Length of array : <input type="text" value="@Model.list.Length" /> Or we can iterate list array also like: @for(int i=0; i< Model.list.Length; i++) { console.log(Model.list[i]); } ``` But my question is how we can iterate or use this array in the javascript code , something similar to : **JS** ``` for(var i=0; i<@Model.list.Length; i++) { $("body").append("<h1></h1>").html(@Model.list[i]); } ``` Thanks !
2012/06/04
[ "https://Stackoverflow.com/questions/10881883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1435222/" ]
As i posted in my comment, this is a bit tricky. However, you can try to construct a javascript object with your c#. Something like this (i don't know how this works exactly...): ``` var array = [ @for(var i = 0; i < Model.list.Length-1; i++){ @Model.list[i] , } @Model.list[length] ] ``` which should result in: ``` var array = [ val1, val2, val3, valn ] ``` Now you have an js var `array`, you can work with in your entire document.
You can't do it exactly that way. What you can do is use the C# to generate the javascript code for each line like this: ``` //...javascript code... @for(var i = 0; i < Model.list.Length; i++) { $("body").append("<h1></h1>").html('@(Model.list[i])'); } //...more javascript code... ``` This should output like this: ``` //...javascript code... $("body").append("<h1></h1>").html(listitem0); $("body").append("<h1></h1>").html(listitem1); $("body").append("<h1></h1>").html(listitem2); //etc. //...more javascript code... ```
4,174,389
There are 2 ways to get the 3 rotation values (azimuth, pitch, roll). One is registering a listener of a type TYPE\_ORIENTATION. It's the easiest way and I get a correct range of values from every rotation as the documentation says: azimuth: [0, 359] pitch: [-180, 180] roll: [-90, 90] The other one, the most precise and complex to understand the first time you see it. Android recommends it, so I want to use it, but I get different values. azimuth: [-180, 180]. -180/180 is S, 0 i N, 90 E and -90 W. pitch: [-90, 90]. 90 is 90, -90 is -90, 0 is 0 but -180/180 (lying with the screen downwards) is 0. roll: [-180, 180]. I should get the same values but with decimals, right? I have the following code: ``` aValues = new float[3]; mValues = new float[3]; sensorListener = new SensorEventListener (){ public void onSensorChanged (SensorEvent event){ switch (event.sensor.getType ()){ case Sensor.TYPE_ACCELEROMETER: aValues = event.values.clone (); break; case Sensor.TYPE_MAGNETIC_FIELD: mValues = event.values.clone (); break; } float[] R = new float[16]; float[] orientationValues = new float[3]; SensorManager.getRotationMatrix (R, null, aValues, mValues); SensorManager.getOrientation (R, orientationValues); orientationValues[0] = (float)Math.toDegrees (orientationValues[0]); orientationValues[1] = (float)Math.toDegrees (orientationValues[1]); orientationValues[2] = (float)Math.toDegrees (orientationValues[2]); azimuthText.setText ("azimuth: " + orientationValues[0]); pitchText.setText ("pitch: " + orientationValues[1]); rollText.setText ("roll: " + orientationValues[2]); } public void onAccuracyChanged (Sensor sensor, int accuracy){} }; ``` Please help. It's very frustrating. Do I have to treat with those values or I'm doing something wrong? Thanks.
2010/11/13
[ "https://Stackoverflow.com/questions/4174389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/458093/" ]
I might be shooting in the dark here, but if I understand your question correctly, you are wondering why you get `[-179..179]` instead of `[0..360]`? Note that `-180` is the same as `+180` and the same as `180 + N*360` where `N` is a whole number (integer). In other words, if you want to get the same numbers as with orientation sensor you can do this: ``` // x = orientationValues[0]; // y = orientationValues[1]; // z = orientationValues[2]; x = (x + 360.0) % 360.0; y = (y + 360.0) % 360.0; z = (z + 360.0) % 360.0; ``` This will give you the values in the `[0..360]` range as you wanted.
You are missing one critical computation in your calculations. The [**remapCoordinateSystem**](http://developer.android.com/reference/android/hardware/SensorManager.html) call afer you do a **getRotationMatrix**. Add that to your code and all will be fine. You can read more about it **[here](http://developer.android.com/reference/android/hardware/Sensor.html#TYPE_ORIENTATION)**.
4,174,389
There are 2 ways to get the 3 rotation values (azimuth, pitch, roll). One is registering a listener of a type TYPE\_ORIENTATION. It's the easiest way and I get a correct range of values from every rotation as the documentation says: azimuth: [0, 359] pitch: [-180, 180] roll: [-90, 90] The other one, the most precise and complex to understand the first time you see it. Android recommends it, so I want to use it, but I get different values. azimuth: [-180, 180]. -180/180 is S, 0 i N, 90 E and -90 W. pitch: [-90, 90]. 90 is 90, -90 is -90, 0 is 0 but -180/180 (lying with the screen downwards) is 0. roll: [-180, 180]. I should get the same values but with decimals, right? I have the following code: ``` aValues = new float[3]; mValues = new float[3]; sensorListener = new SensorEventListener (){ public void onSensorChanged (SensorEvent event){ switch (event.sensor.getType ()){ case Sensor.TYPE_ACCELEROMETER: aValues = event.values.clone (); break; case Sensor.TYPE_MAGNETIC_FIELD: mValues = event.values.clone (); break; } float[] R = new float[16]; float[] orientationValues = new float[3]; SensorManager.getRotationMatrix (R, null, aValues, mValues); SensorManager.getOrientation (R, orientationValues); orientationValues[0] = (float)Math.toDegrees (orientationValues[0]); orientationValues[1] = (float)Math.toDegrees (orientationValues[1]); orientationValues[2] = (float)Math.toDegrees (orientationValues[2]); azimuthText.setText ("azimuth: " + orientationValues[0]); pitchText.setText ("pitch: " + orientationValues[1]); rollText.setText ("roll: " + orientationValues[2]); } public void onAccuracyChanged (Sensor sensor, int accuracy){} }; ``` Please help. It's very frustrating. Do I have to treat with those values or I'm doing something wrong? Thanks.
2010/11/13
[ "https://Stackoverflow.com/questions/4174389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/458093/" ]
I know I'm playing thread necromancer here, but I've been working on this stuff a lot lately, so I thought I'd throw in my 2¢. The device doesn't contain compass or inclinometers, so it doesn't measure azimuth, pitch, or roll directly. (We call those Euler angles, BTW). Instead, it uses accelerometers and magnetometers, both of which produce 3-space XYZ vectors. These are used to compute the azimuth, etc. values. Vectors are in device coordinate space: ![Device coordinates](https://i.stack.imgur.com/Nhlhk.png) World coordinates have Y facing north, X facing east, and Z facing up: ![World coordinates](https://developer.android.com/images/axis_globe.png) Thus, a device's "neutral" orientation is lying flat on its back on a table, with the top of the device facing north. The accelerometer produces a vector in the "UP" direction. The magnetometer produces a vector in the "north" direction. (Note that in the northern hemisphere, this tends to point downward due to [magnetic dip](http://en.wikipedia.org/wiki/Magnetic_dip).) The accelerometer vector and magnetometer vector can be combined mathematically through SensorManager.getRotationMatrix() which returns a 3x3 matrix which will map vectors in device coordinates to world coordinates or vice-versa. For a device in the neutral position, this function would return the identity matrix. This matrix does not vary with the screen orientation. This means your application needs to be aware of orientation and compensate accordingly. SensorManager.getOrientation() takes the transformation matrix and computes azimuth, pitch, and roll values. These are taken relative to a device in the neutral position. I have no idea what the difference is between calling this function and just using TYPE\_ORIENTATION sensor, except that the function lets you manipulate the matrix first. If the device is tilted up at 90° or near it, then the use of Euler angles falls apart. This is a degenerate case mathematically. In this realm, how is the device supposed to know if you're changing azimuth or roll? The function SensorManager.remapCoordinateSystem() can be used to manipulate the transformation matrix to compensate for what you may know about the orientation of the device. However, my experiments have shown that this doesn't cover all cases, not even some of the common ones. For example, if you want to remap for a device held upright (e.g. to take a photo), you would want to multiply the transformation matrix by this matrix: ``` 1 0 0 0 0 1 0 1 0 ``` before calling getOrientation(), and this is not one of the orientation remappings that remapCoordinateSystem() supports [someone please correct me if I've missed something here]. OK, so this has all been a long-winded way of saying that if you're using orientation, either from the TYPE\_ORIENTATION sensor or from getOrientation(), you're probably doing it wrong. The only time you *actually* want the Euler angles is to display orientation information in a user-friendly form, to annotate a photograph, to drive flight instrument display, or something similar. If you want to do computations related to device orientation, you're almost certainly better off using the transformation matrix and working with XYZ vectors. Working as a consultant, whenever someone comes to me with a problem involving Euler angles, I back up and ask them what they're *really* trying to do, and then find a way to do it with vectors instead. Looking back at your original question, getOrientation() should return three values in [-180 180] [-90 90] and [-180 180] (after converting from radians). In practice, we think of azimuth as numbers in [0 360), so you should simply add 360 to any negative numbers you receive. Your code looks correct as written. It would help if I knew exactly what results you were expecting and what you were getting instead. Edited to add: A couple more thoughts. Modern versions of Android use something called "sensor fusion", which basically means that all available inputs -- acceleromter, magnetometer, gyro -- are combined together in a mathematical black box (typically a Kalman filter, but depends on vendor). All of the different sensors -- acceleration, magnetic field, gyros, gravity, linear acceleration, and orientation -- are taken as outputs from this black box. Whenever possible, you should use TYPE\_GRAVITY rather than TYPE\_ACCELEROMETER as the input to getRotationMatrix().
You are missing one critical computation in your calculations. The [**remapCoordinateSystem**](http://developer.android.com/reference/android/hardware/SensorManager.html) call afer you do a **getRotationMatrix**. Add that to your code and all will be fine. You can read more about it **[here](http://developer.android.com/reference/android/hardware/Sensor.html#TYPE_ORIENTATION)**.
4,174,389
There are 2 ways to get the 3 rotation values (azimuth, pitch, roll). One is registering a listener of a type TYPE\_ORIENTATION. It's the easiest way and I get a correct range of values from every rotation as the documentation says: azimuth: [0, 359] pitch: [-180, 180] roll: [-90, 90] The other one, the most precise and complex to understand the first time you see it. Android recommends it, so I want to use it, but I get different values. azimuth: [-180, 180]. -180/180 is S, 0 i N, 90 E and -90 W. pitch: [-90, 90]. 90 is 90, -90 is -90, 0 is 0 but -180/180 (lying with the screen downwards) is 0. roll: [-180, 180]. I should get the same values but with decimals, right? I have the following code: ``` aValues = new float[3]; mValues = new float[3]; sensorListener = new SensorEventListener (){ public void onSensorChanged (SensorEvent event){ switch (event.sensor.getType ()){ case Sensor.TYPE_ACCELEROMETER: aValues = event.values.clone (); break; case Sensor.TYPE_MAGNETIC_FIELD: mValues = event.values.clone (); break; } float[] R = new float[16]; float[] orientationValues = new float[3]; SensorManager.getRotationMatrix (R, null, aValues, mValues); SensorManager.getOrientation (R, orientationValues); orientationValues[0] = (float)Math.toDegrees (orientationValues[0]); orientationValues[1] = (float)Math.toDegrees (orientationValues[1]); orientationValues[2] = (float)Math.toDegrees (orientationValues[2]); azimuthText.setText ("azimuth: " + orientationValues[0]); pitchText.setText ("pitch: " + orientationValues[1]); rollText.setText ("roll: " + orientationValues[2]); } public void onAccuracyChanged (Sensor sensor, int accuracy){} }; ``` Please help. It's very frustrating. Do I have to treat with those values or I'm doing something wrong? Thanks.
2010/11/13
[ "https://Stackoverflow.com/questions/4174389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/458093/" ]
I know I'm playing thread necromancer here, but I've been working on this stuff a lot lately, so I thought I'd throw in my 2¢. The device doesn't contain compass or inclinometers, so it doesn't measure azimuth, pitch, or roll directly. (We call those Euler angles, BTW). Instead, it uses accelerometers and magnetometers, both of which produce 3-space XYZ vectors. These are used to compute the azimuth, etc. values. Vectors are in device coordinate space: ![Device coordinates](https://i.stack.imgur.com/Nhlhk.png) World coordinates have Y facing north, X facing east, and Z facing up: ![World coordinates](https://developer.android.com/images/axis_globe.png) Thus, a device's "neutral" orientation is lying flat on its back on a table, with the top of the device facing north. The accelerometer produces a vector in the "UP" direction. The magnetometer produces a vector in the "north" direction. (Note that in the northern hemisphere, this tends to point downward due to [magnetic dip](http://en.wikipedia.org/wiki/Magnetic_dip).) The accelerometer vector and magnetometer vector can be combined mathematically through SensorManager.getRotationMatrix() which returns a 3x3 matrix which will map vectors in device coordinates to world coordinates or vice-versa. For a device in the neutral position, this function would return the identity matrix. This matrix does not vary with the screen orientation. This means your application needs to be aware of orientation and compensate accordingly. SensorManager.getOrientation() takes the transformation matrix and computes azimuth, pitch, and roll values. These are taken relative to a device in the neutral position. I have no idea what the difference is between calling this function and just using TYPE\_ORIENTATION sensor, except that the function lets you manipulate the matrix first. If the device is tilted up at 90° or near it, then the use of Euler angles falls apart. This is a degenerate case mathematically. In this realm, how is the device supposed to know if you're changing azimuth or roll? The function SensorManager.remapCoordinateSystem() can be used to manipulate the transformation matrix to compensate for what you may know about the orientation of the device. However, my experiments have shown that this doesn't cover all cases, not even some of the common ones. For example, if you want to remap for a device held upright (e.g. to take a photo), you would want to multiply the transformation matrix by this matrix: ``` 1 0 0 0 0 1 0 1 0 ``` before calling getOrientation(), and this is not one of the orientation remappings that remapCoordinateSystem() supports [someone please correct me if I've missed something here]. OK, so this has all been a long-winded way of saying that if you're using orientation, either from the TYPE\_ORIENTATION sensor or from getOrientation(), you're probably doing it wrong. The only time you *actually* want the Euler angles is to display orientation information in a user-friendly form, to annotate a photograph, to drive flight instrument display, or something similar. If you want to do computations related to device orientation, you're almost certainly better off using the transformation matrix and working with XYZ vectors. Working as a consultant, whenever someone comes to me with a problem involving Euler angles, I back up and ask them what they're *really* trying to do, and then find a way to do it with vectors instead. Looking back at your original question, getOrientation() should return three values in [-180 180] [-90 90] and [-180 180] (after converting from radians). In practice, we think of azimuth as numbers in [0 360), so you should simply add 360 to any negative numbers you receive. Your code looks correct as written. It would help if I knew exactly what results you were expecting and what you were getting instead. Edited to add: A couple more thoughts. Modern versions of Android use something called "sensor fusion", which basically means that all available inputs -- acceleromter, magnetometer, gyro -- are combined together in a mathematical black box (typically a Kalman filter, but depends on vendor). All of the different sensors -- acceleration, magnetic field, gyros, gravity, linear acceleration, and orientation -- are taken as outputs from this black box. Whenever possible, you should use TYPE\_GRAVITY rather than TYPE\_ACCELEROMETER as the input to getRotationMatrix().
I might be shooting in the dark here, but if I understand your question correctly, you are wondering why you get `[-179..179]` instead of `[0..360]`? Note that `-180` is the same as `+180` and the same as `180 + N*360` where `N` is a whole number (integer). In other words, if you want to get the same numbers as with orientation sensor you can do this: ``` // x = orientationValues[0]; // y = orientationValues[1]; // z = orientationValues[2]; x = (x + 360.0) % 360.0; y = (y + 360.0) % 360.0; z = (z + 360.0) % 360.0; ``` This will give you the values in the `[0..360]` range as you wanted.
5,442
We know that we wash our hands because germs can get into our body through the nose, the mouth, the eyes, cuts, etc. But I doubt we can completely clean our hands of germs every time we wash them, down to the individual bacterium or virion, even if we use anti-septic soap. So chances are, even if we keep up with our hygiene, germs still get into our body, only in very very small quantities. So here are some questions: 1. In theory, is there a dividing line where we can say "ok, at this non-zero count of bacteria or virion, there is still (*an arbitrary probability*) that a normal healthy person won't get sick" **for every germ known to man**? If not, are there germs that are known to cause havoc in a healthy person even if he comes into contact with a single individual bacterium or virion? 2. Do we know a certain trend based on the classification of the germ? 3. How about the most commonly found germs (whichever they are)? 4. How about some of the most feared, but not so common, virii known to man, like HIV, ebola, SARS? I think that without being able to answer some of these questions, especially #3, hygiene would be nothing but a ritual activity (because "it just works").
2012/12/08
[ "https://biology.stackexchange.com/questions/5442", "https://biology.stackexchange.com", "https://biology.stackexchange.com/users/1114/" ]
There is a Wikipedia page which gives [some typical values](http://en.wikipedia.org/wiki/Infectious_dose) for infectious doses of bacteria. I suspect that lot of these have been taken from [this slideshow](http://www.fsis.usda.gov/PDF/Atlanta2010/Slides_FSEC_JGreig_Doses.pdf) which confirms the values on the Wikipedia page, gives more interesting details of how they have been arrived at, and also mentions a few viruses. It seems from the slideshow that infectious dose isn't estimated in the way that the OP envisages - *"What is the probability of infection if I ingest one cell?"*. What **is** clear is that the infectious doses for some bacteria can be less than 10 cells (e.g. *Shigella flexneri*, *E. coli* O157:H7). Conversely for many other pathogens such as other strains of *E. coli* the estimate is >106 cells, so standard hygiene precautions will always offer some protection.
Washing your hands is an exercise in probability rather than absolute values. An important thing to keep in mind is that not only is it very hard to kill all the bacteria on your hands, it's also not something you actually want to do. Most of the bacteria we encounter day to day are either benign or beneficial to personal health. We know that gnotobiotic mice (sterile mice) exhibit impaired development, especially in the immune system. We want to come into moderate contact with bacteria. Because it is a balancing act, I think hygiene needs to be reframed. For one things anti-septic soap should be reserved only for situations when it is absolutely necessary. Anti-septic soap has a tendency to apply a selective pressure that encourages propagation of resistant strains. Situations where it is worth using would include visiting an international transit center (airport), working in an Operating Room ward at a hospital, or going to a cafeteria during an epidemic. In other situations, regular plain soap and water should be good enough to rub the majority of cells off your hands so that passive immunity has a good chance of eliminating any threats before they get to vulnerable parts of the body. If you have the opportunity, paper towels are better for getting cells off your hands then blowers.
27,691,040
this is my code ``` function masspoke(serverConnectionHandlerID, clientID, txt) local error = ts3.requestClientPoke(serverConnectionHandlerID, clientID, txt) sleep(1) local error = ts3.requestClientPoke(serverConnectionHandlerID, clientID, txt) if error == ts3errors.ERROR_not_connected then ts3.printMessage(serverConnectionHandlerID, "Error: Not Connected") return elseif error ~= ts3errors.ERROR_ok then print("Getting Error: " .. error .. "by poking the ID: " .. clientID) return end ts3.requestClientPoke(serverConnectionHandlerID, clientID, txt) end ``` and my error is ``` attempt to call global 'sleep' (a nil value) ```
2014/12/29
[ "https://Stackoverflow.com/questions/27691040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4402517/" ]
There is no `sleep` function in Lua, hence the error you are getting. The simplest way to achieve what you want is to use [socket.sleep](http://w3.impa.br/~diego/software/luasocket/socket.html#sleep) if you have access to luasocket. There are several other options listed in [this](https://stackoverflow.com/questions/1034334/easiest-way-to-make-lua-script-wait-pause-sleep-block-for-a-few-seconds) and [this](https://stackoverflow.com/questions/17987618/how-to-add-a-sleep-or-wait-to-my-lua-script) SO questions.
Lua does not provide a sleep function. There are several ways to implement one [as discussed on the Lua wiki](http://lua-users.org/wiki/SleepFunction), definitely take a look. The socket based solution is a better option than a timer loop because it doesnt spin the CPU (keep it busy), but it requires that you install the third party `sockets` library. In all solutions, your app can't do anything else, it is stuck waiting for the time to elapse. You should ask if you really need to block your thread for a set time, ie why not instead loop until a certain condition is met. In your case this could be loop until either the OK status is obtained from the request, or a certain amount of time has elapsed. This way, the loop will end as soon as your "go ahead" condition is reached, but function will return if it takes too long to reach the condition. The other advantage of this is that you might be able to give the TS app a chance to process other events, each time through the loop. It would look like this (not tested): ``` function masspoke(serverConnectionHandlerID, clientID, txt) local start = os.clock() -- start timing local MAX_WAIT_SECS = 1 -- seconds to wait for OK local error = ts3.requestClientPoke(serverConnectionHandlerID, clientID, txt) while error ~= ts3errors.ERROR_ok do if os.clock() - start > MAX_WAIT_SECS then -- too long, give up! if error == ts3errors.ERROR_not_connected then ts3.printMessage(serverConnectionHandlerID, "Error: Not Connected") else print("Getting Error: " .. error .. "by poking the ID: " .. clientID) end return end error = ts3.requestClientPoke(serverConnectionHandlerID, clientID, txt) end -- now that ts poke is ok, do whatever: ts3.requestClientPoke(serverConnectionHandlerID, clientID, txt) end ``` I think the above is a cleaner approach, the intent is clearer. If you really want to sleep the main thread via the socket module, then put this before your `masspoke()` function: ``` require "socket" -- you need to install socket lib manually function sleep(sec) socket.select(nil, nil, sec) end ``` But there are several other options on <http://lua-users.org/wiki/SleepFunction> that should be worth trying (depending on your platform, and whether you want your prog to run on multiple platforms or not) that do not require the installation of a third-party library. Make sure to read that page carefully and try out what it shows.
12,004,748
I'm looking for a AaaS to handle the agile/scrum project management for a commercial software development project. We are probably going to use git as SCM and ideally we would like to have a good integration between the code changes in SCM and the tasks/bugs in the project management. I've narrowed down the search to a few options: **Redmine**: Mainstream open source, free software development management tool. Tasks, bugs, wiki, blogs, time tracking, git integration, pretty much everything we need. Not hosted. Could be deployed in-house or in a PaaS like CloudFoundry. **JIRA**: Lots of features. Integration with Git, Eclipse, plenty of plugins, plenty of functionality. 1 to 4 $/month/person/application. Limited integration with google apps. **Zoho Projects**: New generation of management apps, fully integrated with google apps (calendar, docs, tasks). Task Management, Document Sharing, Time Tracking & Billing, Bug Tracking Software, Gantt Charts, Project Wiki, Project Chat, Project Calendar, Project Forums. With bug tracker, ticketing, git integration. Quite expensive (Projects $299 / year, Bug Tracker Add-on $299 / year) **Yodiz**: Looks perfect for scrum (scrum board, release board, backlog, planning board, epics, sprints, releases). It has time sheets and integration with SCM, with automatic posting in the tasks/defects when the code is committed (<http://app.yodiz.com/thirdparty/pages/git.vz?pid=6>). Pricing 5$/user/month + 22$ month for GitHub. There is another similar software fogcreek (<http://www.fogcreek.com>) but it's VERY expensive. **Assembla**: Everything under one roof. SCM repository + all the agile functionality (wiki, tickets, files, etc). 9$ to 99$ per month, 10$/user/month for assembla portfolio. Quite popular. Assembla looks like a very good option, but I don't seem to find a loot of feedback about it. Could you give me your advice on Assembla, the other tools and maybe other different options. An interesting project managament/CRM/bug trackers comparison spreadsheet: <https://spreadsheets.google.com/spreadsheet/pub?hl=en&key=0Ahw066SJeeSadFJGWXRTUVVfaE1WWmpkU09WUkt6Z0E&hl=en&gid=6>
2012/08/17
[ "https://Stackoverflow.com/questions/12004748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1606537/" ]
Assembla is good at integrating your SCM with your ticket/bug tracking. This is it's specialty. You can use Merge Requests for Code Review and Release Management. It has several ticket views for Management planning and Development planning. Every commit is able to be linked directly to tickets and you are able to track not only your bugs as they flow through the system, but the code that surrounds these bugs. You should try it, there is a 30 day free trial that will allow you to use all of the various tools associated.
Looks like you are trying to look at different software alternatives for project management. Here is one good comprehensive list (and comparison) of the different tools you can use: <http://blog.timedoctor.com/2011/02/02/43-project-management-software-alternatives> That should give you some really good alternatives and you can add that to your research.
12,004,748
I'm looking for a AaaS to handle the agile/scrum project management for a commercial software development project. We are probably going to use git as SCM and ideally we would like to have a good integration between the code changes in SCM and the tasks/bugs in the project management. I've narrowed down the search to a few options: **Redmine**: Mainstream open source, free software development management tool. Tasks, bugs, wiki, blogs, time tracking, git integration, pretty much everything we need. Not hosted. Could be deployed in-house or in a PaaS like CloudFoundry. **JIRA**: Lots of features. Integration with Git, Eclipse, plenty of plugins, plenty of functionality. 1 to 4 $/month/person/application. Limited integration with google apps. **Zoho Projects**: New generation of management apps, fully integrated with google apps (calendar, docs, tasks). Task Management, Document Sharing, Time Tracking & Billing, Bug Tracking Software, Gantt Charts, Project Wiki, Project Chat, Project Calendar, Project Forums. With bug tracker, ticketing, git integration. Quite expensive (Projects $299 / year, Bug Tracker Add-on $299 / year) **Yodiz**: Looks perfect for scrum (scrum board, release board, backlog, planning board, epics, sprints, releases). It has time sheets and integration with SCM, with automatic posting in the tasks/defects when the code is committed (<http://app.yodiz.com/thirdparty/pages/git.vz?pid=6>). Pricing 5$/user/month + 22$ month for GitHub. There is another similar software fogcreek (<http://www.fogcreek.com>) but it's VERY expensive. **Assembla**: Everything under one roof. SCM repository + all the agile functionality (wiki, tickets, files, etc). 9$ to 99$ per month, 10$/user/month for assembla portfolio. Quite popular. Assembla looks like a very good option, but I don't seem to find a loot of feedback about it. Could you give me your advice on Assembla, the other tools and maybe other different options. An interesting project managament/CRM/bug trackers comparison spreadsheet: <https://spreadsheets.google.com/spreadsheet/pub?hl=en&key=0Ahw066SJeeSadFJGWXRTUVVfaE1WWmpkU09WUkt6Z0E&hl=en&gid=6>
2012/08/17
[ "https://Stackoverflow.com/questions/12004748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1606537/" ]
Assembla is good at integrating your SCM with your ticket/bug tracking. This is it's specialty. You can use Merge Requests for Code Review and Release Management. It has several ticket views for Management planning and Development planning. Every commit is able to be linked directly to tickets and you are able to track not only your bugs as they flow through the system, but the code that surrounds these bugs. You should try it, there is a 30 day free trial that will allow you to use all of the various tools associated.
Also take a look at SonicAgile.com -- designed specifically for Scrum and it includes support for backlogs, scrumboards, and burndown charts. I wrote a blog entry on its features here: <http://stephenwalther.com/archive/2012/08/08/announcing-sonicagile-an-agile-project-management-solution.aspx>
63,581,152
I have a card view as follow [![enter image description here](https://i.stack.imgur.com/lwx6D.png)](https://i.stack.imgur.com/lwx6D.png) There, the red coloured text row has 2 `Text` fields. I want to keep a space between the `Text` field in the right and the right side of the card(As exact same as text lines in black color). Below is my implementation. How can I achieve this? Thanks in advance! ``` Container( margin: const EdgeInsets.only(top: 20.0), child: Center( child: Align( alignment: Alignment.topCenter, child: Card( child: InkWell( splashColor: Colors.blue.withAlpha(30), onTap: (){ print('Card Tapped'); }, child: Container( width: 380, height: 140, child: Align( alignment: Alignment.centerLeft, child: new Column( children : <Widget>[ Container( margin: const EdgeInsets.only(left: 25, top: 25), alignment: Alignment.centerLeft, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text('Account Number', textAlign: TextAlign.left, style: TextStyle(fontWeight: FontWeight.bold,fontSize: 15, color: Colors.redAccent), ), // Spacer(flex: 1), Text('12345678', textAlign: TextAlign.right, textDirection: TextDirection.rtl, style: TextStyle(fontWeight: FontWeight.bold,fontSize: 15, color: Colors.redAccent),) //<------- This text field should keep a space from right ], ), ), Container( margin: const EdgeInsets.only(left: 25, top: 15), alignment: Alignment.centerLeft, child: Text('Available Amount LKR 1200.00', //<------- I will re-implement these too in a Row once I figure out this style: TextStyle(fontWeight: FontWeight.bold,fontSize: 15), ), ), Container( margin: const EdgeInsets.only(right: 21, top: 15), alignment: Alignment.centerRight, child: Text('Active', style: TextStyle(fontWeight: FontWeight.bold,fontSize: 15), ), ), ], ), ), ), ), ), ), ) ), ```
2020/08/25
[ "https://Stackoverflow.com/questions/63581152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If you want to have multiple predicates for a single WAF rule you must specify the `predicate` block multiple times: ``` resource "aws_wafregional_ipset" "ipset_1" { name = "tfIPSet1" ip_set_descriptor { type = "IPV4" value = "192.0.7.0/24" } } resource "aws_wafregional_ipset" "ipset_2" { name = "tfIPSet2" ip_set_descriptor { type = "IPV4" value = "10.0.0.0/24" } } resource "aws_wafregional_rule" "wafrule" { name = "tfWAFRule" metric_name = "tfWAFRule" predicate { type = "IPMatch" data_id = aws_wafregional_ipset.ipset_1.id negated = false } predicate { type = "IPMatch" data_id = aws_wafregional_ipset.ipset_2.id negated = false } } ``` This would create a single rule that has an allow/deny based on both IP sets specified.
Yes there is, here is an example of a rule with 2 conditions: ``` rule { name = "AllowPath" priority = 1 action { allow {} } statement { and_statement { statement { regex_pattern_set_reference_statement { arn = aws_wafv2_regex_pattern_set.regex_pattern_set_path.arn field_to_match { uri_path {} } text_transformation { priority = 2 type = "NONE" } } } statement { regex_pattern_set_reference_statement { arn = aws_wafv2_regex_pattern_set.regex_pattern_set_example.arn field_to_match { single_header { name = "my_header" } } text_transformation { priority = 2 type = "NONE" } } } } } visibility_config { cloudwatch_metrics_enabled = true metric_name = "AllowPath" sampled_requests_enabled = true } } ``` Basically in this case I'm allowing to access to certain path if has an specific header, but to simplify the example you should follow this structure to have multiple conditions: ``` rule { name = "my_rule" priority = 1 action { allow {} } statement { and_statement { statement { ### STATEMENT 1 } statement { ### STATEMENT 2 } } } } ```
40,848,573
I am trying to select the max timestamped records from table 1 based on some data from table 2. I am getting the correct records based on the where limits I have put on the query, but I am still getting duplicate entries not the max time stamped entries. Any ideas on what is wrong with the query? Basically the ID 901413368 has access to certain leveltypes and I'm trying to find out what the max dated requests were that were put in for that same person for the leveltypes that person manages. ``` SELECT MAX(timestamp) AS maxtime, Leveltype, assign_ID FROM WHERE (leveltype IN (SELECT leveltype FROM dbo.idleveltypes WHERE (id = 901413368))) GROUP BY timestamp, assign_ID, leveltype HAVING (assign_ID = '901413368') ``` UPDATE: The issue has been resolved by WEI\_DBA's response below: ``` Remove the timestamp column from your Group By. Also put the assign_ID in the Where Clause and remove the Having clause ```
2016/11/28
[ "https://Stackoverflow.com/questions/40848573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6114401/" ]
The following may be what you want. It should also be a simpler way to write the query: ``` SELECT MAX(a.timestamp) AS maxtime, a.Leveltype, a.assign_ID FROM dbo.q_Archive a JOIN dbo.idleveltypes lt ON a.leveltype = lt.leveltype AND a.assign_ID = lt.id WHERE assign_ID = 901413368 GROUP BY assign_ID, leveltype; ``` Notes: * Filter on `assign_ID` *before* doing the `group by`. That is much more efficient. * A `JOIN` is the more typical way to represent the relationship between two tables. * The `JOIN` condition should be on all the columns needed for matching; there appear to be two. * I don't understand why the `leveltype` table would have a column called `id`, but this is your data structure. * The `GROUP BY` does not need `timestamp`. * Decide on the type for the id column that should be `901413368`. Is it a number or a string? Only use single quotes for string and date constants.
Remove timestamp from GROUP BY clause due you're getting MAX(timestamp) You shoud not add aggregated fields to GROUP BY clause. ``` SELECT MAX(timestamp) AS maxtime, Leveltype, assign_ID FROM dbo.q_Archive WHERE (leveltype IN (SELECT leveltype FROM dbo.idleveltypes WHERE (id = 901413368))) GROUP assign_ID, leveltype HAVING (assign_ID = '901413368') ```
22,339,345
I don't usually use js, so am hoping for a quick win. Although I can't find the answer on SO in spite of quite a few similar questions out there. I have a form... ``` <input type="text" size="5" id="value1" name="value1" /> <input type="text" size="5" id="value2" name="value2" /> <input type="text" size="5" id="total" readonly="readonly" class="bckground" name="total" /> ``` How can I use ajax (or otherwise) to multiply value1 by value2 after their inputs have been entered, but before the form is submitted? Requirement is to simply display a product of value1 \* value 2 as the form is being filled out. But it would be nice to embed it to the form field, as above, in case I want to add it to my database. Edit: Below is my attempt. But I can only get a span element to update, and not automatically. Also it fails if the fields are blank. ``` <script> function calculateSum() { value1 = parseInt(document.getElementById("value1").value); value2 = parseInt(document.getElementById("value2").value); sum = value1 * value2; document.getElementById("totalpledge").innerHTML = sum; } </script> ``` Seems to work with a button... ``` <input type="text" size="5" id="value1" name="value1" /> <input type="text" size="5" id="value2" name="value2" /> <span id="totalpledge">--</span> <span><button onclick="calculateSum()">Submit!</button></span> ```
2014/03/12
[ "https://Stackoverflow.com/questions/22339345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1901781/" ]
I'd do something like this: HTML ``` <input type="text" size="5" id="value1" name="value1" class="value"/> <input type="text" size="5" id="value2" name="value2" class="value"/> <input type="text" size="5" id="total" readonly="readonly" class="bckground" name="total" /> ``` Just added `class="value"` to the elements so you can easily identify all of the ones that need to contribute to the total. jQuery: ``` jQuery(document).ready(function($) { var $total = $('#total'), $value = $('.value'); $value.on('input', function(e) { var total = 1; $value.each(function(index, elem) { if(!Number.isNaN(parseInt(this.value, 10))) total = total * parseInt(this.value, 10); }); $total.val(total); }); }); ``` That binds an event handler to all of the `.value` elements (all of the elements with `class="value"`) for the `input` event, which fires whenever the value of the input changes. Then it simply iterates through each of the required inputs and multiplies their values together. Finally it puts that total value into the `#total` element. [jsFiddle demo](http://jsfiddle.net/QC6GV/1/)
I'm not sure if this is what you want. HTML part: ``` <form action="some.php" method="POST" id="myForm"> <input type="text" size="5" id="value1" name="value1" /> <input type="text" size="5" id="value2" name="value2" /> <input type="text" size="5" id="total" readonly="readonly" class="bckground" name="total" /> <input type="submit" value="submit" /> </form> ``` jQuery to do the calculation: ``` $("#myForm").submit( function(e) { $("#total").val( parseFloat($("#value1").val()) * parseFloat($("#value2").val()) ); }); ``` And then you could fetch the result by `$_POST['total']` on `some.php`.
22,339,345
I don't usually use js, so am hoping for a quick win. Although I can't find the answer on SO in spite of quite a few similar questions out there. I have a form... ``` <input type="text" size="5" id="value1" name="value1" /> <input type="text" size="5" id="value2" name="value2" /> <input type="text" size="5" id="total" readonly="readonly" class="bckground" name="total" /> ``` How can I use ajax (or otherwise) to multiply value1 by value2 after their inputs have been entered, but before the form is submitted? Requirement is to simply display a product of value1 \* value 2 as the form is being filled out. But it would be nice to embed it to the form field, as above, in case I want to add it to my database. Edit: Below is my attempt. But I can only get a span element to update, and not automatically. Also it fails if the fields are blank. ``` <script> function calculateSum() { value1 = parseInt(document.getElementById("value1").value); value2 = parseInt(document.getElementById("value2").value); sum = value1 * value2; document.getElementById("totalpledge").innerHTML = sum; } </script> ``` Seems to work with a button... ``` <input type="text" size="5" id="value1" name="value1" /> <input type="text" size="5" id="value2" name="value2" /> <span id="totalpledge">--</span> <span><button onclick="calculateSum()">Submit!</button></span> ```
2014/03/12
[ "https://Stackoverflow.com/questions/22339345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1901781/" ]
I'd do something like this: HTML ``` <input type="text" size="5" id="value1" name="value1" class="value"/> <input type="text" size="5" id="value2" name="value2" class="value"/> <input type="text" size="5" id="total" readonly="readonly" class="bckground" name="total" /> ``` Just added `class="value"` to the elements so you can easily identify all of the ones that need to contribute to the total. jQuery: ``` jQuery(document).ready(function($) { var $total = $('#total'), $value = $('.value'); $value.on('input', function(e) { var total = 1; $value.each(function(index, elem) { if(!Number.isNaN(parseInt(this.value, 10))) total = total * parseInt(this.value, 10); }); $total.val(total); }); }); ``` That binds an event handler to all of the `.value` elements (all of the elements with `class="value"`) for the `input` event, which fires whenever the value of the input changes. Then it simply iterates through each of the required inputs and multiplies their values together. Finally it puts that total value into the `#total` element. [jsFiddle demo](http://jsfiddle.net/QC6GV/1/)
``` <!DOCTYPE html> <html> <head> <script> function myFunction() { value1 = parseInt(document.getElementById("value1").value); value2 = parseInt(document.getElementById("value2").value); if(!value1==""&&!value2=="") { sum = value1 * value2; document.getElementById("total").value = sum; } } </script> </head> <body> <form action="some.php" method="POST" id="myForm"> <input type="text" size="5" id="value1" name="value1" onkeyup="myFunction()"/> <input type="text" size="5" id="value2" name="value2" onkeyup="myFunction()"/> <input type="text" size="5" id="total" class="bckground" name="total" /> <input type="submit" value="submit"/> </form> </body> </html> ``` This works please try this
18,615,102
I'm trying to create a listview with onclicklistener, when the user click on an item on list view it will start a new activity.. how can i transfer the file from the listview to another activity? below is my code for updating json data and updating the listview ``` public void updateJSONdata() { mCommentList = new ArrayList<HashMap<String, String>>(); JSONParser jParser = new JSONParser(); JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL); try { mComments = json.getJSONArray(TAG_POSTS); // looping through all posts according to the json object returned for (int i = 0; i < mComments.length(); i++) { JSONObject c = mComments.getJSONObject(i); // gets the content of each tag String title = c.getString(TAG_TITLE); String content = c.getString(TAG_MESSAGE); String username = c.getString(TAG_LNAME); String studnum = c.getString(TAG_USERNAME); // creating new HashMap /**SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(BsitLoungeActivity.this); String fname = sp.getString("firstname","anon"); String lname = sp.getString("lasstname","anon");**/ HashMap<String, String> map = new HashMap<String, String>(); map.put(TAG_TITLE, title); map.put(TAG_MESSAGE, content); map.put(TAG_LNAME, username); map.put(TAG_USERNAME, "ID:"+studnum); // adding HashList to ArrayList mCommentList.add(map); // annndddd, our JSON data is up to date same with our array // listw } } catch (JSONException e) { e.printStackTrace(); } } private void updateList() { ListAdapter adapter = new SimpleAdapter(this, mCommentList, R.layout.single_post, new String[] { TAG_TITLE, TAG_MESSAGE, TAG_LNAME,TAG_USERNAME}, new int[] { R.id.title, R.id.message, R.id.username,R.id.username2 }); ListView lv = getListView(); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // This method is triggered if an item is click within our // list. For our example we won't be using this, but // it is useful to know in real life applications. } }); } ``` Can I use the data inserted in the hashmap? and how? please help me anyone
2013/09/04
[ "https://Stackoverflow.com/questions/18615102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2665158/" ]
You didn't uncomment your SMTP server. Take the semi-colons out of the SMTP and port lines in your php.ini.
I think you should use `jackylonelyboy@gmail.com` instead `jackylonelyboy+gmail.com` as user name for the authentication.
17,759,103
i need to stop loading my iframe page after 5000 ms i'm use these but it's refresh the iframe every 5000 ms later what the problem . pleas fix it pleas. thanks ``` <iframe id="iframe1" src="" width="920" height="900" border="2"></iframe> <script type="text/javascript"> function setIframeSrc() { var s = "http://lx5.in/CGIT-Results-p2-2013.php"; var iframe1 = document.getElementById('iframe1'); if ( -1 == navigator.userAgent.indexOf("MSIE") ) { iframe1.src = s; setTimeout(setIframeSrc, 5000); } else { iframe1.location = s; setTimeout(setIframeSrc, 5000); } } setTimeout(setIframeSrc, 5000); </script> ```
2013/07/20
[ "https://Stackoverflow.com/questions/17759103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598511/" ]
To stop iframe loading you can use the following code based on [this answer](https://stackoverflow.com/questions/8943219/how-to-stop-page-load-in-html-static-page#10415265): ``` function setIframeSrc() { var s = "http://lx5.in/CGIT-Results-p2-2013.php"; var iframe1 = document.getElementById('iframe1'); iframe1.src = s; setTimeout(function(){ if (window.stop) { window.stop(); } else { document.execCommand('Stop'); // MSIE } }, 5000); } setTimeout(setIframeSrc, 5000); ``` [jsfiddle](http://jsfiddle.net/Tsmqn/7/) / [jsfiddle/show](http://jsfiddle.net/Tsmqn/7/show)
I would suggest rethinking the idea. IMO it should be the server that displays timeout information and not the client using some JavaScript timeouts. Explanation below. Your code just says: refresh the iframe every 5 seconds. You cannot stop iframe request execution. You can change iframe's src location or remove it from the DOM tree. But the request that is started is unstoppable once it reaches the server. So: ``` <iframe id="iframe1" src="{url to query}" ...> ``` and in the script: ``` function displayTimeout() { (...) var p = iframe1.parentNode; p.removeChild(iframe1); var div = document.createElement("div"); var text = document.createTextNode("Timeout loading iframe"); div.appendChild(text); p.appendChild(div); } setTimeout(displayTimeout,5000); ``` But this solution **has serious drawbacks** - in order not to display timeout when iframe manages to load in time you should cancel the timeout. But how to do that? If you want to do it from iframe - see [iframe accessing parent DOM?](https://stackoverflow.com/questions/2620755/iframe-accessing-parent-dom) If from parent element - see [jQuery/JavaScript: accessing contents of an iframe](https://stackoverflow.com/questions/364952/jquery-javascript-accessing-contents-of-an-iframe) The further you go, the more problems and the more complicated the solution becomes. So I would suggest abandoning it.
37,774,053
I have a d3 visualisation that works fine with the current stable release (`3.x`) however I wanted to implement the [Pan & Zoom](http://bl.ocks.org/mbostock/2a39a768b1d4bc00a09650edef75ad39) function so I upgraded to `4.alpha`. This threw a lot of bugs as the syntax has changed. I updated the variable names, however there is one remaining bug pertaining to the second line of the following code: ``` function type(d) { d.date = formatDate.parse(d.date); d.Flux = +d.Flux; return d; } ``` Opening up the page source via the browser, I see that `formatDate.parse is not a function.` The visualisation is currently not rendering. I have tried combing the D3 `4.alpha` [documentation](https://github.com/d3/d3), to no avail. Further up in the code, `formatDate` is defined as follows: ``` var formatDate = d3.timeFormat("%d-%b-%y"); ``` I am happy to post the original code, its about 70 lines long, and a bit hacky tho: --- ``` var margin = {top: 20, right: 20, bottom: 30, left: 50}, width = 1400// - margin.left - margin.right, height = 1400// - margin.top - margin.bottom; var formatDate = d3.timeFormat("%d-%b-%y"); var x = d3.scaleLinear() .range([0, width]); var y = d3.scaleLinear() .range([height, 0]); var line = d3.line() .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.Flux); }); var svg = d3.selectAll("#ExoPlanet, #ExoPlanet2").append("svg") .attr("width", '90%') .attr("height", '70%') .attr('viewBox','0 0 '+Math.min(width,height)+' '+Math.min(width,height)) .attr('preserveAspectRatio','xMinYMin') .append("g") .call(d3.zoom() .scaleExtent([1 / 2, 4]) .on("zoom", zoomed)) ; function zoomed() { var transform = d3.event.transform; circle.attr("transform", function(d) { return "translate(" + transform.applyX(d[0]) + "," + transform.applyY(d[1]) + ")"; }); } d3.tsv("/FluxTime.tsv", type, function(error, data) { if (error) throw error; x.domain(d3.extent(data, function(d) { return d.date; })); y.domain(d3.extent(data, function(d) { return d.Flux; })); svg.selectAll("dot") .data(data) .enter().append("circle") .attr("r", 2.0) .attr("cx", function(d) { return x(d.date); }) .attr("cy", function(d) { return y(d.Flux); }) .attr("stroke", "#CE9A76"); }); function type(d) { d.date = formatDate.parse(d.date)); d.Flux = +d.Flux; return d; ``` } A screenshot of the first 8 entries in the dataset: [![datums](https://i.stack.imgur.com/HnKBY.png)](https://i.stack.imgur.com/HnKBY.png)
2016/06/12
[ "https://Stackoverflow.com/questions/37774053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4611375/" ]
In D3 3.5, you could parse just the way you did, setting the time format... ``` var formatDate = d3.time.format("%d-%b-%y"); ``` ...and then using this time format to parse: ``` d.date = formatDate.parse(d.date); ``` But, using D3 4.0, you have to parse dates in a different way, using `timeParse`: ``` var parseTime = d3.timeParse("%d-%b-%y"); ``` And, then, modifying your accessor function: ``` function type(d) { d.date = parseTime(d.date); d.Flux = +d.Flux; return d; } ```
The api has changed. For me the solution was: ``` var parseTime = d3.timeParse("%Y-%m") parseTime("2018-09") => Sat Sep 01 2018 00:00:00 GMT-0400 (Eastern Daylight Time) ``` If you want to go the other way, Date class to string: ``` var formatTime = d3.timeFormat("%Y-%m") formatTime(new Date) => "2020-09" ```
56,138,697
To summarize, I am submitting a POST request VIA axios and I am having the hardest time figuring out why it will not re-render my component that is displaying the newly added data (Where all of this is taking place). Here is my post request (data is persisting correctly): ``` addNewLoad = (pickup_date, pickup_location, rate, delivery_date, delivery_location, loaded_miles, deadhead_miles, local, delivery_id) => { let config = { headers: { 'Content-Type': 'application/json; charset=utf-8', "Accepts": "application/json", } } const instance = axios.create({baseURL: 'http://localhost:3001'}) instance.post('/api/v1/pickup_deliveries', { pickup_date, pickup_location, rate, delivery_date, delivery_location, loaded_miles, deadhead_miles, local, delivery_id}, config) .then(response => { console.log(response) const pickup_deliveries = [ ...this.state.pickup_deliveries, response.data ] this.setState({pickup_deliveries}) }) .catch(error => { console.log(error) }) } ``` Here is my component's state: ``` state = { fiveDayView: [new Date(), addDays(new Date(), 1), addDays(new Date(), 2), addDays(new Date(), 3), addDays(new Date(), 4)], routeId: '', show: false, pickup_deliveries: [], } ``` So.. when I `this.setState({pickup_deliveries})`, I would expect my component to re-render. Not only that but within this component, I am currently pulling all the data from my Rails API and using said data to display within that component. I figured between the `this.setState({pickup_deliveries})` and the re-rendering of the parent component where this data is coming from as `this.props.apiData`, there would be no issue with my component re-rendering and displaying the newly submitted data. Sorry if that is confusing but I am at a loss here.
2019/05/14
[ "https://Stackoverflow.com/questions/56138697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10719868/" ]
**First** of all is to check that you are not getting an empty array from the API, (check network tab). In that case you are not actually changing the array, but running a setState with the same value... setState doesn't re-render if there was no state change detected **Second** important thing when you update a state and use old value of the state you shouldn't access this.state, your code should look smth like this: ``` this.setState((prevState) => ({ pickup_deliveries: [...prevState.pickup_deliveries, response.data]); ``` Because state updates are async so you should never depend on this.state while updating state, as you might get an older state than the one you want to update. More on this topic <https://reactjs.org/docs/state-and-lifecycle.html> Quoting: > > **State Updates May Be Asynchronous** > > > React may batch multiple setState() calls into a single update for performance. > > > Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state. > > > **Third** (**workaround**) to keep in mind in general is a workaround by add a parameter like 'lastRequestTimestamp' to the state to force state changes, specially when you are dealing with updating arrays or objects in state, this workaround is just to prove to yourself you are mutating the array which is not a state change as the array reference is still the same, **but you shouldn't use this workaround except for debugging...**
Change ``` this.setState({ pickup_deliveries }); ``` to ``` this.setState(() => ({ pickup_deliveries })); ``` for callback based `setState`.
64,724,194
I made a table with a dropdown menu that will filter the data shown. It loads correctly and I can toggle the individual teams but when I try to select All Teams (index 0) again I get an error saying property 'name' is undefined. What is wrong and how do I fix it? ``` import React, { useState } from "react"; import "./styles.css"; import { flavours } from "./mock-data"; export default function App() { const [selectedFilter, setFilter] = useState(0); // start table const header = [ { title: "Banana" }, { title: "Chocolate" }, { title: "Vanilla" }, { title: "Total" } ]; // render Table Headers const renderTableHeader = () => header.map((e, index) => { const { title } = e; return ( <th key={Number(index)}> {title} </th> ); }); const renderAllTeamData = () => flavours.map((team) => { const { name, banana, chocolate, vanilla } = team; // destructuring return ( <tr key={team.name}> <th style={{ textAlign: "start" }} > {name} </th> <td>{banana.length}</td> <td>{chocolate}</td> <td>{vanilla}</td> <td> {banana.length + chocolate + vanilla} </td> </tr> ); }); const renderTeamData = () => { const { name, banana, chocolate, vanilla } = flavours[selectedFilter - 1]; // destructuring return ( <tr> <th style={{ textAlign: "start" }}> {name} </th> <td>{banana.length}</td> <td>{chocolate}</td> <td>{vanilla}</td> <td>{banana.length + chocolate + vanilla}</td> </tr> ); }; return ( <div className="App"> <form> <select value={selectedFilter} onChange={(e) => setFilter(e.currentTarget.value)} > <option value={0}>All Teams</option> {flavours.map((value, index) => ( <option key={value.name} value={index + 1}> {value.name} </option> ))} </select> </form> <table> <thead> <tr> <th> </th> {renderTableHeader()} </tr> </thead> <tbody> {selectedFilter === 0 ? renderAllTeamData() : renderTeamData()} </tbody> </table> </div> ); } ``` Here is a code sandbox too <https://codesandbox.io/s/nice-brattain-pwnbr?file=/src/App.js>
2020/11/07
[ "https://Stackoverflow.com/questions/64724194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14069689/" ]
The problem is here ``` {selectedFilter === 0 ? renderAllTeamData() : renderTeamData()} ``` Here you are using === which is comparing against value and type but you set the currentTarget.value which is a string, so the comparison fails and moved to the else part ``` <select value={selectedFilter} onChange={(e) => setFilter(e.currentTarget.value)} > ``` You can fix by changing it to compare by value like below ``` {selectedFilter == 0 ? renderAllTeamData() : renderTeamData()} ```
You need to parse `e.currentTarget.value` to Int. replace that line with : `onChange={(e) => setFilter(parseInt(e.currentTarget.value, 10))}` and it should work fine.
64,724,194
I made a table with a dropdown menu that will filter the data shown. It loads correctly and I can toggle the individual teams but when I try to select All Teams (index 0) again I get an error saying property 'name' is undefined. What is wrong and how do I fix it? ``` import React, { useState } from "react"; import "./styles.css"; import { flavours } from "./mock-data"; export default function App() { const [selectedFilter, setFilter] = useState(0); // start table const header = [ { title: "Banana" }, { title: "Chocolate" }, { title: "Vanilla" }, { title: "Total" } ]; // render Table Headers const renderTableHeader = () => header.map((e, index) => { const { title } = e; return ( <th key={Number(index)}> {title} </th> ); }); const renderAllTeamData = () => flavours.map((team) => { const { name, banana, chocolate, vanilla } = team; // destructuring return ( <tr key={team.name}> <th style={{ textAlign: "start" }} > {name} </th> <td>{banana.length}</td> <td>{chocolate}</td> <td>{vanilla}</td> <td> {banana.length + chocolate + vanilla} </td> </tr> ); }); const renderTeamData = () => { const { name, banana, chocolate, vanilla } = flavours[selectedFilter - 1]; // destructuring return ( <tr> <th style={{ textAlign: "start" }}> {name} </th> <td>{banana.length}</td> <td>{chocolate}</td> <td>{vanilla}</td> <td>{banana.length + chocolate + vanilla}</td> </tr> ); }; return ( <div className="App"> <form> <select value={selectedFilter} onChange={(e) => setFilter(e.currentTarget.value)} > <option value={0}>All Teams</option> {flavours.map((value, index) => ( <option key={value.name} value={index + 1}> {value.name} </option> ))} </select> </form> <table> <thead> <tr> <th> </th> {renderTableHeader()} </tr> </thead> <tbody> {selectedFilter === 0 ? renderAllTeamData() : renderTeamData()} </tbody> </table> </div> ); } ``` Here is a code sandbox too <https://codesandbox.io/s/nice-brattain-pwnbr?file=/src/App.js>
2020/11/07
[ "https://Stackoverflow.com/questions/64724194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14069689/" ]
The problem is here ``` {selectedFilter === 0 ? renderAllTeamData() : renderTeamData()} ``` Here you are using === which is comparing against value and type but you set the currentTarget.value which is a string, so the comparison fails and moved to the else part ``` <select value={selectedFilter} onChange={(e) => setFilter(e.currentTarget.value)} > ``` You can fix by changing it to compare by value like below ``` {selectedFilter == 0 ? renderAllTeamData() : renderTeamData()} ```
change the onchange function of your select ``` <select value={selectedFilter} onChange={(e) => { setFilter(+e.currentTarget.value); }} > <option value={0}>All Teams</option> {flavours.map((value, index) => ( <option key={value.name} value={index + 1}> {value.name} </option> ))} </select> ``` or change tbody like this ``` <tbody> {selectedFilter == 0 ? renderAllTeamData() : renderTeamData()} </tbody> ``` the problem in current scenario is the value u set is integer or number but value u select come as string
64,724,194
I made a table with a dropdown menu that will filter the data shown. It loads correctly and I can toggle the individual teams but when I try to select All Teams (index 0) again I get an error saying property 'name' is undefined. What is wrong and how do I fix it? ``` import React, { useState } from "react"; import "./styles.css"; import { flavours } from "./mock-data"; export default function App() { const [selectedFilter, setFilter] = useState(0); // start table const header = [ { title: "Banana" }, { title: "Chocolate" }, { title: "Vanilla" }, { title: "Total" } ]; // render Table Headers const renderTableHeader = () => header.map((e, index) => { const { title } = e; return ( <th key={Number(index)}> {title} </th> ); }); const renderAllTeamData = () => flavours.map((team) => { const { name, banana, chocolate, vanilla } = team; // destructuring return ( <tr key={team.name}> <th style={{ textAlign: "start" }} > {name} </th> <td>{banana.length}</td> <td>{chocolate}</td> <td>{vanilla}</td> <td> {banana.length + chocolate + vanilla} </td> </tr> ); }); const renderTeamData = () => { const { name, banana, chocolate, vanilla } = flavours[selectedFilter - 1]; // destructuring return ( <tr> <th style={{ textAlign: "start" }}> {name} </th> <td>{banana.length}</td> <td>{chocolate}</td> <td>{vanilla}</td> <td>{banana.length + chocolate + vanilla}</td> </tr> ); }; return ( <div className="App"> <form> <select value={selectedFilter} onChange={(e) => setFilter(e.currentTarget.value)} > <option value={0}>All Teams</option> {flavours.map((value, index) => ( <option key={value.name} value={index + 1}> {value.name} </option> ))} </select> </form> <table> <thead> <tr> <th> </th> {renderTableHeader()} </tr> </thead> <tbody> {selectedFilter === 0 ? renderAllTeamData() : renderTeamData()} </tbody> </table> </div> ); } ``` Here is a code sandbox too <https://codesandbox.io/s/nice-brattain-pwnbr?file=/src/App.js>
2020/11/07
[ "https://Stackoverflow.com/questions/64724194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14069689/" ]
The problem is here ``` {selectedFilter === 0 ? renderAllTeamData() : renderTeamData()} ``` Here you are using === which is comparing against value and type but you set the currentTarget.value which is a string, so the comparison fails and moved to the else part ``` <select value={selectedFilter} onChange={(e) => setFilter(e.currentTarget.value)} > ``` You can fix by changing it to compare by value like below ``` {selectedFilter == 0 ? renderAllTeamData() : renderTeamData()} ```
Convert the filter value to a number before setting it to state. `setFilter(+e.currentTarget.value)` ``` const [selectedFilter, setFilter] = useState(0); <form> <select value={selectedFilter} onChange={(e) => setFilter(+e.currentTarget.value)} > <option value={0}>All Teams</option> {flavours.map((value, index) => ( <option key={value.name} value={index + 1}> {value.name} </option> ))} </select> </form> ```
54,033,545
I have created a rubric that has cells that change color when "xx" is added to the cell. Rather than type into each individual cell when assessing my students I wanted to have the xx's get added to the cell from clicking ion the cell. That's when I started searching around and started to investigate scripts. I added 2 drawings to each cell so I could click on one image to add the "xx" and click on the other image to delete the "xx" (if I changed their assessment rating). I have played with them today and found success in the first cell, but every other cell that I try to assign a script to says that the script can't be found. When I "run" the script from the script file, it shows up on my sheet, but not when I click on the cell like I want. Here is a section of my code for the first row of the rubric (I have 15 rows with different titles-Verbal Communication, Authority, etc.): Top row of rubric pre-click =========================== [![Top row of rubric pre-click](https://i.stack.imgur.com/dEWwp.png)](https://i.stack.imgur.com/dEWwp.png) Top row of rubric post-click ============================ [![Top row of rubric post-click2]](https://i.stack.imgur.com/Est41.png) ``` function verbalcommunication4() { ss=SpreadsheetApp.getActiveSpreadsheet() s=ss.getActiveSheet() var currVal=s.getRange("D5").getValue() var plusVal= currVal +" xx" s.getRange("D5") .setValue(plusVal) } function verbalcommunication4clear() { ss=SpreadsheetApp.getActiveSpreadsheet() s=ss.getActiveSheet() var currVal=s.getRange("D5").getValue() var text =s.getRange("D5").getValue().replace(" xx",""); s.getRange("D5").setValue(text); } function verbalcommunication3() { ss=SpreadsheetApp.getActiveSpreadsheet() s=ss.getActiveSheet() var currVal=s.getRange("E5").getValue() var plusVal= currVal +" xx" s.getRange("E5") .setValue(plusVal) } function verbalcommunication3clear() { ss=SpreadsheetApp.getActiveSpreadsheet() s=ss.getActiveSheet() var currVal=s.getRange("E5").getValue() var text =s.getRange("E5").getValue().replace(" xx",""); s.getRange("E5").setValue(text); } function verbalcommunication2() { ss=SpreadsheetApp.getActiveSpreadsheet() s=ss.getActiveSheet() var currVal=s.getRange("F5").getValue() var plusVal= currVal +" xx" s.getRange("F5") .setValue(plusVal) } function verbalcommunication2clear() { ss=SpreadsheetApp.getActiveSpreadsheet() s=ss.getActiveSheet() var currVal=s.getRange("F5").getValue() var text =s.getRange("F5").getValue().replace(" xx",""); s.getRange("F5").setValue(text); } function verbalcommunication1() { ss=SpreadsheetApp.getActiveSpreadsheet() s=ss.getActiveSheet() var currVal=s.getRange("G5").getValue() var plusVal= currVal +" xx" s.getRange("G5") .setValue(plusVal) } function verbalcommunication1clear() { ss=SpreadsheetApp.getActiveSpreadsheet() s=ss.getActiveSheet() var currVal=s.getRange("G5").getValue() var text =s.getRange("G5").getValue().replace(" xx",""); s.getRange("G5").setValue(text); } ``` verbalcommunication4 and verbalcomunication4clear work just fine. Every other script I try to attach to the drawings in the other cells attach with no error, but when I click on the object to run the script I get the error message "script function 'script name' could not be found." Like I said, when I run the script from the script project page the desired result (xx in the appropriate cell) appears, just not when I click on the cell's drawing like I want. Top row after script is "run" from project page =============================================== [![Top row after script is "run" from project page](https://i.stack.imgur.com/lrKBC.png)](https://i.stack.imgur.com/lrKBC.png) Top row after cell E5's drawing is clicked ========================================== [![Top row after cell E5's drawing is clicked](https://i.stack.imgur.com/GJEV2.png)](https://i.stack.imgur.com/GJEV2.png) I'm new to this so any help would be appreciated. Thanks!
2019/01/04
[ "https://Stackoverflow.com/questions/54033545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10865816/" ]
`has $!hl` declares a private attribute. `has $.hl` declares a public attribute. By public I mean it creates a method of the same name that returns it, and it adds it to the `BUILD`/`gist`/`perl`/`Capture` [sub]methods. ```perl6 class A { has &.hl; } ``` This is effectively the same as: ```perl6 class A { has &!hl; submethod BUILD ( :&!hl ){} method hl (){ &!hl } # return the code object method perl (){ "A.new(hl => $!hl.perl())" } method gist (){ self.perl } method Capture () { \( :&!hl ) } } ``` So when you call `A.hl` it returns the code object that is stored in `&!hl`. --- You can deal with this in a few ways. 1. Just call it “twice”. ```perl6 $a.hl()(42) $a.hl().(42) $a.hl.(42) ``` 2. Have an additional method that uses it. ```perl6 method call-it ( |C ){ &!hl( |C ) } ``` ```perl6 $a.call-it( 42 ) my &hl = $a.hl; ``` Note that I used `|C` to avoid dealing with signatures entirely. It might make sense for you to have a signature and deal with it like you have. 3. Override the automatically generated method by adding it yourself. ```perl6 method hl ( |C ){ &!hl( |C ) } ``` ```perl6 $a.hl( 42 ) ``` By overriding it, all of the other changes that making it a public attribute are still done for you. So there will be no need to create a `BUILD` submethod. --- When you override it, that means that `is rw` has no effect. It also means that there is no way for outside code to retrieve the code object itself. There are ways to deal with that if you need to. If you don't ever need to return the value in `&!hl` then just leave it like it is above. 1. If the code object is never called with zero positional arguments. ```perl6 multi method hl (){ &!hl } multi method hl ( |C ){ &!hl( |C ) } ``` ```perl6 $a.hl; # returns the value in $!hl $a.hl(); # returns the value in $!hl $a.hl( 42 ); # calls &!hl(42) ``` Note that there is no way for a method to differentiate between `.hl` and `.hl()`. 2. You could also use a named argument. ```perl6 multi method hl ( :code($)! ){ &!hl } multi method hl ( |C ){ &hl( |C ) } ``` ```perl6 $a.hl(:code); # returns the value in &!hl $a.hl; # calls &!hl() $a.hl(); # calls &!hl() $a.hl( 42 ); # calls &!hl(42) ``` 3. You could do nothing to make it easier to get the code object, and just have them use subsignature parsing to get the attribute. (This is why the `Capture` method gets created for you) ```perl6 class A { has &.hl; method hl ( |C ){ &!hl( |C ) } } ``` ```perl6 sub get-hl ( A $ ( :&hl ) ){ &hl } my &hl = get-hl($a); my &hl = -> A $ ( :&hl ){ &hl }( $a ); my &hl = $a.Capture{'hl'}; ```
The problem is that the accessor returns the attribute, that happens to be a `Callable`. Only *then* do you want to call the return value of the accessor with parameters. This is essentially what you're doing by creating your own accessor. You don't have to actually create your own accessor. Just add a extra parentheses (indicating you're calling the accessor without any extra arguments), and then the parentheses for the values you actually want to pass: ``` class A { has &.a = *.say; # quick way to make a Callable: { .say } } A.new.a()(42); # 42 ``` Or if you don't like parentheses so much, consider the method invocation syntax, as timotimo pointed out: ``` A.new.a.(42); # 42 ```
54,033,545
I have created a rubric that has cells that change color when "xx" is added to the cell. Rather than type into each individual cell when assessing my students I wanted to have the xx's get added to the cell from clicking ion the cell. That's when I started searching around and started to investigate scripts. I added 2 drawings to each cell so I could click on one image to add the "xx" and click on the other image to delete the "xx" (if I changed their assessment rating). I have played with them today and found success in the first cell, but every other cell that I try to assign a script to says that the script can't be found. When I "run" the script from the script file, it shows up on my sheet, but not when I click on the cell like I want. Here is a section of my code for the first row of the rubric (I have 15 rows with different titles-Verbal Communication, Authority, etc.): Top row of rubric pre-click =========================== [![Top row of rubric pre-click](https://i.stack.imgur.com/dEWwp.png)](https://i.stack.imgur.com/dEWwp.png) Top row of rubric post-click ============================ [![Top row of rubric post-click2]](https://i.stack.imgur.com/Est41.png) ``` function verbalcommunication4() { ss=SpreadsheetApp.getActiveSpreadsheet() s=ss.getActiveSheet() var currVal=s.getRange("D5").getValue() var plusVal= currVal +" xx" s.getRange("D5") .setValue(plusVal) } function verbalcommunication4clear() { ss=SpreadsheetApp.getActiveSpreadsheet() s=ss.getActiveSheet() var currVal=s.getRange("D5").getValue() var text =s.getRange("D5").getValue().replace(" xx",""); s.getRange("D5").setValue(text); } function verbalcommunication3() { ss=SpreadsheetApp.getActiveSpreadsheet() s=ss.getActiveSheet() var currVal=s.getRange("E5").getValue() var plusVal= currVal +" xx" s.getRange("E5") .setValue(plusVal) } function verbalcommunication3clear() { ss=SpreadsheetApp.getActiveSpreadsheet() s=ss.getActiveSheet() var currVal=s.getRange("E5").getValue() var text =s.getRange("E5").getValue().replace(" xx",""); s.getRange("E5").setValue(text); } function verbalcommunication2() { ss=SpreadsheetApp.getActiveSpreadsheet() s=ss.getActiveSheet() var currVal=s.getRange("F5").getValue() var plusVal= currVal +" xx" s.getRange("F5") .setValue(plusVal) } function verbalcommunication2clear() { ss=SpreadsheetApp.getActiveSpreadsheet() s=ss.getActiveSheet() var currVal=s.getRange("F5").getValue() var text =s.getRange("F5").getValue().replace(" xx",""); s.getRange("F5").setValue(text); } function verbalcommunication1() { ss=SpreadsheetApp.getActiveSpreadsheet() s=ss.getActiveSheet() var currVal=s.getRange("G5").getValue() var plusVal= currVal +" xx" s.getRange("G5") .setValue(plusVal) } function verbalcommunication1clear() { ss=SpreadsheetApp.getActiveSpreadsheet() s=ss.getActiveSheet() var currVal=s.getRange("G5").getValue() var text =s.getRange("G5").getValue().replace(" xx",""); s.getRange("G5").setValue(text); } ``` verbalcommunication4 and verbalcomunication4clear work just fine. Every other script I try to attach to the drawings in the other cells attach with no error, but when I click on the object to run the script I get the error message "script function 'script name' could not be found." Like I said, when I run the script from the script project page the desired result (xx in the appropriate cell) appears, just not when I click on the cell's drawing like I want. Top row after script is "run" from project page =============================================== [![Top row after script is "run" from project page](https://i.stack.imgur.com/lrKBC.png)](https://i.stack.imgur.com/lrKBC.png) Top row after cell E5's drawing is clicked ========================================== [![Top row after cell E5's drawing is clicked](https://i.stack.imgur.com/GJEV2.png)](https://i.stack.imgur.com/GJEV2.png) I'm new to this so any help would be appreciated. Thanks!
2019/01/04
[ "https://Stackoverflow.com/questions/54033545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10865816/" ]
`has $!hl` declares a private attribute. `has $.hl` declares a public attribute. By public I mean it creates a method of the same name that returns it, and it adds it to the `BUILD`/`gist`/`perl`/`Capture` [sub]methods. ```perl6 class A { has &.hl; } ``` This is effectively the same as: ```perl6 class A { has &!hl; submethod BUILD ( :&!hl ){} method hl (){ &!hl } # return the code object method perl (){ "A.new(hl => $!hl.perl())" } method gist (){ self.perl } method Capture () { \( :&!hl ) } } ``` So when you call `A.hl` it returns the code object that is stored in `&!hl`. --- You can deal with this in a few ways. 1. Just call it “twice”. ```perl6 $a.hl()(42) $a.hl().(42) $a.hl.(42) ``` 2. Have an additional method that uses it. ```perl6 method call-it ( |C ){ &!hl( |C ) } ``` ```perl6 $a.call-it( 42 ) my &hl = $a.hl; ``` Note that I used `|C` to avoid dealing with signatures entirely. It might make sense for you to have a signature and deal with it like you have. 3. Override the automatically generated method by adding it yourself. ```perl6 method hl ( |C ){ &!hl( |C ) } ``` ```perl6 $a.hl( 42 ) ``` By overriding it, all of the other changes that making it a public attribute are still done for you. So there will be no need to create a `BUILD` submethod. --- When you override it, that means that `is rw` has no effect. It also means that there is no way for outside code to retrieve the code object itself. There are ways to deal with that if you need to. If you don't ever need to return the value in `&!hl` then just leave it like it is above. 1. If the code object is never called with zero positional arguments. ```perl6 multi method hl (){ &!hl } multi method hl ( |C ){ &!hl( |C ) } ``` ```perl6 $a.hl; # returns the value in $!hl $a.hl(); # returns the value in $!hl $a.hl( 42 ); # calls &!hl(42) ``` Note that there is no way for a method to differentiate between `.hl` and `.hl()`. 2. You could also use a named argument. ```perl6 multi method hl ( :code($)! ){ &!hl } multi method hl ( |C ){ &hl( |C ) } ``` ```perl6 $a.hl(:code); # returns the value in &!hl $a.hl; # calls &!hl() $a.hl(); # calls &!hl() $a.hl( 42 ); # calls &!hl(42) ``` 3. You could do nothing to make it easier to get the code object, and just have them use subsignature parsing to get the attribute. (This is why the `Capture` method gets created for you) ```perl6 class A { has &.hl; method hl ( |C ){ &!hl( |C ) } } ``` ```perl6 sub get-hl ( A $ ( :&hl ) ){ &hl } my &hl = get-hl($a); my &hl = -> A $ ( :&hl ){ &hl }( $a ); my &hl = $a.Capture{'hl'}; ```
**TL;DR** There is no way to directly access an attribute outside the source code of the class in which it is declared. The only way to provide access is via a separate public accessor method. This answer hopefully clears up confusion about this. Other answers lay out your options. Why you get a `Too many positionals passed;` error message ========================================================== The code `has &!hl;` *declares* an *attribute*, `&!hl`. The code `has &.hl;` does the same but *also* generates a *method*, `.hl` that's a *public accessor* to the attribute with the same name. Like all such generated accessors, it expects a single argument, the invocant, and no others. ``` my $second = $a.hl( $statement ) ``` This code *calls* the *method* `hl`. Raku passes the value on the left of the dot (`$a`) as a first argument -- the invocant. But you've also added a `$statement` argument. So it passes that too. Hence the error message: ``` Too many positionals passed; expected 1 argument but got 2 ``` > > When `hl` is accessed inside the class, no invocant is added > > > It's not because it's accessed inside the class. It's because you don't call it as a method: ``` method process-it( Str $s --> Str ) { &!hl( $s ) } ``` The `&!hl( $s )` code is a *sub* style call of the routine held in the `&!hl` attribute. It gets *one* argument, `$s`. > > Is there another way to create a public object code variable that does not automagically add the invocant as a variable to the code? > > > The problem is not that Raku is automagically adding an invocant. > > Other than creating a separate accessor method. > > > There is no way to directly access an attribute outside the source code of the class in which it is declared. The only way to provide access is via a separate public accessor method. This answer hopefully clears up confusion about this. Other answers lay out your options.
53,889,488
I am trying to use jquery to aggregate all of the text in each anchor tag into a single message. If it was working correctly, I would see an alert with this content: > > high\_cases::pool\_config::indy\_pool\_config\_request\_works\_for\_disabling\_writing > high\_cases::pool\_restart::indy\_pool\_restart\_request\_works\_for\_start\_cancel\_works > > > I am currently seeing this error in the browser console: > > Uncaught TypeError: Reduce of empty array with no initial value > at Array.reduce () > at copyAllTestNamesToClipboard > > > I do not have my jquery selector correct. What is the correct syntax? ``` <html> <head> <script> function copyAllTestNamesToClipboard() { var array = new Array(); $('div','a').each(function(){ array.push($(this).html()); }); var message = array.reduce(function(pre, next) { return pre + '\n' + next; }); alert(message); } </script> </head> <body> <div class="panel-heading"> <h4 class="panel-title"> <button type="button" class="btn btn-link bnt-sm" onclick="copyAllTestNamesToClipboard()">(Copy)</button> </h4> </div> <div id="error_group_collapse" class="panel-collapse collapse in"> <div class="panel-body"> <div class="panel-body-header"> <a data-toggle="collapse" href="#t189_error_group_collapse">high_cases::pool_config::indy_pool_config_request_works_for_disabling_writing</a> </div> <div class="panel panel-info"> <div id="t189_error_group_collapse" class="panel-collapse collapse in"> <!-- other stuff --> </div> </div> <div class="panel-body-header"> <a data-toggle="collapse" href="#t192_error_group_collapse">high_cases::pool_restart::indy_pool_restart_request_works_for_start_cancel_works</a> </div> </div> </div> </body> ``` Also for note, I did not want to just select all anchor tags in the DOM as there could be additional anchor tags I do not want. I only want the anchor tags in the div with `id="error_group_collapse"`. Thnx for the help.
2018/12/21
[ "https://Stackoverflow.com/questions/53889488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10012683/" ]
Currently you use `$('div','a')` which says 'give me *all* `div` and *all* `anchor` elements. As pointed out in @RoryMcCrossan's comment below: > > The selector `$('div', 'a')` is looking for `div` elements which are children of an `a` element. It only selects those `div`, not both types of element. > > > You need to concatenate the element names in one string, to order the selector to give you all the anchor elements *in* the div element, and use the 'hash' selector (`#`) for an element with an id. If you really want `id="error_group_collapse"` to be the only element to fetch the anchor elements from, this is how you change it: `$('#error_group_collapse a')`. (Note that I replaced your alert with the `console.log` command for demonstration purposes, of course you can just use your alert) ```js function copyAllTestNamesToClipboard() { var array = new Array(); $('#error_group_collapse a').each(function() { array.push($(this).html()); }); var message = array.reduce(function(pre, next) { return pre + '\n' + next; }); console.log(message); } ``` ```html <div class="panel-heading"> <h4 class="panel-title"> <button type="button" class="btn btn-link bnt-sm" onclick="copyAllTestNamesToClipboard()">(Copy)</button> </h4> </div> <div id="error_group_collapse" class="panel-collapse collapse in"> <div class="panel-body"> <div class="panel-body-header"> <a data-toggle="collapse" href="#t189_error_group_collapse">high_cases::pool_config::indy_pool_config_request_works_for_disabling_writing</a> </div> <div class="panel panel-info"> <div id="t189_error_group_collapse" class="panel-collapse collapse in"> <!-- other stuff --> </div> </div> <div class="panel-body-header"> <a data-toggle="collapse" href="#t192_error_group_collapse">high_cases::pool_restart::indy_pool_restart_request_works_for_start_cancel_works</a> </div> </div> </div> ```
You forgot to set the initial value in reduce ``` var message = array.reduce(function(pre, next) { return pre + '\n' + next; }, ''); // <-- forgot that ``` But I am not sure why you are using reduce. Just use join. ``` var message = array.join('\n') ``` And you selector is wrong. It is looking for all the divs inside of the anchors. You probably want: `$('div a')` The jQuery way would be map() and get() and join() ``` $('div a') .map(function () { return $(this).html(); }) .get() .join('\n') ```
13,609,924
I'm currently working on a project where the user defines some parameters in a NSDictionnary, that I'm using to setup some objects. For example, you can ask to create a Sound object with parameters param1=xxx, param2=yyy, gain=3.5 ... Then an Enemi object with parameters speed=10, active=YES, name=zzz ... ``` { active = NO; looping = YES; soundList = "FINAL_PSS_imoverhere_all"; speed = 100.0; ``` } I then instantiate my classes, and would like to set the ivars automatically from this dictionnary. I've actually wrote some code to check that this parameter exists, but I'm having trouble in actually setting the parameter value, especially when the parameter is non object (float or bool). Here's what I'm doing so far : ``` //aKey is the name of the ivar for (NSString *aKey in [properties allKeys]){ //create the name of the setter function from the key (parameter -> setParameter) NSString *setterName = [aKey stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[aKey substringToIndex:1] uppercaseString]]; setterName = [NSString stringWithFormat:@"set%@:",setterName]; SEL setterSelector = NSSelectorFromString(setterName); //Check if the parameter exists if ([pge_object respondsToSelector:setterSelector]){ //TODO : automatically set the parameter } else{ [[PSMessagesChecker sharedInstance]logMessage:[NSString stringWithFormat:@"Cannot find %@ on %@", aKey, [dict objectForKey:@"type"]] inColor:@"red"]; NSLog(@"Cannot find %@ on %@", aKey, [dict objectForKey:@"type"]); } } } ``` As you can see, I don't know what to do once I've found that the parameter exists on the object. I tried to use "performSelector... withObject..., but my problem is that some of the parameters are non-objects (float or bool). I also tried to get the class of the parameter, by using the setter, but it didn't help. Did anyone manage to do something like that?
2012/11/28
[ "https://Stackoverflow.com/questions/13609924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1617234/" ]
Jack Lawrence's comment is spot on. What you are looking for is called **Key Value Coding**, or just **KVC**. This fundamental part of Cocoa lets you get and set any instance variable using its name as a String and a new value. It will automatically handle coercing Objects to primitive values, so you can use it for int and float properties too. There is also support for validating values and handling unknown properties. [see the docs](http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/KeyValueCoding/Articles/KeyValueCoding.html) your code, without validation, could be written ``` for( id eachKey in props ) { [anOb setValue:props[eachKey] forKey:eachKey]; } ``` or just ``` [anOb setValuesForKeysWithDictionary:props]; ``` as Jack said.
For the non-object parameters you have to put them into an object, for example `NSNumber` or `NSValue`. You can then add these objects into your dictionary. For Example: ``` float f = 0.5; NSNumber f_obj = [NSNumber numberWithFloat:f]; ```
59,854,511
I am trying to understand why the below layouts work differently. Can someone explain how the internal layout process happen, in terms of rules? And why below examples behave differently. Except just saying that this is how it is. Example1: ``` return ( <View style = {{borderWidth : 1, borderColor : 'red'}}> <View style = {{borderWidth : 1, borderColor : 'black'}}> <Text>TestText</Text> </View> </View> ) ``` This renders the red box around the black box around the Text. Which means that View resizes based on its content. inner view resizes to consider the text, outer view considers inner view(which already has considered inner text to determine its dimensions), hence everything is as expected. Example2: ``` return ( <View style = {{borderWidth : 1, borderColor : 'red'}}> <View style = {{flex:1,borderWidth : 1, borderColor : 'black'}}> <Text>TestText</Text> </View> </View> ) ``` The text now comes outside both the Views. The inner view still rests inside the outer view though. Now i tried a little different variation: Example3: ``` return <View style = {{borderWidth:1, borderColor:'red', height:10}}> <View style = {{flex:1, borderWidth:1, borderColor:'black'}}> <Text>HelloWorld</Text> </View> </View> ``` This one renders a little better, i.e the text atleast seems to start inside both the views. But still not as expected. Questions i have: 1) in case #2 above, Why does the text flow outside both the views? Whereas inner View still stays inside outer? Can some content ever go beyond the bounds of its parent View? Shouldn't the parent View expand to contain it, as long as we haven't provided specific dimensions to it? 2)In case #3, things behave a little bit as expected..Text is inside the views somewhat, but still overflows.. 3)How does this rendering happen in ReactNative internally & how does it determine the effective heights of these views above?
2020/01/22
[ "https://Stackoverflow.com/questions/59854511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/895429/" ]
**Example with flex** `flex: 1`, obligates child to follow parent's height, "Black view" will fill all the space available of the "Red view", which is `height:60`. [![enter image description here](https://i.stack.imgur.com/LfqPv.png)](https://i.stack.imgur.com/LfqPv.png) ``` <View style={{ borderColor: "red", height: 60 }}> <View style={{ borderColor: "black", flex: 1 }}> <Text>HelloWorld</Text> ... </View> </View> ``` --- **Example without flex:1** Here without flex, "Black view" will occupy all space of its children, it won't matter height of the parent ("Red view"). [![enter image description here](https://i.stack.imgur.com/XPtVF.png)](https://i.stack.imgur.com/XPtVF.png) ``` <View style={{ borderColor: "red", height: 60 }}> <View style={{ borderColor: "black" }}> <Text>HelloWorld</Text> ... </View> </View> ```
The thing is in simple terms the outline misbehaves in case of 2nd one , i.e : ``` <View style = {{borderWidth : 1, borderColor : 'red'}}> <View style = {{flex:1,borderWidth : 1, borderColor : 'black'}}> <Text>TestText</Text> </View> </View> ``` Is because the parent `View` component doesnt have a `flex` property so it doesnt take up whole the space and since you have added `flex:1 in the child View` it tries to take up as whole space as its alloted , hence black border Dominates and TestText is below it. But if you provide flex:1 , to parent View you will see the same structure as it was with no flex given at all. Try : ``` <View style = {{flex:1,borderWidth : 1, borderColor : 'red'}}> <View style = {{flex:1,borderWidth : 1, borderColor : 'black'}}> <Text>TestText</Text> </View> </View> ``` Hope it helps . feel free for doubts