qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
1,265,860
This keeps happening to me all the time: 1) I write a script(ruby, shell, etc). 2) run it, it works. 3) put it in crontab so it runs in a few minutes so I know it runs from there. 4) It doesnt, no error trace, back to step 2 or 3 a 1000 times. When I ruby script fails in crontab, I can't really know why it fails cause when I pipe output like this: ``` ruby script.rb >& /path/to/output ``` I sorta get the output of the script, but I don't get any of the errors from it and I don't get the errors coming from bash (like if ruby is not found or file isn't there) I have no idea what environmental variables are set and whether or not it's a problem. Turns out that to run a ruby script from crontab you have to export a ton of environment variables. Is there a way for me to just have crontab run a script as if **I ran it myself from my terminal**? When debugging, I have to reset the timer and go back to waiting. Very time consuming. How to test things in crontab better or avoid these problems?
2009/08/12
[ "https://Stackoverflow.com/questions/1265860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96087/" ]
> > "Is there a way for me to just have crontab run a script as if I ran it myself from my terminal?" > > > Yes: ``` bash -li -c /path/to/script ``` From the man page: ``` [vindaloo:pgl]:~/p/test $ man bash | grep -A2 -m1 -- -i -i If the -i option is present, the shell is interactive. -l Make bash act as if it had been invoked as a login shell (see INVOCATION below). ```
You could write a wrapper script, called for example `rbcron`, which looks something like: ``` #!/bin/bash RUBY=ruby export VAR1=foo export VAR2=bar export VAR3=baz $RUBY "$*" 2>&1 ``` This will redirect standard error from ruby to the standard output. Then you run `rbcron` in your cron job, and the standard output contains out+err of ruby, but also the "bash" errors existing from rbcron itself. In your cron entry, redirect `2>&1 > /path/to/output` to get output+error messages to go to /path/to/output.
1,265,860
This keeps happening to me all the time: 1) I write a script(ruby, shell, etc). 2) run it, it works. 3) put it in crontab so it runs in a few minutes so I know it runs from there. 4) It doesnt, no error trace, back to step 2 or 3 a 1000 times. When I ruby script fails in crontab, I can't really know why it fails cause when I pipe output like this: ``` ruby script.rb >& /path/to/output ``` I sorta get the output of the script, but I don't get any of the errors from it and I don't get the errors coming from bash (like if ruby is not found or file isn't there) I have no idea what environmental variables are set and whether or not it's a problem. Turns out that to run a ruby script from crontab you have to export a ton of environment variables. Is there a way for me to just have crontab run a script as if **I ran it myself from my terminal**? When debugging, I have to reset the timer and go back to waiting. Very time consuming. How to test things in crontab better or avoid these problems?
2009/08/12
[ "https://Stackoverflow.com/questions/1265860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96087/" ]
To find out the environment in which cron runs jobs, add this cron job: ``` { echo "\nenv\n" && env|sort ; echo "\nset\n" && set; } | /usr/bin/mailx -s 'my env' [email protected] ``` Or send the output to a file instead of email.
You could write a wrapper script, called for example `rbcron`, which looks something like: ``` #!/bin/bash RUBY=ruby export VAR1=foo export VAR2=bar export VAR3=baz $RUBY "$*" 2>&1 ``` This will redirect standard error from ruby to the standard output. Then you run `rbcron` in your cron job, and the standard output contains out+err of ruby, but also the "bash" errors existing from rbcron itself. In your cron entry, redirect `2>&1 > /path/to/output` to get output+error messages to go to /path/to/output.
1,265,860
This keeps happening to me all the time: 1) I write a script(ruby, shell, etc). 2) run it, it works. 3) put it in crontab so it runs in a few minutes so I know it runs from there. 4) It doesnt, no error trace, back to step 2 or 3 a 1000 times. When I ruby script fails in crontab, I can't really know why it fails cause when I pipe output like this: ``` ruby script.rb >& /path/to/output ``` I sorta get the output of the script, but I don't get any of the errors from it and I don't get the errors coming from bash (like if ruby is not found or file isn't there) I have no idea what environmental variables are set and whether or not it's a problem. Turns out that to run a ruby script from crontab you have to export a ton of environment variables. Is there a way for me to just have crontab run a script as if **I ran it myself from my terminal**? When debugging, I have to reset the timer and go back to waiting. Very time consuming. How to test things in crontab better or avoid these problems?
2009/08/12
[ "https://Stackoverflow.com/questions/1265860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96087/" ]
> > "Is there a way for me to just have crontab run a script as if I ran it myself from my terminal?" > > > Yes: ``` bash -li -c /path/to/script ``` From the man page: ``` [vindaloo:pgl]:~/p/test $ man bash | grep -A2 -m1 -- -i -i If the -i option is present, the shell is interactive. -l Make bash act as if it had been invoked as a login shell (see INVOCATION below). ```
To find out the environment in which cron runs jobs, add this cron job: ``` { echo "\nenv\n" && env|sort ; echo "\nset\n" && set; } | /usr/bin/mailx -s 'my env' [email protected] ``` Or send the output to a file instead of email.
1,265,860
This keeps happening to me all the time: 1) I write a script(ruby, shell, etc). 2) run it, it works. 3) put it in crontab so it runs in a few minutes so I know it runs from there. 4) It doesnt, no error trace, back to step 2 or 3 a 1000 times. When I ruby script fails in crontab, I can't really know why it fails cause when I pipe output like this: ``` ruby script.rb >& /path/to/output ``` I sorta get the output of the script, but I don't get any of the errors from it and I don't get the errors coming from bash (like if ruby is not found or file isn't there) I have no idea what environmental variables are set and whether or not it's a problem. Turns out that to run a ruby script from crontab you have to export a ton of environment variables. Is there a way for me to just have crontab run a script as if **I ran it myself from my terminal**? When debugging, I have to reset the timer and go back to waiting. Very time consuming. How to test things in crontab better or avoid these problems?
2009/08/12
[ "https://Stackoverflow.com/questions/1265860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96087/" ]
> > "Is there a way for me to just have crontab run a script as if I ran it myself from my terminal?" > > > Yes: ``` bash -li -c /path/to/script ``` From the man page: ``` [vindaloo:pgl]:~/p/test $ man bash | grep -A2 -m1 -- -i -i If the -i option is present, the shell is interactive. -l Make bash act as if it had been invoked as a login shell (see INVOCATION below). ```
Run a 'set' command from inside of the ruby script, fire it from crontab, and you'll see exactly what's set and what's not.
1,265,860
This keeps happening to me all the time: 1) I write a script(ruby, shell, etc). 2) run it, it works. 3) put it in crontab so it runs in a few minutes so I know it runs from there. 4) It doesnt, no error trace, back to step 2 or 3 a 1000 times. When I ruby script fails in crontab, I can't really know why it fails cause when I pipe output like this: ``` ruby script.rb >& /path/to/output ``` I sorta get the output of the script, but I don't get any of the errors from it and I don't get the errors coming from bash (like if ruby is not found or file isn't there) I have no idea what environmental variables are set and whether or not it's a problem. Turns out that to run a ruby script from crontab you have to export a ton of environment variables. Is there a way for me to just have crontab run a script as if **I ran it myself from my terminal**? When debugging, I have to reset the timer and go back to waiting. Very time consuming. How to test things in crontab better or avoid these problems?
2009/08/12
[ "https://Stackoverflow.com/questions/1265860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96087/" ]
Run a 'set' command from inside of the ruby script, fire it from crontab, and you'll see exactly what's set and what's not.
You could write a wrapper script, called for example `rbcron`, which looks something like: ``` #!/bin/bash RUBY=ruby export VAR1=foo export VAR2=bar export VAR3=baz $RUBY "$*" 2>&1 ``` This will redirect standard error from ruby to the standard output. Then you run `rbcron` in your cron job, and the standard output contains out+err of ruby, but also the "bash" errors existing from rbcron itself. In your cron entry, redirect `2>&1 > /path/to/output` to get output+error messages to go to /path/to/output.
1,265,860
This keeps happening to me all the time: 1) I write a script(ruby, shell, etc). 2) run it, it works. 3) put it in crontab so it runs in a few minutes so I know it runs from there. 4) It doesnt, no error trace, back to step 2 or 3 a 1000 times. When I ruby script fails in crontab, I can't really know why it fails cause when I pipe output like this: ``` ruby script.rb >& /path/to/output ``` I sorta get the output of the script, but I don't get any of the errors from it and I don't get the errors coming from bash (like if ruby is not found or file isn't there) I have no idea what environmental variables are set and whether or not it's a problem. Turns out that to run a ruby script from crontab you have to export a ton of environment variables. Is there a way for me to just have crontab run a script as if **I ran it myself from my terminal**? When debugging, I have to reset the timer and go back to waiting. Very time consuming. How to test things in crontab better or avoid these problems?
2009/08/12
[ "https://Stackoverflow.com/questions/1265860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96087/" ]
G'day, One of the basic problems with cron is that you get a **minimal** environment being set by cron. In fact, you only get four env. var's set and they are: * SHELL - set to /bin/sh * LOGNAME - set to your userid as found in /etc/passwd * HOME - set to your home dir. as found in /etc/passwd * PATH - set to "/usr/bin:/bin" That's it. However, what you can do is take a snapshot of the environment you want and save that to a file. Now make your cronjob source a trivial shell script that sources this env. file and then executes your Ruby script. BTW Having a wrapper source a common env. file is an excellent way to enforce a consistent environment for multiple cronjobs. This also enforces the DRY principle because it gives you just one point to update things as required, instead of having to search through a bunch of scripts and search for a specific string if, say, a logging location is changed or a different utility is now being used, e.g. gnutar instead of vanilla tar. Actually, this technique is used very successfully with The Build Monkey which is used to implement Continuous Integration for a major software project that is common to several major world airlines. 3,500kSLOC being checked out and built several times a day and over 8,000 regression tests run once a day. HTH 'Avahappy,
Run a 'set' command from inside of the ruby script, fire it from crontab, and you'll see exactly what's set and what's not.
116,626
Is there a way to limit the damage one constantly takes in Developper's garden? I get killed every time and don't even know by what.
2013/05/08
[ "https://gaming.stackexchange.com/questions/116626", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/48229/" ]
Another way is to use many invulnerability potions, just before you reach the enemies. Watch the countdown and teleport yourself back, when it's nearly over. Then use a seed or another teleport-scroll, so that you can use another invulnerability potion right before the next enemy. It took me the seeds and teleport-scrolls to finish them.
I did it by teleporting back before I got to those evil CGs, and always threw around earthquake scrolls on my way. Somehow that seemed to work...
307,095
Can't find a post saying this, and I get a compile error, but just to be sure, this is not supported in Apex right? ``` public interface Access { public interface Context { ... } public Set<Id> accessibleContacts(Context context); ... } ``` Pity it isn't given that the inner class approach is good for grouping classes in an outer class that acts as a namespace. And an arbitrary and so annoying irregularity.
2020/05/22
[ "https://salesforce.stackexchange.com/questions/307095", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/887/" ]
As the documentation says in this entry [Differences Between Apex Classes and Java Classes](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_java_diffs.htm) ``` - Inner classes and interfaces can only be declared one level deep inside an outer class. ``` So you are allowed to declare an interface only inside a class (not inside an interface). I think you can still acquire the desired output of having a bunch of interfaces inside a "namespace". Just make it abstract, so it cannot be instantiated ```java public abstract class Access { public interface Context {} public Set<Id> accessibleContacts(Context context) { throw new NotImplementedException('You must implement the accessibleContacts method'); } public class NotImplementedException extends Exception {} } ```
The main reason why this is not supported, is that Apex isn't Java. When salesforce.com sat down and started designing Apex, they created a BNF that they felt could be implemented in a reasonable amount of time, have enough language features to be useful to the majority of customers, and be generally secure and stable enough that it wouldn't crash frequently. Even back then, though, developers had a very good chance of running into Internal Server Errors if they didn't strictly follow the code patterns laid out in the documentation. Things like deeply nested classes, nested interfaces, etc were simply out of scope for the project, as they would have been too complicated, and could be solved by other, simpler patterns. The compiler was too fragile to handle large new features, and many of these probably would have broken Apex completely. Think of all the things we don't have from Java: events, nested interfaces, default parameters, lambdas, anonymous inner classes, deeply nested classes, nested interfaces, java.lang.Reflect, nested namespaces/packages, import statements, there's a huge list of things that are just different or missing. Apex was thrown together in a very short amount of time (as far as compilers go), and the fact that it worked as well as it did initially was a surprise to some. I don't think you can get an official answer for why it's not supported other than a vague "we didn't have time" or "it was too complicated" type answer. Just know that the old compiler could not have handled this type of code, and today we're still in compatibility with that old compiler. For now, if you want interfaces grouped together, put them inside an abstract class, or group your classes into unlocked packages (or not, just use folders into your repo!). If you're not yet using DX, you may want to start leaning in that direction. It offers the sort of organization you're looking for, just not on the server side. It's not likely we'll see many of these features any time soon, although I would be pleasantly surprised if they were.
60,758,670
Given some alphanumerical strings in Python such as * `A9` * `B44B` * `C101` * `4D4` how do I check if the string is a valid Excel cell (i.e., **letters come before numbers**)? I've tried using the `.isalpha` and `.isdigit` methods to "gather" letters and numbers, and then using `.index` to check whether all letters appear before numbers, but my logic is becoming too complex, and I feel like I'm not accounting for all possibilities. Is there a simple way to achieve this? Expected result: ``` >>> is_valid_excel_cell('A9') True >>> is_valid_excel_cell('B44B') False >>> is_valid_excel_cell('C101') True >>> is_valid_excel_cell('4D4') False ```
2020/03/19
[ "https://Stackoverflow.com/questions/60758670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11161432/" ]
As per my comment, validity depends on Excel version. Newer versions have a column range of `A-XDF` and rows from `1-1048576`. It might not be necessary in your project, but for future reference it could be handy: Regex pattern: `^([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])([1-9]\d{0,6})$` To visualize this: ![Regular expression visualization](https://www.debuggex.com/i/C3KU8-0GGTnyiJRH.png) First group captures the column reference for Excel 2010 and higher which is `A-XDF`, and the second group captures the numeric part which should always start with `1-9` followed by 0 to 6 characters but cannot exceed `1048576`. So in full effect you could think about: ``` import re def is_valid_excel_cell(c): m = re.match(r'^([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])([1-9]\d{0,6})$',c) return bool(m) and int(m.group(2)) < 1048577 ```
I would use regular expressions, well fit for the task: ``` import re def is_valid_excel_cell(c): m = re.match("[A-Z]+\d+$",c) return bool(m) ``` that one checks if the cell contents starts with a capital letter and ends with a digit. Now if range check is required on the number one more step would be required, one can extract the digits and convert them to integer, compare to a range (I'll let the reader adjust the range, as I'm not a excel expert). ``` def is_valid_excel_cell(c): m = re.match("[A-Z]+(\d+)$",c) return bool(m) and m.group(1).isdigit() and 0 < int(m.group(1)) < 16384 ```
60,758,670
Given some alphanumerical strings in Python such as * `A9` * `B44B` * `C101` * `4D4` how do I check if the string is a valid Excel cell (i.e., **letters come before numbers**)? I've tried using the `.isalpha` and `.isdigit` methods to "gather" letters and numbers, and then using `.index` to check whether all letters appear before numbers, but my logic is becoming too complex, and I feel like I'm not accounting for all possibilities. Is there a simple way to achieve this? Expected result: ``` >>> is_valid_excel_cell('A9') True >>> is_valid_excel_cell('B44B') False >>> is_valid_excel_cell('C101') True >>> is_valid_excel_cell('4D4') False ```
2020/03/19
[ "https://Stackoverflow.com/questions/60758670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11161432/" ]
I would use regular expressions, well fit for the task: ``` import re def is_valid_excel_cell(c): m = re.match("[A-Z]+\d+$",c) return bool(m) ``` that one checks if the cell contents starts with a capital letter and ends with a digit. Now if range check is required on the number one more step would be required, one can extract the digits and convert them to integer, compare to a range (I'll let the reader adjust the range, as I'm not a excel expert). ``` def is_valid_excel_cell(c): m = re.match("[A-Z]+(\d+)$",c) return bool(m) and m.group(1).isdigit() and 0 < int(m.group(1)) < 16384 ```
``` import re def is_valid_excel_cell(addr): m = re.match(r'^([A-Z]{1,3})([1-9]\d*)$', addr) if not m: return False letters, numbers = m.groups() if len(letters) == 3 and letters > 'XFD': return False if int(numbers) > 1048576: return False return True ``` Semicompressed for Python 3.8+ only (due to the use of the walrus (`:=`) operator): ``` def is_valid_excel_cell(addr): return (bool(m := re.match(r'^([A-Z]{1,3})([1-9]\d*)$', addr)) and (len(m.group(1)) < 3 or m.group(1) <= 'XFD') and int(m.group(2)) <= 1048576) ```
60,758,670
Given some alphanumerical strings in Python such as * `A9` * `B44B` * `C101` * `4D4` how do I check if the string is a valid Excel cell (i.e., **letters come before numbers**)? I've tried using the `.isalpha` and `.isdigit` methods to "gather" letters and numbers, and then using `.index` to check whether all letters appear before numbers, but my logic is becoming too complex, and I feel like I'm not accounting for all possibilities. Is there a simple way to achieve this? Expected result: ``` >>> is_valid_excel_cell('A9') True >>> is_valid_excel_cell('B44B') False >>> is_valid_excel_cell('C101') True >>> is_valid_excel_cell('4D4') False ```
2020/03/19
[ "https://Stackoverflow.com/questions/60758670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11161432/" ]
As per my comment, validity depends on Excel version. Newer versions have a column range of `A-XDF` and rows from `1-1048576`. It might not be necessary in your project, but for future reference it could be handy: Regex pattern: `^([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])([1-9]\d{0,6})$` To visualize this: ![Regular expression visualization](https://www.debuggex.com/i/C3KU8-0GGTnyiJRH.png) First group captures the column reference for Excel 2010 and higher which is `A-XDF`, and the second group captures the numeric part which should always start with `1-9` followed by 0 to 6 characters but cannot exceed `1048576`. So in full effect you could think about: ``` import re def is_valid_excel_cell(c): m = re.match(r'^([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])([1-9]\d{0,6})$',c) return bool(m) and int(m.group(2)) < 1048577 ```
``` import re def is_valid_excel_cell(addr): m = re.match(r'^([A-Z]{1,3})([1-9]\d*)$', addr) if not m: return False letters, numbers = m.groups() if len(letters) == 3 and letters > 'XFD': return False if int(numbers) > 1048576: return False return True ``` Semicompressed for Python 3.8+ only (due to the use of the walrus (`:=`) operator): ``` def is_valid_excel_cell(addr): return (bool(m := re.match(r'^([A-Z]{1,3})([1-9]\d*)$', addr)) and (len(m.group(1)) < 3 or m.group(1) <= 'XFD') and int(m.group(2)) <= 1048576) ```
12,823,347
I'm testing my asp.net website on my local server (Windows Server 2008, IIS 7.0.6), and when I type in just the IP address in my browser, e.g., ``` 192.168.0.5 ``` it comes back like this: ``` http://192.168.0.5/(S(u0nmzwxobbwpuk1mtvuybwn0))/default.aspx ``` The weird stuff between .0.5/ and /default.aspx changes every time I type in the ip and hit enter. The content shows up correctly, but obviously there's a problem with the url.
2012/10/10
[ "https://Stackoverflow.com/questions/12823347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/403748/" ]
Sounds like you might be using cookieless sessions. Basically ASP.NET is storing your session id in the query string instead of storing it in a cookie. Looks gross, but allows you to use session state when someone does not accept cookies. You can read more [here](http://msdn.microsoft.com/en-us/library/aa479314.aspx).
Guessing here - in your `web.config` file, you have set the `sessionState` `cookieless` attribute to `UseUri` or to `true`. See the documentation on the [`sessionState`](http://msdn.microsoft.com/en-us/library/h6bb9cz9%28v=vs.100%29.aspx) element.
12,823,347
I'm testing my asp.net website on my local server (Windows Server 2008, IIS 7.0.6), and when I type in just the IP address in my browser, e.g., ``` 192.168.0.5 ``` it comes back like this: ``` http://192.168.0.5/(S(u0nmzwxobbwpuk1mtvuybwn0))/default.aspx ``` The weird stuff between .0.5/ and /default.aspx changes every time I type in the ip and hit enter. The content shows up correctly, but obviously there's a problem with the url.
2012/10/10
[ "https://Stackoverflow.com/questions/12823347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/403748/" ]
Sounds like you might be using cookieless sessions. Basically ASP.NET is storing your session id in the query string instead of storing it in a cookie. Looks gross, but allows you to use session state when someone does not accept cookies. You can read more [here](http://msdn.microsoft.com/en-us/library/aa479314.aspx).
Seems like you Have Cookieless Sessions enabled. Below article illustrates the behavior: [MSDN - Cookie Less Sessions in ASP.NET](http://msdn.microsoft.com/en-us/library/aa479314.aspx) Changing the Setting in Web.Config can change the behavior: ``` <sessionState cookieless="true" /> ```
12,823,347
I'm testing my asp.net website on my local server (Windows Server 2008, IIS 7.0.6), and when I type in just the IP address in my browser, e.g., ``` 192.168.0.5 ``` it comes back like this: ``` http://192.168.0.5/(S(u0nmzwxobbwpuk1mtvuybwn0))/default.aspx ``` The weird stuff between .0.5/ and /default.aspx changes every time I type in the ip and hit enter. The content shows up correctly, but obviously there's a problem with the url.
2012/10/10
[ "https://Stackoverflow.com/questions/12823347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/403748/" ]
Guessing here - in your `web.config` file, you have set the `sessionState` `cookieless` attribute to `UseUri` or to `true`. See the documentation on the [`sessionState`](http://msdn.microsoft.com/en-us/library/h6bb9cz9%28v=vs.100%29.aspx) element.
Seems like you Have Cookieless Sessions enabled. Below article illustrates the behavior: [MSDN - Cookie Less Sessions in ASP.NET](http://msdn.microsoft.com/en-us/library/aa479314.aspx) Changing the Setting in Web.Config can change the behavior: ``` <sessionState cookieless="true" /> ```
6,320,207
What I would like to be able to do is to add an attribute to specific methods of a class so that those methods so decorated could have the statements in their body be called in a manner that I liked. For example, consider this scenario in C#: ``` public class A { public A() {} [CallTwice()] public void Func1() { Console.WriteLine("Calling Func1()."); } public void Func2() { Console.WriteLine("Calling Func2()."); } } ``` I would like a scenario where if I did this: ``` public static void Main() { A a = new A(); a.Func1(); a.Func2(); } ``` I would get this output: ``` Calling A.Func1(). Calling A.Func1(). Calling A.Func2(). ``` i.e. my decoration of Func1 makes it to be called twice. What I would like to know is how I could write code to take advantage of the specific decoration I have given to Func1 so that I would know to call its body statements twice. Is this possible in C#?
2011/06/12
[ "https://Stackoverflow.com/questions/6320207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192131/" ]
Why not simply make Func1 private or protected, and make different method, that calls Func1 twice? ``` public class A { public A() {} public void Func1() { Func1Core(); Func1Core(); } private void Func1Core() { Console.WriteLine("Calling Func1()."); } public void Func2() { Console.WriteLine("Calling Func2()."); } } ```
You can make Func1 to recursively call itself by decrementing a count variable for each call.
6,320,207
What I would like to be able to do is to add an attribute to specific methods of a class so that those methods so decorated could have the statements in their body be called in a manner that I liked. For example, consider this scenario in C#: ``` public class A { public A() {} [CallTwice()] public void Func1() { Console.WriteLine("Calling Func1()."); } public void Func2() { Console.WriteLine("Calling Func2()."); } } ``` I would like a scenario where if I did this: ``` public static void Main() { A a = new A(); a.Func1(); a.Func2(); } ``` I would get this output: ``` Calling A.Func1(). Calling A.Func1(). Calling A.Func2(). ``` i.e. my decoration of Func1 makes it to be called twice. What I would like to know is how I could write code to take advantage of the specific decoration I have given to Func1 so that I would know to call its body statements twice. Is this possible in C#?
2011/06/12
[ "https://Stackoverflow.com/questions/6320207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192131/" ]
Why not simply make Func1 private or protected, and make different method, that calls Func1 twice? ``` public class A { public A() {} public void Func1() { Func1Core(); Func1Core(); } private void Func1Core() { Console.WriteLine("Calling Func1()."); } public void Func2() { Console.WriteLine("Calling Func2()."); } } ```
I don't know if it helps in this case but [PostSharp](http://www.sharpcrafters.com/) allows you to decorate methods with attributes for special purpose. <http://www.sharpcrafters.com/postsharp/documentation>
45,836
The actual distributions I am dealing with are not uniform, but to keep it simple, consider two uniform distributions, one on [1, 2] and the other on [0,2]. Can we say that the first FOSDs the second? Further, if we have a multitude of distributions (suppose uniform still) on [b, 2], can we say their FOSD increases with b? If not, what concept captures that property?
2021/07/13
[ "https://economics.stackexchange.com/questions/45836", "https://economics.stackexchange.com", "https://economics.stackexchange.com/users/31421/" ]
Let $X\_b$ a random variable uniformly distributed on $[b,2]$ with $b<2$. For every $x\in\mathbb{R}$, $$\mathbb{P}[X\_b\geq x]=\begin{cases} 0\text{ if }x>2\\ \frac{2-x}{2-b}\text{ if } b\leq x\leq 2\\ 1\text{ if }x<b. \end{cases} $$ Clearly, this probability is increasing in $b$. So $b>b'$ implies that $X\_b$ first order stochastically dominates $X\_{b'}$ for $b$ and $b'$ both smaller than $2$.
It is not exactly clear what you mean by "distribution functions that belong to the same class." Consider a random variable $\widehat X$ with an arbitrary distribution on some support $[\underline x,\overline x]$. We can then normalize the support to $[0,1]$ by looking at $X=\frac{\widehat X-\underline x}{\overline x-\underline x}$ and let $F$ be the corresponding cdf. Do you want to see if the conditional random variable $X\geq b$ FOSD $X$? The answer is yes. We can express the cdf of $X\geq b$ as $\frac{F(x)-F(b)}{1-F(b)}$ for all $x \in [b,1]$. Then we have, $$F(x) \geq \frac{F(x)-F(b)}{1-F(b)} \quad \forall x \in [b,1] \mbox{ and } \forall b \in (0,1),$$ and, moreover, we have $$\frac{F(x)-F(b')}{1-F(b')} \geq \frac{F(x)-F(b)}{1-F(b)} \quad \forall x \in [b,1] \mbox{ if } b>b' .$$ Hence, the distribution (or random variable) with some $b$ FOSD the distribution with a lower $b'< b$.
17,541,407
I'm currently making a game in Windows 7 using Batch Files. So I have a sequence where it asks you a question and you type in the answer: ``` :MainMenu set /p LMainMenu= if %LMainMenu%==1 goto PlayMenu if %LMainMenu%==2 goto ColourMenu if %LMainMenu%==3 goto Reset1 if %LMainMenu%==4 goto AboutMenu goto MainMenu ``` So if someone doesn't type anything in and presses 'Enter', the CMD window will close. How do I prevent this from happening? I added the 'goto MainMenu' so if they type in anything other than 1,2,3,4, they will be taken back. Much will be appreciated. Thanks.
2013/07/09
[ "https://Stackoverflow.com/questions/17541407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2507295/" ]
try this ``` :MainMenu set /a LMainMenu=1 set /p "LMainMenu=enter a number: " ``` For more help see `help set` on the command prompt.
Add this should work. if "%LMainMenu%"=="" goto MainMenu
17,541,407
I'm currently making a game in Windows 7 using Batch Files. So I have a sequence where it asks you a question and you type in the answer: ``` :MainMenu set /p LMainMenu= if %LMainMenu%==1 goto PlayMenu if %LMainMenu%==2 goto ColourMenu if %LMainMenu%==3 goto Reset1 if %LMainMenu%==4 goto AboutMenu goto MainMenu ``` So if someone doesn't type anything in and presses 'Enter', the CMD window will close. How do I prevent this from happening? I added the 'goto MainMenu' so if they type in anything other than 1,2,3,4, they will be taken back. Much will be appreciated. Thanks.
2013/07/09
[ "https://Stackoverflow.com/questions/17541407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2507295/" ]
try this ``` :MainMenu set /a LMainMenu=1 set /p "LMainMenu=enter a number: " ``` For more help see `help set` on the command prompt.
If you want to have a default selection (automatically selected when the user just presses `Enter`), use the solution [Endoro](https://stackoverflow.com/a/17541554/1630171) suggested. If you want to loop until the user makes a valid selection, use this instead: ``` :MainMenu set "LMainMenu=" set /p "LMainMenu=Enter a number [1-4]: " if not defined LMainMenu goto MainMenu if "%LMainMenu%"=="1" goto PlayMenu ... ```
17,541,407
I'm currently making a game in Windows 7 using Batch Files. So I have a sequence where it asks you a question and you type in the answer: ``` :MainMenu set /p LMainMenu= if %LMainMenu%==1 goto PlayMenu if %LMainMenu%==2 goto ColourMenu if %LMainMenu%==3 goto Reset1 if %LMainMenu%==4 goto AboutMenu goto MainMenu ``` So if someone doesn't type anything in and presses 'Enter', the CMD window will close. How do I prevent this from happening? I added the 'goto MainMenu' so if they type in anything other than 1,2,3,4, they will be taken back. Much will be appreciated. Thanks.
2013/07/09
[ "https://Stackoverflow.com/questions/17541407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2507295/" ]
If you want to have a default selection (automatically selected when the user just presses `Enter`), use the solution [Endoro](https://stackoverflow.com/a/17541554/1630171) suggested. If you want to loop until the user makes a valid selection, use this instead: ``` :MainMenu set "LMainMenu=" set /p "LMainMenu=Enter a number [1-4]: " if not defined LMainMenu goto MainMenu if "%LMainMenu%"=="1" goto PlayMenu ... ```
Add this should work. if "%LMainMenu%"=="" goto MainMenu
5,997,106
On the production servers I can use the datastore viewer to compose some GQL (as long as it's supported by the indexes) and find data on the fly. What's the best way to do this on the dev server? I'm using the Java sdk 1.4.3, and I already have remote\_api installed.
2011/05/13
[ "https://Stackoverflow.com/questions/5997106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439317/" ]
<http://www.developerfusion.com/tools/convert/csharp-to-vb/> Which will give you: ``` For Each [property] As Google.GData.Client.IExtensionElementFactory In googleEvent.ExtensionElements Dim customProperty As ExtendedProperty = TryCast([property], ExtendedProperty) If customProperty IsNot Nothing Then genericEvent.EventID = customProperty.Value End If Next ```
As already posted, you can use an automated tool for such trivial conversions that don't use more advanced language features. Note however: In VB, `As` is used to declare the **type** of a variable - not a cast, as it is in C#. Thus ``` For Each property As Google.GData.Client.IExtensionElementFactory In googleEvent.ExtensionElements Dim customProperty As ExtendedProperty = TryCast(property, ExtendedProperty) If customProperty IsNot Nothing Then genericEvent.EventID = customProperty.Value End If Next ```
5,997,106
On the production servers I can use the datastore viewer to compose some GQL (as long as it's supported by the indexes) and find data on the fly. What's the best way to do this on the dev server? I'm using the Java sdk 1.4.3, and I already have remote\_api installed.
2011/05/13
[ "https://Stackoverflow.com/questions/5997106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439317/" ]
<http://www.developerfusion.com/tools/convert/csharp-to-vb/> Which will give you: ``` For Each [property] As Google.GData.Client.IExtensionElementFactory In googleEvent.ExtensionElements Dim customProperty As ExtendedProperty = TryCast([property], ExtendedProperty) If customProperty IsNot Nothing Then genericEvent.EventID = customProperty.Value End If Next ```
``` For Each elem As Google.GData.Client.IExtensionElementFactory In googleEvent.ExtensionElements Dim customProperty As ExtendedProperty = DirectCast(elem, ExtendedProperty) If ExtendedProperty IsNot Nothing Then genericEvent.EventID = customProperty.Value End If Next ``` Try That
5,997,106
On the production servers I can use the datastore viewer to compose some GQL (as long as it's supported by the indexes) and find data on the fly. What's the best way to do this on the dev server? I'm using the Java sdk 1.4.3, and I already have remote\_api installed.
2011/05/13
[ "https://Stackoverflow.com/questions/5997106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439317/" ]
<http://www.developerfusion.com/tools/convert/csharp-to-vb/> Which will give you: ``` For Each [property] As Google.GData.Client.IExtensionElementFactory In googleEvent.ExtensionElements Dim customProperty As ExtendedProperty = TryCast([property], ExtendedProperty) If customProperty IsNot Nothing Then genericEvent.EventID = customProperty.Value End If Next ```
Try this: ``` For Each property as Google.GData.Client.IExtensionElementFactory In googleEvent.ExtensionElements Dim customProperty As ExtendedProperty = CType(property, ExtendedProperty) If customerProperty IsNot Nothing Then genericEvent.EventID = customProperty.Value End If Next ```
5,997,106
On the production servers I can use the datastore viewer to compose some GQL (as long as it's supported by the indexes) and find data on the fly. What's the best way to do this on the dev server? I'm using the Java sdk 1.4.3, and I already have remote\_api installed.
2011/05/13
[ "https://Stackoverflow.com/questions/5997106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439317/" ]
<http://www.developerfusion.com/tools/convert/csharp-to-vb/> Which will give you: ``` For Each [property] As Google.GData.Client.IExtensionElementFactory In googleEvent.ExtensionElements Dim customProperty As ExtendedProperty = TryCast([property], ExtendedProperty) If customProperty IsNot Nothing Then genericEvent.EventID = customProperty.Value End If Next ```
``` For Each property As Google.GData.Client.IExtensionElementFactory In googleEvent.ExtensionElements Dim customProperty As ExtendedProperty = TryCast(property, ExtendedProperty) If customProperty IsNot Nothing Then genericEvent.EventID = customProperty.Value End If Next ``` One of the keys to VB.NET is that it is extremely verbose. Whenever a type is defined, it's generally using "name `As` type" . Similarly, `null` is `Nothing` in VB.NET and you do not use the equals operator to compare it in VB.NET. You use `Is` and `IsNot`. Finally, `as` casts, or upon failure, it returns `null` in C#. In VB.NET, you use `TryCast` (rather than `DirectCast`).
5,997,106
On the production servers I can use the datastore viewer to compose some GQL (as long as it's supported by the indexes) and find data on the fly. What's the best way to do this on the dev server? I'm using the Java sdk 1.4.3, and I already have remote\_api installed.
2011/05/13
[ "https://Stackoverflow.com/questions/5997106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439317/" ]
<http://www.developerfusion.com/tools/convert/csharp-to-vb/> Which will give you: ``` For Each [property] As Google.GData.Client.IExtensionElementFactory In googleEvent.ExtensionElements Dim customProperty As ExtendedProperty = TryCast([property], ExtendedProperty) If customProperty IsNot Nothing Then genericEvent.EventID = customProperty.Value End If Next ```
You were pretty close. The main issue is your variable declarations. in VB, declarations are almost reverse of C#. I haven't tested it or anything, but the following code should work. ``` For Each [property] As Google.GData.Client.IExtensionElementFactory In googleEvent.ExtensionElements Dim customProperty as ExtendedProperty = [property] If customProperty IsNot Nothing Then genericEvent.EventID = customProperty.Value End If Next ```
48,691,271
I am trying to extract HSV values from my previously collect RGB values, but I am running into an error that I don't understand. Using the code `> Hmean<-rgb2hsv(Hmean, maxColorValue=255)` I get the error: ``` Error in if (any(0 > rgb) || any(rgb > 1)) stop("rgb values must be in [0, maxColorValue]") : missing value where TRUE/FALSE needed ``` Any help would be greatly appreciated! I am new to R and am really not sure where to go from here. *EDIT* I have added my data below: ``` Hmean <- structure(list(`BIOUG06754-A02` = c(60.517, 68.521, 107.304), `BIOUG06754-A04` = c(150.321, 142.084, 136.413), `BIOUG06754-A05` = c(147.89, 133.011, 92.305), `BIOUG06754-A06` = c(122.536, 131.516, 153.172), `BIOUG06754-A07` = c(123.994, 122.671, 129.04), `BIOUG06754-A11` = c(103.295, 96.326, 97.662), `BIOUG06754-A12` = c(143.705, 125.768, 99.034), `BIOUG06754-B01` = c(80.218, 84.49, 105.947 ), `BIOUG06754-B03` = c(150.792, 153.816, 177.636), `BIOUG06754-B04` = c(171.702, 150.65, 143.737), `BIOUG06754-B05` = c(180.981, 161.6, 129.986 ), `BIOUG06754-B06` = c(138.058, 130, 130.393), `BIOUG06754-B07` = c(179.172, 170.086, 148.312), `BIOUG06754-B08` = c(124.126, 121.128, 110.269), `BIOUG06754-B10` = c(162.904, 140.356, 84.089), `BIOUG06754-B11` = c(149.631, 137.925, 122.061), `BIOUG06754-B12` = c(129.984, 125.308, 126.05), `BIOUG06754-C01` = c(146.569, 148.399, 191.916), `BIOUG06754-C02` = c(81.706, 72.88, 90.784), `BIOUG06754-C05` = c(107.256, 80.714, 111.902), `BIOUG06754-C07` = c(56.156, 61.983, 102.082 ), `BIOUG06754-C09` = c(176.229, 144.778, 98.893), `BIOUG06754-C11` = c(141.205, 144.914, 123.44), `BIOUG06754-C12` = c(140.845, 137.706, 123.588), `BIOUG06754-D01` = c(134.978, 137.257, 143.5), `BIOUG06754-D03` = c(99.99, 99.829, 94.698), `BIOUG06754-D06` = c(92.634, 70.545, 45.073), `BIOUG06754-D09` = c(172.178, 160.303, 126.69 ), `BIOUG06754-D10` = c(166.664, 151.808, 128.265), `BIOUG06754-D11` = c(160.247, 122.13, 77.719), `BIOUG06754-D12` = c(153.807, 152.699, 170.198 ), `BIOUG06754-E01` = c(135.272, 133.118, 155.628), `BIOUG06754-E05` = c(124.053, 114.822, 85.961), `BIOUG06754-E07` = c(157.281, 121.47, 53.801 ), `BIOUG06754-E08` = c(77.183, 76.687, 75.278), `BIOUG06754-E09` = c(112.063, 109.666, 107.04), `BIOUG06754-E11` = c(93.102, 87.039, 79.305 ), `BIOUG06754-F01` = c(165.828, 147.252, 119.478), `BIOUG06754-F02` = c(197.223, 185.272, 159.957), `BIOUG06754-F04` = c(152.897, 136.457, 141.096), `BIOUG06754-F05` = c(117.035, 119.651, 145.869), `BIOUG06754-F06` = c(185.506, 173.124, 157.736), `BIOUG06754-F12` = c(148.994, 140.52, 165.125), `BIOUG06754-G01` = c(128.958, 122.56, 113.381 ), `BIOUG06754-G02` = c(144.513, 136.457, 128.134), `BIOUG06754-G08` = c(113.76, 106.878, 98.195), `BIOUG06754-G09` = c(95.095, 87.19, 104.044 ), `BIOUG06754-G10` = c(106.903, 112.908, 132.635), `BIOUG06754-G12` = c(153.118, 131.854, 129.546), `BIOUG06754-H01` = c(166.928, 171.271, 174.863), `BIOUG06754-H02` = c(192.864, 166.996, 103.896), `BIOUG06754-H03` = c(119.428, 116.207, 107.578), `BIOUG06754-H06` = c(156.38, 157.738, 166.2), `BIOUG06754-H07` = c(200.05, 193.561, 180.402 ), `BIOUG06754-H08` = c(138.912, 141.456, 139.468), `BIOUG07431-A01` = c(196.442, 194.256, 198.569), `BIOUG07431-A02` = c(199.362, 203.439, 221.293), `BIOUG07431-A04` = c(110.508, 109.606, 125.026), `BIOUG07431-A05` = c(154.941, 142.16, 162.201), `BIOUG07431-A07` = c(133.31, 124.794, 166.369), `BIOUG07431-A08` = c(152.72, 145.893, 161.726), `BIOUG07431-A11` = c(193.428, 195.137, 202.514), `BIOUG07431-B01` = c(173.636, 158.312, 166.014), `BIOUG07431-B03` = c(113.928, 101.418, 119.616), `BIOUG07431-B04` = c(158.961, 149.822, 135.504), `BIOUG07431-B05` = c(181.021, 160.866, 135.597), `BIOUG07431-B06` = c(166.364, 166.912, 165.706), `BIOUG07431-B08` = c(108.665, 100.64, 109.878), `BIOUG07431-B09` = c(112.773, 116.487, 136.531), `BIOUG07431-B10` = c(108.834, 103.844, 115.001), `BIOUG07431-B11` = c(86.766, 97.206, 144.516), `BIOUG07431-C02` = c(98.251, 88.443, 127.958), `BIOUG07431-C05` = c(113.635, 117.251, 133.339), `BIOUG07431-C06` = c(115.451, 119.857, 149.481), `BIOUG07431-C08` = c(159.056, 128.007, 110.938), `BIOUG07431-C12` = c(126.557, 125.67, 126.041), `BIOUG07431-D01` = c(214.479, 191.064, 143.42), `BIOUG07431-D02` = c(180.004, 173.532, 161.336), `BIOUG07431-D03` = c(201.794, 192.762, 179.586), `BIOUG07431-D04` = c(125.512, 132.976, 163.184), `BIOUG07431-D05` = c(142.465, 124.835, 113.436), `BIOUG07431-D06` = c(185.26, 186.626, 208.822), `BIOUG07431-D07` = c(195.833, 198.765, 205.444), `BIOUG07431-D09` = c(124.785, 124.127, 144.171), `BIOUG07431-D12` = c(129.071, 140.159, 171.218), `BIOUG07431-E02` = c(182.027, 182.472, 180.621), `BIOUG07431-E03` = c(126.32, 126.024, 133.868), `BIOUG07431-E04` = c(89.118, 72.014, 46.126), `BIOUG07431-E05` = c(125.737, 117.231, 154.487 ), `BIOUG07431-E06` = c(161.714, 152.781, 130.912), `BIOUG07431-E07` = c(149.006, 144.284, 132.184), `BIOUG07431-E09` = c(118.235, 116.151, 123.239), `BIOUG07431-E12` = c(161.982, 163.57, 195.893), `BIOUG07431-F01` = c(210.534, 183.649, 136.178), `BIOUG07431-F06` = c(143.074, 129.267, 105.536), `BIOUG07431-G03` = c(194.663, 168.915, 137.132), `BIOUG07431-G06` = c(125.605, 92.018, 61.595), `BIOUG07431-G07` = c(162.248, 143.445, 169.436), `BIOUG07431-G09` = c(197.991, 197.706, 197.506), `BIOUG07431-G10` = c(156.518, 145.15, 156.341), `BIOUG07431-G11` = c(154.482, 141.215, 144.517), `BIOUG07431-H01` = c(120.332, 122.402, 140.211), `BIOUG07431-H02` = c(153.665, 148.427, 159.549), `BIOUG07431-H04` = c(239.422, 214.916, 171.416), `BIOUG07431-H06` = c(194.847, 181.091, 139.541), `BIOUG07431-H07` = c(200.076, 193.944, 181.532), `BIOUG07797-A01` = c(148.506, 146.768, 173.34), `BIOUG07797-A02` = c(147.511, 144.895, 189.464), `BIOUG07797-A03` = c(222.678, 225.497, 230.171), `BIOUG07797-A05` = c(119.967, 131.053, 203.64), `BIOUG07797-A08` = c(104.015, 108.071, 124.549), `BIOUG07797-A09` = c(164.519, 159.228, 140.04), `BIOUG07797-A11` = c(189.19, 182.955, 189.946), `BIOUG07797-B01` = c(106.99, 110.57, 141.549), `BIOUG07797-B02` = c(113.587, 110.997, 149.402), `BIOUG07797-C01` = c(117.026, 114.161, 128.523), `BIOUG07797-C04` = c(83.18, 84.456, 111.268), `BIOUG07797-C05` = c(118.447, 119.369, 156.932), `BIOUG07797-C06` = c(176.7, 165.73, 139.284 ), `BIOUG07797-C11` = c(148.172, 127.719, 122.872), `BIOUG07797-D02` = c(106.939, 95.452, 108.28), `BIOUG07797-D10` = c(143.813, 130.423, 111.83 ), `BIOUG07797-F03` = c(78.894, 54.359, 50.642), `BIOUG07797-F04` = c(145.08, 123.273, 117.647), `BIOUG07797-F06` = c(235.565, 180.099, 56.442), `BIOUG07797-F07` = c(180.997, 183.258, 183.278), `BIOUG07797-G11` = c(170.54, 175.451, 170.098), `BIOUG07797-H01` = c(190.966, 188.429, 166.054), `BIOUG07797-H09` = c(90.894, 85.603, 111.644 ), `BIOUG09330-A02` = c(78.074, 91.958, 152.859), `BIOUG09330-A03` = c(117.371, 130.345, 172.74), `BIOUG09330-A04` = c(91.953, 110.488, 159.267 ), `BIOUG09330-A05` = c(108.764, 95.986, 109.759), `BIOUG09330-A06` = c(150.302, 107.83, 73.904), `BIOUG09330-A07` = c(97.401, 120.961, 211.18 ), `BIOUG09330-A09` = c(74.834, 79.806, 120.349), `BIOUG09330-A10` = c(95.294, 96.306, 144.771), `BIOUG09330-A11` = c(64.172, 45.898, 71.995 ), `BIOUG09330-A12` = c(117.116, 126.698, 168.934), `BIOUG09330-B01` = c(52.654, 64.766, 128.408), `BIOUG09330-B02` = c(107.182, 133.682, 188.383), `BIOUG09330-B04` = c(125.463, 91.091, 43.414), `BIOUG09330-B05` = c(NA_real_, NA_real_, NA_real_), `BIOUG09330-B06` = c(56.263, 54.981, 81.805), `BIOUG09330-B07` = c(162.31, 159.495, 166.396 ), `BIOUG09330-B08` = c(125.672, 122.209, 116.596), `BIOUG09330-B09` = c(135.056, 129.756, 162.686), `BIOUG09330-B10` = c(202.435, 208.733, 241.3), `BIOUG09330-B11` = c(169.697, 156.222, 141.06), `BIOUG09330-B12` = c(128.235, 102.118, 106.082), `BIOUG09330-C01` = c(98.755, 122.772, 209.765), `BIOUG09330-C02` = c(NA_real_, NA_real_, NA_real_ ), `BIOUG09330-C05` = c(158.578, 130.13, 69.21), `BIOUG09330-C08` = c(103.718, 117.53, 147.786), `BIOUG09330-D02` = c(117.738, 114.214, 118.959), `BIOUG09330-D04` = c(130.504, 122.31, 138.672), `BIOUG09330-D06` = c(218.095, 195.467, 144.224), `BIOUG09330-D07` = c(157.568, 145.151, 91.566), `BIOUG09330-D08` = c(175.808, 172.062, 161.954), `BIOUG09330-D09` = c(144.897, 157.836, 189.74), `BIOUG09330-D11` = c(76.909, 88.817, 121.806), `BIOUG09330-D12` = c(124.881, 126.963, 171.977), `BIOUG09330-E05` = c(129.372, 127.583, 187.464), `BIOUG09330-E08` = c(88.864, 103.971, 212.299), `BIOUG09330-E09` = c(64.557, 72.148, 138.387), `BIOUG09330-E11` = c(135.383, 141.872, 165.028), `BIOUG09330-E12` = c(157.918, 167.997, 181.808), `BIOUG09330-F04` = c(70.144, 79.535, 180.141), `BIOUG09330-F05` = c(70.921, 70.844, 104.806), `BIOUG09330-F09` = c(124.519, 129.736, 189.402), `BIOUG09330-F10` = c(210.979, 205.764, 212.236), `BIOUG09330-F11` = c(190.944, 183.007, 157.038), `BIOUG09330-F12` = c(211.616, 155.883, 39.493), `BIOUG09330-G01` = c(108.666, 120.852, 159.902), `BIOUG09330-G02` = c(156.677, 146.856, 135.241), `BIOUG09330-G03` = c(130.527, 137.194, 144.195), `BIOUG09330-G04` = c(84.576, 81.307, 105.66), `BIOUG09330-G05` = c(144.604, 147.933, 177.82), `BIOUG09330-G06` = c(158.099, 155.194, 175.577), `BIOUG09330-G07` = c(74.709, 67.784, 102.697), `BIOUG09330-G08` = c(76.496, 74.44, 107.494), `BIOUG09330-G09` = c(183.169, 192.008, 235.085), `BIOUG09330-G10` = c(184.362, 180.48, 159.234), `BIOUG09330-G12` = c(77.055, 86.239, 143.91), `BIOUG09330-H06` = c(74.967, 79.455, 144.986), `BIOUG09330-H07` = c(70.484, 70.173, 105.897 ), `BIOUG09330-H09` = c(174.575, 150.184, 80.233), `BIOUG09331-A03` = c(129.706, 113.527, 74.197), `BIOUG09331-A04` = c(136.851, 129.773, 117.237), `BIOUG09331-A05` = c(157.295, 147.808, 124.672), `BIOUG09331-A06` = c(92.13, 90.853, 93.149), `BIOUG09331-A07` = c(144.478, 120.684, 78.015), `BIOUG09331-A08` = c(136.908, 122.667, 88.92), `BIOUG09331-A09` = c(135.86, 106.256, 55.891), `BIOUG09331-A10` = c(203.39, 157.816, 91.879), `BIOUG09331-A11` = c(138.371, 123.186, 96.59), `BIOUG09331-A12` = c(95.404, 88.144, 78.755), `BIOUG09331-B01` = c(91.657, 76.132, 73.637), `BIOUG09331-B03` = c(114.362, 97.15, 87.333 ), `BIOUG09331-B04` = c(125.27, 114.192, 111.006), `BIOUG09331-B05` = c(238.213, 199.398, 99.51), `BIOUG09331-B06` = c(162.797, 133.397, 96.207 ), `BIOUG09331-B07` = c(170.996, 152.071, 91.138), `BIOUG09331-B08` = c(90.596, 83.036, 85.444), `BIOUG09331-B09` = c(78.688, 71.075, 89.184 ), `BIOUG09331-B10` = c(125.612, 113.445, 109.073), `BIOUG09331-B11` = c(145.36, 129.069, 106.892), `BIOUG09331-B12` = c(106.722, 100.317, 89.757), `BIOUG09331-C01` = c(218.155, 179.369, 88.206), `BIOUG09331-C03` = c(90.819, 93.85, 127.7), `BIOUG09331-C04` = c(141.697, 133.081, 128.473), `BIOUG09331-C08` = c(80.76, 78.165, 84.414 ), `BIOUG09331-C09` = c(99.405, 91.629, 88.325), `BIOUG09331-C10` = c(160.779, 152.102, 128.027), `BIOUG09331-C11` = c(146.007, 121.818, 123.986), `BIOUG09331-C12` = c(155.322, 126.561, 76.122), `BIOUG09331-D01` = c(114.51, 108.85, 106.159), `BIOUG09331-D02` = c(168.561, 158.569, 142.675), `BIOUG09331-D03` = c(93.604, 77.639, 72.308 ), `BIOUG09331-D04` = c(115.836, 106.453, 97.403), `BIOUG09331-D05` = c(201.406, 168.583, 121.714), `BIOUG09331-D06` = c(64.72, 39.534, 61.58 ), `BIOUG09331-D07` = c(104.396, 90.888, 88.357), `BIOUG09331-D08` = c(190.058, 162.695, 122.753), `BIOUG09331-D09` = c(130.358, 119.073, 113.842), `BIOUG09331-D10` = c(208.173, 184.573, 150.762), `BIOUG09331-D11` = c(75.621, 68.526, 100.973), `BIOUG09331-D12` = c(120.384, 113.948, 126.971), `BIOUG09331-E02` = c(131.588, 105.849, 112.459), `BIOUG09331-E05` = c(165.058, 153.182, 136.807), `BIOUG09331-E08` = c(205.842, 149.21, 46.914), `BIOUG09331-E09` = c(119.88, 96.932, 81.06), `BIOUG09331-E10` = c(142.077, 129.643, 113.374 ), `BIOUG09331-E11` = c(174.945, 158.418, 140.231), `BIOUG09331-E12` = c(190.955, 157.802, 101.379), `BIOUG09331-F02` = c(149.787, 134.032, 118.371), `BIOUG09331-F03` = c(165.562, 153.43, 129.294), `BIOUG09331-F04` = c(137.762, 130.078, 114.159), `BIOUG09331-F05` = c(154.205, 137.268, 113.15), `BIOUG09331-F06` = c(139.79, 114.26, 79.178 ), `BIOUG09331-F07` = c(164.205, 143.319, 124.28), `BIOUG09331-F08` = c(103.566, 91.445, 117.365), `BIOUG09331-F09` = c(129.748, 116.184, 112.51), `BIOUG09331-F10` = c(89.52, 82.218, 92.811), `BIOUG09331-G03` = c(193.037, 167.988, 161.19), `BIOUG09331-G04` = c(66.484, 61.662, 107.38 ), `BIOUG09331-G05` = c(78.386, 79.355, 127.106), `BIOUG09331-G06` = c(130.345, 121.306, 157.942), `BIOUG09331-G10` = c(228.768, 220.396, 213.442), `BIOUG09331-G11` = c(74.002, 66.019, 115.924), `BIOUG09331-H02` = c(205.078, 182.418, 134.441), `BIOUG09331-H06` = c(175.326, 173.91, 203.724), `BIOUG09331-H08` = c(173.58, 158.376, 136.998 ), `BIOUG09331-H09` = c(81.942, 83.35, 141.956), `BIOUG09331-H10` = c(54.907, 59.226, 100.034), `BIOUG09331-H11` = c(104.378, 99.155, 120 ), `BIOUG09332-A01` = c(144.726, 137.16, 172.673), `BIOUG09332-A03` = c(165.363, 159.332, 152.342), `BIOUG09332-A05` = c(199.72, 201.405, 204.246), `BIOUG09332-A06` = c(161.826, 164.125, 180.692), `BIOUG09332-A07` = c(136.393, 145.575, 171.102), `BIOUG09332-A08` = c(128.538, 131.427, 152.795), `BIOUG09332-A10` = c(184.266, 174.629, 162.196), `BIOUG09332-B03` = c(208.574, 207.05, 205.724), `BIOUG09332-B05` = c(101.794, 110.731, 155.385), `BIOUG09332-B07` = c(122.239, 112.155, 127.472), `BIOUG09332-B09` = c(187.713, 182.566, 170.627), `BIOUG09332-B11` = c(133.217, 133.466, 129.422), `BIOUG09332-C01` = c(101.814, 91.709, 107.163), `BIOUG09332-C03` = c(91.116, 96.167, 131.836), `BIOUG09332-C05` = c(160.936, 156.711, 152.594), `BIOUG09332-C06` = c(149.988, 137.356, 110.038), `BIOUG09332-C07` = c(126.787, 121.185, 127.856), `BIOUG09332-C09` = c(108.19, 120.506, 190.562), `BIOUG09332-C11` = c(175.914, 167.613, 170.927), `BIOUG09332-C12` = c(82.267, 78.821, 94.969), `BIOUG09332-D01` = c(68.758, 70.229, 93.4), `BIOUG09332-D09` = c(144.802, 138.01, 151.703 ), `BIOUG09332-E01` = c(88.358, 92.77, 132.612), `BIOUG09332-E05` = c(106.86, 59.931, 66.577), `BIOUG09332-E09` = c(197.423, 189.931, 176.184 ), `BIOUG09332-E10` = c(151.695, 121.97, 69.789), `BIOUG09332-E11` = c(74.158, 63.902, 68.372), `BIOUG09332-F06` = c(109.16, 120.619, 174.715 ), `BIOUG09332-F09` = c(144.682, 120.658, 129.593), `BIOUG09332-F11` = c(137.976, 113.727, 87.593), `BIOUG09332-G02` = c(182.113, 145.291, 84.664), `BIOUG09332-G03` = c(150.52, 121.721, 96.076), `BIOUG09332-G04` = c(175.154, 165.939, 163.944), `BIOUG09332-G05` = c(217.682, 203.291, 184.977), `BIOUG09332-G06` = c(154.436, 116.008, 59.53), `BIOUG09332-G08` = c(177.95, 142.221, 93.299), `BIOUG09332-G09` = c(213.532, 166.837, 79.52), `BIOUG09332-G11` = c(194.616, 164.073, 126.89 ), `BIOUG09332-H01` = c(151.457, 133.94, 142.631), `BIOUG09332-H06` = c(99.24, 68.681, 52.919), `BIOUG09332-H07` = c(218.904, 150.498, 4.059 ), `BIOUG09332-H08` = c(173.864, 142.466, 109.555), `BIOUG09332-H09` = c(195.81, 156.113, 72.609), `BIOUG09332-H10` = c(178.388, 164.201, 154.31), `BIOUG09332-H11` = c(149.498, 136.439, 122.352)), .Names = c("BIOUG06754-A02", "BIOUG06754-A04", "BIOUG06754-A05", "BIOUG06754-A06", "BIOUG06754-A07", "BIOUG06754-A11", "BIOUG06754-A12", "BIOUG06754-B01", "BIOUG06754-B03", "BIOUG06754-B04", "BIOUG06754-B05", "BIOUG06754-B06", "BIOUG06754-B07", "BIOUG06754-B08", "BIOUG06754-B10", "BIOUG06754-B11", "BIOUG06754-B12", "BIOUG06754-C01", "BIOUG06754-C02", "BIOUG06754-C05", "BIOUG06754-C07", "BIOUG06754-C09", "BIOUG06754-C11", "BIOUG06754-C12", "BIOUG06754-D01", "BIOUG06754-D03", "BIOUG06754-D06", "BIOUG06754-D09", "BIOUG06754-D10", "BIOUG06754-D11", "BIOUG06754-D12", "BIOUG06754-E01", "BIOUG06754-E05", "BIOUG06754-E07", "BIOUG06754-E08", "BIOUG06754-E09", "BIOUG06754-E11", "BIOUG06754-F01", "BIOUG06754-F02", "BIOUG06754-F04", "BIOUG06754-F05", "BIOUG06754-F06", "BIOUG06754-F12", "BIOUG06754-G01", "BIOUG06754-G02", "BIOUG06754-G08", "BIOUG06754-G09", "BIOUG06754-G10", "BIOUG06754-G12", "BIOUG06754-H01", "BIOUG06754-H02", "BIOUG06754-H03", "BIOUG06754-H06", "BIOUG06754-H07", "BIOUG06754-H08", "BIOUG07431-A01", "BIOUG07431-A02", "BIOUG07431-A04", "BIOUG07431-A05", "BIOUG07431-A07", "BIOUG07431-A08", "BIOUG07431-A11", "BIOUG07431-B01", "BIOUG07431-B03", "BIOUG07431-B04", "BIOUG07431-B05", "BIOUG07431-B06", "BIOUG07431-B08", "BIOUG07431-B09", "BIOUG07431-B10", "BIOUG07431-B11", "BIOUG07431-C02", "BIOUG07431-C05", "BIOUG07431-C06", "BIOUG07431-C08", "BIOUG07431-C12", "BIOUG07431-D01", "BIOUG07431-D02", "BIOUG07431-D03", "BIOUG07431-D04", "BIOUG07431-D05", "BIOUG07431-D06", "BIOUG07431-D07", "BIOUG07431-D09", "BIOUG07431-D12", "BIOUG07431-E02", "BIOUG07431-E03", "BIOUG07431-E04", "BIOUG07431-E05", "BIOUG07431-E06", "BIOUG07431-E07", "BIOUG07431-E09", "BIOUG07431-E12", "BIOUG07431-F01", "BIOUG07431-F06", "BIOUG07431-G03", "BIOUG07431-G06", "BIOUG07431-G07", "BIOUG07431-G09", "BIOUG07431-G10", "BIOUG07431-G11", "BIOUG07431-H01", "BIOUG07431-H02", "BIOUG07431-H04", "BIOUG07431-H06", "BIOUG07431-H07", "BIOUG07797-A01", "BIOUG07797-A02", "BIOUG07797-A03", "BIOUG07797-A05", "BIOUG07797-A08", "BIOUG07797-A09", "BIOUG07797-A11", "BIOUG07797-B01", "BIOUG07797-B02", "BIOUG07797-C01", "BIOUG07797-C04", "BIOUG07797-C05", "BIOUG07797-C06", "BIOUG07797-C11", "BIOUG07797-D02", "BIOUG07797-D10", "BIOUG07797-F03", "BIOUG07797-F04", "BIOUG07797-F06", "BIOUG07797-F07", "BIOUG07797-G11", "BIOUG07797-H01", "BIOUG07797-H09", "BIOUG09330-A02", "BIOUG09330-A03", "BIOUG09330-A04", "BIOUG09330-A05", "BIOUG09330-A06", "BIOUG09330-A07", "BIOUG09330-A09", "BIOUG09330-A10", "BIOUG09330-A11", "BIOUG09330-A12", "BIOUG09330-B01", "BIOUG09330-B02", "BIOUG09330-B04", "BIOUG09330-B05", "BIOUG09330-B06", "BIOUG09330-B07", "BIOUG09330-B08", "BIOUG09330-B09", "BIOUG09330-B10", "BIOUG09330-B11", "BIOUG09330-B12", "BIOUG09330-C01", "BIOUG09330-C02", "BIOUG09330-C05", "BIOUG09330-C08", "BIOUG09330-D02", "BIOUG09330-D04", "BIOUG09330-D06", "BIOUG09330-D07", "BIOUG09330-D08", "BIOUG09330-D09", "BIOUG09330-D11", "BIOUG09330-D12", "BIOUG09330-E05", "BIOUG09330-E08", "BIOUG09330-E09", "BIOUG09330-E11", "BIOUG09330-E12", "BIOUG09330-F04", "BIOUG09330-F05", "BIOUG09330-F09", "BIOUG09330-F10", "BIOUG09330-F11", "BIOUG09330-F12", "BIOUG09330-G01", "BIOUG09330-G02", "BIOUG09330-G03", "BIOUG09330-G04", "BIOUG09330-G05", "BIOUG09330-G06", "BIOUG09330-G07", "BIOUG09330-G08", "BIOUG09330-G09", "BIOUG09330-G10", "BIOUG09330-G12", "BIOUG09330-H06", "BIOUG09330-H07", "BIOUG09330-H09", "BIOUG09331-A03", "BIOUG09331-A04", "BIOUG09331-A05", "BIOUG09331-A06", "BIOUG09331-A07", "BIOUG09331-A08", "BIOUG09331-A09", "BIOUG09331-A10", "BIOUG09331-A11", "BIOUG09331-A12", "BIOUG09331-B01", "BIOUG09331-B03", "BIOUG09331-B04", "BIOUG09331-B05", "BIOUG09331-B06", "BIOUG09331-B07", "BIOUG09331-B08", "BIOUG09331-B09", "BIOUG09331-B10", "BIOUG09331-B11", "BIOUG09331-B12", "BIOUG09331-C01", "BIOUG09331-C03", "BIOUG09331-C04", "BIOUG09331-C08", "BIOUG09331-C09", "BIOUG09331-C10", "BIOUG09331-C11", "BIOUG09331-C12", "BIOUG09331-D01", "BIOUG09331-D02", "BIOUG09331-D03", "BIOUG09331-D04", "BIOUG09331-D05", "BIOUG09331-D06", "BIOUG09331-D07", "BIOUG09331-D08", "BIOUG09331-D09", "BIOUG09331-D10", "BIOUG09331-D11", "BIOUG09331-D12", "BIOUG09331-E02", "BIOUG09331-E05", "BIOUG09331-E08", "BIOUG09331-E09", "BIOUG09331-E10", "BIOUG09331-E11", "BIOUG09331-E12", "BIOUG09331-F02", "BIOUG09331-F03", "BIOUG09331-F04", "BIOUG09331-F05", "BIOUG09331-F06", "BIOUG09331-F07", "BIOUG09331-F08", "BIOUG09331-F09", "BIOUG09331-F10", "BIOUG09331-G03", "BIOUG09331-G04", "BIOUG09331-G05", "BIOUG09331-G06", "BIOUG09331-G10", "BIOUG09331-G11", "BIOUG09331-H02", "BIOUG09331-H06", "BIOUG09331-H08", "BIOUG09331-H09", "BIOUG09331-H10", "BIOUG09331-H11", "BIOUG09332-A01", "BIOUG09332-A03", "BIOUG09332-A05", "BIOUG09332-A06", "BIOUG09332-A07", "BIOUG09332-A08", "BIOUG09332-A10", "BIOUG09332-B03", "BIOUG09332-B05", "BIOUG09332-B07", "BIOUG09332-B09", "BIOUG09332-B11", "BIOUG09332-C01", "BIOUG09332-C03", "BIOUG09332-C05", "BIOUG09332-C06", "BIOUG09332-C07", "BIOUG09332-C09", "BIOUG09332-C11", "BIOUG09332-C12", "BIOUG09332-D01", "BIOUG09332-D09", "BIOUG09332-E01", "BIOUG09332-E05", "BIOUG09332-E09", "BIOUG09332-E10", "BIOUG09332-E11", "BIOUG09332-F06", "BIOUG09332-F09", "BIOUG09332-F11", "BIOUG09332-G02", "BIOUG09332-G03", "BIOUG09332-G04", "BIOUG09332-G05", "BIOUG09332-G06", "BIOUG09332-G08", "BIOUG09332-G09", "BIOUG09332-G11", "BIOUG09332-H01", "BIOUG09332-H06", "BIOUG09332-H07", "BIOUG09332-H08", "BIOUG09332-H09", "BIOUG09332-H10", "BIOUG09332-H11" ), row.names = c("Red", "Green", "Blue"), class = "data.frame") ```
2018/02/08
[ "https://Stackoverflow.com/questions/48691271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8059981/" ]
These data would be much easier to work with if each sample was a row, and the colors were on the columns: ``` Hmean.transpose <- as.data.frame(t(Hmean)) head(Hmean.transpose) Red Green Blue BIOUG06754-A02 60.517 68.521 107.304 BIOUG06754-A04 150.321 142.084 136.413 BIOUG06754-A05 147.890 133.011 92.305 BIOUG06754-A06 122.536 131.516 153.172 BIOUG06754-A07 123.994 122.671 129.040 BIOUG06754-A11 103.295 96.326 97.662 ... ``` Now it's easier to see which rows have `NA` values: ``` subset(Hmean.transpose, is.na(Red)) Red Green Blue BIOUG09330-B05 NA NA NA BIOUG09330-C02 NA NA NA ``` If we filter these out, the color conversion will work as expected: ``` Hmean.filter <- subset(Hmean.transpose, !is.na(Red)) data.hsv <- with(Hmean.filter, rgb2hsv(Red, Green, Blue)) ```
If you just want to drop NA values, you can exclude columns that have NA values. For example ``` sapply(Filter(function(x) any(!is.na(x)), Hmean), rgb2hsv, maxColorValue=255) ``` Or using the tidyverse purrr functions, ``` library(purrr) Hmean %>% discard(~any(is.na(.))) %>% map_dfr(rgb2hsv, maxColorValue=255) ```
13,470
Какие существуют слова с одинаковым значением, но ударения ставятся по-разному, например: щавель на А, щавель на Е?
2012/12/12
[ "https://rus.stackexchange.com/questions/13470", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/1439/" ]
Не понимаю, в чём вопрос. Вариант ударения в этом слове всего один — щаве́ль. Разноместное ударение допустимо, например, в слове *"творог"*. Если спрашивается термин, коим именуется такое явление, то его называют по-разному: вариативность ударения, разноместное ударение и др.
> > слова с одинаковым значением но ударения ставятся поразному. > > > > > Здесь не хватает запятой, и слово "по-разному" пишется через дефис. Цитируйте, пожалуйста, без ошибок.
13,470
Какие существуют слова с одинаковым значением, но ударения ставятся по-разному, например: щавель на А, щавель на Е?
2012/12/12
[ "https://rus.stackexchange.com/questions/13470", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/1439/" ]
> > слова с одинаковым значением, но ударения ставятся по-разному > > > Если Вы проедете по славянским странам, то Вы сможете услышать множество слов с одинаковым значением и одинаковым (или почти одинаковым) написанием, но с самыми неожиданными ударениями. И даже в разных регионах одной и той же страны (России, Украины, бывшей Югославии...). Например, *крапИва*, *кропивА* (укр.) и т. п. и мн. др. И конкретно про **щавель.** Цитата из [Википедии](http://ru.wikipedia.org/wiki/%D0%A9%D0%B0%D0%B2%D0%B5%D0%BB%D1%8C): > > щаве́ль, в некоторых регионах России распространён другой вариант произношения — ща́вель > > > Итак, литературный вариант -- это *щаве́ль*, но кое-где в местных говорах произносят *ща́вель*. Если интересно знать, то абсолютно такая же ситуация с этим словом и на Украине. Я полез в словари, подумал, что, возможно, *ща́вель* — это украинизм. Нет, литературное укр. — *щаве́ль.* Хотя в живой разговорной украинской речи говорят и так и так.
> > слова с одинаковым значением но ударения ставятся поразному. > > > > > Здесь не хватает запятой, и слово "по-разному" пишется через дефис. Цитируйте, пожалуйста, без ошибок.
5,601,803
I have a small gallery website but the amount of images in directory differs from that accounted for in database by around 150 so I was wondering if there is a way to find out/list what files are in a directory that are "not" in the database (or vice versa). basic db structure: * **images** + id + images image names are stored in db as "imagename.jpg" and the images themselves are stored in images directory images/
2011/04/08
[ "https://Stackoverflow.com/questions/5601803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/576638/" ]
Put file names from server in one array and files from database in another. Use [array\_diff()](http://www.php.net/manual/en/function.array-diff.php) to get result. Example (PHP): ``` $files_db = array("car.jpg", "bike.jpg", "plane.jpg", "ship.jpg", "tank.jpg"); $files_server = array("car.jpg", "bike.jpg", "ship.jpg", "rocket.jpg"); ``` Use ``` print_r(array_diff($files_db, $files_server)); ``` Output ``` Array ( [2] => plane.jpg [4] => tank.jpg ) ``` Or (vice versa) ``` print_r(array_diff($files_server, $files_db)); ``` Output ``` Array ( [3] => rocket.jpg ) ```
If this is likely a one-off problem, I'd solve this with a half-assed solution, using first a little SQL script: ``` SELECT filename FROM images; ``` and ask the database client [`mysql`](http://dev.mysql.com/doc/refman/5.5/en/mysql.html) or [`psql`](http://developer.postgresql.org/pgdocs/postgres/app-psql.html) or whatever to dump the output as plain text to a file. (Shell redirection may do the job if you can't easily find your database client's 'dump to file' command.) Then I'd get the directory listing: ``` ls /path/to/images/ > ls_files ``` Sort both: ``` sort db_files > db_files.sorted sort ls_files > ls_files.sorted ``` Then run `diff(1)` to see which files are referenced where: ``` diff -u ls_files.sorted db_files.sorted ``` Lines prefixed with a `+` or `-` are in one but not the other. You might need edit the SQL output or the `ls` output to get one to match the other. If your editor has a tool like `vim`'s `^V` block select, some of those editing tasks can be simplified, but sometimes just running `ls` from another directory can help prepend the right directory structure in front of every filename.
32,717,584
I have an array like this: ``` $templateStyleArr = array( 0 => array( 'text' => 'General Text', 'default_value' => '#444', 'scopval' => 'general', ), 1 => array( 'text' => 'Accent Color', 'default_value' => '#c91a1a', 'scopval' => 'Accent', ), 2 => array( 'text' => 'Button Hover', 'default_value' => '#2ec72e', 'scopval' => 'dark_btn_hover', ), 3 => array( 'text' => 'Button Text', 'default_value' => '#3300f5', 'scopval' => 'btn_txt', ), ) ``` I want to save this array to data base in Json format using PHP.I am using json\_encode function. Json saved perfectly.Problem is When I try to decode the saved json(using json\_decode),I am not getting the above array back.
2015/09/22
[ "https://Stackoverflow.com/questions/32717584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5320720/" ]
Referring to [the manual](http://php.net/manual/en/function.json-decode.php), you may need to set the `assoc` parameter to `TRUE` so that the returned object will be converted into an associative array. ``` $array = json_decode($json_string_from_db, TRUE); ```
If you want to store just the array as string in the database you can try [serialize()](http://php.net/manual/de/function.serialize.php), with unserialize you'll get the exactly same array as return value ``` $templateStyleArr = array( 0 => array( 'text' => 'General Text', 'default_value' => '#444', 'scopval' => 'general', ), 1 => array( 'text' => 'Accent Color', 'default_value' => '#c91a1a', 'scopval' => 'Accent', ), 2 => array( 'text' => 'Button Hover', 'default_value' => '#2ec72e', 'scopval' => 'dark_btn_hover', ), 3 => array( 'text' => 'Button Text', 'default_value' => '#3300f5', 'scopval' => 'btn_txt', ), ); $string = serialize( $templateStyleArr ); var_dump( unserialize( $string ) ); ``` If the array indexes are really just numbers you can use this: ``` $string = json_encode( $templateStyleArr ); $arrayFromJson = json_decode( $string ); foreach( $arrayFromJson as $index => $jsonObject ) { // cast object to array $arrayFromJson[$index] = (array) $jsonObject; } var_dump( $arrayFromJson ); ```
32,717,584
I have an array like this: ``` $templateStyleArr = array( 0 => array( 'text' => 'General Text', 'default_value' => '#444', 'scopval' => 'general', ), 1 => array( 'text' => 'Accent Color', 'default_value' => '#c91a1a', 'scopval' => 'Accent', ), 2 => array( 'text' => 'Button Hover', 'default_value' => '#2ec72e', 'scopval' => 'dark_btn_hover', ), 3 => array( 'text' => 'Button Text', 'default_value' => '#3300f5', 'scopval' => 'btn_txt', ), ) ``` I want to save this array to data base in Json format using PHP.I am using json\_encode function. Json saved perfectly.Problem is When I try to decode the saved json(using json\_decode),I am not getting the above array back.
2015/09/22
[ "https://Stackoverflow.com/questions/32717584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5320720/" ]
Referring to [the manual](http://php.net/manual/en/function.json-decode.php), you may need to set the `assoc` parameter to `TRUE` so that the returned object will be converted into an associative array. ``` $array = json_decode($json_string_from_db, TRUE); ```
basicly your json encode will convert array to object when you decode it, so you need create function for generate object to array, you should try this function where will convert correct ``` function to_array( $object ){ if( !is_object( $object ) && !is_array( $object ) ){ return $object; } if( is_object( $object ) ){ $object = get_object_vars( $object ); } return array_map( 'to_array', $object ); } $array = to_array( json_decode($fromdb) ); print_r( $array ); ``` it's work okay for me so let's try :)
32,717,584
I have an array like this: ``` $templateStyleArr = array( 0 => array( 'text' => 'General Text', 'default_value' => '#444', 'scopval' => 'general', ), 1 => array( 'text' => 'Accent Color', 'default_value' => '#c91a1a', 'scopval' => 'Accent', ), 2 => array( 'text' => 'Button Hover', 'default_value' => '#2ec72e', 'scopval' => 'dark_btn_hover', ), 3 => array( 'text' => 'Button Text', 'default_value' => '#3300f5', 'scopval' => 'btn_txt', ), ) ``` I want to save this array to data base in Json format using PHP.I am using json\_encode function. Json saved perfectly.Problem is When I try to decode the saved json(using json\_decode),I am not getting the above array back.
2015/09/22
[ "https://Stackoverflow.com/questions/32717584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5320720/" ]
If you want to store just the array as string in the database you can try [serialize()](http://php.net/manual/de/function.serialize.php), with unserialize you'll get the exactly same array as return value ``` $templateStyleArr = array( 0 => array( 'text' => 'General Text', 'default_value' => '#444', 'scopval' => 'general', ), 1 => array( 'text' => 'Accent Color', 'default_value' => '#c91a1a', 'scopval' => 'Accent', ), 2 => array( 'text' => 'Button Hover', 'default_value' => '#2ec72e', 'scopval' => 'dark_btn_hover', ), 3 => array( 'text' => 'Button Text', 'default_value' => '#3300f5', 'scopval' => 'btn_txt', ), ); $string = serialize( $templateStyleArr ); var_dump( unserialize( $string ) ); ``` If the array indexes are really just numbers you can use this: ``` $string = json_encode( $templateStyleArr ); $arrayFromJson = json_decode( $string ); foreach( $arrayFromJson as $index => $jsonObject ) { // cast object to array $arrayFromJson[$index] = (array) $jsonObject; } var_dump( $arrayFromJson ); ```
basicly your json encode will convert array to object when you decode it, so you need create function for generate object to array, you should try this function where will convert correct ``` function to_array( $object ){ if( !is_object( $object ) && !is_array( $object ) ){ return $object; } if( is_object( $object ) ){ $object = get_object_vars( $object ); } return array_map( 'to_array', $object ); } $array = to_array( json_decode($fromdb) ); print_r( $array ); ``` it's work okay for me so let's try :)
671,589
Here's the stupid thing I did: I deleted many folders inside the icon folder, with root privileges, and now some icons are gone, but not the main ones, the ones from compiz for instance, or some from top notification bar, like the skype one. I looked for days to find a solution to restore the icons folder, or to find the default Ubuntu icons to put them back to the folder, but I have found none. I use Ubuntu Tweak Tool to switch between themes, icons, or cursors, and it works perfectly, but no theme or icon pack seems to bring back some of the icons like I mentioned before. I hope there is a way to reinstall ubuntu default icon packs. Thanks in advance ;)
2015/09/08
[ "https://askubuntu.com/questions/671589", "https://askubuntu.com", "https://askubuntu.com/users/159413/" ]
Unfortunately, applications like compiz usually install their own icons. You can install these icons by re-installing the application to replace the missing files. ``` sudo apt-get update sudo apt-get install --reinstall compizconfig-settings-manager ``` That should work if the files are missing, however, if it doesn't, you can download the application and manually replace the files like so: ``` cd mkdir aptget;cd aptget apt-get download compizconfig-settings-manager ar xvf * tar xvf data* sudo cp -rT ./usr/share/ /usr/share/ cd .. rm -R aptget ```
You can download an unzip in the : `/usr/share/icons` download default icons from here: <http://4uploader.com/dl/257/icons.7z>
671,589
Here's the stupid thing I did: I deleted many folders inside the icon folder, with root privileges, and now some icons are gone, but not the main ones, the ones from compiz for instance, or some from top notification bar, like the skype one. I looked for days to find a solution to restore the icons folder, or to find the default Ubuntu icons to put them back to the folder, but I have found none. I use Ubuntu Tweak Tool to switch between themes, icons, or cursors, and it works perfectly, but no theme or icon pack seems to bring back some of the icons like I mentioned before. I hope there is a way to reinstall ubuntu default icon packs. Thanks in advance ;)
2015/09/08
[ "https://askubuntu.com/questions/671589", "https://askubuntu.com", "https://askubuntu.com/users/159413/" ]
I solved it: Downloaded the ubuntu 14.04 iso. Mounted it with VirtualBox, used root to go to the icons folder, archive it, uploaded it to the internet. Then downloaded it to my OS, and just copied it to the 'shared' folder. Basically I restored the icons folder by copying it from the ubuntu iso file. ;)
You can download an unzip in the : `/usr/share/icons` download default icons from here: <http://4uploader.com/dl/257/icons.7z>
671,589
Here's the stupid thing I did: I deleted many folders inside the icon folder, with root privileges, and now some icons are gone, but not the main ones, the ones from compiz for instance, or some from top notification bar, like the skype one. I looked for days to find a solution to restore the icons folder, or to find the default Ubuntu icons to put them back to the folder, but I have found none. I use Ubuntu Tweak Tool to switch between themes, icons, or cursors, and it works perfectly, but no theme or icon pack seems to bring back some of the icons like I mentioned before. I hope there is a way to reinstall ubuntu default icon packs. Thanks in advance ;)
2015/09/08
[ "https://askubuntu.com/questions/671589", "https://askubuntu.com", "https://askubuntu.com/users/159413/" ]
I solved it: Downloaded the ubuntu 14.04 iso. Mounted it with VirtualBox, used root to go to the icons folder, archive it, uploaded it to the internet. Then downloaded it to my OS, and just copied it to the 'shared' folder. Basically I restored the icons folder by copying it from the ubuntu iso file. ;)
Unfortunately, applications like compiz usually install their own icons. You can install these icons by re-installing the application to replace the missing files. ``` sudo apt-get update sudo apt-get install --reinstall compizconfig-settings-manager ``` That should work if the files are missing, however, if it doesn't, you can download the application and manually replace the files like so: ``` cd mkdir aptget;cd aptget apt-get download compizconfig-settings-manager ar xvf * tar xvf data* sudo cp -rT ./usr/share/ /usr/share/ cd .. rm -R aptget ```
72,793,337
It is 2022/06/28 actually 28th of June 2022; I noticed when I try to get the current time from Python console two different results are possible the Eastern Time (Toronto, Montreal and New York). So what is the difference between these two parameters? I am going to answer the question:
2022/06/28
[ "https://Stackoverflow.com/questions/72793337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284584/" ]
"EST" is not accurate if you want to get the current time in New York because it represents Eastern Standard Time (UTC-05:00), which is one hour behind Eastern Daylight Time (UTC-04:00). Due to daylight savings, New York will observe either EST or EDT depending on the time of year. "US/Eastern" is preferable to "EST" as it represents the Eastern Time Zone in the United States and will account for any shifts due to daylight savings. However, the zone representing "US/Eastern" has been [renamed](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) to "America/New\_York", and is maintained for backwards compatibility.
The first way to get the current time in Toronto is: ``` from datetime import datetime from pytz import timezone tz = timezone('EST') print(datetime.now(tz)) ``` The output is the following: > > 2022-06-28 16:23:23.333585-05:00 > > > The second way to get the current time in Toronto is: ``` from datetime import datetime from pytz import timezone tz = timezone('US/Eastern') print(datetime.now(tz)) ``` The output is the following: > > 2022-06-28 17:24:42.944669-04:00 > > > Conclusion: If you use "EST" it is sometimes 1 hour ahead of the true time. I recommend you usually use ***'US/Eastern'***.
36,095,630
I don't understand what the `...` notation does exactly. I tried a simple example with Babel to understand it ([**view the example**](http://babeljs.io/repl/#?evaluate=true&presets=es2015%2Creact%2Cstage-2&code=let%20myArray%20%3D%20%5B1%2C2%2C3%2C%20...18%5D%3B%0A%0Aconsole.log(myArray)%3B%20%2F%2F%20%5B1%2C%202%2C%203%5D%0Aconsole.log(myArray%5B4%5D)%3B%2F%2F%20undefined%0Aconsole.log(myArray.length)%3B%20%2F%2F%203)), but it seems that: **ES6 syntax** ``` let myArray = [1, 2, 3, ...18]; console.log(myArray); // [1, 2, 3] console.log(myArray[4]);// undefined console.log(myArray.length); // 3 ``` is the same as **this ES5 syntax**: ``` "use strict"; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } var myArray = [1, 2, 3].concat(_toConsumableArray(18)); console.log(myArray); // [1, 2, 3] console.log(myArray[4]); // undefined console.log(myArray.length); // 3 ``` **BUT:** What does this code do? Because the output (`console.log`) is the same as in this code (ES5): ``` var myArray = [1,2,3]; console.log(myArray); // [1, 2, 3] console.log(myArray[4]);// undefined console.log(myArray.length); // 3 ``` What does the `...18` notation mean?
2016/03/18
[ "https://Stackoverflow.com/questions/36095630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4467741/" ]
The `...`([*spread operator*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)) works by returning each value from index `0` to index `length-1`: As example: ``` [...'18'] // returns ['1', '8'] ``` which would be the same as: ``` ['18'[0], '18'[1]] ``` --- Now, to get an array from `1` to `18`, you can do this: ``` [...Array(19).keys()].slice(1) ``` Or this with map: ``` [...Array(18)].map(_=>i++,i=1) ``` Hope it helps.
The expression `[1, 2, 3, ...18]` is invalid. You cannot use `...` with a [**Number**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number). You can only use `...` with an iterable object like an [**Array**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array), [**String**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) or [**Object**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object). It is interesting to note that [**Tracur**](https://github.com/google/traceur-compiler) - another transpiler - throws an error when fed the same code: > > ***TypeError**: Cannot spread non-iterable object.* > > > I am not intimate with the [specification](http://www.ecma-international.org/ecma-262/6.0/) but I think this could be a Babel "bug".
20,246,523
This message is a a bit long with many examples, but I hope it will help me and others to better grasp the full story of variables and attribute lookup in Python 2.7. I am using the terms of PEP 227 (<http://www.python.org/dev/peps/pep-0227/>) for code blocks (such as modules, class definition, function definitions, etc.) and variable bindings (such as assignments, argument declarations, class and function declaration, for loops, etc.) I am using the terms variables for names that can be called without a dot, and attributes for names that need to be qualified with an object name (such as obj.x for the attribute x of object obj). There are three scopes in Python for all code blocks, but the functions: * Local * Global * Builtin There are four blocks in Python for the functions only (according to PEP 227): * Local * Enclosing functions * Global * Builtin The rule for a variable to bind it to and find it in a block is quite simple: * any binding of a variable to an object in a block makes this variable local to this block, unless the variable is declared global (in that case the variable belongs to the global scope) * a reference to a variable is looked up using the rule LGB (local, global, builtin) for all blocks, but the functions * a reference to a variable is looked up using the rule LEGB (local, enclosing, global, builtin) for the functions only. Let me know take examples validating this rule, and showing many special cases. For each example, I will give my understanding. Please correct me if I am wrong. For the last example, I don't understand the outcome. example 1: ``` x = "x in module" class A(): print "A: " + x #x in module x = "x in class A" print locals() class B(): print "B: " + x #x in module x = "x in class B" print locals() def f(self): print "f: " + x #x in module self.x = "self.x in f" print x, self.x print locals() >>>A.B().f() A: x in module {'x': 'x in class A', '__module__': '__main__'} B: x in module {'x': 'x in class B', '__module__': '__main__'} f: x in module x in module self.x in f {'self': <__main__.B instance at 0x00000000026FC9C8>} ``` There is no nested scope for the classes (rule LGB) and a function in a class cannot access the attributes of the class without using a qualified name (self.x in this example). This is well described in PEP227. example 2: ``` z = "z in module" def f(): z = "z in f()" class C(): z = "z in C" def g(self): print z print C.z C().g() f() >>> z in f() z in C ``` Here variables in functions are looked up using the LEGB rule, but if a class is in the path, the class arguments are skipped. Here again, this is what PEP 227 is explaining. example 3: ``` var = 0 def func(): print var var = 1 >>> func() Traceback (most recent call last): File "<pyshell#102>", line 1, in <module> func() File "C:/Users/aa/Desktop/test2.py", line 25, in func print var UnboundLocalError: local variable 'var' referenced before assignment ``` We expect with a dynamic language such as python that everything is resolved dynamically. But this is not the case for functions. Local variables are determined at compile time. PEP 227 and <http://docs.python.org/2.7/reference/executionmodel.html> describe this behavior this way "If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block." example 4: ``` x = "x in module" class A(): print "A: " + x x = "x in A" print "A: " + x print locals() del x print locals() print "A: " + x >>> A: x in module A: x in A {'x': 'x in A', '__module__': '__main__'} {'__module__': '__main__'} A: x in module ``` But we see here that this statement in PEP227 "If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block." is wrong when the code block is a class. Moreover, for classes, it seems that local name binding is not made at compile time, but during execution using the class namespace. In that respect, PEP227 and the execution model in the Python doc is misleading and for some parts wrong. example 5: ``` x = 'x in module' def f2(): x = 'x in f2' def myfunc(): x = 'x in myfunc' class MyClass(object): x = x print x return MyClass myfunc() f2() >>> x in module ``` my understanding of this code is the following. The instruction x = x first look up the object the right hand x of the expression is referring to. In that case, the object is looked up locally in the class, then following the rule LGB it is looked up in the global scope, which is the string 'x in module'. Then a local attribute x to MyClass is created in the class dictionary and pointed to the string object. example 6: Now here is an example I cannot explain. It is very close to example 5, I am just changing the local MyClass attribute from x to y. ``` x = 'x in module' def f2(): x = 'x in f2' def myfunc(): x = 'x in myfunc' class MyClass(object): y = x print y return MyClass myfunc() f2() >>> x in myfunc ``` Why in that case the x reference in MyClass is looked up in the innermost function?
2013/11/27
[ "https://Stackoverflow.com/questions/20246523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3022222/" ]
In two words, the difference between example 5 and example 6 is that in example 5 the variable `x` is also assigned to in the same scope, while not in example 6. This triggers a difference that can be understood by historical reasons. This raises UnboundLocalError: ``` x = "foo" def f(): print x x = 5 f() ``` instead of printing "foo". It makes a bit of sense, even if it seems strange at first: the function f() defines the variable `x` locally, even if it is after the print, and so any reference to `x` in the same function must be to that local variable. At least it makes sense in that it avoids strange surprizes if you have by mistake reused the name of a global variable locally, and are trying to use both the global and the local variable. This is a good idea because it means that we can statically know, just by looking at a variable, *which* variable it means. For example, we know that `print x` refers to the local variable (and thus may raise UnboundLocalError) here: ``` x = "foo" def f(): if some_condition: x = 42 print x f() ``` Now, this rule doesn't work for class-level scopes: there, we want expressions like `x = x` to work, capturing the global variable `x` into the class-level scope. This means that class-level scopes don't follow the basic rule above: we can't know if `x` in this scope refers to some outer variable or to the locally-defined `x` --- for example: ``` class X: x = x # we want to read the global x and assign it locally bar = x # but here we want to read the local x of the previous line class Y: if some_condition: x = 42 print x # may refer to either the local x, or some global x class Z: for i in range(2): print x # prints the global x the 1st time, and 42 the 2nd time x = 42 ``` So in class scopes, a different rule is used: where it would normally raise UnboundLocalError --- and only in that case --- it instead looks up in the module globals. That's all: it doesn't follow the chain of nested scopes. Why not? I actually doubt there is a better explanation that "for historical reasons". In more technical terms, it could consider that the variable `x` is both locally defined in the class scope (because it is assigned to) *and* should be passed in from the parent scope as a lexically nested variable (because it is read). It would be possible to implement it by using a different bytecode than `LOAD_NAME` that looks up in the local scope, and falls back to using the nested scope's reference if not found. **EDIT:** thanks wilberforce for the reference to <http://bugs.python.org/issue532860>. We may have a chance to get some discussion reactivated with the proposed new bytecode, if we feel that it should be fixed after all (the bug report considers killing support for `x = x` but was closed for fear of breaking too much existing code; instead what I'm suggesting here would be to make `x = x` work in more cases). Or I may be missing another fine point... **EDIT2:** it seems that CPython did precisely that in the current 3.4 trunk: <http://bugs.python.org/issue17853> ... or not? They introduced the bytecode for a slightly different reason and don't use it systematically...
Long story short, this is a corner case of Python's scoping that is a bit inconsistent, but has to be kept for backwards compatibility (and because it's not that clear what the right answer should be). You can see lots of the [original discussion](https://mail.python.org/pipermail/python-dev/2002-April/023427.html) about it on the Python mailing list when PEP 227 was being implemented, and some in the [bug](http://bugs.python.org/issue532860) for which this behaviour is the fix. We can work out why there's a difference using the [`dis`](http://docs.python.org/2/library/dis.html) module, which lets us look inside code objects to see the bytecode a piece of code has been compiled to. I'm on Python 2.6, so the details of this might be slightly different - but I see the same behaviour, so I think it's probably close enough to 2.7. The code that initialises each nested `MyClass` lives in a code object that you can get to via the attributes of the top-level functions. (I'm renaming the functions from example 5 and example 6 to `f1` and `f2` respectively.) The code object has a `co_consts` tuple, which contains the `myfunc` code object, which in turn has the code that runs when `MyClass` gets created: ``` In [20]: f1.func_code.co_consts Out[20]: (None, 'x in f2', <code object myfunc at 0x1773e40, file "<ipython-input-3-6d9550a9ea41>", line 4>) In [21]: myfunc1_code = f1.func_code.co_consts[2] In [22]: MyClass1_code = myfunc1_code.co_consts[3] In [23]: myfunc2_code = f2.func_code.co_consts[2] In [24]: MyClass2_code = myfunc2_code.co_consts[3] ``` Then you can see the difference between them in bytecode using `dis.dis`: ``` In [25]: from dis import dis In [26]: dis(MyClass1_code) 6 0 LOAD_NAME 0 (__name__) 3 STORE_NAME 1 (__module__) 7 6 LOAD_NAME 2 (x) 9 STORE_NAME 2 (x) 8 12 LOAD_NAME 2 (x) 15 PRINT_ITEM 16 PRINT_NEWLINE 17 LOAD_LOCALS 18 RETURN_VALUE In [27]: dis(MyClass2_code) 6 0 LOAD_NAME 0 (__name__) 3 STORE_NAME 1 (__module__) 7 6 LOAD_DEREF 0 (x) 9 STORE_NAME 2 (y) 8 12 LOAD_NAME 2 (y) 15 PRINT_ITEM 16 PRINT_NEWLINE 17 LOAD_LOCALS 18 RETURN_VALUE ``` So the only difference is that in `MyClass1`, `x` is loaded using the `LOAD_NAME` op, while in `MyClass2`, it's loaded using `LOAD_DEREF`. `LOAD_DEREF` looks up a name in an enclosing scope, so it gets 'x in myfunc'. `LOAD_NAME` doesn't follow nested scopes - since it can't see the `x` names bound in `myfunc` or `f1`, it gets the module-level binding. Then the question is, why does the code of the two versions of `MyClass` get compiled to two different opcodes? In `f1` the binding is shadowing `x` in the class scope, while in `f2` it's binding a new name. If the `MyClass` scopes were nested functions instead of classes, the `y = x` line in `f2` would be compiled the same, but the `x = x` in `f1` would be a `LOAD_FAST` - this is because the compiler would know that `x` is bound in the function, so it should use the `LOAD_FAST` to retrieve a local variable. This would fail with an `UnboundLocalError` when it was called. ``` In [28]: x = 'x in module' def f3(): x = 'x in f2' def myfunc(): x = 'x in myfunc' def MyFunc(): x = x print x return MyFunc() myfunc() f3() --------------------------------------------------------------------------- Traceback (most recent call last) <ipython-input-29-9f04105d64cc> in <module>() 9 return MyFunc() 10 myfunc() ---> 11 f3() <ipython-input-29-9f04105d64cc> in f3() 8 print x 9 return MyFunc() ---> 10 myfunc() 11 f3() <ipython-input-29-9f04105d64cc> in myfunc() 7 x = x 8 print x ----> 9 return MyFunc() 10 myfunc() 11 f3() <ipython-input-29-9f04105d64cc> in MyFunc() 5 x = 'x in myfunc' 6 def MyFunc(): ----> 7 x = x 8 print x 9 return MyFunc() UnboundLocalError: local variable 'x' referenced before assignment ``` This fails because the `MyFunc` function then uses `LOAD_FAST`: ``` In [31]: myfunc_code = f3.func_code.co_consts[2] MyFunc_code = myfunc_code.co_consts[2] In [33]: dis(MyFunc_code) 7 0 LOAD_FAST 0 (x) 3 STORE_FAST 0 (x) 8 6 LOAD_FAST 0 (x) 9 PRINT_ITEM 10 PRINT_NEWLINE 11 LOAD_CONST 0 (None) 14 RETURN_VALUE ``` (As an aside, it's not a big surprise that there should be a difference in how scoping interacts with code in the body of classes and code in a function. You can tell this because bindings at the class level aren't available in methods - method scopes aren't nested inside the class scope in the same way as nested functions are. You have to explicitly reach them via the class, or by using `self.` (which will fall back to the class if there's not also an instance-level binding).)
20,246,523
This message is a a bit long with many examples, but I hope it will help me and others to better grasp the full story of variables and attribute lookup in Python 2.7. I am using the terms of PEP 227 (<http://www.python.org/dev/peps/pep-0227/>) for code blocks (such as modules, class definition, function definitions, etc.) and variable bindings (such as assignments, argument declarations, class and function declaration, for loops, etc.) I am using the terms variables for names that can be called without a dot, and attributes for names that need to be qualified with an object name (such as obj.x for the attribute x of object obj). There are three scopes in Python for all code blocks, but the functions: * Local * Global * Builtin There are four blocks in Python for the functions only (according to PEP 227): * Local * Enclosing functions * Global * Builtin The rule for a variable to bind it to and find it in a block is quite simple: * any binding of a variable to an object in a block makes this variable local to this block, unless the variable is declared global (in that case the variable belongs to the global scope) * a reference to a variable is looked up using the rule LGB (local, global, builtin) for all blocks, but the functions * a reference to a variable is looked up using the rule LEGB (local, enclosing, global, builtin) for the functions only. Let me know take examples validating this rule, and showing many special cases. For each example, I will give my understanding. Please correct me if I am wrong. For the last example, I don't understand the outcome. example 1: ``` x = "x in module" class A(): print "A: " + x #x in module x = "x in class A" print locals() class B(): print "B: " + x #x in module x = "x in class B" print locals() def f(self): print "f: " + x #x in module self.x = "self.x in f" print x, self.x print locals() >>>A.B().f() A: x in module {'x': 'x in class A', '__module__': '__main__'} B: x in module {'x': 'x in class B', '__module__': '__main__'} f: x in module x in module self.x in f {'self': <__main__.B instance at 0x00000000026FC9C8>} ``` There is no nested scope for the classes (rule LGB) and a function in a class cannot access the attributes of the class without using a qualified name (self.x in this example). This is well described in PEP227. example 2: ``` z = "z in module" def f(): z = "z in f()" class C(): z = "z in C" def g(self): print z print C.z C().g() f() >>> z in f() z in C ``` Here variables in functions are looked up using the LEGB rule, but if a class is in the path, the class arguments are skipped. Here again, this is what PEP 227 is explaining. example 3: ``` var = 0 def func(): print var var = 1 >>> func() Traceback (most recent call last): File "<pyshell#102>", line 1, in <module> func() File "C:/Users/aa/Desktop/test2.py", line 25, in func print var UnboundLocalError: local variable 'var' referenced before assignment ``` We expect with a dynamic language such as python that everything is resolved dynamically. But this is not the case for functions. Local variables are determined at compile time. PEP 227 and <http://docs.python.org/2.7/reference/executionmodel.html> describe this behavior this way "If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block." example 4: ``` x = "x in module" class A(): print "A: " + x x = "x in A" print "A: " + x print locals() del x print locals() print "A: " + x >>> A: x in module A: x in A {'x': 'x in A', '__module__': '__main__'} {'__module__': '__main__'} A: x in module ``` But we see here that this statement in PEP227 "If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block." is wrong when the code block is a class. Moreover, for classes, it seems that local name binding is not made at compile time, but during execution using the class namespace. In that respect, PEP227 and the execution model in the Python doc is misleading and for some parts wrong. example 5: ``` x = 'x in module' def f2(): x = 'x in f2' def myfunc(): x = 'x in myfunc' class MyClass(object): x = x print x return MyClass myfunc() f2() >>> x in module ``` my understanding of this code is the following. The instruction x = x first look up the object the right hand x of the expression is referring to. In that case, the object is looked up locally in the class, then following the rule LGB it is looked up in the global scope, which is the string 'x in module'. Then a local attribute x to MyClass is created in the class dictionary and pointed to the string object. example 6: Now here is an example I cannot explain. It is very close to example 5, I am just changing the local MyClass attribute from x to y. ``` x = 'x in module' def f2(): x = 'x in f2' def myfunc(): x = 'x in myfunc' class MyClass(object): y = x print y return MyClass myfunc() f2() >>> x in myfunc ``` Why in that case the x reference in MyClass is looked up in the innermost function?
2013/11/27
[ "https://Stackoverflow.com/questions/20246523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3022222/" ]
In an ideal world, you'd be right and some of the inconsistencies you found would be wrong. However, CPython has optimized some scenarios, specifically function locals. These optimizations, together with how the compiler and evaluation loop interact and historical precedent, lead to the confusion. Python translates code to bytecodes, and those are then interpreted by a interpreter loop. The 'regular' opcode for accessing a name is `LOAD_NAME`, which looks up a variable name as you would in a dictionary. `LOAD_NAME` will first look up a name as a local, and if that fails, looks for a global. `LOAD_NAME` throws a `NameError` exception when the name is not found. For nested scopes, looking up names outside of the current scope is implemented using closures; if a name is not assigned to but is available in a nested (not global) scope, then such values are handled as a closure. This is needed because a parent scope can hold different values for a given name at different times; two calls to a parent function can lead to different closure values. So Python has `LOAD_CLOSURE`, `MAKE_CLOSURE` and `LOAD_DEREF` opcodes for that situation; the first two opcodes are used in loading and creating a closure for a nested scope, and the `LOAD_DEREF` will load the closed-over value when the nested scope needs it. Now, `LOAD_NAME` is relatively slow; it will consult two dictionaries, which means it has to hash the key first and run a few equality tests (if the name wasn't interned). If the name isn't local, then it has to do this again for a global. For functions, that can potentially be called tens of thousands of times, this can get tedious fast. So function locals have special opcodes. Loading a local name is implemented by `LOAD_FAST`, which looks up local variables *by index* in a special local names array. This is much faster, but it does require that the compiler first has to see if a name is a local and not global. To still be able to look up global names, another opcode `LOAD_GLOBAL` is used. The compiler explicitly optimizes for this case to generate the special opcodes. `LOAD_FAST` will throw an `UnboundLocalError` exception when there is not yet a value for the name. Class definition bodies on the other hand, although they are treated much like a function, do not get this optimization step. Class definitions are not meant to be called all that often; most modules create classes *once*, when imported. Class scopes don't count when nesting either, so the rules are simpler. As a result, class definition bodies do not act like functions when you start mixing scopes up a little. So, for non-function scopes, `LOAD_NAME` and `LOAD_DEREF` are used for locals and globals, and for closures, respectively. For functions, `LOAD_FAST`, `LOAD_GLOBAL` and `LOAD_DEREF` are used instead. Note that class bodies are executed as soon as Python executes the `class` line! So in example 1, `class B` inside `class A` is executed as soon as `class A` is executed, which is when you import the module. In example 2, `C` is not executed until `f()` is called, not before. Lets walk through your examples: 1. You have nested a class `A.B` in a class `A`. Class bodies do not form nested scopes, so even though the `A.B` class body is executed when class `A` is executed, the compiler will use `LOAD_NAME` to look up `x`. `A.B().f()` is a *function* (bound to the `B()` instance as a method), so it uses `LOAD_GLOBAL` to load `x`. We'll ignore attribute access here, that's a very well defined name pattern. 2. Here `f().C.z` is at class scope, so the function `f().C().g()` will skip the `C` scope and look at the `f()` scope instead, using `LOAD_DEREF`. 3. Here `var` was determined to be a local by the compiler because you assign to it within the scope. Functions are optimized, so `LOAD_FAST` is used to look up the local and an exception is thrown. 4. Now things get a little weird. `class A` is executed at class scope, so `LOAD_NAME` is being used. `A.x` was deleted from the locals dictionary for the scope, so the second access to `x` results in the global `x` being found instead; `LOAD_NAME` looked for a local first and didn't find it there, falling back to the global lookup. Yes, this appears inconsistent with the documentation. Python-the-language and CPython-the implementation are clashing a little here. You are, however, pushing the boundaries of what is possible and practical in a dynamic language; checking if `x` should have been a local in `LOAD_NAME` would be possible but takes precious execution time for a corner case that most developers will never run into. 5. Now you are confusing the compiler. You used `x = x` in the class scope, and thus you are setting a *local* from a name outside of the scope. The compiler finds `x` is a local here (you assign to it), so it never considers that it could also be a scoped name. The compiler uses `LOAD_NAME` for all references to `x` in this scope, because this is not an optimized function body. When executing the class definition, `x = x` first requires you to *look up `x`*, so it uses `LOAD_NAME` to do so. No `x` is defined, `LOAD_NAME` doesn't find a local, so the *global* `x` is found. The resulting value is stored as a local, which *happens* to be named `x` as well. `print x` uses `LOAD_NAME` again, and now finds the new local `x` value. 6. Here you did not confuse the compiler. You are creating a local `y`, `x` is not local, so the compiler recognizes it as a scoped name from parent function `f2().myfunc()`. `x` is looked up with `LOAD_DEREF` from the closure, and stored in `y`. You could see the confusion between 5 and 6 as a bug, albeit one that is not worth fixing in my opinion. It was certainly filed as such, see [issue 532860](http://bugs.python.org/issue532860) in the Python bug tracker, it has been there for over 10 years now. The compiler could check for a scoped name `x` even when `x` is *also* a local, for that first assignment in example 5. Or `LOAD_NAME` could check if the name is meant to be a local, really, and throw an `UnboundLocalError` if no local was found, at the expense of more performance. Had this been in a function scope, `LOAD_FAST` would have been used for example 5, and an `UnboundLocalError` would be thrown immediately. However, as the referenced bug shows, for historical reasons the behaviour is retained. There probably is code out there today that'll break were this bug fixed.
Long story short, this is a corner case of Python's scoping that is a bit inconsistent, but has to be kept for backwards compatibility (and because it's not that clear what the right answer should be). You can see lots of the [original discussion](https://mail.python.org/pipermail/python-dev/2002-April/023427.html) about it on the Python mailing list when PEP 227 was being implemented, and some in the [bug](http://bugs.python.org/issue532860) for which this behaviour is the fix. We can work out why there's a difference using the [`dis`](http://docs.python.org/2/library/dis.html) module, which lets us look inside code objects to see the bytecode a piece of code has been compiled to. I'm on Python 2.6, so the details of this might be slightly different - but I see the same behaviour, so I think it's probably close enough to 2.7. The code that initialises each nested `MyClass` lives in a code object that you can get to via the attributes of the top-level functions. (I'm renaming the functions from example 5 and example 6 to `f1` and `f2` respectively.) The code object has a `co_consts` tuple, which contains the `myfunc` code object, which in turn has the code that runs when `MyClass` gets created: ``` In [20]: f1.func_code.co_consts Out[20]: (None, 'x in f2', <code object myfunc at 0x1773e40, file "<ipython-input-3-6d9550a9ea41>", line 4>) In [21]: myfunc1_code = f1.func_code.co_consts[2] In [22]: MyClass1_code = myfunc1_code.co_consts[3] In [23]: myfunc2_code = f2.func_code.co_consts[2] In [24]: MyClass2_code = myfunc2_code.co_consts[3] ``` Then you can see the difference between them in bytecode using `dis.dis`: ``` In [25]: from dis import dis In [26]: dis(MyClass1_code) 6 0 LOAD_NAME 0 (__name__) 3 STORE_NAME 1 (__module__) 7 6 LOAD_NAME 2 (x) 9 STORE_NAME 2 (x) 8 12 LOAD_NAME 2 (x) 15 PRINT_ITEM 16 PRINT_NEWLINE 17 LOAD_LOCALS 18 RETURN_VALUE In [27]: dis(MyClass2_code) 6 0 LOAD_NAME 0 (__name__) 3 STORE_NAME 1 (__module__) 7 6 LOAD_DEREF 0 (x) 9 STORE_NAME 2 (y) 8 12 LOAD_NAME 2 (y) 15 PRINT_ITEM 16 PRINT_NEWLINE 17 LOAD_LOCALS 18 RETURN_VALUE ``` So the only difference is that in `MyClass1`, `x` is loaded using the `LOAD_NAME` op, while in `MyClass2`, it's loaded using `LOAD_DEREF`. `LOAD_DEREF` looks up a name in an enclosing scope, so it gets 'x in myfunc'. `LOAD_NAME` doesn't follow nested scopes - since it can't see the `x` names bound in `myfunc` or `f1`, it gets the module-level binding. Then the question is, why does the code of the two versions of `MyClass` get compiled to two different opcodes? In `f1` the binding is shadowing `x` in the class scope, while in `f2` it's binding a new name. If the `MyClass` scopes were nested functions instead of classes, the `y = x` line in `f2` would be compiled the same, but the `x = x` in `f1` would be a `LOAD_FAST` - this is because the compiler would know that `x` is bound in the function, so it should use the `LOAD_FAST` to retrieve a local variable. This would fail with an `UnboundLocalError` when it was called. ``` In [28]: x = 'x in module' def f3(): x = 'x in f2' def myfunc(): x = 'x in myfunc' def MyFunc(): x = x print x return MyFunc() myfunc() f3() --------------------------------------------------------------------------- Traceback (most recent call last) <ipython-input-29-9f04105d64cc> in <module>() 9 return MyFunc() 10 myfunc() ---> 11 f3() <ipython-input-29-9f04105d64cc> in f3() 8 print x 9 return MyFunc() ---> 10 myfunc() 11 f3() <ipython-input-29-9f04105d64cc> in myfunc() 7 x = x 8 print x ----> 9 return MyFunc() 10 myfunc() 11 f3() <ipython-input-29-9f04105d64cc> in MyFunc() 5 x = 'x in myfunc' 6 def MyFunc(): ----> 7 x = x 8 print x 9 return MyFunc() UnboundLocalError: local variable 'x' referenced before assignment ``` This fails because the `MyFunc` function then uses `LOAD_FAST`: ``` In [31]: myfunc_code = f3.func_code.co_consts[2] MyFunc_code = myfunc_code.co_consts[2] In [33]: dis(MyFunc_code) 7 0 LOAD_FAST 0 (x) 3 STORE_FAST 0 (x) 8 6 LOAD_FAST 0 (x) 9 PRINT_ITEM 10 PRINT_NEWLINE 11 LOAD_CONST 0 (None) 14 RETURN_VALUE ``` (As an aside, it's not a big surprise that there should be a difference in how scoping interacts with code in the body of classes and code in a function. You can tell this because bindings at the class level aren't available in methods - method scopes aren't nested inside the class scope in the same way as nested functions are. You have to explicitly reach them via the class, or by using `self.` (which will fall back to the class if there's not also an instance-level binding).)
87,704
So, I just got a new [ENUTV-2](http://www.encore-usa.com/product_item.php?region=us&bid=2&pgid=17&pid=375#DOWNLOAD) USB TV Tuner Box, and it works fine overall. The driver seems to be OK, but the utility provided by encore doesn't seem to be working 100% in win 7. The only real issue is that I can't mute it, or change the volume level. So I'd like to know: **Is there good (free) software out there for watching TV with a tuner?** EDIT: Windows media center doesn't work. I have it in my version of windows, but it claims to have no support for my region (Brazil). I'm under the impression that the only regional issue is the lack of support for downloading time-tables and stuff, which is something I really don't care about. The drivers for my tuner are installed, why can't WMC just see that the tuner is ON and capture the stream coming from it? Thanks
2009/12/26
[ "https://superuser.com/questions/87704", "https://superuser.com", "https://superuser.com/users/6371/" ]
Have you tried (version of Windows depending) Media Center? It is free and comes with Windows Home Premium and above!
That's because of your gpu drivers. I had the same problem updated them, and it worked just fine. I have an nvidia 9500 gt with 196. something drivers.
191,346
I am writing a report that has graphics, photos and maps. If I use the figure environment everything is labeled as a figure in the caption. However, what I would like to do is where I have a map to have the map labeled appropriately e.g. Map 1: caption text; Map 2: caption text etc and to be able to refer to it in the text Map \ref{map01}. Same as for Photographs. I have looked at some of the FAQs but does not seem to have what I want. Is it possible.
2014/07/14
[ "https://tex.stackexchange.com/questions/191346", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/59053/" ]
Define yourself new floats that match the type you're using: ![enter image description here](https://i.stack.imgur.com/xF8MQ.png) ``` \documentclass{article} \usepackage{float}% http://ctan.org/pkg/float \newfloat{photo}{htbp}{pho}\floatname{photo}{Photo} \newfloat{map}{htbp}{map}\floatname{map}{Map} \setcounter{topnumber}{3}% Just for this example \begin{document} Text \begin{figure}[t] \caption{A figure} \end{figure} \begin{photo}[t] \caption{A photo} \end{photo} \begin{map}[t] \caption{A map} \end{map} \end{document} ``` The [`float` package](http://ctan.org/pkg/float) provides ``` \newfloat{<type>}{<placement>}{<ext>}[<within>] ```
My solution uses the `caption` package and its `\captionsetup` facility, however, this way it is necessary to do this in every `figure` environment where the name should be changed. This will also not provide different counters or separate `lists of maps` etc. ``` \documentclass{report} \usepackage{caption}% \usepackage[demo]{graphicx}% \begin{document} \listoffigures \chapter{First} \begin{figure} \captionsetup{name=Map}% \centering \includegraphics{somefig}% \caption{Some Text}% \end{figure} \begin{figure} \captionsetup{name=Photo}% \centering \includegraphics{somefig}% \caption{This photograph shows ...}% \end{figure} \end{document} ``` ![enter image description here](https://i.stack.imgur.com/c6gI1.jpg) **The figure "2" below the 'Map' is the pagenumber ;-)**
191,346
I am writing a report that has graphics, photos and maps. If I use the figure environment everything is labeled as a figure in the caption. However, what I would like to do is where I have a map to have the map labeled appropriately e.g. Map 1: caption text; Map 2: caption text etc and to be able to refer to it in the text Map \ref{map01}. Same as for Photographs. I have looked at some of the FAQs but does not seem to have what I want. Is it possible.
2014/07/14
[ "https://tex.stackexchange.com/questions/191346", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/59053/" ]
If you use the `tocbasic` package from the KOMA-Script bundle you can also print a list of photos and a list of maps. ``` \documentclass{article} \usepackage{tocbasic} \DeclareNewTOC[% type=photo, float, name=Photo, listname={List of Photos}, ]{pho} \DeclareNewTOC[% type=map, float, name=Map, listname={List of Maps}, ]{map} \makeatletter % entries to the lists should have the same layout like entries to the list of figures \renewcommand\l@photo{\l@figure} \renewcommand\l@map{\l@figure} \makeatother \begin{document} \listoffigures \listofphotos \listofmaps \begin{figure}[ht] \centering\fbox{Figure}\caption{A figure} \end{figure} \begin{photo}[ht] \centering\fbox{Photo}\caption{A photo} \end{photo} \begin{map}[ht] \centering\fbox{Map}\caption{A map} \end{map} \end{document} ``` ![enter image description here](https://i.stack.imgur.com/Tt6On.png) There is also a `nonfloat` option for `\DeclareNewTOC`. It defines the (additional) nonfloating environment `<name>-` (for example `photo-`).
My solution uses the `caption` package and its `\captionsetup` facility, however, this way it is necessary to do this in every `figure` environment where the name should be changed. This will also not provide different counters or separate `lists of maps` etc. ``` \documentclass{report} \usepackage{caption}% \usepackage[demo]{graphicx}% \begin{document} \listoffigures \chapter{First} \begin{figure} \captionsetup{name=Map}% \centering \includegraphics{somefig}% \caption{Some Text}% \end{figure} \begin{figure} \captionsetup{name=Photo}% \centering \includegraphics{somefig}% \caption{This photograph shows ...}% \end{figure} \end{document} ``` ![enter image description here](https://i.stack.imgur.com/c6gI1.jpg) **The figure "2" below the 'Map' is the pagenumber ;-)**
361,990
I have a table in MS SQL server which currently has around 800 records and 20 columns. I want to manually update and add to the information within this table on a frequent basis. Would exporting the table to Microsoft Excel (and later and re-importing it back to SQL Server) be the best solution for this, or is there another (free) solution? Please note that I do know how to export the table data from MS SQL Server to Excel, I am just wondering if this is the neatest way to do this.
2011/11/27
[ "https://superuser.com/questions/361990", "https://superuser.com", "https://superuser.com/users/340/" ]
Assuming your SQL back-end is an MS SQL server you can use the Microsoft [SQL Server Management Studio](http://www.microsoft.com/download/en/details.aspx?id=7593) (Express edition linked) to directly query and edit data (amongst many other things). > > Microsoft SQL Server 2008 Management Studio Express is a free, > integrated environment for accessing, configuring, managing, > administering, and developing all components of SQL Server, as well as > combining a broad group of graphical tools and rich script editors > that provide access to SQL Server to developers and administrators of > all skill levels. > > >
More simply, use SQL Server Management Studio (SSMS) or MS Access if you have it available. If you have SQL Server, you have SSMS... Although, what is the table there for? Does it have other clients using it?
361,990
I have a table in MS SQL server which currently has around 800 records and 20 columns. I want to manually update and add to the information within this table on a frequent basis. Would exporting the table to Microsoft Excel (and later and re-importing it back to SQL Server) be the best solution for this, or is there another (free) solution? Please note that I do know how to export the table data from MS SQL Server to Excel, I am just wondering if this is the neatest way to do this.
2011/11/27
[ "https://superuser.com/questions/361990", "https://superuser.com", "https://superuser.com/users/340/" ]
More simply, use SQL Server Management Studio (SSMS) or MS Access if you have it available. If you have SQL Server, you have SSMS... Although, what is the table there for? Does it have other clients using it?
Many people, my self included, use [PHPMyAdmin](http://www.phpmyadmin.net/home_page/index.php) for MySQL interactions. It may be too slow for what you need though (one entry at a time kind of thing). It's completely free and gives direct access to the database. Even if you don't use if for this I recommend having it available.
361,990
I have a table in MS SQL server which currently has around 800 records and 20 columns. I want to manually update and add to the information within this table on a frequent basis. Would exporting the table to Microsoft Excel (and later and re-importing it back to SQL Server) be the best solution for this, or is there another (free) solution? Please note that I do know how to export the table data from MS SQL Server to Excel, I am just wondering if this is the neatest way to do this.
2011/11/27
[ "https://superuser.com/questions/361990", "https://superuser.com", "https://superuser.com/users/340/" ]
More simply, use SQL Server Management Studio (SSMS) or MS Access if you have it available. If you have SQL Server, you have SSMS... Although, what is the table there for? Does it have other clients using it?
You've already selected an answer, but I was a fan of [Evolutility](http://evolutility.org/index.aspx) for quick CRUD interfaces. It has support for mass updates and a pleasing UI.
361,990
I have a table in MS SQL server which currently has around 800 records and 20 columns. I want to manually update and add to the information within this table on a frequent basis. Would exporting the table to Microsoft Excel (and later and re-importing it back to SQL Server) be the best solution for this, or is there another (free) solution? Please note that I do know how to export the table data from MS SQL Server to Excel, I am just wondering if this is the neatest way to do this.
2011/11/27
[ "https://superuser.com/questions/361990", "https://superuser.com", "https://superuser.com/users/340/" ]
Assuming your SQL back-end is an MS SQL server you can use the Microsoft [SQL Server Management Studio](http://www.microsoft.com/download/en/details.aspx?id=7593) (Express edition linked) to directly query and edit data (amongst many other things). > > Microsoft SQL Server 2008 Management Studio Express is a free, > integrated environment for accessing, configuring, managing, > administering, and developing all components of SQL Server, as well as > combining a broad group of graphical tools and rich script editors > that provide access to SQL Server to developers and administrators of > all skill levels. > > >
Many people, my self included, use [PHPMyAdmin](http://www.phpmyadmin.net/home_page/index.php) for MySQL interactions. It may be too slow for what you need though (one entry at a time kind of thing). It's completely free and gives direct access to the database. Even if you don't use if for this I recommend having it available.
361,990
I have a table in MS SQL server which currently has around 800 records and 20 columns. I want to manually update and add to the information within this table on a frequent basis. Would exporting the table to Microsoft Excel (and later and re-importing it back to SQL Server) be the best solution for this, or is there another (free) solution? Please note that I do know how to export the table data from MS SQL Server to Excel, I am just wondering if this is the neatest way to do this.
2011/11/27
[ "https://superuser.com/questions/361990", "https://superuser.com", "https://superuser.com/users/340/" ]
Assuming your SQL back-end is an MS SQL server you can use the Microsoft [SQL Server Management Studio](http://www.microsoft.com/download/en/details.aspx?id=7593) (Express edition linked) to directly query and edit data (amongst many other things). > > Microsoft SQL Server 2008 Management Studio Express is a free, > integrated environment for accessing, configuring, managing, > administering, and developing all components of SQL Server, as well as > combining a broad group of graphical tools and rich script editors > that provide access to SQL Server to developers and administrators of > all skill levels. > > >
You've already selected an answer, but I was a fan of [Evolutility](http://evolutility.org/index.aspx) for quick CRUD interfaces. It has support for mass updates and a pleasing UI.
33,649,705
I'm trying to make an horizontal list of sticky images with `RecyclerView` and I'd like to move them by pixels' offset with [`scrollToPositionWithOffset`](http://developer.android.com/intl/ja/reference/android/support/v7/widget/LinearLayoutManager.html#scrollToPositionWithOffset(int,%20int)). I thought passing `0` as `position` and the pixels I want to move to right / left as `offset`. But it doesn't work, the list remains untouched, unscrolled, it doesn't move. This is my implementation: ``` final LargeImageAdapter mLargeImageAdapter = new LargeImageAdapter(this); linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setAdapter(mLargeImageAdapter); seekBar = (SeekBar)findViewById(R.id.seekBar); seekBar.setMax(7000); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int scrollToDX = progress; ((LinearLayoutManager)recyclerView.getLayoutManager()).scrollToPositionWithOffset(0, scrollToDX); // tried invoking also linearLayoutManager instead getLayoutManager. } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); ``` what am I doing wrong? Thank you very much. Regards. Rafael.
2015/11/11
[ "https://Stackoverflow.com/questions/33649705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1348187/" ]
I finally used: `recyclerView.scrollBy(int offsetX, int offsetY);` setting `offsetY = 0` and it works now. I don't understand what's the utility of the function `scrollToPositionWithOffset`.
A late answer to your first question, and an addition to your answer: Your method works better for your personal needs, because `scrollToPositionWithOffset` is not intended to do what you want. As the [doc says here](http://developer.android.com/reference/android/support/v7/widget/LinearLayoutManager.html#scrollToPositionWithOffset(int,%20int)): > > [...]Resolved layout start depends on [...] > getLayoutDirection(android.view.View) [...] > > > Which means it would offset the scroll target position in the layout direction, vertically in your case. > > I don't understand what's the utility of the function > scrollToPositionWithOffset. > > > it allows to not only scroll to a given item in the list, but also position it at a more "visible" or otherwise convenient place.
33,649,705
I'm trying to make an horizontal list of sticky images with `RecyclerView` and I'd like to move them by pixels' offset with [`scrollToPositionWithOffset`](http://developer.android.com/intl/ja/reference/android/support/v7/widget/LinearLayoutManager.html#scrollToPositionWithOffset(int,%20int)). I thought passing `0` as `position` and the pixels I want to move to right / left as `offset`. But it doesn't work, the list remains untouched, unscrolled, it doesn't move. This is my implementation: ``` final LargeImageAdapter mLargeImageAdapter = new LargeImageAdapter(this); linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setAdapter(mLargeImageAdapter); seekBar = (SeekBar)findViewById(R.id.seekBar); seekBar.setMax(7000); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int scrollToDX = progress; ((LinearLayoutManager)recyclerView.getLayoutManager()).scrollToPositionWithOffset(0, scrollToDX); // tried invoking also linearLayoutManager instead getLayoutManager. } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); ``` what am I doing wrong? Thank you very much. Regards. Rafael.
2015/11/11
[ "https://Stackoverflow.com/questions/33649705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1348187/" ]
I finally used: `recyclerView.scrollBy(int offsetX, int offsetY);` setting `offsetY = 0` and it works now. I don't understand what's the utility of the function `scrollToPositionWithOffset`.
I had a similar issue. My problem was that my recyclerview wasn't of the same size of its parent layout. I solved it by setting the recycler view width and height to `match_parent`. I don't know why this happens in this case.
33,649,705
I'm trying to make an horizontal list of sticky images with `RecyclerView` and I'd like to move them by pixels' offset with [`scrollToPositionWithOffset`](http://developer.android.com/intl/ja/reference/android/support/v7/widget/LinearLayoutManager.html#scrollToPositionWithOffset(int,%20int)). I thought passing `0` as `position` and the pixels I want to move to right / left as `offset`. But it doesn't work, the list remains untouched, unscrolled, it doesn't move. This is my implementation: ``` final LargeImageAdapter mLargeImageAdapter = new LargeImageAdapter(this); linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setAdapter(mLargeImageAdapter); seekBar = (SeekBar)findViewById(R.id.seekBar); seekBar.setMax(7000); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int scrollToDX = progress; ((LinearLayoutManager)recyclerView.getLayoutManager()).scrollToPositionWithOffset(0, scrollToDX); // tried invoking also linearLayoutManager instead getLayoutManager. } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); ``` what am I doing wrong? Thank you very much. Regards. Rafael.
2015/11/11
[ "https://Stackoverflow.com/questions/33649705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1348187/" ]
I finally used: `recyclerView.scrollBy(int offsetX, int offsetY);` setting `offsetY = 0` and it works now. I don't understand what's the utility of the function `scrollToPositionWithOffset`.
recently I encountered this problem too, I invoke **scrollToPositionWithOffset** when `onScrolled()` directly, but nothing change, with that I turn to scrollToPosition() even scrollBy() but not help, finally I attempt to delay that so it work, first time I delay 50ms, but two weeks later I found that's not enough, so I increase to 100ms with no approachs in my hands, of course it work, just feel a little unsettled. ``` val layoutManager = LinearLayoutManager(hostActivity, VERTICAL, false) fileRv.layoutManager = layoutManager fileRv.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { if (dx == 0 && dy == 0) { scrollToLastPosition() } } private fun scrollToLastPosition() { val lastScrollPosition = viewModel.consumeLastScrollPosition() if (lastScrollPosition > 0) { Handler().postDelayed({ layoutManager.scrollToPositionWithOffset(lastScrollPosition, 0) }, 100) } } }) override fun onItemClick(position: Int) { layoutManager.findFirstVisibleItemPosition().let { if (it >= 0) viewModel.markLastScrollPosition(it) } } fun markLastScrollPosition(position: Int) { currentFolderListData.value?.lastOrNull()?.lastScrollPosition = position } fun consumeLastScrollPosition(): Int { currentFolderListData.value?.lastOrNull()?.run { return lastScrollPosition.apply { lastScrollPosition = -1 } } return 0 } ```
33,649,705
I'm trying to make an horizontal list of sticky images with `RecyclerView` and I'd like to move them by pixels' offset with [`scrollToPositionWithOffset`](http://developer.android.com/intl/ja/reference/android/support/v7/widget/LinearLayoutManager.html#scrollToPositionWithOffset(int,%20int)). I thought passing `0` as `position` and the pixels I want to move to right / left as `offset`. But it doesn't work, the list remains untouched, unscrolled, it doesn't move. This is my implementation: ``` final LargeImageAdapter mLargeImageAdapter = new LargeImageAdapter(this); linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setAdapter(mLargeImageAdapter); seekBar = (SeekBar)findViewById(R.id.seekBar); seekBar.setMax(7000); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int scrollToDX = progress; ((LinearLayoutManager)recyclerView.getLayoutManager()).scrollToPositionWithOffset(0, scrollToDX); // tried invoking also linearLayoutManager instead getLayoutManager. } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); ``` what am I doing wrong? Thank you very much. Regards. Rafael.
2015/11/11
[ "https://Stackoverflow.com/questions/33649705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1348187/" ]
I finally used: `recyclerView.scrollBy(int offsetX, int offsetY);` setting `offsetY = 0` and it works now. I don't understand what's the utility of the function `scrollToPositionWithOffset`.
I find a solution. Coz I am the developer of DNA Launcher. When I use RecyclerView to display A-Z App List, I found that the function scrollToPositionWithOffset is not working. I track the problem for almost one day and I figured it out. When the RecyclerView display again, just let the parent of RecyclerView do requestLayout. It works for me. And I know how to make the function scrollToPositionWithOffset not working. You just need to add a view on it and make it gone then.
33,649,705
I'm trying to make an horizontal list of sticky images with `RecyclerView` and I'd like to move them by pixels' offset with [`scrollToPositionWithOffset`](http://developer.android.com/intl/ja/reference/android/support/v7/widget/LinearLayoutManager.html#scrollToPositionWithOffset(int,%20int)). I thought passing `0` as `position` and the pixels I want to move to right / left as `offset`. But it doesn't work, the list remains untouched, unscrolled, it doesn't move. This is my implementation: ``` final LargeImageAdapter mLargeImageAdapter = new LargeImageAdapter(this); linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setAdapter(mLargeImageAdapter); seekBar = (SeekBar)findViewById(R.id.seekBar); seekBar.setMax(7000); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int scrollToDX = progress; ((LinearLayoutManager)recyclerView.getLayoutManager()).scrollToPositionWithOffset(0, scrollToDX); // tried invoking also linearLayoutManager instead getLayoutManager. } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); ``` what am I doing wrong? Thank you very much. Regards. Rafael.
2015/11/11
[ "https://Stackoverflow.com/questions/33649705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1348187/" ]
I had a similar issue. My problem was that my recyclerview wasn't of the same size of its parent layout. I solved it by setting the recycler view width and height to `match_parent`. I don't know why this happens in this case.
A late answer to your first question, and an addition to your answer: Your method works better for your personal needs, because `scrollToPositionWithOffset` is not intended to do what you want. As the [doc says here](http://developer.android.com/reference/android/support/v7/widget/LinearLayoutManager.html#scrollToPositionWithOffset(int,%20int)): > > [...]Resolved layout start depends on [...] > getLayoutDirection(android.view.View) [...] > > > Which means it would offset the scroll target position in the layout direction, vertically in your case. > > I don't understand what's the utility of the function > scrollToPositionWithOffset. > > > it allows to not only scroll to a given item in the list, but also position it at a more "visible" or otherwise convenient place.
33,649,705
I'm trying to make an horizontal list of sticky images with `RecyclerView` and I'd like to move them by pixels' offset with [`scrollToPositionWithOffset`](http://developer.android.com/intl/ja/reference/android/support/v7/widget/LinearLayoutManager.html#scrollToPositionWithOffset(int,%20int)). I thought passing `0` as `position` and the pixels I want to move to right / left as `offset`. But it doesn't work, the list remains untouched, unscrolled, it doesn't move. This is my implementation: ``` final LargeImageAdapter mLargeImageAdapter = new LargeImageAdapter(this); linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setAdapter(mLargeImageAdapter); seekBar = (SeekBar)findViewById(R.id.seekBar); seekBar.setMax(7000); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int scrollToDX = progress; ((LinearLayoutManager)recyclerView.getLayoutManager()).scrollToPositionWithOffset(0, scrollToDX); // tried invoking also linearLayoutManager instead getLayoutManager. } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); ``` what am I doing wrong? Thank you very much. Regards. Rafael.
2015/11/11
[ "https://Stackoverflow.com/questions/33649705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1348187/" ]
I had a similar issue. My problem was that my recyclerview wasn't of the same size of its parent layout. I solved it by setting the recycler view width and height to `match_parent`. I don't know why this happens in this case.
recently I encountered this problem too, I invoke **scrollToPositionWithOffset** when `onScrolled()` directly, but nothing change, with that I turn to scrollToPosition() even scrollBy() but not help, finally I attempt to delay that so it work, first time I delay 50ms, but two weeks later I found that's not enough, so I increase to 100ms with no approachs in my hands, of course it work, just feel a little unsettled. ``` val layoutManager = LinearLayoutManager(hostActivity, VERTICAL, false) fileRv.layoutManager = layoutManager fileRv.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { if (dx == 0 && dy == 0) { scrollToLastPosition() } } private fun scrollToLastPosition() { val lastScrollPosition = viewModel.consumeLastScrollPosition() if (lastScrollPosition > 0) { Handler().postDelayed({ layoutManager.scrollToPositionWithOffset(lastScrollPosition, 0) }, 100) } } }) override fun onItemClick(position: Int) { layoutManager.findFirstVisibleItemPosition().let { if (it >= 0) viewModel.markLastScrollPosition(it) } } fun markLastScrollPosition(position: Int) { currentFolderListData.value?.lastOrNull()?.lastScrollPosition = position } fun consumeLastScrollPosition(): Int { currentFolderListData.value?.lastOrNull()?.run { return lastScrollPosition.apply { lastScrollPosition = -1 } } return 0 } ```
33,649,705
I'm trying to make an horizontal list of sticky images with `RecyclerView` and I'd like to move them by pixels' offset with [`scrollToPositionWithOffset`](http://developer.android.com/intl/ja/reference/android/support/v7/widget/LinearLayoutManager.html#scrollToPositionWithOffset(int,%20int)). I thought passing `0` as `position` and the pixels I want to move to right / left as `offset`. But it doesn't work, the list remains untouched, unscrolled, it doesn't move. This is my implementation: ``` final LargeImageAdapter mLargeImageAdapter = new LargeImageAdapter(this); linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setAdapter(mLargeImageAdapter); seekBar = (SeekBar)findViewById(R.id.seekBar); seekBar.setMax(7000); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int scrollToDX = progress; ((LinearLayoutManager)recyclerView.getLayoutManager()).scrollToPositionWithOffset(0, scrollToDX); // tried invoking also linearLayoutManager instead getLayoutManager. } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); ``` what am I doing wrong? Thank you very much. Regards. Rafael.
2015/11/11
[ "https://Stackoverflow.com/questions/33649705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1348187/" ]
I had a similar issue. My problem was that my recyclerview wasn't of the same size of its parent layout. I solved it by setting the recycler view width and height to `match_parent`. I don't know why this happens in this case.
I find a solution. Coz I am the developer of DNA Launcher. When I use RecyclerView to display A-Z App List, I found that the function scrollToPositionWithOffset is not working. I track the problem for almost one day and I figured it out. When the RecyclerView display again, just let the parent of RecyclerView do requestLayout. It works for me. And I know how to make the function scrollToPositionWithOffset not working. You just need to add a view on it and make it gone then.
26,051,939
Hi i'm quite new to yii framework, currently trying to establish a login through database authentication. but while im trying to log in i get this error saying > > Please fix the following input errors: > Password is incorrect. > > > but when i check the database table im typing the correct password. can anybody help me out if this Heres the Controller ``` <?php class SiteController extends Controller { public function actions() { return array( 'captcha'=>array( 'class'=>'CCaptchaAction', 'backColor'=>0xFFFFFF, ), 'page'=>array( 'class'=>'CViewAction', ), ); } public function actionIndex() { $this->render('index'); } public function actionError() { if($error=Yii::app()->errorHandler->error) { if(Yii::app()->request->isAjaxRequest) echo $error['message']; else $this->render('error', $error); } } public function actionContact() { $model=new ContactForm; if(isset($_POST['ContactForm'])) { $model->attributes=$_POST['ContactForm']; if($model->validate()) { $name='=?UTF-8?B?'.base64_encode($model->name).'?='; $subject='=?UTF-8?B?'.base64_encode($model->subject).'?='; $headers="From: $name <{$model->email}>\r\n". "Reply-To: {$model->email}\r\n". "MIME-Version: 1.0\r\n". "Content-Type: text/plain; charset=UTF-8"; mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers); Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.'); $this->refresh(); } } $this->render('contact',array('model'=>$model)); } public function actionLogin() { $form=new LoginForm; if(isset($_POST['LoginForm'])) { $form->attributes=$_POST['LoginForm']; if($form->validate() && $form->login()) $this->redirect(Yii::app()->user->returnUrl); } $this->render('login',array('form'=>$form)); } public function actionLogout() { Yii::app()->user->logout(); $this->redirect(Yii::app()->homeUrl); } ``` } herers the model ``` <?php class LoginForm extends CFormModel { public $email; public $password; private $_identity; public function rules() { return array( array('email, password', 'required'), array('email', 'email'), array('password', 'authenticate'), ); } public function attributeLabels() { return array('email'=>'Email Address'); } public function authenticate($attribute,$params) { if(!$this->hasErrors()) // we only want to authenticate when no input errors { $identity=new UserIdentity($this->email,$this->password); $identity->authenticate(); switch($identity->errorCode) { case UserIdentity::ERROR_NONE: Yii::app()->user->login($identity); break; case UserIdentity::ERROR_USERNAME_INVALID: $this->addError('email','Email address is incorrect.'); break; default: // UserIdentity::ERROR_PASSWORD_INVALID $this->addError('password','Password is incorrect.'); break; } } } public function login() { if($this->_identity===null) { $this->_identity=new UserIdentity($this->username,$this->password); $this->_identity->authenticate(); } if($this->_identity->errorCode===UserIdentity::ERROR_NONE) { $duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days Yii::app()->user->login($this->_identity,$duration); return true; } else return false; } ``` } here the view ``` <?php /* @var $this SiteController */ /* @var $model LoginForm */ /* @var $form CActiveForm */ $this->pageTitle=Yii::app()->name . ' - Login'; $this->breadcrumbs=array( 'Login', ); ?> <h1>Login</h1> <p>Please fill out the following form with your login credentials:</p> <div class="form"> <?php $myWidget=$this->beginWidget('CActiveForm', array( 'id'=>'login-form', 'enableClientValidation'=>true, 'clientOptions'=>array( 'validateOnSubmit'=>true, ), )); ?> <p class="note">Fields with <span class="required">*</span> are required.</p> <div> <?php echo CHtml::beginForm(); ?> <?php echo CHtml::errorSummary($form); ?> <div> <?php echo CHtml::activeLabel($form,'email'); ?> <?php echo CHtml::activeTextField($form,'email') ?> </div> <div> <?php echo CHtml::activeLabel($form,'password'); ?> <?php echo CHtml::activePasswordField($form,'password') ?> </div> <div> <?php echo CHtml::submitButton('Login'); ?> </div> <?php echo CHtml::endForm(); ?> ``` endWidget(); ?>
2014/09/26
[ "https://Stackoverflow.com/questions/26051939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3584871/" ]
You have to write your authentication logic inside UserIdentity class not in LoginForm model. 1. LoginForm model ex:- ``` public function authenticate($attribute, $params) { if (!$this->hasErrors()) { $this->_identity = new UserIdentity($this->email, $this->password); if (!$this->_identity->authenticate()) $this->addError('password', 'Incorrect username or password.'); } } public function login() { if ($this->_identity === null) { $this->_identity = new UserIdentity($this->email, $this->password); $this->_identity->authenticate(); } if ($this->_identity->errorCode === UserIdentity::ERROR_NONE) { $duration = $this->rememberMe ? 3600 * 24 * 30 : 0; // 30 days Yii::app()->user->login($this->_identity, $duration); return true; } else return false; } ``` 2. For database authentication you must have to add your authetication logic inside authenticate function using `components\UserIdentity.php` ``` public function authenticate() { Yii::app()->getModule('auth')->getModule('user'); #import your module. $record = User::model() ->findByAttributes(array('email' => CHtml::encode($this->email))); #database call if ($record === null) $this->errorCode = self::ERROR_USERNAME_INVALID; #else if ($record->password !== crypt($this->password, $record->password)) else if ($record->password !== $this->password) $this->errorCode = self::ERROR_PASSWORD_INVALID; else { $this->_uid = $record->user_id; $this->setState('title', $record->user_name); $this->setState('uid', $this->_uid); $this->errorCode = self::ERROR_NONE; } return !$this->errorCode; ``` } 3. If you have role based login then you have to add WebUser class in config/main.php. ``` components' => array( 'user' => array( // enable cookie-based authentication 'class' => 'WebUser', 'allowAutoLogin' => true, 'loginUrl'=>array('/site/login'), 'returnUrl'=>array('/site/index'), ), } ``` 4. For role based assess check you have to write `components\WebUser.php` Class - ``` class WebUser extends CWebUser { public function checkAccess($operation, $params = array()) { if (empty($this->id)) { // Not identified => no rights return false; } $role = $this->getState("roles"); if ($role === '3') { return true; // super admin role has access to everything }else if ($role === '1') { return true; // admin(manager) role has access to everything } // allow access if the operation request is the current user's role return ($operation === $role); } } ``` For more information check [Authentication and Authorization](http://www.yiiframework.com/doc/guide/1.1/en/topics.auth)
In common/models/User.php ``` public function rules() { return [ ['status', 'default', 'value' => self::STATUS_INACTIVE], ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_INACTIVE, self::STATUS_DELETED]], ]; } ``` In this method, set the default 'value'=>self::STATUS\_ACTIVE your problem will be solved. I also had the same issue. After changing the value to Active, it worked, because the default value it is setting is 9 and the database considers it an inactive entry that's why it is shoeing incorrect id or password. I hope this helps.
14,906,751
I have a byte array of data, which should be consistent cross-platform. Let's say I have a pointer, `unsigned char* data`, which points to some location inside my array, and I want to read 4 bytes into a variable. I would think that I could just to this: ``` uint32_t my_int = *data; ``` However, I realize that method doesn't account for endianness. For example, if my data was in big endian, would I have to do this to read it consistently? ``` uint32_t my_int = (data[0] << 3) + (data[1] << 2) + (data[2] << 1) + data[3]; ``` Likewise, do I have to make the same checks when writing this data with `fwrite`? For example, if I wrote that same data to a file with this code: ``` fwrite(&my_int, sizeof(my_int), 1, fh); ``` Would the resulting data have any known endianness? Or would it be dependent upon architecture? If so, what's the simplest way to do these reads and writes and enforce a particular endianness on *all* platforms?
2013/02/16
[ "https://Stackoverflow.com/questions/14906751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/465378/" ]
You need to worry about endianness whenever reading or writing binary data. You also need to worry about variable size and possibly structure packing if you're trying to read/write entire structs. Some architectures can't handle integers on odd variable boundaries as well, so you can't just grab an integer directly from a binary buffer using something like uint32\_t myInteger = \*(uint32\_t\*)bufferPtr++. There are all sorts of ways to make this work. In the old days, when speed and RAM usage were huge concerns, we would read a chunk of data directly from the file into a buffer and then fix the endianness in-place if needed, using pointers into the structure. You can still do that today, although structure packing differences between compilers make it a hassle, so it may make more sense to write some simple i/o routines for specific types, such as ``` int write_integer_at_position( FILE *, size_t position, uint32_t ); int read_integer_from_position( FILE *, size_t position, uint32_t *outResult ); etc ``` Those routines would swap the bytes if needed, perhaps using htonl, after reading or before writing the data to disk. After you've done this 20 or 30 times you'll probably want to write a data description language of some sort to map between structures in RAM and files. Many people have done it, but I don't think any one in particular has really caught on.
If using integers there is a family of functions/macros See [ntol](http://linux.die.net/man/3/ntohl) for example As to packing - just define a protocol and where things should be placed. Then write could to construct a character array with the various bits in the correct locations. This should correspond to the code the retrieves those details.
14,906,751
I have a byte array of data, which should be consistent cross-platform. Let's say I have a pointer, `unsigned char* data`, which points to some location inside my array, and I want to read 4 bytes into a variable. I would think that I could just to this: ``` uint32_t my_int = *data; ``` However, I realize that method doesn't account for endianness. For example, if my data was in big endian, would I have to do this to read it consistently? ``` uint32_t my_int = (data[0] << 3) + (data[1] << 2) + (data[2] << 1) + data[3]; ``` Likewise, do I have to make the same checks when writing this data with `fwrite`? For example, if I wrote that same data to a file with this code: ``` fwrite(&my_int, sizeof(my_int), 1, fh); ``` Would the resulting data have any known endianness? Or would it be dependent upon architecture? If so, what's the simplest way to do these reads and writes and enforce a particular endianness on *all* platforms?
2013/02/16
[ "https://Stackoverflow.com/questions/14906751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/465378/" ]
You need to worry about endianness whenever reading or writing binary data. You also need to worry about variable size and possibly structure packing if you're trying to read/write entire structs. Some architectures can't handle integers on odd variable boundaries as well, so you can't just grab an integer directly from a binary buffer using something like uint32\_t myInteger = \*(uint32\_t\*)bufferPtr++. There are all sorts of ways to make this work. In the old days, when speed and RAM usage were huge concerns, we would read a chunk of data directly from the file into a buffer and then fix the endianness in-place if needed, using pointers into the structure. You can still do that today, although structure packing differences between compilers make it a hassle, so it may make more sense to write some simple i/o routines for specific types, such as ``` int write_integer_at_position( FILE *, size_t position, uint32_t ); int read_integer_from_position( FILE *, size_t position, uint32_t *outResult ); etc ``` Those routines would swap the bytes if needed, perhaps using htonl, after reading or before writing the data to disk. After you've done this 20 or 30 times you'll probably want to write a data description language of some sort to map between structures in RAM and files. Many people have done it, but I don't think any one in particular has really caught on.
These are typical issues you face when data goes out or come in to your application. If producer and consumer of the data is just your application, then it is less of an issue. However, as EricS mentions, if there are other applications that are going to consume or produce this data and if these are on a different platform / language / framework, then definitely the byte order of how you serialize or deserialize will matter. Network order is a kind of de-facto standard used on IP based protocols. There are library functions that can convert from host to network and network to host orders (see link provided by Ed Heal). Apart from byte order, you may also have to look at bit-order, based on the protocol and platform either the most significant bit or the least significant bit may get pushed out first on the wire. Packing of structures, representation of types ( integers, strings, chars ), its sizes, etc., may need to be considered as well.
41,144,752
I am currently refactoring a codebase inherited from another developer. In several classes, i found constants that contained the symbols =, ? and & (and others). They are used to build URLs, like so: ``` class SomeClass { private static final String EQUALS = "="; private static final String AMPERSAND = "&"; private static final String QUESTION_MARK = "?"; private static final String FORWARD_SLASH = "/"; // ... public String getSomeURL() { return ProjectConstants.BASE_URL + entityName + FORWARD_SLASH + anotherName + QUESTION_MARK + parameterName + EQUALS + parameterValue; } } ``` I do not see the benefit of this. What is the reason for this style instead of just writing `variable + '/' + variable + "?parameterName=" + parameterValue`?
2016/12/14
[ "https://Stackoverflow.com/questions/41144752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3419647/" ]
The constants are useful, but poorly named. If they're used in URL construction, they should be named like this: ``` private static final String PARAMETER_ASSIGNMENT = "="; private static final String PARAMETER_SEPARATOR = "&"; private static final String QUERY_INTRODUCER = "?"; private static final String PATH_SEPARATOR = "/"; ``` That way, their names will refer to their *semantics* (which they should) and not to their *contents* (the whole point is to *abstract* away from the contents!). The code of `getSomeURL()` will then much more directly signal what it really does: ``` public String getSomeURL() { return ProjectConstants.BASE_URL + entityName + PATH_SEPARATOR + anotherName + QUERY_INTRODUCER + parameterName + PARAMETER_ASSIGNMENT + parameterValue; } ```
I think there are not *any* deep technical reasons here The only *little* thing I see: they make typos like "==" less likely to happen, as EQUALS + EQUALS is obviously more obvious to spot. On the other hand, that shouldn't really matter in reality; because in reality you would be calling *helper* methods to build those URLs anyway. So, once you got the helpers right, few chances of ever having typos in that "generated" content. But even then I would not be using String constants but char values.
48,354,155
I want to set autocomplete text in my application. The suggestion values will fetch from the database. But for a trial I made a string array for the suggestion values. It works fine when I implement it on an activity but not working in fragment. In place of getActivity function I tried: 1) getContext() 2) this.getActivity() 3) (Search\_Bus)getActivity() but none work... it's giving me error: > > Attempt to invoke virtual method on a null object reference > > > Here's my code... ``` public class Bus_Schedule_tab3 extends Fragment { AutoCompleteTextView autoCompleteTextView; ArrayList<String> array; ArrayAdapter<String> adapter; String[] stop_names; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.bus_schedule_tab3, container, false); stop_names = new String[] {"usa","china","russia","bangladesh"}; autoCompleteTextView = (AutoCompleteTextView)rootView.findViewById(R.id.autoCompleteTextView2); adapter = new ArrayAdapter<String>(getActivity(),R.layout.support_simple_spinner_dropdown_item,stop_names); autoCompleteTextView.setAdapter(adapter); return rootView; } ```
2018/01/20
[ "https://Stackoverflow.com/questions/48354155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5041813/" ]
Its working for me...You missed to set threshold ``` AutoCompleteTextView autoCompleteTextView; ArrayAdapter<String> adapter; String[] stop_names; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_test, container, false); stop_names = new String[]{"usa", "china", "russia", "bangladesh"}; autoCompleteTextView = rootView.findViewById(R.id.autoCompleteTextView2); adapter = new ArrayAdapter<>(getActivity(), R.layout.support_simple_spinner_dropdown_item, stop_names); autoCompleteTextView.setThreshold(1); autoCompleteTextView.setAdapter(adapter); return rootView; } ```
Set in your xml file android:completionThreshold. ``` <AutoCompleteTextView android:id="@+id/id" android:layout_width="match_parent" android:layout_height="wrap_content" android:completionThreshold="1" android:layout_weight="1"/> ```
28,513,470
i have a ready to use .jar file and want to know if its possible to extract and rename the packages? so when usually i start the .jar file with: ``` java -cp myFile.jar com.codehelper.demo.Main ``` i want to rename the "codehelper" in it to something different that i can run it by ``` java -cp myFile.jar com.NEW_NAME.demo.Main ``` i tried to decompile all files, add it to the folderstructure with renamed "codehelper" path and compile it again but it didnt work. i also renamed all the package includes in each file like ``` import com.codehelper... ``` so is my goal unreachable or can i do this? and if someone can explain me how to do, it will be very nice. thank you and sory for my poor english edit: it seems the only file i cant compile is a file containing this switch case. ``` private int priotiryLevel(DiscoveryInfoBehave info) { int ret = 0; switch (1.$SwitchMap$com$peerialism$natcracker$common$GatewayDevice$GatewayType[info.getNatDevice().getGatewayType().ordinal()]) { case 1: ret = 0; break; case 2: ret = 4; break; case 3: ret = 5; break; } return ret; } ``` i tried also to rename the specific word inside this switch case but no effort.
2015/02/14
[ "https://Stackoverflow.com/questions/28513470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4522486/" ]
There is a problem in controller parameter injection. You have not added `$routeParams` in your array injection list. ``` ngAddressBook.controller('ngAddressDetailsController', ['$scope','$routeParams', function ($scope,$routeParams) { alert($routeParams); $scope.id = $routeParams.id; }]); ```
As I found this on top on google: apart from the missing injection - asign the object `$routeParams` and not the Key `$routeParams.id` [I found the explination here (from Sander Elias)](https://groups.google.com/forum/?fromgroups#!topic/angular/_3OtYYRe_-I) ``` ngAddressBook.controller('ngAddressDetailsController', ['$scope','$routeParams', function ($scope,$routeParams) { $scope.id = $routeParams alert($routeParams); }]); ```
16,359,651
I'm trying to add USB controller support to my Android game. I'm using Marmalade and I've created an extension based on the USB example code. Here it is: ``` public class GameControllerInput extends Activity implements InputManager.InputDeviceListener { private static final String TAG = "GameControllerInput"; private InputManager mInputManager; private SparseArray<InputDeviceState> mInputDeviceStates; private static int numEvents = 0; public int EDK_GameControllerInput_Init() { LoaderActivity.m_Activity.runOnUiThread(new Runnable() { public void run() { Log.i(TAG, "Running 1 ========================="); } }); Log.i(TAG, "Init 2 ========================="); return 1; ``` When I call the init function I get this error: ``` java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() ``` I've read other threads with this error and they say the solution is to add the `LoaderActivity.m_Activity.runOnUiThread(new Runnable()` code. However, as you can see, adding this just gives me the same error. I'm not experienced with Java and I'm at a loss on how to fix this. Any help would be greatly appreciated. Cheers, Steve
2013/05/03
[ "https://Stackoverflow.com/questions/16359651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2346286/" ]
A `Looper` (a message queue processor) is tied to a single thread, each thread has at most one looper. A `Handler` needs to register itself with a `Looper` to work, so each time you invoke `new Handler()`, it tries to get the `Looper` for the current thread (the thread that's creating the `Handler`), which can be either present or not. The exception that you see is thrown because the thread that's creating the handler does not have a looper. There is one two things that you can do to fix this: * Add a `Looper` to the current thread. * Make sure you're creating the `Handler` on a thread that already has a `Looper`. In almost all cases, the handler is used to communicate from a background thread to the UI thread, I'm assuming that's the case here. That means option 2. Your `runOnUiThread(Runnable)` thing is close, but no cigar, because all it does is write to the log file. You need to move the code that creates the `new Handler()` (not shown in your posted code sample) into the `runOnUiThread` block, or use some other way to get it to run on the UI thread. The typical way to do this is to create it in the `onCreate(Bundle)` method of your activity or fragment. Keep in mind that, depending on your initialization order, this may mean it's initially `null` as seen by your background thread, so the background code will have to be able to deal with that.
Well it's better to have a callback method and mark it as main thread only by calling `run_on_os_thread` after the method declaration in `s4e` file.
33,876
Count the number of paths from $(0,0)$ to $(2n,n)$ than never go above $y=x$ At first I thought of the problem by expanding the graph to $(0,0)$ to $(2n,2n)$ and messing around with adding and subtracting multiples of the Catalan number formula, but I feel this is far too rudimentary and in doing so I am leaving out many paths that move through the $x=n$ to $x=2n$ and $y=0$ to $y=n$ square section of the graph that has no restrictions (because the diagonal cuts off at $(n,n)$). Of course, you can only go right and up. Thanks!
2011/04/19
[ "https://math.stackexchange.com/questions/33876", "https://math.stackexchange.com", "https://math.stackexchange.com/users/9755/" ]
The [Ballot theorem](http://en.wikipedia.org/wiki/Ballot_problem) says > > In an election where candidate A receives $p$ votes and candidate B $q$ votes with $p$ > $q$, the probability that A will be strictly ahead of B throughout the count is $\dfrac{p-q}{p+q}$ > > > So if you had asked "Count the number of paths from $(0,0)$ to $(2n,n)$ than never *touch* $y=x$" then the answer would have been $$\dfrac{n}{3n} {3n \choose n}$$ which can be slightly simplified. But you want "never go above $y=x$" and this is equivalent to counting the paths from $(-1,0)$ to $(2n,n)$ that never touch $y=x+1$, equivalently the paths from $(0,0)$ to $(2n+1,n)$ that never touch $y=x$. Since this may be homework, perhaps you should try a little to finish this off.
The most straightforward way of doing this seems to be to partition based on where the paths cross over from $x=n$ to $x=n+1$ and then staple together the two calculations: first, how many paths from $(0,0)$ to $(n, k)$ ($k \leq n$) never go above the diagonal (this should be feasible through versions of the usual machinations that bring you to the Catalan numbers), and then how many paths there are from $(n+1, k)$ to $(2n, n)$ (which is, of course, the same as the number of paths from $(0, 0)$ to $(n-1, n-k)$ and is readily evaluated).
34,726,667
**Quick Background** I have received a project from our marketing team to make bulk updates to the descriptions of products that will be displayed on our website (>500k items). They have decided to take many decades worth of descriptions and try to make them as similar as possible. (Ex. 'screw driver', 'screwdriver', 'screw-driver' should all look like 'Screwdriver') I successfully accomplished the task at hand to 95% of their satisfaction using a clunky, long and hard to maintain series of update statements on a table only I maintain, to modify the strings. I then pass these on to our web deployment team, but wasn't thinking they would want to maintain this indefinitely. I can easily produce a table of sub-strings and conditions to find and what to replace portions of the string. I think something depending on a table like this would be easiest to maintain for 90% of the cases we encounter. Now, I'm uncertain about the best way to proceed to make this dependable and easy to maintain. I've received conflicting information that a good use would be a 'while loop' and other say a Cursor would be just fine. **Now to the question** Given we will/may/could be adding somewhere around 1k new products a month, and I have a table of conditions like the following, what is the most efficient and dependable way to execute the manipulation regularly? --- Condition, Find\_substring, Replace\_with --- like '%screw driver%', 'screw driver', 'Screwdriver' --- like '%screw-driver%', 'screw driver', 'Screwdriver' --- like '%screwdriver%', 'screwdriver', 'Screwdriver' **Open to any and all ideas, suggestions and advice.**
2016/01/11
[ "https://Stackoverflow.com/questions/34726667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4528764/" ]
If your rules are really as simple as that then simply having "old\_value" and "new\_value" in the table should suffice, with a single statement to fix all of the data: ``` UPDATE MT SET description = REPLACE(description, old_value, new_value) FROM dbo.My_Table MT INNER JOIN dbo.Fix_Table FT ON MT.description LIKE '%' + FT.old_value + '%' ``` You might need to adjust the query if you expect multiple matches on a single product. Also, be careful of strings that might be part of another string. For example, fixing "ax" to "axe" might cause problems with a "fax machine". There are a lot of little details like this that might affect the exact approach.
Have a table like bad\_val and good\_val (call it tblMod). you can write a stored procedure that loops on tblMod and generate SQL statement and execute the statement as dynamic SQL. ``` loop on tblMod -- generate SQL statements like: set sqlText = 'update myTable set description = ' + good_val + ' where description = ' + bad_val sp_execute sqlText ``` This approach also allows you to use SQL functions or any other functions in good\_val field of tblMod. for instance you can have below data in good\_val field: 'upper(description)' or 'substring(description, 1 ,4)' as you are generating dynamic SQL, those will work. in this case your sqlText will be something like ``` 'update myTable set description = substring(description, 1, 4) where description = 'some bad value' ``` example above might not be correct but I hope you get my idea.
16,939,814
I am getting this `android.util.AndroidRuntimeException: requestFeature() must be called before adding content` error. As you can see in the below code, the `requestWindowFeature(Window.FEATURE_NO_TITLE);` line comes before `setContentView(R.layout.mainmenu);` line of code. This onCreate() code is the same format in just about every one of my activities and I've never had trouble with it before until now. Ever since I updated to ADT 22 a lot of random errors have been popping up everywhere. I have weeded through a lot of those errors and this is my latest one. What can I do to fix this error? ``` @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mainmenu); ``` LogCat ``` 05-31 04:20:43.121: E/AndroidRuntime(14559): FATAL EXCEPTION: main 05-31 04:20:43.121: E/AndroidRuntime(14559): java.lang.RuntimeException: Unable to start activity ComponentInfo{matt.lyons.bibletrivia.lite/matt.lyons.bibletrivia.lite.MainMenu}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.access$600(ActivityThread.java:141) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Handler.dispatchMessage(Handler.java:99) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Looper.loop(Looper.java:137) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.main(ActivityThread.java:5041) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invokeNative(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invoke(Method.java:511) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 05-31 04:20:43.121: E/AndroidRuntime(14559): at dalvik.system.NativeStart.main(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:229) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.requestWindowFeature(Activity.java:3244) 05-31 04:20:43.121: E/AndroidRuntime(14559): at matt.lyons.bibletrivia.lite.MainMenu.onCreate(MainMenu.java:28) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.performCreate(Activity.java:5104) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 05-31 04:20:43.121: E/AndroidRuntime(14559): ... 11 more ```
2013/06/05
[ "https://Stackoverflow.com/questions/16939814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1866707/" ]
I also faced this problem but when i call window request before calling **super.onCreate()** then problem was solved, please try it also like.. ``` @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.mainmenu); } ``` Hope this will help you...:) --- **Edited: For other possible solutions for Android'd new versions** **Hide the Status Bar on Android 4.0 and Lower** ``` <application ... android:theme="@android:style/Theme.Holo.NoActionBar.Fullscreen" > ... </application> ``` The advantages of using an activity theme are as follows: * It's easier to maintain and less error-prone than setting a flag programmatically. * It results in smoother UI transitions, because the system has the information it needs to render your UI before instantiating your app's main activity. --- **Android version is lower than Jellybean** ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // If the Android version is lower than Jellybean, use this call to hide // the status bar. if (Build.VERSION.SDK_INT < 16) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } setContentView(R.layout.activity_main); } ``` --- **Hide the Status Bar on Android 4.1 and Higher** ``` View decorView = getWindow().getDecorView(); // Hide the status bar. int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN; decorView.setSystemUiVisibility(uiOptions); // Remember that you should never show the action bar if the // status bar is hidden, so hide that too if necessary. ActionBar actionBar = getActionBar(); actionBar.hide(); ``` Note the following: * Once UI flags have been cleared (for example, by navigating away from the activity), your app needs to reset them if you want to hide the bars again. See [Responding to UI Visibility Changes](http://developer.android.com/training/system-ui/visibility.html) for a discussion of how to listen for UI visibility changes so that your app can respond accordingly. * Where you set the UI flags makes a difference. If you hide the system bars in your activity's onCreate() method and the user presses Home, the system bars will reappear. When the user reopens the activity, onCreate() won't get called, so the system bars will remain visible. If you want system UI changes to persist as the user navigates in and out of your activity, set UI flags in onResume() or onWindowFocusChanged(). * The method setSystemUiVisibility() only has an effect if the view you call it from is visible. * Navigating away from the view causes flags set with setSystemUiVisibility() to be cleared.
Extend (**Activity**) instead of (**ActionBarActivity**) example: `public class Itemdetails extends Activity {....` then in the onCreate write: ``` super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.Your_Activity); ```
16,939,814
I am getting this `android.util.AndroidRuntimeException: requestFeature() must be called before adding content` error. As you can see in the below code, the `requestWindowFeature(Window.FEATURE_NO_TITLE);` line comes before `setContentView(R.layout.mainmenu);` line of code. This onCreate() code is the same format in just about every one of my activities and I've never had trouble with it before until now. Ever since I updated to ADT 22 a lot of random errors have been popping up everywhere. I have weeded through a lot of those errors and this is my latest one. What can I do to fix this error? ``` @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mainmenu); ``` LogCat ``` 05-31 04:20:43.121: E/AndroidRuntime(14559): FATAL EXCEPTION: main 05-31 04:20:43.121: E/AndroidRuntime(14559): java.lang.RuntimeException: Unable to start activity ComponentInfo{matt.lyons.bibletrivia.lite/matt.lyons.bibletrivia.lite.MainMenu}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.access$600(ActivityThread.java:141) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Handler.dispatchMessage(Handler.java:99) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Looper.loop(Looper.java:137) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.main(ActivityThread.java:5041) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invokeNative(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invoke(Method.java:511) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 05-31 04:20:43.121: E/AndroidRuntime(14559): at dalvik.system.NativeStart.main(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:229) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.requestWindowFeature(Activity.java:3244) 05-31 04:20:43.121: E/AndroidRuntime(14559): at matt.lyons.bibletrivia.lite.MainMenu.onCreate(MainMenu.java:28) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.performCreate(Activity.java:5104) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 05-31 04:20:43.121: E/AndroidRuntime(14559): ... 11 more ```
2013/06/05
[ "https://Stackoverflow.com/questions/16939814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1866707/" ]
```html <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <item name="android:windowActionBar">false</item> </style> ``` just only set style like this no any coding side changing is required.
I had this error with `AlertDialog` and the error was happening in API 19 only when `dialog.show()` was called. figured out that the `android.app.AlertDialog` import is causing the problem so I changed it to `androidx.appcompat.app.AlertDialog` and it fixed it. Note that this will work if you are using androidx. if you are not, you should use the old appcompat version of that import.
16,939,814
I am getting this `android.util.AndroidRuntimeException: requestFeature() must be called before adding content` error. As you can see in the below code, the `requestWindowFeature(Window.FEATURE_NO_TITLE);` line comes before `setContentView(R.layout.mainmenu);` line of code. This onCreate() code is the same format in just about every one of my activities and I've never had trouble with it before until now. Ever since I updated to ADT 22 a lot of random errors have been popping up everywhere. I have weeded through a lot of those errors and this is my latest one. What can I do to fix this error? ``` @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mainmenu); ``` LogCat ``` 05-31 04:20:43.121: E/AndroidRuntime(14559): FATAL EXCEPTION: main 05-31 04:20:43.121: E/AndroidRuntime(14559): java.lang.RuntimeException: Unable to start activity ComponentInfo{matt.lyons.bibletrivia.lite/matt.lyons.bibletrivia.lite.MainMenu}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.access$600(ActivityThread.java:141) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Handler.dispatchMessage(Handler.java:99) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Looper.loop(Looper.java:137) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.main(ActivityThread.java:5041) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invokeNative(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invoke(Method.java:511) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 05-31 04:20:43.121: E/AndroidRuntime(14559): at dalvik.system.NativeStart.main(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:229) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.requestWindowFeature(Activity.java:3244) 05-31 04:20:43.121: E/AndroidRuntime(14559): at matt.lyons.bibletrivia.lite.MainMenu.onCreate(MainMenu.java:28) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.performCreate(Activity.java:5104) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 05-31 04:20:43.121: E/AndroidRuntime(14559): ... 11 more ```
2013/06/05
[ "https://Stackoverflow.com/questions/16939814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1866707/" ]
I got that exception (`android.util.AndroidRuntimeException: requestFeature() must be called before adding content`) when using ``` requestWindowFeature(Window.FEATURE_NO_TITLE); ``` in an older device running Android 2.3.5 (Gingerbread). I am using the v7 support library. The error was fixed when I changed it to use: ``` supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); ``` (This comes after my super.onCreate call in the fix, too). See docs at <https://developer.android.com/reference/android/support/v7/app/ActionBarActivity.html#supportRequestWindowFeature(int)> So it may be more a case of a misleading error message than anything else.
i think the simplest way to do this is use this below code ``` getActionBar().setTitle(null); ```
16,939,814
I am getting this `android.util.AndroidRuntimeException: requestFeature() must be called before adding content` error. As you can see in the below code, the `requestWindowFeature(Window.FEATURE_NO_TITLE);` line comes before `setContentView(R.layout.mainmenu);` line of code. This onCreate() code is the same format in just about every one of my activities and I've never had trouble with it before until now. Ever since I updated to ADT 22 a lot of random errors have been popping up everywhere. I have weeded through a lot of those errors and this is my latest one. What can I do to fix this error? ``` @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mainmenu); ``` LogCat ``` 05-31 04:20:43.121: E/AndroidRuntime(14559): FATAL EXCEPTION: main 05-31 04:20:43.121: E/AndroidRuntime(14559): java.lang.RuntimeException: Unable to start activity ComponentInfo{matt.lyons.bibletrivia.lite/matt.lyons.bibletrivia.lite.MainMenu}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.access$600(ActivityThread.java:141) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Handler.dispatchMessage(Handler.java:99) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Looper.loop(Looper.java:137) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.main(ActivityThread.java:5041) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invokeNative(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invoke(Method.java:511) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 05-31 04:20:43.121: E/AndroidRuntime(14559): at dalvik.system.NativeStart.main(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:229) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.requestWindowFeature(Activity.java:3244) 05-31 04:20:43.121: E/AndroidRuntime(14559): at matt.lyons.bibletrivia.lite.MainMenu.onCreate(MainMenu.java:28) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.performCreate(Activity.java:5104) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 05-31 04:20:43.121: E/AndroidRuntime(14559): ... 11 more ```
2013/06/05
[ "https://Stackoverflow.com/questions/16939814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1866707/" ]
I also faced this problem but when i call window request before calling **super.onCreate()** then problem was solved, please try it also like.. ``` @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.mainmenu); } ``` Hope this will help you...:) --- **Edited: For other possible solutions for Android'd new versions** **Hide the Status Bar on Android 4.0 and Lower** ``` <application ... android:theme="@android:style/Theme.Holo.NoActionBar.Fullscreen" > ... </application> ``` The advantages of using an activity theme are as follows: * It's easier to maintain and less error-prone than setting a flag programmatically. * It results in smoother UI transitions, because the system has the information it needs to render your UI before instantiating your app's main activity. --- **Android version is lower than Jellybean** ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // If the Android version is lower than Jellybean, use this call to hide // the status bar. if (Build.VERSION.SDK_INT < 16) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } setContentView(R.layout.activity_main); } ``` --- **Hide the Status Bar on Android 4.1 and Higher** ``` View decorView = getWindow().getDecorView(); // Hide the status bar. int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN; decorView.setSystemUiVisibility(uiOptions); // Remember that you should never show the action bar if the // status bar is hidden, so hide that too if necessary. ActionBar actionBar = getActionBar(); actionBar.hide(); ``` Note the following: * Once UI flags have been cleared (for example, by navigating away from the activity), your app needs to reset them if you want to hide the bars again. See [Responding to UI Visibility Changes](http://developer.android.com/training/system-ui/visibility.html) for a discussion of how to listen for UI visibility changes so that your app can respond accordingly. * Where you set the UI flags makes a difference. If you hide the system bars in your activity's onCreate() method and the user presses Home, the system bars will reappear. When the user reopens the activity, onCreate() won't get called, so the system bars will remain visible. If you want system UI changes to persist as the user navigates in and out of your activity, set UI flags in onResume() or onWindowFocusChanged(). * The method setSystemUiVisibility() only has an effect if the view you call it from is visible. * Navigating away from the view causes flags set with setSystemUiVisibility() to be cleared.
Please try the following options, at least one of these should work for you: 1. If you are using a DialogFragment then try not overriding both methods `onCreateDialog(..)` and `onCreateView(..)` (This change worked for me) 2. try `supportRequestWindowFeature(Window.FEATURE_NO_TITLE)/requestWindowFeature(Window.FEATURE_NO_TITLE)` before `setContentView(..)` in the activity and after `super.onCreate(..);` 3. Try option 2 before `super.onCreate(..);`
16,939,814
I am getting this `android.util.AndroidRuntimeException: requestFeature() must be called before adding content` error. As you can see in the below code, the `requestWindowFeature(Window.FEATURE_NO_TITLE);` line comes before `setContentView(R.layout.mainmenu);` line of code. This onCreate() code is the same format in just about every one of my activities and I've never had trouble with it before until now. Ever since I updated to ADT 22 a lot of random errors have been popping up everywhere. I have weeded through a lot of those errors and this is my latest one. What can I do to fix this error? ``` @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mainmenu); ``` LogCat ``` 05-31 04:20:43.121: E/AndroidRuntime(14559): FATAL EXCEPTION: main 05-31 04:20:43.121: E/AndroidRuntime(14559): java.lang.RuntimeException: Unable to start activity ComponentInfo{matt.lyons.bibletrivia.lite/matt.lyons.bibletrivia.lite.MainMenu}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.access$600(ActivityThread.java:141) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Handler.dispatchMessage(Handler.java:99) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Looper.loop(Looper.java:137) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.main(ActivityThread.java:5041) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invokeNative(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invoke(Method.java:511) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 05-31 04:20:43.121: E/AndroidRuntime(14559): at dalvik.system.NativeStart.main(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:229) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.requestWindowFeature(Activity.java:3244) 05-31 04:20:43.121: E/AndroidRuntime(14559): at matt.lyons.bibletrivia.lite.MainMenu.onCreate(MainMenu.java:28) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.performCreate(Activity.java:5104) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 05-31 04:20:43.121: E/AndroidRuntime(14559): ... 11 more ```
2013/06/05
[ "https://Stackoverflow.com/questions/16939814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1866707/" ]
I was extending a **DialogFragment** and the above answer didnot work. I had to use getDialog() to remove the title: ``` getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); ```
i think the simplest way to do this is use this below code ``` getActionBar().setTitle(null); ```
16,939,814
I am getting this `android.util.AndroidRuntimeException: requestFeature() must be called before adding content` error. As you can see in the below code, the `requestWindowFeature(Window.FEATURE_NO_TITLE);` line comes before `setContentView(R.layout.mainmenu);` line of code. This onCreate() code is the same format in just about every one of my activities and I've never had trouble with it before until now. Ever since I updated to ADT 22 a lot of random errors have been popping up everywhere. I have weeded through a lot of those errors and this is my latest one. What can I do to fix this error? ``` @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mainmenu); ``` LogCat ``` 05-31 04:20:43.121: E/AndroidRuntime(14559): FATAL EXCEPTION: main 05-31 04:20:43.121: E/AndroidRuntime(14559): java.lang.RuntimeException: Unable to start activity ComponentInfo{matt.lyons.bibletrivia.lite/matt.lyons.bibletrivia.lite.MainMenu}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.access$600(ActivityThread.java:141) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Handler.dispatchMessage(Handler.java:99) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Looper.loop(Looper.java:137) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.main(ActivityThread.java:5041) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invokeNative(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invoke(Method.java:511) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 05-31 04:20:43.121: E/AndroidRuntime(14559): at dalvik.system.NativeStart.main(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:229) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.requestWindowFeature(Activity.java:3244) 05-31 04:20:43.121: E/AndroidRuntime(14559): at matt.lyons.bibletrivia.lite.MainMenu.onCreate(MainMenu.java:28) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.performCreate(Activity.java:5104) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 05-31 04:20:43.121: E/AndroidRuntime(14559): ... 11 more ```
2013/06/05
[ "https://Stackoverflow.com/questions/16939814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1866707/" ]
```html <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <item name="android:windowActionBar">false</item> </style> ``` just only set style like this no any coding side changing is required.
Misplaced your line: super.onCreate(savedInstanceState); use this Manner: ``` @Override protected void onCreate(Bundle savedInstanceState) { this.requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_qrscanner); ```
16,939,814
I am getting this `android.util.AndroidRuntimeException: requestFeature() must be called before adding content` error. As you can see in the below code, the `requestWindowFeature(Window.FEATURE_NO_TITLE);` line comes before `setContentView(R.layout.mainmenu);` line of code. This onCreate() code is the same format in just about every one of my activities and I've never had trouble with it before until now. Ever since I updated to ADT 22 a lot of random errors have been popping up everywhere. I have weeded through a lot of those errors and this is my latest one. What can I do to fix this error? ``` @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mainmenu); ``` LogCat ``` 05-31 04:20:43.121: E/AndroidRuntime(14559): FATAL EXCEPTION: main 05-31 04:20:43.121: E/AndroidRuntime(14559): java.lang.RuntimeException: Unable to start activity ComponentInfo{matt.lyons.bibletrivia.lite/matt.lyons.bibletrivia.lite.MainMenu}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.access$600(ActivityThread.java:141) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Handler.dispatchMessage(Handler.java:99) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Looper.loop(Looper.java:137) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.main(ActivityThread.java:5041) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invokeNative(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invoke(Method.java:511) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 05-31 04:20:43.121: E/AndroidRuntime(14559): at dalvik.system.NativeStart.main(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:229) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.requestWindowFeature(Activity.java:3244) 05-31 04:20:43.121: E/AndroidRuntime(14559): at matt.lyons.bibletrivia.lite.MainMenu.onCreate(MainMenu.java:28) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.performCreate(Activity.java:5104) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 05-31 04:20:43.121: E/AndroidRuntime(14559): ... 11 more ```
2013/06/05
[ "https://Stackoverflow.com/questions/16939814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1866707/" ]
I was extending a **DialogFragment** and the above answer didnot work. I had to use getDialog() to remove the title: ``` getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); ```
I had this error with `AlertDialog` and the error was happening in API 19 only when `dialog.show()` was called. figured out that the `android.app.AlertDialog` import is causing the problem so I changed it to `androidx.appcompat.app.AlertDialog` and it fixed it. Note that this will work if you are using androidx. if you are not, you should use the old appcompat version of that import.
16,939,814
I am getting this `android.util.AndroidRuntimeException: requestFeature() must be called before adding content` error. As you can see in the below code, the `requestWindowFeature(Window.FEATURE_NO_TITLE);` line comes before `setContentView(R.layout.mainmenu);` line of code. This onCreate() code is the same format in just about every one of my activities and I've never had trouble with it before until now. Ever since I updated to ADT 22 a lot of random errors have been popping up everywhere. I have weeded through a lot of those errors and this is my latest one. What can I do to fix this error? ``` @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mainmenu); ``` LogCat ``` 05-31 04:20:43.121: E/AndroidRuntime(14559): FATAL EXCEPTION: main 05-31 04:20:43.121: E/AndroidRuntime(14559): java.lang.RuntimeException: Unable to start activity ComponentInfo{matt.lyons.bibletrivia.lite/matt.lyons.bibletrivia.lite.MainMenu}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.access$600(ActivityThread.java:141) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Handler.dispatchMessage(Handler.java:99) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Looper.loop(Looper.java:137) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.main(ActivityThread.java:5041) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invokeNative(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invoke(Method.java:511) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 05-31 04:20:43.121: E/AndroidRuntime(14559): at dalvik.system.NativeStart.main(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:229) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.requestWindowFeature(Activity.java:3244) 05-31 04:20:43.121: E/AndroidRuntime(14559): at matt.lyons.bibletrivia.lite.MainMenu.onCreate(MainMenu.java:28) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.performCreate(Activity.java:5104) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 05-31 04:20:43.121: E/AndroidRuntime(14559): ... 11 more ```
2013/06/05
[ "https://Stackoverflow.com/questions/16939814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1866707/" ]
Please check your class is extend from Activity or ActionBarActivity. If you are using ActionBarActivity please use Activity.
Please try the following options, at least one of these should work for you: 1. If you are using a DialogFragment then try not overriding both methods `onCreateDialog(..)` and `onCreateView(..)` (This change worked for me) 2. try `supportRequestWindowFeature(Window.FEATURE_NO_TITLE)/requestWindowFeature(Window.FEATURE_NO_TITLE)` before `setContentView(..)` in the activity and after `super.onCreate(..);` 3. Try option 2 before `super.onCreate(..);`
16,939,814
I am getting this `android.util.AndroidRuntimeException: requestFeature() must be called before adding content` error. As you can see in the below code, the `requestWindowFeature(Window.FEATURE_NO_TITLE);` line comes before `setContentView(R.layout.mainmenu);` line of code. This onCreate() code is the same format in just about every one of my activities and I've never had trouble with it before until now. Ever since I updated to ADT 22 a lot of random errors have been popping up everywhere. I have weeded through a lot of those errors and this is my latest one. What can I do to fix this error? ``` @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mainmenu); ``` LogCat ``` 05-31 04:20:43.121: E/AndroidRuntime(14559): FATAL EXCEPTION: main 05-31 04:20:43.121: E/AndroidRuntime(14559): java.lang.RuntimeException: Unable to start activity ComponentInfo{matt.lyons.bibletrivia.lite/matt.lyons.bibletrivia.lite.MainMenu}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.access$600(ActivityThread.java:141) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Handler.dispatchMessage(Handler.java:99) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Looper.loop(Looper.java:137) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.main(ActivityThread.java:5041) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invokeNative(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invoke(Method.java:511) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 05-31 04:20:43.121: E/AndroidRuntime(14559): at dalvik.system.NativeStart.main(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:229) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.requestWindowFeature(Activity.java:3244) 05-31 04:20:43.121: E/AndroidRuntime(14559): at matt.lyons.bibletrivia.lite.MainMenu.onCreate(MainMenu.java:28) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.performCreate(Activity.java:5104) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 05-31 04:20:43.121: E/AndroidRuntime(14559): ... 11 more ```
2013/06/05
[ "https://Stackoverflow.com/questions/16939814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1866707/" ]
Please check your class is extend from Activity or ActionBarActivity. If you are using ActionBarActivity please use Activity.
Misplaced your line: super.onCreate(savedInstanceState); use this Manner: ``` @Override protected void onCreate(Bundle savedInstanceState) { this.requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_qrscanner); ```
16,939,814
I am getting this `android.util.AndroidRuntimeException: requestFeature() must be called before adding content` error. As you can see in the below code, the `requestWindowFeature(Window.FEATURE_NO_TITLE);` line comes before `setContentView(R.layout.mainmenu);` line of code. This onCreate() code is the same format in just about every one of my activities and I've never had trouble with it before until now. Ever since I updated to ADT 22 a lot of random errors have been popping up everywhere. I have weeded through a lot of those errors and this is my latest one. What can I do to fix this error? ``` @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mainmenu); ``` LogCat ``` 05-31 04:20:43.121: E/AndroidRuntime(14559): FATAL EXCEPTION: main 05-31 04:20:43.121: E/AndroidRuntime(14559): java.lang.RuntimeException: Unable to start activity ComponentInfo{matt.lyons.bibletrivia.lite/matt.lyons.bibletrivia.lite.MainMenu}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.access$600(ActivityThread.java:141) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Handler.dispatchMessage(Handler.java:99) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.os.Looper.loop(Looper.java:137) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.main(ActivityThread.java:5041) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invokeNative(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): at java.lang.reflect.Method.invoke(Method.java:511) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 05-31 04:20:43.121: E/AndroidRuntime(14559): at dalvik.system.NativeStart.main(Native Method) 05-31 04:20:43.121: E/AndroidRuntime(14559): Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content 05-31 04:20:43.121: E/AndroidRuntime(14559): at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:229) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.requestWindowFeature(Activity.java:3244) 05-31 04:20:43.121: E/AndroidRuntime(14559): at matt.lyons.bibletrivia.lite.MainMenu.onCreate(MainMenu.java:28) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Activity.performCreate(Activity.java:5104) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 05-31 04:20:43.121: E/AndroidRuntime(14559): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 05-31 04:20:43.121: E/AndroidRuntime(14559): ... 11 more ```
2013/06/05
[ "https://Stackoverflow.com/questions/16939814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1866707/" ]
I also faced this problem but when i call window request before calling **super.onCreate()** then problem was solved, please try it also like.. ``` @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.mainmenu); } ``` Hope this will help you...:) --- **Edited: For other possible solutions for Android'd new versions** **Hide the Status Bar on Android 4.0 and Lower** ``` <application ... android:theme="@android:style/Theme.Holo.NoActionBar.Fullscreen" > ... </application> ``` The advantages of using an activity theme are as follows: * It's easier to maintain and less error-prone than setting a flag programmatically. * It results in smoother UI transitions, because the system has the information it needs to render your UI before instantiating your app's main activity. --- **Android version is lower than Jellybean** ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // If the Android version is lower than Jellybean, use this call to hide // the status bar. if (Build.VERSION.SDK_INT < 16) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } setContentView(R.layout.activity_main); } ``` --- **Hide the Status Bar on Android 4.1 and Higher** ``` View decorView = getWindow().getDecorView(); // Hide the status bar. int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN; decorView.setSystemUiVisibility(uiOptions); // Remember that you should never show the action bar if the // status bar is hidden, so hide that too if necessary. ActionBar actionBar = getActionBar(); actionBar.hide(); ``` Note the following: * Once UI flags have been cleared (for example, by navigating away from the activity), your app needs to reset them if you want to hide the bars again. See [Responding to UI Visibility Changes](http://developer.android.com/training/system-ui/visibility.html) for a discussion of how to listen for UI visibility changes so that your app can respond accordingly. * Where you set the UI flags makes a difference. If you hide the system bars in your activity's onCreate() method and the user presses Home, the system bars will reappear. When the user reopens the activity, onCreate() won't get called, so the system bars will remain visible. If you want system UI changes to persist as the user navigates in and out of your activity, set UI flags in onResume() or onWindowFocusChanged(). * The method setSystemUiVisibility() only has an effect if the view you call it from is visible. * Navigating away from the view causes flags set with setSystemUiVisibility() to be cleared.
I had this error with `AlertDialog` and the error was happening in API 19 only when `dialog.show()` was called. figured out that the `android.app.AlertDialog` import is causing the problem so I changed it to `androidx.appcompat.app.AlertDialog` and it fixed it. Note that this will work if you are using androidx. if you are not, you should use the old appcompat version of that import.
48,398,197
So I am trying to parse HTMl from a website but all I get is menu because body has a preloader. Links are NSFW so I added a wildcard to them. My question is how do I parse whole page and not only menu? Creating a timeout doesn't seem to help (or I am doing the timeout wrong). ``` <?php $ctx = stream_context_create(array( 'http' => array( 'timeout' => 50 ) ) ); $stars_list_page = file_get_contents("https://www.por*pics.com/?q=blue+angel", 0, $ctx); $dom_obj = new DOMDocument(); @$dom_obj->loadHTML($stars_list_page); var_dump($dom_obj); ?> ```
2018/01/23
[ "https://Stackoverflow.com/questions/48398197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8389421/" ]
Well, What I am going to say will sound CRAZY, but it is a fact and known issue and really hard to be found. The problem is in the **project path**, the path for the project I have created contained a special character c:/users/Hussein Khalil(XXX)/PROJECT\_NAME when I created the project on a simple path c:/test/... everything is worked fine. Hope this could help.
I faced the same issue and it was not related with special characters in project path. I executed "clean solution" and then "build solution" and it restored the dependency successfully. It solved the issue.
34,976,628
How can I insert something after the second form with `mform` class, for this markup: ``` <table id="sortme"> <tr> <td>1</td> <td><form class="mform"></form></td> </tr> <tr> <td>2</td> <td><form class="mform"></form><!---Insert Me here !---></td> </tr> <tr> <td>3</td> <td><form class="mform"></form></td> </tr> </table> ``` To insert after the first form, I can use: ``` $(function () { $('<div>block</div>').insertAfter("#sortme form.mform:first"); }); ``` so I've tried this code for the second, didn't work: ``` $(function () { $('<div>block</div>').insertAfter("#sortme > form.mform:nth-child(2)"); }); ```
2016/01/24
[ "https://Stackoverflow.com/questions/34976628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3330034/" ]
Try `.insertAfter("#sortme form.mform:eq(1)");`
You, also, may use a `counter`, conditional statement and `append` as follows: ``` <script> $(document).ready(function(){ counter = 0; $(".mform").each(function(){ if (counter === 1){ $(this).append("<div>Block</div>"); } counter++; }); }); </script> ``` A demo is [HERE](http://jsbin.com/todoqufoti/edit?html,output)
23,303,358
I am creating a simple clock application using MFC. My application title appears as follows : "CLOCK - [CLOCK1]". How do I reset it to simply "CLOCK"? FYI, I have enabled the Document-View architecture.
2014/04/25
[ "https://Stackoverflow.com/questions/23303358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3397590/" ]
Put in this override of the MFC title: ``` void CMainFrame::OnUpdateFrameTitle(BOOL bAddToTitle) { SetWindowText(L"CLOCK"); } ```
You can change it in visual editor by clicking on a your window and typing a title. Or you can add this code in function OnInitDialog `this->SetWindowText(L"CLOCK");`
23,303,358
I am creating a simple clock application using MFC. My application title appears as follows : "CLOCK - [CLOCK1]". How do I reset it to simply "CLOCK"? FYI, I have enabled the Document-View architecture.
2014/04/25
[ "https://Stackoverflow.com/questions/23303358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3397590/" ]
There's an answer [here](https://stackoverflow.com/a/14295450/1850797), but I feel that the following solution is more "proper". In addition to overriding `CMainFrame::OnUpdateFrameTitle()`, you also need to override `CMainFrame::PreCreateWindow()` as below: ``` BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { cs.style &= ~FWS_ADDTOTITLE; return CFrameWndEx::PreCreateWindow(cs); // replace CFrameWndEx by CFrameWnd if } // your CMainFrame is based on CFrameWnd ``` A note: it is better to use `AfxSetWindowText(m_hWnd, _T("foo"))` instead of `SetWindowText(_T("foo"))` to avoid excessive flicker, it checks that the text is different before setting the window text.
You can change it in visual editor by clicking on a your window and typing a title. Or you can add this code in function OnInitDialog `this->SetWindowText(L"CLOCK");`
64,930,506
Please tell me, I have 2 classes. There is a `load_shop()` function that enables the display of the webView. If I call a function from the first class `ViewController` then the function is executed and the webView is displayed, and if from another class `CheckUpdate` the function is executed (print is output) but the webView is not displayed. What could be the problem? Thanks for any help. I'm new to this. ``` class ViewController: UIViewController { ... override func viewDidLoad() { super.viewDidLoad() self.load_shop() } ... func load_shop() { view = webView print("finish_update") } } class CheckUpdate: NSObject { if (...) { ViewController().load_shop() } } ``` ViewController.swift ``` import UIKit import WebKit import UserNotifications import Foundation class ViewController: UIViewController, WKUIDelegate, WKScriptMessageHandler, WKNavigationDelegate { var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() let webConfiguration = WKWebViewConfiguration() webView = WKWebView(frame: .zero, configuration: webConfiguration) webView.scrollView.bounces = false; let myURL = URL(string:"https://google.com") let myRequest = URLRequest(url: myURL!) webView.load(myRequest); webView.navigationDelegate = self } var update = 0 func load_shop() { view = webView print("finish_update") } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { CheckUpdate.shared.showUpdate(withConfirmation: false) } func close() { exit(0); } override var prefersHomeIndicatorAutoHidden: Bool { return true } } ``` CheckUpdate.swift ``` import Foundation import UIKit enum VersionError: Error { case invalidBundleInfo, invalidResponse } class LookupResult: Decodable { var results: [AppInfo] } class AppInfo: Decodable { var version: String var trackViewUrl: String } class CheckUpdate: NSObject { let first_class = ViewController() static let shared = CheckUpdate() func showUpdate(withConfirmation: Bool) { DispatchQueue.global().async { self.checkVersion(force : !withConfirmation) } } private func checkVersion(force: Bool) { if let currentVersion = self.getBundle(key: "CFBundleShortVersionString") { _ = getAppInfo { (info, error) in if let appStoreAppVersion = info?.version { if let error = error { print("error getting app store version: ", error) } else if appStoreAppVersion == currentVersion { self.first_class.load_shop() print("Already on the last app version: ",currentVersion) } else { print("Needs update: AppStore Version: \(appStoreAppVersion) > Current version: ",currentVersion) DispatchQueue.main.async { let topController: UIViewController = (UIApplication.shared.windows.first?.rootViewController)! topController.showAppUpdateAlert(Version: (info?.version)!, Force: force, AppURL: (info?.trackViewUrl)!) } } } } } } private func getAppInfo(completion: @escaping (AppInfo?, Error?) -> Void) -> URLSessionDataTask? { // You should pay attention on the country that your app is located, in my case I put Brazil */br/* // Você deve prestar atenção em que país o app está disponível, no meu caso eu coloquei Brasil */br/* guard let identifier = self.getBundle(key: "CFBundleIdentifier"), let url = URL(string: "http://itunes.apple.com/br/lookup?bundleId=\(identifier)") else { DispatchQueue.main.async { completion(nil, VersionError.invalidBundleInfo) } return nil } let task = URLSession.shared.dataTask(with: url) { (data, response, error) in do { if let error = error { throw error } guard let data = data else { throw VersionError.invalidResponse } let result = try JSONDecoder().decode(LookupResult.self, from: data) print(result.results) guard let info = result.results.first else { throw VersionError.invalidResponse } completion(info, nil) } catch { completion(nil, error) } } task.resume() return task } func getBundle(key: String) -> String? { guard let filePath = Bundle.main.path(forResource: "Info", ofType: "plist") else { fatalError("Couldn't find file 'Info.plist'.") } // 2 - Add the file to a dictionary let plist = NSDictionary(contentsOfFile: filePath) // Check if the variable on plist exists guard let value = plist?.object(forKey: key) as? String else { fatalError("Couldn't find key '\(key)' in 'Info.plist'.") } return value } } extension UIViewController { @objc fileprivate func showAppUpdateAlert( Version : String, Force: Bool, AppURL: String) { guard let appName = CheckUpdate.shared.getBundle(key: "CFBundleName") else { return } //Bundle.appName() let alertTitle = "New version" let alertMessage = "A new version of \(appName) are available on AppStore. Update now!" let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert) if !Force { let notNowButton = UIAlertAction(title: "Not now", style: .default) alertController.addAction(notNowButton) } let updateButton = UIAlertAction(title: "Update", style: .default) { (action:UIAlertAction) in guard let url = URL(string: AppURL) else { return } if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } else { UIApplication.shared.openURL(url) } } alertController.addAction(updateButton) self.present(alertController, animated: true, completion: nil) } } ```
2020/11/20
[ "https://Stackoverflow.com/questions/64930506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14675890/" ]
let first\_class = ViewController() // stop doing this. It will not work. Think of it; you have a car (view controller), you want to turn on the radio of your car. What would you have to do? First turn your car on and then its radio right? But what you do in your code is; instead of turning on the radio of your car, you go and get a new car (like new instance of viewcontroller) and turn on the radio of the new car. But actually you need to turn on the radio of your own car not the new car. This how works instances in object oriented programming. You created an instance of a UIViewController (it is your car), then in another class you are creating another instance of UIViewController (that is not your car in the example). Then you try to modify the first one but actually you are modifying the another one. As soon as I am home I will modify your code from my laptop, because it is hard to edit it from the mobile phone. Here is the modified code. NOTE THAT I just correct the parts where you want to call load\_shop function from the CheckUpdate class. I mean I don't know all the logic behind your code so, if it contains more logical errors it's all up to you. ViewController.swift ``` import UIKit import WebKit import UserNotifications import Foundation // Not really necesary cause UIKit import already imports it class ViewController: UIViewController, WKUIDelegate, WKScriptMessageHandler, WKNavigationDelegate { var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() let webConfiguration = WKWebViewConfiguration() webView = WKWebView(frame: .zero, configuration: webConfiguration) webView.scrollView.bounces = false; let myURL = URL(string:"https://google.com") let myRequest = URLRequest(url: myURL!) webView.load(myRequest); webView.navigationDelegate = self } var update = 0 func load_shop() { view = webView print("finish_update") } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { CheckUpdate.shared.showUpdate(withConfirmation: false, caller: self) // Attention here!!! } func close() { exit(0); } override var prefersHomeIndicatorAutoHidden: Bool { return true } } ``` CheckUpdate.swift ``` import UIKit enum VersionError: Error { case invalidBundleInfo, invalidResponse } class LookupResult: Decodable { var results: [AppInfo] } class AppInfo: Decodable { var version: String var trackViewUrl: String } class CheckUpdate: NSObject { let first_class: ViewController? // Attention here!!! static let shared = CheckUpdate() func showUpdate(withConfirmation: Bool, viewController: ViewController) { first_class = viewController // Attention here!!! DispatchQueue.global().async { self.checkVersion(force : !withConfirmation) } } private func checkVersion(force: Bool) { if let currentVersion = self.getBundle(key: "CFBundleShortVersionString") { _ = getAppInfo { (info, error) in if let appStoreAppVersion = info?.version { if let error = error { print("error getting app store version: ", error) } else if appStoreAppVersion == currentVersion { self.first_class?.load_shop() // Atention here!!! print("Already on the last app version: ",currentVersion) } else { print("Needs update: AppStore Version: \(appStoreAppVersion) > Current version: ",currentVersion) DispatchQueue.main.async { let topController: UIViewController = (UIApplication.shared.windows.first?.rootViewController)! topController.showAppUpdateAlert(Version: (info?.version)!, Force: force, AppURL: (info?.trackViewUrl)!) } } } } } } private func getAppInfo(completion: @escaping (AppInfo?, Error?) -> Void) -> URLSessionDataTask? { // You should pay attention on the country that your app is located, in my case I put Brazil */br/* // Você deve prestar atenção em que país o app está disponível, no meu caso eu coloquei Brasil */br/* guard let identifier = self.getBundle(key: "CFBundleIdentifier"), let url = URL(string: "http://itunes.apple.com/br/lookup?bundleId=\(identifier)") else { DispatchQueue.main.async { completion(nil, VersionError.invalidBundleInfo) } return nil } let task = URLSession.shared.dataTask(with: url) { (data, response, error) in do { if let error = error { throw error } guard let data = data else { throw VersionError.invalidResponse } let result = try JSONDecoder().decode(LookupResult.self, from: data) print(result.results) guard let info = result.results.first else { throw VersionError.invalidResponse } completion(info, nil) } catch { completion(nil, error) } } task.resume() return task } func getBundle(key: String) -> String? { guard let filePath = Bundle.main.path(forResource: "Info", ofType: "plist") else { fatalError("Couldn't find file 'Info.plist'.") } // 2 - Add the file to a dictionary let plist = NSDictionary(contentsOfFile: filePath) // Check if the variable on plist exists guard let value = plist?.object(forKey: key) as? String else { fatalError("Couldn't find key '\(key)' in 'Info.plist'.") } return value } } extension UIViewController { @objc fileprivate func showAppUpdateAlert( Version : String, Force: Bool, AppURL: String) { guard let appName = CheckUpdate.shared.getBundle(key: "CFBundleName") else { return } //Bundle.appName() let alertTitle = "New version" let alertMessage = "A new version of \(appName) are available on AppStore. Update now!" let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert) if !Force { let notNowButton = UIAlertAction(title: "Not now", style: .default) alertController.addAction(notNowButton) } let updateButton = UIAlertAction(title: "Update", style: .default) { (action:UIAlertAction) in guard let url = URL(string: AppURL) else { return } if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } else { UIApplication.shared.openURL(url) } } alertController.addAction(updateButton) self.present(alertController, animated: true, completion: nil) } } ```
If your CheckUpdate class resides in a file other than ViewController's file this is not to correct way to do it. You can define a closure or protocol in ViewController then implement it in CheckUpdate class. Something like: ``` class ViewController: UIViewController { ... typeAlias OnUpdate = () -> Void ... override func viewDidLoad() { super.viewDidLoad() self.load_shop() } ... let checkupdate = CheckUpdate(){ view = webView print("finish_update") } } class CheckUpdate: NSObject { ... var onupdate:OnUpdate? ... init(_ onupdate: OnUpdate?){ self.onupdate = onupdate } ... if (...) { //ViewController().load_shop() onupdate?() } } ```
320,282
I am working on a practice problem for my Calculus 3 course. I am given a contour plot and one of the questions is to determine the sign of the second derivative with respect to $x$ at $(3,2)$: $f\_{xx}(3,2)$. I have no clue how to determine this? Could someone please explain the process of how to figure this out merely from a graph? Thanks. Contour Plot: ![Contour](https://i.imgur.com/DKFZPTy.jpg)
2013/03/04
[ "https://math.stackexchange.com/questions/320282", "https://math.stackexchange.com", "https://math.stackexchange.com/users/64908/" ]
Stand yourself at the point $(3,2)$ in the contour plot and start walking parallel to the $x$-axis in the positive direction. First, we see that the $f(x,2)$ is increasing when we increase $x$ which indicates that $f\_x(3,2)>0$. But we can even go a step further. Because not only does it increase but it increase faster and faster (in other words, the surface is getting steeper and steeper). This indicates that $f\_{xx}(3,2)>0$.
The $f\_x$ tells if you will "hike" up or down ($+$ or $-$) from your position, while $f\_{xx}$ determines if you are "hiking" steeper or leveling off ($+$ or $-$). Since $f\_x$ is moving "uphill" and doing so at a faster and faster rate (the lines are scrunching up) then we know $f\_x$ and $f\_{xx}$ are both positive.
66,785,823
I have written a function in T-SQL that is supposed to take a string value and return any row with a similar value in the 'Course Taken' column. Here is the function: ``` enter code here USE [alumni_project1] GO /****** Object: UserDefinedFunction [dbo].[Course_Search] Script Date: 24-Mar-21 7:45:04 PM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION [dbo].[Course_Search] ( @course varchar(255) ) RETURNS TABLE AS RETURN SELECT * FROM Alumni WHERE Course_taken like '%@course%'; ``` However, when I try to use the function, it produces no results. This is how I called the function: ``` DECLARE @c VARCHAR(255) SET @c = 'comp' SELECT * FROM dbo.Course_Search(@c) ``` NOTE: If I use a regular SELECT statement, it returns the correct output, which is two rows where Course\_taken= 'Computer Science'. How does one solve this issue?
2021/03/24
[ "https://Stackoverflow.com/questions/66785823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14305603/" ]
SOLVED: The issue was in the database data. Using the above configurations, I: 1. Stopped all 3 nodes of Cassandra. 2. Deleted the database from nodes 2 and 3 3. Restored the node 1 DB from a backup I made before changing anything 4. Started Cassandra on node 1 (and let it "settle") 5. Started Cassandra on node 2 (and let it replicate all data to it) 6. Started Cassandra on node 3 (and let it replicate all data to it) My only remaining issue is that only 68% (ish) of the data is owned by each node. Since I am looking for fault tolerance, I believe I need to change the replication\_factor to 3 for all data in my schema. ``` [root@program-node01 ~]# /var/lib/cassandra/bin/nodetool status Datacenter: datacenter1 ======================= Status=Up/Down |/ State=Normal/Leaving/Joining/Moving -- Address Load Tokens Owns (effective) Host ID Rack UN 25.80.44.52 45.77 MiB 256 67.2% bcee7571-a2eb-402e-b86f-c7e3327a8b7d rack1 UN 25.80.44.50 51.93 MiB 256 68.0% cc96b4c7-d55e-4b32-80aa-a114bf8af7d1 rack1 UN 25.80.44.51 51.89 MiB 256 64.8% fa92ebd8-32f8-4f4f-bc85-37afd86a20c2 rack1 ```
Try setting your `seeds` list to be the same across all 3 nodes. Right now, it's different for each node...which works only when one of the nodes in the seed list is already running. The first node in the cluster needs to find itself in that seed list. In a small cluster like this, I'd take the `seeds` setting from your first node, and make sure all other nodes' `seeds` properties match it: ``` - seeds: "25.80.44.51,25.80.44.52" ``` That would be a good start.
7,797,530
I'm building a movie player which requires a highly sensitive scrubbing feature. My aim is to allow the user to scrub frame by frame if he selects the highest sensitivity. Currently I'm using the method: `[player seekToTime:CMTimeMakeWithSeconds(duration*(Float64) slider.value, 600)];` but I'm far from the sensitivity I wish to achieve. Can someone advice or point out better method or even frameworks to get this feature done. Thanks in advance.
2011/10/17
[ "https://Stackoverflow.com/questions/7797530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428213/" ]
Solve this problem. Somehow it slipped from my eyes but there is a method that does exactly that: ``` [player seekToTime:CMTimeMakeWithSeconds(duration*(Float64)value , 600) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero]; ``` The `toleranceBefore` and the `toleranceAfter` are set to zero which means it will get exactly to the point you are searching but it will take more time to decode the frame.
Just want to mention a limitation of HLS here. Even though you specify the tolerance 0, it is not possible to seek in the middle of any ts segment. Once you lift your finger from scrubber to seek a position, the player will start playing the video from the nearest TS segment.
4,563
My cherry tomato plant has been showing some yellowing of leaves over the past week or so. Just today I noticed the formation of these cluster of white granules - not sure if it's connected to the yellowing or not. It looks like grains of salt more than anything else; if it's an insect of some sort, I can't get a close enough look to see any legs. Can you help me identify and respond to this? Updates: * They are stationary when poked * They were getting more dense, so I took a toothbrush and knocked them off. They are fairly sticky, so that took some doing. I'll wait to see if they return and examine more closely for legs. * I was able to examine some white granules I'd missed earlier in detail under a magnifying glass, and couldn't find any signs of legs. At this point, the waxy response hypothesis seems like the most likely answer. I'll keep the question open for a few more days to see if the white granules return. *Click on any image for full size* [![white bits on tomato plant, looks like grains of salt](https://i.stack.imgur.com/8J9Txl.jpg)](https://i.stack.imgur.com/8J9Tx.jpg) [![close up](https://i.stack.imgur.com/4IO0Vl.jpg)](https://i.stack.imgur.com/4IO0V.jpg)
2012/06/17
[ "https://gardening.stackexchange.com/questions/4563", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/644/" ]
Aphids ! Use 2tsps of dishwashing liquid to one quart of water, mix and spray to cover all of the insects. Wait 4-7days repeat as needed. Don't spray during heat of the day!
I used an organic insecticidal soap, it has fatty acid salts in it. Destroys the organisms. I think aphids were my gardenias problem
4,563
My cherry tomato plant has been showing some yellowing of leaves over the past week or so. Just today I noticed the formation of these cluster of white granules - not sure if it's connected to the yellowing or not. It looks like grains of salt more than anything else; if it's an insect of some sort, I can't get a close enough look to see any legs. Can you help me identify and respond to this? Updates: * They are stationary when poked * They were getting more dense, so I took a toothbrush and knocked them off. They are fairly sticky, so that took some doing. I'll wait to see if they return and examine more closely for legs. * I was able to examine some white granules I'd missed earlier in detail under a magnifying glass, and couldn't find any signs of legs. At this point, the waxy response hypothesis seems like the most likely answer. I'll keep the question open for a few more days to see if the white granules return. *Click on any image for full size* [![white bits on tomato plant, looks like grains of salt](https://i.stack.imgur.com/8J9Txl.jpg)](https://i.stack.imgur.com/8J9Tx.jpg) [![close up](https://i.stack.imgur.com/4IO0Vl.jpg)](https://i.stack.imgur.com/4IO0V.jpg)
2012/06/17
[ "https://gardening.stackexchange.com/questions/4563", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/644/" ]
Aphids ! Use 2tsps of dishwashing liquid to one quart of water, mix and spray to cover all of the insects. Wait 4-7days repeat as needed. Don't spray during heat of the day!
Those white granules are crystallized sugar dew from an insect infestation such as scale. You can see a light green scale like insect on the top most leaf of the first image. Alternatively that could be a nymph of the [tomato potato psyllid](https://nzacfactsheets.landcareresearch.co.nz/factsheet/InterestingInsects/Tomato-potato-psyllid---Bactericera-cockerelli.html). Check the leaf edges for the adult. [![tomato potato psyllid nymph with wings](https://i.stack.imgur.com/zNOGu.jpg)](https://i.stack.imgur.com/zNOGu.jpg)
4,563
My cherry tomato plant has been showing some yellowing of leaves over the past week or so. Just today I noticed the formation of these cluster of white granules - not sure if it's connected to the yellowing or not. It looks like grains of salt more than anything else; if it's an insect of some sort, I can't get a close enough look to see any legs. Can you help me identify and respond to this? Updates: * They are stationary when poked * They were getting more dense, so I took a toothbrush and knocked them off. They are fairly sticky, so that took some doing. I'll wait to see if they return and examine more closely for legs. * I was able to examine some white granules I'd missed earlier in detail under a magnifying glass, and couldn't find any signs of legs. At this point, the waxy response hypothesis seems like the most likely answer. I'll keep the question open for a few more days to see if the white granules return. *Click on any image for full size* [![white bits on tomato plant, looks like grains of salt](https://i.stack.imgur.com/8J9Txl.jpg)](https://i.stack.imgur.com/8J9Tx.jpg) [![close up](https://i.stack.imgur.com/4IO0Vl.jpg)](https://i.stack.imgur.com/4IO0V.jpg)
2012/06/17
[ "https://gardening.stackexchange.com/questions/4563", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/644/" ]
Aphids ! Use 2tsps of dishwashing liquid to one quart of water, mix and spray to cover all of the insects. Wait 4-7days repeat as needed. Don't spray during heat of the day!
OK, I'm very late coming to the party on this - but for anyone else that stumbles upon this, wondering what might be causing the sandy deposits on their otherwise healthy tomato plant stems and leaves - I may well have the answer for you! In my case (which looks and sounds identical to the original poster) the sandy deposits were due to ants hollowing out one of the nearby bamboo stakes holding up the tomato plant (I notice that there is a bamboo stake in the above photo!) Look for damage / a crack in the bamboo and prize it apart with a knife - if ants and/or the same sort of sand-like substance falls out of the crack then you have found the problem! Just replace the bamboo!
4,563
My cherry tomato plant has been showing some yellowing of leaves over the past week or so. Just today I noticed the formation of these cluster of white granules - not sure if it's connected to the yellowing or not. It looks like grains of salt more than anything else; if it's an insect of some sort, I can't get a close enough look to see any legs. Can you help me identify and respond to this? Updates: * They are stationary when poked * They were getting more dense, so I took a toothbrush and knocked them off. They are fairly sticky, so that took some doing. I'll wait to see if they return and examine more closely for legs. * I was able to examine some white granules I'd missed earlier in detail under a magnifying glass, and couldn't find any signs of legs. At this point, the waxy response hypothesis seems like the most likely answer. I'll keep the question open for a few more days to see if the white granules return. *Click on any image for full size* [![white bits on tomato plant, looks like grains of salt](https://i.stack.imgur.com/8J9Txl.jpg)](https://i.stack.imgur.com/8J9Tx.jpg) [![close up](https://i.stack.imgur.com/4IO0Vl.jpg)](https://i.stack.imgur.com/4IO0V.jpg)
2012/06/17
[ "https://gardening.stackexchange.com/questions/4563", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/644/" ]
I used an organic insecticidal soap, it has fatty acid salts in it. Destroys the organisms. I think aphids were my gardenias problem
Those white granules are crystallized sugar dew from an insect infestation such as scale. You can see a light green scale like insect on the top most leaf of the first image. Alternatively that could be a nymph of the [tomato potato psyllid](https://nzacfactsheets.landcareresearch.co.nz/factsheet/InterestingInsects/Tomato-potato-psyllid---Bactericera-cockerelli.html). Check the leaf edges for the adult. [![tomato potato psyllid nymph with wings](https://i.stack.imgur.com/zNOGu.jpg)](https://i.stack.imgur.com/zNOGu.jpg)
4,563
My cherry tomato plant has been showing some yellowing of leaves over the past week or so. Just today I noticed the formation of these cluster of white granules - not sure if it's connected to the yellowing or not. It looks like grains of salt more than anything else; if it's an insect of some sort, I can't get a close enough look to see any legs. Can you help me identify and respond to this? Updates: * They are stationary when poked * They were getting more dense, so I took a toothbrush and knocked them off. They are fairly sticky, so that took some doing. I'll wait to see if they return and examine more closely for legs. * I was able to examine some white granules I'd missed earlier in detail under a magnifying glass, and couldn't find any signs of legs. At this point, the waxy response hypothesis seems like the most likely answer. I'll keep the question open for a few more days to see if the white granules return. *Click on any image for full size* [![white bits on tomato plant, looks like grains of salt](https://i.stack.imgur.com/8J9Txl.jpg)](https://i.stack.imgur.com/8J9Tx.jpg) [![close up](https://i.stack.imgur.com/4IO0Vl.jpg)](https://i.stack.imgur.com/4IO0V.jpg)
2012/06/17
[ "https://gardening.stackexchange.com/questions/4563", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/644/" ]
I used an organic insecticidal soap, it has fatty acid salts in it. Destroys the organisms. I think aphids were my gardenias problem
OK, I'm very late coming to the party on this - but for anyone else that stumbles upon this, wondering what might be causing the sandy deposits on their otherwise healthy tomato plant stems and leaves - I may well have the answer for you! In my case (which looks and sounds identical to the original poster) the sandy deposits were due to ants hollowing out one of the nearby bamboo stakes holding up the tomato plant (I notice that there is a bamboo stake in the above photo!) Look for damage / a crack in the bamboo and prize it apart with a knife - if ants and/or the same sort of sand-like substance falls out of the crack then you have found the problem! Just replace the bamboo!
59,887,244
I am trying to use `array.filter()` to compare two arrays and separate out values that the two arrays have in common, based on a certain property (id), vs. values they don't have in common. The common ids I want to push to a new array (recordsToUpdate). And I want to push the remaining elements from `arr2` to a new array (recordsToInsert). What I've tried is not working. How can I rework this to get the results I wanted? - (which in the example here should be one array of 1 common element `{id: 3}`, and another array of the remaining elements from `arr2`): ``` const arr1 = [{id: 1}, {id: 2}, {id: 3}]; const arr2 = [{id: 3}, {id: 4}, {id: 5}]; let recordsToUpdate = []; let recordsToInsert = []; recordsToUpdate = arr1.filter(e => (arr1.id === arr2.id)); recordsToInsert = ? console.log('recordsToUpdate: ', recordsToUpdate); console.log('recordsToInsert: ', recordsToInsert); ``` The desired result should be: ``` recordsToUpdate = [{id: 3}]; recordsToInsert = [{id: 4}, {id: 5}]; ```
2020/01/23
[ "https://Stackoverflow.com/questions/59887244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7934883/" ]
Try this, which uses [Array.prototype.find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) to test for whether an object exists in `arr2` with a given `id`: ```js const arr1 = [{id: 1}, {id: 2}, {id: 3}]; const arr2 = [{id: 3}, {id: 4}, {id: 5}]; const recordsToUpdate = arr1.filter(e => arr2.find(obj => obj.id === e.id) !== undefined); const recordsToInsert = arr1.filter(e => arr2.find(obj => obj.id === e.id) === undefined); console.log('recordsToUpdate: ', recordsToUpdate); console.log('recordsToInsert: ', recordsToInsert); ```
Update to Robin post using `some` instead of `find`. It is just other way around. ```js const arr1 = [{id: 1}, {id: 2}, {id: 3}]; const arr2 = [{id: 3}, {id: 4}, {id: 5}]; const recordsToUpdate = arr1.filter(e => arr2.some(obj => obj.id === e.id)); const recordsToInsert = arr2.filter(e => !arr1.some(obj => obj.id === e.id)); console.log('recordsToUpdate: ', recordsToUpdate); console.log('recordsToInsert: ', recordsToInsert); ```
59,887,244
I am trying to use `array.filter()` to compare two arrays and separate out values that the two arrays have in common, based on a certain property (id), vs. values they don't have in common. The common ids I want to push to a new array (recordsToUpdate). And I want to push the remaining elements from `arr2` to a new array (recordsToInsert). What I've tried is not working. How can I rework this to get the results I wanted? - (which in the example here should be one array of 1 common element `{id: 3}`, and another array of the remaining elements from `arr2`): ``` const arr1 = [{id: 1}, {id: 2}, {id: 3}]; const arr2 = [{id: 3}, {id: 4}, {id: 5}]; let recordsToUpdate = []; let recordsToInsert = []; recordsToUpdate = arr1.filter(e => (arr1.id === arr2.id)); recordsToInsert = ? console.log('recordsToUpdate: ', recordsToUpdate); console.log('recordsToInsert: ', recordsToInsert); ``` The desired result should be: ``` recordsToUpdate = [{id: 3}]; recordsToInsert = [{id: 4}, {id: 5}]; ```
2020/01/23
[ "https://Stackoverflow.com/questions/59887244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7934883/" ]
Try this, which uses [Array.prototype.find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) to test for whether an object exists in `arr2` with a given `id`: ```js const arr1 = [{id: 1}, {id: 2}, {id: 3}]; const arr2 = [{id: 3}, {id: 4}, {id: 5}]; const recordsToUpdate = arr1.filter(e => arr2.find(obj => obj.id === e.id) !== undefined); const recordsToInsert = arr1.filter(e => arr2.find(obj => obj.id === e.id) === undefined); console.log('recordsToUpdate: ', recordsToUpdate); console.log('recordsToInsert: ', recordsToInsert); ```
I think this is what you are after... I added values to show the replacement. If you are doing any kind of state management, be careful as I am directly mutating the current array. ```js const arr1 = [ { id: 1, v: "a" }, { id: 2, v: "b" }, { id: 3, v: "old" } ]; const arr2 = [ { id: 3, v: "new" }, { id: 4, v: "e" }, { id: 5, v: "f" } ]; function updateRecords(currentArray, updatesArray) { const currentIds = currentArray.map(item => item.id); updatesArray.forEach(updateItem => currentIds.includes(updateItem.id) ? (currentArray[ currentIds.findIndex(id => id === updateItem.id) ] = updateItem) : currentArray.push(updateItem) ); return currentArray; } console.log(updateRecords(arr1, arr2)) ``` This now gives the option below: ``` [ { "id": 1, "v": "a" }, { "id": 2, "v": "b" }, { "id": 3, "v": "new" }, { "id": 4, "v": "e" }, { "id": 5, "v": "f" } ] ``` Putting it in a function is also something you likely want to do as you will likely use this multiple places in your code.
59,887,244
I am trying to use `array.filter()` to compare two arrays and separate out values that the two arrays have in common, based on a certain property (id), vs. values they don't have in common. The common ids I want to push to a new array (recordsToUpdate). And I want to push the remaining elements from `arr2` to a new array (recordsToInsert). What I've tried is not working. How can I rework this to get the results I wanted? - (which in the example here should be one array of 1 common element `{id: 3}`, and another array of the remaining elements from `arr2`): ``` const arr1 = [{id: 1}, {id: 2}, {id: 3}]; const arr2 = [{id: 3}, {id: 4}, {id: 5}]; let recordsToUpdate = []; let recordsToInsert = []; recordsToUpdate = arr1.filter(e => (arr1.id === arr2.id)); recordsToInsert = ? console.log('recordsToUpdate: ', recordsToUpdate); console.log('recordsToInsert: ', recordsToInsert); ``` The desired result should be: ``` recordsToUpdate = [{id: 3}]; recordsToInsert = [{id: 4}, {id: 5}]; ```
2020/01/23
[ "https://Stackoverflow.com/questions/59887244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7934883/" ]
Update to Robin post using `some` instead of `find`. It is just other way around. ```js const arr1 = [{id: 1}, {id: 2}, {id: 3}]; const arr2 = [{id: 3}, {id: 4}, {id: 5}]; const recordsToUpdate = arr1.filter(e => arr2.some(obj => obj.id === e.id)); const recordsToInsert = arr2.filter(e => !arr1.some(obj => obj.id === e.id)); console.log('recordsToUpdate: ', recordsToUpdate); console.log('recordsToInsert: ', recordsToInsert); ```
I think this is what you are after... I added values to show the replacement. If you are doing any kind of state management, be careful as I am directly mutating the current array. ```js const arr1 = [ { id: 1, v: "a" }, { id: 2, v: "b" }, { id: 3, v: "old" } ]; const arr2 = [ { id: 3, v: "new" }, { id: 4, v: "e" }, { id: 5, v: "f" } ]; function updateRecords(currentArray, updatesArray) { const currentIds = currentArray.map(item => item.id); updatesArray.forEach(updateItem => currentIds.includes(updateItem.id) ? (currentArray[ currentIds.findIndex(id => id === updateItem.id) ] = updateItem) : currentArray.push(updateItem) ); return currentArray; } console.log(updateRecords(arr1, arr2)) ``` This now gives the option below: ``` [ { "id": 1, "v": "a" }, { "id": 2, "v": "b" }, { "id": 3, "v": "new" }, { "id": 4, "v": "e" }, { "id": 5, "v": "f" } ] ``` Putting it in a function is also something you likely want to do as you will likely use this multiple places in your code.
43,520,034
I am attempting to create a C# application that connects to a PostgreSQL database using SSL with client certificate and key files similar in functionality to the PGAdmin UI, but the documentation for this in NPGSQL is lacking and I cannot find any examples. The [documentation](http://www.npgsql.org/doc/security.html#encryption-ssltls) states that it "works just like on .NET's SSLStream", but I am not seeing any correlation between the two. Has anyone created a connection using this method that can possibly provide some help?
2017/04/20
[ "https://Stackoverflow.com/questions/43520034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7895713/" ]
I am facing the same situation. Documentation certainly needs to describe usage explicitly on how to supply cert, key and CA files if needed to the connection string or connection builder, and how the ProvideClientCertificatesCallback can actually supply back cert, key and CA files. Nov 2018: I got below sample code to work for self-signed certs: ``` var connection = new NpgsqlConnection(connectionStringBuilder.ConnectionString); connection.ProvideClientCertificatesCallback += clientCerts => this.GetMyClientCertificates(clientCerts); private void GetMyClientCertificates(X509CertificateCollection clientCerts) { clientCerts.Add(<supply an instance of X509Certificate2 here>); } ```
You need to have `SSL=true` in your connection stream, and then provide a `ProvideClientCertificatesCallback` on your NpgsqlConnection before opening it (like SSLStream).
51,534,603
Suppose to have 3 date in input, data1 and data2 are the interval and data3 is a generical input dates. data1 and data2 can be null, data3 is not null. So I can have 3 situtation : 1. data3 > data1 (data2 is null) 2. data3 < data2 (data1 is null) 3. data1 < data3 < data2 I don't want create a different if with different queries. I want create a query that handles these cases. Suppose to have a table empolyes(id primary key, registration\_date), suppose I have two Dates in input, how I must do to resolve my problem?
2018/07/26
[ "https://Stackoverflow.com/questions/51534603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10100222/" ]
You can write this explicitly: ``` where (data3 > date1 or date1 is null) and (date3 < date2 or date2 is null) ``` You can also use some form of `coalesce()`, such as: ``` where date3 > coalesce(date1, date3 - interval '1 day') and date3 < coalesce(date2, date3 + interval '1 day') ``` Personally, I find the first version more clear.
I would suggest using following line of code in where clause: (...) WHERE data3 BETWEEN NVL(data1, data3) AND NVL(data2, data3) EDIT: I believe that, when working with dates, handling cases when date3 is equal to date1 (or date2, respectively) is mandatory rather then optional and BETWEEN AND also handle those cases.
26,018,331
I would like to use the wkhtmltopdf for HTML to PDF conversion. When I have tried to convert it via linux terminal, it works fine. But when I have tried with the php script it does not work. I am trying execute the binary directly. here is the code I am trying with PHP. ``` exec('/home/binary_loc/wkhtmltopdf http://www.google.com /home/user/output.pdf'); ``` My binary is at the same folder where "index.php" exist. I have tried to fetch the version of wkhtmltopdf binary with PHP, then it return the version. But i don't able to understand why not it work to execute with php for pdf. Here is code for version check using php. ``` error_reporting(E_ALL); ini_set('display_errors', '1'); $cmd = "./wkhtmltopdf --version"; $t = shell_exec($cmd); echo $t; exit() ``` Do anyone has solution regarding it?? I want this because this will work in the shared hosting too. No need to install the wkhtmltopdf in the server.
2014/09/24
[ "https://Stackoverflow.com/questions/26018331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3305818/" ]
You can do this: ``` display(Optional.<String> absent()); ```
I think you try to pass unvalid parameter to method. You have to wrap it in method. It will solve the issue. ``` private void display(String message) { Optional<String> optionalMessage=Optional.fromNullable(message); ... } ```
70,359,604
[barchart](https://i.stack.imgur.com/kvMPR.png) html file ``` <canvas width="3" height="1" *ngIf="loaded" baseChart [data]="barChartData" [labels]="barChartLabels" [options]="barChartOptions" [legend]="barChartLegend" [chartType]="barChartType" [colors]="chartColors" > </canvas> ``` ts file ``` chartColors: Array<any> = [ { // all colors in order backgroundColor: ['#2EA082', '#2B2272', '#A687FF'], }, ]; barChartOptions: ChartOptions = { responsive: true, legend: { display: false, }, scales: { yAxes: [ { ticks: { callback: function (value: number, index, values) { return '$ ' + Intl.NumberFormat().format(value / 100000) + 'K'; }, }, }, ], xAxes: [ { gridLines: { lineWidth: 0, }, }, ], }, }; barChartLabels: string[] = []; barChartType: ChartType = 'bar'; barChartLegend: boolean = true; barChartData: any[] = []; loaded = false; ``` I'm using chartjs 2.9.4 and ng2 2.4.2 version. how to reduce bar thickness and also i tried using barThickness under xAxes but it is not working. I have attached the image for reference
2021/12/15
[ "https://Stackoverflow.com/questions/70359604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13433597/" ]
You can use the dataset option `barPercentage` as described [here](https://www.chartjs.org/docs/2.9.4/charts/bar.html#dataset-configuration). In you code, this could look as follows: ``` barChartData: ChartDataSets[] = [ { label: 'My Dataset', data: [65, 56, 40], barPercentage: 0.5 } ]; ```
Just insert static data for testing purpose and set barThickness property instead of barPercentage. It worked for me.
46,126,695
I have an algolia application with some objects that look like this: ``` { "company_id": "36ec09ec-6b07-45e3-ae2d-a77bfe381baa", "first_name": "maryam", "objectID": "ffd92558-6bd3-42df-96c2-9c9124e66f6a" } ``` I'm trying to run a query that filter search results by `company_id`. I've read the Algolia docs and this is what I've attempted. First I added the `company_id` to the attributes for faceting in the dashboard. Now in my front end JavaScript application I'm running this query: ``` this.index.search({ query: 'mar', filters: `company_id:'36ec09ec-6b07-45e3-ae2d-a77bfe381baa'` }).then(resp => { console.log(resp); }); ``` When I run this however it returns 0 hits. I've also tried: ``` this.index.search({ query: 'mar', facetFilters: [`company_id:36ec09ec-6b07-45e3-ae2d-a77bfe381baa`] }).then(resp => { console.log(resp); }); ```
2017/09/09
[ "https://Stackoverflow.com/questions/46126695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3666882/" ]
Try like this way, more about filtering <https://www.algolia.com/doc/guides/searching/filtering/> ``` this.index.search({ query: 'mar', filters: 'company_id:36ec09ec-6b07-45e3-ae2d-a77bfe381baa' }).then(resp => { console.log(resp); }); ```
I encountered this issue as well. Looks like we need to add a facet to the attribute we want to filter. So in this case, you might want to create a facet related to `company_id` and make sure it's searchable
46,126,695
I have an algolia application with some objects that look like this: ``` { "company_id": "36ec09ec-6b07-45e3-ae2d-a77bfe381baa", "first_name": "maryam", "objectID": "ffd92558-6bd3-42df-96c2-9c9124e66f6a" } ``` I'm trying to run a query that filter search results by `company_id`. I've read the Algolia docs and this is what I've attempted. First I added the `company_id` to the attributes for faceting in the dashboard. Now in my front end JavaScript application I'm running this query: ``` this.index.search({ query: 'mar', filters: `company_id:'36ec09ec-6b07-45e3-ae2d-a77bfe381baa'` }).then(resp => { console.log(resp); }); ``` When I run this however it returns 0 hits. I've also tried: ``` this.index.search({ query: 'mar', facetFilters: [`company_id:36ec09ec-6b07-45e3-ae2d-a77bfe381baa`] }).then(resp => { console.log(resp); }); ```
2017/09/09
[ "https://Stackoverflow.com/questions/46126695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3666882/" ]
Try like this way, more about filtering <https://www.algolia.com/doc/guides/searching/filtering/> ``` this.index.search({ query: 'mar', filters: 'company_id:36ec09ec-6b07-45e3-ae2d-a77bfe381baa' }).then(resp => { console.log(resp); }); ```
This usually happens if you haven't created an attribute for facet. To create an attribute, follow these steps: 1. Go to your Algoloa dashboard. 2. Scroll down to "Data source" card. 3. Click on the index that you need. 4. In the left pane, choose Configure > Index. 5. In the right pane, click on the configure tab. 6. In the new pane, click on facet on the left menu. 7. Click on Add attribute in the right pane to create an attribute for facet.
46,126,695
I have an algolia application with some objects that look like this: ``` { "company_id": "36ec09ec-6b07-45e3-ae2d-a77bfe381baa", "first_name": "maryam", "objectID": "ffd92558-6bd3-42df-96c2-9c9124e66f6a" } ``` I'm trying to run a query that filter search results by `company_id`. I've read the Algolia docs and this is what I've attempted. First I added the `company_id` to the attributes for faceting in the dashboard. Now in my front end JavaScript application I'm running this query: ``` this.index.search({ query: 'mar', filters: `company_id:'36ec09ec-6b07-45e3-ae2d-a77bfe381baa'` }).then(resp => { console.log(resp); }); ``` When I run this however it returns 0 hits. I've also tried: ``` this.index.search({ query: 'mar', facetFilters: [`company_id:36ec09ec-6b07-45e3-ae2d-a77bfe381baa`] }).then(resp => { console.log(resp); }); ```
2017/09/09
[ "https://Stackoverflow.com/questions/46126695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3666882/" ]
This usually happens if you haven't created an attribute for facet. To create an attribute, follow these steps: 1. Go to your Algoloa dashboard. 2. Scroll down to "Data source" card. 3. Click on the index that you need. 4. In the left pane, choose Configure > Index. 5. In the right pane, click on the configure tab. 6. In the new pane, click on facet on the left menu. 7. Click on Add attribute in the right pane to create an attribute for facet.
I encountered this issue as well. Looks like we need to add a facet to the attribute we want to filter. So in this case, you might want to create a facet related to `company_id` and make sure it's searchable
69,260,783
We are wrapping a component library with React components, but in some cases the library manipulates the DOM tree in such a way that React will crash when trying to remove the React components. Here's a sample that reproduces the issue: ``` function Sample () { let [shouldRender, setShouldRender] = React.useState(true); return ( <React.Fragment> <button onClick={() => setShouldRender(!shouldRender)}>show/hide</button> { shouldRender && <Component /> } </React.Fragment> ); } function Component () { let ref = React.useRef(); React.useEffect(() => { let divElement = ref.current; someExternalLibrary.setup(divElement); return () => someExternalLibrary.cleanup(divElement); }); return <div ref={ref} id="div1">Hello world</div>; } ReactDOM.render( <Sample />, document.getElementById('container') ); let someExternalLibrary = { setup: function(divElement) { let beacon = document.createElement('div'); beacon.id = `beacon${divElement.id}`; divElement.parentElement.replaceChild(beacon, divElement); document.body.append(divElement); }, cleanup: function(divElement) { let beacon = document.getElementById(`beacon${divElement.id}`); beacon.parentElement.replaceChild(divElement, beacon); } } ``` You can find [this sample on JSFiddle](https://jsbin.com/romigaz/edit?js,console,output). The above sample will render the `Component` which integrates with `someExternalLibrary`. The external library moves the elements from inside the React component somewhere else. Even if the external library puts back the element at its original location using a beacon, React will still complain when trying to remove the Component when you click on the show/hide button. This will be the error ``` "Error: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node. at removeChildFromContainer (https://unpkg.com/react-dom@17/umd/react-dom.development.js:10337:17) at unmountHostComponents (https://unpkg.com/react-dom@17/umd/react-dom.development.js:21324:11) at commitDeletion (https://unpkg.com/react-dom@17/umd/react-dom.development.js:21377:7) at commitMutationEffects (https://unpkg.com/react-dom@17/umd/react-dom.development.js:23437:13) at HTMLUnknownElement.callCallback (https://unpkg.com/react-dom@17/umd/react-dom.development.js:3942:16) at Object.invokeGuardedCallbackDev (https://unpkg.com/react-dom@17/umd/react-dom.development.js:3991:18) at invokeGuardedCallback (https://unpkg.com/react-dom@17/umd/react-dom.development.js:4053:33) at commitRootImpl (https://unpkg.com/react-dom@17/umd/react-dom.development.js:23151:11) at unstable_runWithPriority (https://unpkg.com/react@17/umd/react.development.js:2764:14) at runWithPriority$1 (https://unpkg.com/react-dom@17/umd/react-dom.development.js:11306:12)" ``` An easy fix would be to wrap the existing HTML inside another DIV element so that becomes the root of the component, but unfortunately, that's not always possible in our project, so I need another solution. What would be the best approach to solving this? Is there a way to use a ReactFragment and re-associate the HTMLElement with the fragment during cleanup?
2021/09/20
[ "https://Stackoverflow.com/questions/69260783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2919731/" ]
The cleanup function of useEffect, hence `someExternalLibrary.cleanup()`, is called **after** React has updated the DOM (removed the div from the DOM). It fails, because React is trying to remove a DOM node that `someExternalLibrary.setup()` removed (and `someExternalLibrary.cleanup()` will put back later). In class components you can call `someExternalLibrary.cleanup()` **before** React updates the DOM. This would fix your code: ``` class Component extends React.Component { constructor(props) { super(props); this.divElementRef = React.createRef(); } componentDidMount() { someExternalLibrary.setup(this.divElementRef.current); } componentWillUnmount() { someExternalLibrary.cleanup(this.divElementRef.current); } render() { return <div ref={this.divElementRef} id="div1">Hello world</div>; } } ``` The "extra div solution" fails for the same reason: Calling `someExternalLibrary.cleanup()` during the cleanup of useEffect() will mean the DOM has changed, but someExternalLibrary expects no change in the DOM. By using the class component with componentWillUnmount, `someExternalLibrary.setup()` and `someExternalLibrary.cleanup()` will work with the same DOM.
React doesn't expect you to remove nodes that React has created. Treat nodes created by React as read-only. Instead you should: > > wrap the existing HTML inside another DIV element > > > However you don't explain why that isn't feasible: > > but unfortunately, that's not always possible in our project, so I need another solution. > > > Without that info, which is your real issue, a solution cannot be given.
14,403,677
It was hard to find the correct question topic. Well, let me elaborate more. I'm making a barcode generator simple webapp. It is for our warehouse team. I made a class named `SqlComm` where I handle all `SQL` connection related thing. Then, I have a query (the query is just about counting a column where some Date in between). I use the query for setting the `array` size. Later, it loops through a `for` cycle and adds each new label to a placeholder. Sadly, the placeholder is not showing my new labels just created. c# (codebehing) ``` int index = 0; int iLength = 0; dt = SqlComm.SqlDataTable("SELECT [Lenum] FROM [SUIDonMachineTable] WHERE MachineTimestamp BETWEEN CONVERT(datetime,'"+strDayFrom+"', 121) AND CONVERT(datetime,'"+strDayTo+"', 121) AND Station ='NG08NX1BT'"); object obj = new object(); obj = SqlComm.SqlReturn("SELECT COUNT (Lenum) FROM [SUIDonMachineTable] WHERE MachineTimestamp BETWEEN CONVERT(datetime,'"+strDayFrom+"', 121) AND CONVERT(datetime,'"+strDayTo+"', 121) AND Station ='NG08NX1BT'"); iLength = Convert.ToInt32(obj); Label[] labels = new Label[iLength]; for (index = 0; index == iLength; index++) { labels[index] = new Label(); labels[index].Text = (string)dt.Rows[index]["Lenum"]; PH.Controls.Add(labels[index]); } ``` asp.net (placeholder part) ``` <asp:PlaceHolder ID="PH" runat="server"></asp:PlaceHolder> ```
2013/01/18
[ "https://Stackoverflow.com/questions/14403677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1620283/" ]
If `self.variable` is a string holding the name of an attribute, use `getattr`: ``` getattr(self.array, self.variable) ```
It's not clear what you mean here (at least to me). But basically, the `self` is just the conventional name for the instance within a class method. It has local scope, so you don't reference it that way from outside it. It *is* the instance, from outside you should be able to do simply `self.array.variable`. However, it seems you want index style access? You can do that by defining the `__getitem__` special method. Then you can do `myobj["x"]`.
4,971,909
Is there any way of getting the "Windows Live Anonymous ID" from a PC based on the users e-mail-adress, logged in Windows-account, registry, Zune, currently usb-connected phone or else?
2011/02/11
[ "https://Stackoverflow.com/questions/4971909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/382838/" ]
Marcus S. Zarra's "Core Data" book gets good reviews.
I learned by actually doing. [This is where I started](http://cocoadevcentral.com/articles/000085.php). It's a pretty good tutorial. Edit: I forgot two other tutorials I followed: [Part 1](http://www.mactech.com/articles/mactech/Vol.21/21.07/CoreData/) [Part 2](http://www.mactech.com/articles/mactech/Vol.21/21.09/CoreDataII/)
4,971,909
Is there any way of getting the "Windows Live Anonymous ID" from a PC based on the users e-mail-adress, logged in Windows-account, registry, Zune, currently usb-connected phone or else?
2011/02/11
[ "https://Stackoverflow.com/questions/4971909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/382838/" ]
There are several guides besides the [Core Data Programming Guide](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/) that are relevant: * [Model Object Implementation Guide](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ModelObjects/) * [Key-Value Coding Programming Guide](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueCoding/) * [Creating a Managed Object Model](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CreatingMOMWithXcode/) * [Predicate Programming Guide](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/) I got the last two from the “Related Documents” section of the CDPG. Not quite so Core Data/data-modeling related, but still useful for applying Core Data, are the documents on using Bindings: * [Key-Value Observing Programming Guide](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueObserving/) * [Cocoa Bindings Programming Topics](http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CocoaBindings/) * [Cocoa Bindings Reference](http://developer.apple.com/mac/library/documentation/Cocoa/Reference/CocoaBindingsRef/) Bindings makes it easier to use built-in Cocoa views to display the data you keep in your model. You'll also find the framework references worth bookmarking: * [Foundation Framework Reference](http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/ObjC_classic/) * [Application Kit Framework Reference](http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ApplicationKit/ObjC_classic/) * [Core Data Framework reference](http://developer.apple.com/mac/library/documentation/Cocoa/Reference/CoreData_ObjC/)
I learned by actually doing. [This is where I started](http://cocoadevcentral.com/articles/000085.php). It's a pretty good tutorial. Edit: I forgot two other tutorials I followed: [Part 1](http://www.mactech.com/articles/mactech/Vol.21/21.07/CoreData/) [Part 2](http://www.mactech.com/articles/mactech/Vol.21/21.09/CoreDataII/)