qid
int64
1
74.7M
question
stringlengths
17
39.2k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
41.1k
response_k
stringlengths
2
47.9k
41,048,058
Update ------ As [maddy](https://stackoverflow.com/users/1226963/rmaddy) mentioned bellow in the comments it's obvious you need a reference to an object to be able to call a method on it. That is probably in fact my question: how do you keep track of all objects that implement a protocol? Looking back at Objective-C I thought about using something similar to `+load` or `+initialize` methods and add the object as an observer for a specific `NSNotification`. But that wouldn't work since those methods are class methods and not instance methods. So, trying to be even a little bit more specific: is there a method that get's called on all objects after they are created? A method that would allow me to add that object to a collection that I manage or as an observer for a specific `NSNotification`? P.S: I haven't tried adding to much details to the problem 'cause I didn't want to "polute" you with my bad, non-sense ideas. Original -------- So... Imagine this piece of code: ``` protocol MyProtocol: class { func myMethod() } public class MyClass: MyProtocol { func myMethod() { print("myMethod called on MyClass") } } extension UIView: MyProtocol { func myMethod() { print("myMethod called on UIView") } } let myObject = MyClass() let myView = UIView() ``` Now... I'm trying to figure out a way to call `myMethod` on both these objects from a 3rd one which is not aware of them - here's a simplified example of the 3rd one: ``` class MyManager { func callMyMethodOnAllObjecs() { // Do something here so that ALL objects present in memory that conform to MyProtocol get their myMethod called } } ``` Anyone?
2016/12/08
[ "https://Stackoverflow.com/questions/41048058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/831838/" ]
A heads up that what you need requires features belonging to dynamically typed languages, this means using the Objective-C runtime. This doesn't pose many technical challenges, but restricts the area of Swift entities you can use - basically only `NSObject` derived classes. Briefly, here's what you need: 1. support in `MyManager` for registering newly created objects 2. a piece of code that needs to be executed by all `MyProtocol` instances that register themselves to `MyManager` 3. most important, code that doesn't generate memory leaks, as registering an object within `MyManager` poses the risk of having the manager indefinitely retain that object. Below you can find a code that solves the problem: ``` // Since we need ObjectiveC specific runtime features, we need to // restrict the protocol to the NSObject protocol protocol MyProtocol: NSObjectProtocol { func myMethod() } public class MyClass: NSObject, MyProtocol { func myMethod() { print("myMethod called on MyClass") } } extension UIView: MyProtocol { func myMethod() { print("myMethod called on UIView") } } extension NSObject { // this is an alternative to the original init method, that besides the // original edit it registers the object within MyManager @objc func swizzledInit() -> NSObject { // this is not recursive, as init() in exchanged with swizzledInit() let `self` = swizzledInit() if let `self` = self as? MyProtocol { // the object is MyProtocol MyManager.shared.register(self) } return self } } class MyManager { static let shared = MyManager() private var objecters = [() -> MyProtocol?]() private init() { // let's swizzle init() with our custom init if let m1 = class_getInstanceMethod(NSObject.self, #selector(NSObject.init)), let m2 = class_getInstanceMethod(NSObject.self, #selector(NSObject.swizzledInit)) { method_exchangeImplementations(m1, m2) } } public func register(_ object: MyProtocol) { // registering a block in order to be able to keep a weak reference to // the registered object objecters.append({ [weak object] in return object }) } func callMyMethodOnAllObjecs() { var newList = [() -> MyProtocol?]() // go through the list of registered blocks, execute the method, // and retain only the ones for wich the object is still alive for object in objecters { if let o = object() { newList.append(object) o.myMethod() } } objecters = newList } } // This is to make sure the manager is instantiated first, // and thus it swizzles the NSObject initializer _ = MyManager.shared let myObject = MyClass() let myView = UIView() // an instance of MyClass and one of UIView will print stuff MyManager.shared.callMyMethodOnAllObjecs() ``` In summary, the above code: 1. swizzles the `init` of `NSObject` so that besides the original `init` it also registers the object to your manager. 2. keeps a list of closure that return objects instead of the object themselves, in order to be able to weakly reference those objects, thus to avoid keeping the objects alive more than they should be 3. cleans up the closures whose objects got deallocated when `callMyMethodOnAllObjecs` is invoked.
I assume you mean if you don't know if the method exists on the object. If so, just run the test on the method before calling it: ``` myObject.respondsToSelector(Selector("myMethod")) // true if it can respond to it ``` ----- updated answer to updated question: ``` if(myObject && myObject.respondsToSelector(Selector("myMethod"))) [myMutableDic setObject:myObject forKey:@"myObject"]; if(myView && myView.respondsToSelector(Selector("myMethod"))) [myMutableDic setObject:myView forKey:@"myView"]; // and call all myMethods on this set ------------------------------ for (id key in [myMutableDic allKeys]) { id obj = [myMutableDic objectForKey:key]; [obj myMethod]; // since already checked before putting it into dictionary } // or use the block enumeration - does the same thing: [myMutableDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){ [obj myMethod]; }]; // ps didn't test it may need to fix grammar ```
41,048,058
Update ------ As [maddy](https://stackoverflow.com/users/1226963/rmaddy) mentioned bellow in the comments it's obvious you need a reference to an object to be able to call a method on it. That is probably in fact my question: how do you keep track of all objects that implement a protocol? Looking back at Objective-C I thought about using something similar to `+load` or `+initialize` methods and add the object as an observer for a specific `NSNotification`. But that wouldn't work since those methods are class methods and not instance methods. So, trying to be even a little bit more specific: is there a method that get's called on all objects after they are created? A method that would allow me to add that object to a collection that I manage or as an observer for a specific `NSNotification`? P.S: I haven't tried adding to much details to the problem 'cause I didn't want to "polute" you with my bad, non-sense ideas. Original -------- So... Imagine this piece of code: ``` protocol MyProtocol: class { func myMethod() } public class MyClass: MyProtocol { func myMethod() { print("myMethod called on MyClass") } } extension UIView: MyProtocol { func myMethod() { print("myMethod called on UIView") } } let myObject = MyClass() let myView = UIView() ``` Now... I'm trying to figure out a way to call `myMethod` on both these objects from a 3rd one which is not aware of them - here's a simplified example of the 3rd one: ``` class MyManager { func callMyMethodOnAllObjecs() { // Do something here so that ALL objects present in memory that conform to MyProtocol get their myMethod called } } ``` Anyone?
2016/12/08
[ "https://Stackoverflow.com/questions/41048058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/831838/" ]
A heads up that what you need requires features belonging to dynamically typed languages, this means using the Objective-C runtime. This doesn't pose many technical challenges, but restricts the area of Swift entities you can use - basically only `NSObject` derived classes. Briefly, here's what you need: 1. support in `MyManager` for registering newly created objects 2. a piece of code that needs to be executed by all `MyProtocol` instances that register themselves to `MyManager` 3. most important, code that doesn't generate memory leaks, as registering an object within `MyManager` poses the risk of having the manager indefinitely retain that object. Below you can find a code that solves the problem: ``` // Since we need ObjectiveC specific runtime features, we need to // restrict the protocol to the NSObject protocol protocol MyProtocol: NSObjectProtocol { func myMethod() } public class MyClass: NSObject, MyProtocol { func myMethod() { print("myMethod called on MyClass") } } extension UIView: MyProtocol { func myMethod() { print("myMethod called on UIView") } } extension NSObject { // this is an alternative to the original init method, that besides the // original edit it registers the object within MyManager @objc func swizzledInit() -> NSObject { // this is not recursive, as init() in exchanged with swizzledInit() let `self` = swizzledInit() if let `self` = self as? MyProtocol { // the object is MyProtocol MyManager.shared.register(self) } return self } } class MyManager { static let shared = MyManager() private var objecters = [() -> MyProtocol?]() private init() { // let's swizzle init() with our custom init if let m1 = class_getInstanceMethod(NSObject.self, #selector(NSObject.init)), let m2 = class_getInstanceMethod(NSObject.self, #selector(NSObject.swizzledInit)) { method_exchangeImplementations(m1, m2) } } public func register(_ object: MyProtocol) { // registering a block in order to be able to keep a weak reference to // the registered object objecters.append({ [weak object] in return object }) } func callMyMethodOnAllObjecs() { var newList = [() -> MyProtocol?]() // go through the list of registered blocks, execute the method, // and retain only the ones for wich the object is still alive for object in objecters { if let o = object() { newList.append(object) o.myMethod() } } objecters = newList } } // This is to make sure the manager is instantiated first, // and thus it swizzles the NSObject initializer _ = MyManager.shared let myObject = MyClass() let myView = UIView() // an instance of MyClass and one of UIView will print stuff MyManager.shared.callMyMethodOnAllObjecs() ``` In summary, the above code: 1. swizzles the `init` of `NSObject` so that besides the original `init` it also registers the object to your manager. 2. keeps a list of closure that return objects instead of the object themselves, in order to be able to weakly reference those objects, thus to avoid keeping the objects alive more than they should be 3. cleans up the closures whose objects got deallocated when `callMyMethodOnAllObjecs` is invoked.
this way you can have add or remove observer methods ready to use. also you can create custom init to call this methods when instance is created. ``` protocol MyProtocol: class { func myMethod() func addObserverForMyMethod() func removeMyMethodObserver() } extension MyProtocol { func addObserverForMyMethod() { NotificationCenter.default.addObserver(self, selector: #selector(self.myMethod), name: Notification.Name("myMethodCall"), object: nil) } func removeMyMethodObserver() { NSNotificationCenter.default.removeObserver(self, name: "myMethodCall", object: nil) } } public class MyClass: MyProtocol { func myMethod() { print("myMethod called on MyClass") } } extension UIView: MyProtocol { func myMethod() { print("myMethod called on UIView") } } let myObject = MyClass() let myView = UIView() myObject.addObserverForMyMethod() myView.addObserverForMyMethod() ```
41,048,058
Update ------ As [maddy](https://stackoverflow.com/users/1226963/rmaddy) mentioned bellow in the comments it's obvious you need a reference to an object to be able to call a method on it. That is probably in fact my question: how do you keep track of all objects that implement a protocol? Looking back at Objective-C I thought about using something similar to `+load` or `+initialize` methods and add the object as an observer for a specific `NSNotification`. But that wouldn't work since those methods are class methods and not instance methods. So, trying to be even a little bit more specific: is there a method that get's called on all objects after they are created? A method that would allow me to add that object to a collection that I manage or as an observer for a specific `NSNotification`? P.S: I haven't tried adding to much details to the problem 'cause I didn't want to "polute" you with my bad, non-sense ideas. Original -------- So... Imagine this piece of code: ``` protocol MyProtocol: class { func myMethod() } public class MyClass: MyProtocol { func myMethod() { print("myMethod called on MyClass") } } extension UIView: MyProtocol { func myMethod() { print("myMethod called on UIView") } } let myObject = MyClass() let myView = UIView() ``` Now... I'm trying to figure out a way to call `myMethod` on both these objects from a 3rd one which is not aware of them - here's a simplified example of the 3rd one: ``` class MyManager { func callMyMethodOnAllObjecs() { // Do something here so that ALL objects present in memory that conform to MyProtocol get their myMethod called } } ``` Anyone?
2016/12/08
[ "https://Stackoverflow.com/questions/41048058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/831838/" ]
A heads up that what you need requires features belonging to dynamically typed languages, this means using the Objective-C runtime. This doesn't pose many technical challenges, but restricts the area of Swift entities you can use - basically only `NSObject` derived classes. Briefly, here's what you need: 1. support in `MyManager` for registering newly created objects 2. a piece of code that needs to be executed by all `MyProtocol` instances that register themselves to `MyManager` 3. most important, code that doesn't generate memory leaks, as registering an object within `MyManager` poses the risk of having the manager indefinitely retain that object. Below you can find a code that solves the problem: ``` // Since we need ObjectiveC specific runtime features, we need to // restrict the protocol to the NSObject protocol protocol MyProtocol: NSObjectProtocol { func myMethod() } public class MyClass: NSObject, MyProtocol { func myMethod() { print("myMethod called on MyClass") } } extension UIView: MyProtocol { func myMethod() { print("myMethod called on UIView") } } extension NSObject { // this is an alternative to the original init method, that besides the // original edit it registers the object within MyManager @objc func swizzledInit() -> NSObject { // this is not recursive, as init() in exchanged with swizzledInit() let `self` = swizzledInit() if let `self` = self as? MyProtocol { // the object is MyProtocol MyManager.shared.register(self) } return self } } class MyManager { static let shared = MyManager() private var objecters = [() -> MyProtocol?]() private init() { // let's swizzle init() with our custom init if let m1 = class_getInstanceMethod(NSObject.self, #selector(NSObject.init)), let m2 = class_getInstanceMethod(NSObject.self, #selector(NSObject.swizzledInit)) { method_exchangeImplementations(m1, m2) } } public func register(_ object: MyProtocol) { // registering a block in order to be able to keep a weak reference to // the registered object objecters.append({ [weak object] in return object }) } func callMyMethodOnAllObjecs() { var newList = [() -> MyProtocol?]() // go through the list of registered blocks, execute the method, // and retain only the ones for wich the object is still alive for object in objecters { if let o = object() { newList.append(object) o.myMethod() } } objecters = newList } } // This is to make sure the manager is instantiated first, // and thus it swizzles the NSObject initializer _ = MyManager.shared let myObject = MyClass() let myView = UIView() // an instance of MyClass and one of UIView will print stuff MyManager.shared.callMyMethodOnAllObjecs() ``` In summary, the above code: 1. swizzles the `init` of `NSObject` so that besides the original `init` it also registers the object to your manager. 2. keeps a list of closure that return objects instead of the object themselves, in order to be able to weakly reference those objects, thus to avoid keeping the objects alive more than they should be 3. cleans up the closures whose objects got deallocated when `callMyMethodOnAllObjecs` is invoked.
No. There is no overridable initialize method called on all objects. In fact, in swift there is nothing inherited by base classes at all unless they inherit from `NSObject`. This type of dynamism purposefully doesn't exist in swift. In order to do something like this, I'd recommend that you use the objective C runtime. Consider using Injection for Xcode's source as a jumping off point: <https://github.com/johnno1962/injectionforxcode/blob/master/InjectionPluginLite/Classes/BundleSweeper.h> but really this goes very strongly against the grain in swift. If you're willing to consider something similar, this might work for you, and at the same time be more type safe (and it has the benefit of allowing heterogeneous swift types): ``` protocol X { static var insts:[X]{ get } static func create() -> X } final class A:X{ static func create() -> X { let it = A() insts.append(it) return it } static var insts:[X] = [] } struct B:X{ static func create() -> X { let it = B() insts.append(it) return it } static var insts:[X] = [] } var protocols:[X.Type] = [A.self, B.self] for p in protocols { p.insts.forEach({print($0)}) } ```
53,604,360
I have so many of these in my code: ``` if ( x1 == x2 && y1 == y2) { // do nothing } else { // do the thing } ``` I wonder if I can replace it with just if, without else, to make the code cleaner. I tried the following: ``` if ( x1 != x2 && y1 != y2) { // do the thing } ``` but it doesn't work because if only one of them is not equal, then the whole thing is false.
2018/12/04
[ "https://Stackoverflow.com/questions/53604360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5554751/" ]
Use one of De Morgan's laws(a): ``` not (A and B) = (not A) or (not B) ``` In other words: ``` if (x1 != x2 || y1 != y2) { // do the thing } ``` If you don't want to think too much about propositional logic, you can just use the following English variant. 1. You want to *not* do "the thing" *only* if both statements are true. 2. Therefore, if *either or both* statements are false, you should do "the thing". --- (a) The other one is: ``` not (A or B) = (not A) and (not B) ```
If your code going to end in the if or else statement then you can do ``` if (x1 == x2 && y1 == y2) { // do something return; // this will end the execution here. } // the else block would be in the rest of execution. ``` *This method is helpful when you're trying to commit certain input from user or making an assertion. So i you got the the right input continue execution else aport.. instead of checking uncertain possibilities.*
48,087
A colleague in the same team spends most of his time (if not all) conducting private business activities through company’s electronic communication systems or his own cell phone during regular working hours dedicated to company. Usually he comes in office at 9am and leaves at 10am for hours then show up again in the afternoon around 2pm or 3pm. Not mention sometimes doesn't appear for the whole day at all (there is no need for us to work outside the office). Even when he is in the office at his desk, it doesn't seem he is doing company's job - surfing internet about his own business and making/receiving a lot of phone calls which are not work related. It has been like that for almost 3 months. This is definitely against company's policy and I think it's unfair to other team members because we are in the same team and have to share more workload on the projects. However, it seems that our direct team manager knows what he is doing as I overheard they were talking about his private business sometimes - I sit just next to him, but the manager doesn't do anything and even covers him by assigning him less jobs. They are in very good personal relationship though as what I know. Should I report to higher level management or HR in this case? If yes, what and how should I do? Should I only report my colleague's misbehavior or together with my manager's irresponsibility? Would people think I am a snitch if I do so?
2015/06/11
[ "https://workplace.stackexchange.com/questions/48087", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/37018/" ]
Hmm. Tricky one. You don't want in any way to imply that your manager does not know what is happening or cannot see that the coworker is doing what he is doing. There may be circumstances in which your manager and/or HR know about this and due to reasons that are not disclosed to you cannot do anything about it (medical reasons come to mind first). It's not your job to assess if this guy is doing his job and/or is violating any policies. If you feel this could be helpful express your concern to the manager in a 1:1 setting, in a non-threatening/non-confruntational way. At the end of the day, do the job you are paid for and make sure that the amount of work that is assigned to you is fair/doable/manageable. (with or without a slacker as a coworker you should definitely speak up if you think that the amount of work you are given is unreasonable - cannot be done in the given time).
This is not really the type of violation you go to HR with. The worker is not productive and the manager does not seem to care. It is not like a breach of a security policy. Going to HR would be calling out the worker and manager (who is also your manager). There are a lot of ways that could go poorly for you. You can't just report your colleague without reporting your manager as the first thing they will ask is did you take this up with your manager. You can take it up with your manager but you already said the manager is aware.
48,087
A colleague in the same team spends most of his time (if not all) conducting private business activities through company’s electronic communication systems or his own cell phone during regular working hours dedicated to company. Usually he comes in office at 9am and leaves at 10am for hours then show up again in the afternoon around 2pm or 3pm. Not mention sometimes doesn't appear for the whole day at all (there is no need for us to work outside the office). Even when he is in the office at his desk, it doesn't seem he is doing company's job - surfing internet about his own business and making/receiving a lot of phone calls which are not work related. It has been like that for almost 3 months. This is definitely against company's policy and I think it's unfair to other team members because we are in the same team and have to share more workload on the projects. However, it seems that our direct team manager knows what he is doing as I overheard they were talking about his private business sometimes - I sit just next to him, but the manager doesn't do anything and even covers him by assigning him less jobs. They are in very good personal relationship though as what I know. Should I report to higher level management or HR in this case? If yes, what and how should I do? Should I only report my colleague's misbehavior or together with my manager's irresponsibility? Would people think I am a snitch if I do so?
2015/06/11
[ "https://workplace.stackexchange.com/questions/48087", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/37018/" ]
Hmm. Tricky one. You don't want in any way to imply that your manager does not know what is happening or cannot see that the coworker is doing what he is doing. There may be circumstances in which your manager and/or HR know about this and due to reasons that are not disclosed to you cannot do anything about it (medical reasons come to mind first). It's not your job to assess if this guy is doing his job and/or is violating any policies. If you feel this could be helpful express your concern to the manager in a 1:1 setting, in a non-threatening/non-confruntational way. At the end of the day, do the job you are paid for and make sure that the amount of work that is assigned to you is fair/doable/manageable. (with or without a slacker as a coworker you should definitely speak up if you think that the amount of work you are given is unreasonable - cannot be done in the given time).
Maybe he has a smaller contract, like 6 hours a day or less, so he can work on other own projects the rest of the time. Or him beeing away is at customers. You don't know and as long as the manager knows about it, all is fine. Unless you want to report the manager for not doing his job properly. ;-)
48,087
A colleague in the same team spends most of his time (if not all) conducting private business activities through company’s electronic communication systems or his own cell phone during regular working hours dedicated to company. Usually he comes in office at 9am and leaves at 10am for hours then show up again in the afternoon around 2pm or 3pm. Not mention sometimes doesn't appear for the whole day at all (there is no need for us to work outside the office). Even when he is in the office at his desk, it doesn't seem he is doing company's job - surfing internet about his own business and making/receiving a lot of phone calls which are not work related. It has been like that for almost 3 months. This is definitely against company's policy and I think it's unfair to other team members because we are in the same team and have to share more workload on the projects. However, it seems that our direct team manager knows what he is doing as I overheard they were talking about his private business sometimes - I sit just next to him, but the manager doesn't do anything and even covers him by assigning him less jobs. They are in very good personal relationship though as what I know. Should I report to higher level management or HR in this case? If yes, what and how should I do? Should I only report my colleague's misbehavior or together with my manager's irresponsibility? Would people think I am a snitch if I do so?
2015/06/11
[ "https://workplace.stackexchange.com/questions/48087", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/37018/" ]
> > Should I report to higher level management or HR in this case? > > > **No.** The individual doesn't report to you. And you indicate that your common manager knows of this individual's action. So no, it's not your role to report on the misbehavior of others. Just focus on your own work and let your manager be responsible for the actions of his department. Managers need to get the work done, so if this individual's actions prevent the department from getting things done, the manager and the individual will have to deal with it. These things have a way of catching up with the people involved. Make sure you don't cover up for this individual or for the manager. If someone asks where he is between 10 and 2, just say that you don't know. Or if you saw the individual leave the office, just indicate what you actually saw happen. > > Would people think I am a snitch if I do so? > > > **Yes, of course.** What you are considering is pretty much the definition of a "snitch".
This is not really the type of violation you go to HR with. The worker is not productive and the manager does not seem to care. It is not like a breach of a security policy. Going to HR would be calling out the worker and manager (who is also your manager). There are a lot of ways that could go poorly for you. You can't just report your colleague without reporting your manager as the first thing they will ask is did you take this up with your manager. You can take it up with your manager but you already said the manager is aware.
48,087
A colleague in the same team spends most of his time (if not all) conducting private business activities through company’s electronic communication systems or his own cell phone during regular working hours dedicated to company. Usually he comes in office at 9am and leaves at 10am for hours then show up again in the afternoon around 2pm or 3pm. Not mention sometimes doesn't appear for the whole day at all (there is no need for us to work outside the office). Even when he is in the office at his desk, it doesn't seem he is doing company's job - surfing internet about his own business and making/receiving a lot of phone calls which are not work related. It has been like that for almost 3 months. This is definitely against company's policy and I think it's unfair to other team members because we are in the same team and have to share more workload on the projects. However, it seems that our direct team manager knows what he is doing as I overheard they were talking about his private business sometimes - I sit just next to him, but the manager doesn't do anything and even covers him by assigning him less jobs. They are in very good personal relationship though as what I know. Should I report to higher level management or HR in this case? If yes, what and how should I do? Should I only report my colleague's misbehavior or together with my manager's irresponsibility? Would people think I am a snitch if I do so?
2015/06/11
[ "https://workplace.stackexchange.com/questions/48087", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/37018/" ]
> > Should I report to higher level management or HR in this case? > > > **No.** The individual doesn't report to you. And you indicate that your common manager knows of this individual's action. So no, it's not your role to report on the misbehavior of others. Just focus on your own work and let your manager be responsible for the actions of his department. Managers need to get the work done, so if this individual's actions prevent the department from getting things done, the manager and the individual will have to deal with it. These things have a way of catching up with the people involved. Make sure you don't cover up for this individual or for the manager. If someone asks where he is between 10 and 2, just say that you don't know. Or if you saw the individual leave the office, just indicate what you actually saw happen. > > Would people think I am a snitch if I do so? > > > **Yes, of course.** What you are considering is pretty much the definition of a "snitch".
Maybe he has a smaller contract, like 6 hours a day or less, so he can work on other own projects the rest of the time. Or him beeing away is at customers. You don't know and as long as the manager knows about it, all is fine. Unless you want to report the manager for not doing his job properly. ;-)
115,403
I am drawing trees in LATEX. The `qtree` library seems to be what I need but the parent is always placed in the center of its children like this: ``` parent / \ child_1 child_2 ``` (*I'm a new user and does not have enough reputation to post an image.*) What I want is a right-growing tree like this: ``` root -- child_1 -- grandchild_1_1 \- child_2 \- child_3 -- grandchild_3_1 \- grandchild_3_2 -- great-grandchild_3_2_1 \- child_4 -- grandchild_4_1 ``` Rotating the `qtree` to right-growing is insufficient since the parent nodes are then vertically aligned to the center of their children, but I need them to remain on the top of their subtrees. I've tried `trees` library of TikZ, which allows customized "growth function" to specify the position of children. However it does not consider the size of subtrees, so in this case `child_4` would follow immediately under `child_3`, making `grandchild_4_1` overlap with `grandchild_3_2`. Is there a simple way to just "disable" the centering of parents in `qtree`? Or is there any better solution (may be writing my own macro)?
2013/05/21
[ "https://tex.stackexchange.com/questions/115403", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/31039/" ]
I'm not sure if this is what you want, but here's a solution using the `forest` package. It provides an alignment parameter for aligning the children of a node which does most of what you want. I didn't know whether you wanted square edges or not, but they seem more appropriate for this kind of tree, (in the screen shot image the lines look odd, but this is an artefact of the screen rendering). I've added a simple alternative that looks a bit nicer without the squared edges. ``` \documentclass{article} \usepackage{forest} \begin{document} \begin{forest} grow right/.style={for tree={% calign=last, grow=east, ,s sep=.5cm, parent anchor=east, child anchor=west, edge path={\noexpand\path[\forestoption{edge}] (!u.parent anchor) -- +(0pt,-10pt) |- (.child anchor) \forestoption{edge label};} } } ,grow right [Root [Child1 ] [Child2 [GChild1 ] [Gchild2 ] [GChild3 ] ] [Child3 [Gchild4 ] [Gchild5 ] ] ] \end{forest} \hfill \begin{forest} [Root,for tree={calign=last,grow=east,draw, parent anchor=east,child anchor=west} [Child1 ] [Child2 [GChild1 ] [Gchild2 ] [GChild3 ] ] [Child3 [Gchild4 ] [Gchild5 ] ] ] \end{forest} \end{document} ``` ![output of code](https://i.stack.imgur.com/40aNO.png) **Edit:** Notice that the children are organized in a reversed order, due to the counter-clockwise coordinates. Using the options `calign=first, reversed=true` in the `for tree = {...}` block produces the exact tree needed, as shown below: ![order corrected](https://i.stack.imgur.com/3sr83.png)
This is just a supplement to [Alan Munn's answer](https://tex.stackexchange.com/a/115429/) which uses the `edges` library and other features of the current version of Forest. This therefore requires version 2+. ``` \documentclass[tikz,border=10pt,multi,rgb]{standalone} \usepackage[edges]{forest} \begin{document} \begin{forest} for tree={ grow'=0, parent anchor=children, child anchor=parent, anchor=parent, if n children=0{folder}{}, edge path'={(!u.parent anchor) -- ++(5pt,0) |- (.child anchor)}, }, where n=1{ calign with current edge }{}, [Root [Child1] [Child2 [GChild1] [Gchild2] [GChild3] ] [Child3 [Gchild4 ] [Gchild5 ] ] ] \end{forest} \end{document} ``` This code produces the squared-edge version of the tree: [![squared edges](https://i.stack.imgur.com/jOpPy.png)](https://i.stack.imgur.com/jOpPy.png) I think the small offset at the start of the path, prior to the vertical line, looks a bit neater, but this could be eliminated if preferred by changing the definition of the edge path to ``` edge path'={(!u.parent anchor) |- (.child anchor)}, ``` [![squared edges without offset](https://i.stack.imgur.com/y6lz2.png)](https://i.stack.imgur.com/y6lz2.png) Alternatively, deleting this line altogether results in a tree using the default path: [![non-squared default edges](https://i.stack.imgur.com/aooPi.png)](https://i.stack.imgur.com/aooPi.png)
33,557
What is the meaning of the expression "that's the top and bottom of it"? In which situations can it be used?
2011/07/10
[ "https://english.stackexchange.com/questions/33557", "https://english.stackexchange.com", "https://english.stackexchange.com/users/9625/" ]
The phrase simply means "that's everything, the whole story, there's nothing more to be said. As Robusto pointed out, `that's the long and short of it` means the same thing, and is much more common and well-understood in American English. I don't know how common the `top and bottom of it` is in British English.
It means that is the extent of the subject, covering all aspects. Another phrase meaning the same thing is: > > That's the long and the short of it. > > > Use it in situations where you feel you have explained a thing in its entirety (or nearly) and mean to convey that you have said enough on the subject for your listener or reader to understand at least the essential points.
33,557
What is the meaning of the expression "that's the top and bottom of it"? In which situations can it be used?
2011/07/10
[ "https://english.stackexchange.com/questions/33557", "https://english.stackexchange.com", "https://english.stackexchange.com/users/9625/" ]
The phrase simply means "that's everything, the whole story, there's nothing more to be said. As Robusto pointed out, `that's the long and short of it` means the same thing, and is much more common and well-understood in American English. I don't know how common the `top and bottom of it` is in British English.
The expression means the *summary* of something or the final *conclusion*. According to the [Longman](http://www.ldoceonline.com/dictionary/top_1) dictionary: > > "**the top and bottom of it**": > the general result or meaning of a situation, expressed in a few words: > > > > > > > He's trying to embarrass you, that's the top and bottom of it. > > > > > > > > >
8,547,563
Apparently, back in Firefox 3.6, the following was legitimate: ``` /[0-9]{3}/('23 2 34 678 9 09') ``` and the result was '678'. FF8 isn't having any. What's the right syntax now?
2011/12/17
[ "https://Stackoverflow.com/questions/8547563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/131433/" ]
Do you want ``` /[0-9]{3}/.test('23 2 34 678 9 09'); ``` or ``` /[0-9]{3}/.exec('23 2 34 678 9 09'); ```
I don't know why you would need that syntax but here's something for the lulz: ``` RegExp = (function(){ var old = RegExp; return function(){ return old.prototype.exec.bind( old.apply( this, arguments ) ); }; })() ``` Then: ``` new RegExp( "[0-9]{3}" )('23 2 34 678 9 09') //["678"] ``` Note that the hacked constructor won't be invoked when using literals so it only works when using `new RegExp` ;P
8,547,563
Apparently, back in Firefox 3.6, the following was legitimate: ``` /[0-9]{3}/('23 2 34 678 9 09') ``` and the result was '678'. FF8 isn't having any. What's the right syntax now?
2011/12/17
[ "https://Stackoverflow.com/questions/8547563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/131433/" ]
Do you want ``` /[0-9]{3}/.test('23 2 34 678 9 09'); ``` or ``` /[0-9]{3}/.exec('23 2 34 678 9 09'); ```
See this discussion : <http://whereswalden.com/2011/03/06/javascript-change-in-firefox-5-not-4-and-in-other-browsers-regular-expressions-cant-be-called-like-functions/>
5,387,494
I originally had a form set up as such (CSS styles have been removed) ``` <form name="LoginForm" action="login.php" method="post"> <input name="email" id="email" type="text"></input> <input name="password" id="password" type="password"></input> <input name="login" id="login" type="submit" value="Login"></input> </form> ``` and it worked fine, and login.php would validate the user creditionals. However, that approach required a page redirect. I am trying to migrate the code to AJAX so I can query the login details and stay within the page. [edit] here is the AJAX object I use ``` function Ajax(){ this.xmlhttp=null; //code below will assign correct request object if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari this.xmlhttp=new XMLHttpRequest(); } else{ // code for IE6, IE5 this.xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } this.stateChangeFunction=function(){}; //user must reimplement this var that=this; this.xmlhttp.onreadystatechange=function(){ //executes the appropriate code when the ready state and status are correct if (this.readyState==4 && this.status==200){ that.stateChangeFunction(); } else{ dump("Error"); } } } ``` then I have a login.js function, which I am not too sure how to incorporate, currently I add it to the onclick event of the submit button: ``` function login(email,password){ var ajax=new Ajax(); //ajax.xmlhttp.open("GET","login.php?LoginEmailField="+email+",LoginPasswordField="+password,true); //ajax.xmlhttp.send(); } ``` You will notice how those last two lines are commented out, I am not too sure how to send arguments at the moment, but the point is that even with the two commented out, the entire site still reloads. What is the correct way to use AJAX in forms. Thanks
2011/03/22
[ "https://Stackoverflow.com/questions/5387494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654789/" ]
Your code only shows `HTML`. `AJAX` uses `javascript` to communicate to PHP script. So, Only on seeing the `js` code, Debugging is possible.
To avoid the default event you have to use `action='javascript: void(null);'` instead of removing it.
5,387,494
I originally had a form set up as such (CSS styles have been removed) ``` <form name="LoginForm" action="login.php" method="post"> <input name="email" id="email" type="text"></input> <input name="password" id="password" type="password"></input> <input name="login" id="login" type="submit" value="Login"></input> </form> ``` and it worked fine, and login.php would validate the user creditionals. However, that approach required a page redirect. I am trying to migrate the code to AJAX so I can query the login details and stay within the page. [edit] here is the AJAX object I use ``` function Ajax(){ this.xmlhttp=null; //code below will assign correct request object if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari this.xmlhttp=new XMLHttpRequest(); } else{ // code for IE6, IE5 this.xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } this.stateChangeFunction=function(){}; //user must reimplement this var that=this; this.xmlhttp.onreadystatechange=function(){ //executes the appropriate code when the ready state and status are correct if (this.readyState==4 && this.status==200){ that.stateChangeFunction(); } else{ dump("Error"); } } } ``` then I have a login.js function, which I am not too sure how to incorporate, currently I add it to the onclick event of the submit button: ``` function login(email,password){ var ajax=new Ajax(); //ajax.xmlhttp.open("GET","login.php?LoginEmailField="+email+",LoginPasswordField="+password,true); //ajax.xmlhttp.send(); } ``` You will notice how those last two lines are commented out, I am not too sure how to send arguments at the moment, but the point is that even with the two commented out, the entire site still reloads. What is the correct way to use AJAX in forms. Thanks
2011/03/22
[ "https://Stackoverflow.com/questions/5387494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654789/" ]
I havent done enough ajax in raw js to give a tutorial here so Im' going to use jquery. However anything i show can be done in raw javascript so maybe someone else will be kind enough to show you a raw implementation. First of all you should use POST instead of GET for your login. Secondly as i said in my comment you should use the actual URL to the login page as the action. This way users who dont have JS for whatever reason can still login. Its best to do this by binding to the forms `onSubmit` event. ``` <form name="LoginForm" action="login.php" method="post"> <input name="email" id="email" type="text"></input> <input name="password" id="password" type="password"></input> <input name="login" id="login" type="submit" value="Login"></input> </form> ``` And with jquery: ``` function doLogin(event){ event.preventDefault(); // stop the form from doing its normal post var form = $('form[name=LoginForm]'); // post via ajax instead $.ajax({ url: form.attr('action'), // grab the value of the action attribute "login.php" data: form.serialize(), // converts input fields to a query string type: 'post', dataType: 'text', success: function(data){ /* callback when status is 200 * you can redirect here ... data is the response from the server, * send the redirect URL in this response */ window.location.href = data; }, error: function(textStatus){ alert('ERROR'); } }); } // bind our function to the onSubmit event of the form $('form[name=LoginForm]').submit(doLogin); ``` Then on the serverside you can check if its an ajax based request: ``` <?php // do your login stuff // set $successUrl to the URL you want to redirect to // check if its ajax if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { echo $successUrl; exit(0); } else { // was a non-ajax request - do a normal redirect header('Location: '.$successUrl); } ```
Your code only shows `HTML`. `AJAX` uses `javascript` to communicate to PHP script. So, Only on seeing the `js` code, Debugging is possible.
5,387,494
I originally had a form set up as such (CSS styles have been removed) ``` <form name="LoginForm" action="login.php" method="post"> <input name="email" id="email" type="text"></input> <input name="password" id="password" type="password"></input> <input name="login" id="login" type="submit" value="Login"></input> </form> ``` and it worked fine, and login.php would validate the user creditionals. However, that approach required a page redirect. I am trying to migrate the code to AJAX so I can query the login details and stay within the page. [edit] here is the AJAX object I use ``` function Ajax(){ this.xmlhttp=null; //code below will assign correct request object if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari this.xmlhttp=new XMLHttpRequest(); } else{ // code for IE6, IE5 this.xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } this.stateChangeFunction=function(){}; //user must reimplement this var that=this; this.xmlhttp.onreadystatechange=function(){ //executes the appropriate code when the ready state and status are correct if (this.readyState==4 && this.status==200){ that.stateChangeFunction(); } else{ dump("Error"); } } } ``` then I have a login.js function, which I am not too sure how to incorporate, currently I add it to the onclick event of the submit button: ``` function login(email,password){ var ajax=new Ajax(); //ajax.xmlhttp.open("GET","login.php?LoginEmailField="+email+",LoginPasswordField="+password,true); //ajax.xmlhttp.send(); } ``` You will notice how those last two lines are commented out, I am not too sure how to send arguments at the moment, but the point is that even with the two commented out, the entire site still reloads. What is the correct way to use AJAX in forms. Thanks
2011/03/22
[ "https://Stackoverflow.com/questions/5387494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654789/" ]
I havent done enough ajax in raw js to give a tutorial here so Im' going to use jquery. However anything i show can be done in raw javascript so maybe someone else will be kind enough to show you a raw implementation. First of all you should use POST instead of GET for your login. Secondly as i said in my comment you should use the actual URL to the login page as the action. This way users who dont have JS for whatever reason can still login. Its best to do this by binding to the forms `onSubmit` event. ``` <form name="LoginForm" action="login.php" method="post"> <input name="email" id="email" type="text"></input> <input name="password" id="password" type="password"></input> <input name="login" id="login" type="submit" value="Login"></input> </form> ``` And with jquery: ``` function doLogin(event){ event.preventDefault(); // stop the form from doing its normal post var form = $('form[name=LoginForm]'); // post via ajax instead $.ajax({ url: form.attr('action'), // grab the value of the action attribute "login.php" data: form.serialize(), // converts input fields to a query string type: 'post', dataType: 'text', success: function(data){ /* callback when status is 200 * you can redirect here ... data is the response from the server, * send the redirect URL in this response */ window.location.href = data; }, error: function(textStatus){ alert('ERROR'); } }); } // bind our function to the onSubmit event of the form $('form[name=LoginForm]').submit(doLogin); ``` Then on the serverside you can check if its an ajax based request: ``` <?php // do your login stuff // set $successUrl to the URL you want to redirect to // check if its ajax if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { echo $successUrl; exit(0); } else { // was a non-ajax request - do a normal redirect header('Location: '.$successUrl); } ```
To avoid the default event you have to use `action='javascript: void(null);'` instead of removing it.
46,244,889
I am trying to display form information with Shipping Information Heading, with validation of name, contact etc. I am able to display it but not able to validate it and if I submit a form blank it shows blank values except payment and shipping method are displaying with default values selected and one more thing it is not showing errors i.e; fname is required, I am confused a little bit. Can anyone add one things that if anyone post blank form it redirect it to again to form2.php page? This is my form2.php page ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <form action="welcome2.php" method="post"> <label>First name: </label> <input type="text" name="fname"><br> <label>Lastname name: </label> <input type="text" name="lname"><br> <label>Email: </label> <input type="email" name="email"><br> <label>Contact No </label> <input type="text" name="cno"><br> <label>Address </label> <input type="text" name="addr"><br> <label>City </label> <input type="text" name="city"><br> <label>State </label> <input type="text" name="state"><br> <label>Country </label> <input type="text" name="country"><br> <label>Zip Code </label> <input type="text" name="zipcode"><br> <label>Credit Card Number </label> <input type="text" name="ccno"><br> <label>Payment Option </label> <select name="Payment_option"> <option value="Cash On Delivery">Cash On Delivery</option> <option value="Online">Online</option> </select> <br> <label>Shipping Method </label> <select name="Shipping_Method"> <option value="TCS">TCS</option> <option value="Leapord">Leapord</option> <option value="FEDEX">FEDEX</option> </select> <br> <button type="submit" name="sub">Submit</button> </form> <?php if(isset($_SESSION['errors'])) { foreach($_SESSION['errors'] as $key => $error) { echo $error."<br>"; } unset($_SESSION['errors']); } ?> </body> </html> ``` and this is my welcome2.php page ``` <?php session_start(); $fname = ""; $lname = ""; $email = ""; $cno = ""; $addr = ""; $city = ""; $state = ""; $country = ""; $zipcode = ""; $ccno = ""; extract($_POST); $errors = array(); if(isset($_POST['fname'])){ $_SESSION['fname'] = $_POST['fname']; }if(isset($_POST['lname'])){ $_SESSION['lname'] = $_POST['lname']; }if(isset($_POST['email'])){ $_SESSION['email'] = $_POST['email']; }if(isset($_POST['cno'])){ $_SESSION['cno'] = $_POST['cno']; }if(isset($_POST['addr'])){ $_SESSION['addr'] = $_POST['addr']; }if(isset($_POST['city'])){ $_SESSION['city'] = $_POST['city']; }if(isset($_POST['state'])){ $_SESSION['state'] = $_POST['state']; }if(isset($_POST['country'])){ $_SESSION['country'] = $_POST['country']; }if(isset($_POST['zipcode'])){ $_SESSION['zipcode'] = $_POST['zipcode']; }if(isset($_POST['ccno'])){ $_SESSION['ccno'] = $_POST['ccno']; } if(isset($_POST['sub'])) { if(!$fname) $errors[] = "First name is required"; } if(!$lname) { $errors[] = "Last name is required"; } if (!preg_match("/^[a-zA-Z ]*$/",$fname)) { $errors = "Only letters and white space allowed"; } if (!preg_match("/^[a-zA-Z ]*$/",$lname)) { $errors = "Only letters and white space allowed"; } if(!$email) { $errors[] = "Email is required"; } if(!$cno) { $errors[] = "Contact is required"; }if (strlen($cno)<=5) { $errors[] ="Contact contain more than 11 characters"; } if(!$addr) { $errors[] = "Address is required"; } if(!$city) { $errors[] = "City is required"; } if(!$state) { $errors[] = "State is required"; } if(!$country) { $errors[] = "Country is required"; } if(!$zipcode) { $errors[] = "Zip Code is required"; } if(!$ccno) { $errors[] = "Credit Card Number is required"; }?> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h1> Shipping Information </h1> <?php echo $fname; echo "<br>"; echo $lname; echo "<br>"; echo $email; echo "<br>"; echo $cno; echo "<br>"; echo $addr; echo "<br>"; echo $city; echo "<br>"; echo $state; echo "<br>"; echo $country; echo "<br>"; echo $zipcode; echo "<br>"; echo $ccno; echo "<br>"; $option1 = isset($_POST['Payment_option']) ? $_POST['Payment_option'] : false; if ($option1) { echo htmlentities($_POST['Payment_option'], ENT_QUOTES, "UTF-8"); } else { echo "Payment Method is required"; } echo "<br>"; $option2 = isset($_POST['Shipping_Method']) ? $_POST['Shipping_Method'] : false; if ($option2) { echo htmlentities($_POST['Shipping_Method'], ENT_QUOTES, "UTF-8"); } else { echo "Shipping Method is required"; } ?> ```
2017/09/15
[ "https://Stackoverflow.com/questions/46244889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Although MySQL will display timestamps to you in your current timezone (or more specifically the server's timezone), they're stored in the generic UTC timezone. When a user creates an account on your forum, they should select their desired timezone. (You may also be able to auto-detect it from their browser.) Then, each time after your PHP script establishes a database connection, you'll run the query, "SET time\_zone = ?" where the "?" will be the timezone you've saved with their profile. After that, every query they make through that connection will automatically convert the UTC timestamps into their timezone, and you should be able to display the results directly to the user. [MySQL timezone reference](https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html)
Set your default timezone for your page yourself, so all users get to use the time zone you set there. E.g ``` <?php date_default_timezone_set("Africa/Lagos"); ?> ```
46,244,889
I am trying to display form information with Shipping Information Heading, with validation of name, contact etc. I am able to display it but not able to validate it and if I submit a form blank it shows blank values except payment and shipping method are displaying with default values selected and one more thing it is not showing errors i.e; fname is required, I am confused a little bit. Can anyone add one things that if anyone post blank form it redirect it to again to form2.php page? This is my form2.php page ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <form action="welcome2.php" method="post"> <label>First name: </label> <input type="text" name="fname"><br> <label>Lastname name: </label> <input type="text" name="lname"><br> <label>Email: </label> <input type="email" name="email"><br> <label>Contact No </label> <input type="text" name="cno"><br> <label>Address </label> <input type="text" name="addr"><br> <label>City </label> <input type="text" name="city"><br> <label>State </label> <input type="text" name="state"><br> <label>Country </label> <input type="text" name="country"><br> <label>Zip Code </label> <input type="text" name="zipcode"><br> <label>Credit Card Number </label> <input type="text" name="ccno"><br> <label>Payment Option </label> <select name="Payment_option"> <option value="Cash On Delivery">Cash On Delivery</option> <option value="Online">Online</option> </select> <br> <label>Shipping Method </label> <select name="Shipping_Method"> <option value="TCS">TCS</option> <option value="Leapord">Leapord</option> <option value="FEDEX">FEDEX</option> </select> <br> <button type="submit" name="sub">Submit</button> </form> <?php if(isset($_SESSION['errors'])) { foreach($_SESSION['errors'] as $key => $error) { echo $error."<br>"; } unset($_SESSION['errors']); } ?> </body> </html> ``` and this is my welcome2.php page ``` <?php session_start(); $fname = ""; $lname = ""; $email = ""; $cno = ""; $addr = ""; $city = ""; $state = ""; $country = ""; $zipcode = ""; $ccno = ""; extract($_POST); $errors = array(); if(isset($_POST['fname'])){ $_SESSION['fname'] = $_POST['fname']; }if(isset($_POST['lname'])){ $_SESSION['lname'] = $_POST['lname']; }if(isset($_POST['email'])){ $_SESSION['email'] = $_POST['email']; }if(isset($_POST['cno'])){ $_SESSION['cno'] = $_POST['cno']; }if(isset($_POST['addr'])){ $_SESSION['addr'] = $_POST['addr']; }if(isset($_POST['city'])){ $_SESSION['city'] = $_POST['city']; }if(isset($_POST['state'])){ $_SESSION['state'] = $_POST['state']; }if(isset($_POST['country'])){ $_SESSION['country'] = $_POST['country']; }if(isset($_POST['zipcode'])){ $_SESSION['zipcode'] = $_POST['zipcode']; }if(isset($_POST['ccno'])){ $_SESSION['ccno'] = $_POST['ccno']; } if(isset($_POST['sub'])) { if(!$fname) $errors[] = "First name is required"; } if(!$lname) { $errors[] = "Last name is required"; } if (!preg_match("/^[a-zA-Z ]*$/",$fname)) { $errors = "Only letters and white space allowed"; } if (!preg_match("/^[a-zA-Z ]*$/",$lname)) { $errors = "Only letters and white space allowed"; } if(!$email) { $errors[] = "Email is required"; } if(!$cno) { $errors[] = "Contact is required"; }if (strlen($cno)<=5) { $errors[] ="Contact contain more than 11 characters"; } if(!$addr) { $errors[] = "Address is required"; } if(!$city) { $errors[] = "City is required"; } if(!$state) { $errors[] = "State is required"; } if(!$country) { $errors[] = "Country is required"; } if(!$zipcode) { $errors[] = "Zip Code is required"; } if(!$ccno) { $errors[] = "Credit Card Number is required"; }?> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h1> Shipping Information </h1> <?php echo $fname; echo "<br>"; echo $lname; echo "<br>"; echo $email; echo "<br>"; echo $cno; echo "<br>"; echo $addr; echo "<br>"; echo $city; echo "<br>"; echo $state; echo "<br>"; echo $country; echo "<br>"; echo $zipcode; echo "<br>"; echo $ccno; echo "<br>"; $option1 = isset($_POST['Payment_option']) ? $_POST['Payment_option'] : false; if ($option1) { echo htmlentities($_POST['Payment_option'], ENT_QUOTES, "UTF-8"); } else { echo "Payment Method is required"; } echo "<br>"; $option2 = isset($_POST['Shipping_Method']) ? $_POST['Shipping_Method'] : false; if ($option2) { echo htmlentities($_POST['Shipping_Method'], ENT_QUOTES, "UTF-8"); } else { echo "Shipping Method is required"; } ?> ```
2017/09/15
[ "https://Stackoverflow.com/questions/46244889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It is simple. Don't store timestamp directly tends to user timezone. Whatever user time zone u convert to your php default timezone and store it to Database If user1 from india ,convert it to your php timezone save the message post time, while showing to user2 convert the time stamp from your php timezone to user2 time zone and show the data. It will give correct value Make sure your php and MySQL timezone are same. ``` For example User 1 from IST User 2 from UTC Your php and MySQL time zone is PsT If user1 post msg u convert IST to PST store to your db. If user2 post msg u convert UTC to PST store to it db. While showing post to user1 U should convert PST to IST for user2 Convert PST to UTC USE MYSQL FUNCTION convert_tz IN PHP to show ago follow below method function time_elapsed_string($datetime, $full = false) { $now = new DateTime; $ago = new DateTime($datetime); $diff = $now->diff($ago); $diff->w = floor($diff->d / 7); $diff->d -= $diff->w * 7; $string = array( 'y' => 'year', 'm' => 'month', 'w' => 'week', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ); foreach ($string as $k => &$v) { if ($diff->$k) { $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : ''); } else { unset($string[$k]); } } if (!$full) $string = array_slice($string, 0, 1); return $string ? implode(', ', $string) . ' ago' : 'just now'; } ``` Get User Time zone using <http://ipinfodb.com/ip_location_api.php> or by Java script [get user timezone](https://stackoverflow.com/questions/4746249/get-user-timezone)
Set your default timezone for your page yourself, so all users get to use the time zone you set there. E.g ``` <?php date_default_timezone_set("Africa/Lagos"); ?> ```
73,467,363
We are testing [React error boundaries](https://reactjs.org/docs/error-boundaries.html) within our application. Currently, we are seeing the React error boundary intermittently mask the error with the following: *"An error was thrown inside one of your components, but React doesn't know what it was. This is likely due to browser flakiness. React does its best to preserve the "Pause on exceptions" behavior of the DevTools, which requires some DEV-mode only tricks. It's possible that these don't work in your browser. Try triggering the error in production mode, or switching to a modern browser. If you suspect that this is actually an issue with React, please file an issue. at Object.invokeGuardedCallbackImpl"* The error boundary does successfully capture the stack trace; however, without the error message, we only have half of the picture of what's failing. Has anyone come across this behavior before? Or are there any suggestions on capturing the full error with React's Error Boundary? Instead of the error message above, we are expecting something like *"Cannot read properties of undefined (reading 'toString')"* for the error message. **Environment** * We are using React 16.12.0. * We are testing with a production build. **Sample Code** ``` export class ReactErrorBoundary extends React.Component< {}, ReactErrorBoundaryState > { constructor(props) { super(props); this.state = { hasError: false }; } static contextType = CpqTelemetryContext; static getDerivedStateFromError(error: TypeError): ReactErrorBoundaryState { return { hasError: true, error: error }; } componentDidCatch(error, errorInfo): void { const telemetryProvider: ILoggerService = this.context; telemetryProvider.logException("App.ErrorBoundary", error, errorInfo); } render(): JSX.Element { if (this.state.hasError) { return ( <div style={{ margin: "5%", maxWidth: "900px" }}> <h1> Something went wrong in the react project.. </h1> {/* Likely want to add a support email here. */} <div> <b>Message: </b> <p>{this.state.error && this.state.error.message}</p> </div> <div> <b>Stack: </b> <p>{this.state.error && this.state.error.stack}</p> </div> </div> ); } return <div>{this.props.children}</div>; } } ```
2022/08/24
[ "https://Stackoverflow.com/questions/73467363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162217/" ]
Exact behaviour i have seen in my app. Note: Error boundaries do not catch errors for: Event handlers (learn more) Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks) Server side rendering Errors thrown in the error boundary itself (rather than its children) Most of the work we do in event handler or in our async code so as given in documentation it will not be captured. Best solution is use try catch for above use cases and console error in catch to get more info.or may be you can throw Error(your custom exception) and that will get capture in your error boundary which can be captured.
> > Has anyone come across this behavior before? Or are there any suggestions on capturing the full error with React's Error Boundary? > > > I've never come across this behaviour using [react-error-boundary](https://github.com/bvaughn/react-error-boundary/), and I see that [their implementation of the error boundary](https://github.com/bvaughn/react-error-boundary/blob/a0a370c7fe145e5cf169063eb4b7ff1a059fd84c/src/index.tsx#L69) differs from the sample code you provided. Maybe you can try [react-error-boundary](https://github.com/bvaughn/react-error-boundary/), and if it works, experiment with what they do differently in their implementation?
57,680,890
There used to be rule that apps built with beta version of Xcode can not be submitted for review. There doesn't seem to be anything in writing for Xcode 11 beta. Has the rule changed, and can we submit apps built with Xcode 11 beta?
2019/08/27
[ "https://Stackoverflow.com/questions/57680890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/917521/" ]
For TestFlight you can, however for AppStore you have to wait for `GM` version. [What is GM](https://stackoverflow.com/a/32184472)
Steps: * Archive your app * Open Organizer * Select your archive -> Show in Finder * Show Package Contents (Right Click) * Products -> Applications -> * Again Show Package Contents * Open Info.plist * Change "BuildMachineOSBuild" to one public build number, for example 18G87, build number of macOS 10.14.6 * Then you will be able to upload your app. I have been doing it a lot of times during this beta so it is confirmed that it works.
45,922
> > "I'll get yer an owl. All the kids want owls, they're dead useful, carry yer mail **an' everythin'.**" - Hagrid to harry Potter, HP1. > > > So, what other "useful" things are owls for, aside from carrying mail?
2013/12/07
[ "https://scifi.stackexchange.com/questions/45922", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/976/" ]
I can't think of any specific things mentioned within the series about owls. However, we do know Rowling pulls a lot of her magical ideas and creatures from already existing lore. If we were to assume she would attribute at least some already existing owl lore to these amazing birds than they really are quite useful in a host of ways. **First of all, witches are often associated with a "familiar."** Familiars are a bit like witch pets, but with added benefits. How the relationship works is quite mysterious, but they act very much like an animal version of an assistant in much of the lore. They might spy for their master, gather materials, act as watch and guard over a home . . . A familiar can reportedly be any animal, but cats and corvids (birds in the blackbird family) are most commonly used in this way in the lore I know. Whatever animal is used, its skills and usefulness to the witch or wizard it serves is often related to what type of animal it actually is. Since owls are associate in various cultures with death, message delivery, healing and warding off evil, and finally, with prophecy I'd suspect that as familiars their skills would related to these realms in various ways (depending on the specific owl) - but more on that further down. I'd assume in the world of HP, it is cats, toads and owls the school is willing to host and finds most useful (for whatever reason) for beginning witches and wizards. Of course, for some reason Ron is allowed his Rat even though this animal is not specified as allowed for first years on the school supplies list. We see an example of this kind of use of animals in PoA when we see Crookshanks, Hermione's cat is able to distinguish between Animagus and full animal. Crookshanks works with Harry's godfather and is especially obsessed with catching one very particular rat throughout - he never manages to communicate his knowledge to Hermione, but she is a beginner witch so maybe, Hermione hasn't come across how to better listen to her familiar yet. We do see an example of Hedwig fulfilling (or at least trying to fulfill) an assigned task when Harry tells Hedwig to keep pecking at his friends until they send a proper return answer to him in OoP when Harry is pissed because no one is telling him anything while he is still stuck in Little Whinning. Hedwig does follow through and when Harry is reunited with Ron and Hermione at #12, both kids have wounds from the bird's peckings. While this is related to postal delivery, there is definitely more there than just picking up and delivering packages. Hedwig has to judge Ron and Hermione's responses to determine they aren't good enough to bring back to Harry. Hedwig is also able to find where Sirius is hiding even though no one in the Ministry of Magic can find him in book four - that is pretty darn useful. **And** Hedwig does save Harry's life - at least once (if you don't know what I'm talking about, you'll find out in the final book). Nagini, Mrs. Norris and Fawkes are more wonderful examples of the familiar - they are certainly more than pets and have some sort of intelligence that allows them to understand their master's needs in ways beyond the average animal's. **To get more specific about owls' advantages, we have to go further outside of the books** Real-life qualities an owl possesses that may be useful to someone include, near absolute silence in flight, amazing eyesight, strong talons and an almost 360 degree ability to view the world only with moving their necks. They also hear quite well. **It seems if you need a guard (are worried about dormitory pranks etc) having an owl around might well be of great advantage.** **If you need bones of rodents for your potions**, owls automatically collect a plethora of these, as they eat the rodents, digest what they can and then regurgitate the remains that cannot be digested. That leaves you with an easily dissected pellet of fur and bones. The lore associates owls with all kinds of magical things depending on the culture in which you take a look. Greeks saw the owl as a companion to Athena so it was associated with wisdom (we still have this association today in many fairy tales and a mock version of it even in Winnie the Pooh). I think the wisdom shown by many of the owls (except Errol) in the books hearkens back to this traditional association. However, Rowling does give us the counter of Errol and shows us degrees in owl talent - Hedwig is definitely wiser than many of the owls we meet. A student preparing essays, and practicing for exams might appreciate having some extra wisdom around, it that wisdom was accessible. But really, even if they can't communicate it or share their wisdom, just having a servant that is wise (as opposed to the opposite) seems nice anyway. Some cultures believed owl parts can do different things. For example, in Brittany, boiling an owl's eggs till there was nothing left but ash, produced a magical ashen substance that, when used in a potion correctly, could improve eyesight (great for late-night study benders). In Zuni legend, babies with an owl feather in their crib would not be visited upon by evil spirits and if one hung an owl feather over the doorway into the home illness would not enter the house (Only Hermione would appreciate this one, as most of the kids liked sick days as it meant missing classes - especially if it was a potions day). Seriously though, as far as Rowling's choices go, St. Hedwig is associated with Healing and there is a spring that bears her name in Austria. Perhaps, a white owl by this name in particular, would help Harry in coping with his past by warding off some of the anger that could have over-taken him if Harry had let it (No canon - just my own romanticism which is why I use "perhaps"). In North America, many cultures associate the owl with prophecy and vision - particularly as it pertains to death (hmm. . . prophecy and death? In The Harry Potter Series?). In fact, many cultures see the bird as a god of death or at least associated with death around the world. In some, the birds even have the ability to help in **guarding against death** while in others the birds serve as a warning that death is coming. In fact, in Romania the Snowy Owl (Hedwig) was seen as the spirit of a repentant soul flying toward heaven. I don't have any clue how this might be helpful to a student, but Hagrid was the one that said they were useful - who knows, maybe he finds portents of death a useful thing. . . In any case, while Rowling doesn't delve directly, in the series into the benefits of having an owl (more than what you have already quoted), I think it is safe to say, she figured that **at the very least, owls also would help keep the rodents at bay** while they deliver the mail (making it easier for the kiddo's to keep their candy pestilence free as well).
In Order of the Phoenix chapter 3, Harry sends letters to Ron, Hermione and Sirius, asking Hedwig to “Keep pecking them till they've written decent-length answers”. Hedwig does so indeed as in chapter 4 we find Ron and Hermione has peck marks from Hedwig. So that's another useful thing about owls.
373,933
I have a set a linestrings, and I would like to know the area covered by the intersection of those lines. I don't want to merge them though. To make things clearer, here is a diagram of three multiline strings. I want to get the pink polygons. How can I achieve that? [![enter image description here](https://i.stack.imgur.com/vz6Si.png)](https://i.stack.imgur.com/vz6Si.png)
2020/09/12
[ "https://gis.stackexchange.com/questions/373933", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/169892/" ]
Do the following: * Node the linework * Polygonize the set of noded lines (this automatically discards any lines which do not form polygons) * Compute the area of the polygonal result. ``` WITH lines(geom ) AS (VALUES ('LINESTRING (170 250, 80 200, 60 110, 100 70, 145 58, 200 90, 210 150, 165 172, 130 130, 160 90, 200 70, 280 60, 310 70, 360 110, 400 180)'::geometry) ,('LINESTRING (305 6, 260 40, 250 100, 280 160, 344 145, 400 100, 405 78, 375 53)') ,('LINESTRING (540 100, 490 130, 450 90, 459 35, 530 50)') ) ,noded AS (SELECT ST_Node( ST_Collect(geom)) geom FROM lines) SELECT ST_Area( ST_Polygonize( geom)) FROM noded; ``` **Update:** If some of lines are coincident (have shared linework), then `ST_Union` should be used instead of `ST_Node ( ST_Collect`.
So, Since you decided to make the task more complicated by combining 2 situations into one here is my solution for your specific situation as shown in your picture. The source geodata is a table with the name "line" EPSG:4326. Pre-create line identifiers 1,2,3 - they will help us to select/dispose of the necessary/unless lines... Run the script as CTE: ``` WITH tbla AS (SELECT id, (ST_Dump(geom)).geom geom FROM line), tblb AS (SELECT a.id, (ST_Dump(ST_Difference(a.geom, b.geom))).geom geom FROM tbla a JOIN tbla b ON ST_Intersects(a.geom, b.geom) AND a.id<b.id), tblc AS (SELECT ST_Union(ST_Buffer(geom, 0.0001, 'side=right')) geom FROM tblb), tbld AS (SELECT DISTINCT (ST_Dump(ST_Split(a.geom, b.geom))).geom geom FROM tblc a JOIN tbla b ON ST_Intersects(a.geom, b.geom)), tble AS (SELECT DISTINCT ST_MakePolygon(ST_InteriorRingN(geom,1)) geom FROM tbld), tblf AS (SELECT a.id, (ST_Dump(ST_Difference(a.geom, b.geom))).geom geom FROM tbla a JOIN tbla b ON ST_Intersects(a.geom, b.geom) AND a.id>b.id), tblg AS (SELECT ST_Buffer(geom, 0.0001, 'side=left') geom FROM tblf UNION SELECT ST_Buffer(geom, 0.0001, 'side=right') geom FROM tblb), tblh AS (SELECT ST_Union(geom) geom FROM tblg), tbli AS (SELECT DISTINCT (ST_Dump(ST_Split(a.geom, b.geom))).geom geom FROM tblh a JOIN tbla b ON ST_Intersects(a.geom, b.geom)), tblj AS (SELECT DISTINCT ST_MakePolygon(ST_InteriorRingN(geom,1)) geom FROM tbli) SELECT ST_Union(geom) geom FROM (SELECT * FROM tble UNION SELECT * FROM tblj) foo ``` Check your result, Good luck in knowing...
1,769,485
> > Evaluation of $$\sum^{\infty}\_{n=1}\left(\frac{1}{3n+1}-\frac{1}{3n+2}\right)$$ > > > $\bf{My\; Try::}$ Here I have solved it using Definite Integration, Like $$\sum^{\infty}\_{n=1}\left(\frac{1}{3n+1}-\frac{1}{3n+2}\right)=\sum^{\infty}\_{n=1}\int\_{0}^{1}\left(x^{3n}-x^{3n+1}\right)dx$$ So we get $$ = \int\_{0}^{1}(1-x)\sum^{\infty}\_{n=1}\left(x^{3n}\right)dx = \int\_{0}^{1}\frac{(1-x)x^3}{1-x^3}dx=\int\_{0}^{1}\frac{x^3}{x^2+x+1}dx$$ So we get Sum $$ = \sum^{\infty}\_{n=1}\left(\frac{1}{3n+1}-\frac{1}{3n+2}\right) = \int\_{0}^{1}\frac{x^3}{x^2+x+1}dx = \frac{1}{18}\left(2\pi\sqrt{3}-9\right)$$ My Question is can we solve above sum without Using DEfinite Integration, If yes Then how can I solve it, Help required Thanks
2016/05/03
[ "https://math.stackexchange.com/questions/1769485", "https://math.stackexchange.com", "https://math.stackexchange.com/users/14311/" ]
An Eulerian approach. The function $\sin(\pi x)$ has its zeroes at the integers, hence the function $f(x)=\sin\left(\frac{\pi}{3}(x+2)\right)$ has its zeroes at $\{ \ldots,-8, -5,-2,1,4,7,\ldots \}$. Since the Taylor series of $f(x)$ at $x=0$ is given by: $$ f(x) = \frac{\sqrt{3}}{2}-\frac{\pi}{6}x+O(x^2) $$ it happens that: > > $$ \lim\_{n\to +\infty}\sum\_{k=-n}^{n}\frac{1}{3k+1} = -\frac{[x^1]\,f(x)}{[x^0]\,f(x)} = \color{red}{\frac{\pi}{3\sqrt{3}}} $$ > > > and the claim easily follows. We may regard $f(x)$ as *"an infinite-degree-polynomial"* since $\sin(z)$ is an entire function whose Weierstrass product has no exponential term. With the same approach you may prove the more general identity: $$ \sum\_{n\geq 0}\left(\frac{1}{kn+1}-\frac{1}{k(n+1)-1}\right)=\frac{\pi}{k}\,\cot\left(\frac{\pi}{k}\right)$$ that also follows from the reflection formula for the digamma function.
Well you could rewrite your sum as : $$\tag{1}S=-\frac 12+\frac 1{\sin(2\pi/3)}\;\sum\_{k=1}^\infty\frac {\sin(2\pi k/3)}{k}$$ (the $-\dfrac 12$ is from your sum starting at $n=1$ and not $n=0$) and use the [Fourier series for the sawtooth wave](http://mathworld.wolfram.com/FourierSeriesSawtoothWave.html) to get your result or consider $(1)$ as $-\frac 12$ plus the imaginary part of : $$\frac 1{\sin(2\pi/3)}\;\sum\_{k=1}^\infty\frac {\exp(2\pi k\,i/3)}{k}=\frac 1{\sin(2\pi/3)}\;\sum\_{k=1}^\infty\frac {\left(\exp(2\pi \,i/3)\right)^{\;k}}{k}$$ that is \begin{align} \tag{2}S&=-\frac 12-\frac 2{\sqrt{3}}\;\Im\;\log(1-\exp(2\pi \,i/3))\\ &=-\frac 12-\frac 1{\sqrt{3}\;i}\;\log\frac{1-\exp(2\pi \,i/3)}{1-\exp(-2\pi \,i/3)}\\ &=-\frac 12-\frac 1{\sqrt{3}\;i}\;\log(\exp(-\pi \,i/3))\\ \end{align} and thus $$\tag{3}\boxed{S=\frac {\pi}{3\sqrt{3}}-\frac 12}$$
1,769,485
> > Evaluation of $$\sum^{\infty}\_{n=1}\left(\frac{1}{3n+1}-\frac{1}{3n+2}\right)$$ > > > $\bf{My\; Try::}$ Here I have solved it using Definite Integration, Like $$\sum^{\infty}\_{n=1}\left(\frac{1}{3n+1}-\frac{1}{3n+2}\right)=\sum^{\infty}\_{n=1}\int\_{0}^{1}\left(x^{3n}-x^{3n+1}\right)dx$$ So we get $$ = \int\_{0}^{1}(1-x)\sum^{\infty}\_{n=1}\left(x^{3n}\right)dx = \int\_{0}^{1}\frac{(1-x)x^3}{1-x^3}dx=\int\_{0}^{1}\frac{x^3}{x^2+x+1}dx$$ So we get Sum $$ = \sum^{\infty}\_{n=1}\left(\frac{1}{3n+1}-\frac{1}{3n+2}\right) = \int\_{0}^{1}\frac{x^3}{x^2+x+1}dx = \frac{1}{18}\left(2\pi\sqrt{3}-9\right)$$ My Question is can we solve above sum without Using DEfinite Integration, If yes Then how can I solve it, Help required Thanks
2016/05/03
[ "https://math.stackexchange.com/questions/1769485", "https://math.stackexchange.com", "https://math.stackexchange.com/users/14311/" ]
An Eulerian approach. The function $\sin(\pi x)$ has its zeroes at the integers, hence the function $f(x)=\sin\left(\frac{\pi}{3}(x+2)\right)$ has its zeroes at $\{ \ldots,-8, -5,-2,1,4,7,\ldots \}$. Since the Taylor series of $f(x)$ at $x=0$ is given by: $$ f(x) = \frac{\sqrt{3}}{2}-\frac{\pi}{6}x+O(x^2) $$ it happens that: > > $$ \lim\_{n\to +\infty}\sum\_{k=-n}^{n}\frac{1}{3k+1} = -\frac{[x^1]\,f(x)}{[x^0]\,f(x)} = \color{red}{\frac{\pi}{3\sqrt{3}}} $$ > > > and the claim easily follows. We may regard $f(x)$ as *"an infinite-degree-polynomial"* since $\sin(z)$ is an entire function whose Weierstrass product has no exponential term. With the same approach you may prove the more general identity: $$ \sum\_{n\geq 0}\left(\frac{1}{kn+1}-\frac{1}{k(n+1)-1}\right)=\frac{\pi}{k}\,\cot\left(\frac{\pi}{k}\right)$$ that also follows from the reflection formula for the digamma function.
$\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle} \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace} \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack} \newcommand{\dd}{{\rm d}} \newcommand{\ds}[1]{\displaystyle{#1}} \newcommand{\dsc}[1]{\displaystyle{\color{red}{#1}}} \newcommand{\expo}[1]{\,{\rm e}^{#1}\,} \newcommand{\half}{{1 \over 2}} \newcommand{\ic}{{\rm i}} \newcommand{\imp}{\Longrightarrow} \newcommand{\Li}[1]{\,{\rm Li}\_{#1}} \newcommand{\pars}[1]{\left(\, #1 \,\right)} \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}} \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,} \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}} \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$ \begin{align} &\bbox[10px,#ffd]{\sum\_{n = 1}^{\infty}\pars{{1 \over 3n + 1} - {1 \over 3n + 2}}} = \sum\_{n = 1}^{\infty}{1 \over \pars{3n + 2}\pars{3n + 1}} \\[5mm] = &\ \sum\_{n = 0}^{\infty}{1 \over \pars{3n + 5}\pars{3n + 4}} = {1 \over 9}\sum\_{n = 0}^{\infty}{1 \over \pars{n + 5/3}\pars{n + 4/3}} \\[5mm] = &\ {1 \over 9}\,{\Psi\pars{5/3} - \Psi\pars{4/3} \over 5/3 - 4/3} = {1 \over 3}\bracks{\Psi\pars{{2 \over 3}} + {1 \over 2/3} - \Psi\pars{{1 \over 3}} - {1 \over 1/3}} \\[5mm] & = -\,{1 \over 2} + {1 \over 3}\ \underbrace{\bracks{\Psi\pars{{2 \over 3}} - \Psi\pars{{1 \over 3}}}}\_{\ds{\pi\cot\pars{\pi\,{1 \over 3}} = {\root{3} \over 3}\,\pi}}\quad\pars{~Euler\ Reflection\ Formula~} \\[5mm] & = \fbox{$\ds{{\root{3} \over 9}\,\pi - \half}$} \approx 0.1046 \end{align} $\Psi\pars{z}$ is the digamma function where we used its recurrence relation and the Euler identity.
290,196
For topological spaces $X,Y$ let $\text{Cont}(X,Y)$ be the collection of continuous functions $f:X\to Y.$ We endow $\text{Cont}(X,Y)$ with the topology inherited from the product topology on $Y^X.$ Are there spaces $X,Y$ such that $X$ has more than one point and $Y\not\cong\mathbb{R}$ such that $\mathbb{R}\cong\text{Cont}(X,Y)$?
2018/01/08
[ "https://mathoverflow.net/questions/290196", "https://mathoverflow.net", "https://mathoverflow.net/users/8628/" ]
I must admit that I hesitated answering this question, but here it is. The answer is "no". Assume there exist topological spaces $X$ and $Y$ such that $C(X,Y)\simeq \mathbb{R}$ and $Y\not\simeq\mathbb{R}$. Identifying $C(X,Y)$ with $\mathbb{R}$ and $Y$ with the constant functions in $Y^X$ we consider $Y$ as a closed subsapce of $\mathbb{R}$. Considering the surjection $\mathbb{R} \to C(X,Y)\to C(\{x\},Y) \to Y$, we see that $Y$ is connected. Thus $Y\subset\mathbb{R}$ is a closed convex subset. As $Y\not\simeq \mathbb{R}$ there must exist an extreme point $y\in Y$. Note that $C(X,Y)$ is a convex subset of $C(X,\mathbb{R})$ and the constant function $y$ is an extreme point of it. It follows that $C(X,Y)-\{y\}$ is also convex, hence contractible. But $C(X,Y)-\{y\}$ is homeomorphic to $\mathbb{R}$ minus a point. This is a contradiction.
Following the answer of Uri Bader, we can show that $Y$ is a retract of the real line, so can be identified with a closed convex subset of $\mathbb R$. Without loss of generality we can assume that $0,1\in Y$ and hence $[0,1]\subset Y$. It follows that the function $C(X,Y)$ is a convex subset of $Y^X\subset \mathbb R^X$ and $C(X,[0,1])\subset C(X,Y)$. The assumption $Y\not\cong\mathbb R\cong C(X,Y)$ implies that $C(X,Y)$ contains a non-constant function $f$. Consider the constant functions $\mathbf 0:X\to\{0\}\subset Y$ and $\mathbf 1:X\to\{1\}\subset Y$ and observe that the set $T=\{\mathbf 0,\mathbf 1,f\}\subset C(X,Y)\subset Y^X\subset\mathbb R^X$ is affinely independent and its convex hull $conv(T)\subset C(X,Y)$ is homeomorphic to the 2-dimensional symplex, which cannot be contained in the real line $\mathbb R\cong C(X,Y)$. This contradiction completes the proof. The negative answer can also be deduced from the following theorem. We recall that a topological space $X$ is *functionally Hausdorff* if for any distinct points $x,y\in X$ there exists a continuous function $f:X\to\mathbb R$ such that $f(x)\ne f(y)$. **Theorem.** If for non-empty topological spaces $X,Y$ the function space $C(X,Y)$ is functionally Hausdorff and path-connected, then either $C(X,Y)$ is homeomorphic to $Y^n$ for some $n\in\mathbb N$ or $C(X,Y)$ contains a topological copy of the Hilbert cube. *Proof.* The space $Y\cong C(\{x\},Y)$ is functionally Hausdorff and path-connected, being a retract of the functionally Hausdorff path-connected space $C(X,Y)$. If $Y$ is a singleton, then $C(X,Y)\cong Y^1$ is a singleton, too. So, we assume that $Y$ contains more than one point. In this case $Y$ contains a subspace $I$, homeomorphic to the closed interval $[0,1]$. Consider the canonical map $\delta:X\to Y^{C(X,Y)}$, $\delta:x\mapsto (f(x))\_{f\in C(X,Y)}$. If the image $\delta(X)$ is finite of cardinality $n$, then $C(X,Y)$ is homeomorphic to $Y^n$ (since each function $f\in C(X,Y)$ is constant on each set $\delta^{-1}(y)$, $y\in \delta(X)$). So, we assume that the set $\delta(X)$ is infinite. Taking into account that the space $Y^{C(X,Y)}$ is functionally Hausdorff, we can construct a continuous map $g:Y^{C(x,Y)}\to I$ such that the image $Z=g(\delta(X))$ is infinite. The surjective continuous map $p:=g\circ\delta:X\to Z$ induces a continuous injective map $p^\*:C(Z,I)\to C(X,I)$, $p^\*:f\mapsto f\circ p$. It is easy to see that the function space $C(Z,I)\subset I^Z$ contains a topological copy $Q$ of the Hilbert cube $I^\omega$. Then $p^\*(Q)$ is a topological copy of the Hilbert cube in $C(X,I)\subset C(X,Y)$.
785,038
I have a file which looks like this: ``` 1 3 4 1 4 3 1 2 ``` How can I find the total of this (i.e. 1+3+4+1+4+3+1+2 = 19)?
2016/06/09
[ "https://askubuntu.com/questions/785038", "https://askubuntu.com", "https://askubuntu.com/users/186134/" ]
### Use `numsum` from the package `num-utils`! (You may need to `sudo apt-get install num-utils`) The command `numsum` does just what you need by default; ``` $ numsum file.txt 19 ``` Reading the test numbers line by line from `stdin`: ``` $ printf ' 1 3 4 1 4 3 1 2' | numsum 19 ``` Or reading from one line: ``` $ printf '1 3 4 1 4 3 1 2' | numsum -r 19 ``` ### More utilities The package contains some other utilities for number processing that deserve to be more well known: ``` numaverage - find the average of the numbers, or the mode or median numbound - find minimum of maximum of all lines numgrep - to find numbers matching ranges or sets numinterval - roughly like the first derivative numnormalize - normalize numbers to an interval, like 0-1 numrandom - random numbers from ranges or sets, eg odd. numrange - similar to seq numround - round numbers up, down or to nearest ``` and a more general calculator command `numprocess`,
A simple approach is to use a built-in feature of your shell: ``` SUM=0; while read N; do SUM=$((SUM+N)); done </path/to/file echo $SUM ``` This reads your file linewise, sums up and prints the result. If you want to use a pipe and only use the 1st row, it works like this: ``` SUM=0 your_command | while read -r LINE; do for N in $LINE; do break; done; SUM=$((SUM+N)); done echo $SUM ``` Getting the first element is done like this: ``` LIST="foo bar baz" for OBJ in $LIST; do break; done echo $OBJ foo ```
785,038
I have a file which looks like this: ``` 1 3 4 1 4 3 1 2 ``` How can I find the total of this (i.e. 1+3+4+1+4+3+1+2 = 19)?
2016/06/09
[ "https://askubuntu.com/questions/785038", "https://askubuntu.com", "https://askubuntu.com/users/186134/" ]
A simple approach is to use a built-in feature of your shell: ``` SUM=0; while read N; do SUM=$((SUM+N)); done </path/to/file echo $SUM ``` This reads your file linewise, sums up and prints the result. If you want to use a pipe and only use the 1st row, it works like this: ``` SUM=0 your_command | while read -r LINE; do for N in $LINE; do break; done; SUM=$((SUM+N)); done echo $SUM ``` Getting the first element is done like this: ``` LIST="foo bar baz" for OBJ in $LIST; do break; done echo $OBJ foo ```
This is a fairly simple use of `bash` scripting. ``` SUM=0; for line in `cat file.txt`; do SUM=$((SUM + line)); done ```
785,038
I have a file which looks like this: ``` 1 3 4 1 4 3 1 2 ``` How can I find the total of this (i.e. 1+3+4+1+4+3+1+2 = 19)?
2016/06/09
[ "https://askubuntu.com/questions/785038", "https://askubuntu.com", "https://askubuntu.com/users/186134/" ]
`bc` with a little help from `paste` to get the lines in a single one with `+` as the separator: ``` paste -sd+ file.txt | bc ``` To use the output of `grep` (or any other command) instead a static file, pass the `grep`'s STDOUT to the STDIN of `paste`: ``` grep .... | paste -sd+ | bc ``` **Example:** ``` % cat file.txt 1 3 4 1 4 3 1 2 % paste -sd+ file.txt | bc 19 % grep . file.txt | paste -sd+ | bc 19 ``` --- If you must use `bash`, then you can use an array to save the file contents and then iterate over the elements or you can read the file line by line and do the sum for each line, the second approach would be more efficient: ``` $ time { nums=$(<file.txt); for i in ${nums[@]}; do (( sum+=i )); done; echo $sum ;} 19 real 0m0.002s user 0m0.000s sys 0m0.000s $ time { while read i; do (( sum+=i )); done <file.txt; echo $sum ;} 19 real 0m0.000s user 0m0.000s sys 0m0.000s ```
You can use `awk`, a native linux application usefull to scanning and processing files with a pattern per line. For your question, this will produce what you want: ``` awk 'BEGIN { sum=0 } { sum+=$1 } END {print sum }' file.txt ``` Pipes are also accept: ``` cat file.txt | awk 'BEGIN { sum=0 } { sum+=$1 } END {print sum }' ```
785,038
I have a file which looks like this: ``` 1 3 4 1 4 3 1 2 ``` How can I find the total of this (i.e. 1+3+4+1+4+3+1+2 = 19)?
2016/06/09
[ "https://askubuntu.com/questions/785038", "https://askubuntu.com", "https://askubuntu.com/users/186134/" ]
You could use awk, too. To count the total number of lines in **\*.txt** files that contain the word "hello": ``` grep -ch 'hello' *.txt | awk '{n += $1}; END{print n}' ``` To simply sum the numbers in a file: ``` awk '{n += $1}; END{print n}' file.txt ```
### Use `numsum` from the package `num-utils`! (You may need to `sudo apt-get install num-utils`) The command `numsum` does just what you need by default; ``` $ numsum file.txt 19 ``` Reading the test numbers line by line from `stdin`: ``` $ printf ' 1 3 4 1 4 3 1 2' | numsum 19 ``` Or reading from one line: ``` $ printf '1 3 4 1 4 3 1 2' | numsum -r 19 ``` ### More utilities The package contains some other utilities for number processing that deserve to be more well known: ``` numaverage - find the average of the numbers, or the mode or median numbound - find minimum of maximum of all lines numgrep - to find numbers matching ranges or sets numinterval - roughly like the first derivative numnormalize - normalize numbers to an interval, like 0-1 numrandom - random numbers from ranges or sets, eg odd. numrange - similar to seq numround - round numbers up, down or to nearest ``` and a more general calculator command `numprocess`,
785,038
I have a file which looks like this: ``` 1 3 4 1 4 3 1 2 ``` How can I find the total of this (i.e. 1+3+4+1+4+3+1+2 = 19)?
2016/06/09
[ "https://askubuntu.com/questions/785038", "https://askubuntu.com", "https://askubuntu.com/users/186134/" ]
### Use `numsum` from the package `num-utils`! (You may need to `sudo apt-get install num-utils`) The command `numsum` does just what you need by default; ``` $ numsum file.txt 19 ``` Reading the test numbers line by line from `stdin`: ``` $ printf ' 1 3 4 1 4 3 1 2' | numsum 19 ``` Or reading from one line: ``` $ printf '1 3 4 1 4 3 1 2' | numsum -r 19 ``` ### More utilities The package contains some other utilities for number processing that deserve to be more well known: ``` numaverage - find the average of the numbers, or the mode or median numbound - find minimum of maximum of all lines numgrep - to find numbers matching ranges or sets numinterval - roughly like the first derivative numnormalize - normalize numbers to an interval, like 0-1 numrandom - random numbers from ranges or sets, eg odd. numrange - similar to seq numround - round numbers up, down or to nearest ``` and a more general calculator command `numprocess`,
You can use `awk`, a native linux application usefull to scanning and processing files with a pattern per line. For your question, this will produce what you want: ``` awk 'BEGIN { sum=0 } { sum+=$1 } END {print sum }' file.txt ``` Pipes are also accept: ``` cat file.txt | awk 'BEGIN { sum=0 } { sum+=$1 } END {print sum }' ```
785,038
I have a file which looks like this: ``` 1 3 4 1 4 3 1 2 ``` How can I find the total of this (i.e. 1+3+4+1+4+3+1+2 = 19)?
2016/06/09
[ "https://askubuntu.com/questions/785038", "https://askubuntu.com", "https://askubuntu.com/users/186134/" ]
`bc` with a little help from `paste` to get the lines in a single one with `+` as the separator: ``` paste -sd+ file.txt | bc ``` To use the output of `grep` (or any other command) instead a static file, pass the `grep`'s STDOUT to the STDIN of `paste`: ``` grep .... | paste -sd+ | bc ``` **Example:** ``` % cat file.txt 1 3 4 1 4 3 1 2 % paste -sd+ file.txt | bc 19 % grep . file.txt | paste -sd+ | bc 19 ``` --- If you must use `bash`, then you can use an array to save the file contents and then iterate over the elements or you can read the file line by line and do the sum for each line, the second approach would be more efficient: ``` $ time { nums=$(<file.txt); for i in ${nums[@]}; do (( sum+=i )); done; echo $sum ;} 19 real 0m0.002s user 0m0.000s sys 0m0.000s $ time { while read i; do (( sum+=i )); done <file.txt; echo $sum ;} 19 real 0m0.000s user 0m0.000s sys 0m0.000s ```
A simple approach is to use a built-in feature of your shell: ``` SUM=0; while read N; do SUM=$((SUM+N)); done </path/to/file echo $SUM ``` This reads your file linewise, sums up and prints the result. If you want to use a pipe and only use the 1st row, it works like this: ``` SUM=0 your_command | while read -r LINE; do for N in $LINE; do break; done; SUM=$((SUM+N)); done echo $SUM ``` Getting the first element is done like this: ``` LIST="foo bar baz" for OBJ in $LIST; do break; done echo $OBJ foo ```
785,038
I have a file which looks like this: ``` 1 3 4 1 4 3 1 2 ``` How can I find the total of this (i.e. 1+3+4+1+4+3+1+2 = 19)?
2016/06/09
[ "https://askubuntu.com/questions/785038", "https://askubuntu.com", "https://askubuntu.com/users/186134/" ]
You could use awk, too. To count the total number of lines in **\*.txt** files that contain the word "hello": ``` grep -ch 'hello' *.txt | awk '{n += $1}; END{print n}' ``` To simply sum the numbers in a file: ``` awk '{n += $1}; END{print n}' file.txt ```
Perl solution: ``` $ perl -lnae '$c+=$_;END{print $c}' input.txt 19 ``` The above can sum all numbers across multiple files: ``` $ perl -lnae '$c+=$_;END{print $c}' input.txt input2.txt 34 ``` For multiple files given on command-line where we want to see sum of numbers in individual file we can do this: ``` $ perl -lnae '$c+=$_;if(eof){printf("%d %s\n",$c,$ARGV);$c=0}' input.txt input2.txt 19 input.txt 15 input2.txt ```
785,038
I have a file which looks like this: ``` 1 3 4 1 4 3 1 2 ``` How can I find the total of this (i.e. 1+3+4+1+4+3+1+2 = 19)?
2016/06/09
[ "https://askubuntu.com/questions/785038", "https://askubuntu.com", "https://askubuntu.com/users/186134/" ]
You could use awk, too. To count the total number of lines in **\*.txt** files that contain the word "hello": ``` grep -ch 'hello' *.txt | awk '{n += $1}; END{print n}' ``` To simply sum the numbers in a file: ``` awk '{n += $1}; END{print n}' file.txt ```
A simple approach is to use a built-in feature of your shell: ``` SUM=0; while read N; do SUM=$((SUM+N)); done </path/to/file echo $SUM ``` This reads your file linewise, sums up and prints the result. If you want to use a pipe and only use the 1st row, it works like this: ``` SUM=0 your_command | while read -r LINE; do for N in $LINE; do break; done; SUM=$((SUM+N)); done echo $SUM ``` Getting the first element is done like this: ``` LIST="foo bar baz" for OBJ in $LIST; do break; done echo $OBJ foo ```
785,038
I have a file which looks like this: ``` 1 3 4 1 4 3 1 2 ``` How can I find the total of this (i.e. 1+3+4+1+4+3+1+2 = 19)?
2016/06/09
[ "https://askubuntu.com/questions/785038", "https://askubuntu.com", "https://askubuntu.com/users/186134/" ]
You could use awk, too. To count the total number of lines in **\*.txt** files that contain the word "hello": ``` grep -ch 'hello' *.txt | awk '{n += $1}; END{print n}' ``` To simply sum the numbers in a file: ``` awk '{n += $1}; END{print n}' file.txt ```
You can use `awk`, a native linux application usefull to scanning and processing files with a pattern per line. For your question, this will produce what you want: ``` awk 'BEGIN { sum=0 } { sum+=$1 } END {print sum }' file.txt ``` Pipes are also accept: ``` cat file.txt | awk 'BEGIN { sum=0 } { sum+=$1 } END {print sum }' ```
785,038
I have a file which looks like this: ``` 1 3 4 1 4 3 1 2 ``` How can I find the total of this (i.e. 1+3+4+1+4+3+1+2 = 19)?
2016/06/09
[ "https://askubuntu.com/questions/785038", "https://askubuntu.com", "https://askubuntu.com/users/186134/" ]
`bc` with a little help from `paste` to get the lines in a single one with `+` as the separator: ``` paste -sd+ file.txt | bc ``` To use the output of `grep` (or any other command) instead a static file, pass the `grep`'s STDOUT to the STDIN of `paste`: ``` grep .... | paste -sd+ | bc ``` **Example:** ``` % cat file.txt 1 3 4 1 4 3 1 2 % paste -sd+ file.txt | bc 19 % grep . file.txt | paste -sd+ | bc 19 ``` --- If you must use `bash`, then you can use an array to save the file contents and then iterate over the elements or you can read the file line by line and do the sum for each line, the second approach would be more efficient: ``` $ time { nums=$(<file.txt); for i in ${nums[@]}; do (( sum+=i )); done; echo $sum ;} 19 real 0m0.002s user 0m0.000s sys 0m0.000s $ time { while read i; do (( sum+=i )); done <file.txt; echo $sum ;} 19 real 0m0.000s user 0m0.000s sys 0m0.000s ```
This is a fairly simple use of `bash` scripting. ``` SUM=0; for line in `cat file.txt`; do SUM=$((SUM + line)); done ```
23,767,095
I have a new file that I created that has a list of all directories that have a particular file: ``` $ find . -name "bun.biscuts" > TREE.temp ``` This writes all of the correct info I need to the new temp file. I am having trouble writing a bash script using `sed` to replace emails in the `TREE.temp` file. This is what I have so far: ``` #!/bin/bash #set -x echo Start! for bun.biscuts in (TREE.temp) do sed -i 's/EMAIL1/EMAIL2/g'; done ``` Any help would be amazing!
2014/05/20
[ "https://Stackoverflow.com/questions/23767095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3653572/" ]
The usual approach is just to have a quit command at the bottom of the menu.
From the Beginning of Time, Apple has enforced the Human Interface Guidelines. A way for the user to quit the app is required. After all, we don’t want OSX to look like some webpages with popups you can’t get rid of.
8,567,184
So I have several datagridviews that we had set to `FullRowSelect`. The users are now requesting the ability to select on single cells for copy functions. I set the `DataGridView` to `CellSelect` but when I run the app, when I click on the Row Header it doesn't highlight the Full Row, only the first column. I tried using the `RowHeaderMouseClick` with a `CellMouseClick` to get the selection mode to shift but in order for `RowHeaderMouseClick` to select it fully I am having to click on the row header multiple times. ``` private void DataGridView_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; } ``` How can I easily or not so easily switch back and forth between `CellSelect` and `FullRowSelect` depending on what they have selected on the grid?
2011/12/19
[ "https://Stackoverflow.com/questions/8567184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/426671/" ]
If I understand you, you want to be able to select single cells but also easily select a full row? If that's the case, set SelectionMode to `RowHeaderSelect`.
``` DataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; ``` 1- You are actually using the DataGridView Structure, and not your object DataGridView. 2- The SelectionMode shouldn't be modified every time the user click a Row, but in your Constructor of your program. Example ``` public MyForm() { dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; } ```
8,567,184
So I have several datagridviews that we had set to `FullRowSelect`. The users are now requesting the ability to select on single cells for copy functions. I set the `DataGridView` to `CellSelect` but when I run the app, when I click on the Row Header it doesn't highlight the Full Row, only the first column. I tried using the `RowHeaderMouseClick` with a `CellMouseClick` to get the selection mode to shift but in order for `RowHeaderMouseClick` to select it fully I am having to click on the row header multiple times. ``` private void DataGridView_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; } ``` How can I easily or not so easily switch back and forth between `CellSelect` and `FullRowSelect` depending on what they have selected on the grid?
2011/12/19
[ "https://Stackoverflow.com/questions/8567184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/426671/" ]
If I understand you, you want to be able to select single cells but also easily select a full row? If that's the case, set SelectionMode to `RowHeaderSelect`.
add this one line code. ``` this.dataGridView1.SelectionMode = isTrue == true ? DataGridViewSelectionMode.FullRowSelect : DataGridViewSelectionMode.RowHeaderSelect; ```
13,490,150
I used `DateTime` to get the diff of two dates. Directly from the PHP documentation example: ``` $date1 = new DateTime('2012/03/15'); $date2 = new DateTime('2012/6/9'); $interval = $date1->diff($date2,true); $days = $interval->format('%R%a days'); ``` This will result in **`+86 days`**, I wonder where can I get the reference for those `%R%a` I don't know what they mean, but I just know by seeing that `%R = +` while `%a is number of days`. Second, now by having the value **`86`** I can have at least a variable that I can use to tell that `$date1` and `$date2` is not within the length of 3 months (3 months is at least 90 days). I can simply use an `if-else` for this, however for precision, is there another way (built-in PHP functions or library) to determine that the value I have is within the period of 3 months?
2012/11/21
[ "https://Stackoverflow.com/questions/13490150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1302954/" ]
You can find it [in the documentation](http://www.php.net/manual/en/dateinterval.format.php) as well: ``` % Literal % % Y Years, numeric, at least 2 digits with leading 0 01, 03 y Years, numeric 1, 3 M Months, numeric, at least 2 digits with leading 0 01, 03, 12 m Months, numeric 1, 3, 12 D Days, numeric, at least 2 digits with leading 0 01, 03, 31 d Days, numeric 1, 3, 31 a Total number of days as a result of a DateTime:diff() or (unknown) otherwise 4, 18, 8123 H Hours, numeric, at least 2 digits with leading 0 01, 03, 23 h Hours, numeric 1, 3, 23 I Minutes, numeric, at least 2 digits with leading 0 01, 03, 59 i Minutes, numeric 1, 3, 59 S Seconds, numeric, at least 2 digits with leading 0 01, 03, 57 s Seconds, numeric 1, 3, 57 R Sign "-" when negative, "+" when positive -, + r Sign "-" when negative, empty when positive -, ```
<http://www.php.net/manual/en/dateinterval.format.php> for the docs ``` $months = 3; if ($interval->format('%m') < $months) { echo "Less than $months months"; } ```
13,490,150
I used `DateTime` to get the diff of two dates. Directly from the PHP documentation example: ``` $date1 = new DateTime('2012/03/15'); $date2 = new DateTime('2012/6/9'); $interval = $date1->diff($date2,true); $days = $interval->format('%R%a days'); ``` This will result in **`+86 days`**, I wonder where can I get the reference for those `%R%a` I don't know what they mean, but I just know by seeing that `%R = +` while `%a is number of days`. Second, now by having the value **`86`** I can have at least a variable that I can use to tell that `$date1` and `$date2` is not within the length of 3 months (3 months is at least 90 days). I can simply use an `if-else` for this, however for precision, is there another way (built-in PHP functions or library) to determine that the value I have is within the period of 3 months?
2012/11/21
[ "https://Stackoverflow.com/questions/13490150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1302954/" ]
1. Check the documentation for [`DateTime::diff`](http://php.net/manual/en/datetime.diff.php). 2. See that it returns a `DateInterval`, click link to [its documentation](http://php.net/manual/en/class.dateinterval.php). 3. Read [documentation for its `format` method](http://php.net/manual/en/dateinterval.format.php). Use `if ($interval->format('%m') > 3)` to test if it's over three months. Notice that this is only the months portion of the interval, e.g. "3" of "2 years, 3 months". Take the years into account as well. You should not just use days for this, since there's no constant number of days in a month. 90 days and 3 months are not the same thing.
You can find it [in the documentation](http://www.php.net/manual/en/dateinterval.format.php) as well: ``` % Literal % % Y Years, numeric, at least 2 digits with leading 0 01, 03 y Years, numeric 1, 3 M Months, numeric, at least 2 digits with leading 0 01, 03, 12 m Months, numeric 1, 3, 12 D Days, numeric, at least 2 digits with leading 0 01, 03, 31 d Days, numeric 1, 3, 31 a Total number of days as a result of a DateTime:diff() or (unknown) otherwise 4, 18, 8123 H Hours, numeric, at least 2 digits with leading 0 01, 03, 23 h Hours, numeric 1, 3, 23 I Minutes, numeric, at least 2 digits with leading 0 01, 03, 59 i Minutes, numeric 1, 3, 59 S Seconds, numeric, at least 2 digits with leading 0 01, 03, 57 s Seconds, numeric 1, 3, 57 R Sign "-" when negative, "+" when positive -, + r Sign "-" when negative, empty when positive -, ```
13,490,150
I used `DateTime` to get the diff of two dates. Directly from the PHP documentation example: ``` $date1 = new DateTime('2012/03/15'); $date2 = new DateTime('2012/6/9'); $interval = $date1->diff($date2,true); $days = $interval->format('%R%a days'); ``` This will result in **`+86 days`**, I wonder where can I get the reference for those `%R%a` I don't know what they mean, but I just know by seeing that `%R = +` while `%a is number of days`. Second, now by having the value **`86`** I can have at least a variable that I can use to tell that `$date1` and `$date2` is not within the length of 3 months (3 months is at least 90 days). I can simply use an `if-else` for this, however for precision, is there another way (built-in PHP functions or library) to determine that the value I have is within the period of 3 months?
2012/11/21
[ "https://Stackoverflow.com/questions/13490150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1302954/" ]
1. Check the documentation for [`DateTime::diff`](http://php.net/manual/en/datetime.diff.php). 2. See that it returns a `DateInterval`, click link to [its documentation](http://php.net/manual/en/class.dateinterval.php). 3. Read [documentation for its `format` method](http://php.net/manual/en/dateinterval.format.php). Use `if ($interval->format('%m') > 3)` to test if it's over three months. Notice that this is only the months portion of the interval, e.g. "3" of "2 years, 3 months". Take the years into account as well. You should not just use days for this, since there's no constant number of days in a month. 90 days and 3 months are not the same thing.
<http://www.php.net/manual/en/dateinterval.format.php> for the docs ``` $months = 3; if ($interval->format('%m') < $months) { echo "Less than $months months"; } ```
19,311,135
I'm trying save entity to db using dbContext. ``` Type entityType = Type.GetType("class"); object ob = db.Set(entityType).Create(entityType); ob.GetMethod("set_Id").Invoke(ob, new object[] { newId }); //...other set code... db.Set(entityType).Add(ob); db.SaveChanges(); -- here fires exception ``` But after SaveChanges fire the Exception > > "Cannot insert explicit value for identity column in table 'TableName' > when IDENTITY\_INSERT is set to OFF". > > > In the profiler I see the standard insert batch with the id I set. How can I add entity object to db with identity insert ON or how can I just save the new entityObject?
2013/10/11
[ "https://Stackoverflow.com/questions/19311135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971785/" ]
Entity Framework assumes that integer primary keys are database generated. If you don't want that you have to turn it off with the attribute `HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)` or calling `Property(e => e.EventID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)` using the Fluent API. You now have a problem because this only works first time around. You will have to drop the table or use one of the other options here [how to switch identity on/off in entity framework code first migrations](https://stackoverflow.com/a/18917348/150342)
It seems you have a table definition that says the database should inserts ID's and not allow the application to do this. At the same time an entity-framework layout that tries to insert values for id's. You can allow the application to insert ID's by using this: <http://technet.microsoft.com/en-us/library/aa259221(v=sql.80).aspx> to allow it. The question is do you really want to allow that applications can choose their own IDs? Or do you want to let the database decide? In this case you should check the properties in your dbml file. The column Id should have a property "Auto Generated Value". It has to be set to True.
261,941
I'm using Drupal 7 with i18n modules. I have 6 languages on my site. The relative paths are working fine except for: the relative paths in blocks for the languages other than the default language. On my front page I have several blocks. If I add the relative path in a block on my English (default language) front page (www.example.com) it works. If I add a relative path in a block to my French front page (www.example.com/fr) ``` <a href="page-in-french">Link in block on the French page</a> ``` Then my expectation was to get to this page www.example.com/fr/page-in-french but instead I get to the page: www.example.com/page-in-french which obviously does not exist. I know that I can manually add in the relative path the language code ``` <a href="fr/page-in-french">Link in block on the French page</a> ``` but since the URL that I'm accessing is www.example.com/fr , then a relative path should not contain the "fr/" since it is already in the URL. How can I set the relative path to just "page-in-french"? Thank you
2018/05/19
[ "https://drupal.stackexchange.com/questions/261941", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/18096/" ]
You could try using [Twig Tweak module](https://www.drupal.org/project/twig_tweak) `{{ drupal_entity('paragraph', NUMERIC_ID, VIEWMODE_MACHINE_NAME) }}` Also see the [cheat sheet](https://www.drupal.org/docs/8/modules/twig-tweak/cheat-sheet-8x-2x) for Twig tweak, it really is a great module for frontend work!
This question is linked from this [question](https://drupal.stackexchange.com/questions/263451/how-to-print-render-nested-paragraph-values-to-twig-template/263497). Since that question is closed, I'll answer here since I recently found something that's working (in case someone else is directed here and needs help). My setup is like this: Paragraph field > Paragraph Field > Some Field I wanted to get the value of 'Some Field'. Here's how I did that: ``` content.field_paragraph.0['#paragraph'].getFields()['field_content_some_field'].getValue()[0]['value'] ``` This code goes in the paragraph--some-paragraph-name.html.twig. Hope this is able to help someone.
55,674,999
I'm building a trade backtest app and have managed to get the data in jupyter notebook using pdblp. However, the data is multi-level and I don't know enough about data frames to properly unpack it. What I need is to be able to access **df[PX\_LAST]** which should be the same regardless of the stock used. It is not that simple as df.keys() produces ``` MultiIndex(levels=[['AHT LN Equity'], ['BEST_PE_RATIO', 'PX_LAST']], labels=[[0, 0], [1, 0]], names=['ticker', 'field']) ``` I've tried > > df = pd.DataFrame(df.to\_records()) > > > but this results in messy titles and I have had issues changing the name. ``` import pdblp con = pdblp.BCon(debug=False, port=8194, timeout=5000) con.start() df = con.bdh('AHT LN Equity', ['PX_LAST', 'BEST_PE_RATIO'], '20190102', '20190331') ``` I've tried > > df1=df.unstack(level=1).reset\_index() > > > which didn't work, and ``` import pandas as pd import numpy as np df = pd.DataFrame(df.to_records()) ``` the latter partially worked but is tricky as I want to rename the column to something without the ticker and also having issues with the apostrophes I guess as rename failed. ``` df.rename(columns={'('AHT LN Equity', 'PX_LAST')': 'Close'}, inplace=True) File "<ipython-input-37-7677eac9ff45>", line 2 df.rename(columns={'('AHT LN Equity', 'PX_LAST')': 'Close'}, inplace=True) ^ SyntaxError: invalid syntax ``` Any kind of help is appreciated.
2019/04/14
[ "https://Stackoverflow.com/questions/55674999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11358797/" ]
Few examples you can play around with [`xbbg`](https://xbbg.readthedocs.io): ``` In [1]: from xbbg import blp In [2]: df = blp.bdh(['AHT LN Equity', 'AGK LN Equity'], ['PX_LAST', 'BEST_PE_RATIO'], start_date='20190102', end_date='20190331') In [3]: df.tail() Out[3]: ticker AHT LN Equity AGK LN Equity field PX_LAST BEST_PE_RATIO PX_LAST BEST_PE_RATIO 2019-03-25 1,827.50 11.09 749.96 14.62 2019-03-26 1,805.50 10.96 755.63 14.73 2019-03-27 1,809.00 10.98 751.52 14.71 2019-03-28 1,827.50 11.09 753.48 14.74 2019-03-29 1,852.50 11.24 770.71 15.08 ``` To quote `PX_LAST`, you can: ``` In [4]: df.xs('PX_LAST', axis=1, level=1).tail() Out[4]: ticker AHT LN Equity AGK LN Equity 2019-03-25 1,827.50 749.96 2019-03-26 1,805.50 755.63 2019-03-27 1,809.00 751.52 2019-03-28 1,827.50 753.48 2019-03-29 1,852.50 770.71 ``` To quote data for `AHT LN Equity`, you can either: ``` In [5]: df['AHT LN Equity'].tail() Out[5]: field PX_LAST BEST_PE_RATIO 2019-03-25 1,827.50 11.09 2019-03-26 1,805.50 10.96 2019-03-27 1,809.00 10.98 2019-03-28 1,827.50 11.09 2019-03-29 1,852.50 11.24 ``` or ``` In [6]: df.loc[:, 'AHT LN Equity'].tail() Out[6]: field PX_LAST BEST_PE_RATIO 2019-03-25 1,827.50 11.09 2019-03-26 1,805.50 10.96 2019-03-27 1,809.00 10.98 2019-03-28 1,827.50 11.09 2019-03-29 1,852.50 11.24 ``` To quote `BEST_PE_RATIO` of `AHT LN Equity`, you can either (notice the minor differences in the name of the `Series`): ``` In [7]: df['AHT LN Equity']['BEST_PE_RATIO'].tail() Out[7]: 2019-03-25 11.09 2019-03-26 10.96 2019-03-27 10.98 2019-03-28 11.09 2019-03-29 11.24 Name: BEST_PE_RATIO, dtype: float64 ``` or ``` In [8]: df[('AHT LN Equity', 'BEST_PE_RATIO')].tail() Out[8]: 2019-03-25 11.09 2019-03-26 10.96 2019-03-27 10.98 2019-03-28 11.09 2019-03-29 11.24 Name: (AHT LN Equity, BEST_PE_RATIO), dtype: float64 ```
Use [pd.IndexSlice](https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.IndexSlice.html) when trying to slice a column or index in a multiindex, pd.IndexSlice is very efficient. ``` # set idx for ease of use. idx = pd.IndexSlice ``` The slice using .loc ``` # if you are slicing in the column df.loc[:, idx[:,'PX_LAST']] # if you have more than one item in level 1 df.loc[:, idx[:,['BEST_PE_RATIO','PX_LAST']] # if you wish to add slice up one level df.loc[:, idx['AHT LN Equity','BEST_PE_RATIO']] # if you are slicing in the index df.loc[idx[:,'SOME_INDEX'],:] # if you are slicing in both index and column df.loc[idx[:,'SOME_INDEX'], idx[:,'PX_LAST']] ```
8,333,855
Hope you can help. I have created my own Custom UIView and I'm trying to pass in a NSMutableArray which I have setup from data from a sqlite DB. I have NSLog'd the Array from the ViewController and everything is showing correctly. However I want to pass this NSMutableArray into my Custom UIView (it's actually a UIScrollView) so that I can do some magic. However when I do this, my NSLog show's the output as (null). Here is my code (I've also passed a test string to help to see if it's Array specific, but it isn't): viewcontroller.m (just shown the Custom class call - NSLog outputs the Array contents (see end of examples) ``` - (void)viewDidLoad { ... NSString *teststring = @"Testing"; NSLog(@"Subitems: %@", subitems); SubItemView* subitemview = [[SubItemView alloc] initWithFrame:CGRectMake(150,150,0,0)]; subitemview.cvSubitems = subitems; subitemview.teststring = teststring; [self.view addSubview:subitemview]; } ``` customview.h ``` #import <UIKit/UIKit.h> @class SubItemView; @interface SubItemView : UIScrollView { } @property (nonatomic, retain) NSMutableArray *cvSubitems; @property (nonatomic, retain) NSString *teststring; @end ``` customview.m ``` #import "SubItemView.h" @implementation SubItemView @synthesize cvSubitems; @synthesize teststring; - (id)initWithFrame:(CGRect)frame { CGRect rect = CGRectMake(0, 0, 400, 400); NSLog(@"Subclass Properties: %@", self.cvSubitems); self = [super initWithFrame:rect]; if (self) { // Initialization code } return self; } ``` The first NSLog in the viewcontroller.m outputs: ``` Subitems: ( "<SubItems: 0x6894400>", "<SubItems: 0x6894560>" ) ``` The second NSLog from the Custom UIScrollView outputs: ``` Subclass Properties: (null) ``` I am a bit of a newbie, so I'm obviously missing something (possibly obvious) here. I am just really struggling to pass an Array and even a simple string into a Custom class and just output it's contents via NSLog. Any help is gratefully appreciated.
2011/11/30
[ "https://Stackoverflow.com/questions/8333855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/713970/" ]
Well when your initWithFrame method is called, your cvSubitems property isn't set yet, as it is set only **after** your call to initWithFrame. Try again to log your arrays value in a method that is called after your view is initialized, or provide a custom init method (e.g. `initWithMyData: andFrame:`) to solve this issue.
So to clarify what has already been said, you are calling out of order. ``` 1| SubItemView* subitemview = [[SubItemView alloc] initWithFrame:CGRectMake(150,150,0,0)]; 2| subitemview.cvSubitems = subitems; 3| subitemview.teststring = teststring; ``` * On line 1 you are calling the `initWithFrame:` method on `SubItemView` * On lines 2 and 3 you are setting the ivars The point being that you are setting the ivars (lines 2+3) after the `initWithFrame:` method has returned. **But** you are trying to print the ivars in the `initWithFrame:` method You are also trying to log the ivars before you have even assigned `self` which is not a good idea either ``` NSLog(@"Subclass Properties: %@", self.cvSubitems); self = [super initWithFrame:rect]; ``` To prove that they are being set you can just print from where you instantiate: ``` SubItemView *subitemview = [[SubItemView alloc] initWithFrame:CGRectMake(150,150,0,0)]; subitemview.cvSubitems = subitems; subitemview.teststring = teststring; NSLog(@"Subclass Properties: %@", subitemview.cvSubitems); ```
34,591,007
I want to load some images from a folder but I want to works on another pc. I load an image like this: ``` Image1->Picture->Bitmap->LoadFromFile("C:\\Users\\Raul\\Desktop\\Cards BMP\\2_of_diamonds.bmp" ); ``` And when I run project on another pc that "C:\Users\Raul\Desktop\" is diffrent. How can I load that image from another pc? I use C++ Builder 6.
2016/01/04
[ "https://Stackoverflow.com/questions/34591007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5651241/" ]
You can select those using the attribute selector and use `.prop()` to check the checkboxes: ``` $('[value="1"], [value="3"]').prop("checked", true); ``` ```js $('[value="1"], [value="3"]').prop("checked", true); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="checkbox" value="1" />Orders <input type="checkbox" value="2" />Production <input type="checkbox" value="3" />Dispatch <input type="checkbox" value="4" />Returns <input type="checkbox" value="5" />Sundry <input type="checkbox" value="6" />Collection <input type="checkbox" value="7" />Pending Amount <input type="checkbox" value="8" />Pending Bills <input type="checkbox" value="9" />Ledger <input type="checkbox" value="10" />Day Book ``` **Update** From AJAX, you can do this way: ```js $(function () { valuesFromAjax = "1,2"; valuesFromAjax = valuesFromAjax.split(","); valuesFromAjax.map(function (Id) { $('[value="' + Id + '"]').prop("checked", true); }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="checkbox" value="1" />Orders <input type="checkbox" value="2" />Production <input type="checkbox" value="3" />Dispatch <input type="checkbox" value="4" />Returns <input type="checkbox" value="5" />Sundry <input type="checkbox" value="6" />Collection <input type="checkbox" value="7" />Pending Amount <input type="checkbox" value="8" />Pending Bills <input type="checkbox" value="9" />Ledger <input type="checkbox" value="10" />Day Book ```
Assuming the array has string values you can use the following code: ```js $(document).ready(function() { //init an array with the values from OP var values = ["1", "3"]; //iterate through each checkbox $("CheckboxGroup[name='permitted'] :checkbox").each(function() { //if value exist in array change the status of the checkbox $(this).prop("checked", values.indexOf(this.value) !== -1); }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <CheckboxGroup name="permitted"> <input type="checkbox" value="1" />Orders <input type="checkbox" value="2" />Production <input type="checkbox" value="3" />Dispatch <input type="checkbox" value="4" />Returns <input type="checkbox" value="5" />Sundry <input type="checkbox" value="6" />Collection <input type="checkbox" value="7" />Pending Amount <input type="checkbox" value="8" />Pending Bills <input type="checkbox" value="9" />Ledger <input type="checkbox" value="10" />Day Book </CheckboxGroup> ```
17,157,455
I have an img tag as(which of course is not of the exact syntax) `<img src="http://localhost/img/img_1.png" id=1 onclick="say_hi(id)" href="/img_page_1/" alt="Aim Pic" width="230" height= "164" />` what i need here is when user left clicks on img, i need onClick to be triggered and when user right clicks on it, it must act like a general href showing option ("open in new window" etc) why i need it is, i want to show the page preview related to image with in the home page by bluring rest of page(ajax is used here to load preview of image page in say\_hi function) and when user right clicks on it i want it to feel like a normal href so that he can directly open the page in other tab rather than a preview. EDIT: In simple terms i want to state/write/give a link to some image which acts normally as a link when right clicked(showing the context menu which has all the options for a link) but it must trigger a onClick event(or run a function in javascript) when left clicked. Thank you.
2013/06/17
[ "https://Stackoverflow.com/questions/17157455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2068349/" ]
If the parent repository depends on the 'data' repository being a specific version, you might want to consider [git submodules](http://git-scm.com/book/en/Git-Tools-Submodules). This will allow the parent repository to point to a specific commit of the 'data' repository. Even if the two are compatible now they may not be in the future. I don't have much detail on your use-case and how 'myproject' relates to 'data', so submodules may over-complicate things for you.
Yep, that should be fine. I've done that many times before, with no problems.
26,587,020
I am trying to create a VBA script that copies all data in a whole workbook as pastes as values, then saves as a new workbook, thus removing all formulas. Here is my code: ``` Sub MakeAllVals() Dim wSheet As Worksheet For Each wSheet In Worksheets With wSheet .UsedRange.Copy .PasteSpecial xlValues End With Next wSheet Application.Dialogs(xlDialogSaveAs).Show End Sub ``` I'm getting a runtime error 1004 on the .PasteSpecial xlValues command but I can't work out why. How can I accomplish the goal of pasting all data as values and saving as a new workbook?
2014/10/27
[ "https://Stackoverflow.com/questions/26587020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3999951/" ]
You can assign an array to an array item like so: ``` Dim n As Long n = 0 ReDim MyArray(2700 \ 60) For i = 0 To 2700 Step 60 MyArray(n) = Array(i, 1) n = n + 1 Next i ```
You are going correct. Instead of adding to string in loop, just create actual array items. So this is what you will have: ``` Sub Sample() Dim ws As Worksheet Dim MyArray(20) As Variant '<-- specify the number of items you want Dim i As Long For i = 0 To UBound(MyArray) MyArray(i) = Array(i * 60, 1) Next Set ws = ThisWorkbook.Sheets("Sheet1") ws.Columns(1).TextToColumns _ Destination:=Range("A1"), _ DataType:=xlFixedWidth, _ FieldInfo:=MyArray, _ TrailingMinusNumbers:=True End Sub ```
62,425,923
**Versions** * "@angular/common": "~9.0.0" * "@angular/service-worker": "~9.0.0" **Description** I implemented the service-worker using `ng add @angular/pwa --project [app]` and Lighthouse would recognise the web-app as a PWA. Suddenly, after one deploy to Firebase hosting the "install" notification wasn´t popping up, so I checked the dev-console. The manifest was still showing up as usual: [![enter image description here](https://i.stack.imgur.com/t0PKm.png)](https://i.stack.imgur.com/t0PKm.png) But nothing was being cached: [![enter image description here](https://i.stack.imgur.com/kShpH.png)](https://i.stack.imgur.com/kShpH.png) When running a Lighthouse-Audit, I get following error: ``` start_url does not respond with a 200 when offline ``` **ngsw-config.json** ``` { "$schema": "./node_modules/@angular/service-worker/config/schema.json", "index": "/index.html", "assetGroups": [ { "name": "app", "installMode": "prefetch", "resources": { "files": [ "/favicon.ico", "/index.html", "/manifest.webmanifest", "/*.css", "/*.js" ] } }, { "name": "assets", "installMode": "lazy", "updateMode": "prefetch", "resources": { "files": [ "/assets/**", "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)" ] } } ] } ``` **manifest.webmanifest** ``` { "name": "App", "short_name": "App", "theme_color": "#5787b2", "background_color": "#fafafa", "display": "standalone", "scope": "/", "start_url": "/", "icons": [ { "src": "assets/icons/icon-192x192.png", "sizes": "192x192", "type": "image/png" }, { "src": "assets/icons/icon-512x512.png", "sizes": "512x512", "type": "image/png" } ] } ```
2020/06/17
[ "https://Stackoverflow.com/questions/62425923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8581106/" ]
So I found the solution to my problem in this comment to a similar problem: <https://stackoverflow.com/a/61152966/8581106> In `app.module.ts` add `registrationStrategy: 'registerImmediately'` to the registration of the ServiceWorker like this: ``` ServiceWorkerModule.register('ngsw-worker.js', { enabled: env.production, registrationStrategy: 'registerImmediately' }), ```
In my case I had the following in my app.module imports: ``` ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production }) ``` Except the prod variable was returning `false` because the environment being used was not --prod. Make sure `env.production` is actually returning "true" where it's supposed to. A good place to start is in `package.json` in "scripts". Check the command is running `--configuration=prod-env` or however you've got it configured.
2,550,162
I was wondering how [does Nike website make the change](http://nikeid.nike.com/nikeid/?sitesrc=uslp) you can see when selecting a color or a sole. At first I thought they were only using images and when the user picked a color you just replaced that part, but when I selected a different sole I noticed it didn't changed like an image it looked a bit more as if it was being rendered. Does anybody happens to know how this is made? Or where can I get further info about making this effect :)?
2010/03/31
[ "https://Stackoverflow.com/questions/2550162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28586/" ]
It's hard to know for sure, but my guess would be that they're using a rendering service similar to that provided by [Adobe's Scene7](http://www.scene7.com/). It's a product that is used to colorize/customize a base product image based on user choices. If you're interested in using the service, I'd suggest signing up for their weekly webinar. I attended one a while back and was very impressed with their offering. They showed the Converse site (which had functionality almost identical functionality to the Nike site) as a demo.
A lot of these tools are built out in Flash using a variety of techniques: 1) You can use Flash's BitmapData object to directly shift the hues of the pixels in your item. This is probably the simplest technique but often limits you to simple color transformations. 2) You can pre-render transparent PNG's (or photos, I guess) containing the various textures you would want to show on your object (for instance patterns or textures) and have them dynamically added to your stage at runtime. This, I think, offers the highest fidelity but means you need all of your items rendered upfront. 3) You can create 3D collada files and load them via a library like Papervision3D. Then dynamically change the texture at runtime. This is the most memory intensive technique and tends to result in far worse fidelity, but for that you get a full 3D object that you can view in space. I'm sure there are other techniques but those are the top 3 I can think of. I hope that helps!
124,819
I Have tried to add new image upload attribute to Magento Product using sql upgrade script, but I got the error message like: > > Invalid backend model specified: > catalog/product\_attribute\_backend\_image > > > The file has name `upgrade-0.0.1-0.0.2.php` which is correct because I see new version in `core_resource` table. There is my code: ``` $installer = $this; $installer->startSetup(); $this->addAttribute(Mage_Catalog_Model_Product::ENTITY, 'image_cert', array( 'type' => 'varchar', 'group' => 'Design', 'label' => 'Certificate Image', 'input' => 'image', 'backend' => 'catalog/product_attribute_backend_image', 'required' => false, 'sort_order' => 55, 'global' => 1 )); $installer->endSetup(); ``` What I'm doing wrong?
2016/07/08
[ "https://magento.stackexchange.com/questions/124819", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/20188/" ]
Try this code (base image attribute) ``` <?php $setup = new Mage_Catalog_Model_Resource_Setup('core_setup'); $attr = array ( 'attribute_model' => NULL, 'backend' => NULL, 'type' => 'varchar', 'table' => NULL, 'frontend' => 'catalog/product_attribute_frontend_image', 'input' => 'media_image', 'label' => 'Base Image', 'frontend_class' => NULL, 'source' => NULL, 'required' => '0', 'user_defined' => '0', 'default' => NULL, 'unique' => '0', 'note' => NULL, 'input_renderer' => NULL, 'global' => '0', 'visible' => '1', 'searchable' => '0', 'filterable' => '0', 'comparable' => '0', 'visible_on_front' => '0', 'is_html_allowed_on_front' => '0', 'is_used_for_price_rules' => '0', 'filterable_in_search' => '0', 'used_in_product_listing' => '0', 'used_for_sort_by' => '0', 'is_configurable' => '1', 'apply_to' => NULL, 'visible_in_advanced_search' => '0', 'position' => '0', 'wysiwyg_enabled' => '0', 'used_for_promo_rules' => '0', 'tooltip' => NULL, 'max_len' => '0', 'option' => array ( 'values' => array ( ), ), ); $setup->addAttribute('catalog_product', 'image', $attr); $attribute = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product', 'image'); $attribute->setStoreLabels(array ( )); $attribute->save(); ```
You can create attribute from backend itself: 1. *Catalog > Attributes > Manage Attributes > Create New Attribute* 2. Select *Catalog Input Type for Store Owner* as **Media Image** 3. Put this attribute in Image Group of your attribute set. 4. Do Index Management 5. Clear caches
9,961,041
Making a simple hello world app in c++, but it won't compile. I have the folder `C:\WiiGames\e3\` with the files `main.cpp` and `Makefile`. My makefile is: ``` build: main.cpp C:/MinGW/bin/g++.exe main.cpp -o e3.exe ``` My error is: ``` C:\WiiGames\e3>make build C:/MinGW/bin/g++.exe main.cpp -o e3.exe make: *** [build] Error 1 C:\WiiGames\e3> ``` Any help would be greatly appreciated. My code: ``` #include <iostream> #include <stdio.h> #include <string> #include <cmath> #include <cstdlib> #include <time.h> int main() { printf("Hello World!"); } ``` g++ -v: ``` Using built-in specs. COLLECT_GCC=g++ COLLECT_LTO_WRAPPER=c:/mingw/bin/../libexec/gcc/mingw32/4.6.2/lto-wrapper.exe Target: mingw32 Configured with: ../gcc-4.6.2/configure --enable-languages=c,c++,ada,fortran,objc,obj-c++ --disable-sjlj-exceptions --with-dwarf2 --enable-shared --enable-libgomp --disable-win32-registry --enable-libstdcxx-debug --enable-version-specific-runtime-libs --build=mingw32 --prefix=/mingw Thread model: win32 gcc version 4.6.2 (GCC) ```
2012/04/01
[ "https://Stackoverflow.com/questions/9961041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/733880/" ]
First a terminology correction. `var` is just a keyword the compiler lets you use to subsitute for the type. During compiletime, the compiler will figure out what the type is based on usage. ``` var myString = "hihihi"; string myString = "hihihi"; ``` The `var` statement has nothing to do with accessing a database, although it was added to make using LINQ easier on us lazy developers. Instead what you are doing is creating a `LINQ to SQL` query. I've modified it slightly (you don't need to create an anonymous object). After you create the statement, you need to execute it by calling "ToList(), First(), or FirstOrDefault() etc" LINQ typically employs lazy or deferred evaluation for queries, and isn't executed until you trigger execution. ``` var price = from p in BooksDB.Price where p.Book_Name==bookName select p.Book_Price; //assuming Book_Price is stored as a string datatype. string bookPrice = price.FirstOrDefault(); //otherwise string bookPrice = (price.FirstOrDefault() ?? "").ToString(); if(!String.IsNullOrEmpty(bookPrice)) { //do something with the string. } ```
If I understand correctly something like below should work. ``` var record = BooksDB.Price.FirstOrDefault(r => r.Book_Name == bookName); ``` If `record` is not `null` at this point then `record.Book_Price` should contain the data you are looking for (not accounting for ambiguity in the database.)
9,961,041
Making a simple hello world app in c++, but it won't compile. I have the folder `C:\WiiGames\e3\` with the files `main.cpp` and `Makefile`. My makefile is: ``` build: main.cpp C:/MinGW/bin/g++.exe main.cpp -o e3.exe ``` My error is: ``` C:\WiiGames\e3>make build C:/MinGW/bin/g++.exe main.cpp -o e3.exe make: *** [build] Error 1 C:\WiiGames\e3> ``` Any help would be greatly appreciated. My code: ``` #include <iostream> #include <stdio.h> #include <string> #include <cmath> #include <cstdlib> #include <time.h> int main() { printf("Hello World!"); } ``` g++ -v: ``` Using built-in specs. COLLECT_GCC=g++ COLLECT_LTO_WRAPPER=c:/mingw/bin/../libexec/gcc/mingw32/4.6.2/lto-wrapper.exe Target: mingw32 Configured with: ../gcc-4.6.2/configure --enable-languages=c,c++,ada,fortran,objc,obj-c++ --disable-sjlj-exceptions --with-dwarf2 --enable-shared --enable-libgomp --disable-win32-registry --enable-libstdcxx-debug --enable-version-specific-runtime-libs --build=mingw32 --prefix=/mingw Thread model: win32 gcc version 4.6.2 (GCC) ```
2012/04/01
[ "https://Stackoverflow.com/questions/9961041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/733880/" ]
First a terminology correction. `var` is just a keyword the compiler lets you use to subsitute for the type. During compiletime, the compiler will figure out what the type is based on usage. ``` var myString = "hihihi"; string myString = "hihihi"; ``` The `var` statement has nothing to do with accessing a database, although it was added to make using LINQ easier on us lazy developers. Instead what you are doing is creating a `LINQ to SQL` query. I've modified it slightly (you don't need to create an anonymous object). After you create the statement, you need to execute it by calling "ToList(), First(), or FirstOrDefault() etc" LINQ typically employs lazy or deferred evaluation for queries, and isn't executed until you trigger execution. ``` var price = from p in BooksDB.Price where p.Book_Name==bookName select p.Book_Price; //assuming Book_Price is stored as a string datatype. string bookPrice = price.FirstOrDefault(); //otherwise string bookPrice = (price.FirstOrDefault() ?? "").ToString(); if(!String.IsNullOrEmpty(bookPrice)) { //do something with the string. } ```
Instead of `select new {p.Book_Price}`, use something like `select p.Book_Price`. You could add `.ToString()` to the end to force it to come out as a String rather than the data type from the table. You'll also want to wrap the entire LINQ statement in () and append `.FirstOrDefault()` to get just one value. The "OrDefault" part protects you from an exception when the result set us empty.
9,961,041
Making a simple hello world app in c++, but it won't compile. I have the folder `C:\WiiGames\e3\` with the files `main.cpp` and `Makefile`. My makefile is: ``` build: main.cpp C:/MinGW/bin/g++.exe main.cpp -o e3.exe ``` My error is: ``` C:\WiiGames\e3>make build C:/MinGW/bin/g++.exe main.cpp -o e3.exe make: *** [build] Error 1 C:\WiiGames\e3> ``` Any help would be greatly appreciated. My code: ``` #include <iostream> #include <stdio.h> #include <string> #include <cmath> #include <cstdlib> #include <time.h> int main() { printf("Hello World!"); } ``` g++ -v: ``` Using built-in specs. COLLECT_GCC=g++ COLLECT_LTO_WRAPPER=c:/mingw/bin/../libexec/gcc/mingw32/4.6.2/lto-wrapper.exe Target: mingw32 Configured with: ../gcc-4.6.2/configure --enable-languages=c,c++,ada,fortran,objc,obj-c++ --disable-sjlj-exceptions --with-dwarf2 --enable-shared --enable-libgomp --disable-win32-registry --enable-libstdcxx-debug --enable-version-specific-runtime-libs --build=mingw32 --prefix=/mingw Thread model: win32 gcc version 4.6.2 (GCC) ```
2012/04/01
[ "https://Stackoverflow.com/questions/9961041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/733880/" ]
If I understand correctly something like below should work. ``` var record = BooksDB.Price.FirstOrDefault(r => r.Book_Name == bookName); ``` If `record` is not `null` at this point then `record.Book_Price` should contain the data you are looking for (not accounting for ambiguity in the database.)
Instead of `select new {p.Book_Price}`, use something like `select p.Book_Price`. You could add `.ToString()` to the end to force it to come out as a String rather than the data type from the table. You'll also want to wrap the entire LINQ statement in () and append `.FirstOrDefault()` to get just one value. The "OrDefault" part protects you from an exception when the result set us empty.
754,843
> > Prove the series $$\sum\_{n = 1}^{ \infty} \frac 1 6 n (\frac 5 6)^{n-1} = 6.$$ > > > I've tried various methods for proving the series: The series is not geometric, but I see that $\frac 1 6 n (\frac 5 6)^{n-1} \rightarrow 0$. Also the series is not telescoping, as far I'm concerned. What method could solve this ?
2014/04/15
[ "https://math.stackexchange.com/questions/754843", "https://math.stackexchange.com", "https://math.stackexchange.com/users/86379/" ]
Here's a calculus approach: We know that: $$\frac{1}{1 - x} = 1 + x + x^2 + \dots$$ Differentiating both sides, $$\frac{1}{(1-x)^2} = 1 + 2x + 3x^2 + \dots$$ Now, substitute $x = \frac{5}{6}$. Then, $$\sum\_{n = 1}^\infty n\left(\frac{5}{6}\right)^{n-1} = \frac{1}{\left(1 - \frac{5}{6}\right)^2}$$ So we have: $$\frac{1}{6}\sum\_{n = 1}^\infty n\left(\frac{5}{6}\right)^{n-1} = \frac{1}{6\left(1 - \frac{5}{6}\right)^2}\\ = 6$$
**Hint:** $$6S=1+2.\frac56+3.(\frac56)^2+4.(\frac56)^3...$$ $$\frac56\times6S=0+\frac56+2.(\frac56)^2+3.(\frac56)^3...$$ Zero is just to show order of subtraction $$S=1+\frac56+(\frac56)^2+(\frac56)^3...$$ Hope you can carry on from here.
3,989,272
If $\cos(θ) = a$, and $\sin(θ) = a$, and if $a$ is between $-1$ and $1$, how could we find $θ$. I could do this graphically by finding the intersection of $\sin(x), \cos(x)$ and $y=a$. But how could I find out with algebra, maybe the sign rules for each function in each quadrant.
2021/01/17
[ "https://math.stackexchange.com/questions/3989272", "https://math.stackexchange.com", "https://math.stackexchange.com/users/850232/" ]
$$\cos(\theta)=\sin(\theta)\iff\sin\left(\frac\pi2-\theta\right)=\sin(\theta).$$ Hence $$\frac\pi2-\theta=\theta+2k\pi$$ or $$\frac\pi2-\theta=\pi-\theta+2k\pi.$$ The second equation is impossible and finally $$\theta=\frac\pi4+k\pi.$$ From this, $$\sin(\theta)=\pm\frac1{\sqrt2}=a$$ which shows the condition for a solution.
Since $\sin(t) = \cos(\pi/2-t)$, if $0 \le t \le \pi$ then $t = \pi/2-t$ or $t = \pi/4$. If $\pi \le t \le 2\pi$ then, letting $t = \pi+s$ so $0 \le s \le \pi$, since $\sin(t) = \sin(\pi+s) = -\sin(s) $ and $\cos(t) =\cos(\pi+s) =-\cos(s) $, we have, again, $\sin(s)=\cos(s) $ so $s = \pi/4$ and $t = 5\pi/4 $. The value of $a$ is $\pm \sqrt{2}/2$.
3,989,272
If $\cos(θ) = a$, and $\sin(θ) = a$, and if $a$ is between $-1$ and $1$, how could we find $θ$. I could do this graphically by finding the intersection of $\sin(x), \cos(x)$ and $y=a$. But how could I find out with algebra, maybe the sign rules for each function in each quadrant.
2021/01/17
[ "https://math.stackexchange.com/questions/3989272", "https://math.stackexchange.com", "https://math.stackexchange.com/users/850232/" ]
$$\cos(\theta)=\sin(\theta)\iff\sin\left(\frac\pi2-\theta\right)=\sin(\theta).$$ Hence $$\frac\pi2-\theta=\theta+2k\pi$$ or $$\frac\pi2-\theta=\pi-\theta+2k\pi.$$ The second equation is impossible and finally $$\theta=\frac\pi4+k\pi.$$ From this, $$\sin(\theta)=\pm\frac1{\sqrt2}=a$$ which shows the condition for a solution.
A geometric solution: In the first quadrant, $\cos \theta$ and $\sin \theta$ are complementary angles. So we have $\theta + \theta = \frac{\pi}{2}$, or $$\theta=\frac{\pi}{4}+2k\pi.$$ The other solution is in the third quadrant (where cosine and sine are both negative). So the solutions are $$\theta \in \left\{ \frac{\pi}{4}, \frac{5\pi}{4}\right\}+2k\pi.$$
25,967,060
3.9/6 N3797: > > [...] > > > The type of a pointer to array of unknown size, or of a type defined > by a typedef declaration to be an array of unknown size, cannot be > completed. > > > It sounds like a pointer to an array of unknown size is an incomplete type. If so we couldn't define an object of a pointer to array of unknown size. But it is not true, because we can define an array of unknown bound. ``` #include <iostream> using std::cout; using std::endl; int (*a)[] = (int(*)[])0x4243afff; int main() { } ``` It compiles fine. **[DEMO](http://coliru.stacked-crooked.com/a/8c055a33b64bd424)** We could't do it if it were incomplete type. Indeed: 3.9/5: > > Objects shall not be defined to have an incomplete type > > > The Standard previously defined an incomplete types as follows 3./5: > > A class that has been declared but not defined, an enumeration type in > certain contexts (7.2), or an array of unknown size or of incomplete > element type, is an incompletely-defined object type. > Incompletely defined object types and the void types are incomplete > types (3.9.1). > > > Which means the pointer to an incomplete type is complete. Contradiction? So where I'm wrong in my reasoning?
2014/09/22
[ "https://Stackoverflow.com/questions/25967060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I think this wording is defective. In your code: ``` int (*a)[]; ``` the type of `a` is actually complete. The type of `*a` is incomplete. It seems to me (as dyp says in comments) that the intent of the quote was to say that there is no way that later in the program, `*a` will be an expression with complete type. Background: some incomplete types can be completed later e.g. as suggested by cdhowie and dyp: ``` extern int a[]; int b = sizeof a; // error int a[10]; int c = sizeof a; // OK ``` However `int (*a)[];` cannot be completed later; `sizeof *a` will always be an error.
Like C++ statements, English sentences must be interpreted *in context*. The context of the quoted sentence makes its meaning perfectly clear. The paragraph reads (§3.9 [basic.types]/p6, the sentence you quoted is bolded): > > A class type (such as “`class X`”) might be incomplete at one point in > a translation unit and complete later on; the type “`class X`” is the > same type at both points. The declared type of an array object might > be an array of incomplete class type and therefore incomplete; if the > class type is completed later on in the translation unit, the array > type becomes complete; the array type at those two points is the same > type. The declared type of an array object might be an array of > unknown size and therefore be incomplete at one point in a translation > unit and complete later on; the array types at those two points > (“array of unknown bound of `T`” and “array of `N T`”) are different > types. **The type of a pointer to array of unknown size, or of a type > defined by a `typedef` declaration to be an array of unknown size, > cannot be completed.** > > > Read in context, it's clearly saying that a "pointer to array of unknown bound of `T`" can't be "completed" into a "pointer to array of N `T`" in the way that an object declared as an "array of unknown bound of `T`"" can be later defined as an "array of N `T`"
30,179,402
I'm am new to graphics in java and for some reason the graphics are not displaying on the jframe. I am confused of how to set up and instantiate the graphics. There could also be a stupid error in the code that im just not seeing. Thanks for any feedback! Map Class ``` public class Map extends JPanel{ private static int WIDTH; private static int HEIGHT; private static int ROWS; private static int COLS; private static int TILE_SIZE; private static int CLEAR = 0; private static int BLOCKED = 1; private static int[][] GRID; public Map(int w, int h, int t){ WIDTH = w; HEIGHT = h; TILE_SIZE = t; ROWS = HEIGHT/TILE_SIZE; COLS = WIDTH/TILE_SIZE; GRID = new int[ROWS][COLS]; for (int row = 0; row < ROWS; row++){ for (int col = 0; col < COLS; col++){ GRID[row][col] = BLOCKED; } } randomMap(); } public void randomMap(){ int row = 0; int col = 0; int turn; Random rand = new Random(); GRID[row][col] = CLEAR; do{ turn = rand.nextInt(2)+1; if (turn == 1) row++; else col++; GRID[row][col] = CLEAR; }while(row<ROWS-1 && col<COLS-1); if (row == ROWS-1){ for (int i = col; i < COLS; i++){ GRID[row][i] = CLEAR; } } else{ for (int i = row; i < ROWS; i++){ GRID[i][col] = CLEAR; } } } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; for (int row = 0; row < WIDTH; row++){ for (int col = 0; col < HEIGHT; col++){ if (GRID[row][col] == 1){ g2d.setColor(Color.BLACK); g2d.fillRect(row*TILE_SIZE, col*TILE_SIZE, TILE_SIZE, TILE_SIZE); }else{ g2d.setColor(Color.WHITE); g2d.fillRect(row*TILE_SIZE, col*TILE_SIZE, TILE_SIZE, TILE_SIZE); } } } } public void displayConsole(){ for (int row = 0; row < ROWS; row++){ for (int col = 0; col < COLS; col++){ System.out.print(GRID[row][col] + " "); } System.out.println(""); System.out.println(""); } } } ``` Game Class ``` public class Game extends JFrame{ private Map map; public Game(){ setLayout(null); setBounds(0,0,500,500); setSize(500,500); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Map map = new Map(500,500,50); map.displayConsole(); add(map); repaint(); setVisible(true); } public static void main(String[] args) { // TODO Auto-generated method stub Game game = new Game(); } } ```
2015/05/11
[ "https://Stackoverflow.com/questions/30179402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4595287/" ]
It is likely the painted component is of size 0x0. A custom painted component should return the preferred size of the component. After the component is added to a frame, pack the frame to ensure the frame is the exact size needed to display the component. Of course, either use or set an appropriate layout/constraint in the frame. In this case, I would use the default layout of `BorderLayout` and the default constraint of `CENTER`.
Andrew is correct. I had to re-do the layout to get this to work. I added the code for `perferredSize()` and `minimumSize()`, and I added a call to `pack()` and removed the `setLayout(null)`. Also, you have a problem calculating your HEIGHT and WIDTH, they don't line up to ROWS and COLS and will throw Index Out Of Bounds. Corrected code below. ``` class Game extends JFrame { private Map map; public Game() { // setLayout( null ); setBounds( 0, 0, 500, 500 ); setSize( 500, 500 ); setResizable( false ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); Map map = new Map( 500, 500, 50 ); map.displayConsole(); add( map ); pack(); repaint(); setVisible( true ); } public static void main( String[] args ) { // TODO Auto-generated method stub Game game = new Game(); } } class Map extends JPanel { private static int WIDTH; private static int HEIGHT; private static int ROWS; private static int COLS; private static int TILE_SIZE; private static int CLEAR = 0; private static int BLOCKED = 1; private static int[][] GRID; public Map( int w, int h, int t ) { WIDTH = w; HEIGHT = h; TILE_SIZE = t; ROWS = HEIGHT / TILE_SIZE; COLS = WIDTH / TILE_SIZE; GRID = new int[ ROWS ][ COLS ]; for( int row = 0; row < ROWS; row++ ) for( int col = 0; col < COLS; col++ ) GRID[row][col] = BLOCKED; randomMap(); } public void randomMap() { int row = 0; int col = 0; int turn; Random rand = new Random(); GRID[row][col] = CLEAR; do { turn = rand.nextInt( 2 ) + 1; if( turn == 1 ) row++; else col++; GRID[row][col] = CLEAR; } while( row < ROWS - 1 && col < COLS - 1 ); if( row == ROWS - 1 ) for( int i = col; i < COLS; i++ ) GRID[row][i] = CLEAR; else for( int i = row; i < ROWS; i++ ) GRID[i][col] = CLEAR; } @Override public Dimension preferredSize() { // return super.preferredSize(); //To change body of generated methods, choose Tools | return new Dimension( WIDTH, HEIGHT ); } @Override public Dimension minimumSize() { return preferredSize(); } public void paintComponent( Graphics g ) { super.paintComponent( g ); Graphics2D g2d = (Graphics2D) g; for( int row = 0; row < ROWS; row++ ) for( int col = 0; col < COLS; col++ ) if( GRID[row][col] == 1 ) { g2d.setColor( Color.BLACK ); g2d.fillRect( row * TILE_SIZE, col * TILE_SIZE, TILE_SIZE, TILE_SIZE ); } else { g2d.setColor( Color.WHITE ); g2d.fillRect( row * TILE_SIZE, col * TILE_SIZE, TILE_SIZE, TILE_SIZE ); } } public void displayConsole() { for( int row = 0; row < ROWS; row++ ) { for( int col = 0; col < COLS; col++ ) System.out.print( GRID[row][col] + " " ); System.out.println( "" ); System.out.println( "" ); } } } ```
4,063,860
I am trying to work with several documents that all have various encodings - some utf-8, some ISO-8859-2, some ascii etc. Is there a reliable way of decoding to a standard encoding for processing? I have tried the following: ``` import chardet encoding = chardet.detect(text) text = unicode(text,encoding['encoding']).decode(sys.getdefaultencoding(),'ignore') ``` With the above code I still get UnicodeEncodeError errors
2010/10/31
[ "https://Stackoverflow.com/questions/4063860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95472/" ]
Use `decode` to convert bytes to unicode, and `encode` to convert unicode to bytes: ``` text.decode(encoding['encoding'], 'ignore').encode(sys.getdefaultencoding(), 'ignore') ``` Although I would recommend doing your processing on the unicode objects themselves, or UTF-8 encoded strings if you absolutely need to work with bytes. `sys.getdefaultencoding()` is `'ascii'`, which provides a very limited character set. See also: <http://wiki.python.org/moin/DefaultEncoding>
You probably mean `encode`: ``` u = unicode(text, encoding['encoding'], 'ignore') text = u.encode(sys.getdefaultencoding(), 'ignore') ``` or equivalently and more commonly, ``` u = text.decode(encoding['encoding'], 'ignore') text = u.encode(sys.getdefaultencoding(), 'ignore') ``` You may want `ignore` on both, as above: the incoming text may have invalid characters in it, causing it to fail to decode to Unicode, and it may have characters which can't be represented in the default encoding, causing it to fail to encode. (You may not actually want to ignore errors, though, since it looks like you were just trying to work around using the wrong function.)
13,289,033
I have an example of accessing a cell in a Java POI worksheet: ``` CellReference cr = new CellReference("A1"); row = mySheet.getRow(cr.getRow()); cell = row.getCell(cr.getCol()); ``` but now if I need the next cell in a row or another cell in another row, is there an easy way to navigate about the worksheet? Is there some type of increment function?
2012/11/08
[ "https://Stackoverflow.com/questions/13289033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/840930/" ]
You can't match *both* conditions. You mean *either* condition ``` SELECT * FROM interviews WHERE ('YEAR(date) = 2012' OR 'YEAR(date) < 2012'); ``` Better though, makes it SARGable ``` SELECT * FROM interviews WHERE date < '2013-01-01'); SELECT * FROM interviews WHERE date < CONCAT('''', YEAR(CURDATE()), '-01-01'''); ```
try something like ``` SELECT * FROM interviews WHERE YEAR(date) <= YEAR(GETDATE()) ``` GETDATE() basically gives you the current date. Now if your looking into counting how many people were interviewed it would be something like this ``` SELECT COUNT(DISTINCT(id)) FROM interviews WHERE YEAR(date) <= YEAR(GETDATE()) ```
13,289,033
I have an example of accessing a cell in a Java POI worksheet: ``` CellReference cr = new CellReference("A1"); row = mySheet.getRow(cr.getRow()); cell = row.getCell(cr.getCol()); ``` but now if I need the next cell in a row or another cell in another row, is there an easy way to navigate about the worksheet? Is there some type of increment function?
2012/11/08
[ "https://Stackoverflow.com/questions/13289033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/840930/" ]
You can't match *both* conditions. You mean *either* condition ``` SELECT * FROM interviews WHERE ('YEAR(date) = 2012' OR 'YEAR(date) < 2012'); ``` Better though, makes it SARGable ``` SELECT * FROM interviews WHERE date < '2013-01-01'); SELECT * FROM interviews WHERE date < CONCAT('''', YEAR(CURDATE()), '-01-01'''); ```
try this ``` select * from tbl_interviews where year(date)<='2012' ```
13,289,033
I have an example of accessing a cell in a Java POI worksheet: ``` CellReference cr = new CellReference("A1"); row = mySheet.getRow(cr.getRow()); cell = row.getCell(cr.getCol()); ``` but now if I need the next cell in a row or another cell in another row, is there an easy way to navigate about the worksheet? Is there some type of increment function?
2012/11/08
[ "https://Stackoverflow.com/questions/13289033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/840930/" ]
You can't match *both* conditions. You mean *either* condition ``` SELECT * FROM interviews WHERE ('YEAR(date) = 2012' OR 'YEAR(date) < 2012'); ``` Better though, makes it SARGable ``` SELECT * FROM interviews WHERE date < '2013-01-01'); SELECT * FROM interviews WHERE date < CONCAT('''', YEAR(CURDATE()), '-01-01'''); ```
Your query should simply be: ``` SELECT COUNT(DISTINCT user_id) FROM tbl_interviews ``` Explanation: your question is: "I should count the people that has been interviewd this year AND in the years before." First of, this part: "this year AND in the years before" means people interviewed this year, as well as every year before this year. Since you can't have any interviews that occur in the future, this essentially means all interviews regardless of the year. If that's not what you meant, then please rephrase your question. (I have an idea, see below) As for "I should count the people", I take that to mean you want to count each individual that was interviewd, regardless of how many interviews they did. This is done by simply counting unique user\_id's, which is done with COUNT(DISTINCT(user\_id)) Now, regarding your "this year AND in the years before", maybe you meant: "I want to see the number of users we interviewed this year, and the number of users we interviewed in the years prior to this year" then the query would be: ``` SELECT ( SELECT COUNT(DISTINCT user_id) FROM tbl_interviews WHERE date >= CONCAT(YEAR(current_date()), '-01-01') ) thisyear , ( SELECT COUNT(DISTINCT user_id) FROM tbl_interviews WHERE date < CONCAT(YEAR(current_date()), '-01-01') ) previousyears ```
2,060,651
This question is from Sheldon Axler's *Linear Algebra Done Right*, chapter 3, problem 29. Suppose $\phi \in \mathrm{L}(V,\mathbb{F})$. Suppose $u\in V$ is not in $\operatorname{null}\phi$. Prove that $$V=\operatorname{null}\phi \oplus \{au:a\in\mathbb{F}\}$$ I showed that the intersection $\operatorname{null} \phi \cap \{au:a\in\mathbb{F}\}$ has only the zero of $\mathbb{F}$. Now, it is left to show that every $v\in V$ can be written as a sum of two vectors one in $\operatorname{null} \phi$ while the other in $ \{au:a\in\mathbb{F}\}$. Let $v\in V$. So, there are two cases, one is where $T(v)=0$ which then $v\in \operatorname{null} \phi $ and $v=v+0u$. The second case is where $T(v)\neq 0$, but how one can deduce that $v\in\{au:a\in\mathbb{F}\}$?
2016/12/16
[ "https://math.stackexchange.com/questions/2060651", "https://math.stackexchange.com", "https://math.stackexchange.com/users/25654/" ]
Take $$f(x)= \begin{cases} 1, &\text{ if }x>0\\ 0, &\text{ if }x\le 0\\ \end{cases} $$ Then take $A\_n=(-\infty,0]\cup (1/n,\infty)$ $A\_n\subset A\_{n+1}$, $\bigcup\_{n=1}^{\infty}A\_n=\mathbb R$, $f$ is continuous on $A\_n$, but $f$ is not continuous on $\mathbb R$
Take an enumeration $q\_n$ of $\mathbb{Q}$, and define $A\_n:=\{q\_1,\cdots, q\_n\}$. Define $f:\mathbb{Q} \to \mathbb{R}$ by $f(x)=1$ if $x \neq 0$, and $f(x)=0$ if $x=0$.
2,060,651
This question is from Sheldon Axler's *Linear Algebra Done Right*, chapter 3, problem 29. Suppose $\phi \in \mathrm{L}(V,\mathbb{F})$. Suppose $u\in V$ is not in $\operatorname{null}\phi$. Prove that $$V=\operatorname{null}\phi \oplus \{au:a\in\mathbb{F}\}$$ I showed that the intersection $\operatorname{null} \phi \cap \{au:a\in\mathbb{F}\}$ has only the zero of $\mathbb{F}$. Now, it is left to show that every $v\in V$ can be written as a sum of two vectors one in $\operatorname{null} \phi$ while the other in $ \{au:a\in\mathbb{F}\}$. Let $v\in V$. So, there are two cases, one is where $T(v)=0$ which then $v\in \operatorname{null} \phi $ and $v=v+0u$. The second case is where $T(v)\neq 0$, but how one can deduce that $v\in\{au:a\in\mathbb{F}\}$?
2016/12/16
[ "https://math.stackexchange.com/questions/2060651", "https://math.stackexchange.com", "https://math.stackexchange.com/users/25654/" ]
Take $$f(x)= \begin{cases} 1, &\text{ if }x>0\\ 0, &\text{ if }x\le 0\\ \end{cases} $$ Then take $A\_n=(-\infty,0]\cup (1/n,\infty)$ $A\_n\subset A\_{n+1}$, $\bigcup\_{n=1}^{\infty}A\_n=\mathbb R$, $f$ is continuous on $A\_n$, but $f$ is not continuous on $\mathbb R$
Take a countable topological space $A=(B,\tau)$ whose finite subspaces are discrete but which is not itself discrete, e.g. $\mathbb{Q}$ with its usual topology. Take an enumeration of $B$, call it $b\_n$, and set $B\_n=\{ b\_1,\dots,b\_n \}$. Then *any* function from $A$ into any topological space is continuous on each $B\_n$. But since $A$ is not discrete, there is a topological space $C$ and a function $f : A \to C$ such that $f$ is not continuous. (Concretely, one may take $C$ to be the Sierpinski space and $f$ to be the indicator function of a singleton which is not open.)
61,213,903
Here is my working example ``` jsonData = { "3": { "map_id": "1", "marker_id": "3", "title": "Your title here", "address": "456 Example Ave", "desc": "Description", "pic": "", "icon": "", "linkd": "", "lat": "3.14", "lng": "-22.98", "anim": "0", "retina": "0", "category": "1", "infoopen": "0", "other_data": ["0"] }, "4": { "map_id": "1", "marker_id": "4", "title": "Title of Place", "address": "123 Main St, City, State", "desc": "insert description", "pic": "", "icon": "", "linkd": "", "lat": "1.23", "lng": "-4.56", "anim": "0", "retina": "0", "category": "0", "infoopen": "0", "other_data": ["0"] } ``` I am having such a hard time getting the `title` and `address` keys. Here is what I have tried: ``` for each in testJson: print(each["title"]) ``` and I get the following error `TypeError: string indices must be integers`. I don't understand why this isn't working. I have tried so many variations to get the key data, but I just can't get it to work. I can't really change the raw JSON either because my real JSON data is a huge file. I have looked on stackoverflow for a similarly formatted JSON example (e.g., [here](https://stackoverflow.com/questions/45334930/get-multiple-keys-from-json-in-python)) but have come up short. I assume there is something wrong with the way my JSON is formatted, because I have parsed JSON before with the above code without any problems.
2020/04/14
[ "https://Stackoverflow.com/questions/61213903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8585584/" ]
You have to take in account that by assigning `intervals[0]` to `int[] current`, you are not actually creating a new object. So your field `current` points to same object as `intervals[0]`. So when you call `res.add(current)`, you are actually adding the array stored in `intervals[0]` to the List and any changes made in the `current` field will also be done in the array added to the List (because it is the same object). And as far as the code tells, you are not doing any changes on the array in `else` block, that's maybe why no changes are visible :P. If you do not want the array changes to be reflected in the list, before adding the array to the list, create a new array object and initialize it for example this way: ``` int[] current = new int[intervals[0].length] for(int i = 0; i < intervals[0].length; ++i) current[i] = intervals[0][i] ``` For your second question, if you have your array initialized like this: ``` int[][] intervals = new int[size][]; for(int i = 0; i < size; ++i) intervals[i] = new int[size2]; ``` that means that you created a new array (new object) inside each cell of the array. Now. This code: ``` int[] current=intervals[0]; ``` Makes your variable `current` to point on the same object as `intervals[0]` does. So when you call `res.add(current);` you add the object `current` is pointing to to the list. So any changes made on `current`, or `intervals[0]` will also be reflected in the object stored in the list because it is the same object. But when you then assign another object to the `current`, when you call `current = interval;` you are just saying, that `current` now points to same object as `interval` does. That does not change the attributes of the original object `current` was pointing to (`intervals[0]`), current will be just pointing to another object.
A complete example of your program could help to answer to second part of your question. The central point is the pointer reference, and the resign of current has an impact to the second part of your question. The array is a pointer to the memory where the "integers are located". At first when you add the intervals[0] into the res list, actually you are inserting a pointer address to the same memory. When you switch/change the values to the current they're reflected to res, because they points to the same memory. You can think at `current[1]=Math.max(second,fourth);` as: Get the address memory of the array and change its value at position 1. At this point the previous value in res in updated, because the address is the same. You can think it like an alias, they act like streets that goes to the same target.
19,927,495
In a JavaScript regex, how would one turn e.g. ``` Check out http://example.com/foobar#123 ``` into ``` Check out <a href="http://example.com/foobar#123">example.com/foobar#123</a> ``` Thanks!
2013/11/12
[ "https://Stackoverflow.com/questions/19927495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34170/" ]
You can do this with an aggregate, project $toLower See: <http://docs.mongodb.org/manual/reference/operator/aggregation/toLower/> Something like: db.posts.aggregate([{$project:{date2:"$date",title:{$toLower:"$title"}}}
There is no easy way to do it efficiently with MongoDB. I suggest you maintain a lower case version of your fields (eg. normalizedMemberName), have them indexed and use them for your queries.
540,169
In a document I want to do a reference to a specific section of an online documentation. Here is the link: ``` \documentclass{report} \usepackage{hyperref} \begin{document} \href{https://raytracing-docs.nvidia.com/optix_6_0/guide_6_0/index.html\#host\#graph-nodes}{NVidia} \end{document} ``` As you can see there is two `#`. If don't escape both of them I've got this error: `! Illegal parameter number in definition of \Hy@tempa.` But if I escape both, the part of the link after second one is not taken into account. How can I make the link works properly?
2020/04/23
[ "https://tex.stackexchange.com/questions/540169", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/96122/" ]
Try this (hopefully there is nowhere a link with two consecutive hashes) Addition: while with the patch the "correct" link is in the pdf, the comments suggest that not every pdf viewer is able to handle this. So better look for an alternative link which doesn't use two hashes. ``` \documentclass{report} \usepackage{hyperref} \makeatletter \begingroup \catcode`\$=6 % \catcode`\#=12 % \gdef\href@$1{\expandafter\href@split$1###\\}% \gdef\href@split$1#$2##$3\\$4{% \hyper@@link{$1}{$2}{$4}% \endgroup }% \endgroup \makeatother \begin{document} \makeatother \href{https://raytracing-docs.nvidia.com/optix_6_0/guide_6_0/index.html#host#graph-nodes}{NVidia} \end{document} ```
Since I stumbled upon [the same problem](https://tex.stackexchange.com/questions/654824/two-consecutive-hash-caracters-in-url-href-in-latex-produce-incomplete-link-adre) and opened a [hyperref issue](https://github.com/latex3/hyperref/issues/254), I wanted to share the [developer's reply](https://github.com/latex3/hyperref/issues/254#issuecomment-1222642775) here: Apparently, more than one `#` character is not a correct URI and the solution is to replace all but the first `#` by `%23`, i.e., in your example ```latex \href{https://raytracing-docs.nvidia.com/optix_6_0/guide_6_0/index.html\#host\%23graph-nodes}{NVidia} ```
106,428
I'm using rwd package, Magento 1.8. I'm getting two blocks on left sidebar, Popular Tags and COMPANY block containing About Us, Contact us, Customer Service, Privacy Policy. I can remove Popuar Tags using `<remove name="tags_popular"/>` in local.xml but can't get rid of COMPANY block. Any suggestions how this can be done from local.xml? [![screenshot](https://i.stack.imgur.com/QgiTq.png)](https://i.stack.imgur.com/QgiTq.png)
2016/03/15
[ "https://magento.stackexchange.com/questions/106428", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/27312/" ]
You can do one of following to remove `company` block > > Choice 1 : From admin > > > Login to admin panel and navigate to : **`Admin > CMS > Static Blocks`** Find **`cms_menu`** in `Identifier` column. Open **`cms_menu`** block. Set block status to `Disabled`. Save CMS block. > > Choice:2 : using local.xml > > > ``` <layout version="0.1.0"> <default> <reference name="left"> <remove name="cms_menu"/> </reference> </default> </layout> ``` **Note:** Don't forget to clear cache. Hope this make sence to you
Just add this in your `theme->page.xml` default block: ``` <remove name="tags_popular"/> ``` **Or** Have a look into tag.xml where you will find this code, which you have to comment out: ``` <default> <!-- Mage_Tag --> <reference name="left"> <block type="tag/popular" name="tags_popular" template="tag/popular.phtm"> <action method="setTemplate"><template>tag/popular.phtml</template></action> </block> </reference> </default> ```
106,428
I'm using rwd package, Magento 1.8. I'm getting two blocks on left sidebar, Popular Tags and COMPANY block containing About Us, Contact us, Customer Service, Privacy Policy. I can remove Popuar Tags using `<remove name="tags_popular"/>` in local.xml but can't get rid of COMPANY block. Any suggestions how this can be done from local.xml? [![screenshot](https://i.stack.imgur.com/QgiTq.png)](https://i.stack.imgur.com/QgiTq.png)
2016/03/15
[ "https://magento.stackexchange.com/questions/106428", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/27312/" ]
You can do one of following to remove `company` block > > Choice 1 : From admin > > > Login to admin panel and navigate to : **`Admin > CMS > Static Blocks`** Find **`cms_menu`** in `Identifier` column. Open **`cms_menu`** block. Set block status to `Disabled`. Save CMS block. > > Choice:2 : using local.xml > > > ``` <layout version="0.1.0"> <default> <reference name="left"> <remove name="cms_menu"/> </reference> </default> </layout> ``` **Note:** Don't forget to clear cache. Hope this make sence to you
I haven't been using RWD much but looking at your screenshot. I would suggest you to enable block/template hint and check which template is called in that case. You can enable hint `template/block from System -> Configuration -> Developer -> Debug`. More reading: <http://alanstorm.com/find_magento_block_name> Make sure you also select Website name as described here: <https://stackoverflow.com/questions/24273443/in-magento-1-9-0-0-how-can-i-enable-template-path-hint> After you find template/block name, then go to your `layout/catalog.xml` and then search for that template and find the `name` field for that template. Then you can add below code to your local.xml ``` <remove name="your_name"/> ``` **Please replace `your_name` with the exact name you found in catalog.xml.** Hope this makes sense to you.

No dataset card yet

Downloads last month
2