rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
service_class = services[url_path].service_class | service_class = services[url_path].service_factory | def get(self): registry_view = [] services = self.registry.services for url_path in sorted(services): service_class = services[url_path].service_class service_descriptor = descriptor.describe_service(service_class) registry_view.append((url_path, service_class.definition_name(), service_descriptor)) |
ProductCategory(name='Miniconfs', description='Please indicate your preferences for the miniconfs that will be running on Monday and Tuesday. Check the <a href="/programme/miniconfs" target="_blank">Miniconfs page</a> for details on each event. You can choose to attend multiple miniconfs in the one day, as the schedule... | ProductCategory(name='Miniconfs', description='Please indicate your preferences for the miniconfs that will be running on Monday and Tuesday. Check the <a href="/programme/miniconfs" target="_blank">Miniconfs page</a> for details on each event. You can choose to attend multiple miniconfs in the one day, as the schedule... | def setup(meta): meta.Session.add_all( [ ProductCategory(name='Ticket', description='Please choose your registration type. See <a href="/register/prices" target="_blank">the website</a> for a description of what is included in each ticket type.', display='radio', min_qty=1, max_qty=1, display_order=1), ProductCategory(... |
@authorize(h.auth.has_organiser_role) | def view(self, id): c.volunteer = Volunteer.find_by_id(id) | |
if not h.auth.has_organiser_role: | if not h.auth.authorized(h.auth.has_organiser_role): | def index(self): # Check access and redirect if not h.auth.has_organiser_role: redirect_to(action='new') |
if not h.auth.authorized(h.auth.Or(h.auth.is_same_zookeepr_user(person.id), h.auth.has_organiser_role)): | if not h.auth.authorized(h.auth.Or(h.auth.is_same_zookeepr_user(person.id), h.auth.has_organiser_role, h.auth.has_unique_key(h.url_for()))): | def pay(self, id): """Request confirmation from user """ invoice = Invoice.find_by_id(id, True) person = invoice.person |
c.proposal.abstract = h.html_clean(c.proposal.abstract) | c.proposal.abstract = self.clean_abstract(c.proposal.abstract) | def _new(self): if c.cfp_status == 'closed': if not h.auth.authorized(h.auth.Or(h.auth.has_organiser_role, h.auth.has_late_submitter_role)): return render("proposal/closed.mako") elif c.cfp_status == 'not_open': return render("proposal/not_open.mako") |
c.proposal.abstract = h.html_clean(c.proposal.abstract) | c.proposal.abstract = self.clean_abstract(c.proposal.abstract) | def _edit(self, id): # We need to recheck auth in here so we can pass in the id if not h.auth.authorized(h.auth.Or(h.auth.is_same_zookeepr_submitter(id), h.auth.has_organiser_role)): # Raise a no_auth error h.auth.no_role() |
for sn in self.form_result['social_network']: network = SocialNetwork.find_by_name(sn['name']) if sn['account_name']: c.person.social_networks[network] = sn['account_name'] | def _new(self): """Create a new person submit. """ | |
return config['app_conf']['host_name'] | return lca_info['event_url'] | def host_name(): """ Name of the site (hostname) Returns the fqdn for the website. """ return config['app_conf']['host_name'] |
if product.category.display == "checkbox": defaults['products.product_' + category_name + '_' + product.clean_description() + '_checkbox'] = "1" | if product.category.display == 'checkbox': if product.available(): defaults['products.product_' + category_name + '_' + product.clean_description() + '_checkbox'] = '1' elif product.category.display == 'qty': if product.available() and rproduct.qty > 0: defaults['products.product_' + category_name + '_' + product.clean... | def edit(self, id): if not h.auth.authorized(h.auth.Or(h.auth.is_same_zookeepr_registration(id), h.auth.has_organiser_role)): # Raise a no_auth error h.auth.no_role() # If we're an organiser, then don't check payment status. if not h.auth.authorized(h.auth.has_organiser_role): able, response = self._able_to_edit() if n... |
defaults['products.category_' + category_name] = product.id if rproduct.qty > 0: defaults['products.product_' + category_name + '_' + product.clean_description() + '_qty'] = rproduct.qty | if product.available(): defaults['products.category_' + category_name] = product.id | def edit(self, id): if not h.auth.authorized(h.auth.Or(h.auth.is_same_zookeepr_registration(id), h.auth.has_organiser_role)): # Raise a no_auth error h.auth.no_role() # If we're an organiser, then don't check payment status. if not h.auth.authorized(h.auth.has_organiser_role): able, response = self._able_to_edit() if n... |
if voucher.registration[0].person.id != h.signed_in_person().id: | if voucher.registration.person.id != h.signed_in_person().id: | def validate_python(self, value, state): voucher = Voucher.find_by_code(value) if voucher != None: if voucher.registration: if voucher.registration[0].person.id != h.signed_in_person().id: raise Invalid("Voucher code already in use!", value, state) elif value: raise Invalid("Unknown voucher code!", value, state) |
LEFT JOIN review ON (proposal.id=review.proposal_id) | def proposals_by_date(self): """" List of proposals by date submitted [CFP] """ return sql_response(""" SELECT proposal.id, proposal.title, proposal_type.name AS "proposal type", proposal.creation_timestamp AS "submitted" FROM proposal LEFT JOIN review ON (proposal.id=review.proposal_id) LEFT JOIN proposal_type ON (pro... | |
GROUP BY proposal.id, proposal.title, proposal_type.name | def proposals_by_date(self): """" List of proposals by date submitted [CFP] """ return sql_response(""" SELECT proposal.id, proposal.title, proposal_type.name AS "proposal type", proposal.creation_timestamp AS "submitted" FROM proposal LEFT JOIN review ON (proposal.id=review.proposal_id) LEFT JOIN proposal_type ON (pro... | |
return 'http' | return 'https' | def current_protocol(): if request.scheme.lower() == 'https': return 'http' if request.environ.get('HTTPS') == 'on': return 'https' if request.environ.get('HTTP_X_FORWARDED_PROTO') == 'https': return 'https' return 'http' |
if request.environ.get('HTTPS') == 'on': | if request.environ.get('HTTPS') in ('on', '1'): | def current_protocol(): if request.scheme.lower() == 'https': return 'http' if request.environ.get('HTTPS') == 'on': return 'https' if request.environ.get('HTTP_X_FORWARDED_PROTO') == 'https': return 'https' return 'http' |
defaults['products.category_' + category_name] = product.id | if product.category.display == "checkbox": defaults['products.product_' + category_name] = product.id else: defaults['products.category_' + category_name] = product.id | def edit(self, id): if not h.auth.authorized(h.auth.Or(h.auth.is_same_zookeepr_registration(id), h.auth.has_organiser_role)): # Raise a no_auth error h.auth.no_role() # If we're an organiser, then don't check payment status. if not h.auth.authorized(h.auth.has_organiser_role): able, response = self._able_to_edit() if n... |
clean_prod_desc = product.clean_description() if result['products']['product_' + clean_cat_name + '_' + clean_prod_desc] == True: | clean_category_name = category.clean_name() if result['products']['product_' + clean_category_name] == True: | def save_details(self, result): # Store Registration details for k in result['registration']: if k in ('shell', 'editor', 'distro'): if result['registration'][k] == 'other': setattr(c.registration, k, result['registration'][k + 'text']) else: setattr(c.registration, k, result['registration'][k]) else: setattr(c.registr... |
@authorize(h.auth.has_planetfeed_role) | @authorize(h.auth.has_organiser_role) | def partners_programme(self): """ List of partners programme contacts [Partners Programme] """ partners_list = meta.Session.query(Product).filter(Product.category.has(name = 'Partners Programme')).all() c.text = "*Checkin and checkout dates aren't an accurate source." c.columns = ['Partner Type', 'Qty', 'Registration N... |
c.person = Person.find_by_id(self.form_result['person_to_edit']) | c.person = self.form_result['person_to_edit'] | def _edit(self, id): # We need to recheck auth in here so we can pass in the id if not h.auth.authorized(h.auth.Or(h.auth.is_same_zookeepr_submitter(id), h.auth.has_organiser_role)): # Raise a no_auth error h.auth.no_role() |
yesterday = datetime.datetime.now() + datetime.timedelta(-1) return self.due_date <= yesterday | return self.due_date < datetime.datetime.now() | def overdue(self): yesterday = datetime.datetime.now() + datetime.timedelta(-1) return self.due_date <= yesterday |
url = h.url_for() if url[0]=='/': url=url[1:] | url = h.url_for().strip("/") | def page(self): url = h.url_for() if url[0]=='/': url=url[1:] c.db_content = DbContent.find_by_url(url, abort_404=False) if c.db_content is not None: if not c.db_content.published and not h.auth.authorized(h.auth.has_organiser_role): c.db_content = None return NotFoundController().view() return self.view(c.db_content.i... |
c.person = self.form_result['person_to_edit'] | c.person = Person.find_by_id(self.form_result['person_to_edit']) | def _edit(self, id): # We need to recheck auth in here so we can pass in the id if not h.auth.authorized(h.auth.Or(h.auth.is_same_zookeepr_submitter(id), h.auth.has_organiser_role)): # Raise a no_auth error h.auth.no_role() |
return Session.query(SpecialRegistration).order_by(SpecialRegistration.display_order).order_by(SpecialRegistration.name).all() | return Session.query(SpecialRegistration).all() | def find_all(self): return Session.query(SpecialRegistration).order_by(SpecialRegistration.display_order).order_by(SpecialRegistration.name).all() |
defaults['person_to_edit'] = c.person.id defaults['name'] = c.person.firstname + " " + c.person.lastname | def edit(self, id): # We need to recheck auth in here so we can pass in the id if not h.auth.authorized(h.auth.Or(h.auth.is_same_zookeepr_submitter(id), h.auth.has_organiser_role)): # Raise a no_auth error h.auth.no_role() | |
meta.Session.clear() if quiet: return redirect_to(controller='invoice', action='view', id=invoice.id) else: if old_invoice.due_date < new_invoice.due_date: new_invoice.due_date = old_invoice.due_date old_invoice.void = "Registration Change" | if not quiet: redirect_to(controller='invoice', action='view', id=invoice.id) meta.Session.rollback() return if old_invoice.due_date < new_invoice.due_date: new_invoice.due_date = old_invoice.due_date old_invoice.void = "Registration Change" | def pay(self, id, quiet=0): if not h.auth.authorized(h.auth.Or(h.auth.is_same_zookeepr_registration(id), h.auth.has_organiser_role)): # Raise a no_auth error h.auth.no_role() registration = Registration.find_by_id(id) |
if registration.person.is_speaker(): | if registration.person.has_role('core_team'): ticket = 'Organiser' elif registration.person.is_speaker(): | def _registration_badge_data(self, registration, stamp = False): if registration: dinner_tickets = 0 speakers_tickets = 0 pdns_ticket = False ticket = '' for invoice in registration.person.invoices: if invoice.paid() and not invoice.is_void(): for item in invoice.items: if item.description.startswith('Penguin Dinner'):... |
elif (item.description.find('Professional') > -1 or item.description.startswith('Korora')): | elif item.description.find('Professional') > -1 or item.description.find('Korora') > -1: | def _registration_badge_data(self, registration, stamp = False): if registration: dinner_tickets = 0 speakers_tickets = 0 pdns_ticket = False ticket = '' for invoice in registration.person.invoices: if invoice.paid() and not invoice.is_void(): for item in invoice.items: if item.description.startswith('Penguin Dinner'):... |
day_dates = {'monday': date(2010,1,18), 'tuesday': date(2010,1,19), 'wednesday': date(2010,1,20), 'thursday': date(2010,1,21), 'friday': date(2010,1,22), 'saturday': date(2010,1,23)} | day_dates = {'monday': date(2011,1,24), 'tuesday': date(2011,1,25), 'wednesday': date(2011,1,26), 'thursday': date(2011,1,27), 'friday': date(2011,1,28), 'saturday': date(2011,1,29)} | def get_directory_contents(directory): files = {} if os.path.isdir(directory): for filename in os.listdir(directory): if os.path.isfile(directory + "/" + filename): files[filename.rsplit('.')[0]] = filename return files |
display_grid = validators.Bool() | display_mode = validators.String() | def validate_python(self, value, state): product_category = ProductCategory.find_by_name(value['product_category']['name']) if product_category != None and product_category != c.product_category: raise Invalid("Category name already in use", value, state) |
if os.path.isfile(file): short_file = os.path.basename(file) output += "<a href=\"" + file_paths["public_html"] + "/images/" + set + "/" + short_file + "\" rel=\"lightbox[" + set + "]\">" if short_file == small: output += "<img src=\"" + file_paths["public_html"] + "/images/" + set + "/small/" + short_file + "\">" ... | if os.path.isfile(file): short_file = os.path.basename(file) if file == 'captions': continue output += "<a href=\"" + file_paths["public_html"] + "/images/" + set + "/" + short_file + "\" rel=\"lightbox[" + set + "]\"" if short_file in caption: output += " title=\"" + caption[short_file] + "\"" output += ">" if sho... | def slideshow(set, small=None): """ Generate a slideshow of a set of images, randomly selecting one to show first, unless a file is specified. """ try: if small == None or small == "": # Randomly select a smaller image, set the width of the div to be # the width of image. small = random.choice(glob(file_paths["public_p... |
if h.auth.has_organiser_role: c.can_edit = True c.invoice_collection = Invoice.find_all() else: c.can_edit = False c.invoice_collection = Invoice.find_by_person(h.signed_in_person().id) | c.can_edit = True c.invoice_collection = Invoice.find_all() | def index(self): if h.auth.has_organiser_role: c.can_edit = True c.invoice_collection = Invoice.find_all() else: c.can_edit = False c.invoice_collection = Invoice.find_by_person(h.signed_in_person().id) |
rect = self.image.get_rect() self.shift = [y-x for x, y in zip(rect, rect.center)] | self.rect = self.image.get_rect() | def __init__(self, scale, pawn, imagedir): super(SpritePawn, self).__init__() |
self.rotated = +1 | def __init__(self, scale, pawn, imagedir): super(SpritePawn, self).__init__() | |
@property def rect(self): return [x*self.scale - shift for x, shift in zip(self.pawn.pos, self.shift)] | def __init__(self, scale, pawn, imagedir): super(SpritePawn, self).__init__() | |
img = self.images[self.frame] else: img = self.image | img = self.images[self.frame] | def update(self): # animated images: check if it's time to change frame if self.game.time_elapsed - self._last_update > self.delay: # update values self._last_update = self.game.time_elapsed self.frame = self.frame+1 if self.frame < self.ni-1 else 0 # change image img = self.images[self.frame] else: img = self.image |
if Direction.from_vector(self.pawn.speed).hor == -self.rotated: | if Direction.from_vector(self.pawn.speed).hor == 1: | def update(self): # animated images: check if it's time to change frame if self.game.time_elapsed - self._last_update > self.delay: # update values self._last_update = self.game.time_elapsed self.frame = self.frame+1 if self.frame < self.ni-1 else 0 # change image img = self.images[self.frame] else: img = self.image |
self.rotated = -self.rotated | def update(self): # animated images: check if it's time to change frame if self.game.time_elapsed - self._last_update > self.delay: # update values self._last_update = self.game.time_elapsed self.frame = self.frame+1 if self.frame < self.ni-1 else 0 # change image img = self.images[self.frame] else: img = self.image | |
self._draw_object(self.game.carrot) self._surf.blit(self.icarrot, [x*self.scale for x in self.game.carrot.pos]) | self.rcarrot.center = [x*self.scale for x in self.game.carrot.pos] self._surf.blit(self.icarrot, self.rcarrot) | def paint(self): """ Draw the board. """ # Fill self.arena of black self._surf.blit(self._background, (0, 0)) |
output = Direction(int(round((value*2.0)-1.0)) for value in nnout) | output = Direction.from_vector((value*2.0)-1.0 for value in nnout) | def update(self, time): """ The neural network recives in input the following data: Hare position, Fox position, Carrot position and hare speed. """ diagonal = sqrt( HareBrain.size[0]**2 + HareBrain.size[1]**2 ) |
self._screen.flip() | def welcome(self): """ Game started: display a simple welcome message """ # Creating title title = pygame.font.Font(None, 100).render('FoxGame!', True, (0, 0, 255) ).get_rect().copy() title.center = tuple(self.size / 2) | |
def update(self): | def update(self, time): | def update(self): """ The method update is called each single time the pawn needs a new direction to move to. """ raise NotImplementedError('update method not overwritten.') |
n.train(HareBrain.examples_generator(filename), | n.train(tuple(HareBrain.examples_generator(filename)), | def train_network(_net_struct, filename): """ """ n = NeuralNetwork(*_net_struct) n.train(HareBrain.examples_generator(filename), HareBrain.epochs, HareBrain.epsilon, HareBrain.error) n.save(HareBrain._net_data) |
self.rotated = -1 | self.rotated = +1 | def __init__(self, scale, pawn, imagedir): super(SpritePawn, self).__init__() |
self._surf.blit(self.icarrot, [x*self.scale for x in self.game.carrot.pos]) | def paint(self): """ Draw the board. """ # Fill self.arena of black self._surf.blit(self._background, (0, 0)) | |
args = self.arena, pawn.pos.x, pawn.pos.y, pawn.radius, pygame.Color(pawn.color) | args = (self.arena, int(pawn.pos.x), int(pawn.pos.y), pawn.radius, pygame.Color(pawn.color)) | def _draw(self, pawn): """ Draw a GameObject with circular shape on the screen. """ args = self.arena, pawn.pos.x, pawn.pos.y, pawn.radius, pygame.Color(pawn.color) filled_circle(*args) aacircle(*args) |
x, y = fox.pos | x, y = map(int, fox.pos) | def _paint_gamefield(self): """ Draw the board. """ # Fill self.arena of black self.arena.fill((0, 0, 0)) |
Return the discance between two circles. | Return the distance between between the two closest points in the circumference. | def distance(self, other): """ Return the discance between two circles. """ dist = self.pos.distance(other.pos) - self.radius - other.radius return dist if dist > 0 else 0 |
if 0 < newpos.x < self.parent.size[0] - self.radius: | if 0 < newpos.x < (self.parent.size[0] - self.radius): | def _update_pos(self, time_delta): """ Update position keeping the same speed and acceleration. """ newpos = self.pos + self.speed * time_delta |
if 0 < newpos.y < self.parent.size[1] - self.radius: | if 0 < newpos.y < (self.parent.size[1] - self.radius): | def _update_pos(self, time_delta): """ Update position keeping the same speed and acceleration. """ newpos = self.pos + self.speed * time_delta |
""" This is the only public function in this class. | """ | def drive(self, direction, time_delta): """ This is the only public function in this class. Updates position, speed, acceleration according to time and direction. For each one of these points call the correspective private method: self._update_acc => update acceleration self._update_speed => update speed self._udpdat... |
so just checks if their distance < sum of radius. | so just checks if their distance is the sum of radius. | def _collision(self, pawn1, pawn2): """ Find if there's a collision between obj1 and obj2: so just checks if their distance < sum of radius. """ return pawn1.distance(pawn2) == 0 |
game.end() | self.game.end() | def clean_game(self): if self.game: game.end() if self.arena: self.arena.remove() self.arena = None |
color = 250, 50, 0 | color = 'orangered' | def drive(self, direction, time_delta): # This is the only public function in this class. """ Updates position, speed, acceleration according to time and direction. For each one of these points call the correspective private method: self._update_acc => update acceleration self._update_speed => update speed self._udpd... |
color = 192, 192, 192 | color = 'grey' | def drive(self, direction, time_delta): # This is the only public function in this class. """ Updates position, speed, acceleration according to time and direction. For each one of these points call the correspective private method: self._update_acc => update acceleration self._update_speed => update speed self._udpd... |
color = 220, 140, 0 | color = 'darkorange' | def drive(self, direction, time_delta): # This is the only public function in this class. """ Updates position, speed, acceleration according to time and direction. For each one of these points call the correspective private method: self._update_acc => update acceleration self._update_speed => update speed self._udpd... |
self.trace_wi = [[0]*self.nh]*self.ni | self.trace_wi = [[0]*self.nh for i in range(self.ni)] | def __init__(self, ni, nh, no=1, bias=False, funct='sigmoid', wi=None, wo=None): super(TDLambda, self).__init__(ni, nh, 1, False, funct, wi, wo) # Eligibility trace (e vector) self.trace_wi = [[0]*self.nh]*self.ni self.trace_wo = [0]*self.nh |
def __new__(cls): | def __new__(cls, game_factory): | def __new__(cls): # set up jobs properly cls._job, cls._postjob = cls.job.onjob, cls.job.postjob |
return object.__new__(cls, *args) | return object.__new__(cls) | def __new__(cls): # set up jobs properly cls._job, cls._postjob = cls.job.onjob, cls.job.postjob |
log.debug(str(keydir) + ' > ' + str(self.pawn.pos)) | def update(self): keydir = Direction(Direction.NULL) for direction, pressed in self.inputs.iteritems(): if pressed: keydir |= Direction(direction) log.debug(str(keydir) + ' > ' + str(self.pawn.pos)) | |
', '.join(map(lambda x: x.name, sets_list))) | ', '.join(map(lambda x: x.name, self.sets))) | def __repr__(self): return '<Fuzzy variable \'%s\' with sets: %s>' % (self.name, ', '.join(map(lambda x: x.name, sets_list))) |
belong = [set.a_cut(val) for set in self.sets] ret = belong[0] for set in belong[1:]: ret |= set return ret | return reduce(or_, (set.a_cut(val) for set in self.sets[:] if set.u(val) != 0)) | def fuzzify(self, val): """ Fuzzify a value returning the corresponfig fuzzy set. If 'val' belongs to multiple sets, return the union (bit_or) of those. """ # raise exceptions.RuntimeError: maximum recursion depth exceeded wtf? # return reduce(or_, (set.a_cut(val) for set in self.sets # if set.u(va... |
VoidSet = Set(Variable(None, (0, 0)), | VoidSet = Set(Variable('None', (0, 0)), | def register(self, lv): """ Register a linguistic variable in the engine. """ raise NotImplementedError |
for event in pygame.event.get(): if event.type == pygame.KEYDOWN: self.keypress.add(event.key) elif event.type == pygame.KEYUP: self.keypress.remove(event.key) | for evt in pygame.event.get(): if evt.type == pygame.KEYDOWN: self.keypress.add(evt.key) elif evt.type == pygame.KEYUP: self.keypress.remove(evt.key) | def tick(self, time_delta): # update self.keypress for event in pygame.event.get(): if event.type == pygame.KEYDOWN: self.keypress.add(event.key) elif event.type == pygame.KEYUP: self.keypress.remove(event.key) |
event = None | def wait(self): """ Game paused: wait for space to continue the game. XXX """ event = None # XXX while pygame.K_SPACE not in (event.key for event in pygame.event.get()): # XXX pass | |
while pygame.K_SPACE not in (event.key for event in pygame.event.get()): | while pygame.K_SPACE not in (evt.key for evt in pygame.event.get()): | def wait(self): """ Game paused: wait for space to continue the game. XXX """ event = None # XXX while pygame.K_SPACE not in (event.key for event in pygame.event.get()): # XXX pass |
if exists(filename): db = shelve.open(filename) if all(key in ('wi', 'wo') for key in db): self.ni = len(db['wi']) self.nh = len(db['wo']) self.wi = db['wi'] self.wo = db['wo'] db.close() return True raise IOError('File %s broken or corrupted' % filename) | db = shelve.open(filename, 'r') if all(key in ('wi', 'wo') for key in db): self.ni = len(db['wi']) self.nh = len(db['wo']) self.wi = db['wi'] self.wo = db['wo'] db.close() return True | def load(self, filename): """ Load a shelve database with synapses. TODO: improve doc about formatting """ if exists(filename): db = shelve.open(filename) if all(key in ('wi', 'wo') for key in db): self.ni = len(db['wi']) self.nh = len(db['wo']) |
return ('Input weights: %f\n Hidden weights: %f\n' % | return ('Input weights: %s\n Hidden weights: %s\n' % | def __str__(self): return ('Input weights: %f\n Hidden weights: %f\n' % (', '.join(self.wi), ', '.join(self.wh))) |
for j in range(self.nh): | for j in xrange(self.nh): | def back_propagate(self, targets, eps=0.5): if len(targets) != self.no: raise ValueError('wrong number of target values') |
score_rect = score.get_rect().copy() | score_rect = score.get_rect() | def _paint_hud(self): # Head-up display score_msg = 'Score: %03d00' % self.game.hare.carrots score = self.hud_font.render(score_msg, True, (255, 255, 255)) score_rect = score.get_rect().copy() score_rect.top = self._screen.get_rect().top + 5 score_rect.right = self._screen.get_rect().right - 5 |
time_rect = time.get_rect().copy() | time_rect = time.get_rect() | def _paint_hud(self): # Head-up display score_msg = 'Score: %03d00' % self.game.hare.carrots score = self.hud_font.render(score_msg, True, (255, 255, 255)) score_rect = score.get_rect().copy() score_rect.top = self._screen.get_rect().top + 5 score_rect.right = self._screen.get_rect().right - 5 |
self.welcome_subtitle_rect = self.welcome_subtitle.get_rect().copy() | self.welcome_subtitle_rect = self.welcome_subtitle.get_rect() | def welcome_init(self): # Creating title and subtitle surfaces and rects title_font = pygame.font.Font(None, 100) self.welcome_title = title_font.render('FoxGame!', True, (0, 0, 255)) self.welcome_title_rect = self.welcome_title.get_rect() self.welcome_title_rect.center = self._screen.get_rect().center |
self.paused_text_rect = self.paused_text.get_rect().copy() | self.paused_text_rect = self.paused_text.get_rect() | def paused_init(self): title_font = pygame.font.Font(None, 50) self.paused_text = title_font.render('Game paused!', True, (150, 150, 255)) self.paused_text_rect = self.paused_text.get_rect().copy() |
self.paused_subtext_rect = self.paused_subtext.get_rect().copy() | self.paused_subtext_rect = self.paused_subtext.get_rect() | def paused_init(self): title_font = pygame.font.Font(None, 50) self.paused_text = title_font.render('Game paused!', True, (150, 150, 255)) self.paused_text_rect = self.paused_text.get_rect().copy() |
if dpoint * self.speed < 0: | if dpoint * speed < 0: | def _compute_acc(self, dpoint, speed): """ Compute the acceleration on a single component accordingly to move intention. |
self.factory = string | self.factory = str | def _parse_clstype(self, sfactory): if sfactory == 'string': self.factory = string elif sfactory == 'int': self.factory = int elif sfactory == 'bool': self.factory = bool # elif sfactory == 'vector': # self.factory = Vector # elif sfactory == 'direction': # self.factory = Direction else: raise TypeError('Unknow... |
if not isinstance(filename, str): | if not isinstance(filename, basestring): | def SetBoundsByWaypointFile(self, filename): print "Setting map boundaries to match waypoint file contents ..." |
"-r", "cubicspline", | "-r", "cubic", | def __resample(dir_temp, input_file, arcseconds_per_pixel): print "Resampling terrain ..." output_file = os.path.join(dir_temp, "terrain_resampled.tif") if os.path.exists(output_file): os.unlink(output_file) degree_per_pixel = float(arcseconds_per_pixel) / 3600.0 args = [cmd_gdal_warp, "-r", "cubicspline", "-tr", str... |
msg = "From: no-replay@" + self.__mail_server +\ | msg = "From: no-reply@xcsoar.org" +\ | def __send_download_mail(self, job): try: print "Sending download mail to " + job.description.mail + " ..." |
"\nSubject: Download ready (" + job.description.name + ".xcm)\n" +\ "The map generator has finished your map.\n" +\ "It can be downloaded at http://www.xcsoar.org:8037/download?uuid=" + job.uuid s.sendmail("no-replay@" + self.__mail_server, job.description.mail, msg) | "\nSubject: XCSoar Map Generator - Download ready (" + job.description.name + ".xcm)\n" +\ "The XCSoar Map Generator has finished your map.\n" +\ "It can be downloaded at http://www.xcsoar.org/mapgen/download?uuid=" + job.uuid s.sendmail('no-reply@xcsoar.org', job.description.mail, msg) | def __send_download_mail(self, job): try: print "Sending download mail to " + job.description.mail + " ..." |
db.remove(ip) | del db[ip] | def too_many_requests(self): db = None lock = None try: if not os.path.exists(self.__dir_jobs): os.makedirs(self.__dir_jobs) lock = open(os.path.join(self.__dir_jobs, 'requests.db.lock'), 'a') fcntl.flock(lock, fcntl.LOCK_EX) db = shelve.open(os.path.join(self.__dir_jobs, 'requests.db')) for ip in db.keys(): times = db... |
dir_job = self.__get_dir_job(uuid) | file_job = self.__get_file_job(uuid) if os.path.exists(file_job): os.unlink(file_job) | def __delete_job(self, uuid, complete = True): dir_job = self.__get_dir_job(uuid) if complete: for file in os.listdir(dir_job): os.unlink(os.path.join(dir_job, file)) os.rmdir(dir_job) else: file_job = self.__get_file_job(uuid) if os.path.exists(file_job): os.unlink(file_job) print "Job deleted (" + file_job + ")" |
else: file_job = self.__get_file_job(uuid) if os.path.exists(file_job): os.unlink(file_job) | def __delete_job(self, uuid, complete = True): dir_job = self.__get_dir_job(uuid) if complete: for file in os.listdir(dir_job): os.unlink(os.path.join(dir_job, file)) os.rmdir(dir_job) else: file_job = self.__get_file_job(uuid) if os.path.exists(file_job): os.unlink(file_job) print "Job deleted (" + file_job + ")" | |
m.SetBoundsSeperatly(Angle.degrees(float(template["LATMIN"])), Angle.degrees(float(template["LATMAX"])), Angle.degrees(float(template["LONMIN"])), Angle.degrees(float(template["LONMAX"]))) | m.SetBoundsSeperatly(Angle.degrees(float(template["LATMIN"].replace(",", "."))), Angle.degrees(float(template["LATMAX"].replace(",", "."))), Angle.degrees(float(template["LONMIN"].replace(",", "."))), Angle.degrees(float(template["LONMAX"].replace(",", ".")))) | def convert(template, working_dir): if not "NAME" in template: print "Template file has no NAME specified!" return name = template["NAME"] lkm_file = os.path.join(working_dir, name + ".LKM") xcm_file = os.path.join(working_dir, name + ".xcm") if os.path.exists(xcm_file): os.unlink(xcm_file) if not os.path.exists(lk... |
return | def merge_tiles(destination, tiles): print "Merging terrain tiles ..." if os.path.exists(destination + "terrain_merged.tif"): return os.unlink(destination + "terrain_merged.tif") args = [cmd_gdal_merge, "-n", "-32768", "-init", "-32768", "-o", os.path.relpath(destination + "terrain_merged.tif")] args.extend(tiles) p =... | |
return | def resample(destination): print "Resampling terrain ..." if os.path.exists(destination + "terrain_resampled.tif"): return os.unlink(destination + "terrain_resampled.tif") # 1 px = 3 arc seconds seconds_per_pixel = 3.0 degree_per_pixel = seconds_per_pixel / 3600.0 args = [cmd_gdal_warp, "-r", "cubicspline", "-tr", st... | |
return | def crop(destination, rc): print "Cropping terrain ..." if os.path.exists(destination + "terrain.tif"): return os.unlink(destination + "terrain.tif") args = [cmd_gdal_warp, "-srcnodata", "-1", "-dstnodata", "-1", "-te", str(rc.left.value_degrees()), str(rc.bottom.value_degrees()), str(rc.right.value_degrees()), str(rc... | |
return os.path.join(dir_temp, "/topology.tpl") | return os.path.join(dir_temp, "topology.tpl") | def __create_index_file(dir_temp): file = open(os.path.join(dir_temp, "topology.tpl"), "w") file.write("* filename,range,icon,field\n"); file.write("inwaterahydro_area, 100,,,64,96,240\n"); file.write("watrcrslhydro_line, 7,,,64,96,240\n"); file.write("builtupapop_area, 15,,1,223,223,0\n"); file.write("roadltrans_l... |
p = subprocess.Popen(args) | try: p = subprocess.Popen(args) except OSError, WindowsError: print ("There has been a problem running the gdalwarp application "+ "that creates the appropriate GeoTIFF terrain file!") print ("Please check the \"cmd_gdal_warp\" variable in the "+ "terrain_srtm module and modify it if necessary.") print "Current value: ... | def __create(dir_temp, tiles, arcseconds_per_pixel, bounds): print "Resampling terrain ..." output_file = os.path.join(dir_temp, "terrain.tif") if os.path.exists(output_file): os.unlink(output_file) degree_per_pixel = float(arcseconds_per_pixel) / 3600.0 args = [cmd_gdal_warp, "-r", "cubic", "-tr", str(degree_per_pix... |
p = subprocess.Popen(args) | try: p = subprocess.Popen(args) except OSError, WindowsError: print ("There has been a problem running the geojasper application "+ "that converts the GeoTIFF terrain file to GeoJP2!") print ("Please check the \"cmd_geojasper\" variable in the "+ "terrain_srtm module and modify it if necessary.") print "Current value: ... | def __convert(dir_temp, input_file, rc): print "Converting terrain to JP2 format ..." output_file = os.path.join(dir_temp, "terrain.jp2") if os.path.exists(output_file): os.unlink(output_file) args = [cmd_geojasper, "-f", input_file, "-F", output_file, "-T", "jp2", "-O", "rate=0.1", "-O", "tilewidth=256", "-O", "tileh... |
if str.endswith("ft"): | if str.endswith("ft") or str.endswith("f"): | def __parse_winpilot_altitude(self, str): str = str.lower() if str.endswith("ft"): str = str.rstrip("ft") return int(str) * 0.3048 else: str = str.rstrip("m") return int(str) |
f = open(filename, 'f') | f = open(filename, 'r') | def parse_file(self, filename): f = open(filename, 'f') try: return self.parse(f, os.path.splitext(filename)[1]) finally: f.close() |
return self.parse(f, os.path.splitext(filename)[1]) | return self.parse(f, filename) | def parse_file(self, filename): f = open(filename, 'f') try: return self.parse(f, os.path.splitext(filename)[1]) finally: f.close() |
def parse(self, lines, ext = 'dat'): if ext == 'dat' or ext == 'xcw': | def parse(self, lines, filename = 'unknown.dat'): if filename.endswith('.xcw') or filename.endswith('.dat'): | def parse(self, lines, ext = 'dat'): if ext == 'dat' or ext == 'xcw': self.__parse_winpilot(lines) else: raise RuntimeError, 'Waypoint format ' + type + ' is not supported' return self |
raise RuntimeError, 'Waypoint format ' + type + ' is not supported' | raise RuntimeError, 'Waypoint file ' + filename + ' is not supported' | def parse(self, lines, ext = 'dat'): if ext == 'dat' or ext == 'xcw': self.__parse_winpilot(lines) else: raise RuntimeError, 'Waypoint format ' + type + ' is not supported' return self |
print files | def AddTopology(self): print "Adding topology ...", if self.__bounds == None: print "failed!" print "(Boundaries undefined!)" return False print "" o = ogr2ogr() files = o.copy_clipped(self.__bounds, self.__dir_temp) print files self.__files.extend(files) self.__files.append([o.generate_tpl_file(self.__dir_temp), True... | |
zip = ZipFile(os.path.join(dir_data, filename + ".zip"), "r") | try: zip = ZipFile(os.path.join(dir_data, filename + ".zip"), "r") except BadZipfile: print "Decompression of the file "+filename+".zip failed!" print "Please verify the file's integrity before continuing." raise | def __gather_tile(dir_data, dir_temp, lat, lon): # generate filename to search for filename = __get_tile_name(lat, lon) if filename == None: return None # check if the GeoTIFF file already exists in the temporary folder if os.path.exists(os.path.join(dir_temp, filename + ".tif")): print "Tile " + filename + " found!" ... |
m.AddWaypointFile(job.waypoint_file) m.SetBoundsByWaypointFile(job.waypoint_file) | m.AddWaypointFile(os.path.normpath(job.waypoint_file)) m.SetBoundsByWaypointFile(os.path.normpath(job.waypoint_file)) | def __execute_job(self, job): if job.command == "generate": print "Command \"generate\" found. Generating map file." if job.output_file == None: print "No output file set. Aborting." self.__delete_job(job.file_job) return |
m.AddWaypointDetailsFile(job.waypoint_details_file) | m.AddWaypointDetailsFile(os.path.normpath(job.waypoint_details_file)) | def __execute_job(self, job): if job.command == "generate": print "Command \"generate\" found. Generating map file." if job.output_file == None: print "No output file set. Aborting." self.__delete_job(job.file_job) return |
m.AddAirspaceFile(job.airspace_file) | m.AddAirspaceFile(os.path.normpath(job.airspace_file)) | def __execute_job(self, job): if job.command == "generate": print "Command \"generate\" found. Generating map file." if job.output_file == None: print "No output file set. Aborting." self.__delete_job(job.file_job) return |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.