Search Results

Search found 21062 results on 843 pages for 'argos void'.

Page 10/843 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • How to configure a Custom Datacontract Serializer or XMLSerializer

    - by user364445
    Im haveing some xml that have this structure <Person Id="*****" Name="*****"> <AccessControlEntries> <AccessControlEntry Id="*****" Name="****"/> </AccessControlEntries> <AccessControls /> <IdentityGroups> <IdentityGroup Id="****" Name="*****" /> </IdentityGroups></Person> and i also have this entities [DataContract(IsReference = true)] public abstract class EntityBase { protected bool serializing; [DataMember(Order = 1)] [XmlAttribute()] public string Id { get; set; } [DataMember(Order = 2)] [XmlAttribute()] public string Name { get; set; } [OnDeserializing()] public void OnDeserializing(StreamingContext context) { this.Initialize(); } [OnSerializing()] public void OnSerializing(StreamingContext context) { this.serializing = true; } [OnSerialized()] public void OnSerialized(StreamingContext context) { this.serializing = false; } public abstract void Initialize(); public string ToXml() { var settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.OmitXmlDeclaration = true; var sb = new System.Text.StringBuilder(); using (var writer = System.Xml.XmlWriter.Create(sb, settings)) { var serializer = new XmlSerializer(this.GetType()); serializer.Serialize(writer, this); } return sb.ToString(); } } [DataContract()] public abstract class Identity : EntityBase { private EntitySet<AccessControlEntry> accessControlEntries; private EntitySet<IdentityGroup> identityGroups; public Identity() { Initialize(); } [DataMember(Order = 3, EmitDefaultValue = false)] [Association(Name = "AccessControlEntries")] public EntitySet<AccessControlEntry> AccessControlEntries { get { if ((this.serializing && (this.accessControlEntries==null || this.accessControlEntries.HasLoadedOrAssignedValues == false))) { return null; } return accessControlEntries; } set { accessControlEntries.Assign(value); } } [DataMember(Order = 4, EmitDefaultValue = false)] [Association(Name = "IdentityGroups")] public EntitySet<IdentityGroup> IdentityGroups { get { if ((this.serializing && (this.identityGroups == null || this.identityGroups.HasLoadedOrAssignedValues == false))) { return null; } return identityGroups; } set { identityGroups.Assign(value); } } private void attach_accessControlEntry(AccessControlEntry entity) { entity.Identities.Add(this); } private void dettach_accessControlEntry(AccessControlEntry entity) { entity.Identities.Remove(this); } private void attach_IdentityGroup(IdentityGroup entity) { entity.MemberIdentites.Add(this); } private void dettach_IdentityGroup(IdentityGroup entity) { entity.MemberIdentites.Add(this); } public override void Initialize() { this.accessControlEntries = new EntitySet<AccessControlEntry>( new Action<AccessControlEntry>(this.attach_accessControlEntry), new Action<AccessControlEntry>(this.dettach_accessControlEntry)); this.identityGroups = new EntitySet<IdentityGroup>( new Action<IdentityGroup>(this.attach_IdentityGroup), new Action<IdentityGroup>(this.dettach_IdentityGroup)); } } [XmlType(TypeName = "AccessControlEntry")] public class AccessControlEntry : EntityBase, INotifyPropertyChanged { private EntitySet<Service> services; private EntitySet<Identity> identities; private EntitySet<Permission> permissions; public AccessControlEntry() { services = new EntitySet<Service>(new Action<Service>(attach_Service), new Action<Service>(dettach_Service)); identities = new EntitySet<Identity>(new Action<Identity>(attach_Identity), new Action<Identity>(dettach_Identity)); permissions = new EntitySet<Permission>(new Action<Permission>(attach_Permission), new Action<Permission>(dettach_Permission)); } [DataMember(Order = 3, EmitDefaultValue = false)] public EntitySet<Permission> Permissions { get { if ((this.serializing && (this.permissions.HasLoadedOrAssignedValues == false))) { return null; } return permissions; } set { permissions.Assign(value); } } [DataMember(Order = 4, EmitDefaultValue = false)] public EntitySet<Identity> Identities { get { if ((this.serializing && (this.identities.HasLoadedOrAssignedValues == false))) { return null; } return identities; } set { identities.Assign(identities); } } [DataMember(Order = 5, EmitDefaultValue = false)] public EntitySet<Service> Services { get { if ((this.serializing && (this.services.HasLoadedOrAssignedValues == false))) { return null; } return services; } set { services.Assign(value); } } private void attach_Permission(Permission entity) { entity.AccessControlEntires.Add(this); } private void dettach_Permission(Permission entity) { entity.AccessControlEntires.Remove(this); } private void attach_Identity(Identity entity) { entity.AccessControlEntries.Add(this); } private void dettach_Identity(Identity entity) { entity.AccessControlEntries.Remove(this); } private void attach_Service(Service entity) { entity.AccessControlEntries.Add(this); } private void dettach_Service(Service entity) { entity.AccessControlEntries.Remove(this); } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(name)); } #endregion public override void Initialize() { throw new NotImplementedException(); } } [DataContract()] [XmlType(TypeName = "Person")] public class Person : Identity { private EntityRef<Login> login; [DataMember(Order = 3)] [XmlAttribute()] public string Nombre { get; set; } [DataMember(Order = 4)] [XmlAttribute()] public string Apellidos { get; set; } [DataMember(Order = 5)] public Login Login { get { return login.Entity; } set { var previousValue = this.login.Entity; if (((previousValue != value) || (this.login.HasLoadedOrAssignedValue == false))) { if ((previousValue != null)) { this.login.Entity = null; previousValue.Person = null; } this.login.Entity = value; if ((value != null)) value.Person = this; } } } public override void Initialize() { base.Initialize(); } } [DataContract()] [XmlType(TypeName = "Login")] public class Login : EntityBase { private EntityRef<Person> person; [DataMember(Order = 3)] public string UserID { get; set; } [DataMember(Order = 4)] public string Contrasena { get; set; } [DataMember(Order = 5)] public Domain Dominio { get; set; } public Person Person { get { return person.Entity; } set { var previousValue = this.person.Entity; if (((previousValue != value) || (this.person.HasLoadedOrAssignedValue == false))) { if ((previousValue != null)) { this.person.Entity = null; previousValue.Login = null; } this.person.Entity = value; if ((value != null)) value.Login = this; } } } public override void Initialize() { throw new NotImplementedException(); } } [DataContract()] [XmlType(TypeName = "IdentityGroup")] public class IdentityGroup : Identity { private EntitySet<Identity> memberIdentities; public IdentityGroup() { Initialize(); } public override void Initialize() { this.memberIdentities = new EntitySet<Identity>(new Action<Identity>(this.attach_Identity), new Action<Identity>(this.dettach_Identity)); } [DataMember(Order = 3, EmitDefaultValue = false)] [Association(Name = "MemberIdentities")] public EntitySet<Identity> MemberIdentites { get { if ((this.serializing && (this.memberIdentities.HasLoadedOrAssignedValues == false))) { return null; } return memberIdentities; } set { memberIdentities.Assign(value); } } private void attach_Identity(Identity entity) { entity.IdentityGroups.Add(this); } private void dettach_Identity(Identity entity) { entity.IdentityGroups.Remove(this); } } [DataContract()] [XmlType(TypeName = "Group")] public class Group : Identity { public override void Initialize() { throw new NotImplementedException(); } } but the ToXml() response something like this <Person xmlns:xsi="************" xmlns:xsd="******" ID="******" Name="*****"/><AccessControlEntries/></Person> but what i want is something like this <Person Id="****" Name="***" Nombre="****"> <AccessControlEntries/> <IdentityGroups/> </Person>

    Read the article

  • Popping UIView crashes app

    - by Adun
    I'm basically pushing a UIView from a UITableViewController and all it contains is a UIWebView. However when I remove the UIView to return back to the UITableView the app crashes. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Navigation logic may go here. Create and push another view controller. if (indexPath.row == websiteCell) { NSString *urlPath = [NSString stringWithFormat:@"http://%@", exhibitor.website]; WebViewController *webViewController = [[WebViewController alloc] initWithURLString:urlPath]; // Pass the selected object to the new view controller. [self.parentViewController presentModalViewController:webViewController animated:YES]; [webViewController release]; } } If I comment out the [webViewController release] the app doesn't crash, but I know that this would be a leak. Below is the code for the Web Browser: #import "WebViewController.h" @implementation WebViewController @synthesize webBrowserView; @synthesize urlValue; @synthesize toolBar; @synthesize spinner; @synthesize loadUrl; -(id)initWithURLString:(NSString *)urlString { if (self = [super init]) { urlValue = urlString; } return self; } #pragma mark WebView Controls - (void)goBack { [webBrowserView goBack]; } - (void)goForward { [webBrowserView goForward]; } - (void)reload { [webBrowserView reload]; } - (void)closeBrowser { [self.parentViewController dismissModalViewControllerAnimated:YES]; } #pragma end // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; CGRect contentRect = self.view.bounds; //NSLog(@"%f", contentRect.size.height); float webViewHeight = contentRect.size.height - 44.0f; // navBar = 44 float toolBarHeight = contentRect.size.height - webViewHeight; // navigation bar UINavigationBar *navBar = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 20, contentRect.size.width, 44)] autorelease]; navBar.delegate = self; UIBarButtonItem *doneButton = [[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:nil action:@selector(closeBrowser)] autorelease]; UINavigationItem *item = [[[UINavigationItem alloc] initWithTitle:@"CEDIA10"] autorelease]; item.leftBarButtonItem = doneButton; [navBar pushNavigationItem:item animated:NO]; [self.view addSubview:navBar]; // web browser webBrowserView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 64, contentRect.size.width, webViewHeight)]; webBrowserView.delegate = self; webBrowserView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; webBrowserView.scalesPageToFit = YES; [self.view addSubview:webBrowserView]; // buttons UIBarButtonItem *backButton = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrowleft.png"] style:UIBarButtonItemStylePlain target:self action:@selector(goBack)] autorelease]; UIBarButtonItem *fwdButton = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrowright.png"] style:UIBarButtonItemStylePlain target:self action:@selector(goForward)] autorelease]; UIBarButtonItem *refreshButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reload)] autorelease]; UIBarButtonItem *flexSpace = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease]; UIBarButtonItem *fixSpace = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil] autorelease]; [fixSpace setWidth: 40.0f]; spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] autorelease]; [spinner startAnimating]; UIBarButtonItem *loadingIcon = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease]; NSArray *toolBarButtons = [[NSArray alloc] initWithObjects: fixSpace, backButton, fixSpace, fwdButton, flexSpace, loadingIcon, flexSpace, refreshButton, nil]; // toolbar toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, webViewHeight, contentRect.size.width, toolBarHeight)]; toolBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth; toolBar.items = toolBarButtons; [self.view addSubview:toolBar]; // load the request NSURL *requestString = [NSURL URLWithString:urlValue]; [webBrowserView loadRequest:[NSURLRequest requestWithURL: requestString]]; [toolBarButtons release]; } - (void)viewWillDisappear { if ([webBrowserView isLoading]) { [webBrowserView stopLoading]; webBrowserView.delegate = nil; } } #pragma mark UIWebView - (void)webViewDidStartLoad:(UIWebView*)webView { [spinner startAnimating]; } - (void)webViewDidFinishLoad:(UIWebView*)webView { [spinner stopAnimating]; } - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { loadUrl = [[request URL] retain]; if ([[loadUrl scheme] isEqualToString: @"mailto"]) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"CEDIA10" message:@"Do you want to open Mail and exit AREC10?" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes",nil]; [alert show]; [alert release]; return NO; } [loadUrl release]; return YES; } - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { [spinner stopAnimating]; if (error.code == -1009) { // no internet connection UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"CEDIA10" message:@"You need an active Internet connection." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; } } #pragma mark UIAlertView - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { if (buttonIndex == 1) { [[UIApplication sharedApplication] openURL:loadUrl]; [loadUrl release]; } } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. [webBrowserView release]; [urlValue release]; [toolBar release]; [spinner release]; [loadUrl release]; webBrowserView = nil; webBrowserView.delegate = nil; urlValue = nil; toolBar = nil; spinner = nil; loadUrl = nil; } - (void)viewDidUnload { // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)dealloc { [webBrowserView release]; [urlValue release]; [toolBar release]; [spinner release]; [loadUrl release]; webBrowserView.delegate = nil; urlValue = nil; toolBar = nil; spinner = nil; loadUrl = nil; [super dealloc]; } @end Below this is the crash log that I am getting: Date/Time: 2010-05-13 11:58:20.023 +1000 OS Version: iPhone OS 3.1.3 (7E18) Report Version: 104 Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x00000000, 0x00000000 Crashed Thread: 0 Thread 0 Crashed: 0 libSystem.B.dylib 0x00090b2c __kill + 8 1 libSystem.B.dylib 0x00090b1a kill + 4 2 libSystem.B.dylib 0x00090b0e raise + 10 3 libSystem.B.dylib 0x000a7e34 abort + 36 4 libstdc++.6.dylib 0x00066390 __gnu_cxx::__verbose_terminate_handler() + 588 5 libobjc.A.dylib 0x00008898 _objc_terminate + 160 6 libstdc++.6.dylib 0x00063a84 __cxxabiv1::__terminate(void (*)()) + 76 7 libstdc++.6.dylib 0x00063afc std::terminate() + 16 8 libstdc++.6.dylib 0x00063c24 __cxa_throw + 100 9 libobjc.A.dylib 0x00006e54 objc_exception_throw + 104 10 CoreFoundation 0x00095bf6 -[NSObject doesNotRecognizeSelector:] + 106 11 CoreFoundation 0x0001ab12 ___forwarding___ + 474 12 CoreFoundation 0x00011838 _CF_forwarding_prep_0 + 40 13 QuartzCore 0x0000f448 CALayerCopyRenderLayer + 24 14 QuartzCore 0x0000f048 CA::Context::commit_layer(_CALayer*, unsigned int, unsigned int, void*) + 100 15 QuartzCore 0x0000ef34 CALayerCommitIfNeeded + 336 16 QuartzCore 0x0000eedc CALayerCommitIfNeeded + 248 17 QuartzCore 0x00011ee8 CA::Context::commit_root(void*, void*) + 52 18 QuartzCore 0x00011e80 x_hash_table_foreach + 64 19 QuartzCore 0x00011e2c CA::Transaction::foreach_root(void (*)(void*, void*), void*) + 40 20 QuartzCore 0x0000bb68 CA::Context::commit_transaction(CA::Transaction*) + 1068 21 QuartzCore 0x0000b46c CA::Transaction::commit() + 276 22 QuartzCore 0x000135d4 CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 84 23 CoreFoundation 0x0000f82a __CFRunLoopDoObservers + 466 24 CoreFoundation 0x00057340 CFRunLoopRunSpecific + 1812 25 CoreFoundation 0x00056c18 CFRunLoopRunInMode + 44 26 GraphicsServices 0x000041c0 GSEventRunModal + 188 27 UIKit 0x00003c28 -[UIApplication _run] + 552 28 UIKit 0x00002228 UIApplicationMain + 960 29 CEDIA10 0x00002e16 main (main.m:14) 30 CEDIA10 0x00002db8 start + 32 Any ideas on why the app is crashing?

    Read the article

  • Casting an object using 'as' returns null: myObject = newObject as MyObject; // null

    - by John Russell
    I am trying to create a custom object in AS3 to pass information to and from a server, which in this case will be Red5. In the below screenshots you will see that I am able to send a request for an object from as3, and receive it successfully from the java server. However, when I try to cast the received object to my defined objectType using 'as', it takes the value of null. It is my understanding that that when using "as" your checking to see if your variable is a member of the specified data type. If the variable is not, then null will be returned. This screenshot illustrates that I am have successfully received my object 'o' from red5 and I am just about to cast it to the (supposedly) identical datatype testObject of LobbyData: However, when testObject = o as LobbyData; runs, it returns null. :( Below you will see my specifications both on the java server and the as3 client. I am confident that both objects are identical in every way, but for some reason flash does not think so. I have been pulling my hair out for a long time, does anyone have any thoughts? AS3 Object: import flash.utils.IDataInput; import flash.utils.IDataOutput; import flash.utils.IExternalizable; import flash.net.registerClassAlias; [Bindable] [RemoteClass(alias = "myLobbyData.LobbyData")] public class LobbyData implements IExternalizable { private var sent:int; // java sentinel private var u:String; // red5 username private var sen:int; // another sentinel? private var ui:int; // fb uid private var fn:String; // fb name private var pic:String; // fb pic private var inb:Boolean; // is in the table? private var t:int; // table number private var s:int; // seat number public function setSent(sent:int):void { this.sent = sent; } public function getSent():int { return sent; } public function setU(u:String):void { this.u = u; } public function getU():String { return u; } public function setSen(sen:int):void { this.sen = sen; } public function getSen():int { return sen; } public function setUi(ui:int):void { this.ui = ui; } public function getUi():int { return ui; } public function setFn(fn:String):void { this.fn = fn; } public function getFn():String { return fn; } public function setPic(pic:String):void { this.pic = pic; } public function getPic():String { return pic; } public function setInb(inb:Boolean):void { this.inb = inb; } public function getInb():Boolean { return inb; } public function setT(t:int):void { this.t = t; } public function getT():int { return t; } public function setS(s:int):void { this.s = s; } public function getS():int { return s; } public function readExternal(input:IDataInput):void { sent = input.readInt(); u = input.readUTF(); sen = input.readInt(); ui = input.readInt(); fn = input.readUTF(); pic = input.readUTF(); inb = input.readBoolean(); t = input.readInt(); s = input.readInt(); } public function writeExternal(output:IDataOutput):void { output.writeInt(sent); output.writeUTF(u); output.writeInt(sen); output.writeInt(ui); output.writeUTF(fn); output.writeUTF(pic); output.writeBoolean(inb); output.writeInt(t); output.writeInt(s); } } Java Object: package myLobbyData; import org.red5.io.amf3.IDataInput; import org.red5.io.amf3.IDataOutput; import org.red5.io.amf3.IExternalizable; public class LobbyData implements IExternalizable { private static final long serialVersionUID = 115280920; private int sent; // java sentinel private String u; // red5 username private int sen; // another sentinel? private int ui; // fb uid private String fn; // fb name private String pic; // fb pic private Boolean inb; // is in the table? private int t; // table number private int s; // seat number public void setSent(int sent) { this.sent = sent; } public int getSent() { return sent; } public void setU(String u) { this.u = u; } public String getU() { return u; } public void setSen(int sen) { this.sen = sen; } public int getSen() { return sen; } public void setUi(int ui) { this.ui = ui; } public int getUi() { return ui; } public void setFn(String fn) { this.fn = fn; } public String getFn() { return fn; } public void setPic(String pic) { this.pic = pic; } public String getPic() { return pic; } public void setInb(Boolean inb) { this.inb = inb; } public Boolean getInb() { return inb; } public void setT(int t) { this.t = t; } public int getT() { return t; } public void setS(int s) { this.s = s; } public int getS() { return s; } @Override public void readExternal(IDataInput input) { sent = input.readInt(); u = input.readUTF(); sen = input.readInt(); ui = input.readInt(); fn = input.readUTF(); pic = input.readUTF(); inb = input.readBoolean(); t = input.readInt(); s = input.readInt(); } @Override public void writeExternal(IDataOutput output) { output.writeInt(sent); output.writeUTF(u); output.writeInt(sen); output.writeInt(ui); output.writeUTF(fn); output.writeUTF(pic); output.writeBoolean(inb); output.writeInt(t); output.writeInt(s); } } AS3 Client: public function refreshRoom(event:Event) { var resp:Responder=new Responder(handleResp,null); ncLobby.call("getLobbyData", resp, null); } public function handleResp(o:Object):void { var testObject:LobbyData=new LobbyData; testObject = o as LobbyData; trace(testObject); } Java Client public LobbyData getLobbyData(String param) { LobbyData lobbyData1 = new LobbyData(); lobbyData1.setSent(5); lobbyData1.setU("lawlcats"); lobbyData1.setSen(5); lobbyData1.setUi(5); lobbyData1.setFn("lulz"); lobbyData1.setPic("lulzagain"); lobbyData1.setInb(true); lobbyData1.setT(5); lobbyData1.setS(5); return lobbyData1; }

    Read the article

  • Android remote service doesn't call service methods

    - by tarantel
    Hello, I'm developing a GPS tracking software on android. I need IPC to control the service from different activities. So I decide to develop a remote service with AIDL. This wasn't a big problem but now it's always running into the methods of the interface and not into those of my service class. Maybe someone could help me? Here my ADIL file: package test.de.android.tracker interface ITrackingServiceRemote { void startTracking(in long trackId); void stopTracking(); void pauseTracking(); void resumeTracking(in long trackId); long trackingState(); } And the here a short version of my service class: public class TrackingService extends Service implements LocationListener{ private LocationManager mLocationManager; private TrackDb db; private long trackId; private boolean isTracking = false; @Override public void onCreate() { super.onCreate(); mNotificationManager = (NotificationManager) this .getSystemService(NOTIFICATION_SERVICE); mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE); db = new TrackDb(this.getApplicationContext()); } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); } @Override public void onDestroy(){ //TODO super.onDestroy(); } @Override public IBinder onBind(Intent intent){ return this.mBinder; } private IBinder mBinder = new ITrackingServiceRemote.Stub() { public void startTracking(long trackId) throws RemoteException { TrackingService.this.startTracking(trackId); } public void pauseTracking() throws RemoteException { TrackingService.this.pauseTracking(); } public void resumeTracking(long trackId) throws RemoteException { TrackingService.this.resumeTracking(trackId); } public void stopTracking() throws RemoteException { TrackingService.this.stopTracking(); } public long trackingState() throws RemoteException { long state = TrackingService.this.trackingState(); return state; } }; public synchronized void startTracking(long trackId) { // request updates every 250 meters or 0 sec this.trackId = trackId; mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 250, this); isTracking = true; } public synchronized long trackingState() { if(isTracking){ return trackId; } else return -1; } public synchronized void stopTracking() { if(isTracking){ mLocationManager.removeUpdates(this); isTracking = false; } else Log.i(TAG, "Could not stop because service is not tracking at the moment"); } public synchronized void resumeTracking(long trackId) { if(!isTracking){ this.trackId = trackId; mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 250, this); isTracking = true; } else Log.i(TAG, "Could not resume because service is tracking already track " + this.trackId); } public synchronized void pauseTracking() { if(isTracking){ mLocationManager.removeUpdates(this); isTracking = false; } else Log.i(TAG, "Could not pause because service is not tracking at the moment"); } public void onLocationChanged(Location location) { //TODO } For easier access from the client I wrote a ServiceManager class which sets up the ServiceConnection and you can call the service methods. Here my code for this: public class TrackingServiceManager{ private static final String TAG = "TrackingServiceManager"; private ITrackingServiceRemote mService = null; private Context mContext; private Boolean isBound = false; private ServiceConnection mServiceConnection; public TrackingServiceManager(Context ctx){ this.mContext = ctx; } public void start(long trackId) { if (isBound && mService != null) { try { mService.startTracking(trackId); } catch (RemoteException e) { Log.e(TAG, "Could not start tracking!",e); } } else Log.i(TAG, "No Service bound! 1"); } public void stop(){ if (isBound && mService != null) { try { mService.stopTracking(); } catch (RemoteException e) { Log.e(TAG, "Could not stop tracking!",e); } } else Log.i(TAG, "No Service bound!"); } public void pause(){ if (isBound && mService != null) { try { mService.pauseTracking(); } catch (RemoteException e) { Log.e(TAG, "Could not pause tracking!",e); } } else Log.i(TAG, "No Service bound!"); } public void resume(long trackId){ if (isBound && mService != null) { try { mService.resumeTracking(trackId); } catch (RemoteException e) { Log.e(TAG, "Could not resume tracking!",e); } } else Log.i(TAG, "No Service bound!"); } public float state(){ if (isBound && mService != null) { try { return mService.trackingState(); } catch (RemoteException e) { Log.e(TAG, "Could not resume tracking!",e); return -1; } } else Log.i(TAG, "No Service bound!"); return -1; } /** * Method for binding the Service with client */ public boolean connectService(){ mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { TrackingServiceManager.this.mService = ITrackingServiceRemote.Stub.asInterface(service); } } @Override public void onServiceDisconnected(ComponentName name) { if (mService != null) { mService = null; } } }; Intent mIntent = new Intent("test.de.android.tracker.action.intent.TrackingService"); this.isBound = this.mContext.bindService(mIntent, mServiceConnection, Context.BIND_AUTO_CREATE); return this.isBound; } public void disconnectService(){ this.mContext.unbindService(mServiceConnection); this.isBound = false; } } If i now try to call a method from an activity for example start(trackId) nothing happens. The binding is OK. When debugging it always runs into the startTracking() in the generated ITrackingServiceRemote.java file and not into my TrackingService class. Where is the problem? I can't find anything wrong. Thanks in advance! Tobias

    Read the article

  • Where should I put zoomIn in my MapActivity?

    - by Johny
    I'm writing an Android app, and I'd like to zoomIn as soon as the map has been loaded. I get the following error: java.lang.IllegalArgumentException: width and height must be > 0 This MapActivity - width and height must be > 0 question suggests the problem is the zoomIn() method is in the onCreate() method. But I get same error when I put it in the onResume() method. I've been searching for hours and I can't find anything about it at http://developer.android.com or anywhere else... Also I can't find a way to get the time point the map has been loaded. A "MapLoadedListener" or something like that... EDIT Here is my code: public class AMap extends MapActivity{ private final String LOG_TAG = this.getClass().getSimpleName(); private Context mContext; private Chronometer timer; private TextView tvCountdown; private RelativeLayout rl; private MapView mapView; private MapController mapController; private List<Overlay> mapOverlays; private PlayersOverlay playersOverlay; private Drawable drawable; private Builder endDialog; private ContextThemeWrapper ctw; private Handler mHandler = new Handler(); private Player player = new Player(); private StartTask startTask; private EndTask endTask; private MyDBAdapter mdba; private Cursor playersCursor; private UpdateBroadcastReceiver r; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.map_view); mContext = AMap.this; // set map mapView = (MapView) findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); mapView.setFocusable(true); // find the relative layout rl = (RelativeLayout) findViewById(R.id.rl); // set the chronometer timer = (Chronometer) findViewById(R.id.tv_timer); timer.setBackgroundColor(Color.DKGRAY); // set the countdown textview tvCountdown = (TextView) findViewById(R.id.tv_countdown); // Open DB connection and get players Cursor mdba = new MyDBAdapter(mContext); mdba.open(); playersCursor = mdba.getGame(); // Get this player's id and location Intent starter = this.getIntent(); player.setId(starter.getIntExtra("id", 0)); player.setLatitude(starter.getDoubleExtra("lat", 0)); player.setLongitude(starter.getDoubleExtra("lon", 0)); // Set this player's location as map's center GeoPoint geoPoint = new GeoPoint((int) (player.getLatitude()*1E6), (int) (player.getLongitude()*1E6)); mapController = mapView.getController(); mapController.setCenter(geoPoint); mapController.setZoom(15); Log.d(LOG_TAG, "My playersCursor has "+playersCursor.getCount()+" rows"); // drawable is needed but not used drawable = this.getResources().getDrawable(R.drawable.ic_launcher); // set PlayersOverlay (locations and statuses) playersOverlay = new PlayersOverlay(player.getId(), playersCursor, drawable, this); mapOverlays = mapView.getOverlays(); mapOverlays.add(playersOverlay); mHandler.postDelayed(mUpdateTimeTask, 100); } private Runnable mUpdateTimeTask = new Runnable() { public void run() { int h = mapView.getLayoutParams().height; int w = mapView.getLayoutParams().width; Log.d(LOG_TAG, "w = "+w+" , h = "+h); mHandler.postAtTime(this, System.currentTimeMillis() + 1000); } }; @Override public void onAttachedToWindow(){ Log.d(LOG_TAG, "Attached to Window"); int h = mapView.getLayoutParams().height; int w = mapView.getLayoutParams().width; Log.d(LOG_TAG, " Attached to window: w = "+w+" , h = "+h); //mapController.zoomInFixing(screenPoint.x, screenPoint.y); } public void onWindowFocusChanged(boolean hasFocus){ Log.d(LOG_TAG, "Focus changed to: "+hasFocus); int h = mapView.getLayoutParams().height; int w = mapView.getLayoutParams().width; Log.d(LOG_TAG, " Window focus changed: w = "+w+" , h = "+h); //mapController.zoomInFixing(screenPoint.x, screenPoint.y); } @Override protected void onStart(){ super.onStart(); // Create and register the broadcast receiver for messages from service IntentFilter filter = new IntentFilter(AppConstants.iGAME_UPDATE); r = new UpdateBroadcastReceiver(); registerReceiver(r, filter); // Create the dialog for end of game ctw = new ContextThemeWrapper(mContext, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen); endDialog = new AlertDialog.Builder(ctw); endDialog.setMessage("End of Game"); endDialog.setCancelable(false); endDialog.setNeutralButton("OK", new OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { Intent highScores = new Intent(AMap.this, HighScores.class); startActivity(highScores); playersCursor.close(); finish(); } }); } @Override protected void onStop() { if(!playersCursor.isClosed()) playersCursor.close(); unregisterReceiver(r); mdba.close(); super.onStop(); } @Override protected boolean isRouteDisplayed() { return false; } // Receives signal from NetworkService that DB has been updated public class UpdateBroadcastReceiver extends BroadcastReceiver { boolean startSignal, update, endSignal; @Override public void onReceive(Context context, Intent intent) { endSignal = intent.getBooleanExtra("endSignal", false); if(endSignal){ Log.d(LOG_TAG, "Game Update BroadcastReceiver received End Signal"); endTask = new EndTask(); endTask.execute(); return; } update = intent.getBooleanExtra("update", false); if(update){ Log.d(LOG_TAG, "Game Update BroadcastReceiver received game update"); playersCursor.requery(); mapView.invalidate(); return; } startSignal = intent.getBooleanExtra("startSignal", false); if(startSignal){ Log.d(LOG_TAG, "Game Update BroadcastReceiver received Start Signal"); startTask = new StartTask(); startTask.execute(); return; } } } class StartTask extends AsyncTask<Void,Integer,Void>{ private final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100); private final long DELAY = 1200; @Override protected Void doInBackground(Void... params) { int i = 3; while(i>=0){ publishProgress(i); try { Thread.sleep(DELAY); } catch (InterruptedException e) { e.printStackTrace(); } i--; } return null; } @Override protected void onProgressUpdate(Integer... progress){ tg.startTone(ToneGenerator.TONE_PROP_PROMPT); tvCountdown.setText(""+progress[0]); } @Override protected void onPostExecute(Void result) { rl.removeView(tvCountdown); timer.setBase(SystemClock.elapsedRealtime()); timer.start(); //enable screen touches playersOverlay.setGameStarted(true); } } class EndTask extends AsyncTask<Void,Void,Void>{ @Override protected void onPreExecute(){ //disable screen touches playersOverlay.setEndOfGame(true); timer.stop(); } @Override protected Void doInBackground(Void... params) { return null; } @Override protected void onPostExecute(Void result) { try{ endDialog.show(); }catch(Exception e){ Toast.makeText(mContext, "End of game", Toast.LENGTH_LONG); Intent highScores = new Intent(AMap.this, HighScores.class); startActivity(highScores); playersCursor.close(); finish(); } mHandler.removeCallbacks(mUpdateTimeTask); } } }

    Read the article

  • Intent and OnActivityResult causing Activity to get restart Actuomatically : Require to solve this issues

    - by Parth Dani
    i am having 20 imageview and i am having 20 button for them when i click any 1 button it gives me option to select image from gallery or camera when i select any option for example galley it will take me to the gallery and let me select image from their and let me display those images on my imageview for respective button now the problem is sometimes when i do the whole above process my activity is getting restart actuomatically and all the image which were first selected get vanished from their imageview For Refernce my code is as follow: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.new_upload); // **************Code to get Road worthy number and VIN number value in // Shared Preference starts here************************ SharedPreferences myPrefs1 = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE); roadworthynumber = myPrefs1.getString(MY_ROADWORTHY, "Road Worthy Number"); vinnumber = myPrefs1.getString(MY_VIN, "VIN Number"); // **************Code to get Road worthy number and VIN number value in // Shared Preference ends here************************ // **************Code to create Directory AUSRWC starts // here************************ if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { cacheDir = new File(Environment.getExternalStorageDirectory() + File.separator + "AUSRWC" + File.separator); cacheDir.mkdirs(); } // **************Code to Create Directory AUSRWC ends // here************************ // *****************Assigning Button variable their Id declare in XML // file starts here***************** new_select1 = (Button) findViewById(R.id.new_select1); new_select2 = (Button) findViewById(R.id.new_select2); new_select3 = (Button) findViewById(R.id.new_select3); new_select4 = (Button) findViewById(R.id.new_select4); new_select5 = (Button) findViewById(R.id.new_select5); new_select6 = (Button) findViewById(R.id.new_select6); new_select7 = (Button) findViewById(R.id.new_select7); new_select8 = (Button) findViewById(R.id.new_select8); new_select9 = (Button) findViewById(R.id.new_select9); new_select10 = (Button) findViewById(R.id.new_select10); new_select11 = (Button) findViewById(R.id.new_select11); new_select12 = (Button) findViewById(R.id.new_select12); new_select13 = (Button) findViewById(R.id.new_select13); new_select14 = (Button) findViewById(R.id.new_select14); new_select15 = (Button) findViewById(R.id.new_select15); new_select16 = (Button) findViewById(R.id.new_select16); new_select17 = (Button) findViewById(R.id.new_select17); new_select18 = (Button) findViewById(R.id.new_select18); new_select19 = (Button) findViewById(R.id.new_select19); new_select20 = (Button) findViewById(R.id.new_select20); // *****************Assigning Button variable their Id declare in XML // file ends here***************** // *****************Assigning Image variable their Id declare in XML // file starts here***************** new_selectimage1 = (ImageView) findViewById(R.id.new_selectImage1); new_selectimage2 = (ImageView) findViewById(R.id.new_selectImage2); new_selectimage3 = (ImageView) findViewById(R.id.new_selectImage3); new_selectimage4 = (ImageView) findViewById(R.id.new_selectImage4); new_selectimage5 = (ImageView) findViewById(R.id.new_selectImage5); new_selectimage6 = (ImageView) findViewById(R.id.new_selectImage6); new_selectimage7 = (ImageView) findViewById(R.id.new_selectImage7); new_selectimage8 = (ImageView) findViewById(R.id.new_selectImage8); new_selectimage9 = (ImageView) findViewById(R.id.new_selectImage9); new_selectimage10 = (ImageView) findViewById(R.id.new_selectImage10); new_selectimage11 = (ImageView) findViewById(R.id.new_selectImage11); new_selectimage12 = (ImageView) findViewById(R.id.new_selectImage12); new_selectimage13 = (ImageView) findViewById(R.id.new_selectImage13); new_selectimage14 = (ImageView) findViewById(R.id.new_selectImage14); new_selectimage15 = (ImageView) findViewById(R.id.new_selectImage15); new_selectimage16 = (ImageView) findViewById(R.id.new_selectImage16); new_selectimage17 = (ImageView) findViewById(R.id.new_selectImage17); new_selectimage18 = (ImageView) findViewById(R.id.new_selectImage18); new_selectimage19 = (ImageView) findViewById(R.id.new_selectImage19); new_selectimage20 = (ImageView) findViewById(R.id.new_selectImage20); // ****Assigning Image variable their Id declare in XML file ends // here***************** // **************Creating Dialog to give option to user to new_select // image from gallery or from camera starts here**************** final String[] items = new String[] { "From Camera", "From Gallery" }; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, items); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("select Image"); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0) { if (android.os.Environment.getExternalStorageState() .equals(android.os.Environment.MEDIA_MOUNTED)) { Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE); File file = new File(Environment .getExternalStorageDirectory(), "/AUSRWC/picture" + ".jpg"); mImageCaptureUri = Uri.fromFile(file); try { Toast.makeText(getBaseContext(), "Click Image", Toast.LENGTH_SHORT).show(); intent.putExtra( android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri); intent.putExtra("return-data", true); startActivityForResult(intent, PICK_FROM_CAMERA); } catch (Exception e) { e.printStackTrace(); } } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } dialog.cancel(); } else { Intent intent = new Intent(); Toast.makeText(getBaseContext(), "Select Image", Toast.LENGTH_SHORT).show(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE); } } }); dialog = builder.create(); // **************Creating Dialog to give option to user to new_select // image from gallery or from camera ends here**************** final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.anim_alpha); // Animation Code for displaying Button // Clicked. // ********************Image 1 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 1; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 1 button code ends // here******************************* // ********************Image 2 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 2; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 2 button code ends // here******************************* // ********************Image 3 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select3.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 3; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 3 button code ends // here******************************* // ********************Image 4 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select4.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 4; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 4 button code ends // here******************************* // ********************Image 5 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select5.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 5; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 5 button code ends // here******************************* // ********************Image 6 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select6.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 6; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 6 button code ends // here******************************* // ********************Image 7 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select7.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 7; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 7 button code ends // here******************************* // ********************Image 8 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select8.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 8; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 8 button code ends // here******************************* // ********************Image 9 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select9.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 9; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 9 button code ends // here******************************* // ********************Image 10 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select10.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 10; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 10 button code ends // here******************************* // ********************Image 11 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select11.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 11; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 11 button code ends // here******************************* // ********************Image 12 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select12.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 12; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 12 button code ends // here******************************* // ********************Image 13 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select13.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 13; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 13 button code ends // here******************************* // ********************Image 14 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select14.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 14; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 14 button code ends // here******************************* // ********************Image 15 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select15.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 15; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 15 button code ends // here******************************* // ********************Image 16 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select16.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 16; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 16 button code ends // here******************************* // ********************Image 17 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select17.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 17; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 17 button code ends // here******************************* // ********************Image 18 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select18.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 18; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 18 button code ends // here******************************* // ********************Image 19 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select19.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 19; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 19 button code ends // here******************************* // ********************Image 20 button code starts // here******************************* if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { new_select20.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animAlpha); buttonpressed = 20; dialog.show(); } }); } else { Toast.makeText(getBaseContext(), "Please insert SdCard First", Toast.LENGTH_SHORT).show(); } // ********************Image 20 button code ends // here******************************* } // *************************When Back Button is Pressed code begins // here************************************* @Override public void onBackPressed() { Toast.makeText(new_upload.this, "Sorry You are not allowed to go back", Toast.LENGTH_SHORT).show(); return; } // *************************When Back Button is Pressed code ends // here************************************* // ***********************To get Path of new_selected Image code starts // here************************************ public String getRealPathFromURI(Uri contentUri) { String[] proj = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(contentUri, proj, null, null, null); if (cursor == null) return null; int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } // ***********************To get Path of new_selected Image code ends // here************************************ // **********************Picture obtained from the camera or from gallery // code starts here************** @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { //path = ""; Log.e("","requestCode="+requestCode); switch (requestCode){ case PICK_FROM_FILE: if (resultCode == Activity.RESULT_OK) { mImageCaptureUri = data.getData(); path = getRealPathFromURI(mImageCaptureUri); // from Gallery Log.e("", "Imagepath from gallery=" + path); if (path == null) path = mImageCaptureUri.getPath(); // from File Manager if (path != null) { dialog1 = ProgressDialog.show(new_upload.this, "", "Processing Please wait...", true); new ImageDisplayTask().execute(); } } break; case PICK_FROM_CAMERA: if (resultCode == Activity.RESULT_OK) { try { path = mImageCaptureUri.getPath(); Log.e("", "Imagepath from Camera =" + path); // bitmap = BitmapFactory.decodeFile(path); } catch (Exception e) { e.printStackTrace(); } if (path != null) { dialog1 = ProgressDialog.show(new_upload.this, "", "Processing Please wait...", true); //new ImageDisplayTask1().execute(); new ImageDisplayTask().execute(); } } break; default: } } // ********************Picture obtained from the camera or from gallery code // ends here********************************************* // ******************Image Display on Button when new_selected from gallery // Ashynch Code starts here******************************** class ImageDisplayTask extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... unsued) { Bitmap src = BitmapFactory.decodeFile(path); Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888); //Bitmap dest = Bitmap.createScaledBitmap(src, src.getWidth(),src.getHeight(), true); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); String dateTime = sdf.format(Calendar.getInstance().getTime()); // reading local `` String timestamp = dateTime + " " + roadworthynumber; SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); String dateTime1 = sdf1.format(Calendar.getInstance().getTime()); Imagename = dateTime1.toString().trim().replaceAll(":", "") .replaceAll("-", "").replaceAll(" ", "") + roadworthynumber + ".jpg"; Canvas cs = new Canvas(dest); Paint tPaint = new Paint(); tPaint.setTextSize(100); tPaint.setTypeface(Typeface.SERIF); tPaint.setColor(Color.RED); tPaint.setStyle(Style.FILL); cs.drawBitmap(src, 0f, 0f, null); float height = tPaint.measureText("yY"); cs.drawText(timestamp, 5f, src.getHeight() - height + 5f, tPaint); try { dest.compress(Bitmap.CompressFormat.JPEG, 70, new FileOutputStream(new File(cacheDir, Imagename))); dest.recycle(); src.recycle(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onProgressUpdate(Void... unsued) { } @Override protected void onPostExecute(String serverresponse) { String error = "noerror"; Display currentDisplay = getWindowManager().getDefaultDisplay(); int dw = currentDisplay.getWidth(); int dh = currentDisplay.getHeight() - 100; Log.e("", "width= " + dw + " Height= " + dh); try { BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options(); bmpFactoryOptions.inJustDecodeBounds = true; Bitmap bmp = BitmapFactory.decodeFile( Environment.getExternalStorageDirectory() + "/AUSRWC/" + Imagename, bmpFactoryOptions); int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) dh); int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) dw); if (heightRatio > 1 && widthRatio > 1) { if (heightRatio > widthRatio) { bmpFactoryOptions.inSampleSize = heightRatio; } else { bmpFactoryOptions.inSampleSize = widthRatio; } } bmpFactoryOptions.inJustDecodeBounds = false; bmp = BitmapFactory.decodeFile( Environment.getExternalStorageDirectory() + "/AUSRWC/" + Imagename, bmpFactoryOptions); if (buttonpressed == 1) { new_selectimage1.setImageBitmap(bmp); //Image set on ImageView } else if (buttonpressed == 2) { new_selectimage2.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 3) { new_selectimage3.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 4) { new_selectimage4.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 5) { new_selectimage5.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 6) { new_selectimage6.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 7) { new_selectimage7.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 8) { new_selectimage8.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 9) { new_selectimage9.setImageBitmap(bmp);//Image set on ImageView } else if (buttonpressed == 10) { new_selectimage10.setImageBitmap(bmp); } else if (buttonpressed == 11) { new_selectimage11.setImageBitmap(bmp); } else if (buttonpressed == 12) { new_selectimage12.setImageBitmap(bmp); } else if (buttonpressed == 13) { new_selectimage13.setImageBitmap(bmp); } else if (buttonpressed == 14) { new_selectimage14.setImageBitmap(bmp); } else if (buttonpressed == 15) { new_selectimage15.setImageBitmap(bmp); } else if (buttonpressed == 16) { new_selectimage16.setImageBitmap(bmp); } else if (buttonpressed == 17) { new_selectimage17.setImageBitmap(bmp); } else if (buttonpressed == 18) { new_selectimage18.setImageBitmap(bmp); } else if (buttonpressed == 19) { new_selectimage19.setImageBitmap(bmp); } else if (buttonpressed == 20) { new_selectimage20.setImageBitmap(bmp); } } catch (Exc

    Read the article

  • Is this proper OO design for C++?

    - by user121917
    I recently took a software processes course and this is my first time attempting OO design on my own. I am trying to follow OO design principles and C++ conventions. I attempted and gave up on MVC for this application, but I am trying to "decouple" my classes such that they can be easily unit-tested and so that I can easily change the GUI library used and/or the target OS. At this time, I have finished designing classes but have not yet started implementing methods. The function of the software is to log all packets sent and received, and display them on the screen (like WireShark, but for one local process only). The software accomplishes this by hooking the send() and recv() functions in winsock32.dll, or some other pair of analogous functions depending on what the intended Target is. The hooks add packets to SendPacketList/RecvPacketList. The GuiLogic class starts a thread which checks for new packets. When new packets are found, it utilizes the PacketFilter class to determine the formatting for the new packet, and then sends it to MainWindow, a native win32 window (with intent to later port to Qt).1 Full size image of UML class diagram Here are my classes in skeleton/header form (this is my actual code): class PacketModel { protected: std::vector<byte> data; int id; public: PacketModel(); PacketModel(byte* data, unsigned int size); PacketModel(int id, byte* data, unsigned int size); int GetLen(); bool IsValid(); //len >= sizeof(opcode_t) opcode_t GetOpcode(); byte* GetData(); //returns &(data[0]) bool GetData(byte* outdata, int maxlen); void SetData(byte* pdata, int len); int GetId(); void SetId(int id); bool ParseData(char* instr); bool StringRepr(char* outstr); byte& operator[] (const int index); }; class SendPacket : public PacketModel { protected: byte* returnAddy; public: byte* GetReturnAddy(); void SetReturnAddy(byte* addy); }; class RecvPacket : public PacketModel { protected: byte* callAddy; public: byte* GetCallAddy(); void SetCallAddy(byte* addy); }; //problem: packets may be added to list at any time by any number of threads //solution: critical section associated with each packet list class Synch { public: void Enter(); void Leave(); }; template<class PacketType> class PacketList { private: static const int MAX_STORED_PACKETS = 1000; public: static const int DEFAULT_SHOWN_PACKETS = 100; private: vector<PacketType> list; Synch synch; //wrapper for critical section public: void AddPacket(PacketType* packet); PacketType* GetPacket(int id); int TotalPackets(); }; class SendPacketList : PacketList<SendPacket> { }; class RecvPacketList : PacketList<RecvPacket> { }; class Target //one socket { bool Send(SendPacket* packet); bool Inject(RecvPacket* packet); bool InitSendHook(SendPacketList* sendList); bool InitRecvHook(RecvPacketList* recvList); }; class FilterModel { private: opcode_t opcode; int colorID; bool bFilter; char name[41]; }; class FilterFile { private: FilterModel filter; public: void Save(); void Load(); FilterModel* GetFilter(opcode_t opcode); }; class PacketFilter { private: FilterFile filters; public: bool IsFiltered(opcode_t opcode); bool GetName(opcode_t opcode, char* namestr); //return false if name does not exist COLORREF GetColor(opcode_t opcode); //return default color if no custom color }; class GuiLogic { private: SendPacketList sendList; RecvPacketList recvList; PacketFilter packetFilter; void GetPacketRepr(PacketModel* packet); void ReadNew(); void AddToWindow(); public: void Refresh(); //called from thread void GetPacketInfo(int id); //called from MainWindow }; I'm looking for a general review of my OO design, use of UML, and use of C++ features. I especially just want to know if I'm doing anything considerably wrong. From what I've read, design review is on-topic for this site (and off-topic for the Code Review site). Any sort of feedback is greatly appreciated. Thanks for reading this.

    Read the article

  • Which Activator.CreateInstance overload function to call?

    - by user299990
    Which Activator.CreateInstance overload function to call? I have a type returned from "Type proxyType = GetProxyType(contractType);" and the constructorinfo is "[System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext)} base {System.Reflection.MemberInfo} = {Void .ctor(System.ServiceModel.InstanceContext)} [System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext, System.String)} base {System.Reflection.MethodBase} = {Void .ctor(System.ServiceModel.InstanceContext, System.String)} [System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext, System.String, System.String)} base {System.Reflection.MethodBase} = {Void .ctor(System.ServiceModel.InstanceContext, System.String, System.String)} [System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext, System.String, System.ServiceModel.EndpointAddress)} base {System.Reflection.MethodBase} = {Void .ctor(System.ServiceModel.InstanceContext, System.String, System.ServiceModel.EndpointAddress)} [System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext, System.ServiceModel.Channels.Binding, System.ServiceModel.EndpointAddress)} base {System.Reflection.MethodBase} = {Void .ctor(System.ServiceModel.InstanceContext, System.ServiceModel.Channels.Binding, System.ServiceModel.EndpointAddress)}. Thanks!!

    Read the article

  • OpenGL error LNK2019

    - by Ghilliedrone
    I'm trying to compile a basic OpenGL program. I linked opengl32.lib and glu32.lib but I'm getting errors. The errors I get are: error LNK1120: 7 unresolved externals error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup error LNK2019: unresolved external symbol "public: float __thiscall GLWindow::getElapsedSeconds(void)" (?getElapsedSeconds@GLWindow@@QAEMXZ) referenced in function _WinMain@16 error LNK2019: unresolved external symbol "public: bool __thiscall GLWindow::isRunning(void)" (?isRunning@GLWindow@@QAE_NXZ) referenced in function _WinMain@16 error LNK2019: unresolved external symbol "public: void __thiscall GLWindow::attachExample(class Example *)" (?attachExample@GLWindow@@QAEXPAVExample@@@Z) referenced in function _WinMain@16 error LNK2019: unresolved external symbol "public: void __thiscall GLWindow::destroy(void)" (?destroy@GLWindow@@QAEXXZ) referenced in function _WinMain@16 error LNK2019: unresolved external symbol "public: __thiscall GLWindow::GLWindow(struct HINSTANCE__ *)" (??0GLWindow@@QAE@PAUHINSTANCE__@@@Z) referenced in function _WinMain@16 error LNK2019: unresolved external symbol "private: void __thiscall GLWindow::setupPixelFormat(void)" (?setupPixelFormat@GLWindow@@AAEXXZ) referenced in function "public: long __stdcall GLWindow::WndProc(struct HWND__ *,unsigned int,unsigned int,long)" (?WndProc@GLWindow@@QAGJPAUHWND__@@IIJ@Z)

    Read the article

  • MacPorts 1.8.2 fails to build db46 on Mac OS X 1.6.3

    - by themoch
    I'm trying to put a development environment on my Mac, and to do so I need to install several packages which require db46. When running sudo port install db46 I get the following error: ---> Computing dependencies for db46 ---> Fetching db46 ---> Attempting to fetch patch.4.6.21.1 from http://www.oracle.com/technology/products/berkeley-db/db/update/4.6.21/ ---> Attempting to fetch patch.4.6.21.2 from http://www.oracle.com/technology/products/berkeley-db/db/update/4.6.21/ ---> Attempting to fetch patch.4.6.21.3 from http://www.oracle.com/technology/products/berkeley-db/db/update/4.6.21/ ---> Attempting to fetch patch.4.6.21.4 from http://www.oracle.com/technology/products/berkeley-db/db/update/4.6.21/ ---> Attempting to fetch db-4.6.21.tar.gz from http://distfiles.macports.org/db4/4.6.21_6 ---> Verifying checksum(s) for db46 ---> Extracting db46 ---> Applying patches to db46 ---> Configuring db46 ---> Building db46 Error: Target org.macports.build returned: shell command " cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_databases_db46/work/db-4.6.21/build_unix" && /usr/bin/make -j2 all " returned error 2 Command output: ../dist/../libdb_java/db_java_wrap.c:9464: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9487: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jlong' ../dist/../libdb_java/db_java_wrap.c:9509: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9532: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jlong' ../dist/../libdb_java/db_java_wrap.c:9563: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jint' ../dist/../libdb_java/db_java_wrap.c:9588: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jlong' ../dist/../libdb_java/db_java_wrap.c:9613: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jint' ../dist/../libdb_java/db_java_wrap.c:9638: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9666: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jlong' ../dist/../libdb_java/db_java_wrap.c:9691: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jlong' ../dist/../libdb_java/db_java_wrap.c:9716: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9739: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9771: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9796: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9819: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9842: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9867: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jobject' ../dist/../libdb_java/db_java_wrap.c:9899: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9920: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9943: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9966: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jstring' ../dist/../libdb_java/db_java_wrap.c:9991: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jint' ../dist/../libdb_java/db_java_wrap.c:10010: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:10046: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:10071: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' make: *** [db_java_wrap.lo] Error 1 make: *** Waiting for unfinished jobs.... Note: Some input files use unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. cd ./classes && jar cf ../db.jar ./com/sleepycat Error: Status 1 encountered during processing. I have removed my /usr/local folder completely and it does not seem to help.

    Read the article

  • Macports 1.8.2 fails to build db46 on os x 1.6.3

    - by themoch
    i'm trying to put a dev environment on my mac, and to do so i need to install several packages which require db46 when running sudo port install db46 i get the following error: ---> Computing dependencies for db46 ---> Fetching db46 ---> Attempting to fetch patch.4.6.21.1 from http://www.oracle.com/technology/products/berkeley-db/db/update/4.6.21/ ---> Attempting to fetch patch.4.6.21.2 from http://www.oracle.com/technology/products/berkeley-db/db/update/4.6.21/ ---> Attempting to fetch patch.4.6.21.3 from http://www.oracle.com/technology/products/berkeley-db/db/update/4.6.21/ ---> Attempting to fetch patch.4.6.21.4 from http://www.oracle.com/technology/products/berkeley-db/db/update/4.6.21/ ---> Attempting to fetch db-4.6.21.tar.gz from http://distfiles.macports.org/db4/4.6.21_6 ---> Verifying checksum(s) for db46 ---> Extracting db46 ---> Applying patches to db46 ---> Configuring db46 ---> Building db46 Error: Target org.macports.build returned: shell command " cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_databases_db46/work/db-4.6.21/build_unix" && /usr/bin/make -j2 all " returned error 2 Command output: ../dist/../libdb_java/db_java_wrap.c:9464: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9487: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jlong' ../dist/../libdb_java/db_java_wrap.c:9509: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9532: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jlong' ../dist/../libdb_java/db_java_wrap.c:9563: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jint' ../dist/../libdb_java/db_java_wrap.c:9588: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jlong' ../dist/../libdb_java/db_java_wrap.c:9613: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jint' ../dist/../libdb_java/db_java_wrap.c:9638: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9666: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jlong' ../dist/../libdb_java/db_java_wrap.c:9691: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jlong' ../dist/../libdb_java/db_java_wrap.c:9716: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9739: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9771: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9796: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9819: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9842: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9867: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jobject' ../dist/../libdb_java/db_java_wrap.c:9899: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9920: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9943: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:9966: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jstring' ../dist/../libdb_java/db_java_wrap.c:9991: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'jint' ../dist/../libdb_java/db_java_wrap.c:10010: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:10046: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' ../dist/../libdb_java/db_java_wrap.c:10071: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'void' make: *** [db_java_wrap.lo] Error 1 make: *** Waiting for unfinished jobs.... Note: Some input files use unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. cd ./classes && jar cf ../db.jar ./com/sleepycat Error: Status 1 encountered during processing. i have removed my /usr/local folder completely and it does not seem to help

    Read the article

  • Android App crashing on Back Button (performResumeActivity)

    - by Rutger
    My App consists of 2 Activities at the moment. . the MAIN activity with a Gallery View . a FriendsListActivity with a ListView When the user moves away from the FriendsListActivity with the back button, and returns to the MAIN activity the following error keeps popping up in debug mode. DalvikVM[localhost:8676] Thread [<1 main] (Suspended (exception RuntimeException)) ActivityThread.performResumeActivity(IBinder, boolean) line: 2095 ActivityThread.handleResumeActivity(IBinder, boolean, boolean) line: 2110 BinderProxy(ActivityThread$H).handleMessage(Message) line: 954 ActivityThread$H(Handler).dispatchMessage(Message) line: 99 Looper.loop() line: 123 ActivityThread.main(String[]) line: 3647 Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method] Method.invoke(Object, Object...) line: 507 ZygoteInit$MethodAndArgsCaller.run() line: 839 ZygoteInit.main(String[]) line: 597 NativeStart.main(String[]) line: not available [native method] Thread [<8 Binder Thread #2] (Running) Thread [<7 Binder Thread #1] (Running) With the LogCat 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): FATAL EXCEPTION: main 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): java.lang.RuntimeException: Unable to resume activity {com.package.MAIN/com.package.MAIN.MAIN}: java.lang.NullPointerException 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2095) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2110) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:954) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.os.Handler.dispatchMessage(Handler.java:99) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.os.Looper.loop(Looper.java:123) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.ActivityThread.main(ActivityThread.java:3647) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at java.lang.reflect.Method.invokeNative(Native Method) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at java.lang.reflect.Method.invoke(Method.java:507) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at dalvik.system.NativeStart.main(Native Method) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): Caused by: java.lang.NullPointerException 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at com.package.MAIN.MAIN.onResume(MAIN.java:91) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1149) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.Activity.performResume(Activity.java:3833) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2085) 03-13 22:01:10.972: ERROR/AndroidRuntime(1038): ... 10 more Further info in the Variables panel states: this: ActivityThread e: NullPointerException cause: NullPointerException detailMessage: null stackTrace: null r: ActivityThread$ActivityClientRecord activity: MAIN detailMessage after one Eclipse Resume: Unable to resume activity (MAIN) The code from the FriendsListActivity looks like this public class FriendsListActivity extends ListActivity { // =========================================================== // Fields // =========================================================== private ArrayList<Friend> friends = new ArrayList<Friend>(); private FriendsArrayAdapter friendsArrayAdapter; private ListView listView; // =========================================================== // onCreate // =========================================================== @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.friends_list); registerForContextMenu(getListView()); setButtonNewFriendClickListener(); } public void generateFriendsList() { FriendsService fs = new FriendsService(this); friends = fs.getFriendsList(); listView = (ListView) findViewById(android.R.id.list); friendsArrayAdapter = new FriendsArrayAdapter( this, R.layout.friend_list_item, friends); listView.setAdapter(friendsArrayAdapter); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.friends_context_menu, menu); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); FriendsService fs = new FriendsService(this); Friend f = new Friend(); f = friends.get(info.position); switch (item.getItemId()) { case R.id.edit: Intent i = new Intent(this, FriendEditActivity.class); i.putExtra("userid", f.userId); startActivity(i); return true; case R.id.delete: fs.deleteFriend(f.userId); generateFriendsList(); return true; default: return super.onContextItemSelected(item); } } // =========================================================== // onPause // =========================================================== protected void onPause() { super.onPause(); finish(); } // =========================================================== // onResume // =========================================================== protected void onResume() { super.onResume(); generateFriendsList(); } // =========================================================== // onStop // =========================================================== protected void onStop() { super.onStop(); } // =========================================================== // onDestroy // =========================================================== @Override protected void onDestroy() { super.onDestroy(); } // =========================================================== // Activity methods // =========================================================== private void setButtonNewFriendClickListener() { Button clickButton = (Button)findViewById(R.id.button_add_friend); clickButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(v.getContext(), FriendNewActivity.class); startActivity(i); } }); } The AndroidManifest looks like this <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.package.mypackage"> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name="com.package.mypackage.mypackage" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".FriendsListActivity"></activity> <activity android:name=".FriendEditActivity"></activity> <activity android:name=".FriendNewActivity"></activity> <activity android:name=".TakePictureActivity"></activity> <activity android:name=".FriendsService"></activity> <activity android:name=".MyService"></activity> </application> <uses-sdk android:minSdkVersion="9" /> The MAIN activity looks like this: package com.package.mypackage; import java.util.ArrayList; import com.package.domain.Domain; import com.package.service.MyService; import com.package.viewadapter.myImageAdapter; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.Button; import android.widget.Gallery; import android.widget.Toast; public class myActivity extends Activity { // =========================================================== // Fields // =========================================================== private MyImageAdapter myImageAdapter; private ArrayList<Domain> domain = new ArrayList<Domain>(); // =========================================================== // onCreate // =========================================================== @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); /* Set Buttons to listen for any click event. */ setButtonFriendsClickListener(); setButtonCameraClickListener(); setButtonPreferencesClickListener(); } // =========================================================== // onStart // =========================================================== @Override public void onStart() { super.onStart(); /* Find the gallery defined in the main.xml */ Gallery g = (Gallery) findViewById(R.id.gallery); /* Show a Toast message when image is clicked */ g.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { MyImageAdapter image_ID = new MyImageAdapter(myActivity.this, position, null); if (image_ID.getItemId(position) == 0) { Toast test_toast = Toast.makeText(myActivity.this, "This is the New Image click", Toast.LENGTH_SHORT); test_toast.show(); } else { Toast test_toast = Toast.makeText(myActivity.this, "The clicked image has image number " + image_ID.getItemId(position) + " in the imageadapter.", Toast.LENGTH_SHORT); test_toast.show(); } } }); g.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) { MyImageAdapter image_ID = new MyImageAdapter(myActivity.this, position, null); Toast test_toast = Toast.makeText(myActivity.this, "The long clicked image has image number " + image_ID.getItemId(position) + " in the imageadapter.", Toast.LENGTH_SHORT); test_toast.show(); return true; } }); } // =========================================================== // onPause // =========================================================== protected void onPause() { super.onPause(); } // =========================================================== // onResume // =========================================================== protected void onResume() { super.onResume(); generateMyGallery(); } // =========================================================== // onStop // =========================================================== protected void onStop() { super.onStop(); } // =========================================================== // onDestroy // Is also called when user changes from horizontal // to vertical orientation and back // =========================================================== @Override protected void onDestroy() { super.onDestroy(); } // =========================================================== // Save and Restore UI states // =========================================================== @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); } protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } // =========================================================== // Main Activity methods // =========================================================== public void generateMyGallery() { MyService cs = new MyService(this); domain = cs.getDomainList(); // Add the new_image drawable to the ArrayList Domain d = new Domain(); d.photoLocation = "drawable"; d.photoName = "new_image"; d.extra1 = "no_text"; d.extra2 = "no_text"; domain.add(0, d); myImageAdapter = new MyImageAdapter(this, R.layout.text_overlay_image_view, domain); /* Find the gallery defined in the main.xml */ Gallery g = (Gallery) findViewById(R.id.gallery); g.setSpacing(10); /* Apply a new (custom) ImageAdapter to it. */ g.setAdapter(myImageAdapter); g.setSelection(1); } private void setButtonFriendsClickListener() { Button clickButton = (Button)findViewById(R.id.button_friends_list); clickButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { setContentView(R.layout.friends_list); Intent myIntent = new Intent(v.getContext(), FriendsListActivity.class); startActivity(myIntent); } }); } private void setButtonCameraClickListener() { Button clickButton = (Button)findViewById(R.id.button_take_picture); clickButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { setContentView(R.layout.take_picture); Intent myIntent = new Intent(v.getContext(), TakePictureActivity.class); startActivity(myIntent); } }); } private void setButtonPreferencesClickListener() { Button clickButton = (Button)findViewById(R.id.button_preferences); clickButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent myIntent = new Intent(v.getContext(), MyPreferencesActivity.class); startActivity(myIntent); } }); } }; Anyone has an idea why the App crashes. Any help is much appreciated. I did find out that, when I finish() the MAIN activity when I start the FriendListActivity and restart the MAIN activity when closing the FriendListActivity, that the crash does not occur. However, this basically restarts the App and that is not the intention. Thanks all, I got the problem solved. This is what I did. . When moving all gallery related actions to the onCreate, the creash didn't happen anymore. But then after returning to the MAIN activity, the activity wasn't shown. . I then moved all the onCreate (except the super), the generateGallery, and the onStart() to the onResume. Now it works fine!

    Read the article

  • socket operation on nonsocket or bad file descriptor

    - by Magn3s1um
    I'm writing a pthread server which takes requests from clients and sends them back a bunch of .ppm files. Everything seems to go well, but sometimes when I have just 1 client connected, when trying to read from the file descriptor (for the file), it says Bad file Descriptor. This doesn't make sense, since my int fd isn't -1, and the file most certainly exists. Other times, I get this "Socket operation on nonsocket" error. This is weird because other times, it doesn't give me this error and everything works fine. When trying to connect multiple clients, for some reason, it will only send correctly to one, and then the other client gets the bad file descriptor or "nonsocket" error, even though both threads are processing the same messages and do the same routines. Anyone have an idea why? Here's the code that is giving me that error: while(mqueue.head != mqueue.tail && count < dis_m){ printf("Sending to client %s: %s\n", pointer->id, pointer->message); int fd; fd = open(pointer->message, O_RDONLY); char buf[58368]; int bytesRead; printf("This is fd %d\n", fd); bytesRead=read(fd,buf,58368); send(pointer->socket,buf,bytesRead,0); perror("Error:\n"); fflush(stdout); close(fd); mqueue.mcount--; mqueue.head = mqueue.head->next; free(pointer->message); free(pointer); pointer = mqueue.head; count++; } printf("Sending %s\n", pointer->message); int fd; fd = open(pointer->message, O_RDONLY); printf("This is fd %d\n", fd); printf("I am hhere2\n"); char buf[58368]; int bytesRead; bytesRead=read(fd,buf,58368); send(pointer->socket,buf,bytesRead,0); perror("Error:\n"); close(fd); mqueue.mcount--; if(mqueue.head != mqueue.tail){ mqueue.head = mqueue.head->next; } else{ mqueue.head->next = malloc(sizeof(struct message)); mqueue.head = mqueue.head->next; mqueue.head->next = malloc(sizeof(struct message)); mqueue.tail = mqueue.head->next; mqueue.head->message = NULL; } free(pointer->message); free(pointer); pthread_mutex_unlock(&numm); pthread_mutex_unlock(&circ); pthread_mutex_unlock(&slots); The messages for both threads are the same, being of the form ./path/imageXX.ppm where XX is the number that should go to the client. The file size of each image is 58368 bytes. Sometimes, this code hangs on the read, and stops execution. I don't know this would be either, because the file descriptor comes back as valid. Thanks in advanced. Edit: Here's some sample output: Sending to client a: ./support/images/sw90.ppm This is fd 4 Error: : Socket operation on non-socket Sending to client a: ./support/images/sw91.ppm This is fd 4 Error: : Socket operation on non-socket Sending ./support/images/sw92.ppm This is fd 4 I am hhere2 Error: : Socket operation on non-socket My dispatcher has defeated evil Sample with 2 clients (client b was serviced first) Sending to client b: ./support/images/sw87.ppm This is fd 6 Error: : Success Sending to client b: ./support/images/sw88.ppm This is fd 6 Error: : Success Sending to client b: ./support/images/sw89.ppm This is fd 6 Error: : Success This is fd 6 Error: : Bad file descriptor Sending to client a: ./support/images/sw85.ppm This is fd 6 Error: As you can see, who ever is serviced first in this instance can open the files, but not the 2nd person. Edit2: Full code. Sorry, its pretty long and terribly formatted. #include <netinet/in.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <errno.h> #include <stdio.h> #include <unistd.h> #include <pthread.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "ring.h" /* Version 1 Here is what is implemented so far: The threads are created from the arguments specified (number of threads that is) The server will lock and update variables based on how many clients are in the system and such. The socket that is opened when a new client connects, must be passed to the threads. To do this, we need some sort of global array. I did this by specifying an int client and main_pool_busy, and two pointers poolsockets and nonpoolsockets. My thinking on this was that when a new client enters the system, the server thread increments the variable client. When a thread is finished with this client (after it sends it the data), the thread will decrement client and close the socket. HTTP servers act this way sometimes (they terminate the socket as soon as one transmission is sent). *Note down at bottom After the server portion increments the client counter, we must open up a new socket (denoted by new_sd) and get this value to the appropriate thread. To do this, I created global array poolsockets, which will hold all the socket descriptors for our pooled threads. The server portion gets the new socket descriptor, and places the value in the first spot of the array that has a 0. We only place a value in this array IF: 1. The variable main_pool_busy < worknum (If we have more clients in the system than in our pool, it doesn't mean we should always create a new thread. At the end of this, the server signals on the condition variable clientin that a new client has arrived. In our pooled thread, we then must walk this array and check the array until we hit our first non-zero value. This is the socket we will give to that thread. The thread then changes the array to have a zero here. What if our all threads in our pool our busy? If this is the case, then we will know it because our threads in this pool will increment main_pool_busy by one when they are working on a request and decrement it when they are done. If main_pool_busy >= worknum, then we must dynamically create a new thread. Then, we must realloc the size of our nonpoolsockets array by 1 int. We then add the new socket descriptor to our pool. Here's what we need to figure out: NOTE* Each worker should generate 100 messages which specify the worker thread ID, client socket descriptor and a copy of the client message. Additionally, each message should include a message number, starting from 0 and incrementing for each subsequent message sent to the same client. I don't know how to keep track of how many messages were to the same client. Maybe we shouldn't close the socket descriptor, but rather keep an array of structs for each socket that includes how many messages they have been sent. Then, the server adds the struct, the threads remove it, then the threads add it back once they've serviced one request (unless the count is 100). ------------------------------------------------------------- CHANGES Version 1 ---------- NONE: this is the first version. */ #define MAXSLOTS 30 #define dis_m 15 //problems with dis_m ==1 //Function prototypes void inc_clients(); void init_mutex_stuff(pthread_t*, pthread_t*); void *threadpool(void *); void server(int); void add_to_socket_pool(int); void inc_busy(); void dec_busy(); void *dispatcher(); void create_message(long, int, int, char *, char *); void init_ring(); void add_to_ring(char *, char *, int, int, int); int socket_from_string(char *); void add_to_head(char *); void add_to_tail(char *); struct message * reorder(struct message *, struct message *, int); int get_threadid(char *); void delete_socket_messages(int); struct message * merge(struct message *, struct message *, int); int get_request(char *, char *, char*); ///////////////////// //Global mutexes and condition variables pthread_mutex_t startservice; pthread_mutex_t numclients; pthread_mutex_t pool_sockets; pthread_mutex_t nonpool_sockets; pthread_mutex_t m_pool_busy; pthread_mutex_t slots; pthread_mutex_t numm; pthread_mutex_t circ; pthread_cond_t clientin; pthread_cond_t m; /////////////////////////////////////// //Global variables int clients; int main_pool_busy; int * poolsockets, nonpoolsockets; int worknum; struct ring mqueue; /////////////////////////////////////// int main(int argc, char ** argv){ //error handling if not enough arguments to program if(argc != 3){ printf("Not enough arguments to server: ./server portnum NumThreadsinPool\n"); _exit(-1); } //Convert arguments from strings to integer values int port = atoi(argv[1]); worknum = atoi(argv[2]); //Start server portion server(port); } /////////////////////////////////////////////////////////////////////////////////////////////// //The listen server thread///////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// void server(int port){ int sd, new_sd; struct sockaddr_in name, cli_name; int sock_opt_val = 1; int cli_len; pthread_t threads[worknum]; //create our pthread id array pthread_t dis[1]; //create our dispatcher array (necessary to create thread) init_mutex_stuff(threads, dis); //initialize mutexes and stuff //Server setup /////////////////////////////////////////////////////// if ((sd = socket (AF_INET, SOCK_STREAM, 0)) < 0) { perror("(servConn): socket() error"); _exit (-1); } if (setsockopt (sd, SOL_SOCKET, SO_REUSEADDR, (char *) &sock_opt_val, sizeof(sock_opt_val)) < 0) { perror ("(servConn): Failed to set SO_REUSEADDR on INET socket"); _exit (-1); } name.sin_family = AF_INET; name.sin_port = htons (port); name.sin_addr.s_addr = htonl(INADDR_ANY); if (bind (sd, (struct sockaddr *)&name, sizeof(name)) < 0) { perror ("(servConn): bind() error"); _exit (-1); } listen (sd, 5); //End of server Setup ////////////////////////////////////////////////// for (;;) { cli_len = sizeof (cli_name); new_sd = accept (sd, (struct sockaddr *) &cli_name, &cli_len); printf ("Assigning new socket descriptor: %d\n", new_sd); inc_clients(); //New client has come in, increment clients add_to_socket_pool(new_sd); //Add client to the pool of sockets if (new_sd < 0) { perror ("(servConn): accept() error"); _exit (-1); } } pthread_exit(NULL); //Quit } //Adds the new socket to the array designated for pthreads in the pool void add_to_socket_pool(int socket){ pthread_mutex_lock(&m_pool_busy); //Lock so that we can check main_pool_busy int i; //If not all our main pool is busy, then allocate to one of them if(main_pool_busy < worknum){ pthread_mutex_unlock(&m_pool_busy); //unlock busy, we no longer need to hold it pthread_mutex_lock(&pool_sockets); //Lock the socket pool array so that we can edit it without worry for(i = 0; i < worknum; i++){ //Find a poolsocket that is -1; then we should put the real socket there. This value will be changed back to -1 when the thread grabs the sockfd if(poolsockets[i] == -1){ poolsockets[i] = socket; pthread_mutex_unlock(&pool_sockets); //unlock our pool array, we don't need it anymore inc_busy(); //Incrememnt busy (locks the mutex itself) pthread_cond_signal(&clientin); //Signal first thread waiting on a client that a client needs to be serviced break; } } } else{ //Dynamic thread creation goes here pthread_mutex_unlock(&m_pool_busy); } } //Increments the client number. If client number goes over worknum, we must dynamically create new pthreads void inc_clients(){ pthread_mutex_lock(&numclients); clients++; pthread_mutex_unlock(&numclients); } //Increments busy void inc_busy(){ pthread_mutex_lock(&m_pool_busy); main_pool_busy++; pthread_mutex_unlock(&m_pool_busy); } //Initialize all of our mutexes at the beginning and create our pthreads void init_mutex_stuff(pthread_t * threads, pthread_t * dis){ pthread_mutex_init(&startservice, NULL); pthread_mutex_init(&numclients, NULL); pthread_mutex_init(&pool_sockets, NULL); pthread_mutex_init(&nonpool_sockets, NULL); pthread_mutex_init(&m_pool_busy, NULL); pthread_mutex_init(&circ, NULL); pthread_cond_init (&clientin, NULL); main_pool_busy = 0; poolsockets = malloc(sizeof(int)*worknum); int threadreturn; //error checking variables long i = 0; //Loop and create pthreads for(i; i < worknum; i++){ threadreturn = pthread_create(&threads[i], NULL, threadpool, (void *) i); poolsockets[i] = -1; if(threadreturn){ perror("Thread pool created unsuccessfully"); _exit(-1); } } pthread_create(&dis[0], NULL, dispatcher, NULL); } ////////////////////////////////////////////////////////////////////////////////////////// /////////Main pool routines ///////////////////////////////////////////////////////////////////////////////////////// void dec_busy(){ pthread_mutex_lock(&m_pool_busy); main_pool_busy--; pthread_mutex_unlock(&m_pool_busy); } void dec_clients(){ pthread_mutex_lock(&numclients); clients--; pthread_mutex_unlock(&numclients); } //This is what our threadpool pthreads will be running. void *threadpool(void * threadid){ long id = (long) threadid; //Id of this thread int i; int socket; int counter = 0; //Try and gain access to the next client that comes in and wait until server signals that a client as arrived while(1){ pthread_mutex_lock(&startservice); //lock start service (required for cond wait) pthread_cond_wait(&clientin, &startservice); //wait for signal from server that client exists pthread_mutex_unlock(&startservice); //unlock mutex. pthread_mutex_lock(&pool_sockets); //Lock the pool socket so we can get the socket fd unhindered/interrupted for(i = 0; i < worknum; i++){ if(poolsockets[i] != -1){ socket = poolsockets[i]; poolsockets[i] = -1; pthread_mutex_unlock(&pool_sockets); } } printf("Thread #%d is past getting the socket\n", id); int incoming = 1; while(counter < 100 && incoming != 0){ char buffer[512]; bzero(buffer,512); int startcounter = 0; incoming = read(socket, buffer, 512); if(buffer[0] != 0){ //client ID:priority:request:arguments char id[100]; long prior; char request[100]; char arg1[100]; char message[100]; char arg2[100]; char * point; point = strtok(buffer, ":"); strcpy(id, point); point = strtok(NULL, ":"); prior = atoi(point); point = strtok(NULL, ":"); strcpy(request, point); point = strtok(NULL, ":"); strcpy(arg1, point); point = strtok(NULL, ":"); if(point != NULL){ strcpy(arg2, point); } int fd; if(strcmp(request, "start_movie") == 0){ int count = 1; while(count <= 100){ char temp[10]; snprintf(temp, 50, "%d\0", count); strcpy(message, "./support/images/"); strcat(message, arg1); strcat(message, temp); strcat(message, ".ppm"); printf("This is message %s to %s\n", message, id); count++; add_to_ring(message, id, prior, counter, socket); //Adds our created message to the ring counter++; } printf("I'm out of the loop\n"); } else if(strcmp(request, "seek_movie") == 0){ int count = atoi(arg2); while(count <= 100){ char temp[10]; snprintf(temp, 10, "%d\0", count); strcpy(message, "./support/images/"); strcat(message, arg1); strcat(message, temp); strcat(message, ".ppm"); printf("This is message %s\n", message); count++; } } //create_message(id, socket, counter, buffer, message); //Creates our message from the input from the client. Stores it in buffer } else{ delete_socket_messages(socket); break; } } counter = 0; close(socket);//Zero out counter again } dec_clients(); //client serviced, decrement clients dec_busy(); //thread finished, decrement busy } //Creates a message void create_message(long threadid, int socket, int counter, char * buffer, char * message){ snprintf(message, strlen(buffer)+15, "%d:%d:%d:%s", threadid, socket, counter, buffer); } //Gets the socket from the message string (maybe I should just pass in the socket to another method) int socket_from_string(char * message){ char * substr1 = strstr(message, ":"); char * substr2 = substr1; substr2++; int occurance = strcspn(substr2, ":"); char sock[10]; strncpy(sock, substr2, occurance); return atoi(sock); } //Adds message to our ring buffer's head void add_to_head(char * message){ printf("Adding to head of ring\n"); mqueue.head->message = malloc(strlen(message)+1); //Allocate space for message strcpy(mqueue.head->message, message); //copy bytes into allocated space } //Adds our message to our ring buffer's tail void add_to_tail(char * message){ printf("Adding to tail of ring\n"); mqueue.tail->message = malloc(strlen(message)+1); //allocate space for message strcpy(mqueue.tail->message, message); //copy bytes into allocated space mqueue.tail->next = malloc(sizeof(struct message)); //allocate space for the next message struct } //Adds a message to our ring void add_to_ring(char * message, char * id, int prior, int mnum, int socket){ //printf("This is message %s:" , message); pthread_mutex_lock(&circ); //Lock the ring buffer pthread_mutex_lock(&numm); //Lock the message count (will need this to make sure we can't fill the buffer over the max slots) if(mqueue.head->message == NULL){ add_to_head(message); //Adds it to head mqueue.head->socket = socket; //Set message socket mqueue.head->priority = prior; //Set its priority (thread id) mqueue.head->mnum = mnum; //Set its message number (used for sorting) mqueue.head->id = malloc(sizeof(id)); strcpy(mqueue.head->id, id); } else if(mqueue.tail->message == NULL){ //This is the problem for dis_m 1 I'm pretty sure add_to_tail(message); mqueue.tail->socket = socket; mqueue.tail->priority = prior; mqueue.tail->mnum = mnum; mqueue.tail->id = malloc(sizeof(id)); strcpy(mqueue.tail->id, id); } else{ mqueue.tail->next = malloc(sizeof(struct message)); mqueue.tail = mqueue.tail->next; add_to_tail(message); mqueue.tail->socket = socket; mqueue.tail->priority = prior; mqueue.tail->mnum = mnum; mqueue.tail->id = malloc(sizeof(id)); strcpy(mqueue.tail->id, id); } mqueue.mcount++; pthread_mutex_unlock(&circ); if(mqueue.mcount >= dis_m){ pthread_mutex_unlock(&numm); pthread_cond_signal(&m); } else{ pthread_mutex_unlock(&numm); } printf("out of add to ring\n"); fflush(stdout); } ////////////////////////////////// //Dispatcher routines ///////////////////////////////// void *dispatcher(){ init_ring(); while(1){ pthread_mutex_lock(&slots); pthread_cond_wait(&m, &slots); pthread_mutex_lock(&numm); pthread_mutex_lock(&circ); printf("Dispatcher to the rescue!\n"); mqueue.head = reorder(mqueue.head, mqueue.tail, mqueue.mcount); //printf("This is the head %s\n", mqueue.head->message); //printf("This is the tail %s\n", mqueue.head->message); fflush(stdout); struct message * pointer = mqueue.head; int count = 0; while(mqueue.head != mqueue.tail && count < dis_m){ printf("Sending to client %s: %s\n", pointer->id, pointer->message); int fd; fd = open(pointer->message, O_RDONLY); char buf[58368]; int bytesRead; printf("This is fd %d\n", fd); bytesRead=read(fd,buf,58368); send(pointer->socket,buf,bytesRead,0); perror("Error:\n"); fflush(stdout); close(fd); mqueue.mcount--; mqueue.head = mqueue.head->next; free(pointer->message); free(pointer); pointer = mqueue.head; count++; } printf("Sending %s\n", pointer->message); int fd; fd = open(pointer->message, O_RDONLY); printf("This is fd %d\n", fd); printf("I am hhere2\n"); char buf[58368]; int bytesRead; bytesRead=read(fd,buf,58368); send(pointer->socket,buf,bytesRead,0); perror("Error:\n"); close(fd); mqueue.mcount--; if(mqueue.head != mqueue.tail){ mqueue.head = mqueue.head->next; } else{ mqueue.head->next = malloc(sizeof(struct message)); mqueue.head = mqueue.head->next; mqueue.head->next = malloc(sizeof(struct message)); mqueue.tail = mqueue.head->next; mqueue.head->message = NULL; } free(pointer->message); free(pointer); pthread_mutex_unlock(&numm); pthread_mutex_unlock(&circ); pthread_mutex_unlock(&slots); printf("My dispatcher has defeated evil\n"); } } void init_ring(){ mqueue.head = malloc(sizeof(struct message)); mqueue.head->next = malloc(sizeof(struct message)); mqueue.tail = mqueue.head->next; mqueue.mcount = 0; } struct message * reorder(struct message * begin, struct message * end, int num){ //printf("I am reordering for size %d\n", num); fflush(stdout); int i; if(num == 1){ //printf("Begin: %s\n", begin->message); begin->next = NULL; return begin; } else{ struct message * left = begin; struct message * right; int middle = num/2; for(i = 1; i < middle; i++){ left = left->next; } right = left -> next; left -> next = NULL; //printf("Begin: %s\nLeft: %s\nright: %s\nend:%s\n", begin->message, left->message, right->message, end->message); left = reorder(begin, left, middle); if(num%2 != 0){ right = reorder(right, end, middle+1); } else{ right = reorder(right, end, middle); } return merge(left, right, num); } } struct message * merge(struct message * left, struct message * right, int num){ //printf("I am merginging! left: %s %d, right: %s %dnum: %d\n", left->message,left->priority, right->message, right->priority, num); struct message * start, * point; int lenL= 0; int lenR = 0; int flagL = 0; int flagR = 0; int count = 0; int middle1 = num/2; int middle2; if(num%2 != 0){ middle2 = middle1+1; } else{ middle2 = middle1; } while(lenL < middle1 && lenR < middle2){ count++; //printf("In here for count %d\n", count); if(lenL == 0 && lenR == 0){ if(left->priority < right->priority){ start = left; //Set the start point point = left; //set our enum; left = left->next; //move the left pointer point->next = NULL; //Set the next node to NULL lenL++; } else if(left->priority > right->priority){ start = right; point = right; right = right->next; point->next = NULL; lenR++; } else{ if(left->mnum < right->mnum){ ////printf("This is where we are\n"); start = left; //Set the start point point = left; //set our enum; left = left->next; //move the left pointer point->next = NULL; //Set the next node to NULL lenL++; } else{ start = right; point = right; right = right->next; point->next = NULL; lenR++; } } } else{ if(left->priority < right->priority){ point->next = left; left = left->next; //move the left pointer point = point->next; point->next = NULL; //Set the next node to NULL lenL++; } else if(left->priority > right->priority){ point->next = right; right = right->next; point = point->next; point->next = NULL; lenR++; } else{ if(left->mnum < right->mnum){ point->next = left; //set our enum; left = left->next; point = point->next;//move the left pointer point->next = NULL; //Set the next node to NULL lenL++; } else{ point->next = right; right = right->next; point = point->next; point->next = NULL; lenR++; } } } if(lenL == middle1){ flagL = 1; break; } if(lenR == middle2){ flagR = 1; break; } } if(flagL == 1){ point->next = right; point = point->next; for(lenR; lenR< middle2-1; lenR++){ point = point->next; } point->next = NULL; mqueue.tail = point; } else{ point->next = left; point = point->next; for(lenL; lenL< middle1-1; lenL++){ point = point->next; } point->next = NULL; mqueue.tail = point; } //printf("This is the start %s\n", start->message); //printf("This is mqueue.tail %s\n", mqueue.tail->message); return start; } void delete_socket_messages(int a){ }

    Read the article

  • Silverlight Recruiting Application Part 5 - Jobs Module / View

    Now we starting getting into a more code-heavy portion of this series, thankfully though this means the groundwork is all set for the most part and after adding the modules we will have a complete application that can be provided with full source. The Jobs module will have two concerns- adding and maintaining jobs that can then be broadcast out to the website. How they are displayed on the site will be handled by our admin system (which will just poll from this common database), so we aren't too concerned with that, but rather with getting the information into the system and allowing the backend administration/HR users to keep things up to date. Since there is a fair bit of information that we want to display, we're going to move editing to a separate view so we can get all that information in an easy-to-use spot. With all the files created for this module, the project looks something like this: And now... on to the code. XAML for the Job Posting View All we really need for the Job Posting View is a RadGridView and a few buttons. This will let us both show off records and perform operations on the records without much hassle. That XAML is going to look something like this: 01.<Grid x:Name="LayoutRoot" 02.Background="White"> 03.<Grid.RowDefinitions> 04.<RowDefinition Height="30" /> 05.<RowDefinition /> 06.</Grid.RowDefinitions> 07.<StackPanel Orientation="Horizontal"> 08.<Button x:Name="xAddRecordButton" 09.Content="Add Job" 10.Width="120" 11.cal:Click.Command="{Binding AddRecord}" 12.telerik:StyleManager.Theme="Windows7" /> 13.<Button x:Name="xEditRecordButton" 14.Content="Edit Job" 15.Width="120" 16.cal:Click.Command="{Binding EditRecord}" 17.telerik:StyleManager.Theme="Windows7" /> 18.</StackPanel> 19.<telerikGrid:RadGridView x:Name="xJobsGrid" 20.Grid.Row="1" 21.IsReadOnly="True" 22.AutoGenerateColumns="False" 23.ColumnWidth="*" 24.RowDetailsVisibilityMode="VisibleWhenSelected" 25.ItemsSource="{Binding MyJobs}" 26.SelectedItem="{Binding SelectedJob, Mode=TwoWay}" 27.command:SelectedItemChangedEventClass.Command="{Binding SelectedItemChanged}"> 28.<telerikGrid:RadGridView.Columns> 29.<telerikGrid:GridViewDataColumn Header="Job Title" 30.DataMemberBinding="{Binding JobTitle}" 31.UniqueName="JobTitle" /> 32.<telerikGrid:GridViewDataColumn Header="Location" 33.DataMemberBinding="{Binding Location}" 34.UniqueName="Location" /> 35.<telerikGrid:GridViewDataColumn Header="Resume Required" 36.DataMemberBinding="{Binding NeedsResume}" 37.UniqueName="NeedsResume" /> 38.<telerikGrid:GridViewDataColumn Header="CV Required" 39.DataMemberBinding="{Binding NeedsCV}" 40.UniqueName="NeedsCV" /> 41.<telerikGrid:GridViewDataColumn Header="Overview Required" 42.DataMemberBinding="{Binding NeedsOverview}" 43.UniqueName="NeedsOverview" /> 44.<telerikGrid:GridViewDataColumn Header="Active" 45.DataMemberBinding="{Binding IsActive}" 46.UniqueName="IsActive" /> 47.</telerikGrid:RadGridView.Columns> 48.</telerikGrid:RadGridView> 49.</Grid> I'll explain what's happening here by line numbers: Lines 11 and 16: Using the same type of click commands as we saw in the Menu module, we tie the button clicks to delegate commands in the viewmodel. Line 25: The source for the jobs will be a collection in the viewmodel. Line 26: We also bind the selected item to a public property from the viewmodel for use in code. Line 27: We've turned the event into a command so we can handle it via code in the viewmodel. So those first three probably make sense to you as far as Silverlight/WPF binding magic is concerned, but for line 27... This actually comes from something I read onDamien Schenkelman's blog back in the day for creating an attached behavior from any event. So, any time you see me using command:Whatever.Command, the backing for it is actually something like this: SelectedItemChangedEventBehavior.cs: 01.public class SelectedItemChangedEventBehavior : CommandBehaviorBase<Telerik.Windows.Controls.DataControl> 02.{ 03.public SelectedItemChangedEventBehavior(DataControl element) 04.: base(element) 05.{ 06.element.SelectionChanged += new EventHandler<SelectionChangeEventArgs>(element_SelectionChanged); 07.} 08.void element_SelectionChanged(object sender, SelectionChangeEventArgs e) 09.{ 10.// We'll only ever allow single selection, so will only need item index 0 11.base.CommandParameter = e.AddedItems[0]; 12.base.ExecuteCommand(); 13.} 14.} SelectedItemChangedEventClass.cs: 01.public class SelectedItemChangedEventClass 02.{ 03.#region The Command Stuff 04.public static ICommand GetCommand(DependencyObject obj) 05.{ 06.return (ICommand)obj.GetValue(CommandProperty); 07.} 08.public static void SetCommand(DependencyObject obj, ICommand value) 09.{ 10.obj.SetValue(CommandProperty, value); 11.} 12.public static readonly DependencyProperty CommandProperty = 13.DependencyProperty.RegisterAttached("Command", typeof(ICommand), 14.typeof(SelectedItemChangedEventClass), new PropertyMetadata(OnSetCommandCallback)); 15.public static void OnSetCommandCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) 16.{ 17.DataControl element = dependencyObject as DataControl; 18.if (element != null) 19.{ 20.SelectedItemChangedEventBehavior behavior = GetOrCreateBehavior(element); 21.behavior.Command = e.NewValue as ICommand; 22.} 23.} 24.#endregion 25.public static SelectedItemChangedEventBehavior GetOrCreateBehavior(DataControl element) 26.{ 27.SelectedItemChangedEventBehavior behavior = element.GetValue(SelectedItemChangedEventBehaviorProperty) as SelectedItemChangedEventBehavior; 28.if (behavior == null) 29.{ 30.behavior = new SelectedItemChangedEventBehavior(element); 31.element.SetValue(SelectedItemChangedEventBehaviorProperty, behavior); 32.} 33.return behavior; 34.} 35.public static SelectedItemChangedEventBehavior GetSelectedItemChangedEventBehavior(DependencyObject obj) 36.{ 37.return (SelectedItemChangedEventBehavior)obj.GetValue(SelectedItemChangedEventBehaviorProperty); 38.} 39.public static void SetSelectedItemChangedEventBehavior(DependencyObject obj, SelectedItemChangedEventBehavior value) 40.{ 41.obj.SetValue(SelectedItemChangedEventBehaviorProperty, value); 42.} 43.public static readonly DependencyProperty SelectedItemChangedEventBehaviorProperty = 44.DependencyProperty.RegisterAttached("SelectedItemChangedEventBehavior", 45.typeof(SelectedItemChangedEventBehavior), typeof(SelectedItemChangedEventClass), null); 46.} These end up looking very similar from command to command, but in a nutshell you create a command based on any event, determine what the parameter for it will be, then execute. It attaches via XAML and ties to a DelegateCommand in the viewmodel, so you get the full event experience (since some controls get a bit event-rich for added functionality). Simple enough, right? Viewmodel for the Job Posting View The Viewmodel is going to need to handle all events going back and forth, maintaining interactions with the data we are using, and both publishing and subscribing to events. Rather than breaking this into tons of little pieces, I'll give you a nice view of the entire viewmodel and then hit up the important points line-by-line: 001.public class JobPostingViewModel : ViewModelBase 002.{ 003.private readonly IEventAggregator eventAggregator; 004.private readonly IRegionManager regionManager; 005.public DelegateCommand<object> AddRecord { get; set; } 006.public DelegateCommand<object> EditRecord { get; set; } 007.public DelegateCommand<object> SelectedItemChanged { get; set; } 008.public RecruitingContext context; 009.private QueryableCollectionView _myJobs; 010.public QueryableCollectionView MyJobs 011.{ 012.get { return _myJobs; } 013.} 014.private QueryableCollectionView _selectionJobActionHistory; 015.public QueryableCollectionView SelectedJobActionHistory 016.{ 017.get { return _selectionJobActionHistory; } 018.} 019.private JobPosting _selectedJob; 020.public JobPosting SelectedJob 021.{ 022.get { return _selectedJob; } 023.set 024.{ 025.if (value != _selectedJob) 026.{ 027._selectedJob = value; 028.NotifyChanged("SelectedJob"); 029.} 030.} 031.} 032.public SubscriptionToken editToken = new SubscriptionToken(); 033.public SubscriptionToken addToken = new SubscriptionToken(); 034.public JobPostingViewModel(IEventAggregator eventAgg, IRegionManager regionmanager) 035.{ 036.// set Unity items 037.this.eventAggregator = eventAgg; 038.this.regionManager = regionmanager; 039.// load our context 040.context = new RecruitingContext(); 041.this._myJobs = new QueryableCollectionView(context.JobPostings); 042.context.Load(context.GetJobPostingsQuery()); 043.// set command events 044.this.AddRecord = new DelegateCommand<object>(this.AddNewRecord); 045.this.EditRecord = new DelegateCommand<object>(this.EditExistingRecord); 046.this.SelectedItemChanged = new DelegateCommand<object>(this.SelectedRecordChanged); 047.SetSubscriptions(); 048.} 049.#region DelegateCommands from View 050.public void AddNewRecord(object obj) 051.{ 052.this.eventAggregator.GetEvent<AddJobEvent>().Publish(true); 053.} 054.public void EditExistingRecord(object obj) 055.{ 056.if (_selectedJob == null) 057.{ 058.this.eventAggregator.GetEvent<NotifyUserEvent>().Publish("No job selected."); 059.} 060.else 061.{ 062.this._myJobs.EditItem(this._selectedJob); 063.this.eventAggregator.GetEvent<EditJobEvent>().Publish(this._selectedJob); 064.} 065.} 066.public void SelectedRecordChanged(object obj) 067.{ 068.if (obj.GetType() == typeof(ActionHistory)) 069.{ 070.// event bubbles up so we don't catch items from the ActionHistory grid 071.} 072.else 073.{ 074.JobPosting job = obj as JobPosting; 075.GrabHistory(job.PostingID); 076.} 077.} 078.#endregion 079.#region Subscription Declaration and Events 080.public void SetSubscriptions() 081.{ 082.EditJobCompleteEvent editComplete = eventAggregator.GetEvent<EditJobCompleteEvent>(); 083.if (editToken != null) 084.editComplete.Unsubscribe(editToken); 085.editToken = editComplete.Subscribe(this.EditCompleteEventHandler); 086.AddJobCompleteEvent addComplete = eventAggregator.GetEvent<AddJobCompleteEvent>(); 087.if (addToken != null) 088.addComplete.Unsubscribe(addToken); 089.addToken = addComplete.Subscribe(this.AddCompleteEventHandler); 090.} 091.public void EditCompleteEventHandler(bool complete) 092.{ 093.if (complete) 094.{ 095.JobPosting thisJob = _myJobs.CurrentEditItem as JobPosting; 096.this._myJobs.CommitEdit(); 097.this.context.SubmitChanges((s) => 098.{ 099.ActionHistory myAction = new ActionHistory(); 100.myAction.PostingID = thisJob.PostingID; 101.myAction.Description = String.Format("Job '{0}' has been edited by {1}", thisJob.JobTitle, "default user"); 102.myAction.TimeStamp = DateTime.Now; 103.eventAggregator.GetEvent<AddActionEvent>().Publish(myAction); 104.} 105., null); 106.} 107.else 108.{ 109.this._myJobs.CancelEdit(); 110.} 111.this.MakeMeActive(this.regionManager, "MainRegion", "JobPostingsView"); 112.} 113.public void AddCompleteEventHandler(JobPosting job) 114.{ 115.if (job == null) 116.{ 117.// do nothing, new job add cancelled 118.} 119.else 120.{ 121.this.context.JobPostings.Add(job); 122.this.context.SubmitChanges((s) => 123.{ 124.ActionHistory myAction = new ActionHistory(); 125.myAction.PostingID = job.PostingID; 126.myAction.Description = String.Format("Job '{0}' has been added by {1}", job.JobTitle, "default user"); 127.myAction.TimeStamp = DateTime.Now; 128.eventAggregator.GetEvent<AddActionEvent>().Publish(myAction); 129.} 130., null); 131.} 132.this.MakeMeActive(this.regionManager, "MainRegion", "JobPostingsView"); 133.} 134.#endregion 135.public void GrabHistory(int postID) 136.{ 137.context.ActionHistories.Clear(); 138._selectionJobActionHistory = new QueryableCollectionView(context.ActionHistories); 139.context.Load(context.GetHistoryForJobQuery(postID)); 140.} Taking it from the top, we're injecting an Event Aggregator and Region Manager for use down the road and also have the public DelegateCommands (just like in the Menu module). We also grab a reference to our context, which we'll obviously need for data, then set up a few fields with public properties tied to them. We're also setting subscription tokens, which we have not yet seen but I will get into below. The AddNewRecord (50) and EditExistingRecord (54) methods should speak for themselves for functionality, the one thing of note is we're sending events off to the Event Aggregator which some module, somewhere will take care of. Since these aren't entirely relying on one another, the Jobs View doesn't care if anyone is listening, but it will publish AddJobEvent (52), NotifyUserEvent (58) and EditJobEvent (63)regardless. Don't mind the GrabHistory() method so much, that is just grabbing history items (visibly being created in the SubmitChanges callbacks), and adding them to the database. Every action will trigger a history event, so we'll know who modified what and when, just in case. ;) So where are we at? Well, if we click to Add a job, we publish an event, if we edit a job, we publish an event with the selected record (attained through the magic of binding). Where is this all going though? To the Viewmodel, of course! XAML for the AddEditJobView This is pretty straightforward except for one thing, noted below: 001.<Grid x:Name="LayoutRoot" 002.Background="White"> 003.<Grid x:Name="xEditGrid" 004.Margin="10" 005.validationHelper:ValidationScope.Errors="{Binding Errors}"> 006.<Grid.Background> 007.<LinearGradientBrush EndPoint="0.5,1" 008.StartPoint="0.5,0"> 009.<GradientStop Color="#FFC7C7C7" 010.Offset="0" /> 011.<GradientStop Color="#FFF6F3F3" 012.Offset="1" /> 013.</LinearGradientBrush> 014.</Grid.Background> 015.<Grid.RowDefinitions> 016.<RowDefinition Height="40" /> 017.<RowDefinition Height="40" /> 018.<RowDefinition Height="40" /> 019.<RowDefinition Height="100" /> 020.<RowDefinition Height="100" /> 021.<RowDefinition Height="100" /> 022.<RowDefinition Height="40" /> 023.<RowDefinition Height="40" /> 024.<RowDefinition Height="40" /> 025.</Grid.RowDefinitions> 026.<Grid.ColumnDefinitions> 027.<ColumnDefinition Width="150" /> 028.<ColumnDefinition Width="150" /> 029.<ColumnDefinition Width="300" /> 030.<ColumnDefinition Width="100" /> 031.</Grid.ColumnDefinitions> 032.<!-- Title --> 033.<TextBlock Margin="8" 034.Text="{Binding AddEditString}" 035.TextWrapping="Wrap" 036.Grid.Column="1" 037.Grid.ColumnSpan="2" 038.FontSize="16" /> 039.<!-- Data entry area--> 040. 041.<TextBlock Margin="8,0,0,0" 042.Style="{StaticResource LabelTxb}" 043.Grid.Row="1" 044.Text="Job Title" 045.VerticalAlignment="Center" /> 046.<TextBox x:Name="xJobTitleTB" 047.Margin="0,8" 048.Grid.Column="1" 049.Grid.Row="1" 050.Text="{Binding activeJob.JobTitle, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 051.Grid.ColumnSpan="2" /> 052.<TextBlock Margin="8,0,0,0" 053.Grid.Row="2" 054.Text="Location" 055.d:LayoutOverrides="Height" 056.VerticalAlignment="Center" /> 057.<TextBox x:Name="xLocationTB" 058.Margin="0,8" 059.Grid.Column="1" 060.Grid.Row="2" 061.Text="{Binding activeJob.Location, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 062.Grid.ColumnSpan="2" /> 063. 064.<TextBlock Margin="8,11,8,0" 065.Grid.Row="3" 066.Text="Description" 067.TextWrapping="Wrap" 068.VerticalAlignment="Top" /> 069. 070.<TextBox x:Name="xDescriptionTB" 071.Height="84" 072.TextWrapping="Wrap" 073.ScrollViewer.VerticalScrollBarVisibility="Auto" 074.Grid.Column="1" 075.Grid.Row="3" 076.Text="{Binding activeJob.Description, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 077.Grid.ColumnSpan="2" /> 078.<TextBlock Margin="8,11,8,0" 079.Grid.Row="4" 080.Text="Requirements" 081.TextWrapping="Wrap" 082.VerticalAlignment="Top" /> 083. 084.<TextBox x:Name="xRequirementsTB" 085.Height="84" 086.TextWrapping="Wrap" 087.ScrollViewer.VerticalScrollBarVisibility="Auto" 088.Grid.Column="1" 089.Grid.Row="4" 090.Text="{Binding activeJob.Requirements, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 091.Grid.ColumnSpan="2" /> 092.<TextBlock Margin="8,11,8,0" 093.Grid.Row="5" 094.Text="Qualifications" 095.TextWrapping="Wrap" 096.VerticalAlignment="Top" /> 097. 098.<TextBox x:Name="xQualificationsTB" 099.Height="84" 100.TextWrapping="Wrap" 101.ScrollViewer.VerticalScrollBarVisibility="Auto" 102.Grid.Column="1" 103.Grid.Row="5" 104.Text="{Binding activeJob.Qualifications, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 105.Grid.ColumnSpan="2" /> 106.<!-- Requirements Checkboxes--> 107. 108.<CheckBox x:Name="xResumeRequiredCB" Margin="8,8,8,15" 109.Content="Resume Required" 110.Grid.Row="6" 111.Grid.ColumnSpan="2" 112.IsChecked="{Binding activeJob.NeedsResume, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 113. 114.<CheckBox x:Name="xCoverletterRequiredCB" Margin="8,8,8,15" 115.Content="Cover Letter Required" 116.Grid.Column="2" 117.Grid.Row="6" 118.IsChecked="{Binding activeJob.NeedsCV, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 119. 120.<CheckBox x:Name="xOverviewRequiredCB" Margin="8,8,8,15" 121.Content="Overview Required" 122.Grid.Row="7" 123.Grid.ColumnSpan="2" 124.IsChecked="{Binding activeJob.NeedsOverview, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 125. 126.<CheckBox x:Name="xJobActiveCB" Margin="8,8,8,15" 127.Content="Job is Active" 128.Grid.Column="2" 129.Grid.Row="7" 130.IsChecked="{Binding activeJob.IsActive, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 131. 132.<!-- Buttons --> 133. 134.<Button x:Name="xAddEditButton" Margin="8,8,0,10" 135.Content="{Binding AddEditButtonString}" 136.cal:Click.Command="{Binding AddEditCommand}" 137.Grid.Column="2" 138.Grid.Row="8" 139.HorizontalAlignment="Left" 140.Width="125" 141.telerik:StyleManager.Theme="Windows7" /> 142. 143.<Button x:Name="xCancelButton" HorizontalAlignment="Right" 144.Content="Cancel" 145.cal:Click.Command="{Binding CancelCommand}" 146.Margin="0,8,8,10" 147.Width="125" 148.Grid.Column="2" 149.Grid.Row="8" 150.telerik:StyleManager.Theme="Windows7" /> 151.</Grid> 152.</Grid> The 'validationHelper:ValidationScope' line may seem odd. This is a handy little trick for catching current and would-be validation errors when working in this whole setup. This all comes from an approach found on theJoy Of Code blog, although it looks like the story for this will be changing slightly with new advances in SL4/WCF RIA Services, so this section can definitely get an overhaul a little down the road. The code is the fun part of all this, so let us see what's happening under the hood. Viewmodel for the AddEditJobView We are going to see some of the same things happening here, so I'll skip over the repeat info and get right to the good stuff: 001.public class AddEditJobViewModel : ViewModelBase 002.{ 003.private readonly IEventAggregator eventAggregator; 004.private readonly IRegionManager regionManager; 005. 006.public RecruitingContext context; 007. 008.private JobPosting _activeJob; 009.public JobPosting activeJob 010.{ 011.get { return _activeJob; } 012.set 013.{ 014.if (_activeJob != value) 015.{ 016._activeJob = value; 017.NotifyChanged("activeJob"); 018.} 019.} 020.} 021. 022.public bool isNewJob; 023. 024.private string _addEditString; 025.public string AddEditString 026.{ 027.get { return _addEditString; } 028.set 029.{ 030.if (_addEditString != value) 031.{ 032._addEditString = value; 033.NotifyChanged("AddEditString"); 034.} 035.} 036.} 037. 038.private string _addEditButtonString; 039.public string AddEditButtonString 040.{ 041.get { return _addEditButtonString; } 042.set 043.{ 044.if (_addEditButtonString != value) 045.{ 046._addEditButtonString = value; 047.NotifyChanged("AddEditButtonString"); 048.} 049.} 050.} 051. 052.public SubscriptionToken addJobToken = new SubscriptionToken(); 053.public SubscriptionToken editJobToken = new SubscriptionToken(); 054. 055.public DelegateCommand<object> AddEditCommand { get; set; } 056.public DelegateCommand<object> CancelCommand { get; set; } 057. 058.private ObservableCollection<ValidationError> _errors = new ObservableCollection<ValidationError>(); 059.public ObservableCollection<ValidationError> Errors 060.{ 061.get { return _errors; } 062.} 063. 064.private ObservableCollection<ValidationResult> _valResults = new ObservableCollection<ValidationResult>(); 065.public ObservableCollection<ValidationResult> ValResults 066.{ 067.get { return this._valResults; } 068.} 069. 070.public AddEditJobViewModel(IEventAggregator eventAgg, IRegionManager regionmanager) 071.{ 072.// set Unity items 073.this.eventAggregator = eventAgg; 074.this.regionManager = regionmanager; 075. 076.context = new RecruitingContext(); 077. 078.AddEditCommand = new DelegateCommand<object>(this.AddEditJobCommand); 079.CancelCommand = new DelegateCommand<object>(this.CancelAddEditCommand); 080. 081.SetSubscriptions(); 082.} 083. 084.#region Subscription Declaration and Events 085. 086.public void SetSubscriptions() 087.{ 088.AddJobEvent addJob = this.eventAggregator.GetEvent<AddJobEvent>(); 089. 090.if (addJobToken != null) 091.addJob.Unsubscribe(addJobToken); 092. 093.addJobToken = addJob.Subscribe(this.AddJobEventHandler); 094. 095.EditJobEvent editJob = this.eventAggregator.GetEvent<EditJobEvent>(); 096. 097.if (editJobToken != null) 098.editJob.Unsubscribe(editJobToken); 099. 100.editJobToken = editJob.Subscribe(this.EditJobEventHandler); 101.} 102. 103.public void AddJobEventHandler(bool isNew) 104.{ 105.this.activeJob = null; 106.this.activeJob = new JobPosting(); 107.this.activeJob.IsActive = true; // We assume that we want a new job to go up immediately 108.this.isNewJob = true; 109.this.AddEditString = "Add New Job Posting"; 110.this.AddEditButtonString = "Add Job"; 111. 112.MakeMeActive(this.regionManager, "MainRegion", "AddEditJobView"); 113.} 114. 115.public void EditJobEventHandler(JobPosting editJob) 116.{ 117.this.activeJob = null; 118.this.activeJob = editJob; 119.this.isNewJob = false; 120.this.AddEditString = "Edit Job Posting"; 121.this.AddEditButtonString = "Edit Job"; 122. 123.MakeMeActive(this.regionManager, "MainRegion", "AddEditJobView"); 124.} 125. 126.#endregion 127. 128.#region DelegateCommands from View 129. 130.public void AddEditJobCommand(object obj) 131.{ 132.if (this.Errors.Count > 0) 133.{ 134.List<string> errorMessages = new List<string>(); 135. 136.foreach (var valR in this.Errors) 137.{ 138.errorMessages.Add(valR.Exception.Message); 139.} 140. 141.this.eventAggregator.GetEvent<DisplayValidationErrorsEvent>().Publish(errorMessages); 142. 143.} 144.else if (!Validator.TryValidateObject(this.activeJob, new ValidationContext(this.activeJob, null, null), _valResults, true)) 145.{ 146.List<string> errorMessages = new List<string>(); 147. 148.foreach (var valR in this._valResults) 149.{ 150.errorMessages.Add(valR.ErrorMessage); 151.} 152. 153.this._valResults.Clear(); 154. 155.this.eventAggregator.GetEvent<DisplayValidationErrorsEvent>().Publish(errorMessages); 156.} 157.else 158.{ 159.if (this.isNewJob) 160.{ 161.this.eventAggregator.GetEvent<AddJobCompleteEvent>().Publish(this.activeJob); 162.} 163.else 164.{ 165.this.eventAggregator.GetEvent<EditJobCompleteEvent>().Publish(true); 166.} 167.} 168.} 169. 170.public void CancelAddEditCommand(object obj) 171.{ 172.if (this.isNewJob) 173.{ 174.this.eventAggregator.GetEvent<AddJobCompleteEvent>().Publish(null); 175.} 176.else 177.{ 178.this.eventAggregator.GetEvent<EditJobCompleteEvent>().Publish(false); 179.} 180.} 181. 182.#endregion 183.} 184.} We start seeing something new on line 103- the AddJobEventHandler will create a new job and set that to the activeJob item on the ViewModel. When this is all set, the view calls that familiar MakeMeActive method to activate itself. I made a bit of a management call on making views self-activate like this, but I figured it works for one reason. As I create this application, views may not exist that I have in mind, so after a view receives its 'ping' from being subscribed to an event, it prepares whatever it needs to do and then goes active. This way if I don't have 'edit' hooked up, I can click as the day is long on the main view and won't get lost in an empty region. Total personal preference here. :) Everything else should again be pretty straightforward, although I do a bit of validation checking in the AddEditJobCommand, which can either fire off an event back to the main view/viewmodel if everything is a success or sent a list of errors to our notification module, which pops open a RadWindow with the alerts if any exist. As a bonus side note, here's what my WCF RIA Services metadata looks like for handling all of the validation: private JobPostingMetadata() { } [StringLength(2500, ErrorMessage = "Description should be more than one and less than 2500 characters.", MinimumLength = 1)] [Required(ErrorMessage = "Description is required.")] public string Description; [Required(ErrorMessage="Active Status is Required")] public bool IsActive; [StringLength(100, ErrorMessage = "Posting title must be more than 3 but less than 100 characters.", MinimumLength = 3)] [Required(ErrorMessage = "Job Title is required.")] public bool JobTitle; [Required] public string Location; public bool NeedsCV; public bool NeedsOverview; public bool NeedsResume; public int PostingID; [Required(ErrorMessage="Qualifications are required.")] [StringLength(2500, ErrorMessage="Qualifications should be more than one and less than 2500 characters.", MinimumLength=1)] public string Qualifications; [StringLength(2500, ErrorMessage = "Requirements should be more than one and less than 2500 characters.", MinimumLength = 1)] [Required(ErrorMessage="Requirements are required.")] public string Requirements;   The RecruitCB Alternative See all that Xaml I pasted above? Those are now two pieces sitting in the JobsView.xaml file now. The only real difference is that the xEditGrid now sits in the same place as xJobsGrid, with visibility swapping out between the two for a quick switch. I also took out all the cal: and command: command references and replaced Button events with clicks and the Grid selection command replaced with a SelectedItemChanged event. Also, at the bottom of the xEditGrid after the last button, I add a ValidationSummary (with Visibility=Collapsed) to catch any errors that are popping up. Simple as can be, and leads to this being the single code-behind file: 001.public partial class JobsView : UserControl 002.{ 003.public RecruitingContext context; 004.public JobPosting activeJob; 005.public bool isNew; 006.private ObservableCollection<ValidationResult> _valResults = new ObservableCollection<ValidationResult>(); 007.public ObservableCollection<ValidationResult> ValResults 008.{ 009.get { return this._valResults; } 010.} 011.public JobsView() 012.{ 013.InitializeComponent(); 014.this.Loaded += new RoutedEventHandler(JobsView_Loaded); 015.} 016.void JobsView_Loaded(object sender, RoutedEventArgs e) 017.{ 018.context = new RecruitingContext(); 019.xJobsGrid.ItemsSource = context.JobPostings; 020.context.Load(context.GetJobPostingsQuery()); 021.} 022.private void xAddRecordButton_Click(object sender, RoutedEventArgs e) 023.{ 024.activeJob = new JobPosting(); 025.isNew = true; 026.xAddEditTitle.Text = "Add a Job Posting"; 027.xAddEditButton.Content = "Add"; 028.xEditGrid.DataContext = activeJob; 029.HideJobsGrid(); 030.} 031.private void xEditRecordButton_Click(object sender, RoutedEventArgs e) 032.{ 033.activeJob = xJobsGrid.SelectedItem as JobPosting; 034.isNew = false; 035.xAddEditTitle.Text = "Edit a Job Posting"; 036.xAddEditButton.Content = "Edit"; 037.xEditGrid.DataContext = activeJob; 038.HideJobsGrid(); 039.} 040.private void xAddEditButton_Click(object sender, RoutedEventArgs e) 041.{ 042.if (!Validator.TryValidateObject(this.activeJob, new ValidationContext(this.activeJob, null, null), _valResults, true)) 043.{ 044.List<string> errorMessages = new List<string>(); 045.foreach (var valR in this._valResults) 046.{ 047.errorMessages.Add(valR.ErrorMessage); 048.} 049.this._valResults.Clear(); 050.ShowErrors(errorMessages); 051.} 052.else if (xSummary.Errors.Count > 0) 053.{ 054.List<string> errorMessages = new List<string>(); 055.foreach (var err in xSummary.Errors) 056.{ 057.errorMessages.Add(err.Message); 058.} 059.ShowErrors(errorMessages); 060.} 061.else 062.{ 063.if (this.isNew) 064.{ 065.context.JobPostings.Add(activeJob); 066.context.SubmitChanges((s) => 067.{ 068.ActionHistory thisAction = new ActionHistory(); 069.thisAction.PostingID = activeJob.PostingID; 070.thisAction.Description = String.Format("Job '{0}' has been edited by {1}", activeJob.JobTitle, "default user"); 071.thisAction.TimeStamp = DateTime.Now; 072.context.ActionHistories.Add(thisAction); 073.context.SubmitChanges(); 074.}, null); 075.} 076.else 077.{ 078.context.SubmitChanges((s) => 079.{ 080.ActionHistory thisAction = new ActionHistory(); 081.thisAction.PostingID = activeJob.PostingID; 082.thisAction.Description = String.Format("Job '{0}' has been added by {1}", activeJob.JobTitle, "default user"); 083.thisAction.TimeStamp = DateTime.Now; 084.context.ActionHistories.Add(thisAction); 085.context.SubmitChanges(); 086.}, null); 087.} 088.ShowJobsGrid(); 089.} 090.} 091.private void xCancelButton_Click(object sender, RoutedEventArgs e) 092.{ 093.ShowJobsGrid(); 094.} 095.private void ShowJobsGrid() 096.{ 097.xAddEditRecordButtonPanel.Visibility = Visibility.Visible; 098.xEditGrid.Visibility = Visibility.Collapsed; 099.xJobsGrid.Visibility = Visibility.Visible; 100.} 101.private void HideJobsGrid() 102.{ 103.xAddEditRecordButtonPanel.Visibility = Visibility.Collapsed; 104.xJobsGrid.Visibility = Visibility.Collapsed; 105.xEditGrid.Visibility = Visibility.Visible; 106.} 107.private void ShowErrors(List<string> errorList) 108.{ 109.string nm = "Errors received: \n"; 110.foreach (string anerror in errorList) 111.nm += anerror + "\n"; 112.RadWindow.Alert(nm); 113.} 114.} The first 39 lines should be pretty familiar, not doing anything too unorthodox to get this up and running. Once we hit the xAddEditButton_Click on line 40, we're still doing pretty much the same things except instead of checking the ValidationHelper errors, we both run a check on the current activeJob object as well as check the ValidationSummary errors list. Once that is set, we again use the callback of context.SubmitChanges (lines 68 and 78) to create an ActionHistory which we will use to track these items down the line. That's all? Essentially... yes. If you look back through this post, most of the code and adventures we have taken were just to get things working in the MVVM/Prism setup. Since I have the whole 'module' self-contained in a single JobView+code-behind setup, I don't have to worry about things like sending events off into space for someone to pick up, communicating through an Infrastructure project, or even re-inventing events to be used with attached behaviors. Everything just kinda works, and again with much less code. Here's a picture of the MVVM and Code-behind versions on the Jobs and AddEdit views, but since the functionality is the same in both apps you still cannot tell them apart (for two-strike): Looking ahead, the Applicants module is effectively the same thing as the Jobs module, so most of the code is being cut-and-pasted back and forth with minor tweaks here and there. So that one is being taken care of by me behind the scenes. Next time, we get into a new world of fun- the interview scheduling module, which will pull from available jobs and applicants for each interview being scheduled, tying everything together with RadScheduler to the rescue. Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Exception Handling Frequency/Log Detail

    - by Cyborgx37
    I am working on a fairly complex .NET application that interacts with another application. Many single-line statements are possible culprits for throwing an Exception and there is often nothing I can do to check the state before executing them to prevent these Exceptions. The question is, based on best practices and seasoned experience, how frequently should I lace my code with try/catch blocks? I've listed three examples below, but I'm open to any advice. I'm really hoping to get some pros/cons of various approaches. I can certainly come up with some of my own (greater log granularity for the O-C approach, better performance for the Monolithic approach), so I'm looking for experience over opinion. EDIT: I should add that this application is a batch program. The only "recovery" necessary in most cases is to log the error, clean up gracefully, and quit. So this could be seen to be as much a question of log granularity as exception handling. In my mind's eye I can imagine good reasons for both, so I'm looking for some general advice to help me find an appropriate balance. Monolitich Approach class Program{ public static void Main(){ try{ Step1(); Step2(); Step3(); } catch (Exception e) { Log(e); } finally { CleanUp(); } } public static void Step1(){ ExternalApp.Dangerous1(); ExternalApp.Dangerous2(); } public static void Step2(){ ExternalApp.Dangerous3(); ExternalApp.Dangerous4(); } public static void Step3(){ ExternalApp.Dangerous5(); ExternalApp.Dangerous6(); } } Delegated Approach class Program{ public static void Main(){ try{ Step1(); Step2(); Step3(); } finally { CleanUp(); } } public static void Step1(){ try{ ExternalApp.Dangerous1(); ExternalApp.Dangerous2(); } catch (Exception e) { Log(e); throw; } } public static void Step2(){ try{ ExternalApp.Dangerous3(); ExternalApp.Dangerous4(); } catch (Exception e) { Log(e); throw; } } public static void Step3(){ try{ ExternalApp.Dangerous5(); ExternalApp.Dangerous6(); } catch (Exception e) { Log(e); throw; } } } Obsessive-Compulsive Approach class Program{ public static void Main(){ try{ Step1(); Step2(); Step3(); } finally { CleanUp(); } } public static void Step1(){ try{ ExternalApp.Dangerous1(); } catch (Exception e) { Log(e); throw; } try{ ExternalApp.Dangerous2(); } catch (Exception e) { Log(e); throw; } } public static void Step2(){ try{ ExternalApp.Dangerous3(); } catch (Exception e) { Log(e); throw; } try{ ExternalApp.Dangerous4(); } catch (Exception e) { Log(e); throw; } } public static void Step3(){ try{ ExternalApp.Dangerous5(); } catch (Exception e) { Log(e); throw; } try{ ExternalApp.Dangerous6(); } catch (Exception e) { Log(e); throw; } } } Other approaches welcomed and encouraged. Above are examples only.

    Read the article

  • Cumulative +1/-1 Cointoss crashes on 1000 iterations. Please advise; c++ boost random libraries

    - by user1731972
    following some former advice Multithreaded application, am I doing it right? I think I have a threadsafe number generator using boost, but my program crashes when I input 1000 iterations. The output .csv file when graphed looks right, but I'm not sure why it's crashing. It's using _beginthread, and everyone is telling me I should use the more (convoluted) _beingthreadex, which I'm not familiar with. If someone could recommend an example, I would greatly appreciate it. Also... someone pointed out I should be applying a second parameter to my _beginthread for the array counting start positions, but I have no idea how to pass more than one parameter, other than attempting to use a structure, and I've read structure's and _beginthread don't get along (although, I could just use the boost threads...) #include <process.h> #include <windows.h> #include <iostream> #include <fstream> #include <time.h> #include <random> #include <boost/random.hpp> //for srand48_r(time(NULL), &randBuffer); which doesn't work #include <stdio.h> #include <stdlib.h> //#include <thread> using namespace std; using namespace boost; using namespace boost::random; void myThread0 (void *dummy ); void myThread1 (void *dummy ); void myThread2 (void *dummy ); void myThread3 (void *dummy ); //for random seeds void initialize(); //from http://stackoverflow.com/questions/7114043/random-number-generation-in-c11-how-to-generate-how-do-they-work uniform_int_distribution<> two(1,2); typedef std::mt19937 MyRNG; // the Mersenne Twister with a popular choice of parameters uint32_t seed_val; // populate somehow MyRNG rng1; // e.g. keep one global instance (per thread) MyRNG rng2; // e.g. keep one global instance (per thread) MyRNG rng3; // e.g. keep one global instance (per thread) MyRNG rng4; // e.g. keep one global instance (per thread) //only needed for shared variables //CRITICAL_SECTION cs1,cs2,cs3,cs4; // global int main() { ofstream myfile; myfile.open ("coinToss.csv"); int rNum; long numRuns; long count = 0; int divisor = 1; float fHolder = 0; long counter = 0; float percent = 0.0; //? //unsigned threadID; //HANDLE hThread; initialize(); HANDLE hThread[4]; const int size = 100000; int array[size]; printf ("Runs (uses multiple of 100,000) "); cin >> numRuns; for (int a = 0; a < numRuns; a++) { hThread[0] = (HANDLE)_beginthread( myThread0, 0, (void*)(array) ); hThread[1] = (HANDLE)_beginthread( myThread1, 0, (void*)(array) ); hThread[2] = (HANDLE)_beginthread( myThread2, 0, (void*)(array) ); hThread[3] = (HANDLE)_beginthread( myThread3, 0, (void*)(array) ); //waits for threads to finish before continuing WaitForMultipleObjects(4, hThread, TRUE, INFINITE); //closes handles I guess? CloseHandle( hThread[0] ); CloseHandle( hThread[1] ); CloseHandle( hThread[2] ); CloseHandle( hThread[3] ); //dump array into calculations //average array into fHolder //this could be split into threads as well for (int p = 0; p < size; p++) { counter += array[p] == 2 ? 1 : -1; //cout << array[p] << endl; //cout << counter << endl; } //this fHolder calculation didn't work //fHolder = counter / size; //so I had to use this cout << counter << endl; fHolder = counter; fHolder = fHolder / size; myfile << fHolder << endl; } } void initialize() { //seed value needs to be supplied //rng1.seed(seed_val*1); rng1.seed((unsigned int)time(NULL)); rng2.seed(((unsigned int)time(NULL))*2); rng3.seed(((unsigned int)time(NULL))*3); rng4.seed(((unsigned int)time(NULL))*4); }; void myThread0 (void *param) { //EnterCriticalSection(&cs1); //aquire the critical section object int *i = (int *)param; for (int x = 0; x < 25000; x++) { //doesn't work, part of merssene twister //i[x] = next(); i[x] = two(rng1); //original srand //i[x] = rand() % 2 + 1; //doesn't work for some reason. //uint_dist2(rng); //i[x] = qrand() % 2 + 1; //cout << i[x] << endl; } //LeaveCriticalSection(&cs1); // release the critical section object } void myThread1 (void *param) { //EnterCriticalSection(&cs2); //aquire the critical section object int *i = (int *)param; for (int x = 25000; x < 50000; x++) { //param[x] = rand() % 2 + 1; i[x] = two(rng2); //i[x] = rand() % 2 + 1; //cout << i[x] << endl; } //LeaveCriticalSection(&cs2); // release the critical section object } void myThread2 (void *param) { //EnterCriticalSection(&cs3); //aquire the critical section object int *i = (int *)param; for (int x = 50000; x < 75000; x++) { i[x] = two(rng3); //i[x] = rand() % 2 + 1; //cout << i[x] << endl; } //LeaveCriticalSection(&cs3); // release the critical section object } void myThread3 (void *param) { //EnterCriticalSection(&cs4); //aquire the critical section object int *i = (int *)param; for (int x = 75000; x < 100000; x++) { i[x] = two(rng4); //i[x] = rand() % 2 + 1; //cout << i[x] << endl; } //LeaveCriticalSection(&cs4); // release the critical section object }

    Read the article

  • Game Over function is not working Starling

    - by aNgeLyN omar
    I've been following a tutorial over the web but it somehow did not show something about creating a game over function. I am new to the Starling framework and Actionscript so I'm kind of still trying to find a way to make it work. Here's the complete snippet of the code. package screens { import flash.geom.Rectangle; import flash.utils.getTimer; import events.NavigationEvent; import objects.GameBackground; import objects.Hero; import objects.Item; import objects.Obstacle; import starling.display.Button; import starling.display.Image; import starling.display.Sprite; import starling.events.Event; import starling.events.Touch; import starling.events.TouchEvent; import starling.text.TextField; import starling.utils.deg2rad; public class InGame extends Sprite { private var screenInGame:InGame; private var screenWelcome:Welcome; private var startButton:Button; private var playAgain:Button; private var bg:GameBackground; private var hero:Hero; private var timePrevious:Number; private var timeCurrent:Number; private var elapsed:Number; private var gameState:String; private var playerSpeed:Number = 0; private var hitObstacle:Number = 0; private const MIN_SPEED:Number = 650; private var scoreDistance:int; private var obstacleGapCount:int; private var gameArea:Rectangle; private var touch:Touch; private var touchX:Number; private var touchY:Number; private var obstaclesToAnimate:Vector.<Obstacle>; private var itemsToAnimate:Vector.<Item>; private var scoreText:TextField; private var remainingLives:TextField; private var gameOverText:TextField; private var iconSmall:Image; static private var lives:Number = 2; public function InGame() { super(); this.addEventListener(starling.events.Event.ADDED_TO_STAGE, onAddedToStage); } private function onAddedToStage(event:Event):void { this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage); drawGame(); scoreText = new TextField(300, 100, "Score: 0", "MyFontName", 35, 0xD9D919, true); remainingLives = new TextField(600, 100, "Lives: " + lives +" X ", "MyFontName", 35, 0xD9D919, true); iconSmall = new Image(Assets.getAtlas().getTexture("darnahead1")); iconSmall.x = 360; iconSmall.y = 40; this.addChild(iconSmall); this.addChild(scoreText); this.addChild(remainingLives); } private function drawGame():void { bg = new GameBackground(); this.addChild(bg); hero = new Hero(); hero.x = stage.stageHeight / 2; hero.y = stage.stageWidth / 2; this.addChild(hero); startButton = new Button(Assets.getAtlas().getTexture("startButton")); startButton.x = stage.stageWidth * 0.5 - startButton.width * 0.5; startButton.y = stage.stageHeight * 0.5 - startButton.height * 0.5; this.addChild(startButton); gameArea = new Rectangle(0, 100, stage.stageWidth, stage.stageHeight - 250); } public function disposeTemporarily():void { this.visible = false; } public function initialize():void { this.visible = true; this.addEventListener(Event.ENTER_FRAME, checkElapsed); hero.x = -stage.stageWidth; hero.y = stage.stageHeight * 0.5; gameState ="idle"; playerSpeed = 0; hitObstacle = 0; bg.speed = 0; scoreDistance = 0; obstacleGapCount = 0; obstaclesToAnimate = new Vector.<Obstacle>(); itemsToAnimate = new Vector.<Item>(); startButton.addEventListener(Event.TRIGGERED, onStartButtonClick); //var mainStage:InGame =InGame.current.nativeStage; //mainStage.dispatchEvent(new Event(Event.COMPLETE)); //playAgain.addEventListener(Event.TRIGGERED, onRetry); } private function onStartButtonClick(event:Event):void { startButton.visible = false; startButton.removeEventListener(Event.TRIGGERED, onStartButtonClick); launchHero(); } private function launchHero():void { this.addEventListener(TouchEvent.TOUCH, onTouch); this.addEventListener(Event.ENTER_FRAME, onGameTick); } private function onTouch(event:TouchEvent):void { touch = event.getTouch(stage); touchX = touch.globalX; touchY = touch.globalY; } private function onGameTick(event:Event):void { switch(gameState) { case "idle": if(hero.x < stage.stageWidth * 0.5 * 0.5) { hero.x += ((stage.stageWidth * 0.5 * 0.5 + 10) - hero.x) * 0.05; hero.y = stage.stageHeight * 0.5; playerSpeed += (MIN_SPEED - playerSpeed) * 0.05; bg.speed = playerSpeed * elapsed; } else { gameState = "flying"; } break; case "flying": if(hitObstacle <= 0) { hero.y -= (hero.y - touchY) * 0.1; if(-(hero.y - touchY) < 150 && -(hero.y - touchY) > -150) { hero.rotation = deg2rad(-(hero.y - touchY) * 0.2); } if(hero.y > gameArea.bottom - hero.height * 0.5) { hero.y = gameArea.bottom - hero.height * 0.5; hero.rotation = deg2rad(0); } if(hero.y < gameArea.top + hero.height * 0.5) { hero.y = gameArea.top + hero.height * 0.5; hero.rotation = deg2rad(0); } } else { hitObstacle-- cameraShake(); } playerSpeed -= (playerSpeed - MIN_SPEED) * 0.01; bg.speed = playerSpeed * elapsed; scoreDistance += (playerSpeed * elapsed) * 0.1; scoreText.text = "Score: " + scoreDistance; initObstacle(); animateObstacles(); createEggItems(); animateItems(); remainingLives.text = "Lives: "+lives + " X "; if(lives == 0) { gameState = "over"; } break; case "over": gameOver(); break; } } private function gameOver():void { gameOverText = new TextField(800, 400, "Hero WAS KILLED!!!", "MyFontName", 50, 0xD9D919, true); scoreText = new TextField(800, 600, "Score: "+scoreDistance, "MyFontName", 30, 0xFFFFFF, true); this.addChild(scoreText); this.addChild(gameOverText); playAgain = new Button(Assets.getAtlas().getTexture("button_tryAgain")); playAgain.x = stage.stageWidth * 0.5 - startButton.width * 0.5; playAgain.y = stage.stageHeight * 0.75 - startButton.height * 0.75; this.addChild(playAgain); playAgain.addEventListener(Event.TRIGGERED, onRetry); } private function onRetry(event:Event):void { playAgain.visible = false; gameOverText.visible = false; scoreText.visible = false; var btnClicked:Button = event.target as Button; if((btnClicked as Button) == playAgain) { this.dispatchEvent(new NavigationEvent(NavigationEvent.CHANGE_SCREEN, {id: "playnow"}, true)); } disposeTemporarily(); } private function animateItems():void { var itemToTrack:Item; for(var i:uint = 0; i < itemsToAnimate.length; i++) { itemToTrack = itemsToAnimate[i]; itemToTrack.x -= playerSpeed * elapsed; if(itemToTrack.bounds.intersects(hero.bounds)) { itemsToAnimate.splice(i, 1); this.removeChild(itemToTrack); } if(itemToTrack.x < -50) { itemsToAnimate.splice(i, 1); this.removeChild(itemToTrack); } } } private function createEggItems():void { if(Math.random() > 0.95){ var itemToTrack:Item = new Item(Math.ceil(Math.random() * 10)); itemToTrack.x = stage.stageWidth + 50; itemToTrack.y = int(Math.random() * (gameArea.bottom - gameArea.top)) + gameArea.top; this.addChild(itemToTrack); itemsToAnimate.push(itemToTrack); } } private function cameraShake():void { if(hitObstacle > 0) { this.x = Math.random() * hitObstacle; this.y = Math.random() * hitObstacle; } else if(x != 0) { this.x = 0; this.y = 0; lives--; } } private function initObstacle():void { if(obstacleGapCount < 1200) { obstacleGapCount += playerSpeed * elapsed; } else if(obstacleGapCount !=0) { obstacleGapCount = 0; createObstacle(Math.ceil(Math.random() * 5), Math.random() * 1000 + 1000); } } private function animateObstacles():void { var obstacleToTrack:Obstacle; for(var i:uint = 0; i<obstaclesToAnimate.length; i++) { obstacleToTrack = obstaclesToAnimate[i]; if(obstacleToTrack.alreadyHit == false && obstacleToTrack.bounds.intersects(hero.bounds)) { obstacleToTrack.alreadyHit = true; obstacleToTrack.rotation = deg2rad(70); hitObstacle = 30; playerSpeed *= 0.5; } if(obstacleToTrack.distance > 0) { obstacleToTrack.distance -= playerSpeed * elapsed; } else { if(obstacleToTrack.watchOut) { obstacleToTrack.watchOut = false; } obstacleToTrack.x -= (playerSpeed + obstacleToTrack.speed) * elapsed; } if(obstacleToTrack.x < -obstacleToTrack.width || gameState == "over") { obstaclesToAnimate.splice(i, 1); this.removeChild(obstacleToTrack); } } } private function checkElapsed(event:Event):void { timePrevious = timeCurrent; timeCurrent = getTimer(); elapsed = (timeCurrent - timePrevious) * 0.001; } private function createObstacle(type:Number, distance:Number):void{ var obstacle:Obstacle = new Obstacle(type, distance, true, 300); obstacle.x = stage.stageWidth; this.addChild(obstacle); if(type >= 4) { if(Math.random() > 0.5) { obstacle.y = gameArea.top; obstacle.position = "top" } else { obstacle.y = gameArea.bottom - obstacle.height; obstacle.position = "bottom"; } } else { obstacle.y = int(Math.random() * (gameArea.bottom - obstacle.height - gameArea.top)) + gameArea.top; obstacle.position = "middle"; } obstaclesToAnimate.push(obstacle); } } }

    Read the article

  • UITableView crashes when trying to scroll

    - by Ondrej
    Hi, I have a problem with data in UITableView. I have UIViewController, that contains UITableView outlet and few more things I am using and ... It works :) ... it works lovely, but ... I've created an RSS reader class that is using delegates to deploy the data to the table ... and once again, If I'll just create dummy data in the main controller everything works! problem is with this line: rss.delegate = self; Preview looks a little bit broken than here are those RSS reader files on Google code: (Link to the header file on GoogleCode) (Link to the implementation file on Google code) viewDidLoad function of my controller: IGDataRss20 *rss = [[[IGDataRss20 alloc] init] autorelease]; rss.delegate = self; [rss initWithContentsOfUrl:@"http://rss.cnn.com/rss/cnn_topstories.rss"]; and my delegate methods: - (void)parsingEnded:(NSArray *)result { super.data = [[NSMutableArray alloc] initWithArray:result]; NSLog(@"My Items: %d", [super.data count]); [super.table reloadData]; NSLog(@"Parsing ended"); } (void)parsingError:(NSString *)message { NSLog(@"MyMessage: %@", message); } (void)parsingStarted:(NSXMLParser *)parser { NSLog(@"Parsing started"); } Just to clarify, NSLog(@"Parsing ended"); is being executed and I have 10 items in the array. Ok, here's my RSS reader header file: @class IGDataRss20; @protocol IGDataRss20Delegate @optional (void)parsingStarted:(NSXMLParser *)parser; (void)parsingError:(NSString *)message; (void)parsingEnded:(NSArray *)result; @end @interface IGDataRss20 : NSObject { NSXMLParser *rssParser; NSMutableArray *data; NSMutableDictionary *currentItem; NSString *currentElement; id <IGDataRss20Delegate> delegate; } @property (nonatomic, retain) NSMutableArray *data; @property (nonatomic, assign) id delegate; (void)initWithContentsOfUrl:(NSString *)rssUrl; (void)initWithContentsOfData:(NSData *)inputData; @end And this RSS reader implementation file: #import "IGDataRss20.h" @implementation IGDataRss20 @synthesize data, delegate; (void)initWithContentsOfUrl:(NSString *)rssUrl { self.data = [[NSMutableArray alloc] init]; NSURL *xmlURL = [NSURL URLWithString:rssUrl]; rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL]; [rssParser setDelegate:self]; [rssParser setShouldProcessNamespaces:NO]; [rssParser setShouldReportNamespacePrefixes:NO]; [rssParser setShouldResolveExternalEntities:NO]; [rssParser parse]; } (void)initWithContentsOfData:(NSData *)inputData { self.data = [[NSMutableArray alloc] init]; rssParser = [[NSXMLParser alloc] initWithData:inputData]; [rssParser setDelegate:self]; [rssParser setShouldProcessNamespaces:NO]; [rssParser setShouldReportNamespacePrefixes:NO]; [rssParser setShouldResolveExternalEntities:NO]; [rssParser parse]; } (void)parserDidStartDocument:(NSXMLParser *)parser { [[self delegate] parsingStarted:parser]; } (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { NSString * errorString = [NSString stringWithFormat:@"Unable to parse RSS feed (Error code %i )", [parseError code]]; NSLog(@"Error parsing XML: %@", errorString); if ([parseError code] == 31) NSLog(@"Error code 31 is usually caused by encoding problem."); [[self delegate] parsingError:errorString]; } (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { currentElement = [elementName copy]; if ([elementName isEqualToString:@"item"]) currentItem = [[NSMutableDictionary alloc] init]; } (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqualToString:@"item"]) { [data addObject:(NSDictionary *)[currentItem copy]]; } } (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if (![currentItem objectForKey:currentElement]) [currentItem setObject:[[[NSMutableString alloc] init] autorelease] forKey:currentElement]; [[currentItem objectForKey:currentElement] appendString:string]; } (void)parserDidEndDocument:(NSXMLParser *)parser { //NSLog(@"RSS array has %d items: %@", [data count], data); [[self delegate] parsingEnded:(NSArray *)self.data]; } (void)dealloc { [data, delegate release]; [super dealloc]; } @end Hope someone will be able to help me as I am becoming to be quite desperate, and I thought I am not already such a greenhorn :) Thanks, Ondrej

    Read the article

  • Coupling/Cohesion

    - by user559142
    Hi All, Whilst there are many good examples on this forum that contain examples of coupling and cohesion, I am struggling to apply it to my code fully. I can identify parts in my code that may need changing. Would any Java experts be able to take a look at my code and explain to me what aspects are good and bad. I don't mind changing it myself at all. It's just that many people seem to disagree with each other and I'm finding it hard to actually understand what principles to follow... package familytree; /** * * @author David */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here KeyboardInput in = new KeyboardInput(); FamilyTree familyTree = new FamilyTree(in, System.out); familyTree.start(); } } package familytree; import java.io.PrintStream; /** * * @author David */ public class FamilyTree { /** * @param args the command line arguments */ private static final int DISPLAY_FAMILY_MEMBERS = 1; private static final int ADD_FAMILY_MEMBER = 2; private static final int REMOVE_FAMILY_MEMBER = 3; private static final int EDIT_FAMILY_MEMBER = 4; private static final int SAVE_FAMILY_TREE = 5; private static final int LOAD_FAMILY_TREE = 6; private static final int DISPLAY_ANCESTORS = 7; private static final int DISPLAY_DESCENDANTS = 8; private static final int QUIT = 9; private KeyboardInput in; private Family family; private PrintStream out; public FamilyTree(KeyboardInput in, PrintStream out) { this.in = in; this.out = out; family = new Family(); } public void start() { out.println("\nWelcome to the Family Tree Builder"); //enterUserDetails(); initialise(); while (true) { displayFamilyTreeMenu(); out.print("\nEnter Choice: "); int option = in.readInteger(); if (option > 0 && option <= 8) { if (quit(option)) { break; } executeOption(option); } else { out.println("Invalid Choice!"); } } } //good private void displayFamilyTreeMenu() { out.println("\nFamily Tree Menu"); out.println(DISPLAY_FAMILY_MEMBERS + ". Display Family Members"); out.println(ADD_FAMILY_MEMBER + ". Add Family Member"); out.println(REMOVE_FAMILY_MEMBER + ". Remove Family Member"); out.println(EDIT_FAMILY_MEMBER + ". Edit Family Member"); out.println(SAVE_FAMILY_TREE + ". Save Family Tree"); out.println(LOAD_FAMILY_TREE + ". Load Family Tree"); out.println(DISPLAY_ANCESTORS + ". Display Ancestors"); out.println(DISPLAY_DESCENDANTS + ". Display Descendants"); out.println(QUIT + ". Quit"); } //good private boolean quit(int opt) { return (opt == QUIT) ? true : false; } //good private void executeOption(int choice) { switch (choice) { case DISPLAY_FAMILY_MEMBERS: displayFamilyMembers(); break; case ADD_FAMILY_MEMBER: addFamilyMember(); break; case REMOVE_FAMILY_MEMBER: break; case EDIT_FAMILY_MEMBER: break; case SAVE_FAMILY_TREE: break; case LOAD_FAMILY_TREE: break; case DISPLAY_ANCESTORS: displayAncestors(); break; case DISPLAY_DESCENDANTS: displayDescendants(); break; default: out.println("Not a valid option! Try again."); break; } } //for selecting family member for editing adding nodes etc private void displayFamilyMembers() { out.println("\nDisplay Family Members"); int count = 0; for (FamilyMember member : family.getFamilyMembers()) { out.println(); if (count + 1 < 10) { out.println((count + 1) + ". " + member.getFirstName() + " " + member.getLastName()); out.println(" " + member.getDob()); out.println(" Generation: " + member.getGeneration()); } else { out.println((count + 1) + ". " + member.getFirstName() + " " + member.getLastName()); out.println(" " + member.getDob()); out.println(" Generation: " + member.getGeneration()); } count++; } } private int selectRelative() { out.println("\nSelect Relative"); out.println("1. Add Parents"); out.println("2. Add Child"); out.println("3. Add Partner"); out.println("4. Add Sibling"); out.print("\nEnter Choice: "); int choice = in.readInteger(); if (choice > 0 && choice < 5) { return choice; } return (-1); } private void addFamilyMember() { int memberIndex = selectMember(); if (memberIndex >= 0) { FamilyMember member = family.getFamilyMember(memberIndex); int relative = selectRelative(); if (relative > 0) { out.println("\nAdd Member"); //if choice is valid switch (relative) { case 1: //adding parents if (member.getFather() == null) { FamilyMember mum, dad; out.println("Enter Mothers Details"); mum = addMember(relative, "Female"); out.println("\nEnter Fathers Details"); dad = addMember(relative, "Male"); member.linkParent(mum); member.linkParent(dad); mum.linkPartner(dad); mum.setGeneration(member.getGeneration() - 1); dad.setGeneration(member.getGeneration() - 1); sortGenerations(); } else { out.println(member.getFirstName() + " " + member.getLastName() + " already has parents."); } break; case 2: //adding child if (member.getPartner() == null) { FamilyMember partner; if (member.getGender().equals("Male")) { out.println("Enter Mothers Details"); partner = addMember(1, "Female"); } else { out.println("Enter Fathers Details"); partner = addMember(1, "Male"); } //create partner member.linkPartner(partner); partner.setGeneration(member.getGeneration()); out.println(); } out.println("Enter Childs Details"); FamilyMember child = addMember(relative, ""); child.linkParent(member); child.linkParent(member.getPartner()); child.setGeneration(member.getGeneration() + 1); sortGenerations(); break; case 3: //adding partner if (member.getPartner() == null) { out.println("Enter Partners Details"); FamilyMember partner = addMember(relative, ""); member.linkPartner(partner); partner.setGeneration(member.getGeneration()); } else { out.println(member.getFirstName() + " " + member.getLastName() + " already has a partner."); } break; case 4: //adding sibling FamilyMember mum, dad; if (member.getFather() == null) { out.println("Enter Mothers Details"); mum = addMember(1, "Female"); out.println("\nEnter Fathers Details"); dad = addMember(1, "Male"); member.linkParent(mum); member.linkParent(dad); mum.linkPartner(dad); mum.setGeneration(member.getGeneration() - 1); dad.setGeneration(member.getGeneration() - 1); sortGenerations(); out.println("\nEnter Siblings Details"); } else { out.println("Enter Siblings Details"); } FamilyMember sibling = addMember(relative, ""); //create mum and dad mum = member.getMother(); dad = member.getFather(); sibling.linkParent(mum); sibling.linkParent(dad); sibling.setGeneration(member.getGeneration()); break; } } else { out.println("Invalid Option!"); } } else { out.println("Invalid Option!"); } } private int selectMember() { displayFamilyMembers(); out.print("\nSelect Member: "); int choice = in.readInteger(); if (choice > 0 && choice <= family.getFamilyMembers().size()) { return (choice - 1); } return -1; } private FamilyMember addMember(int option, String gender) { out.print("Enter First Name: "); String fName = formatString(in.readString().trim()); out.print("Enter Last Name: "); String lName = formatString(in.readString().trim()); if (option != 1) { //if not adding parents out.println("Select Gender"); out.println("1. Male"); out.println("2. Female"); out.print("Enter Choice: "); int gOpt = in.readInteger(); if (gOpt == 1) { gender = "Male"; } else if (gOpt == 2) { gender = "Female"; } else { out.println("Invalid Choice"); return null; } } String dob = enterDateOfBirth(); lName = formatString(lName); FamilyMember f = family.getFamilyMember(family.addMember(fName, lName, gender, dob)); f.setIndex(family.getFamilyMembers().size() - 1); return (f); } private String formatString(String s){ String firstLetter = s.substring(0, 1); String remainingLetters = s.substring(1, s.length()); s = firstLetter.toUpperCase() + remainingLetters.toLowerCase(); return s; } private String enterDateOfBirth(){ out.print("Enter Year Of Birth (0 - 2011): "); String y = in.readString(); out.print("Enter Month Of Birth (1-12): "); String m = in.readString(); if (Integer.parseInt(m) < 10) { m = "0" + m; } m += "-"; out.print("Enter Date of Birth (1-31): "); String d = in.readString(); if (Integer.parseInt(d) < 10) { d = "0" + d; } d += "-"; String dob = d + m + y; while(!DateValidator.isValid(dob)){ out.println("Invalid Date. Try Again:"); dob = enterDateOfBirth(); } return (dob); } private void displayAncestors() { out.print("\nDisplay Ancestors For Which Member: "); int choice = selectMember(); if (choice >= 0) { FamilyMember node = family.getFamilyMember(choice ); FamilyMember ms = findRootNode(node, 0, 2, -1); FamilyMember fs = findRootNode(node, 1, 2, -1); out.println("\nPrint Ancestors"); out.println("\nMothers Side"); printDescendants(ms, node, ms.getGeneration()); out.println("\nFathers Side"); printDescendants(fs, node, fs.getGeneration()); } else { out.println("Invalid Option!"); } } private void displayDescendants() { out.print("\nDisplay Descendants For Which Member: "); int choice = selectMember(); if (choice >= 0) { FamilyMember node = family.getFamilyMember(choice); out.println("\nPrint Descendants"); printDescendants(node, null, 0); } else { out.println("Invalid Option!"); } } private FamilyMember findRootNode(FamilyMember node, int parent, int numGenerations, int count) { FamilyMember root; count++; if (node.hasParents() && count < numGenerations) { if (parent == 0) { node = node.getMother(); root = findRootNode(node, 1, numGenerations, count); } else { node = node.getFather(); root = findRootNode(node, 1, numGenerations, count); } return root; } return node; } private int findHighestLeafGeneration(FamilyMember node) { int gen = node.getGeneration(); for (int i = 0; i < node.getChildren().size(); i++) { int highestChild = findHighestLeafGeneration(node.getChild(i)); if (highestChild > gen) { gen = highestChild; } } return gen; } private void printDescendants(FamilyMember root, FamilyMember node, int gen) { out.print((root.getGeneration() + 1) + " " + root.getFullName()); out.print(" [" + root.getDob() + "] "); if (root.getPartner() != null) { out.print("+Partner: " + root.getPartner().getFullName() + " [" + root.getPartner().getDob() + "] "); } if (root == node) { out.print("*"); } out.println(); if (!root.getChildren().isEmpty() && root != node) { for (int i = 0; i < root.getChildren().size(); i++) { for (int j = 0; j < root.getChild(i).getGeneration() - gen; j++) { out.print(" "); } printDescendants(root.getChild(i), node, gen); } } else { return; } } //retrieve highest generation public int getRootGeneration(){ int min = family.getFamilyMember(0).getGeneration(); for(int i = 0; i < family.getFamilyMembers().size(); i++){ min = Math.min(min, family.getFamilyMember(i).getGeneration()); } return Math.abs(min); } public void sortGenerations(){ int amount = getRootGeneration(); for (FamilyMember member : family.getFamilyMembers()) { member.setGeneration(member.getGeneration() + amount); } } //test method - temporary private void initialise() { family.addMember("Bilbo", "Baggins", "Male", "23-06-1920"); } } package familytree; import java.util.ArrayList; import java.util.Date; /** * * @author David */ public class Family { //family members private ArrayList<FamilyMember> family; //create Family public Family() { family = new ArrayList<FamilyMember>(); } //add member to the family public int addMember(String f, String l, String g, String d) { family.add(new FamilyMember(f, l, g, d)); return family.size()-1; } //remove member from family public void removeMember(int index) { family.remove(index); } public FamilyMember getFamilyMember(int index) { return family.get(index); } //return family public ArrayList <FamilyMember> getFamilyMembers() { return family; } public void changeFirstName(int index, String f) { family.get(index).setFirstName(f);//change to setfirstname and others } public void changeLastName(int index, String l) { family.get(index).setLastName(l); } public void changeAge(int index, int a) { family.get(index).setAge(a); } public void changeDOB() { //implement } } package familytree; import java.util.ArrayList; import java.util.Collections; /** * * @author David */ public class FamilyMember extends Person { private FamilyMember mother; private FamilyMember father; private FamilyMember partner; private ArrayList<FamilyMember> children; private int generation; private int index; //initialise family member public FamilyMember(String f, String l, String g, String d) { super(f, l, g, d); mother = null; father = null; partner = null; children = new ArrayList<FamilyMember>(); generation = 0; index = -1; } public void linkParent(FamilyMember parent) { if (parent.getGender().equals("Female")) { this.setMother(parent); } else { this.setFather(parent); } parent.addChild(this); } public void linkPartner(FamilyMember partner) { partner.setPartner(this); this.setPartner(partner); } public boolean hasParents() { if (this.getMother() == null && this.getFather() == null) { return false; } return true; } public FamilyMember getMother() { return mother; } public FamilyMember getFather() { return father; } public FamilyMember getPartner() { return partner; } public FamilyMember getChild(int index) { return children.get(index); } public int getGeneration() { return generation; } public int getIndex() { return index; } public ArrayList<FamilyMember> getChildren() { return children; } public void setMother(FamilyMember f) { mother = f; } public void setFather(FamilyMember f) { father = f; } public void setPartner(FamilyMember f) { partner = f; } public void addChild(FamilyMember f) { children.add(f); //add child if(children.size() > 1){ //sort in ascending order Collections.sort(children, new DateComparator()); } } public void addChildAt(FamilyMember f, int index) { children.set(index, f); } public void setGeneration(int g) { generation = g; } public void setIndex(int i){ index = i; } } package familytree; /** * * @author David */ public class Person{ private String fName; private String lName; private String gender; private int age; private String dob; public Person(String fName, String lName, String gender, String dob){ this.fName = fName; this.lName = lName; this.gender = gender; this.dob = dob; } public String getFullName(){ return (this.fName + " " + this.lName); } public String getFirstName(){ return (fName); } public String getLastName(){ return (lName); } public String getGender(){ return (gender); } public String getDob(){ return dob; } public int getAge(){ return age; } public void setFirstName(String fName){ this.fName = fName; } public void setLastName(String lName){ this.lName = lName; } public void setGender(String gender){ this.gender = gender; } public void setAge(int age){ this.age = age; } }

    Read the article

  • Asynchronuos callback saves value but prints FAILED

    - by sprasad12
    Hi, I am using nested Asynchronous callbacks to save my front-end data to the back-end database. The data is being save into the tables the way i want them to, but it is printing that it failed. Here is the code: oksave.addClickHandler(new ClickHandler(){ public void onClick(ClickEvent event) { if(erasync == null) erasync = GWT.create(EntityRelationService.class); AsyncCallback<Void> callback = new AsyncCallback<Void>(){ public void onFailure(Throwable caught) { String msg = caught.getLocalizedMessage(); if (caught instanceof NotFoundException) { msg = ((NotFoundException) caught).getType() + ((NotFoundException) caught).getMessage(); } System.out.println("Failed" + msg); } public void onSuccess(Void result) { Label success = new Label("Name : " + pname.getText() + " was successfully saved"); Button close = new Button("close"); VerticalPanel sp = new VerticalPanel(); d1 = new DialogBox(); sp.add(success); sp.add(close); close.addClickHandler(new ClickHandler(){ @Override public void onClick(ClickEvent event) { if(erasync == null) erasync = GWT.create(EntityRelationService.class); AsyncCallback<Void> callbackOthers = new AsyncCallback<Void>(){ @Override public void onFailure(Throwable caught) { String msg = caught.getLocalizedMessage(); if (caught instanceof NotFoundException) { msg = ((NotFoundException) caught).getType() + ((NotFoundException) caught).getMessage(); } System.out.println("Failed" + msg); } @Override public void onSuccess(Void result) { System.out.println("Success"); } }; erasync.setEntityType(name, top, left, pname, callbackOthers); }); }; erasync.setProject(name, callback); }); Here it prints successful for the first callback, but for the nested one it says failed though it saves the value. Am i missing something? Any input will be of great help. Thank you.

    Read the article

  • Boost bind with asio::placeholders::error

    - by Leandro
    Why it doesn't work? --- boost_bind.cc --- #include #include #include void func1 (const int& i) { } void func2 (const ::asio::error_code& e) { } int main () { ::boost::function f1 = ::boost::bind (&func1, 1); // it doesn't work! ::boost::function f2 = ::boost::bind (&func2, ::asio::placeholders::error); return 0; } This is the error: while_true@localhost:~ g++ -lpthread boost_bind.cc -o boost_bind In file included from boost_bind.cc:2: /usr/include/boost/bind.hpp: In member function ‘void boost::_bi::list1::operator()(boost::_bi::type, F&, A&, int) [with F = void (*)(const asio::error_code&), A = boost::_bi::list0, A1 = boost::arg (*)()]’: /usr/include/boost/bind/bind_template.hpp:20: instantiated from ‘typename boost::_bi::result_traits::type boost::_bi::bind_t::operator()() [with R = void, F = void (*)(const asio::error_code&), L = boost::_bi::list1 (*)()]’ /usr/include/boost/function/function_template.hpp:152: instantiated from ‘static void boost::detail::function::void_function_obj_invoker0::invoke(boost::detail::function::function_buffer&) [with FunctionObj = boost::_bi::bind_t (*)() , R = void]’ /usr/include/boost/function/function_template.hpp:904: instantiated from ‘void boost::function0::assign_to(Functor) [with Functor = boost::_bi::bind_t (*)() , R = void]’ /usr/include/boost/function/function_template.hpp:720: instantiated from ‘boost::function0::function0(Functor, typename boost::enable_if_c::type) [with Functor = boost::_bi::bind_t (*)() , R = void]’ /usr/include/boost/function/function_template.hpp:1040: instantiated from ‘boost::function::function(Functor, typename boost::enable_if_c::type) [with Functor = boost::_bi::bind_t (*)() , R = void]’ boost_bind.cc:14: instantiated from here /usr/include/boost/bind.hpp:232: error: no match for ‘operator[]’ in ‘a[boost::_bi::storage1 (*)()::a1_ [with int I = 1]]’ while_true@localhost:~

    Read the article

  • C++ LNK2019 error with constructors and destructors in derived classes

    - by BLH
    I have two classes, one inherited from the other. When I compile, I get the following errors: 1Entity.obj : error LNK2019: unresolved external symbol "public: __thiscall Utility::Parsables::Base::Base(void)" (??0Base@Parsables@Utility@@QAE@XZ) referenced in function "public: __thiscall Utility::Parsables::Entity::Entity(void)" (??0Entity@Parsables@Utility@@QAE@XZ) 1Entity.obj : error LNK2019: unresolved external symbol "public: virtual __thiscall Utility::Parsables::Base::~Base(void)" (??1Base@Parsables@Utility@@UAE@XZ) referenced in function "public: virtual __thiscall Utility::Parsables::Entity::~Entity(void)" (??1Entity@Parsables@Utility@@UAE@XZ) 1D:\Programming\Projects\Caffeine\Debug\Caffeine.exe : fatal error LNK1120: 2 unresolved externals I really can't figure out what's going on.. can anyone see what I'm doing wrong? I'm using Visual C++ Express 2008. Here are the files.. "include/Utility/Parsables/Base.hpp" #ifndef CAFFEINE_UTILITY_PARSABLES_BASE_HPP #define CAFFEINE_UTILITY_PARSABLES_BASE_HPP namespace Utility { namespace Parsables { class Base { public: Base( void ); virtual ~Base( void ); }; } } #endif //CAFFEINE_UTILITY_PARSABLES_BASE_HPP "src/Utility/Parsables/Base.cpp" #include "Utility/Parsables/Base.hpp" namespace Utility { namespace Parsables { Base::Base( void ) { } Base::~Base( void ) { } } } "include/Utility/Parsables/Entity.hpp" #ifndef CAFFEINE_UTILITY_PARSABLES_ENTITY_HPP #define CAFFEINE_UTILITY_PARSABLES_ENTITY_HPP #include "Utility/Parsables/Base.hpp" namespace Utility { namespace Parsables { class Entity : public Base { public: Entity( void ); virtual ~Entity( void ); }; } } #endif //CAFFEINE_UTILITY_PARSABLES_ENTITY_HPP "src/Utility/Parsables/Entity.cpp" #include "Utility/Parsables/Entity.hpp" namespace Utility { namespace Parsables { Entity::Entity( void ) { } Entity::~Entity( void ) { } } }

    Read the article

  • How does void QTableWidget::setItemPrototype ( const QTableWidgetItem * item ) clones objects?

    - by chappar
    QTableWidget::setItemPrototype says following. "The table widget will use the item prototype clone function when it needs to create a new table item. For example when the user is editing in an empty cell. This is useful when you have a QTableWidgetItem subclass and want to make sure that QTableWidget creates instances of your subclass." How does this actually work as you can pass any of the QTableWidgetItem subclass pointer to setItemPrototype and at run time there is no way you can get the size of an object having just pointer to it?

    Read the article

  • Generate java class and call it's method dynamically

    - by Jacob
    package reflection; import java.io.*; import java.lang.reflect.*; class class0 { public void writeout0() { System.out.println("class0"); } } class class1 { public void writeout1() { System.out.println("class1"); } } class class2 { public void writeout2() { System.out.println("class2"); } } class class3 { public void run() { try { BufferedReader reader= new BufferedReader(new InputStreamReader (System.in)); String line=reader.readLine(); Class cls=Class.forName(line); //define method here } catch(Exception ee) { System.out.println("here "+ee); } } public void writeout3() { System.out.println("class3"); } } class class4 { public void writeout4() { System.out.println("class4"); } } class class5 { public void writeout5() { System.out.println("class5"); } } class class6 { public void writeout6() { System.out.println("class6"); } } class class7 { public void writeout7() { System.out.println("class7"); } } class class8 { public void writeout8() { System.out.println("class8"); } } class class9 { public void writeout9() { System.out.println("class9"); } } class testclass { public static void main(String[] args) { System.out.println("Write class name : "); class3 example=new class3(); example.run(); } } Question is ; third class will read the name of the class as String from console. Upon reading the name of the class, it will automatically and dynamically generate that class and call its writeout method.If that class is not read from input, it will not be initialized. but I can't continue any more ; i need to more something for 3.class, what can i do? Thanks;

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >