Search Results

Search found 9929 results on 398 pages for 'self destruction'.

Page 16/398 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • Retrieving text from password field [python][pyqt4]

    - by Dr. Johnson
    def welcomeStage (self): self.test = QtGui.QLineEdit (self) self.test.move (50, 150) QtCore.QObject.connect (self.test, QtCore.SIGNAL ('returnPressed()'), self.passwordStage) def passwordStage (self): self.email = self.test.text() self.test.clear() self.test.setEchoMode (QtGui.QLineEdit.Password) QtCore.QObject.connect (self.test, QtCore.SIGNAL ('returnPressed()'), self.loginStage) def loginStage (self): self.pwd = self.test.text() print self.pwd if len (self.pwd) < 0: welcomeStage () return Simply put, I am making a login form. The user enters their email, then the text field is cleared and echo mode is set to Password mode. The text() function returns the email fine, but when I call text() after I have changed the echo mode, it returns 0. I've been pouring over the documentation looking for anything regarding the text() function and how it operates when Password mode is on, however I have not found anything. Does anybody know how this is done?

    Read the article

  • Can using Chronic impair your sense of time?

    - by Trip
    Haha.. I'm using Chronic to parse the time users add in the Calendar. Where the code works and implements the right time, the end result is that, IF a user adds a time, then it has no date, and because it has no date, it will not show in results. Any ideas? def set_dates unless self.natural_date.blank? || Chronic.parse(self.natural_date).blank? # check if we are dealing with a date or a date + time if time_provided?(self.natural_date) self.date = nil self.time = Chronic.parse(self.natural_date) else self.date = Chronic.parse(self.natural_date).to_date self.time = nil end end unless self.natural_end_date.blank? || Chronic.parse(self.natural_end_date).blank? # check if we are dealing with a date or a date + time if time_provided?(self.natural_end_date) self.end_date = nil self.end_time = Chronic.parse(self.natural_end_date) else self.end_date = Chronic.parse(self.natural_end_date).to_date self.end_time = nil end end end Edit: Here is the time_provided? method: def time_provided?(natural_date_string) date_span = Chronic.parse(natural_date_string, :guess => false) (date_span.last - date_span.first).to_i == 1 end

    Read the article

  • Can using Chronic impair you sense of time?

    - by Trip
    Haha.. I'm using Chronic to parse the time users add in the Calendar. Where the code works and implements the right time, the end result is that, IF a user adds a time, then it has no date, and because it has no date, it will not show in results. Any ideas? def set_dates unless self.natural_date.blank? || Chronic.parse(self.natural_date).blank? # check if we are dealing with a date or a date + time if time_provided?(self.natural_date) self.date = nil self.time = Chronic.parse(self.natural_date) else self.date = Chronic.parse(self.natural_date).to_date self.time = nil end end unless self.natural_end_date.blank? || Chronic.parse(self.natural_end_date).blank? # check if we are dealing with a date or a date + time if time_provided?(self.natural_end_date) self.end_date = nil self.end_time = Chronic.parse(self.natural_end_date) else self.end_date = Chronic.parse(self.natural_end_date).to_date self.end_time = nil end end end

    Read the article

  • Need Directions to become a programmer [closed]

    - by Omin
    Before youguys go on about how there are many types of programmers, please read through the post. Long term goal: Develop my own software (company) Short term goal: Get a job that involves coding/programming Current status: Support Analyst (at a software company but does not involve any programming) with 40k salary, 3rd year computer engineering student I had everything figured out. I'm going to develop a 2D scrolling game for iphone or android, publish the app, sell a bunch, and then apply at a studios as a software developer. And then something hit me. I think I need to get a job that involes programming to learn as much as I can in the shortest time possible. So I got a phone interview at a fast growing start up software company, passed that no problem, but then had to take an online technical assessment. That failed miserably. I thought that if I could just present myself, show that I am hard working, positive attitude, eager to make self improvements, type of a guy, I could get the job. I was wrong. And now, I am lost. Im thinking of staying with my job until I find a new one as a programmer. I will be working, self studying, and trying to make this happen without finishing university. I forgot to mention that the online technical assessment was based on data structures/algorithms, OO design, runtime complexity. I was hoping that I could get some guidence. Should I be focusing on app development or study computer science fundamentals? I have a list of books I can be going through: Learning C# O'Reilly (I got interested in C# because of Unity3D and Mono), C# 5.0 in a Nutshell, Head First Design Patterns, Code Complete, Introduction to Algorithms, Programming Interviews Exposed, Cracking the Coding Interview, The Google Resume.

    Read the article

  • Cant connect to mysql using self signed SSL certificate

    - by carpii
    After creating a self-signed SSL certificate, I have configured my remote mysqld to use them (and ssl is enabled) I ssh into my remote server, and try connecting to its own mysqld using ssl (mysql server is 5.5.25).. ~> mysql -u <user> -p --ssl=1 --ssl-cert=client.cert --ssl-key=client.key --ssl-ca=ca.cert Enter password: ERROR 2026 (HY000): SSL connection error: error:00000001:lib(0):func(0):reason(1) Ok, I remember reading theres some problem with connecting to the same server via SSL. So I download the client keys down to my local box, and test from there... ~> mysql -h <server> -u <user> -p --ssl=1 --ssl-cert=client.cert --ssl-key=client.key --ssl-ca=ca.cert Enter password: ERROR 2026 (HY000): SSL connection error Its unclear what this "SSL connection error" error refers to, but if I omit the -ssl-ca, then I am able to connect using SSL.. ~> mysql -h <server> -u <user> -p --ssl=1 --ssl-cert=client.cert --ssl-key=client.key Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 37 Server version: 5.5.25 MySQL Community Server (GPL) However, I believe that this is only encrypting the connection, and not actually verifying the validity of the cert (meaning I would be potentially vulnerable to man-in-middle attack) The ssl certs are valid (albeit self signed), and do not have a passphrase on them So my question is, what am I doing wrong? How can I connect via SSL, using a self signed certificate? MySQL Server version is 5.5.25 and the server and clients are Centos 5 Thanks for any advice Edit: Note that in all cases, the command is being issued from the same directory where the ssl keys reside (hence no absolute path)

    Read the article

  • Simple iOS glDrawElements - BAD_ACCESS

    - by user699215
    You can copy paste this into the default OpenGl template created in Xcode. Why am I not seeing anything :-) It is strange as the glDrawArrays(GL_TRIANGLES, 0, 3); is working fine, but with glDrawElements(GL_TRIANGLE_STRIP, sizeof(indices)/sizeof(GLubyte), GL_UNSIGNED_BYTE, indices); Is giving BAD_ACCESS? Copy paste this into Xcode default OpenGl template: ViewController #import "ViewController.h" #define BUFFER_OFFSET(i) ((char *)NULL + (i)) // Uniform index. enum { UNIFORM_MODELVIEWPROJECTION_MATRIX, UNIFORM_NORMAL_MATRIX, NUM_UNIFORMS }; GLint uniforms[NUM_UNIFORMS]; // Attribute index. enum { ATTRIB_VERTEX, ATTRIB_NORMAL, NUM_ATTRIBUTES }; @interface ViewController () { GLKMatrix4 _modelViewProjectionMatrix; GLKMatrix3 _normalMatrix; float _rotation; GLuint _vertexArray; GLuint _vertexBuffer; NSArray* arrayOfVertex; } @property (strong, nonatomic) EAGLContext *context; @property (strong, nonatomic) GLKBaseEffect *effect; - (void)setupGL; - (void)tearDownGL; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2]; GLKView *view = (GLKView *)self.view; view.context = self.context; view.drawableDepthFormat = GLKViewDrawableDepthFormat24; [self setupGL]; } - (void)dealloc { [self tearDownGL]; if ([EAGLContext currentContext] == self.context) { [EAGLContext setCurrentContext:nil]; } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; if ([self isViewLoaded] && ([[self view] window] == nil)) { self.view = nil; [self tearDownGL]; if ([EAGLContext currentContext] == self.context) { [EAGLContext setCurrentContext:nil]; } self.context = nil; } // Dispose of any resources that can be recreated. } GLuint vertexBufferID; GLuint indexBufferID; static const GLfloat vertices[9] = { -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5 }; static const GLubyte indices[3] = { 0, 1, 2 }; - (void)setupGL { [EAGLContext setCurrentContext:self.context]; // [self loadShaders]; self.effect = [[GLKBaseEffect alloc] init]; self.effect.light0.enabled = GL_TRUE; self.effect.light0.diffuseColor = GLKVector4Make(1.0f, 0.4f, 0.4f, 1.0f); glEnable(GL_DEPTH_TEST); // glGenVertexArraysOES(1, &_vertexArray); // glBindVertexArrayOES(_vertexArray); glGenBuffers(1, &vertexBufferID); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glGenBuffers(1, &indexBufferID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glEnableVertexAttribArray(GLKVertexAttribPosition); glVertexAttribPointer(GLKVertexAttribPosition, // Specifies the index of the generic vertex attribute to be modified. 3, // Specifies the number of components per generic vertex attribute. Must be 1, 2, 3, 4. GL_FLOAT, // GL_FALSE, // 0, // BUFFER_OFFSET(0)); // // glBindVertexArrayOES(0); } - (void)tearDownGL { [EAGLContext setCurrentContext:self.context]; glDeleteBuffers(1, &_vertexBuffer); glDeleteVertexArraysOES(1, &_vertexArray); self.effect = nil; } #pragma mark - GLKView and GLKViewController delegate methods - (void)update { float aspect = fabsf(self.view.bounds.size.width / self.view.bounds.size.height); GLKMatrix4 projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(65.0f), aspect, 0.1f, 100.0f); self.effect.transform.projectionMatrix = projectionMatrix; GLKMatrix4 baseModelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -4.0f); baseModelViewMatrix = GLKMatrix4Rotate(baseModelViewMatrix, _rotation, 0.0f, 1.0f, 0.0f); // Compute the model view matrix for the object rendered with GLKit GLKMatrix4 modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -1.5f); modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, _rotation, 1.0f, 1.0f, 1.0f); modelViewMatrix = GLKMatrix4Multiply(baseModelViewMatrix, modelViewMatrix); self.effect.transform.modelviewMatrix = modelViewMatrix; // Compute the model view matrix for the object rendered with ES2 modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, 1.5f); modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, _rotation, 1.0f, 1.0f, 1.0f); modelViewMatrix = GLKMatrix4Multiply(baseModelViewMatrix, modelViewMatrix); _normalMatrix = GLKMatrix3InvertAndTranspose(GLKMatrix4GetMatrix3(modelViewMatrix), NULL); _modelViewProjectionMatrix = GLKMatrix4Multiply(projectionMatrix, modelViewMatrix); _rotation += self.timeSinceLastUpdate * 0.5f; } int i; - (void)glkView:(GLKView *)view drawInRect:(CGRect)rect { glClearColor(0.65f, 0.65f, 0.65f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // glBindVertexArrayOES(_vertexArray); // Render the object with GLKit [self.effect prepareToDraw]; //glDrawArrays(GL_TRIANGLES, 0, 3); // Render the object again with ES2 // glDrawArrays(GL_TRIANGLES, 0, 3); glDrawElements(GL_TRIANGLE_STRIP, sizeof(indices)/sizeof(GLubyte), GL_UNSIGNED_BYTE, indices); } @end

    Read the article

  • Scrolling a canvas as a shape you're moving approaches its edges

    - by Steven Sproat
    Hi, I develop a Python-based drawing program, Whyteboard. I have tools that the user can create new shapes on the canvas, such as text/images/rectangles/circles/polygons. I also have a Select tool that allows the users to modify these shapes - for example, moving a shape's position, resizing, or editing polygon's points' positions. I'm adding in a new feature where moving or resizing a point near the canvas edge will automatically scroll the canvas. I think it's a good idea in terms of program usability, and annoys me when other program's don't have this feature. I've made some good progress on coding this; below is some Python code to demonstrate what I'm doing. These functions demonstrate how some shapes calculate their "edges": def find_edges(self): """A line.""" self.edges = {EDGE_TOP: min(self.y, self.y2), EDGE_RIGHT: max(self.x, self.x2), EDGE_BOTTOM: max(self.y, self.y2), EDGE_LEFT: min(self. x, self.x2)} def find_edges(self): """An image""" self.edges = {EDGE_TOP: self.y, EDGE_RIGHT: self.x + self.image.GetWidth(), EDGE_BOTTOM: self.y + self.image.GetWidth(), EDGE_LEFT: self.x} def find_edges(self): """Get the bounding rectangle for the polygon""" xmin = min(x for x, y in self.points) ymin = min(y for x, y in self.points) xmax = max(x for x, y in self.points) ymax = max(y for x, y in self.points) self.edges = {EDGE_TOP: ymin, EDGE_RIGHT: xmax, EDGE_BOTTOM: ymax, EDGE_LEFT: xmin} And here's the code I have so far to implement the scrolling when a shape nears the edge: def check_canvas_scroll(self, x, y, moving=False): """ We check that the x/y coords are within 50px from the edge of the canvas and scroll the canvas accordingly. If the shape is being moved, we need to check specific edges of the shape (e.g. left/right side of rectangle) """ size = self.board.GetClientSizeTuple() # visible area of the canvas if not self.board.area > size: # canvas is too small to need to scroll return start = self.board.GetViewStart() # user's starting "viewport" scroll = (-1, -1) # -1 means no change if moving: if self.shape.edges[EDGE_RIGHT] > start[0] + size[0] - 50: scroll = (start[0] + 5, -1) if self.shape.edges[EDGE_BOTTOM] > start[1] + size[1] - 50: scroll = (-1, start[1] + 5) # snip others else: if x > start[0] + size[0] - 50: scroll = (start[0] + 5, -1) if y > start[1] + size[1] - 50: scroll = (-1, start[1] + 5) # snip others self.board.Scroll(*scroll) This code actually works pretty well. If we're moving a shape, then we need to know its edges to calculate when they're coming close to the canvas edge. If we're resizing just a single point, then we just use the x/y coords of that point to see if it's close to the edge. The problem I'm having is a little tricky to describe - basically, if you move a shape to the left, and stop moving it, if you positioned the shape within the 50px from the canvas, then the next time you go to move the shape, the code that says "ok, is this shape close to the end?" gets triggered, and the canvas scrolls to the left, even if you're moving the shape to the right. Can anyone think on how to stop this? I created a youtube video to demonstrate the issue. At about 0:54, I move a polygon to the left of the canvas and position it there. The next time I move it, the canvas scrolls to the left even though I'm moving it right Another thing I'd like to add, but I'm stuck on is the scroll gaining momentum the longer a shape is scrolling? So, with a large canvas, you're not moving a shape for ages, moving 5px at a time, when you need to cover a 2000px distance. Any suggestions there? Thanks all - sorry for the super long question!

    Read the article

  • Accessing multiple view controllers in page controller

    - by Apple Delegates
    I am showing view in ipad like a book, single view shows two view. I want to add more views so that when view flipped third and fourth view appears and further. I am using the code below to do so. I am adding ViewControllers to array it got kill at orientation method at this line " ContentViewController *currentViewController = [self.pageViewController.viewControllers objectAtIndex:0];". - (void)viewDidLoad { [super viewDidLoad]; //Instantiate the model array self.modelArray = [[NSMutableArray alloc] init]; for (int index = 1; index <= 12 ; index++) { [self.modelArray addObject:[NSString stringWithFormat:@"Page %d",index]]; } //Step 1 //Instantiate the UIPageViewController. self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil]; //Step 2: //Assign the delegate and datasource as self. self.pageViewController.delegate = self; self.pageViewController.dataSource = self; //Step 3: //Set the initial view controllers. ViewOne *one = [[ViewOne alloc]initWithNibName:@"ViewOne" bundle:nil]; viewTwo *two = [[viewTwo alloc]initWithNibName:@"ViewTwo" bundle:nil]; ContentViewController *contentViewController = [[ContentViewController alloc] initWithNibName:@"ContentViewController" bundle:nil]; contentViewController.labelContents = [self.modelArray objectAtIndex:0]; // NSArray *viewControllers = [NSArray arrayWithObject:contentViewController]; viewControllers = [NSArray arrayWithObjects:contentViewController,one,two,nil]; [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil]; //Step 4: //ViewController containment steps //Add the pageViewController as the childViewController [self addChildViewController:self.pageViewController]; //Add the view of the pageViewController to the current view [self.view addSubview:self.pageViewController.view]; //Call didMoveToParentViewController: of the childViewController, the UIPageViewController instance in our case. [self.pageViewController didMoveToParentViewController:self]; //Step 5: // set the pageViewController's frame as an inset rect. CGRect pageViewRect = self.view.bounds; pageViewRect = CGRectInset(pageViewRect, 40.0, 40.0); self.pageViewController.view.frame = pageViewRect; //Step 6: //Assign the gestureRecognizers property of our pageViewController to our view's gestureRecognizers property. self.view.gestureRecognizers = self.pageViewController.gestureRecognizers; } - (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation { if(UIInterfaceOrientationIsPortrait(orientation)) { //Set the array with only 1 view controller UIViewController *currentViewController = [self.pageViewController.viewControllers objectAtIndex:0]; NSArray *viewControllers = [NSArray arrayWithObject:currentViewController]; [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL]; //Important- Set the doubleSided property to NO. self.pageViewController.doubleSided = NO; //Return the spine location return UIPageViewControllerSpineLocationMin; } else { // NSArray *viewControllers = nil; ContentViewController *currentViewController = [self.pageViewController.viewControllers objectAtIndex:0]; NSUInteger currentIndex = [self.modelArray indexOfObject:[(ContentViewController *)currentViewController labelContents]]; if(currentIndex == 0 || currentIndex %2 == 0) { UIViewController *nextViewController = [self pageViewController:self.pageViewController viewControllerAfterViewController:currentViewController]; viewControllers = [NSArray arrayWithObjects:currentViewController, nextViewController, nil]; } else { UIViewController *previousViewController = [self pageViewController:self.pageViewController viewControllerBeforeViewController:currentViewController]; viewControllers = [NSArray arrayWithObjects:previousViewController, currentViewController, nil]; } //Now, set the viewControllers property of UIPageViewController [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL]; return UIPageViewControllerSpineLocationMid; } }

    Read the article

  • Would using a self-signed SSL certificate be appropriate in this scenario?

    - by Kevin Y
    Now I realize this topic has been discussed in a few questions before (specifically this one), but I'm still a little confused about the implications of using a self-signed certificate, and how I would be affected by doing so in this case. After reading various sources, I'm still a little confused about the exact details of using one. The biggest problem with a self-signed certificate, is a man-in-the-middle attack. Even if you are 100% sure that you are on the correct website and you completely trust the site (your email server for example), you could have someone intercept the connection and present you with their own self-signed certificate. You would think that you are using a secure connection with your email server but you are really using a secure connection to an attacker's email server. – SSL Shopper So somebody could switch out my self-signed certificate with their own, and I wouldn't be able to detect it? The way this site phrases it, it makes it sound worse to install a self-signed certificate than to leave your site without a certificate at all. Self-signed certificates cannot (by nature) be revoked, which may allow an attacker who has already gained access to monitor and inject data into a connection to spoof an identity if a private key has been compromised. CAs on the other hand have the ability to revoke a compromised certificate if alerted, which prevents its further use. - Wikipedia Does this mean that the only way someone could switch out their own certificate for mine is for them to find out the private key? I suppose this is more secure, but I'm still slightly confused about what exactly results from using a self-signed certificate. Is the only issue that obnoxious security warning that pops up in your browser when directed to the site, or is there more to it? Now in my case, I want to add the an SSL certificate to a minuscule Wordpress blog I run that I don't expect anyone else will read anytime soon; I mainly started it to get into the habit of blogging, and to learn more about the process of administrating a site (ex. what to do in situations like this one). Whenever I go to the login page and there's an HTTP:// instead of HTTPS://, I cringe a little. Submitting my password feels like I'm shouting my password out loud with hundreds of people listening. I don't plan on adding any other authors to the site, so I am the only person who would ever need to login. This isn't a site I'm trying to get page views from, or one that handles e-commerce or any sensitive info like that, simply my username and password to login with. One of the concerns (that I've gathered so far) of a self-signed certificate is that non-technical users might be scared by the security warning, but this would not be an issue in my case. TL;DR: If scaring visitors away isn't a concern (which it isn't in my case), is it acceptable to use a self-signed certificate for the purpose of encrypting my Wordpress blog's password, or are there added security issues I should be aware of? Essentially, I'm wondering whether adding a self-signed certificate will be safer than leaving my login page the way it is now, or if it adds the potential for more security breaches than leaving it sans-SSL.

    Read the article

  • Fitting Gaussian KDE in numpy/scipy in Python

    - by user248237
    I am fitting a Gaussian kernel density estimator to a variable that is the difference of two vectors, called "diff", as follows: gaussian_kde_covfact(diff, smoothing_param) -- where gaussian_kde_covfact is defined as: class gaussian_kde_covfact(stats.gaussian_kde): def __init__(self, dataset, covfact = 'scotts'): self.covfact = covfact scipy.stats.gaussian_kde.__init__(self, dataset) def _compute_covariance_(self): '''not used''' self.inv_cov = np.linalg.inv(self.covariance) self._norm_factor = sqrt(np.linalg.det(2*np.pi*self.covariance)) * self.n def covariance_factor(self): if self.covfact in ['sc', 'scotts']: return self.scotts_factor() if self.covfact in ['si', 'silverman']: return self.silverman_factor() elif self.covfact: return float(self.covfact) else: raise ValueError, \ 'covariance factor has to be scotts, silverman or a number' def reset_covfact(self, covfact): self.covfact = covfact self.covariance_factor() self._compute_covariance() This works, but there is an edge case where the diff is a vector of all 0s. In that case, I get the error: File "/srv/pkg/python/python-packages/python26/scipy/scipy-0.7.1/lib/python2.6/site-packages/scipy/stats/kde.py", line 334, in _compute_covariance self.inv_cov = linalg.inv(self.covariance) File "/srv/pkg/python/python-packages/python26/scipy/scipy-0.7.1/lib/python2.6/site-packages/scipy/linalg/basic.py", line 382, in inv if info>0: raise LinAlgError, "singular matrix" numpy.linalg.linalg.LinAlgError: singular matrix What's a way to get around this? In this case, I'd like it to return a density that's essentially peaked completely at a difference of 0, with no mass everywhere else. thanks.

    Read the article

  • How to Return Variable for all tests to use Unittest

    - by chrissygormley
    Hello, I have a Python script and I am trying to set a variable so that if the first test fail's the rest of then will be set to fail. The script I have so far is: class Tests(): def function: result function.......... def errorHandle(self): return self.error def sudsPass(self): try: result = self.client.service.GetStreamUri(self.stream, self.token) except suds.WebFault, e: assert False except Exception, e: pass finally: if 'result' in locals(): self.error = True self.errorHandle() assert True else: self.error = False self.errorHandle() assert False def sudsFail(self): try: result = self.client.service.GetStreamUri(self.stream, self.token) except suds.WebFault, e: assert False except Exception, e: pass finally: if 'result' in locals() or self.error == False: assert False else: assert True class GetStreamUri(TestGetStreamUri): def runTest(self): self.sudsPass() class GetStreamUriProtocolFail(TestGetStreamUri): def runTest(self): self.stream.Transport.Protocol = "NoValue" self.errorHandle() self.sudsFail() if __name__ == '__main__': unittest.main() I am trying to get self.error to be set to False if the first test fail. I understand that it is being set in another test but I was hoping someone could help me find a solution to this problem using some other means. Thanks PS. Please ignore the strange tests. There is a problem with the error handling at the moment.

    Read the article

  • Changing direction of rotation Pygame

    - by czl
    How would you change the direction of a rotating image/rect in Pygame? Applying positive and negative degree values works but it seems to only be able to rotate one direction throughout my window. Is there a way to ensure a change in direction of rotation? Perhaps change up rotation of a spinning image every 5 seconds, or if able to change the direction of the spin when hitting a X or Y axis. I've added some code below. It seems like switching movement directions is easy with rect.move_ip as long as I specify a speed and have location clause, it does what I want. Unfortunately rotation is't like that. Here I'l adding angles to make sure it spins, but no matter what I try, I'm unable to negate the rotation. def rotate_image(self): #rotate image orig_rect = self.image.get_rect() rot_image = pygame.transform.rotate(self.image, self.angle) rot_rect = orig_rect.copy() rot_rect.center = rot_image.get_rect().center rot_image = rot_image.subsurface(rot_rect).copy() return rot_image def render(self): self.screen.fill(self.bg_color) self.rect.move_ip(0,5) #Y axis movement at 5 px per frame self.angle += 5 #add 5 anglewhen the rect has not hit one of the window self.angle %= 360 if self.rect.left < 0 or self.rect.right > self.width: self.speed[0] = -self.speed[0] self.angle = -self.angle #tried to invert the angle self.angle -= 5 #trying to negate the angle rotation self.angle %= 360 self.screen.blit(self.rotate_image(),self.rect) pygame.display.flip() I would really like to know how to invert rotation of a image. You may provide your own examples.

    Read the article

  • Python "callable" attribute (pseudo-property)

    - by mgilson
    In python, I can alter the state of an instance by directly assigning to attributes, or by making method calls which alter the state of the attributes: foo.thing = 'baz' or: foo.thing('baz') Is there a nice way to create a class which would accept both of the above forms which scales to large numbers of attributes that behave this way? (Shortly, I'll show an example of an implementation that I don't particularly like.) If you're thinking that this is a stupid API, let me know, but perhaps a more concrete example is in order. Say I have a Document class. Document could have an attribute title. However, title may want to have some state as well (font,fontsize,justification,...), but the average user might be happy enough just setting the title to a string and being done with it ... One way to accomplish this would be to: class Title(object): def __init__(self,text,font='times',size=12): self.text = text self.font = font self.size = size def __call__(self,*text,**kwargs): if(text): self.text = text[0] for k,v in kwargs.items(): setattr(self,k,v) def __str__(self): return '<title font={font}, size={size}>{text}</title>'.format(text=self.text,size=self.size,font=self.font) class Document(object): _special_attr = set(['title']) def __setattr__(self,k,v): if k in self._special_attr and hasattr(self,k): getattr(self,k)(v) else: object.__setattr__(self,k,v) def __init__(self,text="",title=""): self.title = Title(title) self.text = text def __str__(self): return str(self.title)+'<body>'+self.text+'</body>' Now I can use this as follows: doc = Document() doc.title = "Hello World" print (str(doc)) doc.title("Goodbye World",font="Helvetica") print (str(doc)) This implementation seems a little messy though (with __special_attr). Maybe that's because this is a messed up API. I'm not sure. Is there a better way to do this? Or did I leave the beaten path a little too far on this one? I realize I could use @property for this as well, but that wouldn't scale well at all if I had more than just one attribute which is to behave this way -- I'd need to write a getter and setter for each, yuck.

    Read the article

  • Problems with self-signed SSL certificate for SSTP in Windows Server Foundation 2008

    - by John Barton
    I am trying to configure SSTP in Windows Server Foundation 2008. I want to use a self-signed SSL certificate to do authentication. When the server is running, I get the following error when trying to connect: 0x800B0109: A certificate chain processed, but terminated in a root certificate that is not trusted by the trust provider. I created the self-signed certificate in the IIS "Server Certificates" panel. From that panel, I exported the certificate, with the private key, to a .pfx file. I installed this certificate on the client computer which I tried to connect from. The certificate bound to the SSL listener in the RRAS-Security panel is present in the Trusted Root Certificate Authority stores on both machines. I've been getting super annoyed setting up certificates. Any advice here?

    Read the article

  • CentOS ISO DVD self-disc-check failing

    - by Jakobud
    I downloaded a CentOS 5.4 DVD ISO from one of the official mirrors. The MD5 sum is correct for the iso file that was downloaded. I burned the ISO onto a DVD+R using ImgBurn. I got no errors during the burning process and it says it finished burning successfully. When booting a server using this DVD to install CentOS on it, the first thing I did was run the self-disc-check (where it checks the files to make sure its genuine, etc). It failed. Didn't really say why. Am I doing something wrong here? Or is there someplace I can see why its failing? If the MD5 is correct and I don't get any burning errors, how can it be failing its own self-check mechanism?

    Read the article

  • How to display a QGraphicsScene?

    - by Chris
    I've got the following code and I'm not sure how to add the QGraphicsScene to my layout.. class MainForm(QDialog): def __init__(self, parent=None): super(MainForm, self).__init__(parent) self.scene = QGraphicsScene(self) self.scene.setSceneRect(0, 0, 500, 500) self.view = QGraphicsView() self.view.setRenderHint(QPainter.Antialiasing) self.view.setScene(self.scene) self.view.setFocusPolicy(Qt.NoFocus) zoomSlider = QSlider(Qt.Horizontal) zoomSlider.setRange(5, 200) zoomSlider.setValue(100) self.pauseButton = QPushButton("Pause") quitButton = QPushButton("Quit") layout = QVBoxLayout() layout.addWidget(zoomSlider) self.setLayout(layout) self.startTimer(10) How can I get my QGraphicsScene running? I'm new to Qt. Am I even supposed to be adding a QGraphicsScene to a layout/

    Read the article

  • Django FileField not saving to upload_to location

    - by Erik
    I have an Attachment model that has a FileField in a Django 1.4.1 app. This FileField has a callable upload_to parameter which, per the Django docs should be called when the form (and therefore the model) is saved. When I run FormTest below, the upload_to callable is never called and the file therefore does not appear in the location provided by the upload_to method. What am I doing wrong? Notice that in the passing tests in ModelTest (also below), the upload_to method works as expected. Test: from core.forms.attachments import AttachmentForm from django.test import TestCase import unittest from django.core.files.uploadedfile import SimpleUploadedFile from django.core.files.storage import default_storage def suite(): return unittest.TestSuite( [ unittest.TestLoader().loadTestsFromTestCase(FormTest), ] ) class FormTest(TestCase): def test_form_1(self): filename = 'filename' f = file(filename) data = {'name':'name',} file_data = {'attachment_file':SimpleUploadedFile(f.name,f.read()),} form = AttachmentForm(data=data,files=file_data) self.assertTrue(form.is_valid()) attachment = form.save() root_directory = 'attachments' upload_location = root_directory + '/' + attachment.directory + '/' + filename self.assertTrue(attachment.attachment_file) # Fails self.assertTrue(default_storage.exists(upload_location)) # Fails Attachment Model: from django.db import models from parent_mixins import Parent_Mixin import uuid from django.db.models.signals import pre_delete,pre_save from dirtyfields import DirtyFieldsMixin def upload_to(instance,filename): return 'attachments/' + instance.directory + '/' + filename def uuid_directory_name(): return uuid.uuid4().hex class Attachment(DirtyFieldsMixin,Parent_Mixin,models.Model): attachment_file = models.FileField(blank=True,null=True,upload_to=upload_to) directory = models.CharField(blank=False,default=uuid_directory_name,null=False,max_length=32) name = models.CharField(blank=False,default=None,null=False,max_length=128) class Meta: app_label = 'core' def __str__(self): return unicode(self).encode('utf-8') def __unicode__(self): return unicode(self.name) @models.permalink def get_absolute_url(self): return('core_attachments_update',(),{'pk': self.pk}) # def save(self,*args,**kwargs): # super(Attachment,self).save(*args,**kwargs) def pre_delete_callback(sender, instance, *args, **kwargs): if not isinstance(instance, Attachment): return if not instance.attachment_file: return instance.attachment_file.delete(save=False) def pre_save_callback(sender, instance, *args, **kwargs): if not isinstance(instance, Attachment): return if not instance.attachment_file: return if instance.is_dirty(): dirty_fields = instance.get_dirty_fields() if 'attachment_file' in dirty_fields: old_attachment_file = dirty_fields['attachment_file'] old_attachment_file.delete() pre_delete.connect(pre_delete_callback) pre_save.connect(pre_save_callback) Attachment Form: from ..models.attachments import Attachment from crispy_forms.helper import FormHelper from crispy_forms.layout import Div,Layout,HTML,Field,Fieldset,Button,ButtonHolder,Submit from django import forms class AttachmentFormHelper(FormHelper): form_tag=False layout = Layout( Div( Div( Field('name',css_class='span4'), Field('attachment_file',css_class='span4'), css_class='span4', ), css_class='row', ), ) class AttachmentForm(forms.ModelForm): helper = AttachmentFormHelper() class Meta: fields=('attachment_file','name') model = Attachment class AttachmentInlineFormHelper(FormHelper): form_tag=False form_style='inline' layout = Layout( Div( Div( Field('name',css_class='span4'), Field('attachment_file',css_class='span4'), Field('DELETE',css_class='span4'), css_class='span4', ), css_class='row', ), ) class AttachmentInlineForm(forms.ModelForm): helper = AttachmentInlineFormHelper() class Meta: fields=('attachment_file','name') model = Attachment UPDATE I also do testing on the Attachment model class with these unit tests -- which all pass: from core.models.attachments import Attachment from core.models.attachments import upload_to from django.test import TestCase import unittest from django.core.files.storage import default_storage from django.core.files.base import ContentFile def suite(): return unittest.TestSuite( [ unittest.TestLoader().loadTestsFromTestCase(ModelTest), ] ) class ModelTest(TestCase): def test_model_minimum_fields(self): attachment = Attachment(name='name') attachment.attachment_file.save('test.txt',ContentFile("hello world")) attachment.save() self.assertEqual(str(attachment),'name') self.assertEqual(unicode(attachment),'name') self.assertTrue(attachment.directory) # def test_model_full_fields(self): # attachment = Attachment() # attachement.save() def test_file_operations_basic(self): root_directory = 'attachments' filename = 'test.txt' attachment = Attachment(name='name') attachment.attachment_file.save(filename,ContentFile('test')) attachment.save() upload_location = root_directory + '/' + attachment.directory + '/' + filename self.assertEqual(upload_to(attachment,filename),upload_location) self.assertTrue(default_storage.exists(upload_location)) def test_file_operations_delete(self): root_directory = 'attachments' filename = 'test.txt' attachment = Attachment(name='name') attachment.attachment_file.save(filename,ContentFile('test')) attachment.save() upload_location = upload_to(attachment,filename) attachment.delete() self.assertFalse(default_storage.exists(upload_location)) def test_file_operations_change(self): root_directory = 'attachments' filename_1 = 'test_1.txt' attachment = Attachment(name='name') attachment.attachment_file.save(filename_1,ContentFile('test')) attachment.save() upload_location_1 = upload_to(attachment,filename_1) self.assertTrue(default_storage.exists(upload_location_1)) filename_2 = 'test_2.txt' attachment.attachment_file.save(filename_2,ContentFile('test')) attachment.save() upload_location_2 = upload_to(attachment,filename_2) self.assertTrue(default_storage.exists(upload_location_2)) self.assertFalse(default_storage.exists(upload_location_1))

    Read the article

  • ASP.net Create Self re-caching objects?

    - by BlackTea
    How can i make a cached object re-cache it self with updated info when the cache has expired? I'm trying to prevent the next user who request the cache to have to deal with getting the data setting the cache then using it is there any background method/event i can tie the object to so that when it expires it just calls the method it self and self-caches.

    Read the article

  • Self-type mismatch in Scala

    - by Alexey Romanov
    Given this: abstract class ViewPresenterPair { type V <: View type P <: Presenter trait View {self: V => val presenter: P } trait Presenter {self: P => var view: V } } I am trying to define an implementation in this way: case class SensorViewPresenter[T] extends ViewPresenterPair { type V = SensorView[T] type P = SensorPresenter[T] trait SensorView[T] extends View { } class SensorViewImpl[T](val presenter: P) extends SensorView[T] { presenter.view = this } class SensorPresenter[T] extends Presenter { var view: V } } Which gives me the following errors: error: illegal inheritance; self-type SensorViewPresenter.this.SensorView[T] does not conform to SensorViewPresenter.this.View's selftype SensorViewPresenter.this.V trait SensorView[T] extends View { ^ <console>:13: error: type mismatch; found : SensorViewPresenter.this.SensorViewImpl[T] required: SensorViewPresenter.this.V presenter.view = this ^ <console>:16: error: illegal inheritance; self-type SensorViewPresenter.this.SensorPresenter[T] does not conform to SensorViewPresenter.this.Presenter's selftype SensorViewPresenter.this.P class SensorPresenter[T] extends Presenter { ^ I don't understand why. After all, V is just an alias for SensorView[T], and the paths are the same, so how can it not conform?

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >