Search Results

Search found 4969 results on 199 pages for 'def'.

Page 7/199 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Passing parameter to base class constructor or using instance variable?

    - by deamon
    All classes derived from a certain base class have to define an attribute called "path". In the sense of duck typing I could rely upon definition in the subclasses: class Base: pass # no "path" variable here def Sub(Base): def __init__(self): self.path = "something/" Another possiblity would be to use the base class constructor: class Base: def __init__(self, path): self.path = path def Sub(Base): def __init__(self): super().__init__("something/") What would you prefer and why? Is there a better way?

    Read the article

  • Running the same code for get(self) as post(self)

    - by Peter Farmer
    Its been mentioned in other answers about getting the same code running for both the def get(self) and the def post(self) for any given request. I was wondering what techniques people use, I was thinking of: class ListSubs(webapp.RequestHandler): def get(self): self._run() def post(self): self._run() def _run(self): self.response.out.write("This works nicely!")

    Read the article

  • Class definition thinks setting a variable is a Unit?

    - by DeLongey
    Writing out a Scala class and problem here is that the compiler thinks that the code is a unit not returning the proper value. It's a method used to set a property in the class: def setObject(`object`:StripeObject):StripeObject = { this.`object` = `object` } The error is: type mismatch; found : Unit required: com.stripe.StripeObject The full class is: case class EventData(var previousAttributes: HashMap[String,Object], var `object`:StripeObject) extends StripeObject { def getPreviousAttributes = { previousAttributes } def setPreviousAttributes(previousAttributes: HashMap[String, Object]) = { this.previousAttributes = previousAttributes } def getObject = { `object` } def setObject(`object`:StripeObject):StripeObject = { this.`object` = `object` } } How do I make sure it doesn't return a Unit?

    Read the article

  • How to get attributes from parent?

    - by bribon
    Hi all, Let's say we have these classes: class Foo(object): _bar = "" def __init__(self): self.bar = "hello" def getBar(self): return self._bar def setBar(self, bar): self._bar = bar def getAttributes(self): for attr in self.__dict__: print attr bar = property(getBar, setBar) class Child(Foo): def __init__(self): super(Child, self).__init__() self.a = "" self.b = "" if I do something like: child = Child() child.getAttributes() I get all the attributes from parent and child. How could I get the attributes only from the parent? Thanks in advance!

    Read the article

  • REST API Help in Rails

    - by dannymcc
    Hi Everyone, I am trying to get some information posted using our accountancy package (FreeAgentCentral) using their API via a GEM. http://github.com/aaronrussell/freeagent_api/ I have the following code to get it working (supposedly): Kase Controller def create @kase = Kase.new(params[:kase]) @company = Company.find(params[:kase][:company_id]) @kase = @company.kases.create!(params[:kase]) respond_to do |format| if @kase.save UserMailer.deliver_makeakase("[email protected]", "Highrise", @kase) @kase.create_freeagent_project(current_user) #flash[:notice] = 'Case was successfully created.' flash[:notice] = fading_flash_message("Case was successfully created & sent to Highrise.", 5) format.html { redirect_to(@kase) } format.xml { render :xml => @kase, :status => :created, :location => @kase } else format.html { render :action => "new" } format.xml { render :xml => @kase.errors, :status => :unprocessable_entity } end end end To save you looking through, the important part is: @kase.create_freeagent_project(current_user) Kase Model # FreeAgent API Project Create # Required attribues # :contact_id # :name # :payment_term_in_days # :billing_basis # must be 1, 7, 7.5, or 8 # :budget_units # must be Hours, Days, or Monetary # :status # must be Active or Completed def create_freeagent_project(current_user) p = Freeagent::Project.create( :contact_id => 0, :name => "#{jobno} - #{highrisesubject}", :payment_terms_in_days => 5, :billing_basis => 1, :budget_units => 'Hours', :status => 'Active' ) user = Freeagent::User.find_by_email(current_user.email) Freeagent::Timeslip.create( :project_id => p.id, :user_id => user.id, :hours => 1, :new_task => 'Setup', :dated_on => Time.now ) end lib/freeagent_api.rb require 'rubygems' gem 'activeresource', '< 3.0.0.beta1' require 'active_resource' module Freeagent class << self def authenticate(options) Base.authenticate(options) end end class Error < StandardError; end class Base < ActiveResource::Base def self.authenticate(options) self.site = "https://#{options[:domain]}" self.user = options[:username] self.password = options[:password] end end # Company class Company def self.invoice_timeline InvoiceTimeline.find :all, :from => '/company/invoice_timeline.xml' end def self.tax_timeline TaxTimeline.find :all, :from => '/company/tax_timeline.xml' end end class InvoiceTimeline < Base self.prefix = '/company/' end class TaxTimeline < Base self.prefix = '/company/' end # Contacts class Contact < Base end # Projects class Project < Base def invoices Invoice.find :all, :from => "/projects/#{id}/invoices.xml" end def timeslips Timeslip.find :all, :from => "/projects/#{id}/timeslips.xml" end end # Tasks - Complete class Task < Base self.prefix = '/projects/:project_id/' end # Invoices - Complete class Invoice < Base def mark_as_draft connection.put("/invoices/#{id}/mark_as_draft.xml", encode, self.class.headers).tap do |response| load_attributes_from_response(response) end end def mark_as_sent connection.put("/invoices/#{id}/mark_as_sent.xml", encode, self.class.headers).tap do |response| load_attributes_from_response(response) end end def mark_as_cancelled connection.put("/invoices/#{id}/mark_as_cancelled.xml", encode, self.class.headers).tap do |response| load_attributes_from_response(response) end end end # Invoice items - Complete class InvoiceItem < Base self.prefix = '/invoices/:invoice_id/' end # Timeslips class Timeslip < Base def self.find(*arguments) scope = arguments.slice!(0) options = arguments.slice!(0) || {} if options[:params] && options[:params][:from] && options[:params][:to] options[:params][:view] = options[:params][:from]+'_'+options[:params][:to] options[:params].delete(:from) options[:params].delete(:to) end case scope when :all then find_every(options) when :first then find_every(options).first when :last then find_every(options).last when :one then find_one(options) else find_single(scope, options) end end end # Users class User < Base self.prefix = '/company/' def self.find_by_email(email) users = User.find :all users.each do |u| u.email == email ? (return u) : next end raise Error, "No user matches that email!" end end end config/initializers/freeagent.rb Freeagent.authenticate({ :domain => 'XXXXX.freeagentcentral.com', :username => '[email protected]', :password => 'XXXXXX' }) The above render the following error when trying to create a new Case and send the details to FreeAgent: ActiveResource::ResourceNotFound in KasesController#create Failed with 404 Not Found and ActiveResource::ResourceNotFound (Failed with 404 Not Found): app/models/kase.rb:56:in `create_freeagent_project' app/controllers/kases_controller.rb:96:in `create' app/controllers/kases_controller.rb:93:in `create' Rendered rescues/_trace (176.5ms) Rendered rescues/_request_and_response (1.1ms) Rendering rescues/layout (internal_server_error) If anyone can shed any light on this problem it would be greatly appreciated! Thanks, Danny

    Read the article

  • OpenGL basics: calling glDrawElements once per object

    - by Bethor
    Hi all, continuing on from my explorations of the basics of OpenGL (see this question), I'm trying to figure out the basic principles of drawing a scene with OpenGL. I am trying to render a simple cube repeated n times in every direction. My method appears to yield terrible performance : 1000 cubes brings performance below 50fps (on a QuadroFX 1800, roughly a GeForce 9600GT). My method for drawing these cubes is as follows: done once: set up a vertex buffer and array buffer containing my cube vertices in model space set up an array buffer indexing the cube for drawing as 12 triangles done for each frame: update uniform values used by the vertex shader to move all cubes at once done for each cube, for each frame: update uniform values used by the vertex shader to move each cube to its position call glDrawElements to draw the positioned cube Is this a sane method ? If not, how does one go about something like this ? I'm guessing I need to minimize calls to glUniform, glDrawElements, or both, but I'm not sure how to do that. Full code for my little test : (depends on gletools and pyglet) I'm aware that my init code (at least) is really ugly; I'm concerned with the rendering code for each frame right now, I'll move to something a little less insane for the creation of the vertex buffers and such later on. import pyglet from pyglet.gl import * from pyglet.window import key from numpy import deg2rad, tan from gletools import ShaderProgram, FragmentShader, VertexShader, GeometryShader vertexData = [-0.5, -0.5, -0.5, 1.0, -0.5, 0.5, -0.5, 1.0, 0.5, -0.5, -0.5, 1.0, 0.5, 0.5, -0.5, 1.0, -0.5, -0.5, 0.5, 1.0, -0.5, 0.5, 0.5, 1.0, 0.5, -0.5, 0.5, 1.0, 0.5, 0.5, 0.5, 1.0] elementArray = [2, 1, 0, 1, 2, 3,## back face 4, 7, 6, 4, 5, 7,## front face 1, 3, 5, 3, 7, 5,## top face 2, 0, 4, 2, 4, 6,## bottom face 1, 5, 4, 0, 1, 4,## left face 6, 7, 3, 6, 3, 2]## right face def toGLArray(input): return (GLfloat*len(input))(*input) def toGLushortArray(input): return (GLushort*len(input))(*input) def initPerspectiveMatrix(aspectRatio = 1.0, fov = 45): frustumScale = 1.0 / tan(deg2rad(fov) / 2.0) fzNear = 0.5 fzFar = 300.0 perspectiveMatrix = [frustumScale*aspectRatio, 0.0 , 0.0 , 0.0 , 0.0 , frustumScale, 0.0 , 0.0 , 0.0 , 0.0 , (fzFar+fzNear)/(fzNear-fzFar) , -1.0, 0.0 , 0.0 , (2*fzFar*fzNear)/(fzNear-fzFar), 0.0 ] return perspectiveMatrix class ModelObject(object): vbo = GLuint() vao = GLuint() eao = GLuint() initDone = False verticesPool = [] indexPool = [] def __init__(self, vertices, indexing): super(ModelObject, self).__init__() if not ModelObject.initDone: glGenVertexArrays(1, ModelObject.vao) glGenBuffers(1, ModelObject.vbo) glGenBuffers(1, ModelObject.eao) glBindVertexArray(ModelObject.vao) initDone = True self.numIndices = len(indexing) self.offsetIntoVerticesPool = len(ModelObject.verticesPool) ModelObject.verticesPool.extend(vertices) self.offsetIntoElementArray = len(ModelObject.indexPool) ModelObject.indexPool.extend(indexing) glBindBuffer(GL_ARRAY_BUFFER, ModelObject.vbo) glEnableVertexAttribArray(0) #position glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ModelObject.eao) glBufferData(GL_ARRAY_BUFFER, len(ModelObject.verticesPool)*4, toGLArray(ModelObject.verticesPool), GL_STREAM_DRAW) glBufferData(GL_ELEMENT_ARRAY_BUFFER, len(ModelObject.indexPool)*2, toGLushortArray(ModelObject.indexPool), GL_STREAM_DRAW) def draw(self): glDrawElements(GL_TRIANGLES, self.numIndices, GL_UNSIGNED_SHORT, self.offsetIntoElementArray) class PositionedObject(object): def __init__(self, mesh, pos, objOffsetUf): super(PositionedObject, self).__init__() self.mesh = mesh self.pos = pos self.objOffsetUf = objOffsetUf def draw(self): glUniform3f(self.objOffsetUf, self.pos[0], self.pos[1], self.pos[2]) self.mesh.draw() w = 800 h = 600 AR = float(h)/float(w) window = pyglet.window.Window(width=w, height=h, vsync=False) window.set_exclusive_mouse(True) pyglet.clock.set_fps_limit(None) ## input forward = [False] left = [False] back = [False] right = [False] up = [False] down = [False] inputs = {key.Z: forward, key.Q: left, key.S: back, key.D: right, key.UP: forward, key.LEFT: left, key.DOWN: back, key.RIGHT: right, key.PAGEUP: up, key.PAGEDOWN: down} ## camera camX = 0.0 camY = 0.0 camZ = -1.0 def simulate(delta): global camZ, camX, camY scale = 10.0 move = scale*delta if forward[0]: camZ += move if back[0]: camZ += -move if left[0]: camX += move if right[0]: camX += -move if up[0]: camY += move if down[0]: camY += -move pyglet.clock.schedule(simulate) @window.event def on_key_press(symbol, modifiers): global forward, back, left, right, up, down if symbol in inputs.keys(): inputs[symbol][0] = True @window.event def on_key_release(symbol, modifiers): global forward, back, left, right, up, down if symbol in inputs.keys(): inputs[symbol][0] = False ## uniforms for shaders camOffsetUf = GLuint() objOffsetUf = GLuint() perspectiveMatrixUf = GLuint() camRotationUf = GLuint() program = ShaderProgram( VertexShader(''' #version 330 layout(location = 0) in vec4 objCoord; uniform vec3 objOffset; uniform vec3 cameraOffset; uniform mat4 perspMx; void main() { mat4 translateCamera = mat4(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, cameraOffset.x, cameraOffset.y, cameraOffset.z, 1.0f); mat4 translateObject = mat4(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, objOffset.x, objOffset.y, objOffset.z, 1.0f); vec4 modelCoord = objCoord; vec4 positionedModel = translateObject*modelCoord; vec4 cameraPos = translateCamera*positionedModel; gl_Position = perspMx * cameraPos; }'''), FragmentShader(''' #version 330 out vec4 outputColor; const vec4 fillColor = vec4(1.0f, 1.0f, 1.0f, 1.0f); void main() { outputColor = fillColor; }''') ) shapes = [] def init(): global camOffsetUf, objOffsetUf with program: camOffsetUf = glGetUniformLocation(program.id, "cameraOffset") objOffsetUf = glGetUniformLocation(program.id, "objOffset") perspectiveMatrixUf = glGetUniformLocation(program.id, "perspMx") glUniformMatrix4fv(perspectiveMatrixUf, 1, GL_FALSE, toGLArray(initPerspectiveMatrix(AR))) obj = ModelObject(vertexData, elementArray) nb = 20 for i in range(nb): for j in range(nb): for k in range(nb): shapes.append(PositionedObject(obj, (float(i*2), float(j*2), float(k*2)), objOffsetUf)) glEnable(GL_CULL_FACE) glCullFace(GL_BACK) glFrontFace(GL_CW) glEnable(GL_DEPTH_TEST) glDepthMask(GL_TRUE) glDepthFunc(GL_LEQUAL) glDepthRange(0.0, 1.0) glClearDepth(1.0) def update(dt): print pyglet.clock.get_fps() pyglet.clock.schedule_interval(update, 1.0) @window.event def on_draw(): with program: pyglet.clock.tick() glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) glUniform3f(camOffsetUf, camX, camY, camZ) for shape in shapes: shape.draw() init() pyglet.app.run()

    Read the article

  • Detect user logout / shutdown in Python / GTK under Linux

    - by Ivo Wetzel
    OK this is presumably a hard one, I've got an pyGTK application that has random crashes due to X Window errors that I can't catch/control. So I created a wrapper that restarts the app as soon as it detects a crash, now comes the problem, when the user logs out or shuts down the system, the app exits with status 1. But on some X errors it does so too. So I tried literally anything to catch the shutdown/logout, with no success, here's what I've tried: import pygtk import gtk import sys class Test(gtk.Window): def delete_event(self, widget, event, data=None): open("delete_event", "wb") def destroy_event(self, widget, data=None): open("destroy_event", "wb") def destroy_event2(self, widget, event, data=None): open("destroy_event2", "wb") def __init__(self): gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL) self.show() self.connect("delete_event", self.delete_event) self.connect("destroy", self.destroy_event) self.connect("destroy-event", self.destroy_event2) def foo(): open("add_event", "wb") def ex(): open("sys_event", "wb") from signal import * def clean(sig): f = open("sig_event", "wb") f.write(str(sig)) f.close() exit(0) for sig in (SIGABRT, SIGILL, SIGINT, SIGSEGV, SIGTERM): signal(sig, lambda *args: clean(sig)) def at(): open("at_event", "wb") import atexit atexit.register(at) f = Test() sys.exitfunc = ex gtk.quit_add(gtk.main_level(), foo) gtk.main() open("exit_event", "wb") Not one of these succeeds, is there any low level way to detect the system shutdown? Google didn't find anything related to that. I guess there must be a way, am I right? :/

    Read the article

  • Single player 'pong' game

    - by Jam
    I am just starting out learning pygame and livewires, and I'm trying to make a single-player pong game, where you just hit the ball, and it bounces around until it passes your paddle (located on the left side of the screen and controlled by the mouse), which makes you lose. I have the basic code, but the ball doesn't stay on the screen, it just flickers and doesn't remain constant. Also, the paddle does not move with the mouse. I'm sure I'm missing something simple, but I just can't figure it out. Help please! Here's what I have: from livewires import games import random games.init(screen_width=640, screen_height=480, fps=50) class Paddle(games.Sprite): image=games.load_image("paddle.bmp") def __init__(self, x=10): super(Paddle, self).__init__(image=Paddle.image, y=games.mouse.y, left=10) self.score=games.Text(value=0, size=25, top=5, right=games.screen.width - 10) games.screen.add(self.score) def update(self): self.y=games.mouse.y if self.top<0: self.top=0 if self.bottom>games.screen.height: self.bottom=games.screen.height self.check_collide() def check_collide(self): for ball in self.overlapping_sprites: self.score.value+=1 ball.handle_collide() class Ball(games.Sprite): image=games.load_image("ball.bmp") speed=5 def __init__(self, x=90, y=90): super(Ball, self).__init__(image=Ball.image, x=x, y=y, dx=Ball.speed, dy=Ball.speed) def update(self): if self.right>games.screen.width: self.dx=-self.dx if self.bottom>games.screen.height or self.top<0: self.dy=-self.dy if self.left<0: self.end_game() self.destroy() def handle_collide(self): self.dx=-self.dx def end_game(self): end_message=games.Message(value="Game Over", size=90, x=games.screen.width/2, y=games.screen.height/2, lifetime=250, after_death=games.screen.quit) games.screen.add(end_message) def main(): background_image=games.load_image("background.bmp", transparent=False) games.screen.background=background_image paddle_image=games.load_image("paddle.bmp") the_paddle=games.Sprite(image=paddle_image, x=10, y=games.mouse.y) games.screen.add(the_paddle) ball_image=games.load_image("ball.bmp") the_ball=games.Sprite(image=ball_image, x=630, y=200, dx=2, dy=2) games.screen.add(the_ball) games.mouse.is_visible=False games.screen.event_grab=True games.screen.mainloop() main()

    Read the article

  • Classes, methods, and polymorphism in Python

    - by Morlock
    I made a module prototype for building complex timer schedules in python. The classe prototypes permit to have Timer objects, each with their waiting times, Repeat objects that group Timer and other Repeat objects, and a Schedule class, just for holding a whole construction or Timers and Repeat instances. The construction can be as complex as needed and needs to be flexible. Each of these three classes has a .run() method, permitting to go through the whole schedule. Whatever the Class, the .run() method either runs a timer, a repeat group for a certain number of iterations, or a schedule. Is this polymorphism-oriented approach sound or silly? What are other appropriate approaches I should consider to build such a versatile utility that permits to put all building blocks together in as complex a way as desired with simplicity? Thanks! Here is the module code: ##################### ## Importing modules from time import time, sleep ##################### ## Class definitions class Timer: """ Timer object with duration. """ def __init__(self, duration): self.duration = duration def run(self): print "Waiting for %i seconds" % self.duration wait(self.duration) chime() class Repeat: """ Repeat grouped objects for a certain number of repetitions. """ def __init__(self, objects=[], rep=1): self.rep = rep self.objects = objects def run(self): print "Repeating group for %i times" % self.rep for i in xrange(self.rep): for group in self.objects: group.run() class Schedule: """ Groups of timers and repetitions. Maybe redundant with class Repeat. """ def __init__(self, schedule=[]): self.schedule = schedule def run(self): for group in self.schedule: group.run() ######################## ## Function definitions def wait(duration): """ Wait a certain number of seconds. """ time_end = time() + float(duration) #uncoment for minutes# * 60 time_diff = time_end - time() while time_diff > 0: sleep(1) time_diff = time_end - time() def chime(): print "Ding!"

    Read the article

  • pyqt QObject: Cannot create children for a parent that is in a different thread

    - by memomk
    QObject: Cannot create children for a parent that is in a different thread. (Parent is QTextDocument(0x9919018), parent's thread is QThread(0x97331e0), current thread is flooderthread(0x97b4c10) error means ? am sorry because am new to pyqt here is the code : i know the code is finished yet but it should work i guess the problem is with myfun.log function... #! /usr/bin/python # -*- coding: utf-8 -*- import urllib, urllib2, itertools, threading, cookielib, Cookie, sys, time, hashlib, os from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s gui=QtGui.QApplication.processEvents texttoset="" class fun(): global texttoset def checkpassword(self): if ui.passwordcheck.isChecked()==True: return 1 else : return 0 def log(self, text): if text != False: firsttext=str(ui.console.toPlainText()) secondtext=firsttext+text+"\n" ui.console.setText(secondtext) log=open("log.log", "a") log.write(text+"\n") log.close() else : firsttext=str(ui.console.toPlainText()) secondtext=firsttext+texttoset+"\n" ui.console.setText(secondtext) log=open("log.log", "a") log.write(texttoset+"\n") log.close() def disable(self): MainWindow.setEnabled(False) pass def enable(self): MainWindow.setEnabled(True) pass def checkmethod(self): if ui.get.isChecked()==True: return 1 elif ui.post.isChecked()==True: return 2 else : return 0 def main(self): connecter() gui() f1.start() gui() time.sleep(3) gui() f2.start() gui() time.sleep(3) gui() f3.start() gui() time.sleep(3) gui() f4.start() gui() time.sleep(3) gui() f5.start() gui() self.sleep(3) gui() f6.start() gui() def killer(self): f1.terminate() f2.terminate() f3.terminate() f4.terminate() f5.terminate() f6.terminate() def close(self): self.killer() os.abort() sys.exit() myfun=fun() def connecter(): QtCore.QObject.connect(f1, QtCore.SIGNAL("log(bool)"), myfun.log) QtCore.QObject.connect(f1, QtCore.SIGNAL("enable()"), myfun.enable) QtCore.QObject.connect(f1, QtCore.SIGNAL("disable()"), myfun.disable) QtCore.QObject.connect(f2, QtCore.SIGNAL("log(bool)"), myfun.log) QtCore.QObject.connect(f2, QtCore.SIGNAL("enable()"), myfun.enable) QtCore.QObject.connect(f2, QtCore.SIGNAL("disable()"), myfun.disable) QtCore.QObject.connect(f3, QtCore.SIGNAL("log(bool)"), myfun.log) QtCore.QObject.connect(f3, QtCore.SIGNAL("enable()"), myfun.enable) QtCore.QObject.connect(f3, QtCore.SIGNAL("disable()"), myfun.disable) QtCore.QObject.connect(f4, QtCore.SIGNAL("log(bool)"), myfun.log) QtCore.QObject.connect(f4, QtCore.SIGNAL("enable()"), myfun.enable) QtCore.QObject.connect(f4, QtCore.SIGNAL("disable()"), myfun.disable) QtCore.QObject.connect(f5, QtCore.SIGNAL("log(bool)"), myfun.log) QtCore.QObject.connect(f5, QtCore.SIGNAL("enable()"), myfun.enable) QtCore.QObject.connect(f5, QtCore.SIGNAL("disable()"), myfun.disable) QtCore.QObject.connect(f6, QtCore.SIGNAL("log(bool)"), myfun.log) QtCore.QObject.connect(f6, QtCore.SIGNAL("enable()"), myfun.enable) QtCore.QObject.connect(f6, QtCore.SIGNAL("disable()"), myfun.disable) x=0 num=0 class flooderthread(QtCore.QThread): global texttoset def __init__(self, x, num): QtCore.QThread.__init__(self) self.x=x self.num=num def log(self, text): texttolog=str(text) time.sleep(1) self.emit(QtCore.SIGNAL("log(bool)"), False) time.sleep(2) def enable(self): time.sleep(1) self.emit(QtCore.SIGNAL("enable()")) def disable(self): time.sleep(1) self.emit(QtCore.SIGNAL("disable()")) def run(self): connecter() self.log("\n\n--------------------------------------------------new session-------------------------------------\n\n") itered=False gui() self.disable() gui() self.log("setting params...") param={ui.dataname1.text():ui.datavalue1.text(),ui.dataname3.text():ui.datavalue3.text(),ui.dataname3.text():ui.datavalue3.text(), } self.log("checking password...") if myfun.checkpassword()==1: itered=True self.log("password is true") else : self.log("password is null ") self.log("itered operation") self.log("setting url") url=str(ui.url.text()) if url[:4]!="http" and url[:3]!="ftp": self.log("url error exiting the whole function") self.log("please set a valide protocole!!") gui() self.enable() gui() return 1 pass else : self.log("valid url") gui() self.log("url is "+url) self.log("setting proxy") proxy="http://"+ui.proxyuser.text()+":"+ui.proxypass.text()+"@"+ui.proxyhost.text()+":"+ui.proxyport.text() self.log("proxy is "+proxy) gui() self.log("preparing params...") urlparam=urllib.urlencode(param) gui() self.log("params are "+urlparam) self.log("setting up headers...") header={'User-Agent':str(ui.useragent.toPlainText())} self.log("headers are "+ str(header)) self.log("setting up proxy handler..") proxyhandler=urllib2.ProxyHandler({"http":str(proxy)}) self.log("checking method") if myfun.checkmethod()==1: self.log("method is get..") self.log("setting request..") finalurl=url+urlparam gui() self.log("final url is"+finalurl) req=urllib2.Request(finalurl, None, headers) elif myfun.checkmethod()==2: self.log("method is post...") self.log("setting request..") finalurl=url gui() self.log("final url is "+finalurl) req=urllib2.Request(finalurl, urlparam, header) else : self.log("error has been accourded") self.log("please select a method!!") gui() self.log("exiting the whole functions") gui() self.enable() return 1 pass self.log("intilizing cookies..") c1=Cookie.SimpleCookie() c1[str(ui.cookiename1.text())]=str(ui.cookievalue1.text()) c1[str(ui.cookiename1.text())]['path']='/' c1[str(ui.cookiename2.text())]=str(ui.cookievalue2.text()) c1[str(ui.cookiename2.text())]['path']='/' c1[str(ui.cookiename3.text())]=str(ui.cookievalue3.text()) c1[str(ui.cookiename3.text())]['domain']=url c1[str(ui.cookiename3.text())]['path']='/' c1[str(ui.cookiename4.text())]=str(ui.cookievalue4.text()) c1[str(ui.cookiename4.text())]['domain']=url c1[str(ui.cookiename4.text())]['path']='/' self.log("cookies are.. :"+str(c1)) cj=cookielib.CookieJar() cj.set_cookie(c1) opener = urllib2.build_opener(proxyhandler, urllib2.HTTPCookieProcessor(cj)) self.log("insatlling opener") urllib2.install_opener(opener) self.log("setting the two operations....") if itered==Fasle: self.log("starting the flooding loop") gui() while true: try: gui() opener.open(req) except e: self.log("error connecting : "+e.reason) self.log("will continue....") continue gui() elif itered==True: pass f1=flooderthread(1, 1) f2=flooderthread(2, 2) f3=flooderthread(3, 3) f4=flooderthread(4, 4) f5=flooderthread(5, 5) f6=flooderthread(6, 6) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.setMinimumSize(QtCore.QSize(838, 500)) MainWindow.setMaximumSize(QtCore.QSize(838, 500)) MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "memo flooder", None, QtGui.QApplication.UnicodeUTF8)) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.console=QtGui.QTextEdit(self.centralwidget) self.console.setGeometry(10, 350, 800,130) self.console.setReadOnly(True) self.console.setObjectName("console") self.groupBox = QtGui.QGroupBox(self.centralwidget) self.groupBox.setGeometry(QtCore.QRect(30, 50, 71, 80)) self.groupBox.setTitle(QtGui.QApplication.translate("MainWindow", "method:", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox.setObjectName(_fromUtf8("groupBox")) self.post = QtGui.QRadioButton(self.groupBox) self.post.setGeometry(QtCore.QRect(10, 20, 61, 22)) self.post.setText(QtGui.QApplication.translate("MainWindow", "post", None, QtGui.QApplication.UnicodeUTF8)) self.post.setChecked(True) self.post.setObjectName(_fromUtf8("post")) self.get = QtGui.QRadioButton(self.groupBox) self.get.setGeometry(QtCore.QRect(10, 50, 51, 22)) self.get.setText(QtGui.QApplication.translate("MainWindow", "get", None, QtGui.QApplication.UnicodeUTF8)) self.get.setObjectName(_fromUtf8("get")) self.url = QtGui.QLineEdit(self.centralwidget) self.url.setGeometry(QtCore.QRect(70, 20, 671, 27)) self.url.setInputMethodHints(QtCore.Qt.ImhUrlCharactersOnly) self.url.setObjectName(_fromUtf8("url")) self.groupBox_2 = QtGui.QGroupBox(self.centralwidget) self.groupBox_2.setGeometry(QtCore.QRect(110, 50, 371, 111)) self.groupBox_2.setTitle(QtGui.QApplication.translate("MainWindow", "data:", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_2.setObjectName(_fromUtf8("groupBox_2")) self.dataname1 = QtGui.QLineEdit(self.groupBox_2) self.dataname1.setGeometry(QtCore.QRect(20, 30, 101, 27)) self.dataname1.setObjectName(_fromUtf8("dataname1")) self.label = QtGui.QLabel(self.groupBox_2) self.label.setGeometry(QtCore.QRect(40, 10, 67, 17)) self.label.setText(QtGui.QApplication.translate("MainWindow", "name:", None, QtGui.QApplication.UnicodeUTF8)) self.label.setObjectName(_fromUtf8("label")) self.dataname2 = QtGui.QLineEdit(self.groupBox_2) self.dataname2.setGeometry(QtCore.QRect(130, 30, 113, 27)) self.dataname2.setObjectName(_fromUtf8("dataname2")) self.dataname3 = QtGui.QLineEdit(self.groupBox_2) self.dataname3.setGeometry(QtCore.QRect(250, 30, 113, 27)) self.dataname3.setObjectName(_fromUtf8("dataname3")) self.label_2 = QtGui.QLabel(self.groupBox_2) self.label_2.setGeometry(QtCore.QRect(40, 60, 67, 17)) self.label_2.setText(QtGui.QApplication.translate("MainWindow", "value:", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setObjectName(_fromUtf8("label_2")) self.datavalue1 = QtGui.QLineEdit(self.groupBox_2) self.datavalue1.setGeometry(QtCore.QRect(20, 80, 101, 27)) self.datavalue1.setObjectName(_fromUtf8("datavalue1")) self.datavalue2 = QtGui.QLineEdit(self.groupBox_2) self.datavalue2.setGeometry(QtCore.QRect(130, 80, 113, 27)) self.datavalue2.setObjectName(_fromUtf8("datavalue2")) self.datavalue3 = QtGui.QLineEdit(self.groupBox_2) self.datavalue3.setGeometry(QtCore.QRect(250, 80, 113, 27)) self.datavalue3.setObjectName(_fromUtf8("datavalue3")) self.groupBox_4 = QtGui.QGroupBox(self.centralwidget) self.groupBox_4.setGeometry(QtCore.QRect(670, 50, 151, 111)) self.groupBox_4.setTitle(QtGui.QApplication.translate("MainWindow", "password:", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_4.setObjectName(_fromUtf8("groupBox_4")) self.passname = QtGui.QLineEdit(self.groupBox_4) self.passname.setGeometry(QtCore.QRect(10, 30, 113, 27)) self.passname.setObjectName(_fromUtf8("passname")) self.passvalue = QtGui.QLineEdit(self.groupBox_4) self.passvalue.setGeometry(QtCore.QRect(10, 80, 113, 27)) self.passvalue.setObjectName(_fromUtf8("passvalue")) self.passwordcheck = QtGui.QCheckBox(self.centralwidget) self.passwordcheck.setGeometry(QtCore.QRect(670, 180, 97, 22)) self.passwordcheck.setText(QtGui.QApplication.translate("MainWindow", "password", None, QtGui.QApplication.UnicodeUTF8)) self.passwordcheck.setChecked(True) self.passwordcheck.setObjectName(_fromUtf8("passwordcheck")) self.groupBox_5 = QtGui.QGroupBox(self.centralwidget) self.groupBox_5.setGeometry(QtCore.QRect(29, 169, 441, 81)) self.groupBox_5.setTitle(QtGui.QApplication.translate("MainWindow", "proxy:", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_5.setObjectName(_fromUtf8("groupBox_5")) self.proxyhost = QtGui.QLineEdit(self.groupBox_5) self.proxyhost.setGeometry(QtCore.QRect(20, 30, 113, 27)) self.proxyhost.setObjectName(_fromUtf8("proxyhost")) self.proxyport = QtGui.QLineEdit(self.groupBox_5) self.proxyport.setGeometry(QtCore.QRect(140, 30, 51, 27)) self.proxyport.setInputMethodHints(QtCore.Qt.ImhDigitsOnly|QtCore.Qt.ImhPreferNumbers) self.proxyport.setObjectName(_fromUtf8("proxyport")) self.proxyuser = QtGui.QLineEdit(self.groupBox_5) self.proxyuser.setGeometry(QtCore.QRect(200, 30, 113, 27)) self.proxyuser.setObjectName(_fromUtf8("proxyuser")) self.proxypass = QtGui.QLineEdit(self.groupBox_5) self.proxypass.setGeometry(QtCore.QRect(320, 30, 113, 27)) self.proxypass.setObjectName(_fromUtf8("proxypass")) self.label_4 = QtGui.QLabel(self.groupBox_5) self.label_4.setGeometry(QtCore.QRect(100, 10, 67, 17)) self.label_4.setText(QtGui.QApplication.translate("MainWindow", "host", None, QtGui.QApplication.UnicodeUTF8)) self.label_4.setObjectName(_fromUtf8("label_4")) self.label_5 = QtGui.QLabel(self.groupBox_5) self.label_5.setGeometry(QtCore.QRect(150, 10, 67, 17)) self.label_5.setText(QtGui.QApplication.translate("MainWindow", "port", None, QtGui.QApplication.UnicodeUTF8)) self.label_5.setObjectName(_fromUtf8("label_5")) self.label_6 = QtGui.QLabel(self.groupBox_5) self.label_6.setGeometry(QtCore.QRect(200, 10, 67, 17)) self.label_6.setText(QtGui.QApplication.translate("MainWindow", "username", None, QtGui.QApplication.UnicodeUTF8)) self.label_6.setObjectName(_fromUtf8("label_6")) self.label_7 = QtGui.QLabel(self.groupBox_5) self.label_7.setGeometry(QtCore.QRect(320, 10, 67, 17)) self.label_7.setText(QtGui.QApplication.translate("MainWindow", "password", None, QtGui.QApplication.UnicodeUTF8)) self.label_7.setObjectName(_fromUtf8("label_7")) self.groupBox_6 = QtGui.QGroupBox(self.centralwidget) self.groupBox_6.setGeometry(QtCore.QRect(30, 260, 531, 91)) self.groupBox_6.setTitle(QtGui.QApplication.translate("MainWindow", "cookies:", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_6.setObjectName(_fromUtf8("groupBox_6")) self.cookiename1 = QtGui.QLineEdit(self.groupBox_6) self.cookiename1.setGeometry(QtCore.QRect(10, 20, 113, 27)) self.cookiename1.setObjectName(_fromUtf8("cookiename1")) self.cookiename2 = QtGui.QLineEdit(self.groupBox_6) self.cookiename2.setGeometry(QtCore.QRect(140, 20, 113, 27)) self.cookiename2.setObjectName(_fromUtf8("cookename2")) self.cookiename3 = QtGui.QLineEdit(self.groupBox_6) self.cookiename3.setGeometry(QtCore.QRect(270, 20, 113, 27)) self.cookiename3.setObjectName(_fromUtf8("cookiename3")) self.cookiename4 = QtGui.QLineEdit(self.groupBox_6) self.cookiename4.setGeometry(QtCore.QRect(390, 20, 113, 27)) self.cookiename4.setObjectName(_fromUtf8("cookiename4")) self.cookievalue1 = QtGui.QLineEdit(self.groupBox_6) self.cookievalue1.setGeometry(QtCore.QRect(10, 50, 113, 27)) self.cookievalue1.setObjectName(_fromUtf8("cookievalue1")) self.cookievalue2 = QtGui.QLineEdit(self.groupBox_6) self.cookievalue2.setGeometry(QtCore.QRect(140, 50, 113, 27)) self.cookievalue2.setObjectName(_fromUtf8("cookievalue2")) self.cookievalue3 = QtGui.QLineEdit(self.groupBox_6) self.cookievalue3.setGeometry(QtCore.QRect(270, 50, 113, 27)) self.cookievalue3.setObjectName(_fromUtf8("cookievalue3")) self.cookievalue4 = QtGui.QLineEdit(self.groupBox_6) self.cookievalue4.setGeometry(QtCore.QRect(390, 50, 113, 27)) self.cookievalue4.setObjectName(_fromUtf8("cookievalue4")) self.groupBox_7 = QtGui.QGroupBox(self.centralwidget) self.groupBox_7.setGeometry(QtCore.QRect(570, 260, 251, 80)) self.groupBox_7.setTitle(QtGui.QApplication.translate("MainWindow", "useragents:", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_7.setObjectName(_fromUtf8("groupBox_7")) self.useragent = QtGui.QTextEdit(self.groupBox_7) self.useragent.setGeometry(QtCore.QRect(10, 20, 211, 51)) self.useragent.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) self.useragent.setObjectName(_fromUtf8("useragent")) self.start = QtGui.QPushButton(self.centralwidget) self.start.setGeometry(QtCore.QRect(750, 20, 71, 27)) self.start.setText(QtGui.QApplication.translate("MainWindow", "start", None, QtGui.QApplication.UnicodeUTF8)) self.start.setObjectName(_fromUtf8("start")) self.label_3 = QtGui.QLabel(self.centralwidget) self.label_3.setGeometry(QtCore.QRect(30, 20, 67, 17)) self.label_3.setText(QtGui.QApplication.translate("MainWindow", "url :", None, QtGui.QApplication.UnicodeUTF8)) self.label_3.setObjectName(_fromUtf8("label_3")) MainWindow.setCentralWidget(self.centralwidget) QtCore.QObject.connect(self.start, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), myfun.main) QtCore.QObject.connect(self.passwordcheck, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.groupBox_4.setEnabled) QtCore.QMetaObject.connectSlotsByName(MainWindow) def __del__(): myfun.killer() os.abort() sys.exit() app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) myfun.log("\n\n--------------------------------------------------new session-------------------------------------\n\n") MainWindow.show() sys.exit(app.exec_())

    Read the article

  • Single-player pong game

    - by Jam
    I am just starting out learning pygame and livewires, and I'm trying to make a single-player pong game, where you just hit the ball, and it bounces around until it passes your paddle (located on the left side of the screen and controlled by the mouse), which makes you lose. However, I keep getting the error: "Cannot have more than on Screen object", which I can find no references to online really, and I can't make sense of it. I want to eventually make the game more complicated, but I need to make it work first. Help please! Here's the code so far: from livewires import games games.init(screen_width=640, screen_height=480, fps=50) class Paddle(games.Sprite): image=games.load_image("paddle.bmp") def __init__(self): super(Paddle, self).__init__(image=Paddle.image, y=games.mouse.y, left=0) self.score=games.Text(value=0, size=25, top=5, right=games.screen.width-10) games.screen.add(self.score) def update(self): self.y=games.mouse.y self.check_collide() def check_collide(self): for ball in self.overlapping_sprites: self.score.value+=1 self.score.right=games.screen.width-10 ball.handle_collide() class Ball(games.Sprite): image=games.load_image("ball.bmp") speed=1 def __init__(self, x, y=90): super(Ball, self).__init__(image=Ball.image, x=x, y=y, dx=Ball.speed, dy=Ball.speed) def update(self): if self.left<0: self.end_game() self.destroy() def handle_collide(self): if self.right>games.screen.width: self.dx=-self.dx if self.bottom>games.screen.height or self.top<0: self.dy=-self.dy def ball_destroy(self): self.destroy() def main(): background_image=games.load_image("background.bmp", transparent=False) games.screen.background=background_image the_ball=Ball() games.screen.add(the_ball) the_paddle=Paddle() games.screen.add(the_paddle) games.mouse.is_visible=False games.screen.event_grab=True games.screen.mainloop() main()

    Read the article

  • I'm using spring, hibernate and mysql. How can I let my app create the table automatically.

    - by Yousui
    Hi guys, I'm using spring, all my annotated entity class information are put in the ApplicationContext.xml. I'm using a MySql database, now how can I use the SchemaExport function in hibernate to create the tables? My application can't create the table automatically, though i have set <prop key="hbm2ddl.auto">create</prop>. This is my ApplicationContext.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql:///edde" /> <property name="username" value="root" /> <property name="password" value="" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="annotatedClasses"> <list> <value>com.edde.Book</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="current_session_context_class">thread</prop> <prop key="show_sql">true</prop> <prop key="hbm2ddl.auto">create</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.use_sql_comments">true</prop> <prop key="hibernate.format_sql">true</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> <bean id="bookDao" class="com.edde.BookDao"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="bookService" class="com.edde.BookServiceImpl"> <property name="dao" ref="bookDao"></property> </bean> </beans> This is my test application: package com.edde; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { /** * @param args */ public static void main(String[] args) { ClassPathXmlApplicationContext factory = new ClassPathXmlApplicationContext("applicationContext.xml"); BookService service = (BookService) factory.getBean("bookService"); Book book = new Book(); book.setBookName("great book"); service.saveBook(book); } } When I run my app, I get this error: 2010-05-20 17:25:20,777 DEBUG [org.hibernate.SQL] - /* insert com.edde.Book */ insert into Book (author, bookName, publication) values (?, ?, ?) Hibernate: /* insert com.edde.Book */ insert into Book (author, bookName, publication) values (?, ?, ?) 2010-05-20 17:25:20,809 DEBUG [org.hibernate.jdbc.AbstractBatcher] - about to close PreparedStatement (open PreparedStatements: 1, globally: 1) 2010-05-20 17:25:20,809 DEBUG [org.hibernate.util.JDBCExceptionReporter] - could not insert: [com.edde.Book] [/* insert com.edde.Book */ insert into Book (author, bookName, publication) values (?, ?, ?)] com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'edde.book' doesn't exist at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at com.mysql.jdbc.Util.handleNewInstance(Util.java:409) at com.mysql.jdbc.Util.getInstance(Util.java:384) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3562) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3494) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1960) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2114) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2696) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2105) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2398) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2316) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2301) at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:94) at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2329) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2836) at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:268) at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:321) at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204) at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210) at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195) at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93) at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:705) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:693) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:689) at org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:686) at org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:1) at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406) at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374) at org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:683) at com.edde.BookDao.insertBook(BookDao.java:18) at com.edde.BookServiceImpl.saveBook(BookServiceImpl.java:34) at com.edde.Test.main(Test.java:17) 2010-05-20 17:25:20,809 WARN [org.hibernate.util.JDBCExceptionReporter] - SQL Error: 1146, SQLState: 42S02 2010-05-20 17:25:20,809 ERROR [org.hibernate.util.JDBCExceptionReporter] - Table 'edde.book' doesn't exist 2010-05-20 17:25:20,809 DEBUG [org.springframework.orm.hibernate3.SessionFactoryUtils] - Closing Hibernate Session 2010-05-20 17:25:20,809 DEBUG [org.hibernate.jdbc.ConnectionManager] - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)] 2010-05-20 17:25:20,809 DEBUG [org.hibernate.jdbc.ConnectionManager] - transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources! Exception in thread "main" org.springframework.dao.InvalidDataAccessResourceUsageException: could not insert: [com.edde.Book]; SQL [/* insert com.edde.Book */ insert into Book (author, bookName, publication) values (?, ?, ?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not insert: [com.edde.Book] at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:629) at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412) at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411) at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374) at org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:683) at com.edde.BookDao.insertBook(BookDao.java:18) at com.edde.BookServiceImpl.saveBook(BookServiceImpl.java:34) at com.edde.Test.main(Test.java:17) Caused by: org.hibernate.exception.SQLGrammarException: could not insert: [com.edde.Book] at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2329) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2836) at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:268) at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:321) at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204) at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210) at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195) at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93) at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:705) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:693) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:689) at org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:686) at org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:1) at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406) ... 5 more Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'edde.book' doesn't exist at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at com.mysql.jdbc.Util.handleNewInstance(Util.java:409) at com.mysql.jdbc.Util.getInstance(Util.java:384) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3562) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3494) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1960) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2114) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2696) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2105) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2398) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2316) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2301) at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:94) at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57) ... 23 more Now my question is: how to create the table automatically? Thanks.

    Read the article

  • Python Locking Implementation (with threading module)

    - by Matty
    This is probably a rudimentary question, but I'm new to threaded programming in Python and am not entirely sure what the correct practice is. Should I be creating a single lock object (either globally or being passed around) and using that everywhere that I need to do locking? Or, should I be creating multiple lock instances in each of the classes where I will be employing them. Take these 2 rudimentary code samples, which direction is best to go? The main difference being that a single lock instance is used in both class A and B in the second, while multiple instances are used in the first. Sample 1 class A(): def __init__(self, theList): self.theList = theList self.lock = threading.Lock() def poll(self): while True: # do some stuff that eventually needs to work with theList self.lock.acquire() try: self.theList.append(something) finally: self.lock.release() class B(threading.Thread): def __init__(self,theList): self.theList = theList self.lock = threading.Lock() self.start() def run(self): while True: # do some stuff that eventually needs to work with theList self.lock.acquire() try: self.theList.remove(something) finally: self.lock.release() if __name__ == "__main__": aList = [] for x in range(10): B(aList) A(aList).poll() Sample 2 class A(): def __init__(self, theList,lock): self.theList = theList self.lock = lock def poll(self): while True: # do some stuff that eventually needs to work with theList self.lock.acquire() try: self.theList.append(something) finally: self.lock.release() class B(threading.Thread): def __init__(self,theList,lock): self.theList = theList self.lock = lock self.start() def run(self): while True: # do some stuff that eventually needs to work with theList self.lock.acquire() try: self.theList.remove(something) finally: self.lock.release() if __name__ == "__main__": lock = threading.Lock() aList = [] for x in range(10): B(aList,lock) A(aList,lock).poll()

    Read the article

  • Associations and the Grails webflow

    - by callie16
    Hi, it's my first time using webflows in Grails and I can't seem to solve this. I have 3 domain classes with associations that look something like this: class A { ... static hasMany = [ b : B ] ... } class B { ... static belongsTo = [ a : A ] static hasMany = [ c : C ] ... } class C { ... static belongsTo = [ b : B ] ... } Now, the GSP communicates with the controller via Javascript (due to my use of Dojo). When I try to remoteFunction a normal action, I can do something like this: def action1 = { def anId = params.id def currA = A.get(anId) def sample = currA.b?.c // I can get all the way to 'c' without any problems ... } However, I have a webflow and the contents of that action is in the webflow... It looks something like this: def someFlow = { ... someState { on("next") { def anId = params.id // this does NOT return a null value def currA = A.get(anId) // this does NOT return a null value def sample = currA.b // error already occurs here and I need to get 'c'! }.("somePage") ... } ... } In this case, it tells me that b doesn't exist... so I can't even get to 'c'. Any suggestions on what to do??? Thanks... getting real desperate...

    Read the article

  • Override ActiveRecord#save, Method Alias? Trying to mixin functionality into save method...

    - by viatropos
    Here's the situation: I have a User model, and two modules for authentication: Oauth and Openid. Both of them override ActiveRecord#save, and have a fair share of implementation logic. Given that I can tell when the user is trying to login via Oauth vs. Openid, but that both of them have overridden save, how do "finally" override save such that I can conditionally call one of the modules' implementations of it? Here is the base structure of what I'm describing: module UsesOauth def self.included(base) base.class_eval do def save puts "Saving with Oauth!" end def save_with_oauth save end end end end module UsesOpenid def self.included(base) base.class_eval do def save puts "Saving with OpenID!" end def save_with_openid save end end end end module Sequencer def save if using_oauth? save_with_oauth elsif using_openid? save_with_openid else super end end end class User < ActiveRecord::Base include UsesOauth include UsesOpenid include Sequencer end I was thinking about using alias_method like so, but that got too complicated, because I might have 1 or 2 more similar modules. I also tried using those save_with_oauth methods (shown above), which almost works. The only thing that's missing is that I also need to call ActiveRecord::Base#save (the super method), so something like this: def save_with_oauth # do this and that super.save # the rest end But I'm not allowed to do that in ruby. Any ideas for a clever solution to this?

    Read the article

  • I'm making a simulated tv

    - by Jam
    I need to make a tv that shows the user the channel and the volume, and shows whether or not the television is on. I have the majority of the code made, but for some reason the channels won't switch. I'm fairly unfamiliar with how properties work, and I think that's what my problem here is. Help please. class Television(object): def __init__(self, __channel=1, volume=1, is_on=0): self.__channel=__channel self.volume=volume self.is_on=is_on def __str__(self): if self.is_on==1: print "The tv is on" print self.__channel print self.volume else: print "The television is off." def toggle_power(self): if self.is_on==1: self.is_on=0 return self.is_on if self.is_on==0: self.is_on=1 return self.is_on def get_channel(self): return channel def set_channel(self, choice): if self.is_on==1: if choice>=0 and choice<=499: channel=self.__channel else: print "Invalid channel!" else: print "The television isn't on!" channel=property(get_channel, set_channel) def raise_volume(self, up=1): if self.is_on==1: self.volume+=up if self.volume>=10: self.volume=10 print "Max volume!" else: print "The television isn't on!" def lower_volume(self, down=1): if self.is_on==1: self.volume-=down if self.volume<=0: self.volume=0 print "Muted!" else: print "The television isn't on!" def main(): tv=Television() choice=None while choice!="0": print \ """ Television 0 - Exit 1 - Toggle Power 2 - Change Channel 3 - Raise Volume 4 - Lower Volume """ choice=raw_input("Choice: ") print if choice=="0": print "Good-bye." elif choice=="1": tv.toggle_power() tv.__str__() elif choice=="2": change=raw_input("What would you like to change the channel to?") tv.set_channel(change) tv.__str__() elif choice=="3": tv.raise_volume() tv.__str__() elif choice=="4": tv.lower_volume() tv.__str__() else: print "\nSorry, but", choice, "isn't a valid choice." main() raw_input("Press enter to exit.")

    Read the article

  • python can't start a new thread

    - by Giorgos Komnino
    I am building a multi threading application. I have setup a threadPool. [ A Queue of size N and N Workers that get data from the queue] When all tasks are done I use tasks.join() where tasks is the queue . The application seems to run smoothly until suddently at some point (after 20 minutes in example) it terminates with the error thread.error: can't start new thread Any ideas? Edit: The threads are daemon Threads and the code is like: while True: t0 = time.time() keyword_statuses = DBSession.query(KeywordStatus).filter(KeywordStatus.status==0).options(joinedload(KeywordStatus.keyword)).with_lockmode("update").limit(100) if keyword_statuses.count() == 0: DBSession.commit() break for kw_status in keyword_statuses: kw_status.status = 1 DBSession.commit() t0 = time.time() w = SWorker(threads_no=32, network_server='http://192.168.1.242:8180/', keywords=keyword_statuses, cities=cities, saver=MySqlRawSave(DBSession), loglevel='debug') w.work() print 'finished' When the daemon threads are killed? When the application finishes or when the work() finishes? Look at the thread pool and the worker (it's from a recipe ) from Queue import Queue from threading import Thread, Event, current_thread import time event = Event() class Worker(Thread): """Thread executing tasks from a given tasks queue""" def __init__(self, tasks): Thread.__init__(self) self.tasks = tasks self.daemon = True self.start() def run(self): '''Start processing tasks from the queue''' while True: event.wait() #time.sleep(0.1) try: func, args, callback = self.tasks.get() except Exception, e: print str(e) return else: if callback is None: func(args) else: callback(func(args)) self.tasks.task_done() class ThreadPool: """Pool of threads consuming tasks from a queue""" def __init__(self, num_threads): self.tasks = Queue(num_threads) for _ in range(num_threads): Worker(self.tasks) def add_task(self, func, args=None, callback=None): ''''Add a task to the queue''' self.tasks.put((func, args, callback)) def wait_completion(self): '''Wait for completion of all the tasks in the queue''' self.tasks.join() def broadcast_block_event(self): '''blocks running threads''' event.clear() def broadcast_unblock_event(self): '''unblocks running threads''' event.set() def get_event(self): '''returns the event object''' return event

    Read the article

  • rspec and ruby 1.9.1: problem with dummy controller and routes

    - by giorgian
    I want to test a module that basically executes some verify statements, to ensure that actions are invoked with the correct method. # /lib/rest_verification.rb module RestVerification def self.included(base) # :nodoc: base.extend(ClassMethods) end module ClassMethods def verify_rest_actions verify :method => :post, :only => [:create], :redirect_to => { :action => :new } ... end end end I tried this: describe RestVerification do class FooController < ActionController::Base include RestVerification verify_rest_actions def new ; end def index ; end def create ; end def edit ; end def update ; end def destroy ; end end # controller_name 'foo' # this only works with ruby 1.8.7 : 1.9.1 says "uninitialized constant FooController" tests FooController # this works with both before(:each) do ActionController::Routing::Routes.draw do |map| map.resources :foo end end after(:each) do ActionController::Routing::Routes.reload! end it ':create should redirect to :new if invoked with wrong verb' do [:get, :put, :delete].each do |verb| send verb, :create response.should redirect_to(new_foo_url) end end ... end When testing: $ ruby -v ruby 1.8.7 (2010-01-10 patchlevel 249) [i486-linux] $ rake RestVerification :create should redirect to :new if invoked with wrong verb Finished in 0.175586 seconds $ rvm use 1.9.1 Using ruby 1.9.1 p378 $ rake RestVerification :create should redirect to :new if invoked with wrong verb (FAILED - 1) 1) 'RestVerification :create should redirect to :new if invoked with wrong verb' FAILED expected redirect to "http://test.host/foo/new", got redirect to "http://test.host/spec/rails/example/controller_example_group/subclass_1/foo/new" Is this a known issue? Is there a workaround?

    Read the article

  • How to parallelize this groovy code?

    - by lucas
    I'm trying to write a reusable component in Groovy to easily shoot off emails from some of our Java applications. I would like to pass it a List, where Email is just a POJO(POGO?) with some email info. I'd like it to be multithreaded, at least running all the email logic in a second thread, or make one thread per email. I am really foggy on multithreading in Java so that probably doesn't help! I've attempted a few different ways, but here is what I have right now: void sendEmails(List<Email> emails) { def threads = [] def sendEm = emails.each{ email -> def th = new Thread({ Random rand = new Random() def wait = (long)(rand.nextDouble() * 1000) println "in closure" this.sleep wait sendEmail(email) }) println "putting thread in list" threads << th } threads.each { it.run() } threads.each { it.join() } } I was hoping the sleep would randomly slow some threads down so the console output wouldn't be sequential. Instead, I see this: putting thread in list putting thread in list putting thread in list putting thread in list putting thread in list putting thread in list putting thread in list putting thread in list putting thread in list putting thread in list in closure sending email1 in closure sending email2 in closure sending email3 in closure sending email4 in closure sending email5 in closure sending email6 in closure sending email7 in closure sending email8 in closure sending email9 in closure sending email10 sendEmail basically does what you'd expect, including the println statement, and the client that calls this follows, void doSomething() { Mailman emailer = MailmanFactory.getExchangeEmailer() def to = ["one","two"] def from = "noreply" def li = [] def email (1..10).each { email = new Email(to,null,from,"email"+it,"hello") li << email } emailer.sendEmails li }

    Read the article

  • urllib2.Request() with data returns empty url

    - by Mr. Polywhirl
    My main concern is the function: getUrlAndHtml() If I manually build and append the query to the end of the uri, I can get the response.url(), but if I pass a dictionary as the request data, the url does not come back. Is there anyway to guarantee the redirected url? In my example below, if thisWorks = True I get back a url, but the returned url is the request url as opposed to a redirect link. On a sidenote, the encoding for .E2.80.93 does not translate to - for some reason? #!/usr/bin/python import pprint import urllib import urllib2 from bs4 import BeautifulSoup from sys import argv URL = 'http://en.wikipedia.org/w/index.php?' def yesOrNo(boolVal): return 'yes' if boolVal else 'no' def getTitleFromRaw(page): return page.strip().replace(' ', '_') def getUrlAndHtml(title, printable=False): thisWorks = False if thisWorks: query = 'title={:s}&printable={:s}'.format(title, yesOrNo(printable)) opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] response = opener.open(URL + query) else: params = {'title':title,'printable':yesOrNo(printable)} data = urllib.urlencode(params) headers = {'User-agent':'Mozilla/5.0'}; request = urllib2.Request(URL, data, headers) response = urllib2.urlopen(request) return response.geturl(), response.read() def getSoup(html, name=None, attrs=None): soup = BeautifulSoup(html) if name is None: return None return soup.find(name, attrs) def setTitle(soup, newTitle): title = soup.find('div', {'id':'toctitle'}) h2 = title.find('h2') h2.contents[0].replaceWith('{:s} for {:s}'.format(h2.getText(), newTitle)) def updateLinks(soup, url): fragment = '#' for a in soup.findAll('a', href=True): a['href'] = a['href'].replace(fragment, url + fragment) def writeToFile(soup, filename='out.html', indentLevel=2): with open(filename, 'wt') as out: pp = pprint.PrettyPrinter(indent=indentLevel, stream=out) pp.pprint(soup) print('Wrote {:s} successfully.'.format(filename)) if __name__ == '__main__': def exitPgrm(): print('usage: {:s} "<PAGE>" <FILE>'.format(argv[0])) exit(0) if len(argv) == 2: help = argv[1] if help == '-h' or help == '--help': exitPgrm() if False:''' if not len(argv) == 3: exitPgrm() ''' page = 'Led Zeppelin' # argv[1] filename = 'test.html' # argv[2] title = getTitleFromRaw(page) url, html = getUrlAndHtml(title) soup = getSoup(html, 'div', {'id':'toc'}) setTitle(soup, page) updateLinks(soup, url) writeToFile(soup, filename)

    Read the article

  • how to set Content-Type automatically when i download the data that i uploaded.

    - by zjm1126
    this is my code : import os from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db #from login import htmlPrefix,get_current_user class MyModel(db.Model): blob = db.BlobProperty() class BaseRequestHandler(webapp.RequestHandler): def render_template(self, filename, template_args=None): if not template_args: template_args = {} path = os.path.join(os.path.dirname(__file__), 'templates', filename) self.response.out.write(template.render(path, template_args)) class upload(BaseRequestHandler): def get(self): self.render_template('index.html',) def post(self): file=self.request.get('file') obj = MyModel() obj.blob = db.Blob(file.encode('utf8')) obj.put() self.response.out.write('upload ok') class download(BaseRequestHandler): def get(self): #id=self.request.get('id') o = MyModel.all().get() #self.response.out.write(''.join('%s: %s <br/>' % (a, getattr(o, a)) for a in dir(o))) self.response.out.write(o) application = webapp.WSGIApplication( [ ('/?', upload), ('/download',download), ], debug=True ) def main(): run_wsgi_app(application) if __name__ == "__main__": main() my index.html is : <form action="/" method="post"> <input type="file" name="file" /> <input type="submit" /> </form> and it show : <__main__.MyModel object at 0x02506830> but ,i don't want to see this , i want to download it , how to change my code to run, thanks updated it is ok now : class upload(BaseRequestHandler): def get(self): self.render_template('index.html',) def post(self): file=self.request.get('file') obj = MyModel() obj.blob = db.Blob(file) obj.put() self.response.out.write('upload ok') class download(BaseRequestHandler): def get(self): #id=self.request.get('id') o = MyModel.all().order('-').get() #self.response.out.write(''.join('%s: %s <br/>' % (a, getattr(o, a)) for a in dir(o))) self.response.headers['Content-Type'] = "image/png" self.response.out.write(o.blob) and new question is : if you upload a 'png' file ,it will show successful , but ,when i upload a rar file ,i will run error , so how to set Content-Type automatically , and what is the Content-Type of the 'rar' file thanks

    Read the article

  • AttributeError in my Python program regarding classes

    - by Axel Finkel
    I'm doing an exercise out of the Python book that involves creating a class and a subclass. I am getting the following error when I try to run the program: AttributeError: 'Customer' object has no attribute 'name', when it tries to go through this bit of code: self.name.append(name) As this is my first time dealing with classes and objects in Python, I'm sure I am making some overt mistake somewhere, but I can't seem to figure it out. I've looked over the documentation for creating classes and writing member functions, and it looks correct, but it is obviously not. I want the Customer subclass to inherit the name, address, and telephone attributes from the Person superclass, but it doesn't seem to be doing so? Here is my code: class Person: def __init__(self): self.name = None self.address = None self.telephone = None def changeName(self, name): self.name.append(name) def changeAddress(self, address): self.address.append(address) def changeTelephone(self, telephone): self.telephone.append(telephone) class Customer(Person): def __init__(self): self.customerNumber = None self.onMailingList = False def changeCustomerNumber(self, customerNumber): self.customerNumber.append(customerNumber) def changeOnMailingList(): if onMailingList == False: onMailingList == True else: onMailingList == False def main(): customer1 = Customer() name = 'Bob Smith' address = '123 Somewhere Road' telephone = '111 222 3333' customerNumber = '12345' customer1.changeName(name) customer1.changeAddress(address) customer1.changeTelephone(telephone) customer1.changeCustomerNumber(customerNumber) print("Customer name: " + customer1.name) print("Customer address: " + customer1.address) print("Customer telephone number: " + customer1.telephone) print("Customer number: " + customer1.customerNumber) print("On mailing list: " + customer1.OnMailingList) customer1.changeOnMailingList() print("On mailing list: " + customer1.OnMailingList) main()

    Read the article

  • undefined method `output_data' for #<EventManager:0x007fa4220320c8> (NoMethodError)

    - by Roger Camps
    I keep getting this error: event_manager.rb:83:in': undefined method output_data' for #<EventManager:0x007fc5018320c0> (NoMethodError) I am following the exercise on this website: Here is my code (My error comes towards the end with DEF OUTPUT_DATA ...): # Dependencies require "csv" # Class Definition class EventManager INVALID_PHONE_NUMBER = "0000000000" INVALID_ZIPCODE = "00000" def initialize puts "EventManager Initialized." filename = "event_attendees.csv" @file = CSV.open(filename, {:headers => true, :header_converters => :symbol}) end def print_names @file.each do |line| puts line.inspect puts line[2] + " " + line[3] end end #printing home phone number method def print_numbers @file.each do |line| number = clean_number(line[:homephone]) puts number end end #cleaning numbers method def clean_number(number) cleaner= number.delete('.' + ')' + '(' + '-') if cleaner.length == 10 # Do Nothing elsif cleaner.length == 11 if cleaner.start_with?("1") cleaner = cleaner[1..-1] else cleaner = INVALID_PHONE_NUMBER end else cleaner = INVALID_PHONE_NUMBER end return cleaner end def clean_zipcode(original) if original.nil? zipcode = INVALID_ZIPCODE elsif original.length < 5 while original.length < 5 original = original.insert(0, "0") end else return original end return zipcode end def print_zipcodes @file.each do |line| zipcode = clean_zipcode(line[:zipcode]) puts zipcode end def output_data output = CSV.open("event_attendees_clean.csv", "w") @file.each do |line| output << line end end end end # Script manager = EventManager.new #manager.print_numbers #manager.print_zipcodes manager.output_data I've tried several things, checked all through the internet and I just can't figure it out myself. I will really appreciate any help. Thank you in advance!

    Read the article

  • Python threading question (Working with a method that blocks forever)

    - by Nix
    I am trying to wrap a thread around some receiving logic in python. Basically we have an app, that will have a thread in the background polling for messages, the problem I ran into is that piece that actually pulls the messages waits forever for a message. Making it impossible to terminate... I ended up wrapping the pull in another thread, but I wanted to make sure there wasn't a better way to do it. Original code: class Manager: def __init__(self): receiver = MessageReceiver() receiver.start() #do other stuff... class MessageReceiver(Thread): receiver = Receiver() def __init__(self): Thread.__init__(self) def run(self): #stop is a flag that i use to stop the thread... while(not stopped ): #can never stop because pull below blocks message = receiver.pull() print "Message" + message What I refectored to: class Manager: def __init__(self): receiver = MessageReceiver() receiver.start() class MessageReceiver(Thread): receiver = Receiver() def __init__(self): Thread.__init__(self) def run(self): pullThread = PullThread(self.receiver) pullThread.start() #stop is a flag that i use to stop the thread... while(not stopped and pullThread.last_message ==None): pass message = pullThread.last_message print "Message" + message class PullThread(Thread): last_message = None def __init__(self, receiver): Thread.__init(self, target=get_message, args=(receiver)) def get_message(self, receiver): self.last_message = None self.last_message = receiver.pull() return self.last_message I know the obvious locking issues exist, but is this the appropriate way to control a receive thread that waits forever for a message? One thing I did notice was this thing eats 100% cpu while waiting for a message... **If you need to see the stopping logic please let me know and I will post.

    Read the article

  • Python: Trouble with YACC

    - by Rosarch
    I'm parsing sentences like: "CS 2310 or equivalent experience" The desired output: [[("CS", 2310)], ["equivalent experience"]] YACC tokenizer symbols: tokens = [ 'DEPT_CODE', 'COURSE_NUMBER', 'OR_CONJ', 'MISC_TEXT', ] t_DEPT_CODE = r'[A-Z]{2,}' t_COURSE_NUMBER = r'[0-9]{4}' t_OR_CONJ = r'or' t_ignore = ' \t' terms = {'DEPT_CODE': t_DEPT_CODE, 'COURSE_NUMBER': t_COURSE_NUMBER, 'OR_CONJ': t_OR_CONJ} for name, regex in terms.items(): terms[name] = "^%s$" % regex def t_MISC_TEXT(t): r'\S+' for name, regex in terms.items(): # print "trying to match %s with regex %s" % (t.value, regex) if re.match(regex, t.value): t.type = name return t return t (MISC_TEXT is meant to match anything not caught by the other terms.) Some relevant rules from the parser: precedence = ( ('left', 'MISC_TEXT'), ) def p_statement_course_data(p): 'statement : course_data' p[0] = p[1] def p_course_data(p): 'course_data : course' p[0] = p[1] def p_course(p): 'course : DEPT_CODE COURSE_NUMBER' p[0] = make_course(p[1], int(p[2])) def p_or_phrase(p): 'or_phrase : statement OR_CONJ statement' p[0] = [[p[1]], [p[3]]] def p_misc_text(p): '''text_aggregate : MISC_TEXT MISC_TEXT | MISC_TEXT text_aggregate | text_aggregate MISC_TEXT ''' p[0] = "%s %s" % (p[0], [1]) def p_text_aggregate_statement(p): 'statement : text_aggregate' p[0] = p[1] Unfortunately, this fails: # works as it should >>> token_list("CS 2110 or equivalent experience") [LexToken(DEPT_CODE,'CS',1,0), LexToken(COURSE_NUMBER,'2110',1,3), LexToken(OR_CONJ,'or',1,8), LexToken(MISC_TEXT,'equivalent',1,11), LexToken(MISC_TEXT,'experience',1,22)] # fails. bummer. >>> parser.parse("CS 2110 or equivalent experience") Syntax error in input: LexToken(MISC_TEXT,'equivalent',1,11) What am I doing wrong? I don't fully understand how to set precedence rules. Also, this is my error function: def p_error(p): print "Syntax error in input: %s" % p Is there a way to see which rule the parser was trying when it failed? Or some other way to make the parser print which rules its trying?

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >