qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
36,527,873
My Request looks something like this: User-Agent: Fiddler Content-Type: application/json; charset=utf-8 Host: localhost:12841 Content-Length: 4512954 Inside Body I have--> "*base64encoded String*" API Controller contains a method : ``` [HttpPost] public bool SaveProductImage([FromBody]string image) { if(image!=null) var result = productImageRules.StoreSingleImageOnDisk(image.ToString()); return result; } ```
2016/04/10
[ "https://Stackoverflow.com/questions/36527873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4711916/" ]
Be sure to allow the application to receive large POSTs in your **web.config**. Here's an example for **10mb**. For **ASP.NET**. ```xml <system.web> <httpRuntime targetFramework="4.6" maxRequestLength="102400" executionTimeout="3600" /> </system.web> ``` For **IIS** ```xml <security> <requestFiltering> <requestLimits maxAllowedContentLength="10485760" /> </requestFiltering> </security> ```
I fix it using this in the controller ``` [HttpPost] [RequestFormLimits(ValueLengthLimit = int.MaxValue)] ```
36,527,873
My Request looks something like this: User-Agent: Fiddler Content-Type: application/json; charset=utf-8 Host: localhost:12841 Content-Length: 4512954 Inside Body I have--> "*base64encoded String*" API Controller contains a method : ``` [HttpPost] public bool SaveProductImage([FromBody]string image) { if(image!=null) var result = productImageRules.StoreSingleImageOnDisk(image.ToString()); return result; } ```
2016/04/10
[ "https://Stackoverflow.com/questions/36527873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4711916/" ]
this is my solution. in your web.config(in server) ``` ---------- <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> <standardEndpoints> <webHttpEndpoint> <standardEndpoint name="" helpEnabled="true"automaticFormatSelectionEnabled="false" defaultOutgoingResponseFormat="Json" crossDomainScriptAccessEnabled="true" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" /> </webHttpEndpoint> </standardEndpoints> </system.serviceModel> ---------- <system.web.extensions> <scripting> <webServices> <jsonSerialization maxJsonLength="2147483647"/> </webServices> </scripting> </system.web.extensions> <system.web> <httpRuntime targetFramework="4.5" maxRequestLength="2097151" useFullyQualifiedRedirectUrl="true" executionTimeout="14400" /> ---------- <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="2147483647" /> </requestFiltering> </security> ---------- ``` good look
I fix it using this in the controller ``` [HttpPost] [RequestFormLimits(ValueLengthLimit = int.MaxValue)] ```
34,979,260
I am trying to apply a class to an HTML element based on a click event. This works fine when setting the class property for the child component's selector from the parent component's template as seen by the following snippet from the parent component: ```ts [class.bordered]='isSelected(item)' ``` This will appropriately set the style when that item is clicked. However, I want to set an inner HTML element's class in the child component based on the same sort of click event, here's the desired target for the style for the child component: ```ts template: ` <div class="This is where I really want to apply the style"> {{ item.val }} </div> ` ``` Is there a way to do this that is easily supported? Or is this considered a bad practice and I should design my components to avoid this sort of conditional styling situation? Full code: ```ts @Component({ selector: 'parent-component', directives: [ChildComponent], template: ` <child-component *ngFor='#item of items' [item]='item' (click)='clicked(item)' [class.bordered]='isSelected(item)'> </child-component> ` }) export class ParentComponent { items: Item[]; currentItem: item; constructor(private i: ItemService) { this.items = i.items; } clicked(item: Item): void { this.currentItem = item; } isSelected(item: Items): boolean { if (!item || !this.currentItem) { return false; } return item.val === this.currentItem.val; } } @Component({ selector: 'child-component', inputs: ['item'], template: ` <div class="This is where I really want to apply the style"> {{ item.val }} </div> ` }) export class ChildComponent {} ```
2016/01/24
[ "https://Stackoverflow.com/questions/34979260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1100640/" ]
I found a better way to solve this making good use of Angular2 features. Specifically instead of doing trickery with :host and CSS functionality you can just pass in a variable to the child component by changing: ``` [class.bordered]='isSelected(item)' ``` being set in the element of the child class change it to ``` [isBordered]='isSelected(item)' ``` Then on the div you'd like to apply the bordered class to in the template of the child component just add: ``` [ngClass]='{bordered: isBordered}' ``` Here is the full code with the change: ``` @Component({ selector: 'parent-component', directives: [ChildComponent], template: ` <child-component *ngFor='#item of items' [item]='item' (click)='clicked(item)' [isBordered]='isSelected(item)'> </child-component> ` }) export class ParentComponent { items: Item[]; currentItem: item; constructor(private i: ItemService) { this.items = i.items; } clicked(item: Item): void { this.currentItem = item; } isSelected(item: Items): boolean { if (!item || !this.currentItem) { return false; } return item.val === this.currentItem.val; } } @Component({ selector: 'child-component', inputs: ['item'], template: ` <div [ngClass]='{bordered: isBordered}'> {{ item.val }} </div> ` }) export class ChildComponent {} ```
Add a style to the `child-component` ```ts @Component({ selector: 'child-component', inputs: ['item'], template: ` <div class="This is where I really want to apply the style"> {{ item.val }} </div> `, styles: [` :host(.bordered) > div { // if this selector doesn't work use instead // child-component.bordered > div { border: 3px solid red; } `], }) export class ChildComponent {} ```
34,979,260
I am trying to apply a class to an HTML element based on a click event. This works fine when setting the class property for the child component's selector from the parent component's template as seen by the following snippet from the parent component: ```ts [class.bordered]='isSelected(item)' ``` This will appropriately set the style when that item is clicked. However, I want to set an inner HTML element's class in the child component based on the same sort of click event, here's the desired target for the style for the child component: ```ts template: ` <div class="This is where I really want to apply the style"> {{ item.val }} </div> ` ``` Is there a way to do this that is easily supported? Or is this considered a bad practice and I should design my components to avoid this sort of conditional styling situation? Full code: ```ts @Component({ selector: 'parent-component', directives: [ChildComponent], template: ` <child-component *ngFor='#item of items' [item]='item' (click)='clicked(item)' [class.bordered]='isSelected(item)'> </child-component> ` }) export class ParentComponent { items: Item[]; currentItem: item; constructor(private i: ItemService) { this.items = i.items; } clicked(item: Item): void { this.currentItem = item; } isSelected(item: Items): boolean { if (!item || !this.currentItem) { return false; } return item.val === this.currentItem.val; } } @Component({ selector: 'child-component', inputs: ['item'], template: ` <div class="This is where I really want to apply the style"> {{ item.val }} </div> ` }) export class ChildComponent {} ```
2016/01/24
[ "https://Stackoverflow.com/questions/34979260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1100640/" ]
Add a style to the `child-component` ```ts @Component({ selector: 'child-component', inputs: ['item'], template: ` <div class="This is where I really want to apply the style"> {{ item.val }} </div> `, styles: [` :host(.bordered) > div { // if this selector doesn't work use instead // child-component.bordered > div { border: 3px solid red; } `], }) export class ChildComponent {} ```
Something like this works very nicely for me: ``` import { Component } from '@angular/core'; @Component({ selector: 'my-app', styleUrls: [ './app.component.css' ], template: ` <button (click)='buttonClick1()' [disabled] = "btnDisabled" [ngStyle]="{'color': (btnDisabled)? 'gray': 'black'}"> {{btnText}} </button>` }) export class AppComponent { name = 'Angular'; btnText = 'Click me'; btnDisabled = false; buttonClick1() { this.btnDisabled = true; this.btnText = 'you clicked me'; setTimeout(() => { this.btnText = 'click me again'; this.btnDisabled = false }, 5000); } } ``` Here's a working example: <https://stackblitz.com/edit/example-conditional-disable-button?file=src%2Fapp%2Fapp.component.html>
34,979,260
I am trying to apply a class to an HTML element based on a click event. This works fine when setting the class property for the child component's selector from the parent component's template as seen by the following snippet from the parent component: ```ts [class.bordered]='isSelected(item)' ``` This will appropriately set the style when that item is clicked. However, I want to set an inner HTML element's class in the child component based on the same sort of click event, here's the desired target for the style for the child component: ```ts template: ` <div class="This is where I really want to apply the style"> {{ item.val }} </div> ` ``` Is there a way to do this that is easily supported? Or is this considered a bad practice and I should design my components to avoid this sort of conditional styling situation? Full code: ```ts @Component({ selector: 'parent-component', directives: [ChildComponent], template: ` <child-component *ngFor='#item of items' [item]='item' (click)='clicked(item)' [class.bordered]='isSelected(item)'> </child-component> ` }) export class ParentComponent { items: Item[]; currentItem: item; constructor(private i: ItemService) { this.items = i.items; } clicked(item: Item): void { this.currentItem = item; } isSelected(item: Items): boolean { if (!item || !this.currentItem) { return false; } return item.val === this.currentItem.val; } } @Component({ selector: 'child-component', inputs: ['item'], template: ` <div class="This is where I really want to apply the style"> {{ item.val }} </div> ` }) export class ChildComponent {} ```
2016/01/24
[ "https://Stackoverflow.com/questions/34979260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1100640/" ]
I found a better way to solve this making good use of Angular2 features. Specifically instead of doing trickery with :host and CSS functionality you can just pass in a variable to the child component by changing: ``` [class.bordered]='isSelected(item)' ``` being set in the element of the child class change it to ``` [isBordered]='isSelected(item)' ``` Then on the div you'd like to apply the bordered class to in the template of the child component just add: ``` [ngClass]='{bordered: isBordered}' ``` Here is the full code with the change: ``` @Component({ selector: 'parent-component', directives: [ChildComponent], template: ` <child-component *ngFor='#item of items' [item]='item' (click)='clicked(item)' [isBordered]='isSelected(item)'> </child-component> ` }) export class ParentComponent { items: Item[]; currentItem: item; constructor(private i: ItemService) { this.items = i.items; } clicked(item: Item): void { this.currentItem = item; } isSelected(item: Items): boolean { if (!item || !this.currentItem) { return false; } return item.val === this.currentItem.val; } } @Component({ selector: 'child-component', inputs: ['item'], template: ` <div [ngClass]='{bordered: isBordered}'> {{ item.val }} </div> ` }) export class ChildComponent {} ```
Something like this works very nicely for me: ``` import { Component } from '@angular/core'; @Component({ selector: 'my-app', styleUrls: [ './app.component.css' ], template: ` <button (click)='buttonClick1()' [disabled] = "btnDisabled" [ngStyle]="{'color': (btnDisabled)? 'gray': 'black'}"> {{btnText}} </button>` }) export class AppComponent { name = 'Angular'; btnText = 'Click me'; btnDisabled = false; buttonClick1() { this.btnDisabled = true; this.btnText = 'you clicked me'; setTimeout(() => { this.btnText = 'click me again'; this.btnDisabled = false }, 5000); } } ``` Here's a working example: <https://stackblitz.com/edit/example-conditional-disable-button?file=src%2Fapp%2Fapp.component.html>
44,054,266
I have a CMake project with next post\_build command: ``` add_custom_command(TARGET ncd_json POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/ncd.json $<TARGET_FILE_DIR:ncd_json>/ncd.json COMMENT "Copy ncd.json into binaries folder" ) ``` `ncd.json` is copied every time target build. But I really need to copy this file only if it is changed, and **even if target is already built** and this is the main problem. I think this question is not full duplicate of [CMake copy if original file changed](https://stackoverflow.com/questions/8434055/cmake-copy-if-original-file-changed/31635069) but supplements it.
2017/05/18
[ "https://Stackoverflow.com/questions/44054266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3743145/" ]
Something like the following should do close to what you want: ``` add_custom_target(copyJson ALL COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/ncd.json $<TARGET_FILE_DIR:ncd_json>/ncd.json ) add_dependencies(copyJson ncd_json) ``` It will only copy the file if it is different and it will still copy if the target is already built. Note, however, that it *won't* copy if you ask only for the target itself to be built. The above relies on you building the default target to get the file copied. You could always combine the approach in your question with the above and it would probably be robust for the cases you want.
While writing question I found a good answer [here](https://stackoverflow.com/a/31635069/3743145) ``` configure_file(input_file output_file COPYONLY) ``` or in my case ``` configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/ncd.json ${CMAKE_CURRENT_BINARY_DIR}/ncd.json COPYONLY ) ``` But I still not sure if it copies `ncd.json` every time or not... See also [documentation](https://cmake.org/cmake/help/v3.0/command/configure_file.html).
13,021,825
I want to change properties of another object, when a method is called in another class. The code to change the properties of this object sits in a method of the first class, and works when calling it from it's own class, but when called from the other class the object in the method returns nil. *Here is the code:* **ViewController.h** ``` @interface ViewController : UIViewController { UIView *menuView; //the object } @property (nonatomic, retain) IBOutlet UIView *menuView; -(void)closeMenu; //the method @end ``` **ViewController.m** ``` @implementation ViewController @synthesize menuView; -(void)closeMenu{ [menuView setFrame:CGRectMake(menuView.frame.origin.x, -menuView.frame.size.height, menuView.frame.size.width, menuView.frame.size.height)]; NSLog(@"%f", menuView.frame.size.height); //returns height when method is called from it's own class. But returns 0 (nil) when called from the other class. } ``` **SDNestedTableViewController.h** (nothing too important, but might help?) ``` @interface SDMenuViewController : SDNestedTableViewController{ } ``` **SDNestedTableViewController.m** ``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = [[[ViewController alloc] init] autorelease]; SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); [firstViewController closeMenu]; //called from other class break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } ```
2012/10/23
[ "https://Stackoverflow.com/questions/13021825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1265071/" ]
EDIT 2: Well, you shipped your code over to me, so now I can no longer say that I don't have enough information to solve your problem. Let's see. Now I see that your ViewController is the rootViewController of your app, like so: ``` - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; // Override point for customization after application launch. self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease]; self.window.rootViewController = self.viewController; [self.window makeKeyAndVisible]; return YES; } ``` Good, now how does the ViewController relate to your SDNestedTableViewController? You have this in your ViewController's viewDidLoad: ``` - (void)viewDidLoad { [super viewDidLoad]; SDMenuViewController *mvc = [[[SDMenuViewController alloc] initWithNibName:@"SDNestedTableView" bundle:nil] autorelease]; [self addChildViewController:mvc]; [mvc didMoveToParentViewController:self]; [menuView addSubview:mvc.view]; // Some other stuff with gesture recognizers I'm omitting... [self openMenu]; } ``` Alright, so it looks like SDMenuViewController is the child of ViewController. Now, you have a method in SDMenuViewController called item:subItemDidChange: ``` - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease]; SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); //close the menuView [firstViewController closeMenu]; break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } ``` So, you want the reference back to the *existing* ViewController object, right? Because right there you're making another one. So, you can do this: ``` ViewController *firstViewController = self.parentViewController; ``` That gets you a reference to SDMenuViewController's parent, which is the instance of ViewController. This property is set when you do your `addChildViewController:` call. --- Okay, this is confusing though: In your post, you say that your `item:subItemDidChange:` method is in SDNestedTableViewController, but in the code you sent me it's in the SDMenuViewController. In the SDNestedTableViewController, I found this method: ``` - (void) mainItem:(SDGroupCell *)item subItemDidChange: (SDSelectableCell *)subItem forTap:(BOOL)tapped { if(delegate != nil && [delegate respondsToSelector:@selector(item:subItemDidChange:)] ) { [delegate performSelector:@selector(item:subItemDidChange:) withObject:item withObject:subItem]; } } ``` So it looks like you're not using the same code as in the original post, but close enough, whatever. --- Now, if you want to get a reference to the ViewController instance from *anywhere* in the app, not just your SDMenuViewController (which happens to be the child of the ViewController instance) you should use @Mathew Varghese's [answer](https://stackoverflow.com/a/13118017/700471). Here's a restatement of this method: 1. Add the line `+ (AppDelegate *)instance;` to your AppDelegate.h file. 2. Add the following method to your AppDelegate.m file. Like so: ``` + (AppDelegate *)instance { AppDelegate *dg = [UIApplication sharedApplication].delegate; return dg; } ``` Then, in whatever object you want that reference, you `#import AppDelegate.h` and say `ViewController *vc = AppDelegate.instance.firstViewController;` Anyway, it's just another way of saying what Mathew mentioned earlier.
``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ``` > > // why are we allocating this object here, if it is only required in case Checked : > > > ``` ViewController *firstViewController = [[[ViewController alloc] init] autorelease]; SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); [firstViewController closeMenu]; //called from other class break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } ``` Change it to ``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ``` > > // why are we allocating this object here, if it is only required in case Checked : > > > ``` SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); // here no need to put object in autorelease mode. ViewController *firstViewController = [[ViewController alloc] init]; [firstViewController closeMenu]; //called from other class [firstViewController release]; break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } ```
13,021,825
I want to change properties of another object, when a method is called in another class. The code to change the properties of this object sits in a method of the first class, and works when calling it from it's own class, but when called from the other class the object in the method returns nil. *Here is the code:* **ViewController.h** ``` @interface ViewController : UIViewController { UIView *menuView; //the object } @property (nonatomic, retain) IBOutlet UIView *menuView; -(void)closeMenu; //the method @end ``` **ViewController.m** ``` @implementation ViewController @synthesize menuView; -(void)closeMenu{ [menuView setFrame:CGRectMake(menuView.frame.origin.x, -menuView.frame.size.height, menuView.frame.size.width, menuView.frame.size.height)]; NSLog(@"%f", menuView.frame.size.height); //returns height when method is called from it's own class. But returns 0 (nil) when called from the other class. } ``` **SDNestedTableViewController.h** (nothing too important, but might help?) ``` @interface SDMenuViewController : SDNestedTableViewController{ } ``` **SDNestedTableViewController.m** ``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = [[[ViewController alloc] init] autorelease]; SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); [firstViewController closeMenu]; //called from other class break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } ```
2012/10/23
[ "https://Stackoverflow.com/questions/13021825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1265071/" ]
I think this may help you. At Your `AppDelegate` class, you have to declare an object of `ViewController` class. Make it as a property of the `YourAppDelegate` class. like below. (This would import `ViewController` class and creates a shared object of `YourAppDelegate` class so that you can access the members of `YourAppDelegate` class globally by simply importing the `YourAppDelegate.h`). ``` #import "ViewController.h" #define UIAppDelegate ((YourAppDelegate *)[UIApplication sharedApplication].delegate) @interface YourAppDelegate : NSObject <UIApplicationDelegate> { ViewController *objViewController; } @property (nonatomic, retain) ViewController *objViewController; @end ``` And synthesize the property at `YourAppDelegate.m` file. ``` @implementation YourAppDelegate @synthesize objViewController; @end ``` Then the tricky part is, you have to backup the object of `ViewController` class in the `YourAppDelegate` class at the time you are loading the `ViewController` class. For that first import the `YourAppDelegate.h` in the `ViewController.h` class and at the `ViewController.m` implement `viewWillAppear:` delegate as follows. ``` - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; UIAppDelegate.objViewController = self; } ``` Then at `SDNestedTableViewController.m`, ``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = (ViewController *)UIAppDelegate.objViewController; if(firstViewController && [firstViewController isKindOfClass:[ViewController class]]) { SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); [firstViewController closeMenu]; //called from other class break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } } ``` Try this way. I am not saying this as the right way but, this should works. Glad if this helps you.
the problem is: ``` - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = [[[ViewController alloc] init] autorelease]; ... [firstViewController closeMenu]; } ``` When you call `closeMenu` from there, it is never initialized, because not enough time has passed to initialize `view` of view controller, `viewDidLoad` method of your `firstViewController` is not called at this point either. `menuView` is not created from nib either, so this is the reason why it is `nil`. Maybe for some reason there might be a delay long enough so `menuView` is created, but this is not how you should do things in iOS. So, if you don't want to show your `menuView`, just add some boolean value to your `firstViewController` and instead of `closeMenu` do: ``` firstViewController.shouldCloseMenu = YES; ``` Then in your `ViewController` in `viewDidLoad` method do something like: ``` if (self.shouldCloseMenu ) { [self closeMenu]; } ``` Maybe this is not the best way to do it, but now you have an idea how it suppose to work.
13,021,825
I want to change properties of another object, when a method is called in another class. The code to change the properties of this object sits in a method of the first class, and works when calling it from it's own class, but when called from the other class the object in the method returns nil. *Here is the code:* **ViewController.h** ``` @interface ViewController : UIViewController { UIView *menuView; //the object } @property (nonatomic, retain) IBOutlet UIView *menuView; -(void)closeMenu; //the method @end ``` **ViewController.m** ``` @implementation ViewController @synthesize menuView; -(void)closeMenu{ [menuView setFrame:CGRectMake(menuView.frame.origin.x, -menuView.frame.size.height, menuView.frame.size.width, menuView.frame.size.height)]; NSLog(@"%f", menuView.frame.size.height); //returns height when method is called from it's own class. But returns 0 (nil) when called from the other class. } ``` **SDNestedTableViewController.h** (nothing too important, but might help?) ``` @interface SDMenuViewController : SDNestedTableViewController{ } ``` **SDNestedTableViewController.m** ``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = [[[ViewController alloc] init] autorelease]; SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); [firstViewController closeMenu]; //called from other class break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } ```
2012/10/23
[ "https://Stackoverflow.com/questions/13021825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1265071/" ]
What you posted looks like: ``` -(void)closeMenu{ // menuView is never initialized, == nil [nil setFrame:CGRectMake(0, -0, 0, 0)]; NSLog(@"%f", 0); //returns height when method is called from it's own class. But returns 0 (nil) when called from the other class. } ``` So you are doing `NSLog(@"%f", 0);`. If you do load the view by accessing the `view` property, the menuView will be initialized by IB rules. For the details of viewController view loading/unloading see the [reference docs](http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/ViewLoadingandUnloading/ViewLoadingandUnloading.html).
try to remove **UIView \*menuView; //the object** from the interface file ``` @interface ViewController : UIViewController { // try to remove this line UIView *menuView; //the object } ``` and update this method ``` -(void)closeMenu{ [self.menuView setFrame:CGRectMake(self.menuView.frame.origin.x, -self.menuView.frame.size.height, self.menuView.frame.size.width, self.menuView.frame.size.height)]; NSLog(@"%f", self.menuView.frame.size.height); } ```
13,021,825
I want to change properties of another object, when a method is called in another class. The code to change the properties of this object sits in a method of the first class, and works when calling it from it's own class, but when called from the other class the object in the method returns nil. *Here is the code:* **ViewController.h** ``` @interface ViewController : UIViewController { UIView *menuView; //the object } @property (nonatomic, retain) IBOutlet UIView *menuView; -(void)closeMenu; //the method @end ``` **ViewController.m** ``` @implementation ViewController @synthesize menuView; -(void)closeMenu{ [menuView setFrame:CGRectMake(menuView.frame.origin.x, -menuView.frame.size.height, menuView.frame.size.width, menuView.frame.size.height)]; NSLog(@"%f", menuView.frame.size.height); //returns height when method is called from it's own class. But returns 0 (nil) when called from the other class. } ``` **SDNestedTableViewController.h** (nothing too important, but might help?) ``` @interface SDMenuViewController : SDNestedTableViewController{ } ``` **SDNestedTableViewController.m** ``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = [[[ViewController alloc] init] autorelease]; SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); [firstViewController closeMenu]; //called from other class break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } ```
2012/10/23
[ "https://Stackoverflow.com/questions/13021825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1265071/" ]
I think this may help you. At Your `AppDelegate` class, you have to declare an object of `ViewController` class. Make it as a property of the `YourAppDelegate` class. like below. (This would import `ViewController` class and creates a shared object of `YourAppDelegate` class so that you can access the members of `YourAppDelegate` class globally by simply importing the `YourAppDelegate.h`). ``` #import "ViewController.h" #define UIAppDelegate ((YourAppDelegate *)[UIApplication sharedApplication].delegate) @interface YourAppDelegate : NSObject <UIApplicationDelegate> { ViewController *objViewController; } @property (nonatomic, retain) ViewController *objViewController; @end ``` And synthesize the property at `YourAppDelegate.m` file. ``` @implementation YourAppDelegate @synthesize objViewController; @end ``` Then the tricky part is, you have to backup the object of `ViewController` class in the `YourAppDelegate` class at the time you are loading the `ViewController` class. For that first import the `YourAppDelegate.h` in the `ViewController.h` class and at the `ViewController.m` implement `viewWillAppear:` delegate as follows. ``` - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; UIAppDelegate.objViewController = self; } ``` Then at `SDNestedTableViewController.m`, ``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = (ViewController *)UIAppDelegate.objViewController; if(firstViewController && [firstViewController isKindOfClass:[ViewController class]]) { SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); [firstViewController closeMenu]; //called from other class break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } } ``` Try this way. I am not saying this as the right way but, this should works. Glad if this helps you.
try to remove **UIView \*menuView; //the object** from the interface file ``` @interface ViewController : UIViewController { // try to remove this line UIView *menuView; //the object } ``` and update this method ``` -(void)closeMenu{ [self.menuView setFrame:CGRectMake(self.menuView.frame.origin.x, -self.menuView.frame.size.height, self.menuView.frame.size.width, self.menuView.frame.size.height)]; NSLog(@"%f", self.menuView.frame.size.height); } ```
13,021,825
I want to change properties of another object, when a method is called in another class. The code to change the properties of this object sits in a method of the first class, and works when calling it from it's own class, but when called from the other class the object in the method returns nil. *Here is the code:* **ViewController.h** ``` @interface ViewController : UIViewController { UIView *menuView; //the object } @property (nonatomic, retain) IBOutlet UIView *menuView; -(void)closeMenu; //the method @end ``` **ViewController.m** ``` @implementation ViewController @synthesize menuView; -(void)closeMenu{ [menuView setFrame:CGRectMake(menuView.frame.origin.x, -menuView.frame.size.height, menuView.frame.size.width, menuView.frame.size.height)]; NSLog(@"%f", menuView.frame.size.height); //returns height when method is called from it's own class. But returns 0 (nil) when called from the other class. } ``` **SDNestedTableViewController.h** (nothing too important, but might help?) ``` @interface SDMenuViewController : SDNestedTableViewController{ } ``` **SDNestedTableViewController.m** ``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = [[[ViewController alloc] init] autorelease]; SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); [firstViewController closeMenu]; //called from other class break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } ```
2012/10/23
[ "https://Stackoverflow.com/questions/13021825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1265071/" ]
I think this may help you. At Your `AppDelegate` class, you have to declare an object of `ViewController` class. Make it as a property of the `YourAppDelegate` class. like below. (This would import `ViewController` class and creates a shared object of `YourAppDelegate` class so that you can access the members of `YourAppDelegate` class globally by simply importing the `YourAppDelegate.h`). ``` #import "ViewController.h" #define UIAppDelegate ((YourAppDelegate *)[UIApplication sharedApplication].delegate) @interface YourAppDelegate : NSObject <UIApplicationDelegate> { ViewController *objViewController; } @property (nonatomic, retain) ViewController *objViewController; @end ``` And synthesize the property at `YourAppDelegate.m` file. ``` @implementation YourAppDelegate @synthesize objViewController; @end ``` Then the tricky part is, you have to backup the object of `ViewController` class in the `YourAppDelegate` class at the time you are loading the `ViewController` class. For that first import the `YourAppDelegate.h` in the `ViewController.h` class and at the `ViewController.m` implement `viewWillAppear:` delegate as follows. ``` - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; UIAppDelegate.objViewController = self; } ``` Then at `SDNestedTableViewController.m`, ``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = (ViewController *)UIAppDelegate.objViewController; if(firstViewController && [firstViewController isKindOfClass:[ViewController class]]) { SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); [firstViewController closeMenu]; //called from other class break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } } ``` Try this way. I am not saying this as the right way but, this should works. Glad if this helps you.
There is a difference between `alloc-init`'ing a ViewController and `alloc-init`'ing that view controller's properties. Regarding your second example (calling from another class). Your current code indicates that you `alloc-init` firstViewController, but then don't do anything with it. Assuming you have not overriden your ViewController's `init` method, its properties and iVars should be `nil` (or undefined at worst). You need to `alloc-init` your `firstViewController.menuView` first. I.e: ``` firstViewController.menuView = [[UIView alloc] initWithFrame]; // Don't do this. ``` The problem with this approach is that you're setting up firstViewController's properties form another class, and that's generally fairly average design practice. This required setup would usually happen in `viewDidLoad` but because you haven't done anything with firstViewController yet, it never gets called. In contrast, when you call `closeMenu` from its own View Controller, the odds are you are actually doing something with the view and viewDidLoad (or wherever `menuView = [[UIView alloc] init];`is found) is called first, thus initialising your menuView object. You need to ensure that your menuView object is initialised first before you try and do anything with it, just initialising the View Controller that contains it is not enough.
13,021,825
I want to change properties of another object, when a method is called in another class. The code to change the properties of this object sits in a method of the first class, and works when calling it from it's own class, but when called from the other class the object in the method returns nil. *Here is the code:* **ViewController.h** ``` @interface ViewController : UIViewController { UIView *menuView; //the object } @property (nonatomic, retain) IBOutlet UIView *menuView; -(void)closeMenu; //the method @end ``` **ViewController.m** ``` @implementation ViewController @synthesize menuView; -(void)closeMenu{ [menuView setFrame:CGRectMake(menuView.frame.origin.x, -menuView.frame.size.height, menuView.frame.size.width, menuView.frame.size.height)]; NSLog(@"%f", menuView.frame.size.height); //returns height when method is called from it's own class. But returns 0 (nil) when called from the other class. } ``` **SDNestedTableViewController.h** (nothing too important, but might help?) ``` @interface SDMenuViewController : SDNestedTableViewController{ } ``` **SDNestedTableViewController.m** ``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = [[[ViewController alloc] init] autorelease]; SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); [firstViewController closeMenu]; //called from other class break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } ```
2012/10/23
[ "https://Stackoverflow.com/questions/13021825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1265071/" ]
EDIT 2: Well, you shipped your code over to me, so now I can no longer say that I don't have enough information to solve your problem. Let's see. Now I see that your ViewController is the rootViewController of your app, like so: ``` - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; // Override point for customization after application launch. self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease]; self.window.rootViewController = self.viewController; [self.window makeKeyAndVisible]; return YES; } ``` Good, now how does the ViewController relate to your SDNestedTableViewController? You have this in your ViewController's viewDidLoad: ``` - (void)viewDidLoad { [super viewDidLoad]; SDMenuViewController *mvc = [[[SDMenuViewController alloc] initWithNibName:@"SDNestedTableView" bundle:nil] autorelease]; [self addChildViewController:mvc]; [mvc didMoveToParentViewController:self]; [menuView addSubview:mvc.view]; // Some other stuff with gesture recognizers I'm omitting... [self openMenu]; } ``` Alright, so it looks like SDMenuViewController is the child of ViewController. Now, you have a method in SDMenuViewController called item:subItemDidChange: ``` - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease]; SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); //close the menuView [firstViewController closeMenu]; break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } ``` So, you want the reference back to the *existing* ViewController object, right? Because right there you're making another one. So, you can do this: ``` ViewController *firstViewController = self.parentViewController; ``` That gets you a reference to SDMenuViewController's parent, which is the instance of ViewController. This property is set when you do your `addChildViewController:` call. --- Okay, this is confusing though: In your post, you say that your `item:subItemDidChange:` method is in SDNestedTableViewController, but in the code you sent me it's in the SDMenuViewController. In the SDNestedTableViewController, I found this method: ``` - (void) mainItem:(SDGroupCell *)item subItemDidChange: (SDSelectableCell *)subItem forTap:(BOOL)tapped { if(delegate != nil && [delegate respondsToSelector:@selector(item:subItemDidChange:)] ) { [delegate performSelector:@selector(item:subItemDidChange:) withObject:item withObject:subItem]; } } ``` So it looks like you're not using the same code as in the original post, but close enough, whatever. --- Now, if you want to get a reference to the ViewController instance from *anywhere* in the app, not just your SDMenuViewController (which happens to be the child of the ViewController instance) you should use @Mathew Varghese's [answer](https://stackoverflow.com/a/13118017/700471). Here's a restatement of this method: 1. Add the line `+ (AppDelegate *)instance;` to your AppDelegate.h file. 2. Add the following method to your AppDelegate.m file. Like so: ``` + (AppDelegate *)instance { AppDelegate *dg = [UIApplication sharedApplication].delegate; return dg; } ``` Then, in whatever object you want that reference, you `#import AppDelegate.h` and say `ViewController *vc = AppDelegate.instance.firstViewController;` Anyway, it's just another way of saying what Mathew mentioned earlier.
I suggest you use this: ``` if(menuView) { [menuView setFrame:CGRectMake(menuView.frame.origin.x, -menuView.frame.size.height, menuView.frame.size.width, menuView.frame.size.height)]; } else { NSLog(@"menuView is nil"); } ```
13,021,825
I want to change properties of another object, when a method is called in another class. The code to change the properties of this object sits in a method of the first class, and works when calling it from it's own class, but when called from the other class the object in the method returns nil. *Here is the code:* **ViewController.h** ``` @interface ViewController : UIViewController { UIView *menuView; //the object } @property (nonatomic, retain) IBOutlet UIView *menuView; -(void)closeMenu; //the method @end ``` **ViewController.m** ``` @implementation ViewController @synthesize menuView; -(void)closeMenu{ [menuView setFrame:CGRectMake(menuView.frame.origin.x, -menuView.frame.size.height, menuView.frame.size.width, menuView.frame.size.height)]; NSLog(@"%f", menuView.frame.size.height); //returns height when method is called from it's own class. But returns 0 (nil) when called from the other class. } ``` **SDNestedTableViewController.h** (nothing too important, but might help?) ``` @interface SDMenuViewController : SDNestedTableViewController{ } ``` **SDNestedTableViewController.m** ``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = [[[ViewController alloc] init] autorelease]; SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); [firstViewController closeMenu]; //called from other class break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } ```
2012/10/23
[ "https://Stackoverflow.com/questions/13021825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1265071/" ]
I think this may help you. At Your `AppDelegate` class, you have to declare an object of `ViewController` class. Make it as a property of the `YourAppDelegate` class. like below. (This would import `ViewController` class and creates a shared object of `YourAppDelegate` class so that you can access the members of `YourAppDelegate` class globally by simply importing the `YourAppDelegate.h`). ``` #import "ViewController.h" #define UIAppDelegate ((YourAppDelegate *)[UIApplication sharedApplication].delegate) @interface YourAppDelegate : NSObject <UIApplicationDelegate> { ViewController *objViewController; } @property (nonatomic, retain) ViewController *objViewController; @end ``` And synthesize the property at `YourAppDelegate.m` file. ``` @implementation YourAppDelegate @synthesize objViewController; @end ``` Then the tricky part is, you have to backup the object of `ViewController` class in the `YourAppDelegate` class at the time you are loading the `ViewController` class. For that first import the `YourAppDelegate.h` in the `ViewController.h` class and at the `ViewController.m` implement `viewWillAppear:` delegate as follows. ``` - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; UIAppDelegate.objViewController = self; } ``` Then at `SDNestedTableViewController.m`, ``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = (ViewController *)UIAppDelegate.objViewController; if(firstViewController && [firstViewController isKindOfClass:[ViewController class]]) { SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); [firstViewController closeMenu]; //called from other class break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } } ``` Try this way. I am not saying this as the right way but, this should works. Glad if this helps you.
I suggest you use this: ``` if(menuView) { [menuView setFrame:CGRectMake(menuView.frame.origin.x, -menuView.frame.size.height, menuView.frame.size.width, menuView.frame.size.height)]; } else { NSLog(@"menuView is nil"); } ```
13,021,825
I want to change properties of another object, when a method is called in another class. The code to change the properties of this object sits in a method of the first class, and works when calling it from it's own class, but when called from the other class the object in the method returns nil. *Here is the code:* **ViewController.h** ``` @interface ViewController : UIViewController { UIView *menuView; //the object } @property (nonatomic, retain) IBOutlet UIView *menuView; -(void)closeMenu; //the method @end ``` **ViewController.m** ``` @implementation ViewController @synthesize menuView; -(void)closeMenu{ [menuView setFrame:CGRectMake(menuView.frame.origin.x, -menuView.frame.size.height, menuView.frame.size.width, menuView.frame.size.height)]; NSLog(@"%f", menuView.frame.size.height); //returns height when method is called from it's own class. But returns 0 (nil) when called from the other class. } ``` **SDNestedTableViewController.h** (nothing too important, but might help?) ``` @interface SDMenuViewController : SDNestedTableViewController{ } ``` **SDNestedTableViewController.m** ``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = [[[ViewController alloc] init] autorelease]; SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); [firstViewController closeMenu]; //called from other class break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } ```
2012/10/23
[ "https://Stackoverflow.com/questions/13021825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1265071/" ]
I think this may help you. At Your `AppDelegate` class, you have to declare an object of `ViewController` class. Make it as a property of the `YourAppDelegate` class. like below. (This would import `ViewController` class and creates a shared object of `YourAppDelegate` class so that you can access the members of `YourAppDelegate` class globally by simply importing the `YourAppDelegate.h`). ``` #import "ViewController.h" #define UIAppDelegate ((YourAppDelegate *)[UIApplication sharedApplication].delegate) @interface YourAppDelegate : NSObject <UIApplicationDelegate> { ViewController *objViewController; } @property (nonatomic, retain) ViewController *objViewController; @end ``` And synthesize the property at `YourAppDelegate.m` file. ``` @implementation YourAppDelegate @synthesize objViewController; @end ``` Then the tricky part is, you have to backup the object of `ViewController` class in the `YourAppDelegate` class at the time you are loading the `ViewController` class. For that first import the `YourAppDelegate.h` in the `ViewController.h` class and at the `ViewController.m` implement `viewWillAppear:` delegate as follows. ``` - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; UIAppDelegate.objViewController = self; } ``` Then at `SDNestedTableViewController.m`, ``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = (ViewController *)UIAppDelegate.objViewController; if(firstViewController && [firstViewController isKindOfClass:[ViewController class]]) { SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); [firstViewController closeMenu]; //called from other class break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } } ``` Try this way. I am not saying this as the right way but, this should works. Glad if this helps you.
``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ``` > > // why are we allocating this object here, if it is only required in case Checked : > > > ``` ViewController *firstViewController = [[[ViewController alloc] init] autorelease]; SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); [firstViewController closeMenu]; //called from other class break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } ``` Change it to ``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ``` > > // why are we allocating this object here, if it is only required in case Checked : > > > ``` SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); // here no need to put object in autorelease mode. ViewController *firstViewController = [[ViewController alloc] init]; [firstViewController closeMenu]; //called from other class [firstViewController release]; break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } ```
13,021,825
I want to change properties of another object, when a method is called in another class. The code to change the properties of this object sits in a method of the first class, and works when calling it from it's own class, but when called from the other class the object in the method returns nil. *Here is the code:* **ViewController.h** ``` @interface ViewController : UIViewController { UIView *menuView; //the object } @property (nonatomic, retain) IBOutlet UIView *menuView; -(void)closeMenu; //the method @end ``` **ViewController.m** ``` @implementation ViewController @synthesize menuView; -(void)closeMenu{ [menuView setFrame:CGRectMake(menuView.frame.origin.x, -menuView.frame.size.height, menuView.frame.size.width, menuView.frame.size.height)]; NSLog(@"%f", menuView.frame.size.height); //returns height when method is called from it's own class. But returns 0 (nil) when called from the other class. } ``` **SDNestedTableViewController.h** (nothing too important, but might help?) ``` @interface SDMenuViewController : SDNestedTableViewController{ } ``` **SDNestedTableViewController.m** ``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = [[[ViewController alloc] init] autorelease]; SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); [firstViewController closeMenu]; //called from other class break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } ```
2012/10/23
[ "https://Stackoverflow.com/questions/13021825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1265071/" ]
the problem is: ``` - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = [[[ViewController alloc] init] autorelease]; ... [firstViewController closeMenu]; } ``` When you call `closeMenu` from there, it is never initialized, because not enough time has passed to initialize `view` of view controller, `viewDidLoad` method of your `firstViewController` is not called at this point either. `menuView` is not created from nib either, so this is the reason why it is `nil`. Maybe for some reason there might be a delay long enough so `menuView` is created, but this is not how you should do things in iOS. So, if you don't want to show your `menuView`, just add some boolean value to your `firstViewController` and instead of `closeMenu` do: ``` firstViewController.shouldCloseMenu = YES; ``` Then in your `ViewController` in `viewDidLoad` method do something like: ``` if (self.shouldCloseMenu ) { [self closeMenu]; } ``` Maybe this is not the best way to do it, but now you have an idea how it suppose to work.
``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ``` > > // why are we allocating this object here, if it is only required in case Checked : > > > ``` ViewController *firstViewController = [[[ViewController alloc] init] autorelease]; SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); [firstViewController closeMenu]; //called from other class break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } ``` Change it to ``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ``` > > // why are we allocating this object here, if it is only required in case Checked : > > > ``` SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); // here no need to put object in autorelease mode. ViewController *firstViewController = [[ViewController alloc] init]; [firstViewController closeMenu]; //called from other class [firstViewController release]; break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } ```
13,021,825
I want to change properties of another object, when a method is called in another class. The code to change the properties of this object sits in a method of the first class, and works when calling it from it's own class, but when called from the other class the object in the method returns nil. *Here is the code:* **ViewController.h** ``` @interface ViewController : UIViewController { UIView *menuView; //the object } @property (nonatomic, retain) IBOutlet UIView *menuView; -(void)closeMenu; //the method @end ``` **ViewController.m** ``` @implementation ViewController @synthesize menuView; -(void)closeMenu{ [menuView setFrame:CGRectMake(menuView.frame.origin.x, -menuView.frame.size.height, menuView.frame.size.width, menuView.frame.size.height)]; NSLog(@"%f", menuView.frame.size.height); //returns height when method is called from it's own class. But returns 0 (nil) when called from the other class. } ``` **SDNestedTableViewController.h** (nothing too important, but might help?) ``` @interface SDMenuViewController : SDNestedTableViewController{ } ``` **SDNestedTableViewController.m** ``` #import "SDMenuViewController.h" #import "ViewController.h" - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = [[[ViewController alloc] init] autorelease]; SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); [firstViewController closeMenu]; //called from other class break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } ```
2012/10/23
[ "https://Stackoverflow.com/questions/13021825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1265071/" ]
EDIT 2: Well, you shipped your code over to me, so now I can no longer say that I don't have enough information to solve your problem. Let's see. Now I see that your ViewController is the rootViewController of your app, like so: ``` - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; // Override point for customization after application launch. self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease]; self.window.rootViewController = self.viewController; [self.window makeKeyAndVisible]; return YES; } ``` Good, now how does the ViewController relate to your SDNestedTableViewController? You have this in your ViewController's viewDidLoad: ``` - (void)viewDidLoad { [super viewDidLoad]; SDMenuViewController *mvc = [[[SDMenuViewController alloc] initWithNibName:@"SDNestedTableView" bundle:nil] autorelease]; [self addChildViewController:mvc]; [mvc didMoveToParentViewController:self]; [menuView addSubview:mvc.view]; // Some other stuff with gesture recognizers I'm omitting... [self openMenu]; } ``` Alright, so it looks like SDMenuViewController is the child of ViewController. Now, you have a method in SDMenuViewController called item:subItemDidChange: ``` - (void) item:(SDGroupCell *)item subItemDidChange:(SDSelectableCell *)subItem { ViewController *firstViewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease]; SelectableCellState state = subItem.selectableCellState; NSIndexPath *indexPath = [item.subTable indexPathForCell:subItem]; switch (state) { case Checked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Checked\"", indexPath); //close the menuView [firstViewController closeMenu]; break; case Unchecked: NSLog(@"Changed Sub Item at indexPath:%@ to state \"Unchecked\"", indexPath); break; default: break; } } ``` So, you want the reference back to the *existing* ViewController object, right? Because right there you're making another one. So, you can do this: ``` ViewController *firstViewController = self.parentViewController; ``` That gets you a reference to SDMenuViewController's parent, which is the instance of ViewController. This property is set when you do your `addChildViewController:` call. --- Okay, this is confusing though: In your post, you say that your `item:subItemDidChange:` method is in SDNestedTableViewController, but in the code you sent me it's in the SDMenuViewController. In the SDNestedTableViewController, I found this method: ``` - (void) mainItem:(SDGroupCell *)item subItemDidChange: (SDSelectableCell *)subItem forTap:(BOOL)tapped { if(delegate != nil && [delegate respondsToSelector:@selector(item:subItemDidChange:)] ) { [delegate performSelector:@selector(item:subItemDidChange:) withObject:item withObject:subItem]; } } ``` So it looks like you're not using the same code as in the original post, but close enough, whatever. --- Now, if you want to get a reference to the ViewController instance from *anywhere* in the app, not just your SDMenuViewController (which happens to be the child of the ViewController instance) you should use @Mathew Varghese's [answer](https://stackoverflow.com/a/13118017/700471). Here's a restatement of this method: 1. Add the line `+ (AppDelegate *)instance;` to your AppDelegate.h file. 2. Add the following method to your AppDelegate.m file. Like so: ``` + (AppDelegate *)instance { AppDelegate *dg = [UIApplication sharedApplication].delegate; return dg; } ``` Then, in whatever object you want that reference, you `#import AppDelegate.h` and say `ViewController *vc = AppDelegate.instance.firstViewController;` Anyway, it's just another way of saying what Mathew mentioned earlier.
There is a difference between `alloc-init`'ing a ViewController and `alloc-init`'ing that view controller's properties. Regarding your second example (calling from another class). Your current code indicates that you `alloc-init` firstViewController, but then don't do anything with it. Assuming you have not overriden your ViewController's `init` method, its properties and iVars should be `nil` (or undefined at worst). You need to `alloc-init` your `firstViewController.menuView` first. I.e: ``` firstViewController.menuView = [[UIView alloc] initWithFrame]; // Don't do this. ``` The problem with this approach is that you're setting up firstViewController's properties form another class, and that's generally fairly average design practice. This required setup would usually happen in `viewDidLoad` but because you haven't done anything with firstViewController yet, it never gets called. In contrast, when you call `closeMenu` from its own View Controller, the odds are you are actually doing something with the view and viewDidLoad (or wherever `menuView = [[UIView alloc] init];`is found) is called first, thus initialising your menuView object. You need to ensure that your menuView object is initialised first before you try and do anything with it, just initialising the View Controller that contains it is not enough.
31,669,238
Here is an array object that contains an array [body]. How do I get to know that this object has array inside and give me it's keys? ``` Array ( [6] => stdClass Object ( [vid] => 6 [uid] => 1 [title] => om [log] => [status] => 1 [comment] => 2 [promote] => 0 [sticky] => 0 [nid] => 6 [type] => article [language] => und [created] => 1436514497 [changed] => 1438003101 [tnid] => 0 [translate] => 0 [revision_timestamp] => 1438003101 [revision_uid] => 1 [body] => Array ( [und] => Array ( [0] => Array ( [value] ```
2015/07/28
[ "https://Stackoverflow.com/questions/31669238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2555662/" ]
You need to check whether the object has `body` property, `which is array` and `which should not be empty`. And fetch the keys it all three conditions fulfill. Use [is\_array(](http://php.net/manual/en/function.is-array.php)), [array\_keys()](http://php.net/manual/en/function.array-keys.php) and [isset()](http://php.net/manual/en/function.isset.php) ``` if (isset($obj->body) && is_array($obj->body) && ! empty($obj->body)) { // yes it has $keys = array_keys($obj->body); } else { // either body is not there or body is empty. } ``` **EDIT:** Check if any of the object properties is an array and return its keys. ``` foreach (get_object_vars($obj) as $var) { if (gettype($var) == 'array') { $keys = array_keys($var); } } ```
Considering `$main_array` as your given result. Try this ``` if( is_array($main_array->body) ) { // do your process } ```
31,669,238
Here is an array object that contains an array [body]. How do I get to know that this object has array inside and give me it's keys? ``` Array ( [6] => stdClass Object ( [vid] => 6 [uid] => 1 [title] => om [log] => [status] => 1 [comment] => 2 [promote] => 0 [sticky] => 0 [nid] => 6 [type] => article [language] => und [created] => 1436514497 [changed] => 1438003101 [tnid] => 0 [translate] => 0 [revision_timestamp] => 1438003101 [revision_uid] => 1 [body] => Array ( [und] => Array ( [0] => Array ( [value] ```
2015/07/28
[ "https://Stackoverflow.com/questions/31669238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2555662/" ]
Considering `$main_array` as your given result. Try this ``` if( is_array($main_array->body) ) { // do your process } ```
Check if it is an array with: <http://php.net/manual/de/function.is-array.php>
31,669,238
Here is an array object that contains an array [body]. How do I get to know that this object has array inside and give me it's keys? ``` Array ( [6] => stdClass Object ( [vid] => 6 [uid] => 1 [title] => om [log] => [status] => 1 [comment] => 2 [promote] => 0 [sticky] => 0 [nid] => 6 [type] => article [language] => und [created] => 1436514497 [changed] => 1438003101 [tnid] => 0 [translate] => 0 [revision_timestamp] => 1438003101 [revision_uid] => 1 [body] => Array ( [und] => Array ( [0] => Array ( [value] ```
2015/07/28
[ "https://Stackoverflow.com/questions/31669238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2555662/" ]
You need to check whether the object has `body` property, `which is array` and `which should not be empty`. And fetch the keys it all three conditions fulfill. Use [is\_array(](http://php.net/manual/en/function.is-array.php)), [array\_keys()](http://php.net/manual/en/function.array-keys.php) and [isset()](http://php.net/manual/en/function.isset.php) ``` if (isset($obj->body) && is_array($obj->body) && ! empty($obj->body)) { // yes it has $keys = array_keys($obj->body); } else { // either body is not there or body is empty. } ``` **EDIT:** Check if any of the object properties is an array and return its keys. ``` foreach (get_object_vars($obj) as $var) { if (gettype($var) == 'array') { $keys = array_keys($var); } } ```
Check if it is an array with: <http://php.net/manual/de/function.is-array.php>
55,085,683
My main model `Tag` has a one-to-many relationship with `Product` where one `Tag` can have many `Products` assigned to them via `tag_id` relationship on the DB. On my edit view, I am allowing users to edit the tag `products`. These products can be added/edited/deleted on the form request. Each `product` field on the form is picked up from a `request()` array. E.g: `request('title'),request('price')`. I have set `$title[$key]` as the `request('title')` array for example. My thoughts next, was to loop through each of the `products` for this `tag` and `updateOrCreate` based on the request data. The issue here, is that there's no way of detecting if that particular `product` was indeed needing updated. **TagController - Update Product Model (One-to-Many)** ``` foreach($tag->products as $key => $product){ Product::updateOrCreate([ 'id' => $product->id, ], [ 'title' => $title[$key], 'price' => $price[$key], 'detail' => $detail[$key], 'order' => $order[$key], 'tagX' => $tagX[$key], 'tagY' => $tagY[$key], 'thumb' => $img[$key], ]); } ``` For the initial `tag` update, I have set an `if` statement which works great (albeit messy) for the main tag `img`. **TagController - Update Tag Model** ``` //Update the tag collection if($request->hasFile('img')) { $tag->update([ 'name' => $name, 'hashtag' => $hashtag, 'img' => $imgPub, ]); } else{ $tag->update([ 'name' => $name, 'hashtag' => $hashtag, ]); } ``` Is there a better way to determine if the `product` fields were updated on the request? Ideally I would like the user to be able to add/remove or edit `products` from the `tag` edit request, but not delete existing product images if they have not been updated. Thanks!
2019/03/10
[ "https://Stackoverflow.com/questions/55085683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5986598/" ]
As per my view, you are on the wrong track. Tagging relationship should be **Many To Many.** You must check about `sync()` method of Laravel in ManyToMany relationship. Please check this: <https://laravel.com/docs/5.8/eloquent-relationships#many-to-many> **Notes:** Please add codes as per your business logic. **Product.php** ``` public function products(){ return $this->belongsToMany( 'App\Product', 'product_tags', 'tag_id', 'product_id'); } ``` **Tag.php** ``` public function tags(){ return $this->belongsToMany( 'App\Tag', 'product_tags', 'product_id', 'tag_id'); } ``` **ProductController.php** ``` public function update(Product $products, Request $request){ //update the product $products->update($request->all()); //attach new tags to the product $products->tags()->sync($request->input('tag_list')); return redirect('articles'); } ```
Normally I do something similar on the frontend side ``` <div class="product"> <!-- For Products that may be edited --> <input type="hidden" name="id" value={{$product->id??0}}> <input type="hidden" name="action" value="update"> <input type="text" name="title" value={{$product->title}}> ... </div> <div class="product"> <!-- For New Products --> <input type="hidden" name="id" value=0> <input type="hidden" name="action" value="add"> <input type="text" name="title" value="New Title"> ... </div> <div class="product"> <!-- For Deleted Products --> <input type="hidden" name="id" value={{$product->id}}> <input type="hidden" name="action" value="delete"> <input type="text" name="title" value="New Title"> ... </div> ``` Create the json (array of product objects) payload using javascript and send ajax request to the backend ``` [{'id':101,'title':'product 1','action':'update'}, {'id':102,'title':'product 2','action':'update'}, ... , {'id':201,'action':'delete'}, {'id':202, 'action':'delete'}, ... , {'id':0,'title':'new product 1','action':'add'}, {'id':0,'title':'new product 2','action':'add'}] ``` Now on the backend side, loop through the list of products and check for action. Depending on the action, take necessary step.
4,344,940
I'm developing a C# asp.net web application. I'm basically done with it, but I have this little problem. I want to save xml files to the "Users" folder within my project, but if I don't psychically hard code the path "C:......\Users" in my project it wants to save the file in this "C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\Users" folder, this is an annoying problem because I can't use the hard coded directory on our web hosts server. Also, I have a checkbox list that populates from the the "DownloadLibrary" folder in my project, and its suppose to download the files from that fold but its also looking to the "C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\" folder for download even though its populating from the correct folder. I'm very confused by this, its the first time something like this has ever happened to me. Can anyone please help me with this, its the only thing standing in my way to complete this project.
2010/12/03
[ "https://Stackoverflow.com/questions/4344940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/529272/" ]
You don't want to use the working directory at all; you want to use a directory relative to where the web application is located (which can be retrieved from [`HttpRequest.ApplicationPath`](http://msdn.microsoft.com/en-us/library/system.web.httprequest.applicationpath.aspx). ``` HttpRequest request = HttpContext.Current.Request; // get the physical path to the web application string pathToApp = request.MapPath(request.ApplicationPath); string usersPath = System.IO.Path.Combine(pathToApp, "Users"); ``` **Update** As [VincayC](https://stackoverflow.com/users/417057/vinayc) points out; asp.net development is not my strongest skill ;) The above code is essentially equivalent of this (much simpler) code: ``` string usersPath = HttpRequest.Current.Request.MapPath("~/Users"); ``` If this code appears in the code-behind of a page, you can probably cut `HttpContext.Current` as well, since the page has a `Request` property.
That did fix the one problem I'm having, but the downloads are still not downloading from the right place, the program still wants to get the files from "C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\" directory here is the code I'm using --Code to populate the checkbox-- ``` HttpRequest request = HttpContext.Current.Request; // get the physical path to the web application string appPath = request.MapPath(request.ApplicationPath); string directory = System.IO.Path.Combine(appPath, "DownloadLibrary/"); // Get the list of files into the CheckBoxList var dirInfo = new DirectoryInfo(directory); cblFiles.DataSource = dirInfo.GetFiles(); cblFiles.DataBind(); ``` --Download Button Code-- ``` // Tell the browser we're sending a ZIP file! var downloadFileName = string.Format("Items-{0}.zip", DateTime.Now.ToString("yyyy-MM-dd-HH_mm_ss")); Response.ContentType = "application/zip"; Response.AddHeader("Content-Disposition", "filename=" + downloadFileName); ``` // Zip the contents of the selected files using (var zip = new ZipFile()) { // Add the password protection, if specified /\*if (!string.IsNullOrEmpty(txtZIPPassword.Text)) { zip.Password = txtZIPPassword.Text; // 'This encryption is weak! Please see http://cheeso.members.winisp.net/DotNetZipHelp/html/24077057-63cb-ac7e-6be5-697fe9ce37d6.htm for more details zip.Encryption = EncryptionAlgorithm.WinZipAes128; }\*/ // Construct the contents of the README.txt file that will be included in this ZIP var readMeMessage = string.Format("Your ZIP file {0} contains the following files:{1}{1}", downloadFileName, Environment.NewLine); // Add the checked files to the ZIP foreach (ListItem li in cblFiles.Items) if (li.Selected) { // Record the file that was included in readMeMessage readMeMessage += string.Concat("\t\* ", li.Text, Environment.NewLine); // Now add the file to the ZIP (use a value of "" as the second parameter to put the files in the "root" folder) zip.AddFile(li.Value, "Your Files"); } // Add the README.txt file to the ZIP //zip.AddEntry("README.txt", readMeMessage, Encoding.ASCII); // Send the contents of the ZIP back to the output stream zip.Save(Response.OutputStream);</pre></code> I'm not sure how to get the downloads to point to my application directory,I tried everything I can think off.
51,881,728
``` a=['abc', '234', 'wdg', '220', '400', '395', '230', '350', ' ', '300', '300', '340', '420', '190', '300', '380', '270', 'wdg', '350', '380'] for i in range(len(a)): if a[i]=="wdg": a.pop(i) print(a) ``` When I run these code, the error message shows" IndexError: list index out of range".(in line"if a[i]=="wdg":") What's wrong with it? I want to find all of the "wdg" in a list and delete it
2018/08/16
[ "https://Stackoverflow.com/questions/51881728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10043318/" ]
Do not remove items from list while iterating through it. Every time, you `pop` from list, the length of list reduces by one. But you never account for this change in your loop. This causes `list index out of range` and stops your program abruptly. A more secure and effective way is to use a list-comprehension like below: ``` a = ['abc', '234', 'wdg', '220', '400', '395', '230', '350', ' ', '300', '300', '340', '420', '190', '300', '380', '270', 'wdg', '350', '380'] a = [x for x in a if x != 'wdg'] ```
The list is getting shorter every time you pop an item, so by the time you get to the end, the index is longer than the length of the list. Try a list comprehension: ``` newList=[x for x in a if x!="wdg"] ```
51,881,728
``` a=['abc', '234', 'wdg', '220', '400', '395', '230', '350', ' ', '300', '300', '340', '420', '190', '300', '380', '270', 'wdg', '350', '380'] for i in range(len(a)): if a[i]=="wdg": a.pop(i) print(a) ``` When I run these code, the error message shows" IndexError: list index out of range".(in line"if a[i]=="wdg":") What's wrong with it? I want to find all of the "wdg" in a list and delete it
2018/08/16
[ "https://Stackoverflow.com/questions/51881728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10043318/" ]
To remove an element you can do: ``` >>> a = ['a', 'b', 'c', 'd'] >>> a.remove('b') >>> print a ['a', 'c', 'd'] ``` The error is occurring because you are iterating over a sequence of numbers - the original size of the list. Once the list shrinks, the index no longer exists. I would recommend iterating over the elements of the list like: ``` for elem in my_list: print(elem) ``` Instead of: ``` for i in len(range(my_list)): print(my_list[i]) ```
The list is getting shorter every time you pop an item, so by the time you get to the end, the index is longer than the length of the list. Try a list comprehension: ``` newList=[x for x in a if x!="wdg"] ```
51,881,728
``` a=['abc', '234', 'wdg', '220', '400', '395', '230', '350', ' ', '300', '300', '340', '420', '190', '300', '380', '270', 'wdg', '350', '380'] for i in range(len(a)): if a[i]=="wdg": a.pop(i) print(a) ``` When I run these code, the error message shows" IndexError: list index out of range".(in line"if a[i]=="wdg":") What's wrong with it? I want to find all of the "wdg" in a list and delete it
2018/08/16
[ "https://Stackoverflow.com/questions/51881728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10043318/" ]
To remove an element you can do: ``` >>> a = ['a', 'b', 'c', 'd'] >>> a.remove('b') >>> print a ['a', 'c', 'd'] ``` The error is occurring because you are iterating over a sequence of numbers - the original size of the list. Once the list shrinks, the index no longer exists. I would recommend iterating over the elements of the list like: ``` for elem in my_list: print(elem) ``` Instead of: ``` for i in len(range(my_list)): print(my_list[i]) ```
Do not remove items from list while iterating through it. Every time, you `pop` from list, the length of list reduces by one. But you never account for this change in your loop. This causes `list index out of range` and stops your program abruptly. A more secure and effective way is to use a list-comprehension like below: ``` a = ['abc', '234', 'wdg', '220', '400', '395', '230', '350', ' ', '300', '300', '340', '420', '190', '300', '380', '270', 'wdg', '350', '380'] a = [x for x in a if x != 'wdg'] ```
51,881,728
``` a=['abc', '234', 'wdg', '220', '400', '395', '230', '350', ' ', '300', '300', '340', '420', '190', '300', '380', '270', 'wdg', '350', '380'] for i in range(len(a)): if a[i]=="wdg": a.pop(i) print(a) ``` When I run these code, the error message shows" IndexError: list index out of range".(in line"if a[i]=="wdg":") What's wrong with it? I want to find all of the "wdg" in a list and delete it
2018/08/16
[ "https://Stackoverflow.com/questions/51881728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10043318/" ]
Do not remove items from list while iterating through it. Every time, you `pop` from list, the length of list reduces by one. But you never account for this change in your loop. This causes `list index out of range` and stops your program abruptly. A more secure and effective way is to use a list-comprehension like below: ``` a = ['abc', '234', 'wdg', '220', '400', '395', '230', '350', ' ', '300', '300', '340', '420', '190', '300', '380', '270', 'wdg', '350', '380'] a = [x for x in a if x != 'wdg'] ```
Since you measure the lenght of the list *before* the for loop, and you remove items *during* the for loop, your `len(list)` becomes wrong during iteration. That's why you run out of range. A simple way would be to iterate the list *in reverse* eg `for i in reversed(range(len(mylist)))`. That way, when you are removing an element, it does not affect your remaining (previous) elements. However, it would be better to use a list comprehension, as other users have pointed out.
51,881,728
``` a=['abc', '234', 'wdg', '220', '400', '395', '230', '350', ' ', '300', '300', '340', '420', '190', '300', '380', '270', 'wdg', '350', '380'] for i in range(len(a)): if a[i]=="wdg": a.pop(i) print(a) ``` When I run these code, the error message shows" IndexError: list index out of range".(in line"if a[i]=="wdg":") What's wrong with it? I want to find all of the "wdg" in a list and delete it
2018/08/16
[ "https://Stackoverflow.com/questions/51881728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10043318/" ]
To remove an element you can do: ``` >>> a = ['a', 'b', 'c', 'd'] >>> a.remove('b') >>> print a ['a', 'c', 'd'] ``` The error is occurring because you are iterating over a sequence of numbers - the original size of the list. Once the list shrinks, the index no longer exists. I would recommend iterating over the elements of the list like: ``` for elem in my_list: print(elem) ``` Instead of: ``` for i in len(range(my_list)): print(my_list[i]) ```
Since you measure the lenght of the list *before* the for loop, and you remove items *during* the for loop, your `len(list)` becomes wrong during iteration. That's why you run out of range. A simple way would be to iterate the list *in reverse* eg `for i in reversed(range(len(mylist)))`. That way, when you are removing an element, it does not affect your remaining (previous) elements. However, it would be better to use a list comprehension, as other users have pointed out.
77,019
Most PhD students I know have the problem that their supervisor is not involved enough. I have a different problem, my supervisor is too involved. He wants to be a co author on all three of my PhD papers, and to get them published. I know that this sounds great, but I do not want to free ride on my supervisors work, I want it to be my own, and I want to be proud of it. Regardless of whether it is published or not. A publication is a bonus, not the end game for me. I spent half my phd working on what I intended to be my job market paper (the paper I show to employers that best showcases my skills). My supervisor made some suggestions here and there, but nothing substantial. I am now getting ready to submit my paper to a journal and my supervisor has rewritten my entire paper without permission and wants me to sign off on this. He has justified it by saying it has a better shot of being published in its new form. I feel very uncomfortable about this, it is in effect no longer my paper. I thought he would make suggestions and I would fix the paper myself. He is too involved in other ways too. When I settle on a research question, he throws methodology and research design at me, before I have a chance to think about the topic myself and come to my own conclusions, and then encourages me to do it his way and not explore my way. Is this normal behaviour from a supervisor? I have to talk to him about this, but I am unsure how to bring it up and what to say. Do you have any advice? I need at least one paper where I am the sole author, is it appropriate to mention this to my supervisor, without offending him or his position? He will try to put his name on all my papers. I do not want to come across ungrateful, I am very happy for his help, and I will be the first to admit that I need help. But all I want is a chance to learn from my mistakes and be given opportunities to grow, I will never be a successful researcher if I cannot exercise this. Unfortunately, I feel like my supervisors research assistant instead of a PhD student. I am really struggling to continue on the course, and I appreciate any comments you may have.
2016/09/17
[ "https://academia.stackexchange.com/questions/77019", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/61988/" ]
You seem to have a lot of problems with this: > > He wants to be a co author on all three of my PhD papers, and to get them published. > > > I do not know what your field is and what are the conventions there, but in all of the fields I am familiar with, this is not a bad thing. Having your supervisor as a co-author does not make the paper any less "yours". If my field(s), whenever there is a PhD student as the first author, everyone knows that the paper is theirs, and they did most (if not all) of the work. > > ...and my supervisor has rewritten my entire paper... > > > Nothing wrong with that. As noted elsewhere in the answers, your supervisor knows more about writing papers than you do. It was not uncommon for sections of my own papers to be rewritten by my supervisor. > > He has justified it by saying it has a better shot of being published in its new form. > > > He is probably right. Instead of thinking along those lines... > > ...but I do not want to free ride on my supervisors work, I want it to be > my own, and I want to be proud of it. > > > You should be thanking your supervisor for this. He is teaching you how to write proper papers. You have to remember that you are still a student. This is why you are there - to learn how to be a scientist or researcher. Part of the process is accepting feedback from your supervisor. If you don't, it will come in the form of a much more harsh peer-review when you submit the paper. If your job market absolutely requires a single author paper written by you (which I doubt), ask your supervisor about it. I am pretty sure he does not want to ruin your job prospects. Explain the situation and see what he thinks.
First off, please be aware that I have not personally put to practice the advice I am offering; this is more of an after-the-fact "I should have done that" situation. I assume that the papers you publish will be part of your thesis. I don't know enough about job-market papers or the significance of sole authorship in your field, so I'm not going to touch on that. I'm going to address two other specific problems that you mentioned. a) Your supervisor rewriting your paper: You can say "I appreciate that you made the paper more publishable, but whenever one person rewrites the work of another there's always a danger that some details in a proof/argument is accidentally misrepresented" (be careful to phrase this diplomatically so as not to imply that he's not capable enough of understanding your work - he's just not as involved with the specific details as you). "Next time, can you give me your suggestions separately and let me implement them, to eliminate this possibility?" Then you have a choice to reject some changes if you wish. They should understand where you're coming from, as even the most involved and capable supervisor can get a detail wrong. b) Your supervisor pushing their choice of methodology on you: The following solution only works in countries where the PhD presentation is more an actual examination than a formality (I'm thinking of the UK). You can say: "I don't feel that I can defend this direction of research in my upcoming examination." They'll probably say something along the lines of "Sure you can, we're doing this because of XYZ", to which you can reply "I know the justification but since this is not the direction that makes the most sense to me personally, I don't think I can offer a coherent explanation if I'm pushed by the examiners, and you wouldn't want me to say 'this is just what my supervisor told me to do'." This also requires some diplomacy, but basically your argument here is that you're expected to defend your thesis as your own creation and show independence, and if you just trust someone else's authority you're going to fail on that front. Lastly, in the event that you are in complete disagreement with your supervisor's suggestions, an extreme solution here may be to drop the subject altogether, as long as it is not integral to your thesis. Just say "We're clearly not seeing eye to eye on this, let's just focus on some of the other things we have been looking at". Maybe you won't even need to address this in the end.
77,019
Most PhD students I know have the problem that their supervisor is not involved enough. I have a different problem, my supervisor is too involved. He wants to be a co author on all three of my PhD papers, and to get them published. I know that this sounds great, but I do not want to free ride on my supervisors work, I want it to be my own, and I want to be proud of it. Regardless of whether it is published or not. A publication is a bonus, not the end game for me. I spent half my phd working on what I intended to be my job market paper (the paper I show to employers that best showcases my skills). My supervisor made some suggestions here and there, but nothing substantial. I am now getting ready to submit my paper to a journal and my supervisor has rewritten my entire paper without permission and wants me to sign off on this. He has justified it by saying it has a better shot of being published in its new form. I feel very uncomfortable about this, it is in effect no longer my paper. I thought he would make suggestions and I would fix the paper myself. He is too involved in other ways too. When I settle on a research question, he throws methodology and research design at me, before I have a chance to think about the topic myself and come to my own conclusions, and then encourages me to do it his way and not explore my way. Is this normal behaviour from a supervisor? I have to talk to him about this, but I am unsure how to bring it up and what to say. Do you have any advice? I need at least one paper where I am the sole author, is it appropriate to mention this to my supervisor, without offending him or his position? He will try to put his name on all my papers. I do not want to come across ungrateful, I am very happy for his help, and I will be the first to admit that I need help. But all I want is a chance to learn from my mistakes and be given opportunities to grow, I will never be a successful researcher if I cannot exercise this. Unfortunately, I feel like my supervisors research assistant instead of a PhD student. I am really struggling to continue on the course, and I appreciate any comments you may have.
2016/09/17
[ "https://academia.stackexchange.com/questions/77019", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/61988/" ]
I feel you! Being a phd researcher in social sciences isn't what I expected. It is more about doing things the right way than it is being innovative or creative. This right way is where our kind supervisors try to guide us for the articles to be published. If and when you come up with a special idea you want to do your own way, I would present this idea to your supervisor as a "crazy idea you want to try even if it means you would have to do it on your own". Just to tell your supervisor that you want to be a single author to some article doesn't sound like fair or even wise.
Your's is not an isolated case. In my experience, what works best is to be assertive and convey him your intellectual capacities. Such degree of involvement indicates that he feels more prepared than you to do the work, show him that you have very relevant things to offer. This is a challenging task, the key is on logic and the scientific method, be very smart about it. He probably has a lot more practice than you at arguing, but thankfully in science people tend to be slightly more logical in debate/confrontation. Also, try to be humble, it is always easier to see other people's flaws. Your intuition may tell you many things, but try to build your arguments on evidence and specific points. Ultimately, he is a more experienced person. In regards to the writing, that is tricky and very important. You can always ask a third person to blindly evaluate both versions, that can be quite helpful. ( read him/her, I don't know the gender of your supervisor)
77,019
Most PhD students I know have the problem that their supervisor is not involved enough. I have a different problem, my supervisor is too involved. He wants to be a co author on all three of my PhD papers, and to get them published. I know that this sounds great, but I do not want to free ride on my supervisors work, I want it to be my own, and I want to be proud of it. Regardless of whether it is published or not. A publication is a bonus, not the end game for me. I spent half my phd working on what I intended to be my job market paper (the paper I show to employers that best showcases my skills). My supervisor made some suggestions here and there, but nothing substantial. I am now getting ready to submit my paper to a journal and my supervisor has rewritten my entire paper without permission and wants me to sign off on this. He has justified it by saying it has a better shot of being published in its new form. I feel very uncomfortable about this, it is in effect no longer my paper. I thought he would make suggestions and I would fix the paper myself. He is too involved in other ways too. When I settle on a research question, he throws methodology and research design at me, before I have a chance to think about the topic myself and come to my own conclusions, and then encourages me to do it his way and not explore my way. Is this normal behaviour from a supervisor? I have to talk to him about this, but I am unsure how to bring it up and what to say. Do you have any advice? I need at least one paper where I am the sole author, is it appropriate to mention this to my supervisor, without offending him or his position? He will try to put his name on all my papers. I do not want to come across ungrateful, I am very happy for his help, and I will be the first to admit that I need help. But all I want is a chance to learn from my mistakes and be given opportunities to grow, I will never be a successful researcher if I cannot exercise this. Unfortunately, I feel like my supervisors research assistant instead of a PhD student. I am really struggling to continue on the course, and I appreciate any comments you may have.
2016/09/17
[ "https://academia.stackexchange.com/questions/77019", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/61988/" ]
The first part (rewriting your text) is quite frequent. Believe it or not, most PhD students are terrible writers and though a good adviser would patiently go over the paper with a student pointing out the presentation flaws and asking the student to fix them himself (take my word for it, you do not want to get that list from the reviewer *after* the paper has been submitted), I know many people who lost their patience in that respect eons ago and other people who give up after 6 months of modifications and still do the job themselves. So, the first question to ask is "How well was your paper written in the first place?". If not too well, there is a chance that you should be merely grateful for the revision and stop at there. The second point is "throwing his ideas at you". Here the question is "How fast are you coming with workable ideas of your own?" Giving a PhD student the solution together with the problem is a terrible idea, insisting that the student do things your way and your way only is even more terrible, but giving him no suggestions after 6 months of no progress is also not good. The third question is whether the supervisor should be a co-author. Unfortunately, your post is somewhat self-contradictory on this point: compare > > My supervisor made some suggestions here and there, but nothing substantial. > > > with > > he throws methodology and research design at me, before I have a chance to think about the topic myself and come to my own conclusions, and then encourages me to do it his way and not explore my way. > > > So was that particular paper done his way or your way? In the first case, IMHO, it is his choice whether he should become a co-author or not though you may still drop a hint that "the job market is tough and having a single author paper is a nearly must to land at the place you want to go to", in the second case it should be yours even if he rewrote the whole thing and you have all moral rights to insist on a single authorship if it is important to you. How exactly to do it without offending him I don't know (different people need different approaches), but judging from the tone of your post, you have had arguments with your adviser before, so you should know better than I what upsets him and what makes him cooperative. So, alas, the only things I can tell you are the usual "Look into the mirror and try to figure out what exactly you see there before making final judgements" and "Hold your ground but use your common sense and pay attention to the reaction to your words when insisting on something". I should confess that I often fail on both accounts myself, but I'm in a different position than you. Let's see if other people can come up with some better advice :-).
You seem to have a lot of problems with this: > > He wants to be a co author on all three of my PhD papers, and to get them published. > > > I do not know what your field is and what are the conventions there, but in all of the fields I am familiar with, this is not a bad thing. Having your supervisor as a co-author does not make the paper any less "yours". If my field(s), whenever there is a PhD student as the first author, everyone knows that the paper is theirs, and they did most (if not all) of the work. > > ...and my supervisor has rewritten my entire paper... > > > Nothing wrong with that. As noted elsewhere in the answers, your supervisor knows more about writing papers than you do. It was not uncommon for sections of my own papers to be rewritten by my supervisor. > > He has justified it by saying it has a better shot of being published in its new form. > > > He is probably right. Instead of thinking along those lines... > > ...but I do not want to free ride on my supervisors work, I want it to be > my own, and I want to be proud of it. > > > You should be thanking your supervisor for this. He is teaching you how to write proper papers. You have to remember that you are still a student. This is why you are there - to learn how to be a scientist or researcher. Part of the process is accepting feedback from your supervisor. If you don't, it will come in the form of a much more harsh peer-review when you submit the paper. If your job market absolutely requires a single author paper written by you (which I doubt), ask your supervisor about it. I am pretty sure he does not want to ruin your job prospects. Explain the situation and see what he thinks.
77,019
Most PhD students I know have the problem that their supervisor is not involved enough. I have a different problem, my supervisor is too involved. He wants to be a co author on all three of my PhD papers, and to get them published. I know that this sounds great, but I do not want to free ride on my supervisors work, I want it to be my own, and I want to be proud of it. Regardless of whether it is published or not. A publication is a bonus, not the end game for me. I spent half my phd working on what I intended to be my job market paper (the paper I show to employers that best showcases my skills). My supervisor made some suggestions here and there, but nothing substantial. I am now getting ready to submit my paper to a journal and my supervisor has rewritten my entire paper without permission and wants me to sign off on this. He has justified it by saying it has a better shot of being published in its new form. I feel very uncomfortable about this, it is in effect no longer my paper. I thought he would make suggestions and I would fix the paper myself. He is too involved in other ways too. When I settle on a research question, he throws methodology and research design at me, before I have a chance to think about the topic myself and come to my own conclusions, and then encourages me to do it his way and not explore my way. Is this normal behaviour from a supervisor? I have to talk to him about this, but I am unsure how to bring it up and what to say. Do you have any advice? I need at least one paper where I am the sole author, is it appropriate to mention this to my supervisor, without offending him or his position? He will try to put his name on all my papers. I do not want to come across ungrateful, I am very happy for his help, and I will be the first to admit that I need help. But all I want is a chance to learn from my mistakes and be given opportunities to grow, I will never be a successful researcher if I cannot exercise this. Unfortunately, I feel like my supervisors research assistant instead of a PhD student. I am really struggling to continue on the course, and I appreciate any comments you may have.
2016/09/17
[ "https://academia.stackexchange.com/questions/77019", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/61988/" ]
You seem to have a lot of problems with this: > > He wants to be a co author on all three of my PhD papers, and to get them published. > > > I do not know what your field is and what are the conventions there, but in all of the fields I am familiar with, this is not a bad thing. Having your supervisor as a co-author does not make the paper any less "yours". If my field(s), whenever there is a PhD student as the first author, everyone knows that the paper is theirs, and they did most (if not all) of the work. > > ...and my supervisor has rewritten my entire paper... > > > Nothing wrong with that. As noted elsewhere in the answers, your supervisor knows more about writing papers than you do. It was not uncommon for sections of my own papers to be rewritten by my supervisor. > > He has justified it by saying it has a better shot of being published in its new form. > > > He is probably right. Instead of thinking along those lines... > > ...but I do not want to free ride on my supervisors work, I want it to be > my own, and I want to be proud of it. > > > You should be thanking your supervisor for this. He is teaching you how to write proper papers. You have to remember that you are still a student. This is why you are there - to learn how to be a scientist or researcher. Part of the process is accepting feedback from your supervisor. If you don't, it will come in the form of a much more harsh peer-review when you submit the paper. If your job market absolutely requires a single author paper written by you (which I doubt), ask your supervisor about it. I am pretty sure he does not want to ruin your job prospects. Explain the situation and see what he thinks.
I feel you! Being a phd researcher in social sciences isn't what I expected. It is more about doing things the right way than it is being innovative or creative. This right way is where our kind supervisors try to guide us for the articles to be published. If and when you come up with a special idea you want to do your own way, I would present this idea to your supervisor as a "crazy idea you want to try even if it means you would have to do it on your own". Just to tell your supervisor that you want to be a single author to some article doesn't sound like fair or even wise.
77,019
Most PhD students I know have the problem that their supervisor is not involved enough. I have a different problem, my supervisor is too involved. He wants to be a co author on all three of my PhD papers, and to get them published. I know that this sounds great, but I do not want to free ride on my supervisors work, I want it to be my own, and I want to be proud of it. Regardless of whether it is published or not. A publication is a bonus, not the end game for me. I spent half my phd working on what I intended to be my job market paper (the paper I show to employers that best showcases my skills). My supervisor made some suggestions here and there, but nothing substantial. I am now getting ready to submit my paper to a journal and my supervisor has rewritten my entire paper without permission and wants me to sign off on this. He has justified it by saying it has a better shot of being published in its new form. I feel very uncomfortable about this, it is in effect no longer my paper. I thought he would make suggestions and I would fix the paper myself. He is too involved in other ways too. When I settle on a research question, he throws methodology and research design at me, before I have a chance to think about the topic myself and come to my own conclusions, and then encourages me to do it his way and not explore my way. Is this normal behaviour from a supervisor? I have to talk to him about this, but I am unsure how to bring it up and what to say. Do you have any advice? I need at least one paper where I am the sole author, is it appropriate to mention this to my supervisor, without offending him or his position? He will try to put his name on all my papers. I do not want to come across ungrateful, I am very happy for his help, and I will be the first to admit that I need help. But all I want is a chance to learn from my mistakes and be given opportunities to grow, I will never be a successful researcher if I cannot exercise this. Unfortunately, I feel like my supervisors research assistant instead of a PhD student. I am really struggling to continue on the course, and I appreciate any comments you may have.
2016/09/17
[ "https://academia.stackexchange.com/questions/77019", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/61988/" ]
The first part (rewriting your text) is quite frequent. Believe it or not, most PhD students are terrible writers and though a good adviser would patiently go over the paper with a student pointing out the presentation flaws and asking the student to fix them himself (take my word for it, you do not want to get that list from the reviewer *after* the paper has been submitted), I know many people who lost their patience in that respect eons ago and other people who give up after 6 months of modifications and still do the job themselves. So, the first question to ask is "How well was your paper written in the first place?". If not too well, there is a chance that you should be merely grateful for the revision and stop at there. The second point is "throwing his ideas at you". Here the question is "How fast are you coming with workable ideas of your own?" Giving a PhD student the solution together with the problem is a terrible idea, insisting that the student do things your way and your way only is even more terrible, but giving him no suggestions after 6 months of no progress is also not good. The third question is whether the supervisor should be a co-author. Unfortunately, your post is somewhat self-contradictory on this point: compare > > My supervisor made some suggestions here and there, but nothing substantial. > > > with > > he throws methodology and research design at me, before I have a chance to think about the topic myself and come to my own conclusions, and then encourages me to do it his way and not explore my way. > > > So was that particular paper done his way or your way? In the first case, IMHO, it is his choice whether he should become a co-author or not though you may still drop a hint that "the job market is tough and having a single author paper is a nearly must to land at the place you want to go to", in the second case it should be yours even if he rewrote the whole thing and you have all moral rights to insist on a single authorship if it is important to you. How exactly to do it without offending him I don't know (different people need different approaches), but judging from the tone of your post, you have had arguments with your adviser before, so you should know better than I what upsets him and what makes him cooperative. So, alas, the only things I can tell you are the usual "Look into the mirror and try to figure out what exactly you see there before making final judgements" and "Hold your ground but use your common sense and pay attention to the reaction to your words when insisting on something". I should confess that I often fail on both accounts myself, but I'm in a different position than you. Let's see if other people can come up with some better advice :-).
Your's is not an isolated case. In my experience, what works best is to be assertive and convey him your intellectual capacities. Such degree of involvement indicates that he feels more prepared than you to do the work, show him that you have very relevant things to offer. This is a challenging task, the key is on logic and the scientific method, be very smart about it. He probably has a lot more practice than you at arguing, but thankfully in science people tend to be slightly more logical in debate/confrontation. Also, try to be humble, it is always easier to see other people's flaws. Your intuition may tell you many things, but try to build your arguments on evidence and specific points. Ultimately, he is a more experienced person. In regards to the writing, that is tricky and very important. You can always ask a third person to blindly evaluate both versions, that can be quite helpful. ( read him/her, I don't know the gender of your supervisor)
77,019
Most PhD students I know have the problem that their supervisor is not involved enough. I have a different problem, my supervisor is too involved. He wants to be a co author on all three of my PhD papers, and to get them published. I know that this sounds great, but I do not want to free ride on my supervisors work, I want it to be my own, and I want to be proud of it. Regardless of whether it is published or not. A publication is a bonus, not the end game for me. I spent half my phd working on what I intended to be my job market paper (the paper I show to employers that best showcases my skills). My supervisor made some suggestions here and there, but nothing substantial. I am now getting ready to submit my paper to a journal and my supervisor has rewritten my entire paper without permission and wants me to sign off on this. He has justified it by saying it has a better shot of being published in its new form. I feel very uncomfortable about this, it is in effect no longer my paper. I thought he would make suggestions and I would fix the paper myself. He is too involved in other ways too. When I settle on a research question, he throws methodology and research design at me, before I have a chance to think about the topic myself and come to my own conclusions, and then encourages me to do it his way and not explore my way. Is this normal behaviour from a supervisor? I have to talk to him about this, but I am unsure how to bring it up and what to say. Do you have any advice? I need at least one paper where I am the sole author, is it appropriate to mention this to my supervisor, without offending him or his position? He will try to put his name on all my papers. I do not want to come across ungrateful, I am very happy for his help, and I will be the first to admit that I need help. But all I want is a chance to learn from my mistakes and be given opportunities to grow, I will never be a successful researcher if I cannot exercise this. Unfortunately, I feel like my supervisors research assistant instead of a PhD student. I am really struggling to continue on the course, and I appreciate any comments you may have.
2016/09/17
[ "https://academia.stackexchange.com/questions/77019", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/61988/" ]
Regarding the argument of an article as a single article (to get a job), I doubt that, at least in my field (chemical engineering). Every supervisor is different, so I'll just focus on my own process as a Ph.D. student and I will hope it helps you in any way. I published 6 articles on my direct Ph.D.; 4 as a first author and other 2 helping others in their projects. My first article had 24 versions (drafts) before sending it to a journal! I was *very* frustrated–until we sent it: it got accepted without a single correction in *Chemical Engineering Science* (a really nice journal for what I was doing). After that article, the level of involvement from my advisor decreased, slowly but surely: the fourth article he merely sent it as is to *Chemical Engineering Journal*. He was a co-author for all of my articles, although most of the lab work, programming (algorithms and implementation), and even the ideas were mine. Sure, we debated some ideas (mine worked at the end), but still, the lab was his, the money for research was his, the technicians helping me were his, and even the frustrating debates helped me. He helped me a lot when getting a job and still does; we collaborate as equals now. My first article as a corresponding author came up when I was in my first year as a postdoc... so my advice is: be patient, learning to be a researcher takes more than a Ph.D. nowadays; some decades ago you could be doing cutting-edge research a year after finishing your undergrad, but that is not the case nowadays. Be patient, this can only get better with time; you don't want/need an offended advisor.
I think this is a great question, thanks for coming up with it. What you report is common -- though not widespread --, **advisor** behaviour in my field. I have, myself done this. And I believe it is not productive behaviour for the advisee for the exact reason you state, feeling "(...) very uncomfortable about this, it is in effect no longer my paper". I see you there. First of all, *I recommend you abide to this*, for the time being. Put yourself in his shoes to understand the conflict: this guy sees your work as his own. I think trying too hard to react against that will generate unnecessary stress. Academia nowadays is unfortunately pressed for productivity and published papers are worth more than human resources and development, or bonafide science. Your advisor may feel frustrated for not having the time/ability/space for doing your project(s) directly, and sees in you an extension of himself. He is eager to impress his peers. I don't think you should stand in the way by being, well, a real person in his career game. Take the opportunity to learn some of his ways, if you really believe (and it looks like you do) he is fairly competent in the field. You can try to observe his strategy, style, ask him questions, while building your own independent line inside. Finally, I do understand your urge to become an independent investigator (i.e. a true PhD) and I think you should strive for that. Consider writing some essays of your own without telling your advisor and without delaying your projects. Consider, e.g., an opinion piece, a methods paper, a mini-review. As long as you *don't* include locally-obtained data or ideas from others, these are 100% private and you can do whatever you wish with those. P.S. Why did I put the word "advisor" in bold? Because that's how you should see your PhD mentor. Better leave the word "supervisor" to postdocs, and avoid the terms "boss", "leader", "owner", etc completely.
77,019
Most PhD students I know have the problem that their supervisor is not involved enough. I have a different problem, my supervisor is too involved. He wants to be a co author on all three of my PhD papers, and to get them published. I know that this sounds great, but I do not want to free ride on my supervisors work, I want it to be my own, and I want to be proud of it. Regardless of whether it is published or not. A publication is a bonus, not the end game for me. I spent half my phd working on what I intended to be my job market paper (the paper I show to employers that best showcases my skills). My supervisor made some suggestions here and there, but nothing substantial. I am now getting ready to submit my paper to a journal and my supervisor has rewritten my entire paper without permission and wants me to sign off on this. He has justified it by saying it has a better shot of being published in its new form. I feel very uncomfortable about this, it is in effect no longer my paper. I thought he would make suggestions and I would fix the paper myself. He is too involved in other ways too. When I settle on a research question, he throws methodology and research design at me, before I have a chance to think about the topic myself and come to my own conclusions, and then encourages me to do it his way and not explore my way. Is this normal behaviour from a supervisor? I have to talk to him about this, but I am unsure how to bring it up and what to say. Do you have any advice? I need at least one paper where I am the sole author, is it appropriate to mention this to my supervisor, without offending him or his position? He will try to put his name on all my papers. I do not want to come across ungrateful, I am very happy for his help, and I will be the first to admit that I need help. But all I want is a chance to learn from my mistakes and be given opportunities to grow, I will never be a successful researcher if I cannot exercise this. Unfortunately, I feel like my supervisors research assistant instead of a PhD student. I am really struggling to continue on the course, and I appreciate any comments you may have.
2016/09/17
[ "https://academia.stackexchange.com/questions/77019", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/61988/" ]
Regarding the argument of an article as a single article (to get a job), I doubt that, at least in my field (chemical engineering). Every supervisor is different, so I'll just focus on my own process as a Ph.D. student and I will hope it helps you in any way. I published 6 articles on my direct Ph.D.; 4 as a first author and other 2 helping others in their projects. My first article had 24 versions (drafts) before sending it to a journal! I was *very* frustrated–until we sent it: it got accepted without a single correction in *Chemical Engineering Science* (a really nice journal for what I was doing). After that article, the level of involvement from my advisor decreased, slowly but surely: the fourth article he merely sent it as is to *Chemical Engineering Journal*. He was a co-author for all of my articles, although most of the lab work, programming (algorithms and implementation), and even the ideas were mine. Sure, we debated some ideas (mine worked at the end), but still, the lab was his, the money for research was his, the technicians helping me were his, and even the frustrating debates helped me. He helped me a lot when getting a job and still does; we collaborate as equals now. My first article as a corresponding author came up when I was in my first year as a postdoc... so my advice is: be patient, learning to be a researcher takes more than a Ph.D. nowadays; some decades ago you could be doing cutting-edge research a year after finishing your undergrad, but that is not the case nowadays. Be patient, this can only get better with time; you don't want/need an offended advisor.
Your's is not an isolated case. In my experience, what works best is to be assertive and convey him your intellectual capacities. Such degree of involvement indicates that he feels more prepared than you to do the work, show him that you have very relevant things to offer. This is a challenging task, the key is on logic and the scientific method, be very smart about it. He probably has a lot more practice than you at arguing, but thankfully in science people tend to be slightly more logical in debate/confrontation. Also, try to be humble, it is always easier to see other people's flaws. Your intuition may tell you many things, but try to build your arguments on evidence and specific points. Ultimately, he is a more experienced person. In regards to the writing, that is tricky and very important. You can always ask a third person to blindly evaluate both versions, that can be quite helpful. ( read him/her, I don't know the gender of your supervisor)
77,019
Most PhD students I know have the problem that their supervisor is not involved enough. I have a different problem, my supervisor is too involved. He wants to be a co author on all three of my PhD papers, and to get them published. I know that this sounds great, but I do not want to free ride on my supervisors work, I want it to be my own, and I want to be proud of it. Regardless of whether it is published or not. A publication is a bonus, not the end game for me. I spent half my phd working on what I intended to be my job market paper (the paper I show to employers that best showcases my skills). My supervisor made some suggestions here and there, but nothing substantial. I am now getting ready to submit my paper to a journal and my supervisor has rewritten my entire paper without permission and wants me to sign off on this. He has justified it by saying it has a better shot of being published in its new form. I feel very uncomfortable about this, it is in effect no longer my paper. I thought he would make suggestions and I would fix the paper myself. He is too involved in other ways too. When I settle on a research question, he throws methodology and research design at me, before I have a chance to think about the topic myself and come to my own conclusions, and then encourages me to do it his way and not explore my way. Is this normal behaviour from a supervisor? I have to talk to him about this, but I am unsure how to bring it up and what to say. Do you have any advice? I need at least one paper where I am the sole author, is it appropriate to mention this to my supervisor, without offending him or his position? He will try to put his name on all my papers. I do not want to come across ungrateful, I am very happy for his help, and I will be the first to admit that I need help. But all I want is a chance to learn from my mistakes and be given opportunities to grow, I will never be a successful researcher if I cannot exercise this. Unfortunately, I feel like my supervisors research assistant instead of a PhD student. I am really struggling to continue on the course, and I appreciate any comments you may have.
2016/09/17
[ "https://academia.stackexchange.com/questions/77019", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/61988/" ]
Your's is not an isolated case. In my experience, what works best is to be assertive and convey him your intellectual capacities. Such degree of involvement indicates that he feels more prepared than you to do the work, show him that you have very relevant things to offer. This is a challenging task, the key is on logic and the scientific method, be very smart about it. He probably has a lot more practice than you at arguing, but thankfully in science people tend to be slightly more logical in debate/confrontation. Also, try to be humble, it is always easier to see other people's flaws. Your intuition may tell you many things, but try to build your arguments on evidence and specific points. Ultimately, he is a more experienced person. In regards to the writing, that is tricky and very important. You can always ask a third person to blindly evaluate both versions, that can be quite helpful. ( read him/her, I don't know the gender of your supervisor)
First off, please be aware that I have not personally put to practice the advice I am offering; this is more of an after-the-fact "I should have done that" situation. I assume that the papers you publish will be part of your thesis. I don't know enough about job-market papers or the significance of sole authorship in your field, so I'm not going to touch on that. I'm going to address two other specific problems that you mentioned. a) Your supervisor rewriting your paper: You can say "I appreciate that you made the paper more publishable, but whenever one person rewrites the work of another there's always a danger that some details in a proof/argument is accidentally misrepresented" (be careful to phrase this diplomatically so as not to imply that he's not capable enough of understanding your work - he's just not as involved with the specific details as you). "Next time, can you give me your suggestions separately and let me implement them, to eliminate this possibility?" Then you have a choice to reject some changes if you wish. They should understand where you're coming from, as even the most involved and capable supervisor can get a detail wrong. b) Your supervisor pushing their choice of methodology on you: The following solution only works in countries where the PhD presentation is more an actual examination than a formality (I'm thinking of the UK). You can say: "I don't feel that I can defend this direction of research in my upcoming examination." They'll probably say something along the lines of "Sure you can, we're doing this because of XYZ", to which you can reply "I know the justification but since this is not the direction that makes the most sense to me personally, I don't think I can offer a coherent explanation if I'm pushed by the examiners, and you wouldn't want me to say 'this is just what my supervisor told me to do'." This also requires some diplomacy, but basically your argument here is that you're expected to defend your thesis as your own creation and show independence, and if you just trust someone else's authority you're going to fail on that front. Lastly, in the event that you are in complete disagreement with your supervisor's suggestions, an extreme solution here may be to drop the subject altogether, as long as it is not integral to your thesis. Just say "We're clearly not seeing eye to eye on this, let's just focus on some of the other things we have been looking at". Maybe you won't even need to address this in the end.
77,019
Most PhD students I know have the problem that their supervisor is not involved enough. I have a different problem, my supervisor is too involved. He wants to be a co author on all three of my PhD papers, and to get them published. I know that this sounds great, but I do not want to free ride on my supervisors work, I want it to be my own, and I want to be proud of it. Regardless of whether it is published or not. A publication is a bonus, not the end game for me. I spent half my phd working on what I intended to be my job market paper (the paper I show to employers that best showcases my skills). My supervisor made some suggestions here and there, but nothing substantial. I am now getting ready to submit my paper to a journal and my supervisor has rewritten my entire paper without permission and wants me to sign off on this. He has justified it by saying it has a better shot of being published in its new form. I feel very uncomfortable about this, it is in effect no longer my paper. I thought he would make suggestions and I would fix the paper myself. He is too involved in other ways too. When I settle on a research question, he throws methodology and research design at me, before I have a chance to think about the topic myself and come to my own conclusions, and then encourages me to do it his way and not explore my way. Is this normal behaviour from a supervisor? I have to talk to him about this, but I am unsure how to bring it up and what to say. Do you have any advice? I need at least one paper where I am the sole author, is it appropriate to mention this to my supervisor, without offending him or his position? He will try to put his name on all my papers. I do not want to come across ungrateful, I am very happy for his help, and I will be the first to admit that I need help. But all I want is a chance to learn from my mistakes and be given opportunities to grow, I will never be a successful researcher if I cannot exercise this. Unfortunately, I feel like my supervisors research assistant instead of a PhD student. I am really struggling to continue on the course, and I appreciate any comments you may have.
2016/09/17
[ "https://academia.stackexchange.com/questions/77019", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/61988/" ]
I feel you! Being a phd researcher in social sciences isn't what I expected. It is more about doing things the right way than it is being innovative or creative. This right way is where our kind supervisors try to guide us for the articles to be published. If and when you come up with a special idea you want to do your own way, I would present this idea to your supervisor as a "crazy idea you want to try even if it means you would have to do it on your own". Just to tell your supervisor that you want to be a single author to some article doesn't sound like fair or even wise.
First off, please be aware that I have not personally put to practice the advice I am offering; this is more of an after-the-fact "I should have done that" situation. I assume that the papers you publish will be part of your thesis. I don't know enough about job-market papers or the significance of sole authorship in your field, so I'm not going to touch on that. I'm going to address two other specific problems that you mentioned. a) Your supervisor rewriting your paper: You can say "I appreciate that you made the paper more publishable, but whenever one person rewrites the work of another there's always a danger that some details in a proof/argument is accidentally misrepresented" (be careful to phrase this diplomatically so as not to imply that he's not capable enough of understanding your work - he's just not as involved with the specific details as you). "Next time, can you give me your suggestions separately and let me implement them, to eliminate this possibility?" Then you have a choice to reject some changes if you wish. They should understand where you're coming from, as even the most involved and capable supervisor can get a detail wrong. b) Your supervisor pushing their choice of methodology on you: The following solution only works in countries where the PhD presentation is more an actual examination than a formality (I'm thinking of the UK). You can say: "I don't feel that I can defend this direction of research in my upcoming examination." They'll probably say something along the lines of "Sure you can, we're doing this because of XYZ", to which you can reply "I know the justification but since this is not the direction that makes the most sense to me personally, I don't think I can offer a coherent explanation if I'm pushed by the examiners, and you wouldn't want me to say 'this is just what my supervisor told me to do'." This also requires some diplomacy, but basically your argument here is that you're expected to defend your thesis as your own creation and show independence, and if you just trust someone else's authority you're going to fail on that front. Lastly, in the event that you are in complete disagreement with your supervisor's suggestions, an extreme solution here may be to drop the subject altogether, as long as it is not integral to your thesis. Just say "We're clearly not seeing eye to eye on this, let's just focus on some of the other things we have been looking at". Maybe you won't even need to address this in the end.
77,019
Most PhD students I know have the problem that their supervisor is not involved enough. I have a different problem, my supervisor is too involved. He wants to be a co author on all three of my PhD papers, and to get them published. I know that this sounds great, but I do not want to free ride on my supervisors work, I want it to be my own, and I want to be proud of it. Regardless of whether it is published or not. A publication is a bonus, not the end game for me. I spent half my phd working on what I intended to be my job market paper (the paper I show to employers that best showcases my skills). My supervisor made some suggestions here and there, but nothing substantial. I am now getting ready to submit my paper to a journal and my supervisor has rewritten my entire paper without permission and wants me to sign off on this. He has justified it by saying it has a better shot of being published in its new form. I feel very uncomfortable about this, it is in effect no longer my paper. I thought he would make suggestions and I would fix the paper myself. He is too involved in other ways too. When I settle on a research question, he throws methodology and research design at me, before I have a chance to think about the topic myself and come to my own conclusions, and then encourages me to do it his way and not explore my way. Is this normal behaviour from a supervisor? I have to talk to him about this, but I am unsure how to bring it up and what to say. Do you have any advice? I need at least one paper where I am the sole author, is it appropriate to mention this to my supervisor, without offending him or his position? He will try to put his name on all my papers. I do not want to come across ungrateful, I am very happy for his help, and I will be the first to admit that I need help. But all I want is a chance to learn from my mistakes and be given opportunities to grow, I will never be a successful researcher if I cannot exercise this. Unfortunately, I feel like my supervisors research assistant instead of a PhD student. I am really struggling to continue on the course, and I appreciate any comments you may have.
2016/09/17
[ "https://academia.stackexchange.com/questions/77019", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/61988/" ]
Regarding the argument of an article as a single article (to get a job), I doubt that, at least in my field (chemical engineering). Every supervisor is different, so I'll just focus on my own process as a Ph.D. student and I will hope it helps you in any way. I published 6 articles on my direct Ph.D.; 4 as a first author and other 2 helping others in their projects. My first article had 24 versions (drafts) before sending it to a journal! I was *very* frustrated–until we sent it: it got accepted without a single correction in *Chemical Engineering Science* (a really nice journal for what I was doing). After that article, the level of involvement from my advisor decreased, slowly but surely: the fourth article he merely sent it as is to *Chemical Engineering Journal*. He was a co-author for all of my articles, although most of the lab work, programming (algorithms and implementation), and even the ideas were mine. Sure, we debated some ideas (mine worked at the end), but still, the lab was his, the money for research was his, the technicians helping me were his, and even the frustrating debates helped me. He helped me a lot when getting a job and still does; we collaborate as equals now. My first article as a corresponding author came up when I was in my first year as a postdoc... so my advice is: be patient, learning to be a researcher takes more than a Ph.D. nowadays; some decades ago you could be doing cutting-edge research a year after finishing your undergrad, but that is not the case nowadays. Be patient, this can only get better with time; you don't want/need an offended advisor.
This post really resonates with me as I have been in the same situation for now 6+ years as PhD and now Postdoc under a similar supervisor. I disagree with some of the comments above that imply the goal of a PhD program is simply to get papers accepted. Papers are important but the purpose of a PhD program is to develop the student as an INDEPENDENT RESEACHER. Human's learn and improve by attempting, failing and reviewing. Not by having do someone do the job for them. Has it been shown in any field this is a better approach? Unfortunately there is little supervisor training that targets this type of thing (even though student revisions are a predominant part of the supervisor's job), and each supervivor will differ greatly in their approach. I agree you need to be delicate when bringing this up. Try and voice your concerns without pointing the finger. Maybe at your next meeting ask what is their opinion on needing a student single name publication for success. And when is the best was to show case lots of skills in paper. They may come to the same conclusion.
3,000
I work currently as an IT contractor through a placement agency in Massachusetts, as a sole proprietor. I do not have any sort of liability insurance, or "workers comp" insurance for that matter. I recently applied for a consulting position with a company in Connecticut, and when they asked if I was looking for a permanent (salaried) position or contract position, I told them that I would like to work as a contractor. They told me that for that I would need to make sure that I have various insurances besides just workers comp: * One million dollars ($1,000,000.00) in comprehensive general liability insurance (each occurrence) and a minimum of three million dollars ($3,000,000.00) in comprehensive general liability insurance (aggregate) * Five million dollars ($5,000,000.00) professional liability/errors and omissions insurance * One million dollars ($1,000,000.00) automobile liability insurance covering bodily injury and property damage liability * One million dollars ($1,000,000.00) third party bond or employee dishonesty coverage indemnifying them for losses caused by dishonest acts committed by Vendor’s personnel. So the questions I wanted to ask are: A. Are these insurance requirements because my contract role with this new company would be more direct (as opposed to being through a placement agency)? B. Is it common in USA to have to get insurances like this, or are there some states where insurances are not required? (some roles that I have applied for have been in places like Texas and Arizona). C. Do US companies require insurances also from off shore companies (in other countries, like India) they hire to work remotely? (In my case here some of these insurances are probably because I am expected to work on-site, but some of them could apply to remote work as well.)
2015/03/12
[ "https://freelancing.stackexchange.com/questions/3000", "https://freelancing.stackexchange.com", "https://freelancing.stackexchange.com/users/-1/" ]
This is quite a strange request honestly. It is even stranger if you have a proper corporation/LLC that you have established. As a 1099 (sole proprietor) contractor, some of this could be attempting to force you to have the same insurance as the employer. There are a few things that I can think of as to why they require this level of insurance : * They have been burned in the past and want to make sure that if they sue you they can receive some compensation (this is what the general liability and professional liability covers). * They are operating in a regulated industry (think aircraft, other government contracts, bridge building, etc.) and require all contractors to meet the regulated standards. * They are attempting to use this as a negotiating tool (but this would be strange). The one that I find odd is the auto insurance requirement. Are you going to be driving a vehicle owned by them? Are you going to be be wearing a uniform provided by them? As a contractor, you are typically responsible for any liability from things like automobile accidents while on the job, so this requirement is *particularly strange.* The answers to your questions > > A. Are these insurance requirements because my contract role with this > new company would be more direct (as opposed to being through a > placement agency)? > > > B. Is it common in USA to have to get insurances like this, or are > there some states where insurances are not required? (some roles that > I have applied for have been in places like Texas and Arizona). > > > C. Do US companies require insurances also from off shore companies > (in other countries, like India) they hire to work remotely? (In my > case here some of these insurances are probably because I am expected > to work on-site, but some of them could apply to remote work as well.) > > > are: * I don't know, if you are acting as an actual *employee* they may be using it to try to make it look like you are really a contractor to the IRS. * It is common for consultants, contractors, and small businesses to have general liability insurance, but the complete requirements and the coverage amounts are somewhat strange. In many states the insurances aren't required, however, *as a sole proprietor* **you have no legal shield between your personal assets and your company** which can result you losing all of your personal assets if successfully sued. * No, depending on the size of the foreign company etc. This is all over the map, some large Indian companies have a US based corporation, which can be sued, and likely have liability insurance. Some guy on oDesk, probably not...
I have not had a "company" ask me anything about my insurance before. But every time I've proposed work for a government agency (A city or county in California) they have required insurance. Sometimes they will waive it. Sometimes not. But it's not as high as what this company wants of you. (Are you driving a truck for them? The high automobile insurance requirements seem odd to me.) I think it is common in the US for contractors to have general liability and errors & omissions insurance. But it's also common not to. I don't ***think*** it is ***required*** by ***law***. One reason a company might want you to get it is because if you damage something while on their property (accidentally burn the building down) General Liability would cover it. If you make a big mistake (accidentally wipe out all their data and backup.) I think Error and Omissions would cover it. I don't know if they are legally liable for your actions during your commute to/from the premises. Not sure how your auto liability would protect them. When I dealt with the cities that required the insurance they were very used to independent contractors not having insurance. One waived the requirement and the other let me raise my rate to cover the cost since I had to get it just for them. You might ask them if they will consider waiving it. If they won't, you might find out the cost then add an "administrative fee" to your proposal that covers it.
3,000
I work currently as an IT contractor through a placement agency in Massachusetts, as a sole proprietor. I do not have any sort of liability insurance, or "workers comp" insurance for that matter. I recently applied for a consulting position with a company in Connecticut, and when they asked if I was looking for a permanent (salaried) position or contract position, I told them that I would like to work as a contractor. They told me that for that I would need to make sure that I have various insurances besides just workers comp: * One million dollars ($1,000,000.00) in comprehensive general liability insurance (each occurrence) and a minimum of three million dollars ($3,000,000.00) in comprehensive general liability insurance (aggregate) * Five million dollars ($5,000,000.00) professional liability/errors and omissions insurance * One million dollars ($1,000,000.00) automobile liability insurance covering bodily injury and property damage liability * One million dollars ($1,000,000.00) third party bond or employee dishonesty coverage indemnifying them for losses caused by dishonest acts committed by Vendor’s personnel. So the questions I wanted to ask are: A. Are these insurance requirements because my contract role with this new company would be more direct (as opposed to being through a placement agency)? B. Is it common in USA to have to get insurances like this, or are there some states where insurances are not required? (some roles that I have applied for have been in places like Texas and Arizona). C. Do US companies require insurances also from off shore companies (in other countries, like India) they hire to work remotely? (In my case here some of these insurances are probably because I am expected to work on-site, but some of them could apply to remote work as well.)
2015/03/12
[ "https://freelancing.stackexchange.com/questions/3000", "https://freelancing.stackexchange.com", "https://freelancing.stackexchange.com/users/-1/" ]
This is a complicated area and the answers vary from state to state in the US also the contracting firm paying you on the 1099 might have there own idiosyncrasies based on the state where they are incorporated, or the municipality where the contract client is located, or just stuff that happened to them in the past. I don't know much about Connecticut I can only talk about my experience. I live in NJ and took my first 1099 contract position in the spring of 2015. The position was with a large foreign owned investment bank with offices in NYC and it paid a very good rate. The contractor firm insisted I have general liability coverage for 1M and Workman's compensation coverage. I had to show proof of both insurances before I could collect my first paycheck. The GL coverage cost around 500 and the WC is about 700 per year, since I obtained IRS s-corp status I am able to expense all this insurance cost. It turns out that the contracting firm I am dealing with is trying to make as much money as possible while doing as little as possible. Since they don't want to pay for workman's comp insurance, or worse yet have someone actually make a claim against said insurance, they simply push this requirement to each 1099 contractor. It's perfectly legal and it saves them a lot of headaches. Now the idea of software developers having workman's comp claims might seem funny to some people, but I can tell you that NY State takes this very seriously. As I found out the hard way after letting my coverage lapse. I received a threatening letter from NYS Workman's Compensation Board telling me that I could be fined up to $1000 per week for every week I operate without Workmen's Comp Insurance. After receiving letter I immediately got a new policy and notified them of the new coverage. I am still waiting to find out if there will be a fine, but my insurance agent thinks I can easily appeal since I am an SLLC (single member owner). I would suspect Connecticut has a similar bureaucracy that will hound you if you drop/decline the required coverage. As for the GL coverage I think this is about the contracting firm covering it's ass in the litigious sense as others has said. In my case the LLC protects my personal assets so any lawsuit recovery would be limited to the cash in my business account that I don't already owe to the government, so I guess the GL policy helps them sleep at night, that and the big pile of cash I earned them!
I have not had a "company" ask me anything about my insurance before. But every time I've proposed work for a government agency (A city or county in California) they have required insurance. Sometimes they will waive it. Sometimes not. But it's not as high as what this company wants of you. (Are you driving a truck for them? The high automobile insurance requirements seem odd to me.) I think it is common in the US for contractors to have general liability and errors & omissions insurance. But it's also common not to. I don't ***think*** it is ***required*** by ***law***. One reason a company might want you to get it is because if you damage something while on their property (accidentally burn the building down) General Liability would cover it. If you make a big mistake (accidentally wipe out all their data and backup.) I think Error and Omissions would cover it. I don't know if they are legally liable for your actions during your commute to/from the premises. Not sure how your auto liability would protect them. When I dealt with the cities that required the insurance they were very used to independent contractors not having insurance. One waived the requirement and the other let me raise my rate to cover the cost since I had to get it just for them. You might ask them if they will consider waiving it. If they won't, you might find out the cost then add an "administrative fee" to your proposal that covers it.
27,777,092
I am creating a json response in golang.I have a question that i am able to generate a json such as : ``` { "Name" : "Country", "Value" : "abc" } ``` The value of name and value can change based on the user and the struct I am using is like: ``` type xAxis struct { Name string, Value string } ``` I want my json to look like this: ``` { "Country" : "abc" } ``` Is it possible to create the json like this?
2015/01/05
[ "https://Stackoverflow.com/questions/27777092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3481046/" ]
you can override the way Go's json package marshals a struct by writing a custom `MarshalJSON` function: ``` type xAxis struct { Name string Value string } func (a xAxis) MarshalJSON() ([]byte, error) { return json.Marshal(map[string]interface{}{a.Name: a.Value}) } ``` to try it: <http://play.golang.org/p/G_E4IpNYIz>
The `encoding/json` package allows you to use a map instead of a struct. That's probably not as performant as structures, but it works. ``` data := map[string]string { "Country": "abc", "Foo": "bar", } // Creating JSON from a map j, err := json.Marshal(data) if err != nil { log.Fatal(err) } fmt.Println(string(j)) // ==> {"Country":"abc","Foo":"bar"} // Creating map from JSON var data2 map[string]string err = json.Unmarshal(j, &data2) if err != nil { log.Fatal(err) } fmt.Println(data2) // ==> map[Country:abc Foo:bar] ```
42,515,859
So I am trying to get my head around AWS Cognito but I have hit some walls. So, right now I can register an account, and verify it and sign in. Simple enough. The edge cases are where my walls are. Here's the info I have so far: * `username`'s cannot be changed once created * I am using UUIDs as my `username` values * `email` is marked as an **alias**, which in Cognito terms means I can use it to sign in with in addition to `username`. * if `email` is chosen as an **alias**, per the docs, the same value cannot be used as the username (<http://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-aliases>): > > If email is selected as an alias, a username cannot match a valid email format. Similarly, if phone number is selected as an alias, a username that matches a valid phone number pattern will not be accepted by the service for that user pool. > > > * The `email` address can **ONLY** be used to sign in once the account has been **verified** (<http://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#user-pool-settings-aliases>) > > Phone numbers and email addresses only become active aliases for a user after the phone numbers and email addresses have been verified. We therefore recommend that you choose automatic verification of email addresses and phone numbers if you choose to use them as aliases. > > > Here in lies my edge case. If a user signs up, but does **NOT** immediately verify: * they get called away * maybe the app crashes * they lose connectivity * their battery dies * they force quit * app get's accidentally deleted. In their mind they have signed up just not verified their account. At this point it effectively leaves no way to verify their account they thought they signed up for. I guess it could be solved with messaging: "Warning your account will not be created until you verify your email address." or something along those lines. Anyway... * They can't attempt to sign in as they won't know the UUID that was randomly assigned as their `username`. * Even if that wasn't the case, they provided their email address as their username. From the user's POV they would have no idea what their `username` could even be since they only entered their email address. * The best they could hope for is to try to sign up again. (Assuming they read the verification warning above) In this case now Cognito potentially has abandoned **unconfirmed** accounts piling up. "Piling up" may be too strong a phrase, this is likely a pretty fringe case. Now the plus side is, since they have not "verified" their `email` they can sign up again with the same `email` address since the `email` doesn't get uniquely constrained until it's `verified`. If someone tries to verify an address that has already been verified they get a `AliasExistsException`. This actually brings up an interesting point which I just tested as well. I can register with an email address, then verify that email address so the account becomes confirmed. I can then turn right around and sign up with the **same** email address and I don't get an official AWS error until I try go to verify that account with the duplicate email address. There isn't any way to surface this error earlier? I guess the expectation is that it's on the developer to write a verification service in the Pre-Signup Trigger: > > This trigger is invoked when a user submits their information to sign up, allowing you to perform custom validation to accept or deny the sign up request. > > > To sum up, and to restate the question: It seems to be **required**, practically speaking, that when using an email address with Cognito a Pre-Signup Lambda is required to ensure an account with an email doesn't already exist since the AWS Exception won't be handled until a verification attempt is made. Is my assumption here correct? By **required** here I think it's pretty reasonable to let a user know an email address is not available as soon as possible. For example: ``` John Doe : jdoe@gmail.com Jane Doe : jdoe@gmail.com ```
2017/02/28
[ "https://Stackoverflow.com/questions/42515859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1060314/" ]
You are correct. Another solution is to create a lambda (not triggered by preSignUp) and called whenever the user finished typing into the email field. And getting a response "This email is already used" or "This email is available" before even sending the sign-up event. Referring the first part of your question. If the user does not immediately verify their email. You probably mean confirmation by code. I prefer using confirmation by link sent to email which avoids this problem.
Knowing that this is an old question, here's a solution for posterity... I am using generated UUIDs for usernames, just like you, undisclosed to the user. When the user wants to confirm the code at a later time (or perhaps ask to resend it), he doesn't know the username but he does know the email address that he registered with... You can search for Cognito users with a certain email (or any other attribute) using [ListUsers](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsers.html) with a filter like `email = "user@signupemail.com"`. Once you find the user, you can access their username via `response.Users[0].Username`, and use it to [confirm the account](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmSignUp.html).
10,269,764
I have a problem that I've searched the internet for a solution for with no avail. I'm following along in chapter 10 of Apress' Beginning iOS 5 development which is on storyboards. I'm thinking the book is missing a simple piece of code and since I'm going through this for the first time, I don't know how to resolve it. I've restarted the project twice, but keep getting this error in the debugger: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:' ``` #import "BIDTaskListController.h" @interface BIDTaskListController () @property (strong, nonatomic) NSArray *tasks; @end @implementation BIDTaskListController @synthesize tasks; - (void)viewDidLoad { [super viewDidLoad]; self.tasks = [NSArray arrayWithObjects: @"Walk the dog", @"URGENT:Buy milk", @"Clean hidden lair", @"Invent miniature dolphins", @"Find new henchmen", @"Get revenge on do-gooder heroes", @"URGENT: Fold laundry", @"Hold entire world hostage", @"Manicure", nil]; } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; self.tasks = nil; } ``` // ``` - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation == UIInterfaceOrientationPortrait); } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return [tasks count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *identifier = nil; NSString *task = [self.tasks objectAtIndex:indexPath.row]; NSRange urgentRange = [task rangeOfString:@"URGENT"]; if (urgentRange.location == NSNotFound) { identifier = @"plainCell"; } else { identifier = @"attentionCell"; } UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; UILabel *cellLabel = (UILabel *)[cell viewWithTag:1]; cellLabel.text = task; return cell; } @end ```
2012/04/22
[ "https://Stackoverflow.com/questions/10269764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1349737/" ]
You need to enclose your function using raw pointers in an `unsafe` block. ``` unsafe { //your code } ```
Perhaps I've missed it, but you don't appear to be doing anything that actually requires the use of a `int*`. Why not simply pass it an int array and change the ParseBits function signature to: `public int ParseBits(string bits, **int[]** buffer)` and remove the `unsafe{ ... }` blocks altogether.
10,269,764
I have a problem that I've searched the internet for a solution for with no avail. I'm following along in chapter 10 of Apress' Beginning iOS 5 development which is on storyboards. I'm thinking the book is missing a simple piece of code and since I'm going through this for the first time, I don't know how to resolve it. I've restarted the project twice, but keep getting this error in the debugger: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:' ``` #import "BIDTaskListController.h" @interface BIDTaskListController () @property (strong, nonatomic) NSArray *tasks; @end @implementation BIDTaskListController @synthesize tasks; - (void)viewDidLoad { [super viewDidLoad]; self.tasks = [NSArray arrayWithObjects: @"Walk the dog", @"URGENT:Buy milk", @"Clean hidden lair", @"Invent miniature dolphins", @"Find new henchmen", @"Get revenge on do-gooder heroes", @"URGENT: Fold laundry", @"Hold entire world hostage", @"Manicure", nil]; } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; self.tasks = nil; } ``` // ``` - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation == UIInterfaceOrientationPortrait); } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return [tasks count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *identifier = nil; NSString *task = [self.tasks objectAtIndex:indexPath.row]; NSRange urgentRange = [task rangeOfString:@"URGENT"]; if (urgentRange.location == NSNotFound) { identifier = @"plainCell"; } else { identifier = @"attentionCell"; } UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; UILabel *cellLabel = (UILabel *)[cell viewWithTag:1]; cellLabel.text = task; return cell; } @end ```
2012/04/22
[ "https://Stackoverflow.com/questions/10269764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1349737/" ]
You need to enclose your function using raw pointers in an `unsafe` block. ``` unsafe { //your code } ```
I had the same problem, but it wasn't solved by any of the other answers up here. I kept getting different errors. Whatever functions use unsafe code simply need to be declared with the "unsafe" keyword. For example: ``` static unsafe void myFunction(int* myInt, float* myFloat) { // Function definition } ``` Personally, I was trying to do this when making a wrapper class. For those interested, it ended up looking something like this: ``` using System.Runtime.InteropServices; namespace myNamespace { public class myClass { [DllImport("myLib.so", EntryPoint = "myFunction")] public static extern unsafe void myFunction(float* var1, float* var2); } } ``` Theres a lot of great information in the MSDN "Unsafe Code Tutorial": <https://msdn.microsoft.com/en-us/library/aa288474(v=vs.71).aspx> It's probably worth a read, I found it quite useful.
10,269,764
I have a problem that I've searched the internet for a solution for with no avail. I'm following along in chapter 10 of Apress' Beginning iOS 5 development which is on storyboards. I'm thinking the book is missing a simple piece of code and since I'm going through this for the first time, I don't know how to resolve it. I've restarted the project twice, but keep getting this error in the debugger: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:' ``` #import "BIDTaskListController.h" @interface BIDTaskListController () @property (strong, nonatomic) NSArray *tasks; @end @implementation BIDTaskListController @synthesize tasks; - (void)viewDidLoad { [super viewDidLoad]; self.tasks = [NSArray arrayWithObjects: @"Walk the dog", @"URGENT:Buy milk", @"Clean hidden lair", @"Invent miniature dolphins", @"Find new henchmen", @"Get revenge on do-gooder heroes", @"URGENT: Fold laundry", @"Hold entire world hostage", @"Manicure", nil]; } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; self.tasks = nil; } ``` // ``` - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation == UIInterfaceOrientationPortrait); } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return [tasks count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *identifier = nil; NSString *task = [self.tasks objectAtIndex:indexPath.row]; NSRange urgentRange = [task rangeOfString:@"URGENT"]; if (urgentRange.location == NSNotFound) { identifier = @"plainCell"; } else { identifier = @"attentionCell"; } UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; UILabel *cellLabel = (UILabel *)[cell viewWithTag:1]; cellLabel.text = task; return cell; } @end ```
2012/04/22
[ "https://Stackoverflow.com/questions/10269764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1349737/" ]
Perhaps I've missed it, but you don't appear to be doing anything that actually requires the use of a `int*`. Why not simply pass it an int array and change the ParseBits function signature to: `public int ParseBits(string bits, **int[]** buffer)` and remove the `unsafe{ ... }` blocks altogether.
I had the same problem, but it wasn't solved by any of the other answers up here. I kept getting different errors. Whatever functions use unsafe code simply need to be declared with the "unsafe" keyword. For example: ``` static unsafe void myFunction(int* myInt, float* myFloat) { // Function definition } ``` Personally, I was trying to do this when making a wrapper class. For those interested, it ended up looking something like this: ``` using System.Runtime.InteropServices; namespace myNamespace { public class myClass { [DllImport("myLib.so", EntryPoint = "myFunction")] public static extern unsafe void myFunction(float* var1, float* var2); } } ``` Theres a lot of great information in the MSDN "Unsafe Code Tutorial": <https://msdn.microsoft.com/en-us/library/aa288474(v=vs.71).aspx> It's probably worth a read, I found it quite useful.
69,946,919
To explain my problem, I'm a beginner in Python and I've got to do a loop in Python to make an automatic map production in Qgis. There are 2 facts. The first is that I'm using the French Government's API called "Addresses" that return addresses (and many data linked to this address) from geographic coordinates. When I run my code in the Qgis python console, the response is 200 but I don't see anything appearing. This is a real problem for me because I want to import those pieces of information into my Layout and I don't know how to do this too (this is the second fact). Here I show you the code I have with the API : ``` for feat in mylayer.getFeatures(): Shops_name = feat['nom_sho'] x = feat['x'] #x and Y stands for longitude and latitude y = feat['y'] x = str(x) y = str(y) date = datetime.date.today() today = str(date) expr = u"nom_sho = '{}'".format(Shops_name) myselect = mylayer.getFeatures( QgsFeatureRequest().setFilterExpression ( expr )) iface.mapCanvas().zoomToSelected(mylayer) iface.mapCanvas().zoomScale(1625) print(f"Voici {Shops_name}" ) mylayer.selectByIds( [ f.id() for f in myselect ] ) project = QgsProject.instance() manager = project.layoutManager() layoutName = str(Shops_name) #layout layouts_list = manager.printLayouts() for layout in layouts_list: if layout.name() == layoutName: manager.removeLayout(layout) layout = QgsPrintLayout(project) layout.initializeDefaults() layout.setName(layoutName) manager.addLayout(layout) #symbology symbol_shop = QgsMarkerSymbol.createSimple({'name': 'Triangle', 'color': '#0088CC', 'outline_color': 'black', 'size': '4'}) symbol_shop_selected = QgsMarkerSymbol.createSimple({'name': 'Triangle', 'color': 'blue', 'outline_color': 'black', 'size': '7'}) color_shop = QgsRendererCategory(None,symbol_shop,"Other shops",True) color_shop_selected = QgsRendererCategory(layoutName,symbol_shop_selected,layoutName,True) renderer = QgsCategorizedSymbolRenderer("nom_sho", [color_shop,color_shop_selected]) mylayer.setRenderer(renderer) mylayer.triggerRepaint() # empty map map = QgsLayoutItemMap(layout) map.setRect(20, 20, 20, 20) # layout2 rectangle = QgsRectangle(1355502, -46398, 1734534, 137094) map.setExtent(rectangle) layout.addLayoutItem(map) # Canva update canvas = iface.mapCanvas() map.setExtent(canvas.extent()) layout.addLayoutItem(map) # Resize map map.attemptMove(QgsLayoutPoint(5, 27, QgsUnitTypes.LayoutMillimeters)) map.attemptResize(QgsLayoutSize(220, 178, QgsUnitTypes.LayoutMillimeters)) # Legende tree_layers = project.layerTreeRoot().children() checked_layers = [layer.name() for layer in tree_layers if layer.isVisible()] layers_to_remove = [layer for layer in project.mapLayers().values() if layer.name() not in checked_layers] legend = QgsLayoutItemLegend(layout) legend.setTitle(html.unescape("L&eacute;gende")) legend.setStyleFont(QgsLegendStyle.Title, myBoldFont) layout.addLayoutItem(legend) legend.attemptMove(QgsLayoutPoint(230, 24, QgsUnitTypes.LayoutMillimeters)) legend.setAutoUpdateModel(False) m = legend.model() g = m.rootGroup() for l in layers_to_remove: g.removeLayer(l) g.removeLayer(osm) legend.adjustBoxSize() #api r = requests.get("https://api-adresse.data.gouv.fr/reverse/?lon="+x+"&lat="+y+"") r.json() print(r) # Title title = QgsLayoutItemLabel(layout) title.setText(layoutName) title.setFont(myTitleBoldFont) title.adjustSizeToText() layout.addLayoutItem(title) title.attemptMove(QgsLayoutPoint(5, 4, QgsUnitTypes.LayoutMillimeters)) # Subtitle subtitle = QgsLayoutItemLabel(layout) subtitle.setFont(QFont("Verdana", 18)) subtitle.adjustSizeToText() layout.addLayoutItem(subtitle) subtitle.attemptMove(QgsLayoutPoint(5, 18, QgsUnitTypes.LayoutMillimeters)) # Scale scalebar = QgsLayoutItemScaleBar(layout) scalebar.setStyle('Single Box') scalebar.setUnits(QgsUnitTypes.DistanceMeters) scalebar.setNumberOfSegments(2) scalebar.setNumberOfSegmentsLeft(0) scalebar.setUnitsPerSegment(25) scalebar.setLinkedMap(map) scalebar.setUnitLabel('km') scalebar.setFont(QFont('Verdana', 20)) scalebar.update() layout.addLayoutItem(scalebar) scalebar.attemptMove(QgsLayoutPoint(10, 185, QgsUnitTypes.LayoutMillimeters)) ``` Thank you for your help.
2021/11/12
[ "https://Stackoverflow.com/questions/69946919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17397602/" ]
My answer includes the potential for skipped steps which OP mentioned in comments. Rather than using a strictly matching sequence this approach looks for adjacent pairs where the preceding step was numbered higher: ``` with A as ( select *, case status when 'CLICKED' then 1 when 'CLAIMED' then 2 when 'BOUGHT' then 3 end as desired_order from T ), B as ( select *, row_number() over ( partition by number_id order by datetime, desired_order) as rn -- handles date ties from A ), C as ( select *, -- look for pairs of rows where one is reversed case when lag(desired_order) over (partition by number_id order by rn) > desired_order then 'Y' end as flag from B ) select number_id, min(country) as country, case min(flag) when 'Y' then 'Out of order' else 'In order' end as "status" from C group by number_id; ``` <https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=f0ee1de8e8e81229ddc23acc97bce7d7> As Thorston pointed out, you could also take the approach of generating a pair of row numbers and then comparing the two looking for mismatches. Glancing at the query plans this may involve an extra sort operation so it would be worth trying both ways on your data. ``` ... ), B as ( select *, row_number() over ( partition by number_id order by desired_order) as rn1, row_number() over ( partition by number_id order by datetime, desired_order) as rn2 from A ) select number_id, min(country) as country, case when max(case when rn1 <> rn2 then 1 else 0 end) = 1 then 'Out of order' else 'In order' end as status ... ```
Here is one way using some string aggregation and manipulations. This works as expected against the sample data and also accounts for edge cases that include skipping status, missing status, and single status. ``` with cte as (select *,listagg(status,'>') within group (order by datetime,charindex(status,'CLICKED>CLAIMED>BOUGHT')) over (partition by number_id, country) as event_order from t) select distinct number_id, country, case when charindex(event_order,'CLICKED>CLAIMED>BOUGHT,CLICKED>BOUGHT')>0 then 'Ordered' else 'Unordered' end as order_flag from cte order by number_id; ```
69,946,919
To explain my problem, I'm a beginner in Python and I've got to do a loop in Python to make an automatic map production in Qgis. There are 2 facts. The first is that I'm using the French Government's API called "Addresses" that return addresses (and many data linked to this address) from geographic coordinates. When I run my code in the Qgis python console, the response is 200 but I don't see anything appearing. This is a real problem for me because I want to import those pieces of information into my Layout and I don't know how to do this too (this is the second fact). Here I show you the code I have with the API : ``` for feat in mylayer.getFeatures(): Shops_name = feat['nom_sho'] x = feat['x'] #x and Y stands for longitude and latitude y = feat['y'] x = str(x) y = str(y) date = datetime.date.today() today = str(date) expr = u"nom_sho = '{}'".format(Shops_name) myselect = mylayer.getFeatures( QgsFeatureRequest().setFilterExpression ( expr )) iface.mapCanvas().zoomToSelected(mylayer) iface.mapCanvas().zoomScale(1625) print(f"Voici {Shops_name}" ) mylayer.selectByIds( [ f.id() for f in myselect ] ) project = QgsProject.instance() manager = project.layoutManager() layoutName = str(Shops_name) #layout layouts_list = manager.printLayouts() for layout in layouts_list: if layout.name() == layoutName: manager.removeLayout(layout) layout = QgsPrintLayout(project) layout.initializeDefaults() layout.setName(layoutName) manager.addLayout(layout) #symbology symbol_shop = QgsMarkerSymbol.createSimple({'name': 'Triangle', 'color': '#0088CC', 'outline_color': 'black', 'size': '4'}) symbol_shop_selected = QgsMarkerSymbol.createSimple({'name': 'Triangle', 'color': 'blue', 'outline_color': 'black', 'size': '7'}) color_shop = QgsRendererCategory(None,symbol_shop,"Other shops",True) color_shop_selected = QgsRendererCategory(layoutName,symbol_shop_selected,layoutName,True) renderer = QgsCategorizedSymbolRenderer("nom_sho", [color_shop,color_shop_selected]) mylayer.setRenderer(renderer) mylayer.triggerRepaint() # empty map map = QgsLayoutItemMap(layout) map.setRect(20, 20, 20, 20) # layout2 rectangle = QgsRectangle(1355502, -46398, 1734534, 137094) map.setExtent(rectangle) layout.addLayoutItem(map) # Canva update canvas = iface.mapCanvas() map.setExtent(canvas.extent()) layout.addLayoutItem(map) # Resize map map.attemptMove(QgsLayoutPoint(5, 27, QgsUnitTypes.LayoutMillimeters)) map.attemptResize(QgsLayoutSize(220, 178, QgsUnitTypes.LayoutMillimeters)) # Legende tree_layers = project.layerTreeRoot().children() checked_layers = [layer.name() for layer in tree_layers if layer.isVisible()] layers_to_remove = [layer for layer in project.mapLayers().values() if layer.name() not in checked_layers] legend = QgsLayoutItemLegend(layout) legend.setTitle(html.unescape("L&eacute;gende")) legend.setStyleFont(QgsLegendStyle.Title, myBoldFont) layout.addLayoutItem(legend) legend.attemptMove(QgsLayoutPoint(230, 24, QgsUnitTypes.LayoutMillimeters)) legend.setAutoUpdateModel(False) m = legend.model() g = m.rootGroup() for l in layers_to_remove: g.removeLayer(l) g.removeLayer(osm) legend.adjustBoxSize() #api r = requests.get("https://api-adresse.data.gouv.fr/reverse/?lon="+x+"&lat="+y+"") r.json() print(r) # Title title = QgsLayoutItemLabel(layout) title.setText(layoutName) title.setFont(myTitleBoldFont) title.adjustSizeToText() layout.addLayoutItem(title) title.attemptMove(QgsLayoutPoint(5, 4, QgsUnitTypes.LayoutMillimeters)) # Subtitle subtitle = QgsLayoutItemLabel(layout) subtitle.setFont(QFont("Verdana", 18)) subtitle.adjustSizeToText() layout.addLayoutItem(subtitle) subtitle.attemptMove(QgsLayoutPoint(5, 18, QgsUnitTypes.LayoutMillimeters)) # Scale scalebar = QgsLayoutItemScaleBar(layout) scalebar.setStyle('Single Box') scalebar.setUnits(QgsUnitTypes.DistanceMeters) scalebar.setNumberOfSegments(2) scalebar.setNumberOfSegmentsLeft(0) scalebar.setUnitsPerSegment(25) scalebar.setLinkedMap(map) scalebar.setUnitLabel('km') scalebar.setFont(QFont('Verdana', 20)) scalebar.update() layout.addLayoutItem(scalebar) scalebar.attemptMove(QgsLayoutPoint(10, 185, QgsUnitTypes.LayoutMillimeters)) ``` Thank you for your help.
2021/11/12
[ "https://Stackoverflow.com/questions/69946919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17397602/" ]
Using ARRAY\_AGG ordered by datetime: ``` SELECT number_id, ARRAY_AGG(status) WITHIN GROUP(ORDER BY datetime) AS statuses, -- debug CASE WHEN ARRAY_AGG(status) WITHIN GROUP(ORDER BY datetime) IN (ARRAY_CONSTRUCT('CLICKED', 'CLAIMED', 'BOUGHT'), ARRAY_CONSTRUCT('CLICKED', 'CLAIMED')) THEN 'In order' ELSE 'Out of order' END AS status FROM TBL_A GROUP BY number_id; ``` Output: [![enter image description here](https://i.stack.imgur.com/JkNN4.png)](https://i.stack.imgur.com/JkNN4.png)
Here is one way using some string aggregation and manipulations. This works as expected against the sample data and also accounts for edge cases that include skipping status, missing status, and single status. ``` with cte as (select *,listagg(status,'>') within group (order by datetime,charindex(status,'CLICKED>CLAIMED>BOUGHT')) over (partition by number_id, country) as event_order from t) select distinct number_id, country, case when charindex(event_order,'CLICKED>CLAIMED>BOUGHT,CLICKED>BOUGHT')>0 then 'Ordered' else 'Unordered' end as order_flag from cte order by number_id; ```
43,332,208
**UPDATE: PROBLEM FIXED** - The ActionBar was covering the first item on the list. **SOLUTION:** [Android AppBarLayout overlaps listview](https://stackoverflow.com/questions/32653767/android-appbarlayout-overlaps-listview) In my program, I am retrieving data from the database and displaying it using List View. However, the first row elements are always skipped in the process and the display begins from the second row. ``` public void displaydata(){ Cursor res = myDb.getAllData(); lv = (ListView) findViewById(R.id.idListView); if(res.getCount() == 0){ //show message return; } ArrayList<String> buffer = new ArrayList<>(); while(res.moveToNext()){ buffer.add(res.getString(1)); }; ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,buffer); lv.setAdapter(adapter); } ``` How do I make it display from the first row? Any help is appreciated, thanks. EDIT: I have tried all suggested answers of using a 'do-while' and a 'for loop', all of which give the same result.
2017/04/10
[ "https://Stackoverflow.com/questions/43332208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4242616/" ]
Try changing ``` while(res.moveToNext()){ buffer.add(res.getString(1)); }; ``` to Edit: change the while so it increments after: ``` do { buffer.add(res.getString(1)); } while (cursor.moveToNext()); ```
Personally, I would recommend a `CursorAdapter` when using a database. ``` lv = (ListView) findViewById(R.id.idListView); String from = { COLUMN_NAME }; int[] to = { android.R.id.text1 }; SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, myDb.getAllData(), from, to); lv.setAdapter(adapter); ```
43,332,208
**UPDATE: PROBLEM FIXED** - The ActionBar was covering the first item on the list. **SOLUTION:** [Android AppBarLayout overlaps listview](https://stackoverflow.com/questions/32653767/android-appbarlayout-overlaps-listview) In my program, I am retrieving data from the database and displaying it using List View. However, the first row elements are always skipped in the process and the display begins from the second row. ``` public void displaydata(){ Cursor res = myDb.getAllData(); lv = (ListView) findViewById(R.id.idListView); if(res.getCount() == 0){ //show message return; } ArrayList<String> buffer = new ArrayList<>(); while(res.moveToNext()){ buffer.add(res.getString(1)); }; ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,buffer); lv.setAdapter(adapter); } ``` How do I make it display from the first row? Any help is appreciated, thanks. EDIT: I have tried all suggested answers of using a 'do-while' and a 'for loop', all of which give the same result.
2017/04/10
[ "https://Stackoverflow.com/questions/43332208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4242616/" ]
Try changing ``` while(res.moveToNext()){ buffer.add(res.getString(1)); }; ``` to Edit: change the while so it increments after: ``` do { buffer.add(res.getString(1)); } while (cursor.moveToNext()); ```
Try out this this code may be useful for fetching data from db using cursor. ``` public ArrayList<BasicInfo> getFetchBasicInfo() { ArrayList<BasicInfo> data = new ArrayList<BasicInfo>(); String sql = "select * from basic_info; Cursor c = fetchData(sql); if (c != null) { while (c.moveToNext()) { String FirstName = c.getString(c.getColumnIndex("first_name")); String LastName = c.getString(c.getColumnIndex("last_name")); String Sabcription = c.getString(c .getColumnIndex("salutation_id")); data.add(new BasicInfo(FirstName, LastName)); } c.close(); } return data; } ```
31,322,347
I need a fast way to check if a 2d array is entirely adjacent, meaning all values are adjacent to other same values. Adjacent means the four cardinal directions. ``` This would be an adjacent array [1 1 2] [1 2 2] [3 3 3] This isn't [1 2 1] [1 2 2] [3 3 3] This is [1 2 4] [1 2 2] [3 3 3] ``` So far, I've tried an O(M \* N) method where I go through the whole array and check if at least one of the neighbors is the same value. I'm looking for a possibly faster way. EDIT: just noticed my method doesn't even work correctly. eg: ``` This should fail (not all of the 1s are adjacent) [1 2 1] [1 2 1] [3 3 3] ``` So now I need an actual algorithm for this.
2015/07/09
[ "https://Stackoverflow.com/questions/31322347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3273194/" ]
I'm reminded of the game Minesweeper. 1. Outer loop: Scan the entire array (row by row, from left to right). This is to find the next position for the inner loop. If we have not visited this position from the inner loop, and the number at this position has not yet been seen, start the inner loop at this position. If we have already seen the number at this position, then the matrix is not "adjacent". 2. Inner loop: Find all adjacent cells with the same number and mark them as visited (the Minesweeper part). Record this number as visited and return to the outer loop. This requires a boolean matrix showing "visited" positions (the same size as the array being scanned) and a boolean list of numbers [1..n] that have been "visited".
Since, I assume, similar values can be arbitrarily far from each other, and can take any shape, in the matrix I don't see how you do it with out first computing the connected components of the values: 1. Find the [connected components labeling](https://en.wikipedia.org/wiki/Connected-component_labeling) of your matrix 2. For each matrix value keep a list of the component label it belongs to. 3. If any value already has a label associated with it, stop, the matrix is not "adjacent". If none, then the matrix is "adjacent".
31,322,347
I need a fast way to check if a 2d array is entirely adjacent, meaning all values are adjacent to other same values. Adjacent means the four cardinal directions. ``` This would be an adjacent array [1 1 2] [1 2 2] [3 3 3] This isn't [1 2 1] [1 2 2] [3 3 3] This is [1 2 4] [1 2 2] [3 3 3] ``` So far, I've tried an O(M \* N) method where I go through the whole array and check if at least one of the neighbors is the same value. I'm looking for a possibly faster way. EDIT: just noticed my method doesn't even work correctly. eg: ``` This should fail (not all of the 1s are adjacent) [1 2 1] [1 2 1] [3 3 3] ``` So now I need an actual algorithm for this.
2015/07/09
[ "https://Stackoverflow.com/questions/31322347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3273194/" ]
Since, I assume, similar values can be arbitrarily far from each other, and can take any shape, in the matrix I don't see how you do it with out first computing the connected components of the values: 1. Find the [connected components labeling](https://en.wikipedia.org/wiki/Connected-component_labeling) of your matrix 2. For each matrix value keep a list of the component label it belongs to. 3. If any value already has a label associated with it, stop, the matrix is not "adjacent". If none, then the matrix is "adjacent".
I just want to mention that you can't create an algorithm which is better than `O(M*N)`(of course this is worst case complexity), because in worst case you will have to visit all the elements. As you said your `O(M*N)` algorithm does not work for all cases, you can solve this using BFS and `Time complexity is O(M*N)` ``` if(no.of connected components == no.of distinct elements) { return true; }else{ return false; } ``` How do you find number of connected components? ``` yourFunction(int[][] matrix){ boolean visited[][]; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(!visited[i][j]){ BFS(matrix,i,j); connectedComponents++; } } } int distinctNumbers = findDistinctNumbers(matrix); // you can write this function easily. } void BFS(int[][] martix, int i,int j){ queue<Point> queue = new LinkedList<>(); queue.add(new Point(i,j)); while(queue.isEmpty()){ Point point = queue.poll(); for each neighbour of point if neighbour is not visited && neighbour value =current point value add neighbour to queue; } } ```
31,322,347
I need a fast way to check if a 2d array is entirely adjacent, meaning all values are adjacent to other same values. Adjacent means the four cardinal directions. ``` This would be an adjacent array [1 1 2] [1 2 2] [3 3 3] This isn't [1 2 1] [1 2 2] [3 3 3] This is [1 2 4] [1 2 2] [3 3 3] ``` So far, I've tried an O(M \* N) method where I go through the whole array and check if at least one of the neighbors is the same value. I'm looking for a possibly faster way. EDIT: just noticed my method doesn't even work correctly. eg: ``` This should fail (not all of the 1s are adjacent) [1 2 1] [1 2 1] [3 3 3] ``` So now I need an actual algorithm for this.
2015/07/09
[ "https://Stackoverflow.com/questions/31322347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3273194/" ]
I'm reminded of the game Minesweeper. 1. Outer loop: Scan the entire array (row by row, from left to right). This is to find the next position for the inner loop. If we have not visited this position from the inner loop, and the number at this position has not yet been seen, start the inner loop at this position. If we have already seen the number at this position, then the matrix is not "adjacent". 2. Inner loop: Find all adjacent cells with the same number and mark them as visited (the Minesweeper part). Record this number as visited and return to the outer loop. This requires a boolean matrix showing "visited" positions (the same size as the array being scanned) and a boolean list of numbers [1..n] that have been "visited".
I just want to mention that you can't create an algorithm which is better than `O(M*N)`(of course this is worst case complexity), because in worst case you will have to visit all the elements. As you said your `O(M*N)` algorithm does not work for all cases, you can solve this using BFS and `Time complexity is O(M*N)` ``` if(no.of connected components == no.of distinct elements) { return true; }else{ return false; } ``` How do you find number of connected components? ``` yourFunction(int[][] matrix){ boolean visited[][]; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(!visited[i][j]){ BFS(matrix,i,j); connectedComponents++; } } } int distinctNumbers = findDistinctNumbers(matrix); // you can write this function easily. } void BFS(int[][] martix, int i,int j){ queue<Point> queue = new LinkedList<>(); queue.add(new Point(i,j)); while(queue.isEmpty()){ Point point = queue.poll(); for each neighbour of point if neighbour is not visited && neighbour value =current point value add neighbour to queue; } } ```
146
How should we deal with questions that are posted simultaneously at Unix.SE and another Stack Exchange site? I've found some discussion on [Meta Stack Overflow](http://meta.stackoverflow.com), but no official policy: * [Cross-posting on StackExchange sites](https://meta.stackexchange.com/questions/65931/cross-posting-on-stackexchange-sites) has answers recommending to multi-post only if the question hasn't had good answers on the first site, and to create links between questions. * [This question](https://meta.stackexchange.com/questions/11600/allow-cross-posting-between-serverfault-com-and-superuser-com) and [this question](https://meta.stackexchange.com/questions/32234/is-it-ok-to-ask-something-on-so-which-has-been-already-asked-unsuccessfully-on-su) each had one answer discouraging multiposting. This is especially a concern here since most questions would also be on-topic at one or more of [Stack Overflow](http://stackoverflow.com), [Super User](http://superuser.com), [Server Fault](http://serverfault.com), [Ubuntu.SE](http://ubuntu.stackexchange.com). I recently echoed [Robert Cartaino's answer](https://meta.stackexchange.com/questions/11600/allow-cross-posting-between-serverfault-com-and-superuser-com/11633#11633) in a comment to [this question](https://unix.stackexchange.com/questions/1677), but it's nothing like an official policy or at least an FAQ entry.
2010/09/19
[ "https://unix.meta.stackexchange.com/questions/146", "https://unix.meta.stackexchange.com", "https://unix.meta.stackexchange.com/users/885/" ]
At the moment we don't deal with it at all. We can't migrate then merge... or anything like that. Basically our hands are tied. Plus I've no interest in watching for cross posting. Actually I've been encouraging cross posting due to lack of migration capabilities in a way. Since I tell people "you'd be better off asking on X". In the future "Migrate and Merge" might be the most appropriate solution.
I think if someone posts an Ubuntu-specific question both here and on Ask Ubuntu, it should be closed here. I say this because I really care about quality, and Ubuntu folk are surely going to give a superior Answer (and it's a larger community too, so will have a quicker response). As for Super User, I think both Ask Ubuntu and Unix & Linux supercede it, and it should be restricted to Questions about Windows, Hardware, cross-platform apps..., but that's another topic.
146
How should we deal with questions that are posted simultaneously at Unix.SE and another Stack Exchange site? I've found some discussion on [Meta Stack Overflow](http://meta.stackoverflow.com), but no official policy: * [Cross-posting on StackExchange sites](https://meta.stackexchange.com/questions/65931/cross-posting-on-stackexchange-sites) has answers recommending to multi-post only if the question hasn't had good answers on the first site, and to create links between questions. * [This question](https://meta.stackexchange.com/questions/11600/allow-cross-posting-between-serverfault-com-and-superuser-com) and [this question](https://meta.stackexchange.com/questions/32234/is-it-ok-to-ask-something-on-so-which-has-been-already-asked-unsuccessfully-on-su) each had one answer discouraging multiposting. This is especially a concern here since most questions would also be on-topic at one or more of [Stack Overflow](http://stackoverflow.com), [Super User](http://superuser.com), [Server Fault](http://serverfault.com), [Ubuntu.SE](http://ubuntu.stackexchange.com). I recently echoed [Robert Cartaino's answer](https://meta.stackexchange.com/questions/11600/allow-cross-posting-between-serverfault-com-and-superuser-com/11633#11633) in a comment to [this question](https://unix.stackexchange.com/questions/1677), but it's nothing like an official policy or at least an FAQ entry.
2010/09/19
[ "https://unix.meta.stackexchange.com/questions/146", "https://unix.meta.stackexchange.com", "https://unix.meta.stackexchange.com/users/885/" ]
We're in line with the SE policy on this now; the [FAQ](https://unix.stackexchange.com/faq) explicitly discourages cross-posting: > > Cross-posting is [strongly discouraged](https://meta.stackexchange.com/questions/71938/can-i-cross-post-my-question-from-one-site-to-another/71949#71949) -- if you post on one site and then change your mind it can always be migrated to another. If you're not sure if your question is on-topic, [ask on meta](https://unix.meta.stackexchange.com/questions/ask) or just [give it a try](https://unix.stackexchange.com/questions/ask) and the community will decide. > > >
At the moment we don't deal with it at all. We can't migrate then merge... or anything like that. Basically our hands are tied. Plus I've no interest in watching for cross posting. Actually I've been encouraging cross posting due to lack of migration capabilities in a way. Since I tell people "you'd be better off asking on X". In the future "Migrate and Merge" might be the most appropriate solution.
146
How should we deal with questions that are posted simultaneously at Unix.SE and another Stack Exchange site? I've found some discussion on [Meta Stack Overflow](http://meta.stackoverflow.com), but no official policy: * [Cross-posting on StackExchange sites](https://meta.stackexchange.com/questions/65931/cross-posting-on-stackexchange-sites) has answers recommending to multi-post only if the question hasn't had good answers on the first site, and to create links between questions. * [This question](https://meta.stackexchange.com/questions/11600/allow-cross-posting-between-serverfault-com-and-superuser-com) and [this question](https://meta.stackexchange.com/questions/32234/is-it-ok-to-ask-something-on-so-which-has-been-already-asked-unsuccessfully-on-su) each had one answer discouraging multiposting. This is especially a concern here since most questions would also be on-topic at one or more of [Stack Overflow](http://stackoverflow.com), [Super User](http://superuser.com), [Server Fault](http://serverfault.com), [Ubuntu.SE](http://ubuntu.stackexchange.com). I recently echoed [Robert Cartaino's answer](https://meta.stackexchange.com/questions/11600/allow-cross-posting-between-serverfault-com-and-superuser-com/11633#11633) in a comment to [this question](https://unix.stackexchange.com/questions/1677), but it's nothing like an official policy or at least an FAQ entry.
2010/09/19
[ "https://unix.meta.stackexchange.com/questions/146", "https://unix.meta.stackexchange.com", "https://unix.meta.stackexchange.com/users/885/" ]
We're in line with the SE policy on this now; the [FAQ](https://unix.stackexchange.com/faq) explicitly discourages cross-posting: > > Cross-posting is [strongly discouraged](https://meta.stackexchange.com/questions/71938/can-i-cross-post-my-question-from-one-site-to-another/71949#71949) -- if you post on one site and then change your mind it can always be migrated to another. If you're not sure if your question is on-topic, [ask on meta](https://unix.meta.stackexchange.com/questions/ask) or just [give it a try](https://unix.stackexchange.com/questions/ask) and the community will decide. > > >
I think if someone posts an Ubuntu-specific question both here and on Ask Ubuntu, it should be closed here. I say this because I really care about quality, and Ubuntu folk are surely going to give a superior Answer (and it's a larger community too, so will have a quicker response). As for Super User, I think both Ask Ubuntu and Unix & Linux supercede it, and it should be restricted to Questions about Windows, Hardware, cross-platform apps..., but that's another topic.
110,318
[![Guitar studies excerpt](https://i.stack.imgur.com/jLb87.png)](https://i.stack.imgur.com/jLb87.png) I am trying to learn how to read sheet music for my guitar. I am starting with this beginner exercise, but I am confused on how I am supposed to know, for example, which F note to play when it comes up on the sheet music here (there are multiple F notes right?). How are you supposed to know which one it is referring to?
2021/01/30
[ "https://music.stackexchange.com/questions/110318", "https://music.stackexchange.com", "https://music.stackexchange.com/users/74815/" ]
Because these exercises are to be played entirely in first position, each F indicated has only one option. The lowest F, for example (the second note of the first exercise), can only be played on the first fret of the 6th string. Here's a chart that may be helpful: [![Natural notes in first position](https://i.stack.imgur.com/YHOxi.png)](https://i.stack.imgur.com/YHOxi.png) © 1998, 2015 Jeffrey L Anvinson. Used by permission. Complete chart is available at: <http://www.jlamusic.com/Learn/guitarnotes/naturalnotesfirstposition/naturalnotesfirstposition.html> --- It's worth mention that the website from which the OP image is taken includes lessons mapping written notes to finger positions. In particular, the ["Guitar Method" page](https://shedthemusic.com/guitar) includes videos in the "Notes on the Guitar" section. In particular, the videos and pages "[Notes in Open Position](https://shedthemusic.com/guitar)", "[Notes in Fifth Position](https://shedthemusic.com/notes-in-5th-position)", and "[Reading Low Ledger Lines"](https://youtu.be/BzmuIYJYUrQ) contain information that may be helpful.
Answering directly, there are 3 F notes in that music. Since the whole exercise is in first position, open, 1st, 2nd, 3rd 4th and for the very highest note, A, the 5th fret are used. There is only one place on guitar for the lowest F - the second note shown - and that is 6th string, 1st fret. The F in the bottom space of the stave is on 4th string, 3rd fret, and the F on the top line will be found by pressing the top string at the 1st fret. True, there are often multiple places to play the same note, but since this is basic guitar tuition, one finger per fret, it's kept simple so each note is either an open string, or has a dedicated finger. Although you'll have to move your hand up two frets for the highest A note. Which makes me think the writer hasn't thought quite enough about what 1st position means.
110,318
[![Guitar studies excerpt](https://i.stack.imgur.com/jLb87.png)](https://i.stack.imgur.com/jLb87.png) I am trying to learn how to read sheet music for my guitar. I am starting with this beginner exercise, but I am confused on how I am supposed to know, for example, which F note to play when it comes up on the sheet music here (there are multiple F notes right?). How are you supposed to know which one it is referring to?
2021/01/30
[ "https://music.stackexchange.com/questions/110318", "https://music.stackexchange.com", "https://music.stackexchange.com/users/74815/" ]
Because these exercises are to be played entirely in first position, each F indicated has only one option. The lowest F, for example (the second note of the first exercise), can only be played on the first fret of the 6th string. Here's a chart that may be helpful: [![Natural notes in first position](https://i.stack.imgur.com/YHOxi.png)](https://i.stack.imgur.com/YHOxi.png) © 1998, 2015 Jeffrey L Anvinson. Used by permission. Complete chart is available at: <http://www.jlamusic.com/Learn/guitarnotes/naturalnotesfirstposition/naturalnotesfirstposition.html> --- It's worth mention that the website from which the OP image is taken includes lessons mapping written notes to finger positions. In particular, the ["Guitar Method" page](https://shedthemusic.com/guitar) includes videos in the "Notes on the Guitar" section. In particular, the videos and pages "[Notes in Open Position](https://shedthemusic.com/guitar)", "[Notes in Fifth Position](https://shedthemusic.com/notes-in-5th-position)", and "[Reading Low Ledger Lines"](https://youtu.be/BzmuIYJYUrQ) contain information that may be helpful.
You are in the first position and there is no duplicate of notes in the first position with the exception of the B on the 4th fret of the G string and the corresponding open string. It is not enough to ask "what F do I play", you also want to understand which octave you are in. While there may be 3 F's in the first position they are each a different frequency, different octave, and each has a unique note in the music staff. So, 3 ledger lines below the staff is first fret of the low E string. The lowest space (Face, in F-A-C-E) is the 3rd fret of the D string. The highest line in the staff (Fine, in E-G-B-D-F) is the first fret of the high E string. Assuming standard tuning, there is NO other option for the lowest pitch F. The others will eventually have duplicates higher up the neck but never in the first position. As long as you are not moving up to the 5th position and beyond with this exercise every note is unique (again, with the exception of the aforementioned B).
10,621,383
Using JQuery, I created a simple date text field with `dateFormat: "mmddyy"`. There is no problem in the way it works. But the corresponding database field is of type DATE and stores the value in "YYYY-MM-DD" format. So, when I read the value from database and set it to the date text field, the date format appears to be "YYYY-MM-DD", but not "mmddyy". So, how can we format that database date value in JQuery before setting it to the date field ? Thanks!
2012/05/16
[ "https://Stackoverflow.com/questions/10621383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1158189/" ]
Set the target's build settings as follows: ``` GCC_PRECOMPILE_PREFIX_HEADER=YES GCC_PREFIX_HEADER="Prefix.pch" ``` Note that you can plop these keys in the Build Settings search field, if you prefer to use Xcode's UI for your build settings.
I got this error in my flutter app when using the library flutter\_inappwebview and tried to set deployment version of ios in Runner > General to 12.0. I set it back to 11.4 and it built with no problems.
77,788
Here is the situation. There are two machines, laptop A and workstation B. B has a fixed IP, A has a dynamic IP, and I want to avoid the need of connecting from B to A (setting up an ssh tunnel for example; for the sake of the argument, assume that ssh from B to A is not possible). There is a git repository, `/home/user/foo.git`, on both machines. Problem: working on A, merge the changes on `A:/home/user/foo.git` and `B:/home/user/foo.git`. In the end, both repositories should be identical. The simplest solution I was able to come up with is as follows: ``` A:~$ cd foo.git A:~/foo.git$ git commit -a A:~/foo.git$ ssh B B:~$ cd foo.git B:~/foo.git$ git commit -a B:~/foo.git$ logout A:~/foo.git$ git pull ssh://B/home/user/foo.git A:~/foo.git$ git push ssh://B/home/user/foo.git master ``` (before being able to do that, I had to change git config on B and add a post-receive hook as described in the answer to this [stackoverflow question](https://stackoverflow.com/questions/11395398/git-push-failing-refusing-to-update-checked-out-branch)) My questions: 1) is the above correct? 2) is there a simpler way of achieving the same purpose?
2013/05/31
[ "https://unix.stackexchange.com/questions/77788", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/24405/" ]
**Your post-receive hook** has some pretty dire caveats IMO! I have a similar setup, but server B has two copies of the repo. One is a bare repo and used as the default remote ("origin") for both. Then I don't have to supply arguments to "git push" and "git pull". That last is the only simplification I have over the commands you're mentioning. (And in my case B is a server; I have an ARM box I can just leave on). If you "don't really use Git", it's not necessarily the best idea. Git was designed for power, and the UI is still not as consistent as other DVCS's. Simpler tools for this use might include <http://git-annex.branchable.com/assistant/> (new - I've not tried it) <http://www.cis.upenn.edu/~bcpierce/unison/> (old standby, works over ssh) Dropbox (non-free and requires internet connection, but slick and will optimize transfers over the LAN as well) Or there's Mercurial or even Darcs. I think either would avoid the issue that Git requires an extra bare repo or a worrying commit hook. Mercurial should be more user friendly than Git. Darcs has a different design to any other DVCS... so that might not be the best idea. Looking at the docs it seems Bazaar would be dubious for this case.
I think that `git` it's not good for you, I also think that [`rsync`](http://en.wikipedia.org/wiki/Rsync) it's much better suited for your task, since you simply have to keep files in sync git is not ideal in my opinion because: * you don't apparently need any branching/versioning/distributed model * you need to deal with files, git doesn't deal with files directly, in a nutshell git sees every "object" on your filesystem ( files and dirs basically ) as a SHA1 hash, as a consequence there is no way to really recover a file or to simply do anything specific to a file, the only thing that git is able to tell is if the content of your branch is changed or not, that's it, and it doesn't even keeps a real track in the middle, for example the checksum is done when you commit not when you add files to the stage.
77,788
Here is the situation. There are two machines, laptop A and workstation B. B has a fixed IP, A has a dynamic IP, and I want to avoid the need of connecting from B to A (setting up an ssh tunnel for example; for the sake of the argument, assume that ssh from B to A is not possible). There is a git repository, `/home/user/foo.git`, on both machines. Problem: working on A, merge the changes on `A:/home/user/foo.git` and `B:/home/user/foo.git`. In the end, both repositories should be identical. The simplest solution I was able to come up with is as follows: ``` A:~$ cd foo.git A:~/foo.git$ git commit -a A:~/foo.git$ ssh B B:~$ cd foo.git B:~/foo.git$ git commit -a B:~/foo.git$ logout A:~/foo.git$ git pull ssh://B/home/user/foo.git A:~/foo.git$ git push ssh://B/home/user/foo.git master ``` (before being able to do that, I had to change git config on B and add a post-receive hook as described in the answer to this [stackoverflow question](https://stackoverflow.com/questions/11395398/git-push-failing-refusing-to-update-checked-out-branch)) My questions: 1) is the above correct? 2) is there a simpler way of achieving the same purpose?
2013/05/31
[ "https://unix.stackexchange.com/questions/77788", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/24405/" ]
If all that's keeping you is that you can't ssh from B to A, but you can ssh from A to B, then [establish a reverse ssh tunnel](https://unix.stackexchange.com/questions/46235/how-does-reverse-ssh-tunneling-work).
I think that `git` it's not good for you, I also think that [`rsync`](http://en.wikipedia.org/wiki/Rsync) it's much better suited for your task, since you simply have to keep files in sync git is not ideal in my opinion because: * you don't apparently need any branching/versioning/distributed model * you need to deal with files, git doesn't deal with files directly, in a nutshell git sees every "object" on your filesystem ( files and dirs basically ) as a SHA1 hash, as a consequence there is no way to really recover a file or to simply do anything specific to a file, the only thing that git is able to tell is if the content of your branch is changed or not, that's it, and it doesn't even keeps a real track in the middle, for example the checksum is done when you commit not when you add files to the stage.
77,788
Here is the situation. There are two machines, laptop A and workstation B. B has a fixed IP, A has a dynamic IP, and I want to avoid the need of connecting from B to A (setting up an ssh tunnel for example; for the sake of the argument, assume that ssh from B to A is not possible). There is a git repository, `/home/user/foo.git`, on both machines. Problem: working on A, merge the changes on `A:/home/user/foo.git` and `B:/home/user/foo.git`. In the end, both repositories should be identical. The simplest solution I was able to come up with is as follows: ``` A:~$ cd foo.git A:~/foo.git$ git commit -a A:~/foo.git$ ssh B B:~$ cd foo.git B:~/foo.git$ git commit -a B:~/foo.git$ logout A:~/foo.git$ git pull ssh://B/home/user/foo.git A:~/foo.git$ git push ssh://B/home/user/foo.git master ``` (before being able to do that, I had to change git config on B and add a post-receive hook as described in the answer to this [stackoverflow question](https://stackoverflow.com/questions/11395398/git-push-failing-refusing-to-update-checked-out-branch)) My questions: 1) is the above correct? 2) is there a simpler way of achieving the same purpose?
2013/05/31
[ "https://unix.stackexchange.com/questions/77788", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/24405/" ]
**Your post-receive hook** has some pretty dire caveats IMO! I have a similar setup, but server B has two copies of the repo. One is a bare repo and used as the default remote ("origin") for both. Then I don't have to supply arguments to "git push" and "git pull". That last is the only simplification I have over the commands you're mentioning. (And in my case B is a server; I have an ARM box I can just leave on). If you "don't really use Git", it's not necessarily the best idea. Git was designed for power, and the UI is still not as consistent as other DVCS's. Simpler tools for this use might include <http://git-annex.branchable.com/assistant/> (new - I've not tried it) <http://www.cis.upenn.edu/~bcpierce/unison/> (old standby, works over ssh) Dropbox (non-free and requires internet connection, but slick and will optimize transfers over the LAN as well) Or there's Mercurial or even Darcs. I think either would avoid the issue that Git requires an extra bare repo or a worrying commit hook. Mercurial should be more user friendly than Git. Darcs has a different design to any other DVCS... so that might not be the best idea. Looking at the docs it seems Bazaar would be dubious for this case.
If all that's keeping you is that you can't ssh from B to A, but you can ssh from A to B, then [establish a reverse ssh tunnel](https://unix.stackexchange.com/questions/46235/how-does-reverse-ssh-tunneling-work).
19,507,775
I have to make a function for take all the circle elements and make them clickable. With my code i can click only the last node created and i can't understand why. Can you help me please? I use the d3 library, thats my code: ``` var allCircles = vis.selectAll('circle'); allCircles.on('click', function(){ /* make the same stuff depending from the circle clicked */ }); ``` If you need more explication ask me. Thank you very much for helping me!`
2013/10/22
[ "https://Stackoverflow.com/questions/19507775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2448854/" ]
It's probably better to add the event listener on the (parent) container element of the circles instead. This implies that you have such an element, e.g a `<g>` where you can add the listener. ``` var circleContainer = /* find your g element that contains the circles here */; circleContainer.on('click', function(){ // d3.event.target is the clicked circle d3.select(d3.event.target).attr("fill", "blue"); }); ``` If you're more familiar with jQuery the concept is called ['delegated events'](http://api.jquery.com/on/) there.
I don't use the d3 library and I've never heard of it but I can do it without ``` var circles=document.getElementsByTagName('circle'); function onclik() { //do stuff } for(var i=0;i<circles.length;i++){ circles[i].setAttribute("onclick","onclik()") } ``` I hope it helps!
49,007,908
It seems that I am still missing some basics of python. I was trying to understand [submodules importing](https://docs.python.org/3/reference/import.html#submodules), which I feel I have not understood yet. But I have also stumbled upon something new. I am having following two packages in two different PyDev projects: ``` package1 | +--mod1.py | +--mod2.py package2 | +--__init__.py | +--modx.py | +--mody.py ``` In `mod1`, I can do `import mod2`. But in `__init__` and `modx`, I cannot do `import mody` (Eclipse says "unresolved imports"). In `__init__`, I can do `import .mody` or `from .mody import vary`. In `modx`, I cannot do `import .mody`. (In fact I never saw use of `.` in `import` statement as prefix to the module. Earlier I only came across `import mod` and `from mod import var`, but never saw `import .mod` and `from .mod import var`.) Why this might be happening? I must be unaware some context which is causing this behaviour. But then I dont know what is it? PS: I am using Python 3.4
2018/02/27
[ "https://Stackoverflow.com/questions/49007908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1317018/" ]
There is a subtle different between how Python is treating both of those packages. `package1` is treated as a **namespace** package in that it **does not** contain an `__init__.py` file. `package2` is treated as a **regular** package in that it **does** contain an `__init__.py` file. So I'll give a quick breakdown of why each step is happening: > > In mod1, I can do import mod2. > > > This is happening due to how **namespace** packages are handled using absolute imports. You're most likely executing `python mod1.py` from the directory in which the file is stored, right (in my attempt to re-create your folder structure and test it myself locally, I did the same)? So `package1` becomes your **current working directory** with your `mod2` file being at the root of that directory. With namespace packages, Python will default look to `sys.path` in an attempt to find the imports you have requested. Since your current working directory is automatically added to and included in `sys.path`, Python can successfully find your `import mod2` request without any difficulty. **Thanks to ShadowRanger for correcting my initial response to this where I had misunderstood exactly how Python is including the current working directory in its search.** > > In **init**, I can do import .mody or from .mody import vary. > > > This is because Python is treating this as a **regular** package. The name of your regular package in this case is `package2`. When you use the `.` notation, you are asking Python to start searching for the import from the **current** package (which in this case is your parent `package2`). So you have to use `import .mody` to find the `mody` package within the current package. If you used `..` then it would import from the parent of the current package and so on. The dot notation is useful as you are explicitly declaring that you wish to search from the current package only - so if there was another `package2` package on your `PYTHONPATH`, Python would know which one to choose. > > But in **init** and modx, I cannot do import mody (Eclipse says "unresolved imports"). > > > With `__init__.py` this is because you have not used the dot notation and have not told Python that you wish to search for these modules in the **current** package. So it's looking to the Python standard library and to your `PYTHONPATH` for these packages and not finding them (hence your error in Eclipse). By using the dot notation, you are stating that you wish to include the current package in the search and, thus, Python will then be able to locate those files. Using the dot notation like this, to import via `from . import mody`, is to use a **relative import**. With `modx` you also have to use a relative import (see next section). > > In modx, I cannot do import .mody. Why this might be happening? > > > This is because you're not using a **relative / absolute import**. You'll be using a relative import in this case. A relative import is the `from . import mody` syntax you've seen already. Using a relative or absolute import behaviour is default in Python. It is now the default behaviour as, with the old Python `import` behaviour, suppose Python's own standard library had a package called `mody`. When you'd use `import mody` it would previously have imported `mody` from your package and **not** the standard library. This wasn't always desirable. What if you specifically wanted the standard library version? So now your imports must be made using `from . import mody` or `from .mody import vary` syntax so as the import is very clear. If you use `import` and not the `from...` syntax, Python will assume it's a standard library or `PYTHONPATH` import. By the way, sources for a lot of the above information came from the following sites: <https://docs.python.org/3/reference/import.html> <https://docs.python.org/2.5/whatsnew/pep-328.html>
Python modules are optional "additions" to Python that can be imported using the `import` command like so: ``` import package1 package1.mod1 # Can be accessed using this ``` To import individual parts of the package, use `from` like so: ``` from package1 import mod1 mod1 # Can be accessed using this ``` If you want to import every part of a module and use it without `package.`, use: from package1 i
9,412,501
I have created plugin for background service (to run the application in background) in phonegap. here is my java code for plugin: ``` public class BackgroundService extends Plugin { @Override public PluginResult execute(String action, JSONArray args, String callbackId) { PluginResult.Status status = PluginResult.Status.OK; String result = ""; try { if (action.equals("onCreate")) { this.onCreate(); } else if (action.equals("onBind")) { Intent intent = null; this.onBind(intent); } else if (action.equals("onDestroy")) { this.onDestroy(); } else if (action.equals("onStart")) { Intent intent = null; this.onStart(intent,args.getInt(1)); } else if (action.equals("onUnbind")) { Intent intent = null; this.onUnbind(intent); } return new PluginResult(status, result); } catch(JSONException e) { return new PluginResult(PluginResult.Status.JSON_EXCEPTION); } } public void onCreate() { // TODO Auto-generated method stub } public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub //super.onStart(intent, startId); } public boolean onUnbind(Intent intent) { // TODO Auto-generated method stub } public void onPause() { super.webView.loadUrl("javascript:navigator.BackgroundService.onBackground();"); } public void onResume() { super.webView.loadUrl("javascript:navigator.BackgroundService.onForeground();"); } } ``` and my js file is: ``` function BackgroundService() { }; BackgroundService.prototype.create = function() { PhoneGap.exec(null, null, "BackgroundService", "onCreate", []); }; BackgroundService.prototype.destroy = function() { PhoneGap.exec(null, null, "BackgroundService", "onDestroy", []); }; BackgroundService.prototype.start = function(intent,startId) { PhoneGap.exec(null, null, "BackgroundService", "onStart", [intent,startId]); }; BackgroundService.prototype.bind = function(intent) { PhoneGap.exec(null, null, "BackgroundService", "onBind", [intent]); }; BackgroundService.prototype.unbind = function(intent) { PhoneGap.exec(null, null, "BackgroundService", "onUnbind", [intent]); }; PhoneGap.addConstructor(function() { PhoneGap.addPlugin("BackgroundService", new BackgroundService()); }); ``` and in my index.html. I have added the below code in my button click navigator.BackgroundService.onCreate(); navigator.BackgroundService.onStart(intent,1); My error is: ``` ERROR/AndroidRuntime(14981): FATAL EXCEPTION: main ERROR/AndroidRuntime(14981): java.lang.RuntimeException: Unable to instantiate service com.app.newly.BackgroundService: java.lang.ClassCastException: com.app.newly.BackgroundService ERROR/AndroidRuntime(14981):at android.app.ActivityThread.handleCreateService(ActivityThread.java:2943) ERROR/AndroidRuntime(14981):at android.app.ActivityThread.access$3300(ActivityThread.java:125) ERROR/AndroidRuntime(14981): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2087) ERROR/AndroidRuntime(14981): at android.os.Handler.dispatchMessage(Handler.java:99) ERROR/AndroidRuntime(14981): at android.os.Looper.loop(Looper.java:123) ERROR/AndroidRuntime(14981): at android.app.ActivityThread.main(ActivityThread.java:4627) ERROR/AndroidRuntime(14981): at java.lang.reflect.Method.invokeNative(Native Method) ERROR/AndroidRuntime(14981): at java.lang.reflect.Method.invoke(Method.java:521) ERROR/AndroidRuntime(14981): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) ERROR/AndroidRuntime(14981): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) ERROR/AndroidRuntime(14981): at dalvik.system.NativeStart.main(Native Method) ERROR/AndroidRuntime(14981): Caused by: java.lang.ClassCastException: com.app.newly.BackgroundService ERROR/AndroidRuntime(14981): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2940) ERROR/AndroidRuntime(14981): ... 10 more ``` If I removed **startService(new Intent(this,MyService.class));** from java file I got the below error: ``` ERROR/Web Console(4785): ReferenceError: Can't find variable: SqlitePlugin at file:///android_asset/www/BackgroundService.js:31 ERROR/Web Console(4785): TypeError: Result of expression 'window.plugins.SqlitePlugin' [undefined] is not an object. at file:///android_asset/www/index.html:26 ``` otherwise I can't able to run the application I am getting the error in the java file.Am getting the red cross mark(like '**X**') in the left corner of this line 'startService(new Intent(this,MyService.class));' please tell me where I am wrong,please guide me,thanks in advance. ![please check the image where i am getting the error](https://i.stack.imgur.com/hY79n.png) I am getting the error in start service.when i move the cursor to the startService i am getting create method 'startService(intent)' And I Am having the doubt in this plugin can i able to run the javascript in background or not.If it is possible how to get the alert in background.please tell me where I am wrong,please guide me,thanks in advance.
2012/02/23
[ "https://Stackoverflow.com/questions/9412501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/993437/" ]
Creation of plugin is fine.You create your service just like a normal java file. And then As soon as you call this plugin . you just start your service like ``` startService(new Intent(this, MyService.class)); ``` Then your service will run in background.This is an easy way to do. If separately you create service then Your **Plugin** should look like this ``` public class BackgroundService extends Plugin { private static final String TAG = "BackgroundService"; private static final String CALL_SERVICE_ACTION = "callService"; @Override public PluginResult execute(String action, JSONArray args, String callbackId) { Log.i(TAG, "Plugin Called"); PluginResult result = null; if (CALL_SERVICE_ACTION.equals(action)) { Log.d(TAG, "CALL_SERVICE_ACTION"); startService(new Intent(ctx, MyService.class)); } else { result = new PluginResult(Status.INVALID_ACTION); Log.d(TAG, "Invalid action : " + action + " passed"); } return result; } } ``` Your **.js** file should look like this ``` function BackgroundService() { }; BackgroundService.prototype.callService = function(successCallback, failCallback) { return PhoneGap.exec(successCallback, failCallback, "BackgroundService", "callService", [ null ]); }; PhoneGap.addConstructor(function() { PhoneGap.addPlugin("BackgroundService", new BackgroundService()); }); ``` And your **HTML** file should look like this ``` function callServiceFunction() { window.plugins.BackgroundService.callService('callService', callServiceSuccessCallBack, callServiceFailCallBack); } function callServiceSuccessCallBack(e) { alert("Success"); } function callServiceFailCallBack(f) { alert("Failure"); } ``` Also you need to register your phonegap plugin in your res/xml/plugins.xml like ``` <plugin name="BackgroundService" value="package-structure.BackgroundService"/> ```
In the onCreate method of your Java class that extends from DroidGap make sure you have set "keepRunning" properly. ``` super.setBooleanProperty("keepRunning", true); ```
479,555
I am looking to drive a piezo transducer at its resonant frequency (20kHz) to generate sound waves. I am doing an application similar to sonar technology. I was looking into how to drive the transducer and I thought I would have to generate and feed it sine waves with its resonant frequency. I have access to an Arduino DUE, I was looking into how to do so and it seemed a bit complicated. I was curious if anyone had any experience driving a piezo and if it would be possible to do so with just square waves. Or if they have experience generating sine waves of any frequency within an Arduino please let me know!
2020/02/05
[ "https://electronics.stackexchange.com/questions/479555", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/241804/" ]
A square wave will work fine -- in fact better than a sine wave ! This is because the piezo barely responds to any signals not at its resonant frequency, and the amplitude of the sinusoidal component of a squarewave at the fundamental is *higher* than the amplitude of a square wave.
I'm not sure what the specs. of your piezo is, but you need a really high voltage to drive them. You will probably not be able to drive them with the outputs of a regular MCUs. If you have a DAC inside Arduino, connect it to a high Voltage audio amp specific for piezo speakers.
9,498,318
I'd like to create a custom context menu. The idea is to create a panel with a textBox a button and a list of labels and be able to show it on right click and make it behave exactly like a contextMenu. I can probably use a form without borders but I was thinking there might be a class I can derive from that would help me handle the positionnig of the context menu and the shading. Any ideas? Thank you Edit: An example to clear a few ideas: Say you have a label on your form, when you right click on it (or even left click) a menu appears. This menu is NOT the classic context menu but rather a custom panel with controls that I created personnaly. An example is search box ont top with a list of items. As you enter letters the list is trimmed to the matching items and when an item is clicked the context menu disappears and the value selected is wrtitten in the label we first clicked on.
2012/02/29
[ "https://Stackoverflow.com/questions/9498318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875130/" ]
You can use the method described here: <http://www.codeproject.com/Articles/22780/Super-Context-Menu-Strip> Since it uses ContextMenuStrip you can set its position: ``` contextMenuStrip1.Show(Cursor.Position); ``` and shadow effect: <http://msdn.microsoft.com/en-us/library/system.windows.controls.contextmenu.hasdropshadow.aspx>
The simplest way (since this doesn't appear to be an actual menu) would be to create a borderless form and add shadow to it: ``` public class ShadowForm : Form { // Define the CS_DROPSHADOW constant private const int CS_DROPSHADOW = 0x00020000; // Override the CreateParams property protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ClassStyle |= CS_DROPSHADOW; return cp; } } } ``` Regarding position, there is not much to it. Just check `Cursor.Position` or set coordinates using the arguments in your `MouseUp` event handler. Complete code would look something like: ``` public partial class ParentForm : Form { public ParentForm() { InitializeComponent(); } protected override OnMouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { var menu = new CustomMenu(); menu.Location = PointToScreen(e.Location); menu.Show(this); } } } ``` and for the "menu" form: ``` public partial class CustomMenu : Form { public CustomMenu() { InitializeComponent(); this.StartPosition = FormStartPosition.Manual; } private const int CS_DROPSHADOW = 0x00020000; protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ClassStyle |= CS_DROPSHADOW; return cp; } } protected override void OnLostFocus(EventArgs e) { this.Close(); base.OnLostFocus(e); } } ```
9,498,318
I'd like to create a custom context menu. The idea is to create a panel with a textBox a button and a list of labels and be able to show it on right click and make it behave exactly like a contextMenu. I can probably use a form without borders but I was thinking there might be a class I can derive from that would help me handle the positionnig of the context menu and the shading. Any ideas? Thank you Edit: An example to clear a few ideas: Say you have a label on your form, when you right click on it (or even left click) a menu appears. This menu is NOT the classic context menu but rather a custom panel with controls that I created personnaly. An example is search box ont top with a list of items. As you enter letters the list is trimmed to the matching items and when an item is clicked the context menu disappears and the value selected is wrtitten in the label we first clicked on.
2012/02/29
[ "https://Stackoverflow.com/questions/9498318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875130/" ]
The simplest way (since this doesn't appear to be an actual menu) would be to create a borderless form and add shadow to it: ``` public class ShadowForm : Form { // Define the CS_DROPSHADOW constant private const int CS_DROPSHADOW = 0x00020000; // Override the CreateParams property protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ClassStyle |= CS_DROPSHADOW; return cp; } } } ``` Regarding position, there is not much to it. Just check `Cursor.Position` or set coordinates using the arguments in your `MouseUp` event handler. Complete code would look something like: ``` public partial class ParentForm : Form { public ParentForm() { InitializeComponent(); } protected override OnMouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { var menu = new CustomMenu(); menu.Location = PointToScreen(e.Location); menu.Show(this); } } } ``` and for the "menu" form: ``` public partial class CustomMenu : Form { public CustomMenu() { InitializeComponent(); this.StartPosition = FormStartPosition.Manual; } private const int CS_DROPSHADOW = 0x00020000; protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ClassStyle |= CS_DROPSHADOW; return cp; } } protected override void OnLostFocus(EventArgs e) { this.Close(); base.OnLostFocus(e); } } ```
When you click outside the ContextMenu it disappears. Yes. With this CustomMenu also you can do that. ``` protected override void OnDeactivate(EventArgs e) { this.Close(); base.OnDeactivate(e); } ``` I tested this and it worked fine for me. OnLeave and OnLostFocus did not fire when you click outside the form.
9,498,318
I'd like to create a custom context menu. The idea is to create a panel with a textBox a button and a list of labels and be able to show it on right click and make it behave exactly like a contextMenu. I can probably use a form without borders but I was thinking there might be a class I can derive from that would help me handle the positionnig of the context menu and the shading. Any ideas? Thank you Edit: An example to clear a few ideas: Say you have a label on your form, when you right click on it (or even left click) a menu appears. This menu is NOT the classic context menu but rather a custom panel with controls that I created personnaly. An example is search box ont top with a list of items. As you enter letters the list is trimmed to the matching items and when an item is clicked the context menu disappears and the value selected is wrtitten in the label we first clicked on.
2012/02/29
[ "https://Stackoverflow.com/questions/9498318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875130/" ]
You can use the method described here: <http://www.codeproject.com/Articles/22780/Super-Context-Menu-Strip> Since it uses ContextMenuStrip you can set its position: ``` contextMenuStrip1.Show(Cursor.Position); ``` and shadow effect: <http://msdn.microsoft.com/en-us/library/system.windows.controls.contextmenu.hasdropshadow.aspx>
When you click outside the ContextMenu it disappears. Yes. With this CustomMenu also you can do that. ``` protected override void OnDeactivate(EventArgs e) { this.Close(); base.OnDeactivate(e); } ``` I tested this and it worked fine for me. OnLeave and OnLostFocus did not fire when you click outside the form.
163,885
I'd like to route only Ips from within the US via my vpn. I can't find a specific range for States. How can I do that properly?
2010/07/25
[ "https://serverfault.com/questions/163885", "https://serverfault.com", "https://serverfault.com/users/17573/" ]
There is no US-only [IP address](http://en.wikipedia.org/wiki/IP_address) range. See also [Geolocation](http://en.wikipedia.org/wiki/Geolocation). [![](https://imgs.xkcd.com/comics/map_of_the_internet.jpg "xkcd IP map")](http://xkcd.com/195/)
You can do a decent approximation by looking at what [RIRs](http://en.wikipedia.org/wiki/Regional_Internet_registry) various /8s have been assigned to, but it's going to be just that--an approximation. To take another approach, you can conclusively determine if someone is connecting via a computer in the States based on ping times and the speed of light, but you can't disprove someone is in the US via this method, nor can you tell whether they're merely using a US-based proxy server with either method. Essentially, what you're looking for lies somewhere between impossible and flawed; you can trade-off between the two to get less of the other, but you can't eliminate either one.
12,704,217
I have a link in a dialog modal window. I need this link to show in the same DIALOG MODAL window where it is. Here's how my link looks like, it is formed in a php file and then passed to the html template: ``` $link = "<a href='mypage.php?f=dosomething&param1=".$var1."&param2=".$var2."' id='dosomething' >Need to open this link in the same dialog window</a>"; ``` And here's my jquery code: ``` $("#dosomething").dialog( { autoOpen:false, modal:true, overlay: { opacity: 0.8, background: "black" }, width:850, height:650, title:"A title", draggable:true, hide:"slow", closeOnEscape: true }); $("#dosomething").dialog("open"); ```
2012/10/03
[ "https://Stackoverflow.com/questions/12704217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/523129/" ]
The probable solution would be you **create a base class** which **extends TextView**, and use this text view class as edit text. Hope you are asking for size in first screen. In any case, u set the text size in the base class. This will solve your problem. like u create this class in package com.example and class name is BaseTextView, then in xml file instead of `<TextView .../>` you will write `<com.example.BaseTextView ... />` Hope this helps.
Create a function and pass the spinner size value as ``` void setSize(int size){ ... setTextSize() // on All of the layout texts and views on screen } ``` Call setTextSize() on all of your views and layout texts on the screen. Check out the Documentations [Here](http://developer.android.com/reference/android/widget/TextView.html#setTextSize%28float%29)
12,704,217
I have a link in a dialog modal window. I need this link to show in the same DIALOG MODAL window where it is. Here's how my link looks like, it is formed in a php file and then passed to the html template: ``` $link = "<a href='mypage.php?f=dosomething&param1=".$var1."&param2=".$var2."' id='dosomething' >Need to open this link in the same dialog window</a>"; ``` And here's my jquery code: ``` $("#dosomething").dialog( { autoOpen:false, modal:true, overlay: { opacity: 0.8, background: "black" }, width:850, height:650, title:"A title", draggable:true, hide:"slow", closeOnEscape: true }); $("#dosomething").dialog("open"); ```
2012/10/03
[ "https://Stackoverflow.com/questions/12704217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/523129/" ]
`Android` documentation is not specific on the most efficient way to change the font size globally through the user’s selection at application level. There is a problem I think with the [answer](https://stackoverflow.com/a/12706334/1554935) given by **Black Devil**. The problem is that many of the `Android` widgets subclass `TextView`, such as `Button`, `RadioButton`, and `CheckBox`. Some of these are indirect subclasses of `TextView`, which makes implementing customized version of `TextView` in these classes very difficult. However as **pointed out by Siddharth Lele in his comment**, using `styles` or `themes` is much better way to handle change in the text size throughout the app. We set styles for layouts to control the look and feel of the view. Themes are essentially just collections of these styles. However, we can use a theme just for text size settings; without defining values for every property. Using a theme over styles provides us with one huge advantage: we can set a theme for the entire view programmatically. **theme.xml** ``` <resources> <style name="FontSizeSmall"> <item name="android:textSize">12sp</item> </style> <style name="FontSizeMedium"> <item name="android:textSize">16sp</item> </style> <style name="FontSizeLarge"> <item name="android:textSize">20sp</item> </style> </resources> ``` Create a class to handle loading our preferences: ``` public class BaseActivity extends Activity { @Override public void onStart() { super.onStart(); // Enclose everything in a try block so we can just // use the default view if anything goes wrong. try { // Get the font size value from SharedPreferences. SharedPreferences settings = getSharedPreferences("com.example.YourAppPackage", Context.MODE_PRIVATE); // Get the font size option. We use "FONT_SIZE" as the key. // Make sure to use this key when you set the value in SharedPreferences. // We specify "Medium" as the default value, if it does not exist. String fontSizePref = settings.getString("FONT_SIZE", "Medium"); // Select the proper theme ID. // These will correspond to your theme names as defined in themes.xml. int themeID = R.style.FontSizeMedium; if (fontSizePref == "Small") { themeID = R.style.FontSizeSmall; } else if (fontSizePref == "Large") { themeID = R.style.FontSizeLarge; } // Set the theme for the activity. setTheme(themeID); } catch (Exception ex) { ex.printStackTrace(); } } ``` Finally, create activities by extending BaseActivity, like this: ``` public class AppActivity extends BaseActivity{ } ``` As most of the application have a much fewer amount of Activities than TextViews or widgets that inherit TextView. This will be exponentially so as complexity increases, so this solution requires less changes in code. Thanks to [Ray Kuhnell](http://raykuhnell.com/2013/07/09/dynamic-font-size-and-other-styles-in-an-android-app/)
I'm not sure if it help. But there is something called "SSP" - Scalable size Unit for Text. Add this to your build gradle ``` implementation 'com.intuit.ssp:ssp-android:1.0.6' ``` And this to use ``` android:textSize="@dimen/_22ssp" ``` <https://github.com/intuit/ssp>
12,704,217
I have a link in a dialog modal window. I need this link to show in the same DIALOG MODAL window where it is. Here's how my link looks like, it is formed in a php file and then passed to the html template: ``` $link = "<a href='mypage.php?f=dosomething&param1=".$var1."&param2=".$var2."' id='dosomething' >Need to open this link in the same dialog window</a>"; ``` And here's my jquery code: ``` $("#dosomething").dialog( { autoOpen:false, modal:true, overlay: { opacity: 0.8, background: "black" }, width:850, height:650, title:"A title", draggable:true, hide:"slow", closeOnEscape: true }); $("#dosomething").dialog("open"); ```
2012/10/03
[ "https://Stackoverflow.com/questions/12704217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/523129/" ]
`Android` documentation is not specific on the most efficient way to change the font size globally through the user’s selection at application level. There is a problem I think with the [answer](https://stackoverflow.com/a/12706334/1554935) given by **Black Devil**. The problem is that many of the `Android` widgets subclass `TextView`, such as `Button`, `RadioButton`, and `CheckBox`. Some of these are indirect subclasses of `TextView`, which makes implementing customized version of `TextView` in these classes very difficult. However as **pointed out by Siddharth Lele in his comment**, using `styles` or `themes` is much better way to handle change in the text size throughout the app. We set styles for layouts to control the look and feel of the view. Themes are essentially just collections of these styles. However, we can use a theme just for text size settings; without defining values for every property. Using a theme over styles provides us with one huge advantage: we can set a theme for the entire view programmatically. **theme.xml** ``` <resources> <style name="FontSizeSmall"> <item name="android:textSize">12sp</item> </style> <style name="FontSizeMedium"> <item name="android:textSize">16sp</item> </style> <style name="FontSizeLarge"> <item name="android:textSize">20sp</item> </style> </resources> ``` Create a class to handle loading our preferences: ``` public class BaseActivity extends Activity { @Override public void onStart() { super.onStart(); // Enclose everything in a try block so we can just // use the default view if anything goes wrong. try { // Get the font size value from SharedPreferences. SharedPreferences settings = getSharedPreferences("com.example.YourAppPackage", Context.MODE_PRIVATE); // Get the font size option. We use "FONT_SIZE" as the key. // Make sure to use this key when you set the value in SharedPreferences. // We specify "Medium" as the default value, if it does not exist. String fontSizePref = settings.getString("FONT_SIZE", "Medium"); // Select the proper theme ID. // These will correspond to your theme names as defined in themes.xml. int themeID = R.style.FontSizeMedium; if (fontSizePref == "Small") { themeID = R.style.FontSizeSmall; } else if (fontSizePref == "Large") { themeID = R.style.FontSizeLarge; } // Set the theme for the activity. setTheme(themeID); } catch (Exception ex) { ex.printStackTrace(); } } ``` Finally, create activities by extending BaseActivity, like this: ``` public class AppActivity extends BaseActivity{ } ``` As most of the application have a much fewer amount of Activities than TextViews or widgets that inherit TextView. This will be exponentially so as complexity increases, so this solution requires less changes in code. Thanks to [Ray Kuhnell](http://raykuhnell.com/2013/07/09/dynamic-font-size-and-other-styles-in-an-android-app/)
Create a function and pass the spinner size value as ``` void setSize(int size){ ... setTextSize() // on All of the layout texts and views on screen } ``` Call setTextSize() on all of your views and layout texts on the screen. Check out the Documentations [Here](http://developer.android.com/reference/android/widget/TextView.html#setTextSize%28float%29)
12,704,217
I have a link in a dialog modal window. I need this link to show in the same DIALOG MODAL window where it is. Here's how my link looks like, it is formed in a php file and then passed to the html template: ``` $link = "<a href='mypage.php?f=dosomething&param1=".$var1."&param2=".$var2."' id='dosomething' >Need to open this link in the same dialog window</a>"; ``` And here's my jquery code: ``` $("#dosomething").dialog( { autoOpen:false, modal:true, overlay: { opacity: 0.8, background: "black" }, width:850, height:650, title:"A title", draggable:true, hide:"slow", closeOnEscape: true }); $("#dosomething").dialog("open"); ```
2012/10/03
[ "https://Stackoverflow.com/questions/12704217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/523129/" ]
you can scale to text size of your app up/down using base activity Configuration, make all activities inherent base activity. Scale normal value is 1.0, 2.0 would double the font size and .50 would make it half. ``` public void adjustFontScale( Configuration configuration,float scale) { configuration.fontScale = scale; DisplayMetrics metrics = getResources().getDisplayMetrics(); WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE); wm.getDefaultDisplay().getMetrics(metrics); metrics.scaledDensity = configuration.fontScale * metrics.density; getBaseContext().getResources().updateConfiguration(configuration, metrics); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); adjustFontScale( getResources().getConfiguration()); } ```
To scale the font size of all components(mean whole application), there is pretty well approach which is implemented and tested trough several devices. This solution could be applied for cases like; declaring ***dp*** size unit statically(android sp by default) , scaling to desired font sizes and etc. The solution is similar to [answer](https://stackoverflow.com/a/49710418/5031257) given by **Usama Saeed US** but will cover all buggy cases. Declare static util method which will scale font size. ``` //LocaleConfigurationUtil.class public static Context adjustFontSize(Context context){ Configuration configuration = context.getResources().getConfiguration(); // This will apply to all text like -> Your given text size * fontScale configuration.fontScale = 1.0f; return context.createConfigurationContext(configuration); } ``` In your all activities, override the attachBaseContext and call util method in onCreate. ``` @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(LocaleConfigurationUtil.adjustFontSize(newBase)); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LocaleConfigurationUtil.adjustFontSize(this); } ``` If you are using fragments then override onAttach method ``` @Override public void onAttach(Context context) { super.onAttach(LocaleConfigurationUtil.adjustFontSize(context)); } ```
12,704,217
I have a link in a dialog modal window. I need this link to show in the same DIALOG MODAL window where it is. Here's how my link looks like, it is formed in a php file and then passed to the html template: ``` $link = "<a href='mypage.php?f=dosomething&param1=".$var1."&param2=".$var2."' id='dosomething' >Need to open this link in the same dialog window</a>"; ``` And here's my jquery code: ``` $("#dosomething").dialog( { autoOpen:false, modal:true, overlay: { opacity: 0.8, background: "black" }, width:850, height:650, title:"A title", draggable:true, hide:"slow", closeOnEscape: true }); $("#dosomething").dialog("open"); ```
2012/10/03
[ "https://Stackoverflow.com/questions/12704217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/523129/" ]
you can scale to text size of your app up/down using base activity Configuration, make all activities inherent base activity. Scale normal value is 1.0, 2.0 would double the font size and .50 would make it half. ``` public void adjustFontScale( Configuration configuration,float scale) { configuration.fontScale = scale; DisplayMetrics metrics = getResources().getDisplayMetrics(); WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE); wm.getDefaultDisplay().getMetrics(metrics); metrics.scaledDensity = configuration.fontScale * metrics.density; getBaseContext().getResources().updateConfiguration(configuration, metrics); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); adjustFontScale( getResources().getConfiguration()); } ```
The probable solution would be you **create a base class** which **extends TextView**, and use this text view class as edit text. Hope you are asking for size in first screen. In any case, u set the text size in the base class. This will solve your problem. like u create this class in package com.example and class name is BaseTextView, then in xml file instead of `<TextView .../>` you will write `<com.example.BaseTextView ... />` Hope this helps.
12,704,217
I have a link in a dialog modal window. I need this link to show in the same DIALOG MODAL window where it is. Here's how my link looks like, it is formed in a php file and then passed to the html template: ``` $link = "<a href='mypage.php?f=dosomething&param1=".$var1."&param2=".$var2."' id='dosomething' >Need to open this link in the same dialog window</a>"; ``` And here's my jquery code: ``` $("#dosomething").dialog( { autoOpen:false, modal:true, overlay: { opacity: 0.8, background: "black" }, width:850, height:650, title:"A title", draggable:true, hide:"slow", closeOnEscape: true }); $("#dosomething").dialog("open"); ```
2012/10/03
[ "https://Stackoverflow.com/questions/12704217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/523129/" ]
`Android` documentation is not specific on the most efficient way to change the font size globally through the user’s selection at application level. There is a problem I think with the [answer](https://stackoverflow.com/a/12706334/1554935) given by **Black Devil**. The problem is that many of the `Android` widgets subclass `TextView`, such as `Button`, `RadioButton`, and `CheckBox`. Some of these are indirect subclasses of `TextView`, which makes implementing customized version of `TextView` in these classes very difficult. However as **pointed out by Siddharth Lele in his comment**, using `styles` or `themes` is much better way to handle change in the text size throughout the app. We set styles for layouts to control the look and feel of the view. Themes are essentially just collections of these styles. However, we can use a theme just for text size settings; without defining values for every property. Using a theme over styles provides us with one huge advantage: we can set a theme for the entire view programmatically. **theme.xml** ``` <resources> <style name="FontSizeSmall"> <item name="android:textSize">12sp</item> </style> <style name="FontSizeMedium"> <item name="android:textSize">16sp</item> </style> <style name="FontSizeLarge"> <item name="android:textSize">20sp</item> </style> </resources> ``` Create a class to handle loading our preferences: ``` public class BaseActivity extends Activity { @Override public void onStart() { super.onStart(); // Enclose everything in a try block so we can just // use the default view if anything goes wrong. try { // Get the font size value from SharedPreferences. SharedPreferences settings = getSharedPreferences("com.example.YourAppPackage", Context.MODE_PRIVATE); // Get the font size option. We use "FONT_SIZE" as the key. // Make sure to use this key when you set the value in SharedPreferences. // We specify "Medium" as the default value, if it does not exist. String fontSizePref = settings.getString("FONT_SIZE", "Medium"); // Select the proper theme ID. // These will correspond to your theme names as defined in themes.xml. int themeID = R.style.FontSizeMedium; if (fontSizePref == "Small") { themeID = R.style.FontSizeSmall; } else if (fontSizePref == "Large") { themeID = R.style.FontSizeLarge; } // Set the theme for the activity. setTheme(themeID); } catch (Exception ex) { ex.printStackTrace(); } } ``` Finally, create activities by extending BaseActivity, like this: ``` public class AppActivity extends BaseActivity{ } ``` As most of the application have a much fewer amount of Activities than TextViews or widgets that inherit TextView. This will be exponentially so as complexity increases, so this solution requires less changes in code. Thanks to [Ray Kuhnell](http://raykuhnell.com/2013/07/09/dynamic-font-size-and-other-styles-in-an-android-app/)
To scale the font size of all components(mean whole application), there is pretty well approach which is implemented and tested trough several devices. This solution could be applied for cases like; declaring ***dp*** size unit statically(android sp by default) , scaling to desired font sizes and etc. The solution is similar to [answer](https://stackoverflow.com/a/49710418/5031257) given by **Usama Saeed US** but will cover all buggy cases. Declare static util method which will scale font size. ``` //LocaleConfigurationUtil.class public static Context adjustFontSize(Context context){ Configuration configuration = context.getResources().getConfiguration(); // This will apply to all text like -> Your given text size * fontScale configuration.fontScale = 1.0f; return context.createConfigurationContext(configuration); } ``` In your all activities, override the attachBaseContext and call util method in onCreate. ``` @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(LocaleConfigurationUtil.adjustFontSize(newBase)); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LocaleConfigurationUtil.adjustFontSize(this); } ``` If you are using fragments then override onAttach method ``` @Override public void onAttach(Context context) { super.onAttach(LocaleConfigurationUtil.adjustFontSize(context)); } ```
12,704,217
I have a link in a dialog modal window. I need this link to show in the same DIALOG MODAL window where it is. Here's how my link looks like, it is formed in a php file and then passed to the html template: ``` $link = "<a href='mypage.php?f=dosomething&param1=".$var1."&param2=".$var2."' id='dosomething' >Need to open this link in the same dialog window</a>"; ``` And here's my jquery code: ``` $("#dosomething").dialog( { autoOpen:false, modal:true, overlay: { opacity: 0.8, background: "black" }, width:850, height:650, title:"A title", draggable:true, hide:"slow", closeOnEscape: true }); $("#dosomething").dialog("open"); ```
2012/10/03
[ "https://Stackoverflow.com/questions/12704217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/523129/" ]
Create a function and pass the spinner size value as ``` void setSize(int size){ ... setTextSize() // on All of the layout texts and views on screen } ``` Call setTextSize() on all of your views and layout texts on the screen. Check out the Documentations [Here](http://developer.android.com/reference/android/widget/TextView.html#setTextSize%28float%29)
I'm not sure if it help. But there is something called "SSP" - Scalable size Unit for Text. Add this to your build gradle ``` implementation 'com.intuit.ssp:ssp-android:1.0.6' ``` And this to use ``` android:textSize="@dimen/_22ssp" ``` <https://github.com/intuit/ssp>
12,704,217
I have a link in a dialog modal window. I need this link to show in the same DIALOG MODAL window where it is. Here's how my link looks like, it is formed in a php file and then passed to the html template: ``` $link = "<a href='mypage.php?f=dosomething&param1=".$var1."&param2=".$var2."' id='dosomething' >Need to open this link in the same dialog window</a>"; ``` And here's my jquery code: ``` $("#dosomething").dialog( { autoOpen:false, modal:true, overlay: { opacity: 0.8, background: "black" }, width:850, height:650, title:"A title", draggable:true, hide:"slow", closeOnEscape: true }); $("#dosomething").dialog("open"); ```
2012/10/03
[ "https://Stackoverflow.com/questions/12704217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/523129/" ]
The probable solution would be you **create a base class** which **extends TextView**, and use this text view class as edit text. Hope you are asking for size in first screen. In any case, u set the text size in the base class. This will solve your problem. like u create this class in package com.example and class name is BaseTextView, then in xml file instead of `<TextView .../>` you will write `<com.example.BaseTextView ... />` Hope this helps.
I'm not sure if it help. But there is something called "SSP" - Scalable size Unit for Text. Add this to your build gradle ``` implementation 'com.intuit.ssp:ssp-android:1.0.6' ``` And this to use ``` android:textSize="@dimen/_22ssp" ``` <https://github.com/intuit/ssp>
12,704,217
I have a link in a dialog modal window. I need this link to show in the same DIALOG MODAL window where it is. Here's how my link looks like, it is formed in a php file and then passed to the html template: ``` $link = "<a href='mypage.php?f=dosomething&param1=".$var1."&param2=".$var2."' id='dosomething' >Need to open this link in the same dialog window</a>"; ``` And here's my jquery code: ``` $("#dosomething").dialog( { autoOpen:false, modal:true, overlay: { opacity: 0.8, background: "black" }, width:850, height:650, title:"A title", draggable:true, hide:"slow", closeOnEscape: true }); $("#dosomething").dialog("open"); ```
2012/10/03
[ "https://Stackoverflow.com/questions/12704217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/523129/" ]
you can scale to text size of your app up/down using base activity Configuration, make all activities inherent base activity. Scale normal value is 1.0, 2.0 would double the font size and .50 would make it half. ``` public void adjustFontScale( Configuration configuration,float scale) { configuration.fontScale = scale; DisplayMetrics metrics = getResources().getDisplayMetrics(); WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE); wm.getDefaultDisplay().getMetrics(metrics); metrics.scaledDensity = configuration.fontScale * metrics.density; getBaseContext().getResources().updateConfiguration(configuration, metrics); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); adjustFontScale( getResources().getConfiguration()); } ```
I'm not sure if it help. But there is something called "SSP" - Scalable size Unit for Text. Add this to your build gradle ``` implementation 'com.intuit.ssp:ssp-android:1.0.6' ``` And this to use ``` android:textSize="@dimen/_22ssp" ``` <https://github.com/intuit/ssp>
12,704,217
I have a link in a dialog modal window. I need this link to show in the same DIALOG MODAL window where it is. Here's how my link looks like, it is formed in a php file and then passed to the html template: ``` $link = "<a href='mypage.php?f=dosomething&param1=".$var1."&param2=".$var2."' id='dosomething' >Need to open this link in the same dialog window</a>"; ``` And here's my jquery code: ``` $("#dosomething").dialog( { autoOpen:false, modal:true, overlay: { opacity: 0.8, background: "black" }, width:850, height:650, title:"A title", draggable:true, hide:"slow", closeOnEscape: true }); $("#dosomething").dialog("open"); ```
2012/10/03
[ "https://Stackoverflow.com/questions/12704217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/523129/" ]
`Android` documentation is not specific on the most efficient way to change the font size globally through the user’s selection at application level. There is a problem I think with the [answer](https://stackoverflow.com/a/12706334/1554935) given by **Black Devil**. The problem is that many of the `Android` widgets subclass `TextView`, such as `Button`, `RadioButton`, and `CheckBox`. Some of these are indirect subclasses of `TextView`, which makes implementing customized version of `TextView` in these classes very difficult. However as **pointed out by Siddharth Lele in his comment**, using `styles` or `themes` is much better way to handle change in the text size throughout the app. We set styles for layouts to control the look and feel of the view. Themes are essentially just collections of these styles. However, we can use a theme just for text size settings; without defining values for every property. Using a theme over styles provides us with one huge advantage: we can set a theme for the entire view programmatically. **theme.xml** ``` <resources> <style name="FontSizeSmall"> <item name="android:textSize">12sp</item> </style> <style name="FontSizeMedium"> <item name="android:textSize">16sp</item> </style> <style name="FontSizeLarge"> <item name="android:textSize">20sp</item> </style> </resources> ``` Create a class to handle loading our preferences: ``` public class BaseActivity extends Activity { @Override public void onStart() { super.onStart(); // Enclose everything in a try block so we can just // use the default view if anything goes wrong. try { // Get the font size value from SharedPreferences. SharedPreferences settings = getSharedPreferences("com.example.YourAppPackage", Context.MODE_PRIVATE); // Get the font size option. We use "FONT_SIZE" as the key. // Make sure to use this key when you set the value in SharedPreferences. // We specify "Medium" as the default value, if it does not exist. String fontSizePref = settings.getString("FONT_SIZE", "Medium"); // Select the proper theme ID. // These will correspond to your theme names as defined in themes.xml. int themeID = R.style.FontSizeMedium; if (fontSizePref == "Small") { themeID = R.style.FontSizeSmall; } else if (fontSizePref == "Large") { themeID = R.style.FontSizeLarge; } // Set the theme for the activity. setTheme(themeID); } catch (Exception ex) { ex.printStackTrace(); } } ``` Finally, create activities by extending BaseActivity, like this: ``` public class AppActivity extends BaseActivity{ } ``` As most of the application have a much fewer amount of Activities than TextViews or widgets that inherit TextView. This will be exponentially so as complexity increases, so this solution requires less changes in code. Thanks to [Ray Kuhnell](http://raykuhnell.com/2013/07/09/dynamic-font-size-and-other-styles-in-an-android-app/)
The probable solution would be you **create a base class** which **extends TextView**, and use this text view class as edit text. Hope you are asking for size in first screen. In any case, u set the text size in the base class. This will solve your problem. like u create this class in package com.example and class name is BaseTextView, then in xml file instead of `<TextView .../>` you will write `<com.example.BaseTextView ... />` Hope this helps.
11,815
I have a 2006 Nissan Altima 2.5S that has been making a metallic shh-shh noise. I've replaced the front brake pads and rotors, but the noise continues and is now becoming a distinct grinding noise. It's difficult to tell, but it seems that the noise is coming from the front of the vehicle and when brakes are applied comes more so on the passenger side of the car. Today I noticed the noise has become louder and more of a grinding sound. The grinding sound becomes more noticable when I turn to the left, with some noise when driving straight and none when turning left. I've linked to some recordings of the sound. They're both faint, but you can hear it better on the first one. [Recording #1](https://soundcloud.com/fyreflyt/sets/sounds-from-card) [Recording #2](https://soundcloud.com/fyreflyt/voice-003-08-13-2015)
2014/08/13
[ "https://mechanics.stackexchange.com/questions/11815", "https://mechanics.stackexchange.com", "https://mechanics.stackexchange.com/users/6706/" ]
In this case, the sound came from the rear brake pads which had completely worn away down to the metal backing. Once I replaced the rear pads and rotors (which had significant scoring) the sound went away.
When you are driving in a straight line, the load on the front axle is shared equally between the two front hubs, so any noises will be low. When you turn to the left, there is a weight transfer to the outside wheel(right wheel) and any noises from it will be more accentuated/louder. It is the opposite when you turn right. You need to check your hub bearings by rocking the wheels in the vertical plane with the vehicle raised and securely sitting on stands. Spinning the wheels by hand may also give you enough noise to make a diagnosis. Because changing the hub bearing involves pressing them in and out, this is a repair shop job.
31,146,647
On a page I'm working on, the results of the Google Places Autocomplete is showing up 70px below where it should, leaving a gap between the search box and the beginning of the results container. The height of the gap happens to be the exact height of Chrome's autofill feature, so I'm suspicious that the Autocomplete library is for some reason taking that height into account when calculating the position, even though I've managed to disable that feature on my search box. I'm able to fix the problem by overriding the value of the `top` attribute of the `.pac-container` class (replacing the value of `1234px` which the API has calculated with `1164px`), but I would rather have a way to do this dynamically or just based on an offset than have to hard-code that number. Is there a way, with CSS or JavaScript/jQuery, to move the Autocomplete results container up by a certain amount? A list of the CSS classes involved in the Autocomplete box can be found in Google's [documentation](https://developers.google.com/maps/documentation/javascript/places-autocomplete#style_autocomplete).
2015/06/30
[ "https://Stackoverflow.com/questions/31146647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2324475/" ]
I have tried many approaches and the best thing so far that worked for me is the good old (negative) margin. I wanted the resulting menu to be shown on top and I did this: ``` <style type="text/css"> .pac-container{ margin-top: -210px; } </style> ```
please check parent element of searchbox, if parent element has margin-top, then convert it into padding-top example code ` ``` .parent_element { /* margin-top: 70px; */ padding-top: 70px; } </style> <div class="parent_element"> <input type="text" class="autocomplete"> </div>` ``` I hope will work for you :)
31,146,647
On a page I'm working on, the results of the Google Places Autocomplete is showing up 70px below where it should, leaving a gap between the search box and the beginning of the results container. The height of the gap happens to be the exact height of Chrome's autofill feature, so I'm suspicious that the Autocomplete library is for some reason taking that height into account when calculating the position, even though I've managed to disable that feature on my search box. I'm able to fix the problem by overriding the value of the `top` attribute of the `.pac-container` class (replacing the value of `1234px` which the API has calculated with `1164px`), but I would rather have a way to do this dynamically or just based on an offset than have to hard-code that number. Is there a way, with CSS or JavaScript/jQuery, to move the Autocomplete results container up by a certain amount? A list of the CSS classes involved in the Autocomplete box can be found in Google's [documentation](https://developers.google.com/maps/documentation/javascript/places-autocomplete#style_autocomplete).
2015/06/30
[ "https://Stackoverflow.com/questions/31146647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2324475/" ]
**The below snippet worked for me.** In this initially, it will remove the previous **pac-container** div anywhere in the DOM. Later on, It tries to find the **pac-container** div element inside autocomplete object and it will place **pac-container** the div element inside another div in this case it is **"book-billing-address"** ``` $(".pac-container").remove(); autocomplete = new google.maps.places.Autocomplete(input); if(id_val == 'payment-address'){ setTimeout(function(){ if(autocomplete.gm_accessors_ != undefined){ var container_val = autocomplete.gm_accessors_.place.qe.gm_accessors_.input.qe.H autocomplete.gm_accessors_.place.qe.gm_accessors_.input.qe.H.remove(); $('#book-billing-address').append(container_val); } }, 100); } ``` and applied the following **CSS**, when div element moved inside **book-billing-address** div. ``` #book-billing-address .pac-container{ position: absolute !important; left: 0px !important; top: 36px !important; } ```
Add css on body tag with position: relative It worked.
31,146,647
On a page I'm working on, the results of the Google Places Autocomplete is showing up 70px below where it should, leaving a gap between the search box and the beginning of the results container. The height of the gap happens to be the exact height of Chrome's autofill feature, so I'm suspicious that the Autocomplete library is for some reason taking that height into account when calculating the position, even though I've managed to disable that feature on my search box. I'm able to fix the problem by overriding the value of the `top` attribute of the `.pac-container` class (replacing the value of `1234px` which the API has calculated with `1164px`), but I would rather have a way to do this dynamically or just based on an offset than have to hard-code that number. Is there a way, with CSS or JavaScript/jQuery, to move the Autocomplete results container up by a certain amount? A list of the CSS classes involved in the Autocomplete box can be found in Google's [documentation](https://developers.google.com/maps/documentation/javascript/places-autocomplete#style_autocomplete).
2015/06/30
[ "https://Stackoverflow.com/questions/31146647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2324475/" ]
I have tried many approaches and the best thing so far that worked for me is the good old (negative) margin. I wanted the resulting menu to be shown on top and I did this: ``` <style type="text/css"> .pac-container{ margin-top: -210px; } </style> ```
**The below snippet worked for me.** In this initially, it will remove the previous **pac-container** div anywhere in the DOM. Later on, It tries to find the **pac-container** div element inside autocomplete object and it will place **pac-container** the div element inside another div in this case it is **"book-billing-address"** ``` $(".pac-container").remove(); autocomplete = new google.maps.places.Autocomplete(input); if(id_val == 'payment-address'){ setTimeout(function(){ if(autocomplete.gm_accessors_ != undefined){ var container_val = autocomplete.gm_accessors_.place.qe.gm_accessors_.input.qe.H autocomplete.gm_accessors_.place.qe.gm_accessors_.input.qe.H.remove(); $('#book-billing-address').append(container_val); } }, 100); } ``` and applied the following **CSS**, when div element moved inside **book-billing-address** div. ``` #book-billing-address .pac-container{ position: absolute !important; left: 0px !important; top: 36px !important; } ```
31,146,647
On a page I'm working on, the results of the Google Places Autocomplete is showing up 70px below where it should, leaving a gap between the search box and the beginning of the results container. The height of the gap happens to be the exact height of Chrome's autofill feature, so I'm suspicious that the Autocomplete library is for some reason taking that height into account when calculating the position, even though I've managed to disable that feature on my search box. I'm able to fix the problem by overriding the value of the `top` attribute of the `.pac-container` class (replacing the value of `1234px` which the API has calculated with `1164px`), but I would rather have a way to do this dynamically or just based on an offset than have to hard-code that number. Is there a way, with CSS or JavaScript/jQuery, to move the Autocomplete results container up by a certain amount? A list of the CSS classes involved in the Autocomplete box can be found in Google's [documentation](https://developers.google.com/maps/documentation/javascript/places-autocomplete#style_autocomplete).
2015/06/30
[ "https://Stackoverflow.com/questions/31146647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2324475/" ]
I have tried many approaches and the best thing so far that worked for me is the good old (negative) margin. I wanted the resulting menu to be shown on top and I did this: ``` <style type="text/css"> .pac-container{ margin-top: -210px; } </style> ```
Add css on body tag with position: relative It worked.
31,146,647
On a page I'm working on, the results of the Google Places Autocomplete is showing up 70px below where it should, leaving a gap between the search box and the beginning of the results container. The height of the gap happens to be the exact height of Chrome's autofill feature, so I'm suspicious that the Autocomplete library is for some reason taking that height into account when calculating the position, even though I've managed to disable that feature on my search box. I'm able to fix the problem by overriding the value of the `top` attribute of the `.pac-container` class (replacing the value of `1234px` which the API has calculated with `1164px`), but I would rather have a way to do this dynamically or just based on an offset than have to hard-code that number. Is there a way, with CSS or JavaScript/jQuery, to move the Autocomplete results container up by a certain amount? A list of the CSS classes involved in the Autocomplete box can be found in Google's [documentation](https://developers.google.com/maps/documentation/javascript/places-autocomplete#style_autocomplete).
2015/06/30
[ "https://Stackoverflow.com/questions/31146647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2324475/" ]
**The below snippet worked for me.** In this initially, it will remove the previous **pac-container** div anywhere in the DOM. Later on, It tries to find the **pac-container** div element inside autocomplete object and it will place **pac-container** the div element inside another div in this case it is **"book-billing-address"** ``` $(".pac-container").remove(); autocomplete = new google.maps.places.Autocomplete(input); if(id_val == 'payment-address'){ setTimeout(function(){ if(autocomplete.gm_accessors_ != undefined){ var container_val = autocomplete.gm_accessors_.place.qe.gm_accessors_.input.qe.H autocomplete.gm_accessors_.place.qe.gm_accessors_.input.qe.H.remove(); $('#book-billing-address').append(container_val); } }, 100); } ``` and applied the following **CSS**, when div element moved inside **book-billing-address** div. ``` #book-billing-address .pac-container{ position: absolute !important; left: 0px !important; top: 36px !important; } ```
Yes, you can style the Autocomplete <https://google-developers.appspot.com/maps/documentation/javascript/places-autocomplete#style_autocomplete> However, lets look at WHY the "gap" is happening. **Double check your HTML and BODY tags, see if they have margin/padding added to them** So, the way Autocomplete detects it's position is by calculating the X/Y from the top/left of the BODY tag. I had this same problem (autocomplete had a big gap between the result box and the field), I discovered that my CMS system was adding a 30px margin to the BODY tag for the admin bar, *this pushed the Autocomplete box down by 30 pixals...* (the *real* problem) ``` html, body{margin:0 0 0 0;} ``` and the autocomplete vertical position was proper and the gap was gone without any odd JS scripting...
31,146,647
On a page I'm working on, the results of the Google Places Autocomplete is showing up 70px below where it should, leaving a gap between the search box and the beginning of the results container. The height of the gap happens to be the exact height of Chrome's autofill feature, so I'm suspicious that the Autocomplete library is for some reason taking that height into account when calculating the position, even though I've managed to disable that feature on my search box. I'm able to fix the problem by overriding the value of the `top` attribute of the `.pac-container` class (replacing the value of `1234px` which the API has calculated with `1164px`), but I would rather have a way to do this dynamically or just based on an offset than have to hard-code that number. Is there a way, with CSS or JavaScript/jQuery, to move the Autocomplete results container up by a certain amount? A list of the CSS classes involved in the Autocomplete box can be found in Google's [documentation](https://developers.google.com/maps/documentation/javascript/places-autocomplete#style_autocomplete).
2015/06/30
[ "https://Stackoverflow.com/questions/31146647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2324475/" ]
please check parent element of searchbox, if parent element has margin-top, then convert it into padding-top example code ` ``` .parent_element { /* margin-top: 70px; */ padding-top: 70px; } </style> <div class="parent_element"> <input type="text" class="autocomplete"> </div>` ``` I hope will work for you :)
It's perfectly work for me , no issue with position bug when scroll ``` function initAutocomplete() { //....codes... //....add this code just before close function... setTimeout(function(){ $(".pac-container").prependTo("#mapMoveHere"); }, 300); } ``` <https://codepen.io/gmkhussain/pen/qPpryg>
31,146,647
On a page I'm working on, the results of the Google Places Autocomplete is showing up 70px below where it should, leaving a gap between the search box and the beginning of the results container. The height of the gap happens to be the exact height of Chrome's autofill feature, so I'm suspicious that the Autocomplete library is for some reason taking that height into account when calculating the position, even though I've managed to disable that feature on my search box. I'm able to fix the problem by overriding the value of the `top` attribute of the `.pac-container` class (replacing the value of `1234px` which the API has calculated with `1164px`), but I would rather have a way to do this dynamically or just based on an offset than have to hard-code that number. Is there a way, with CSS or JavaScript/jQuery, to move the Autocomplete results container up by a certain amount? A list of the CSS classes involved in the Autocomplete box can be found in Google's [documentation](https://developers.google.com/maps/documentation/javascript/places-autocomplete#style_autocomplete).
2015/06/30
[ "https://Stackoverflow.com/questions/31146647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2324475/" ]
**The below snippet worked for me.** In this initially, it will remove the previous **pac-container** div anywhere in the DOM. Later on, It tries to find the **pac-container** div element inside autocomplete object and it will place **pac-container** the div element inside another div in this case it is **"book-billing-address"** ``` $(".pac-container").remove(); autocomplete = new google.maps.places.Autocomplete(input); if(id_val == 'payment-address'){ setTimeout(function(){ if(autocomplete.gm_accessors_ != undefined){ var container_val = autocomplete.gm_accessors_.place.qe.gm_accessors_.input.qe.H autocomplete.gm_accessors_.place.qe.gm_accessors_.input.qe.H.remove(); $('#book-billing-address').append(container_val); } }, 100); } ``` and applied the following **CSS**, when div element moved inside **book-billing-address** div. ``` #book-billing-address .pac-container{ position: absolute !important; left: 0px !important; top: 36px !important; } ```
It's perfectly work for me , no issue with position bug when scroll ``` function initAutocomplete() { //....codes... //....add this code just before close function... setTimeout(function(){ $(".pac-container").prependTo("#mapMoveHere"); }, 300); } ``` <https://codepen.io/gmkhussain/pen/qPpryg>
31,146,647
On a page I'm working on, the results of the Google Places Autocomplete is showing up 70px below where it should, leaving a gap between the search box and the beginning of the results container. The height of the gap happens to be the exact height of Chrome's autofill feature, so I'm suspicious that the Autocomplete library is for some reason taking that height into account when calculating the position, even though I've managed to disable that feature on my search box. I'm able to fix the problem by overriding the value of the `top` attribute of the `.pac-container` class (replacing the value of `1234px` which the API has calculated with `1164px`), but I would rather have a way to do this dynamically or just based on an offset than have to hard-code that number. Is there a way, with CSS or JavaScript/jQuery, to move the Autocomplete results container up by a certain amount? A list of the CSS classes involved in the Autocomplete box can be found in Google's [documentation](https://developers.google.com/maps/documentation/javascript/places-autocomplete#style_autocomplete).
2015/06/30
[ "https://Stackoverflow.com/questions/31146647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2324475/" ]
I have tried many approaches and the best thing so far that worked for me is the good old (negative) margin. I wanted the resulting menu to be shown on top and I did this: ``` <style type="text/css"> .pac-container{ margin-top: -210px; } </style> ```
Yes, you can style the Autocomplete <https://google-developers.appspot.com/maps/documentation/javascript/places-autocomplete#style_autocomplete> However, lets look at WHY the "gap" is happening. **Double check your HTML and BODY tags, see if they have margin/padding added to them** So, the way Autocomplete detects it's position is by calculating the X/Y from the top/left of the BODY tag. I had this same problem (autocomplete had a big gap between the result box and the field), I discovered that my CMS system was adding a 30px margin to the BODY tag for the admin bar, *this pushed the Autocomplete box down by 30 pixals...* (the *real* problem) ``` html, body{margin:0 0 0 0;} ``` and the autocomplete vertical position was proper and the gap was gone without any odd JS scripting...
31,146,647
On a page I'm working on, the results of the Google Places Autocomplete is showing up 70px below where it should, leaving a gap between the search box and the beginning of the results container. The height of the gap happens to be the exact height of Chrome's autofill feature, so I'm suspicious that the Autocomplete library is for some reason taking that height into account when calculating the position, even though I've managed to disable that feature on my search box. I'm able to fix the problem by overriding the value of the `top` attribute of the `.pac-container` class (replacing the value of `1234px` which the API has calculated with `1164px`), but I would rather have a way to do this dynamically or just based on an offset than have to hard-code that number. Is there a way, with CSS or JavaScript/jQuery, to move the Autocomplete results container up by a certain amount? A list of the CSS classes involved in the Autocomplete box can be found in Google's [documentation](https://developers.google.com/maps/documentation/javascript/places-autocomplete#style_autocomplete).
2015/06/30
[ "https://Stackoverflow.com/questions/31146647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2324475/" ]
Yes, you can style the Autocomplete <https://google-developers.appspot.com/maps/documentation/javascript/places-autocomplete#style_autocomplete> However, lets look at WHY the "gap" is happening. **Double check your HTML and BODY tags, see if they have margin/padding added to them** So, the way Autocomplete detects it's position is by calculating the X/Y from the top/left of the BODY tag. I had this same problem (autocomplete had a big gap between the result box and the field), I discovered that my CMS system was adding a 30px margin to the BODY tag for the admin bar, *this pushed the Autocomplete box down by 30 pixals...* (the *real* problem) ``` html, body{margin:0 0 0 0;} ``` and the autocomplete vertical position was proper and the gap was gone without any odd JS scripting...
please check parent element of searchbox, if parent element has margin-top, then convert it into padding-top example code ` ``` .parent_element { /* margin-top: 70px; */ padding-top: 70px; } </style> <div class="parent_element"> <input type="text" class="autocomplete"> </div>` ``` I hope will work for you :)
31,146,647
On a page I'm working on, the results of the Google Places Autocomplete is showing up 70px below where it should, leaving a gap between the search box and the beginning of the results container. The height of the gap happens to be the exact height of Chrome's autofill feature, so I'm suspicious that the Autocomplete library is for some reason taking that height into account when calculating the position, even though I've managed to disable that feature on my search box. I'm able to fix the problem by overriding the value of the `top` attribute of the `.pac-container` class (replacing the value of `1234px` which the API has calculated with `1164px`), but I would rather have a way to do this dynamically or just based on an offset than have to hard-code that number. Is there a way, with CSS or JavaScript/jQuery, to move the Autocomplete results container up by a certain amount? A list of the CSS classes involved in the Autocomplete box can be found in Google's [documentation](https://developers.google.com/maps/documentation/javascript/places-autocomplete#style_autocomplete).
2015/06/30
[ "https://Stackoverflow.com/questions/31146647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2324475/" ]
I have tried many approaches and the best thing so far that worked for me is the good old (negative) margin. I wanted the resulting menu to be shown on top and I did this: ``` <style type="text/css"> .pac-container{ margin-top: -210px; } </style> ```
It's perfectly work for me , no issue with position bug when scroll ``` function initAutocomplete() { //....codes... //....add this code just before close function... setTimeout(function(){ $(".pac-container").prependTo("#mapMoveHere"); }, 300); } ``` <https://codepen.io/gmkhussain/pen/qPpryg>
37,372,436
I'm using ASP.NET with C# 4.0. My problem is that I want only one button to activate a certain method on server. What do i mean? I'm glad you asked. I have 2 buttons.[!["Filter" and "FetchEvents"](https://i.stack.imgur.com/Fp7qB.png)](https://i.stack.imgur.com/Fp7qB.png) Any my aspx code is: ``` <form id="form2" runat="server"> <div class="box-generic"> <div class="form-group well" style=""> <input type="submit" name="button_filter" value="filter" class="btn btn-primary" /> <input type="button" id="all_events_button" name="all_events_button" value="All Events CSV" class="btn btn-primary" OnServerClick="downloadAllEvents" runat="server"/> </div> </div> </form> ``` If I press the "filter" button it works awesome. Whenever I press the "All Events CSV" button, it works great. **Scenario** **1.** Clicking on All Events. (Activates the all events button normally) **2.** Clicking on Filter. downloadAllEvents() Method is being activated. BAD BAD BAD ---------------------------------------------------------- And the weirdest part about it is that this method will be activated through filter only **after** it has been activated through AllEvents. EDIT: ----- I'm currently checking inside the method that the call didn't came from the filter button. not a pretty sight. Haven't found someone with the same problem. Thanks in advance :)
2016/05/22
[ "https://Stackoverflow.com/questions/37372436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3434672/" ]
In Kotlin [classes and members are final by default](https://kotlinlang.org/docs/reference/classes.html#wait-how-will-i-hack-my-libraries-now). In other words the following declarations have the same bytecode: ``` @JvmField final val CREATOR: Parcelable.Creator<Person> = PersonCreator() @JvmField val CREATOR: Parcelable.Creator<Person> = PersonCreator() ``` So while the generated code has `final` keyword and it is not an error it is redundant. Even though classes and members are final by default there are still a need for `final` modifier in Kotlin. One example would be to mark `open` method as `final` in derived class: ``` open class Base { open fun test(){} } open class DerivedA : Base(){ final override fun test(){} } class DerivedB : DerivedA() { override fun test(){} //error: 'test' in 'DerivedA' is final and cannot be overriden } ``` While it's a good practice to make `public static` field `final` in java there's [no strict requirement for the `Parccelable.Creator` field](https://developer.android.com/reference/android/os/Parcelable.html) to be marked as such: > > Classes implementing the Parcelable interface must also have a > non-null static field called CREATOR of a type that implements the > Parcelable.Creator interface. > > >
In Kotlin you can use the `@Parcelize` Kotlin Android Extension: ``` @Parcelize data class User(val id: String, val name: String) : Parcelable ``` This is a compiler plugin that automatically generates the [Parcelable](https://developer.android.com/reference/android/os/Parcelable) implementation for you. [This page](https://kotlinlang.org/docs/reference/compiler-plugins.html#parcelable-implementations-generator) on the Kotlin docs gives more details about it, including requirements, [supported types](https://kotlinlang.org/docs/reference/compiler-plugins.html#supported-types) and how to create [custom parcelers](https://kotlinlang.org/docs/reference/compiler-plugins.html#custom-parcelers) for unsupported types. --- If you are curious and you want dive into the technical details of the implementation, see the Kotlin Evolution and Enhancement Process [*Compiler Extension to Support `android.os.Parcelable`*](https://github.com/Kotlin/KEEP/blob/master/proposals/extensions/android-parcelable.md). --- This feature was [experimental until Kotlin 1.3.40](https://github.com/JetBrains/kotlin/blob/1.3.40/ChangeLog.md#tools-android-extensions). If you are still using a Kotlin version earlier than 1.3.40, you need to enable the experimental features to use this: ``` android { // Enable @Parcelize // You only need this for Kotlin < 1.3.40 androidExtensions { experimental = true } ... } ```
37,372,436
I'm using ASP.NET with C# 4.0. My problem is that I want only one button to activate a certain method on server. What do i mean? I'm glad you asked. I have 2 buttons.[!["Filter" and "FetchEvents"](https://i.stack.imgur.com/Fp7qB.png)](https://i.stack.imgur.com/Fp7qB.png) Any my aspx code is: ``` <form id="form2" runat="server"> <div class="box-generic"> <div class="form-group well" style=""> <input type="submit" name="button_filter" value="filter" class="btn btn-primary" /> <input type="button" id="all_events_button" name="all_events_button" value="All Events CSV" class="btn btn-primary" OnServerClick="downloadAllEvents" runat="server"/> </div> </div> </form> ``` If I press the "filter" button it works awesome. Whenever I press the "All Events CSV" button, it works great. **Scenario** **1.** Clicking on All Events. (Activates the all events button normally) **2.** Clicking on Filter. downloadAllEvents() Method is being activated. BAD BAD BAD ---------------------------------------------------------- And the weirdest part about it is that this method will be activated through filter only **after** it has been activated through AllEvents. EDIT: ----- I'm currently checking inside the method that the call didn't came from the filter button. not a pretty sight. Haven't found someone with the same problem. Thanks in advance :)
2016/05/22
[ "https://Stackoverflow.com/questions/37372436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3434672/" ]
In Kotlin [classes and members are final by default](https://kotlinlang.org/docs/reference/classes.html#wait-how-will-i-hack-my-libraries-now). In other words the following declarations have the same bytecode: ``` @JvmField final val CREATOR: Parcelable.Creator<Person> = PersonCreator() @JvmField val CREATOR: Parcelable.Creator<Person> = PersonCreator() ``` So while the generated code has `final` keyword and it is not an error it is redundant. Even though classes and members are final by default there are still a need for `final` modifier in Kotlin. One example would be to mark `open` method as `final` in derived class: ``` open class Base { open fun test(){} } open class DerivedA : Base(){ final override fun test(){} } class DerivedB : DerivedA() { override fun test(){} //error: 'test' in 'DerivedA' is final and cannot be overriden } ``` While it's a good practice to make `public static` field `final` in java there's [no strict requirement for the `Parccelable.Creator` field](https://developer.android.com/reference/android/os/Parcelable.html) to be marked as such: > > Classes implementing the Parcelable interface must also have a > non-null static field called CREATOR of a type that implements the > Parcelable.Creator interface. > > >
Use @Parcelize annotation to data class and extends Parcelable. Kotlin automatically do the rest for you. Example- Person data class. ``` @Parcelize data class Person(val name: String, val age: Int, val email: String) : Parcelable ``` You can send value lets press on a button click like below from an activity. ``` private val PERSON = "person" // first ensure a person object with data val person = Person("Shihab Uddin", 30, "shihab.mi7@gmai.com") binding.buttonSend.setOnClickListener { val intent = Intent(this, ReceiveParcelableAcitivty::class.java) //then put an parcelable extra to intent intent.putExtra(PERSON, person) startActivity(intent) } ``` Receivers activity will get the data like ``` private val PERSON = "person" intent?.let { var person = intent.extras.getParcelable(PERSON) as Person bind.textViewData.text = " Data Receive: $person" } ``` **androidExtensions** attribute is no more necessary < kotlin 1.3.40 ``` android { // You only need this for Kotlin < 1.3.40 androidExtensions { experimental = true } ... } ```
37,372,436
I'm using ASP.NET with C# 4.0. My problem is that I want only one button to activate a certain method on server. What do i mean? I'm glad you asked. I have 2 buttons.[!["Filter" and "FetchEvents"](https://i.stack.imgur.com/Fp7qB.png)](https://i.stack.imgur.com/Fp7qB.png) Any my aspx code is: ``` <form id="form2" runat="server"> <div class="box-generic"> <div class="form-group well" style=""> <input type="submit" name="button_filter" value="filter" class="btn btn-primary" /> <input type="button" id="all_events_button" name="all_events_button" value="All Events CSV" class="btn btn-primary" OnServerClick="downloadAllEvents" runat="server"/> </div> </div> </form> ``` If I press the "filter" button it works awesome. Whenever I press the "All Events CSV" button, it works great. **Scenario** **1.** Clicking on All Events. (Activates the all events button normally) **2.** Clicking on Filter. downloadAllEvents() Method is being activated. BAD BAD BAD ---------------------------------------------------------- And the weirdest part about it is that this method will be activated through filter only **after** it has been activated through AllEvents. EDIT: ----- I'm currently checking inside the method that the call didn't came from the filter button. not a pretty sight. Haven't found someone with the same problem. Thanks in advance :)
2016/05/22
[ "https://Stackoverflow.com/questions/37372436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3434672/" ]
In Kotlin you can use the `@Parcelize` Kotlin Android Extension: ``` @Parcelize data class User(val id: String, val name: String) : Parcelable ``` This is a compiler plugin that automatically generates the [Parcelable](https://developer.android.com/reference/android/os/Parcelable) implementation for you. [This page](https://kotlinlang.org/docs/reference/compiler-plugins.html#parcelable-implementations-generator) on the Kotlin docs gives more details about it, including requirements, [supported types](https://kotlinlang.org/docs/reference/compiler-plugins.html#supported-types) and how to create [custom parcelers](https://kotlinlang.org/docs/reference/compiler-plugins.html#custom-parcelers) for unsupported types. --- If you are curious and you want dive into the technical details of the implementation, see the Kotlin Evolution and Enhancement Process [*Compiler Extension to Support `android.os.Parcelable`*](https://github.com/Kotlin/KEEP/blob/master/proposals/extensions/android-parcelable.md). --- This feature was [experimental until Kotlin 1.3.40](https://github.com/JetBrains/kotlin/blob/1.3.40/ChangeLog.md#tools-android-extensions). If you are still using a Kotlin version earlier than 1.3.40, you need to enable the experimental features to use this: ``` android { // Enable @Parcelize // You only need this for Kotlin < 1.3.40 androidExtensions { experimental = true } ... } ```
Use @Parcelize annotation to data class and extends Parcelable. Kotlin automatically do the rest for you. Example- Person data class. ``` @Parcelize data class Person(val name: String, val age: Int, val email: String) : Parcelable ``` You can send value lets press on a button click like below from an activity. ``` private val PERSON = "person" // first ensure a person object with data val person = Person("Shihab Uddin", 30, "shihab.mi7@gmai.com") binding.buttonSend.setOnClickListener { val intent = Intent(this, ReceiveParcelableAcitivty::class.java) //then put an parcelable extra to intent intent.putExtra(PERSON, person) startActivity(intent) } ``` Receivers activity will get the data like ``` private val PERSON = "person" intent?.let { var person = intent.extras.getParcelable(PERSON) as Person bind.textViewData.text = " Data Receive: $person" } ``` **androidExtensions** attribute is no more necessary < kotlin 1.3.40 ``` android { // You only need this for Kotlin < 1.3.40 androidExtensions { experimental = true } ... } ```
50,975,032
I am trying to connect local mongodb from a docker container ruby on rails application. I have added the variable as `env MONGODB_URI` in envFile file with value: `MONGODB_URI=mongodb://username:password@host:27017/database` command I am using to run the image in container: `docker run -p 80:80 --env-file ~/envFile -v ~/.ssh/filename:/tmp/filename --name=name imagename` But it's not connecting with mongodb. I am new in working with docker.
2018/06/21
[ "https://Stackoverflow.com/questions/50975032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2510165/" ]
So, I figured out the answer as I had this same problem. My encoding was wrong and so it wouldn't read the text correctly. I opened it in Visual Studio Code and found the encoding was UTF-16 LE. My output came from powershell so yours likely did too and you probably just need to specify the output encoding or change the encoding for panda. ``` pd.read_csv("ADSearch.txt",encoding='UTF-16 LE') Empty DataFrame Columns: [lastname, firstname, username, site, email, Unnamed: 5, False, True] Index: [] ```
Works perfectly with the sample input that you have given Sample input also shown Version of Python and pandas also shown ``` ~ $ python Python 3.6.4 |Anaconda custom (64-bit)| (default, Jan 16 2018, 18:10:19) [GCC 7.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import pandas as pd >>> pd.read_csv('sample.csv') A B 0 0.0 0.0 1 0.0 0.0 >>> pd.__version__ '0.22.0' >>> exit() ~ $ cat sample.csv A, B 0.000, 0.000 0.000, 0.000 ```
50,975,032
I am trying to connect local mongodb from a docker container ruby on rails application. I have added the variable as `env MONGODB_URI` in envFile file with value: `MONGODB_URI=mongodb://username:password@host:27017/database` command I am using to run the image in container: `docker run -p 80:80 --env-file ~/envFile -v ~/.ssh/filename:/tmp/filename --name=name imagename` But it's not connecting with mongodb. I am new in working with docker.
2018/06/21
[ "https://Stackoverflow.com/questions/50975032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2510165/" ]
I found this issue and here are some steps to diagnostic: First check with command line if the file is human readable: ``` head file.txt ``` After that in python3 console try to print some lines: ``` with open("file.txt", encoding="latin1", errors='ignore') as f: for i in f: print([str(i.strip())]) ``` If you see lines in hex format, i.e. `\x00N\x00A\x00S\x00S\x00A\x00U\x00"\x00;` indicates that there are null chars in the source file. So to remove them just `sed -i 's/\x0//g' file.txt` as stated [here](https://stackoverflow.com/a/2399817/4086871) and load the file in python again.
Works perfectly with the sample input that you have given Sample input also shown Version of Python and pandas also shown ``` ~ $ python Python 3.6.4 |Anaconda custom (64-bit)| (default, Jan 16 2018, 18:10:19) [GCC 7.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import pandas as pd >>> pd.read_csv('sample.csv') A B 0 0.0 0.0 1 0.0 0.0 >>> pd.__version__ '0.22.0' >>> exit() ~ $ cat sample.csv A, B 0.000, 0.000 0.000, 0.000 ```
50,975,032
I am trying to connect local mongodb from a docker container ruby on rails application. I have added the variable as `env MONGODB_URI` in envFile file with value: `MONGODB_URI=mongodb://username:password@host:27017/database` command I am using to run the image in container: `docker run -p 80:80 --env-file ~/envFile -v ~/.ssh/filename:/tmp/filename --name=name imagename` But it's not connecting with mongodb. I am new in working with docker.
2018/06/21
[ "https://Stackoverflow.com/questions/50975032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2510165/" ]
So, I figured out the answer as I had this same problem. My encoding was wrong and so it wouldn't read the text correctly. I opened it in Visual Studio Code and found the encoding was UTF-16 LE. My output came from powershell so yours likely did too and you probably just need to specify the output encoding or change the encoding for panda. ``` pd.read_csv("ADSearch.txt",encoding='UTF-16 LE') Empty DataFrame Columns: [lastname, firstname, username, site, email, Unnamed: 5, False, True] Index: [] ```
I found this issue and here are some steps to diagnostic: First check with command line if the file is human readable: ``` head file.txt ``` After that in python3 console try to print some lines: ``` with open("file.txt", encoding="latin1", errors='ignore') as f: for i in f: print([str(i.strip())]) ``` If you see lines in hex format, i.e. `\x00N\x00A\x00S\x00S\x00A\x00U\x00"\x00;` indicates that there are null chars in the source file. So to remove them just `sed -i 's/\x0//g' file.txt` as stated [here](https://stackoverflow.com/a/2399817/4086871) and load the file in python again.
1,136,549
I realise that this might be a question that has been asked and answered, but please bear with me. I want to know if it is possible to use annotations to inject code into your classes compile time. The classic example is to generate a getter and setter for the members of your object. This is not exactly what I need it for, but it serves to illustrate the basic idea. Now on the internet the basic answer I get is no, but this guy did it: [link text](http://www.hanhuy.com/pfn/java_property_annotation) Does anyone know how he does what he does (and if he actually does what he says he does)? The main thing is that he does not use an annotation processor to generate a new java file to compile. This technique I am aware of and will not work for our purpose. Thanks
2009/07/16
[ "https://Stackoverflow.com/questions/1136549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It is not supported to modify code at compile time but it seems to be possible by using non-supported javac-internal APIs, [here](http://forums.sun.com/thread.jspa?threadID=5269463) is a post referencing the hanbuy-panno solution with also a link to the [code](http://svntrac.hanhuy.com/repo/browser/hanhuy/trunk/panno/src/com/hanhuy/panno/processing/PropertyProcessor.java)...
Something needs to process the annotations, so it either happens at compile time with an annotation processor or at runtime with reflection (yes I know, there are even more exotic ways of doing it at runtime). He most definitely is using an annotation processor, it's just that it's implicit. The `javac` command will search the class path for annotation processors if not explicitly set. Since he uses this command to compile: `javac -cp ~/development/panno/build/hanhuy-panno.jar *.java` We see he has modified the class path to include the `hanhuy-panno.jar`, which will contain the annotation processor. Why not just email the guy and ask if he'll give you the code?
1,136,549
I realise that this might be a question that has been asked and answered, but please bear with me. I want to know if it is possible to use annotations to inject code into your classes compile time. The classic example is to generate a getter and setter for the members of your object. This is not exactly what I need it for, but it serves to illustrate the basic idea. Now on the internet the basic answer I get is no, but this guy did it: [link text](http://www.hanhuy.com/pfn/java_property_annotation) Does anyone know how he does what he does (and if he actually does what he says he does)? The main thing is that he does not use an annotation processor to generate a new java file to compile. This technique I am aware of and will not work for our purpose. Thanks
2009/07/16
[ "https://Stackoverflow.com/questions/1136549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I went looking for [something similar](https://stackoverflow.com/questions/340353/plugging-in-to-java-compilers) last year. There is no standard way to alter classes using annotation processors or the compiler and the annotation API documentation recommends creating decorators. If you are willing to live with the hacks, have a look at [Adrian Kuhn](https://stackoverflow.com/users/24468/adrian-kuhn)'s use of the private API where he [adds Roman numeral literals to Java](http://www.iam.unibe.ch/~akuhn/blog/2008/roman-numerals-in-your-java/). This approach is limited to the Sun javac compiler and you would need to implement something else if you used another (like the Eclipse compiler). --- Edit: anyone interested in this area should check out [Project Lombok](http://projectlombok.org/).
Something needs to process the annotations, so it either happens at compile time with an annotation processor or at runtime with reflection (yes I know, there are even more exotic ways of doing it at runtime). He most definitely is using an annotation processor, it's just that it's implicit. The `javac` command will search the class path for annotation processors if not explicitly set. Since he uses this command to compile: `javac -cp ~/development/panno/build/hanhuy-panno.jar *.java` We see he has modified the class path to include the `hanhuy-panno.jar`, which will contain the annotation processor. Why not just email the guy and ask if he'll give you the code?
1,136,549
I realise that this might be a question that has been asked and answered, but please bear with me. I want to know if it is possible to use annotations to inject code into your classes compile time. The classic example is to generate a getter and setter for the members of your object. This is not exactly what I need it for, but it serves to illustrate the basic idea. Now on the internet the basic answer I get is no, but this guy did it: [link text](http://www.hanhuy.com/pfn/java_property_annotation) Does anyone know how he does what he does (and if he actually does what he says he does)? The main thing is that he does not use an annotation processor to generate a new java file to compile. This technique I am aware of and will not work for our purpose. Thanks
2009/07/16
[ "https://Stackoverflow.com/questions/1136549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can do this, but you're not supposed to modify the class containing the annotations. (The trick you link to uses the compile tree api to modify the bytecode being generated...) This is not supported and will probably be guarded against in later Java SDKs. The proper way to do it is to generate a superclass, subclass or wrapper class. I've written a set of annotations that generate getters/setters and other fun stuff. I generate a superclass. See <http://code.google.com/p/javadude/wiki/Annotations> You can do things like ``` package sample; import com.javadude.annotation.Bean; import com.javadude.annotation.Property; import com.javadude.annotation.PropertyKind; @Bean(properties={ @Property(name="name"), @Property(name="phone", bound=true), @Property(name="friend", type=Person.class, kind=PropertyKind.LIST) }) public class Person extends PersonGen { } ``` and it'll generate PersonGen for you with the fields/getters/setters and bound property support.
Something needs to process the annotations, so it either happens at compile time with an annotation processor or at runtime with reflection (yes I know, there are even more exotic ways of doing it at runtime). He most definitely is using an annotation processor, it's just that it's implicit. The `javac` command will search the class path for annotation processors if not explicitly set. Since he uses this command to compile: `javac -cp ~/development/panno/build/hanhuy-panno.jar *.java` We see he has modified the class path to include the `hanhuy-panno.jar`, which will contain the annotation processor. Why not just email the guy and ask if he'll give you the code?
1,136,549
I realise that this might be a question that has been asked and answered, but please bear with me. I want to know if it is possible to use annotations to inject code into your classes compile time. The classic example is to generate a getter and setter for the members of your object. This is not exactly what I need it for, but it serves to illustrate the basic idea. Now on the internet the basic answer I get is no, but this guy did it: [link text](http://www.hanhuy.com/pfn/java_property_annotation) Does anyone know how he does what he does (and if he actually does what he says he does)? The main thing is that he does not use an annotation processor to generate a new java file to compile. This technique I am aware of and will not work for our purpose. Thanks
2009/07/16
[ "https://Stackoverflow.com/questions/1136549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It is not supported to modify code at compile time but it seems to be possible by using non-supported javac-internal APIs, [here](http://forums.sun.com/thread.jspa?threadID=5269463) is a post referencing the hanbuy-panno solution with also a link to the [code](http://svntrac.hanhuy.com/repo/browser/hanhuy/trunk/panno/src/com/hanhuy/panno/processing/PropertyProcessor.java)...
I went looking for [something similar](https://stackoverflow.com/questions/340353/plugging-in-to-java-compilers) last year. There is no standard way to alter classes using annotation processors or the compiler and the annotation API documentation recommends creating decorators. If you are willing to live with the hacks, have a look at [Adrian Kuhn](https://stackoverflow.com/users/24468/adrian-kuhn)'s use of the private API where he [adds Roman numeral literals to Java](http://www.iam.unibe.ch/~akuhn/blog/2008/roman-numerals-in-your-java/). This approach is limited to the Sun javac compiler and you would need to implement something else if you used another (like the Eclipse compiler). --- Edit: anyone interested in this area should check out [Project Lombok](http://projectlombok.org/).
1,136,549
I realise that this might be a question that has been asked and answered, but please bear with me. I want to know if it is possible to use annotations to inject code into your classes compile time. The classic example is to generate a getter and setter for the members of your object. This is not exactly what I need it for, but it serves to illustrate the basic idea. Now on the internet the basic answer I get is no, but this guy did it: [link text](http://www.hanhuy.com/pfn/java_property_annotation) Does anyone know how he does what he does (and if he actually does what he says he does)? The main thing is that he does not use an annotation processor to generate a new java file to compile. This technique I am aware of and will not work for our purpose. Thanks
2009/07/16
[ "https://Stackoverflow.com/questions/1136549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It is not supported to modify code at compile time but it seems to be possible by using non-supported javac-internal APIs, [here](http://forums.sun.com/thread.jspa?threadID=5269463) is a post referencing the hanbuy-panno solution with also a link to the [code](http://svntrac.hanhuy.com/repo/browser/hanhuy/trunk/panno/src/com/hanhuy/panno/processing/PropertyProcessor.java)...
You can do this, but you're not supposed to modify the class containing the annotations. (The trick you link to uses the compile tree api to modify the bytecode being generated...) This is not supported and will probably be guarded against in later Java SDKs. The proper way to do it is to generate a superclass, subclass or wrapper class. I've written a set of annotations that generate getters/setters and other fun stuff. I generate a superclass. See <http://code.google.com/p/javadude/wiki/Annotations> You can do things like ``` package sample; import com.javadude.annotation.Bean; import com.javadude.annotation.Property; import com.javadude.annotation.PropertyKind; @Bean(properties={ @Property(name="name"), @Property(name="phone", bound=true), @Property(name="friend", type=Person.class, kind=PropertyKind.LIST) }) public class Person extends PersonGen { } ``` and it'll generate PersonGen for you with the fields/getters/setters and bound property support.
5,032,552
I have an ASP.NET MVC 3 application, [WouldBeBetter.com](http://www.wouldbebetter.com), currently hosted on Windows Azure. I have an Introductory Special subscription package that was free for several months but was surprised at how expensive it has turned out to be (€150 p/m on average!) now that I have started paying for it. That is just *way* too much money for a site that is not going to generate money any time soon so I've decided to move to a regular hosting provider (DiscountASP.Net). One of the things I'll truly miss though, is the separated Staging and Production environments Azure provides, along with the zero-downtime environment swap. My question is, how could I go about "simulating" a staging environment while hosting on a traditional provider? And what is my best shot at minimizing downtime on new deployments? Thanks. **UPDATE:** I chose the answer I chose not because I consider it the best method, but because it is what makes the most sense for me at this point.
2011/02/17
[ "https://Stackoverflow.com/questions/5032552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93356/" ]
I use DiscountASP myself. It's pretty basic hosting for sure, a little behind the times. But I have found just creating a subdirectory and publishing my beta/test/whatever versions there works pretty well. It's not fancy or pretty, but does get the job done. In order to do this you need to create the subdirectory first, then go into the control panel and tell DASP that directory is an application. Then you also have to consider that directory's web.config is going to be a combination of its own and the parent one. You also have to consider robots.txt for this subdirectory and protecting it in general from nosy people. You could probably pull this off with subdomains too, depending on how your domain is set up. Another option: appharbor? They have a free plan. If you can stay within the confines of their free plan, it might work well (I've never used them, currently interested in trying them though)
1) Get an automated deployment tool. There are plenty of free/open-source ones that million/billion dollar companies actually use for their production environments. 2) Get a second hosting package identical to the first. Use it as your staging, then just redeploy to production when staging passes.