rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
... self.items = [] | ... self.items = {} ... self.next_id = 1 | ... def __init__(self): |
... self.items.append(MockBooking(**kwargs)) | ... booking_id = str(self.next_id) ... self.next_id += 1 ... self.items[booking_id] = MockBooking(**kwargs) ... return booking_id | ... def invokeFactory(self, type, **kwargs): |
... return [x.id for x in self.items] | ... return self.items.keys() ... def get(self, id): ... return self.items.get(id) | ... def objectIds(self): |
>>> booking = context.items[0] | >>> booking = context.get('1') | ... def objectIds(self): |
>>> booking = context.items[-1] | >>> booking = context.get('2') | ... def objectIds(self): |
>>> booking = context.items[-1] | >>> booking = context.get('3') | ... def objectIds(self): |
>>> booking = context.items[-1] | >>> booking = context.get('4') | ... def objectIds(self): |
context.invokeFactory('Booking', id=str(idx), title=title, hours=hours, minutes=minutes, description=description, bookingDate=day) | booking_id = context.invokeFactory( 'Booking', id=str(idx), title=title, hours=hours, minutes=minutes, description=description, bookingDate=day) obj = context.get(booking_id) obj.unmarkCreationFlag() | ... def objectIds(self): |
u = User.objects.get(id=int(id)) | try: u = User.objects.get(id=int(id)) except User.DoesNotExist: continue | def member_list(request, eid=None): if 'event' in request.REQUEST: return HttpResponseRedirect('/member_list/%s/' % request.REQUEST['event']) if request.method == 'POST': if not request.user.profile.is_admin: message(request, 'Error: you are not an administrator!') return HttpResponseRedirect('/member_list') action = r... |
return render_template('errors/404.mako', request, parent='../base.mako' if request.user else '../layout.mako') | return render_template('errors/404.mako', request, parent='../base.mako' if request.user.is_authenticated() else '../layout.mako') | def custom404(request): print request.user return render_template('errors/404.mako', request, parent='../base.mako' if request.user else '../layout.mako') |
return render_template('errors/500.mako', request, parent='../base.mako' if request.user else '../layout.mako') | return render_template('errors/500.mako', request, parent='../base.mako' if request.user.is_authenticated() else '../layout.mako') | def custom500(request): return render_template('errors/500.mako', request, parent='../base.mako' if request.user else '../layout.mako') |
for event in chapter.calendar_events.filter(date__gte=datetime.date.today()): | for event in (chapter.link or chapter).calendar_events.filter(date__gte=datetime.date.today()): | def calendar(request): if 'chapter' not in request.GET: return HttpResponse('No chapter specified.') chapter = Chapter.objects.get(id=int(request.GET['chapter'])) if 'key' not in request.GET or chapter.calendar_key != request.GET['key']: return HttpResponse('Invalid key specified.') cal = vobject.iCalendar() cal.add('m... |
confirm_password = request.POST['password'] | confirm_password = request.POST['confirm_password'] | def reset_password(request): if request.method == 'POST': if 'username' in request.POST: try: user = User.objects.get(Q(username=request.POST['username']) | Q(email=request.POST['username'])) except User.DoesNotExist: return render_template('registration/request_reset.mako', request, error_msg='Unknown username or emai... |
return render_template('registration/perform_reset.mako', reques, user=uid, auth=auth , error_msg='Error: passwords do not match.') | return render_template('registration/perform_reset.mako', request, user=uid, auth=auth , error_msg='Error: passwords do not match.') | def reset_password(request): if request.method == 'POST': if 'username' in request.POST: try: user = User.objects.get(Q(username=request.POST['username']) | Q(email=request.POST['username'])) except User.DoesNotExist: return render_template('registration/request_reset.mako', request, error_msg='Unknown username or emai... |
return render_template('registration/perform_reset.mako', request, user=uid, auth=auth ) | return render_template('registration/perform_reset.mako', request, uid=uid, auth=auth ) | def reset_password(request): if request.method == 'POST': if 'username' in request.POST: try: user = User.objects.get(Q(username=request.POST['username']) | Q(email=request.POST['username'])) except User.DoesNotExist: return render_template('registration/request_reset.mako', request, error_msg='Unknown username or emai... |
gtk.main() | if _main_loop: _main_loop.run() else: gtk.main() | def run(self): self.success = False self._timeout_count = 0 |
if gtk.main_level(): gtk.main_quit() | if _main_loop: _main_loop.quit() else: if gtk.main_level(): gtk.main_quit() | def _timeout_cb(self): if self.success: # dispose of previous waiters. return False self._timeout_count += 1 self.poll() if self._timeout_count >= self.timeout or self.success: try: if gtk.main_level(): gtk.main_quit() except RuntimeError: # In Mandriva RuntimeError exception is thrown # If, gtk.main was already quit p... |
if gtk.main_level(): gtk.main_quit() | if _main_loop: _main_loop.quit() else: if gtk.main_level(): gtk.main_quit() | def _event_cb(self, event): self.event_cb(event) if self.success: try: if gtk.main_level(): gtk.main_quit() except RuntimeError: # In Mandriva RuntimeError exception is thrown # If, gtk.main was already quit pass |
''' | """ | def generatemouseevent(self, x, y, eventType = 'b1c'): ''' Generate mouse event on x, y co-ordinates. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: int @param object_name: Object name to look for, either full name, LDTP's name convention, or a... |
''' | """ | def mouseleftclick(self, window_name, object_name): ''' Mouse left click on an object. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. ... |
''' | """ | def mousemove(self, window_name, object_name): ''' Mouse move on an object. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. Or menu hei... |
''' | """ | def mouserightclick(self, window_name, object_name): ''' Mouse right click on an object. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob... |
''' | """ | def doubleclick(self, window_name, object_name): ''' Double click on the object @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. Or menu... |
if cls._isRemoteMethod(d[attr]) and cls._isRelevant(d[attr]): | if cls._isRemoteMethod(d[attr]): | def __new__(cls, *args, **kwargs): if not cls._generated: cls._generated = True d = ldtp.__dict__ cls._wrapped_methods =[] for attr in d: if cls._isRemoteMethod(d[attr]) and cls._isRelevant(d[attr]): setted = attr if hasattr(cls, attr): setted = "_remote_"+setted cls._wrapped_methods.append(setted) setattr(cls, setted,... |
def getchild(self, child_name='', role=''): matches = self._remote_getchild(child_name, role, True) if matches: if role: return [Component(self._window_name, matches[0])] else: return Component(self._window_name, matches[0]) else: return None | def getchild(self, child_name='', role=''): # TODO: Bad API choice. Inconsistent, should return object or list, # not both. UPDATE: Only returns first match. matches = self._remote_getchild(child_name, role, True) if matches: if role: return [Component(self._window_name, matches[0])] else: return Component(self._window... | |
self._callback = {} | def __init__(self): lazy_load = True self._states = {} self._state_names = {} self._callback = {} self._window_uptime = {} self._callback_event = [] self._get_all_state_names() self._handle_table_cell = False self._desktop = pyatspi.Registry.getDesktop(0) if Utils.cached_apps is None: pyatspi.Registry.registerEventList... | |
for app in list(self.cached_apps): | for app in self.cached_apps: | def _list_apps(self): for app in list(self.cached_apps): if not app: continue yield app |
for app in list(self.cached_apps): | for app in self.cached_apps: | def _list_guis(self): for app in list(self.cached_apps): if not app: continue try: for gui in app: if not gui: continue yield gui except LookupError: self.cached_apps.remove(app) |
try: if acc.name == name: | if acc.name == name: return 1 _ldtpize_accessible_name = self._ldtpize_accessible(acc) _object_name = u'%s%s' % (_ldtpize_accessible_name[0], _ldtpize_accessible_name[1]) if _object_name == name: return 1 if self._glob_match(name, acc.name): return 1 if self._glob_match(name, _object_name): return 1 role = acc.getRole(... | def _match_name_to_acc(self, name, acc): try: if acc.name == name: return 1 _ldtpize_accessible_name = self._ldtpize_accessible(acc) _object_name = u'%s%s' % (_ldtpize_accessible_name[0], _ldtpize_accessible_name[1]) if _object_name == name: return 1 if self._glob_match(name, acc.name): return 1 if self._glob_match(nam... |
_ldtpize_accessible_name = self._ldtpize_accessible(acc) _object_name = u'%s%s' % (_ldtpize_accessible_name[0], _ldtpize_accessible_name[1]) if _object_name == name: | if acc['label']: _tmp_name = re.sub(strip, '', acc['label']) if self._glob_match(obj_name, _tmp_name): | def _match_name_to_acc(self, name, acc): try: if acc.name == name: return 1 _ldtpize_accessible_name = self._ldtpize_accessible(acc) _object_name = u'%s%s' % (_ldtpize_accessible_name[0], _ldtpize_accessible_name[1]) if _object_name == name: return 1 if self._glob_match(name, acc.name): return 1 if self._glob_match(nam... |
if self._glob_match(name, acc.name): return 1 if self._glob_match(name, _object_name): return 1 role = acc.getRole() if role == pyatspi.ROLE_FRAME or role == pyatspi.ROLE_DIALOG or \ role == pyatspi.ROLE_WINDOW or \ role == pyatspi.ROLE_FONT_CHOOSER or \ role == pyatspi.ROLE_FILE_CHOOSER or \ role == pyatspi.ROLE_ALERT... | if self._glob_match(obj_name, acc['key']): | def _match_name_to_acc(self, name, acc): try: if acc.name == name: return 1 _ldtpize_accessible_name = self._ldtpize_accessible(acc) _object_name = u'%s%s' % (_ldtpize_accessible_name[0], _ldtpize_accessible_name[1]) if _object_name == name: return 1 if self._glob_match(name, acc.name): return 1 if self._glob_match(nam... |
if child and child.getRole() == pyatspi.ROLE_TABLE_CELL and \ | if child.getRole() == pyatspi.ROLE_TABLE_CELL and \ | def _list_objects(self, obj): if obj: yield obj for child in obj: if child and child.getRole() == pyatspi.ROLE_TABLE_CELL and \ not self._handle_table_cell: # In OO.o navigating table cells consumes more time # and resource break for c in self._list_objects(child): yield c |
try: if obj: for child in obj: if not child: continue if child.childCount > 0: child_obj = self._get_combo_child_object_type(child) if child_obj: return child_obj if child.getRole() == pyatspi.ROLE_LIST: return child elif child.getRole() == pyatspi.ROLE_MENU: return child except: pass return None | if obj: for child in obj: if not child: continue if child.childCount > 0: child_obj = self._get_combo_child_object_type(child) if child_obj: return child_obj if child.getRole() == pyatspi.ROLE_LIST: return child elif child.getRole() == pyatspi.ROLE_MENU: return child | def _get_combo_child_object_type(self, obj): """ This function will check for all levels and returns the first matching LIST / MENU type """ try: if obj: for child in obj: if not child: continue if child.childCount > 0: child_obj = self._get_combo_child_object_type(child) if child_obj: return child_obj if child.getRole... |
try: if obj and role_type: for child in obj: if not child: continue if child.childCount > 0: child_obj = self._get_child_object_type(child, role_type) if child_obj: return child_obj if child.getRole() == role_type: return child except: pass return None def _appmap_pairs(self, gui): ldtpized_list = [] ldtpized_obj_inde... | if obj and role_type: for child in obj: if not child: continue if child.childCount > 0: child_obj = self._get_child_object_type(child, role_type) if child_obj: return child_obj if child.getRole() == role_type: return child def _add_appmap_data(self, obj, parent): abbrev_role, abbrev_name = self._ldtpize_accessible(obj... | def _get_child_object_type(self, obj, role_type): """ This function will check for all levels and returns the first matching role_type """ try: if obj and role_type: for child in obj: if not child: continue if child.childCount > 0: child_obj = self._get_child_object_type(child, role_type) if child_obj: return child_obj... |
if not re.search('^mnu', _menu_hierarchy[0]): _menu_hierarchy[0] = 'mnu%s' % _menu_hierarchy[0] | def _get_menu_hierarchy(self, window_name, object_name): _menu_hierarchy = re.split(';', object_name) # Get handle of menu obj = self._get_object(window_name, _menu_hierarchy[0]) # Navigate all sub-menu under a menu for _menu in _menu_hierarchy[1:]: _flag = False for _child in self._list_objects(obj): if obj == _child:... | |
_flag = True | def _get_menu_hierarchy(self, window_name, object_name): _menu_hierarchy = re.split(';', object_name) # Get handle of menu obj = self._get_object(window_name, _menu_hierarchy[0]) # Navigate all sub-menu under a menu for _menu in _menu_hierarchy[1:]: _flag = False for _child in self._list_objects(obj): if obj == _child:... | |
"Menu item %s doesn't exist in hierarchy" % _menu) | 'Menu item "%s" doesn\'t exist in hierarchy' % _menu) | def _get_menu_hierarchy(self, window_name, object_name): _menu_hierarchy = re.split(';', object_name) # Get handle of menu obj = self._get_object(window_name, _menu_hierarchy[0]) # Navigate all sub-menu under a menu for _menu in _menu_hierarchy[1:]: _flag = False for _child in self._list_objects(obj): if obj == _child:... |
raise LdtpServerException('Object does not have a "click" action') | raise LdtpServerException('Object does not have a "%s" action' % action) def _get_object_in_window(self, appmap, obj_name): for name in appmap.keys(): obj = appmap[name] if self._match_name_to_appmap(obj_name, obj): return obj return None | def _click_object(self, obj, action = 'click'): try: iaction = obj.queryAction() except NotImplementedError: raise LdtpServerException( 'Object does not have an Action interface') else: for i in xrange(iaction.nActions): if re.match(action, iaction.getName(i)): iaction.doAction(i) return raise LdtpServerException('Obje... |
def _get_object_info(self, window_name, obj_name): | def _get_object(self, window_name, obj_name): | def _get_object_info(self, window_name, obj_name): _window_handle = self._get_window_handle(window_name) if not _window_handle: raise LdtpServerException('Unable to find window "%s"' % \ window_name) for name, obj, obj_index in self._appmap_pairs(_window_handle): if self._glob_match(obj_name, obj_index) or \ self._matc... |
for name, obj, obj_index in self._appmap_pairs(_window_handle): if self._glob_match(obj_name, obj_index) or \ self._match_name_to_acc(obj_name, obj) or \ self._match_name_to_appmap(obj_name, name): return name, obj, obj_index raise LdtpServerException( 'Unable to find object name "%s" in application map' % obj_name) d... | appmap = self._appmap_pairs(_window_handle) obj = self._get_object_in_window(appmap, obj_name) if not obj: appmap = self._appmap_pairs(_window_handle, force_remap = True) obj = self._get_object_in_window(appmap, obj_name) if not obj: raise LdtpServerException( 'Unable to find object name "%s" in application map' % obj... | def _get_object_info(self, window_name, obj_name): _window_handle = self._get_window_handle(window_name) if not _window_handle: raise LdtpServerException('Unable to find window "%s"' % \ window_name) for name, obj, obj_index in self._appmap_pairs(_window_handle): if self._glob_match(obj_name, obj_index) or \ self._matc... |
else: self._ldtp_debug = None | def __init__(self): lazy_load = True self._states = {} self._appmap = {} self._callback = {} self._state_names = {} self._window_uptime = {} self._callback_event = [] self._get_all_state_names() self._handle_table_cell = False self._desktop = pyatspi.Registry.getDesktop(0) if Utils.cached_apps is None: pyatspi.Registry... | |
@param cmdline: Command line string to execute. @type cmdline: string | @param cmd: Command line string to execute. @type cmd: string | def launchapp(self, cmd, args = [], delay = 0, env = 1): ''' Launch application. |
print 'obj', obj | def _get_menu_hierarchy(self, window_name, object_name): _menu_hierarchy = re.split(';', object_name) if not re.search('^mnu', _menu_hierarchy[0]): _menu_hierarchy[0] = 'mnu%s' % _menu_hierarchy[0] obj = self._get_object(window_name, _menu_hierarchy[0]) for _menu in _menu_hierarchy[1:]: _flag = False print 'obj', obj f... | |
print '_child', _child | def _get_menu_hierarchy(self, window_name, object_name): _menu_hierarchy = re.split(';', object_name) if not re.search('^mnu', _menu_hierarchy[0]): _menu_hierarchy[0] = 'mnu%s' % _menu_hierarchy[0] obj = self._get_object(window_name, _menu_hierarchy[0]) for _menu in _menu_hierarchy[1:]: _flag = False print 'obj', obj f... | |
def _click_object(self, obj, action = 'click'): | def _click_object(self, obj, action = '(click|press|activate)'): | def _click_object(self, obj, action = 'click'): try: iaction = obj.queryAction() except NotImplementedError: raise LdtpServerException( 'Object does not have an Action interface') else: for i in xrange(iaction.nActions): if re.match(action, iaction.getName(i)): iaction.doAction(i) return raise LdtpServerException('Obje... |
''' | """ | def imagecapture(self, window_name = None, x = 0, y = 0, width = None, height = None): ''' Captures screenshot of the whole desktop or given window @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param x: x co-ordinate value @type x: int... |
def _ebRender(self, failure): '''Custom error render method (used by our XMLRPC objects)''' if isinstance(failure.value, xmlrpclib.Fault): return failure.value | if not _ldtp_debug: def _ebRender(self, failure): '''Custom error render method (used by our XMLRPC objects)''' if isinstance(failure.value, xmlrpclib.Fault): return failure.value | def _ebRender(self, failure): '''Custom error render method (used by our XMLRPC objects)''' if isinstance(failure.value, xmlrpclib.Fault): return failure.value |
x, y, resolution2, resolution1 = bb.x, bb.y, bb.height, bb.width | x, y, height, width = bb.x, bb.y, bb.height, bb.width | def imagecapture(self, window_name = None, x = 0, y = 0, width = None, height = None): ''' Captures screenshot of the whole desktop or given window @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param x: x co-ordinate value @type x: int... |
@return: list of integers on success. | @return: list of string on success | def getallstates(self, window_name, object_name): ''' Get all states of given object @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. @t... |
_obj_states.append(state.real) | _obj_states.append(self._state_names[state.real]) | def getallstates(self, window_name, object_name): ''' Get all states of given object @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. @t... |
_state = obj.getState() _obj_state = _state.getStates() | _state_inst = obj.getState() _obj_state = _state_inst.getStates() | def hasstate(self, window_name, object_name, state): ''' has state @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. @type object_name: s... |
print "ldtpd exited!" | if _ldtp_debug: print "ldtpd exited!" | def _handle_signal(self, signum, frame): if os.environ.has_key('LDTP_DEBUG'): if signum == signal.SIGCHLD: print "ldtpd exited!" elif signum == signal.SIGUSR1: print "SIGUSR1 received. ldtpd ready for requests." elif signum == signal.SIGALRM: print "SIGALRM received. Timeout waiting for SIGUSR1." |
print "SIGUSR1 received. ldtpd ready for requests." | if _ldtp_debug: print "SIGUSR1 received. ldtpd ready for requests." | def _handle_signal(self, signum, frame): if os.environ.has_key('LDTP_DEBUG'): if signum == signal.SIGCHLD: print "ldtpd exited!" elif signum == signal.SIGUSR1: print "SIGUSR1 received. ldtpd ready for requests." elif signum == signal.SIGALRM: print "SIGALRM received. Timeout waiting for SIGUSR1." |
print "SIGALRM received. Timeout waiting for SIGUSR1." | if _ldtp_debug: print "SIGALRM received. Timeout waiting for SIGUSR1." | def _handle_signal(self, signum, frame): if os.environ.has_key('LDTP_DEBUG'): if signum == signal.SIGCHLD: print "ldtpd exited!" elif signum == signal.SIGUSR1: print "SIGUSR1 received. ldtpd ready for requests." elif signum == signal.SIGALRM: print "SIGALRM received. Timeout waiting for SIGUSR1." |
self._daemon = subprocess.Popen( ['python', '-c', 'import ldtpd; ldtpd.main()'], close_fds = True) | self._daemon = os.spawnlp(os.P_NOWAIT, 'python', 'python', '-c', 'import ldtpd; ldtpd.main()') | def _spawn_daemon(self): self._daemon = subprocess.Popen( ['python', '-c', 'import ldtpd; ldtpd.main()'], close_fds = True) |
self._daemon.kill() | os.kill(self._daemon, 9) | def kill_daemon(self): try: self._daemon.kill() except AttributeError: pass |
raise LdtpServerException('Could not find a child.') | if child_name: _name = 'name "%s" ' % child_name if role: _role = 'role "%s" ' % role if parent: _parent = 'parent "%s"' % parent exception = 'Could not find a child %s%s%s' % (_name, _role, _parent) raise LdtpServerException(exception) | def _get_all_children_under_obj(obj, child_list): if role and obj['class'] == role: child_list.append(obj['key']) elif child_name and self._match_name_to_appmap(child_name, obj): child_list.append(obj['key']) if obj: children = obj['children'] if not children: return child_list for child in children: return _get_all_ch... |
@rtype: string | @rtype: list | def getcpustat(self, process_name): """ get CPU stat for the give process name |
'`' : 49, '\\' : 51, ' :' : 59, | '`' : 49, '\\' : 51, ',' : 59, | def _get_key_value(self, keyval): # A - Z / a - z _char_key = {'a' : 38, 'b' : 56, 'c' : 54, 'd' : 40, 'e' : 26, 'f' : 41, 'g' : 42, 'h' : 43, 'i' : 31, 'j' : 44, 'k' : 45, 'l' : 46, 'm' : 58, 'n' : 57, 'o' : 32, 'p' : 33, 'q' : 24, 'r' : 27, 's' : 39, 't' : 28, 'u' : 30, 'v' : 55, 'w' : 25, 'x' : 53, 'y' : 29, 'z' : 5... |
return HttpResponse(json.dumps(response), | return HttpResponse(json.dumps(response, indent=2), | def geotag(request): """ accepts a block of text, extracts addresses, locations and places and geocodes them. """ # XXX this is very brutal and wacky looking... # it re-uses as much of the existing way of doing things # as possible without regard to time costs or instanity of # interface. Once this has a more clear fo... |
Block.objects.exclude(right_city=SHORT_NAME.upper()).exclude(left_city=SHORT_NAME.upper()).delete() | Block.objects.exclude(right_city=settings.SHORT_NAME.upper()).exclude(left_city=settings.SHORT_NAME.upper()).delete() | def update_block_numbers(): Block.objects.exclude(right_city=SHORT_NAME.upper()).exclude(left_city=SHORT_NAME.upper()).delete() for b in Block.objects.all(): (from_num, to_num) = make_block_numbers(b.left_from_num, b.left_to_num, b.right_from_num, b.right_to_num) if b.from_num != from_num and b.to_num != to_num: b.from... |
item.location_name = e['x-calconnect-street'] item.item_date = datetime.datetime.strptime(e.dtstart, "%Y-%m-%d %H:%M:%S +0000") | item.item_date = datetime.datetime(*e.updated_parsed[:6]) | def main(argv=None): url = 'http://calendar.boston.com/search?acat=&cat=&commit=Search&new=n&rss=1&search=true&sort=0&srad=20&srss=50&ssrss=5&st=event&st_select=any&svt=text&swhat=&swhen=today&swhere=&trim=1' schema = 'events' try: schema = Schema.objects.get(slug=schema) except Schema.DoesNotExist: print "Schema (%s)... |
try: add = geocoder.geocode(item.location_name) item.location = add['point'] item.block = add['block'] except: pass item.save() print "Added: %s" % item.title | def main(argv=None): url = 'http://calendar.boston.com/search?acat=&cat=&commit=Search&new=n&rss=1&search=true&sort=0&srad=20&srss=50&ssrss=5&st=event&st_select=any&svt=text&swhat=&swhen=today&swhere=&trim=1' schema = 'events' try: schema = Schema.objects.get(slug=schema) except Schema.DoesNotExist: print "Schema (%s)... | |
status = "Updated" | status = "updated" | def main(): """ Download Calendar RSS feed and update database """ logger.info("Starting add_events") url = """http://calendar.boston.com/search?acat=&cat=&commit=Search\ |
status = "Added" | status = "added" | def main(): """ Download Calendar RSS feed and update database """ logger.info("Starting add_events") url = """http://calendar.boston.com/search?acat=&cat=&commit=Search\ |
summary_detail = list_record['summary_detail']['value'] content = list_record['summary'] content = content.replace(summary_detail, '') import re address_re = re.compile(r'Address: (.*?)<br />') addr = address_re.search(summary_detail) if addr: addr = addr.group(1) location_name = ', '.join([part.strip() for part in ad... | def save(self, old_record, list_record, detail_record): kwargs = self.pk_fields(list_record) summary_detail = list_record['summary_detail']['value'] content = list_record['summary'] # remove address and rating from content, i guess. content = content.replace(summary_detail, '') import re address_re = re.compile(r'Addre... | |
kwargs.update(dict( description=list_record['summary_detail']['value'], location_name=location_name, location=location, )) | summary_detail = list_record['summary_detail']['value'] content = list_record['summary'] content = address_re.sub('', content) content = rating_re.sub('', content) kwargs.update(dict(description=content, location=location, )) | def save(self, old_record, list_record, detail_record): kwargs = self.pk_fields(list_record) summary_detail = list_record['summary_detail']['value'] content = list_record['summary'] # remove address and rating from content, i guess. content = content.replace(summary_detail, '') import re address_re = re.compile(r'Addre... |
block = location = None if 'location' not in kwargs: | block = kwargs.get('block') location = kwargs.get('location') location_name = kwargs.get('location_name') assert location or location_name, "At least one of location or location_name must be provided" if location is None: | def create_newsitem(self, attributes, **kwargs): """ Creates and saves a NewsItem with the given kwargs. Returns the new NewsItem. |
location=kwargs.get('location', location), location_name=kwargs['location_name'], | location=location, location_name=location_name, | def create_newsitem(self, attributes, **kwargs): """ Creates and saves a NewsItem with the given kwargs. Returns the new NewsItem. |
block=kwargs.get('block', block), | block=block, | def create_newsitem(self, attributes, **kwargs): """ Creates and saves a NewsItem with the given kwargs. Returns the new NewsItem. |
def __init__(self, shapefile, city=None, layer_id=0): | def __init__(self, shapefile, city=None, layer_id=0, encoding='utf8', verbose=False): self.verbose = verbose self.encoding = encoding | def __init__(self, shapefile, city=None, layer_id=0): ds = DataSource(shapefile) self.layer = ds[layer_id] self.city = city and city or Metro.objects.get_current().name self.fcc_pat = re.compile('^(' + '|'.join(VALID_FCC_PREFIXES) + ')\d$') |
response = TileResponse(render_tile(layername, z, x, y, extension=extension)) | response = TileResponse(render_tile(layername, z, x, y, extension='png')) | def get_tile(request, version, layername, z, x, y, extension='png'): 'Returns a map tile in the requested format' z, x, y = int(z), int(x), int(y) response = TileResponse(render_tile(layername, z, x, y, extension=extension)) return response(extension) |
self.params['is_multi'] = False geom_type = value.geom_type.upper() | def render(self, name, value, attrs=None): # Update the template parameters with any attributes passed in. if attrs: self.params.update(attrs) | |
self.params['geom_type'] = OGRGeomType(value.geom_type) if geom_type == 'LINESTRING': self.params['is_linestring'] = True elif geom_type == 'POLYGON': self.params['is_polygon'] = True elif geom_type == 'MULTIPOLYGON': self.params['is_polygon'] = True self.params['is_multi'] = False elif geom_type == 'POINT': self.para... | self.params['geom_type'] = OGRGeomType(value.geom_type) if value.geom_type.upper() in ('LINESTRING', 'MULTILINESTRING'): self.params['is_linestring'] = True elif value.geom_type.upper() in ('POLYGON', 'MULTIPOLYGON'): self.params['is_polygon'] = True elif value.geom_type.upper() in ('POINT', 'MULTIPOINT'): self.params[... | def render(self, name, value, attrs=None): # Update the template parameters with any attributes passed in. if attrs: self.params.update(attrs) |
user_settings_module = '%s.settings' % (options.app, options.user_settings) | user_settings_module = '%s.settings' % options.app | def get_app_settings(options): settings_module = '%s.settings_default' % options.app user_settings_module = '%s.settings' % (options.app, options.user_settings) try: __import__(settings_module) except: exit_with_traceback("Problem with %s or %s, see above" % (settings_module, user_settings_module)) return sys.modules[s... |
__import__(settings_module) | __import__(user_settings_module) | def get_app_settings(options): settings_module = '%s.settings_default' % options.app user_settings_module = '%s.settings' % (options.app, options.user_settings) try: __import__(settings_module) except: exit_with_traceback("Problem with %s or %s, see above" % (settings_module, user_settings_module)) return sys.modules[s... |
return sys.modules[settings_module] | return sys.modules[user_settings_module] | def get_app_settings(options): settings_module = '%s.settings_default' % options.app user_settings_module = '%s.settings' % (options.app, options.user_settings) try: __import__(settings_module) except: exit_with_traceback("Problem with %s or %s, see above" % (settings_module, user_settings_module)) return sys.modules[s... |
item = NewsItem.objects.get(schema__id=schema.id, title=entry.title, description=entry.description) | item = NewsItem.objects.get(schema__id=schema.id, url=entry.link) | def main(argv=None): logger.info("Starting add_news") if argv: url = argv[0] else: url = 'http://search.boston.com/search/api?q=*&sort=-articleprintpublicationdate&subject=massachusetts&scope=bonzai' schema_slug = 'local-news' try: schema = Schema.objects.get(slug=schema_slug) except Schema.DoesNotExist: print "Schema... |
addcount = updatecount = 0 | def main(): """ Download Calendar RSS feed and update database """ logger.info("Starting add_events") url = """http://calendar.boston.com/search?acat=&cat=&commit=Search\ | |
item = NewsItem.objects.get(title=entry.title, description=entry.description) | item = NewsItem.objects.get(title=title, schema=schema) | def main(): """ Download Calendar RSS feed and update database """ logger.info("Starting add_events") url = """http://calendar.boston.com/search?acat=&cat=&commit=Search\ |
addcount += 1 except NewsItem.MultipleObjectsReturned: logger.warn("Multiple entries matched title %r, event titles are not unique?" % title) continue | def main(): """ Download Calendar RSS feed and update database """ logger.info("Starting add_events") url = """http://calendar.boston.com/search?acat=&cat=&commit=Search\ | |
item.title = convert_entities(entry.title) | item.title = title | def main(): """ Download Calendar RSS feed and update database """ logger.info("Starting add_events") url = """http://calendar.boston.com/search?acat=&cat=&commit=Search\ |
logger.info("add_events finished") | logger.info("add_events finished: %d added, %d updated" % (addcount, updatecount)) | def main(): """ Download Calendar RSS feed and update database """ logger.info("Starting add_events") url = """http://calendar.boston.com/search?acat=&cat=&commit=Search\ |
return self.schema.slug | return (self.schema.slug,) | def natural_key(self): return self.schema.slug |
item = NewsItem.objects.get(title=entry.title, description=entry.description) | item = NewsItem.objects.get(schema__id=schema.id, title=entry.title, description=entry.description) | def main(argv=None): logger.info("Starting add_news") if argv: url = argv[0] else: url = 'http://search.boston.com/search/api?q=*&sort=-articleprintpublicationdate&subject=massachusetts&scope=bonzai' schema_slug = 'local-news' try: schema = Schema.objects.get(slug=schema_slug) except Schema.DoesNotExist: print "Schema... |
if 'point' in entry: x,y = entry.point.split(' ') elif 'georss_point' in entry: x,y = entry.georss_point.split(' ') | point = entry.get('georss_point') or entry.get('point') if point: x, y = point.split(' ') | def main(argv=None): logger.info("Starting add_news") if argv: url = argv[0] else: url = 'http://search.boston.com/search/api?q=*&sort=-articleprintpublicationdate&subject=massachusetts&scope=bonzai' schema_slug = 'local-news' try: schema = Schema.objects.get(slug=schema_slug) except Schema.DoesNotExist: print "Schema... |
newsitem_qs = kwargs.get('newsitem_qs') or NewsItem.objects.all() | newsitem_qs = kwargs.get('newsitem_qs') if newsitem_qs is None: newsitem_qs = NewsItem.objects.all() | def get_place_info_for_request(request, *args, **kwargs): """ A utility function that abstracts getting commonly used location-related information: a place, its type, a queryset of intersecting NewsItems, a bbox, nearby locations, etc. """ info = dict(bbox=None, nearby_locations=[], location=None, is_block=False, block... |
def test_make_pid__block__not_enough_args(self): | def test_make_pid__block__default_radius(self): | def test_make_pid__block__not_enough_args(self): b = self._makeBlock() self.assertRaises(TypeError, make_pid, b) |
self.assertRaises(TypeError, make_pid, b) | self.assertEqual(make_pid(b), 'b:%d.8' % b.id) | def test_make_pid__block__not_enough_args(self): b = self._makeBlock() self.assertRaises(TypeError, make_pid, b) |
objects = models.Manager() public_objects = SchemaManager() | objects = SchemaManager() public_objects = SchemaPublicManager() | def get_query_set(self): return super(SchemaManager, self).get_query_set().filter(is_public=True) |
objects = models.GeoManager() | objects = LocationManager() | def url(self): return '/locations/%s/' % self.slug |
'b:12;1' (block ID 12, 1-block radius) | 'b:12.1' (block ID 12, 1-block radius) | def parse_pid(pid): """ Returns a tuple of (place, block_radius, xy_radius), where block_radius and xy_radius are None for Locations. PID examples: 'b:12;1' (block ID 12, 1-block radius) 'l:32' (location ID 32) """ try: place_type, place_id = pid.split(':') if place_type == 'b': place_id, block_radius = place_id.split... |
JSON -- expects request.GET['pid'] and request.GET['s'] (a schema ID). | JSON -- expects request.GET['pid'] (a location ID) and request.GET['s'] (a schema ID). Returns a JSON mapping containing {'bunches': {scale: [list of clusters]}, 'ids': [list of newsitem ids]} where clusters are represented as [[list of newsitem IDs], [center x, y]] NB: the list of all newsitem IDs should be the unio... | def ajax_place_newsitems(request): """ JSON -- expects request.GET['pid'] and request.GET['s'] (a schema ID). """ try: s = Schema.public_objects.get(id=int(request.GET['s'])) except (KeyError, ValueError, Schema.DoesNotExist): raise Http404('Invalid Schema') place, block_radius, xy_radius = parse_pid(request.GET.get('p... |
place, block_radius, xy_radius = parse_pid(request.GET.get('pid', '')) | pid = request.GET.get('pid', '') place, block_radius, xy_radius = parse_pid(pid) | def ajax_place_newsitems(request): """ JSON -- expects request.GET['pid'] and request.GET['s'] (a schema ID). """ try: s = Schema.public_objects.get(id=int(request.GET['s'])) except (KeyError, ValueError, Schema.DoesNotExist): raise Http404('Invalid Schema') place, block_radius, xy_radius = parse_pid(request.GET.get('p... |
sh("django-admin.py dbshell --settings=%s < ../../ebpub/ebpub/db/sql/location.sql" % settings_mod) | def sync_all(options): """Use django-admin to initialize all our databases. """ settings_mod = "%s.settings" % options.app settings = get_app_settings(options) for dbname in settings.DATABASE_SYNC_ORDER: sh("django-admin.py syncdb --settings=%s --database=%s --noinput" % (settings_mod, dbname)) for dbname in settings.... | |
yield self.get_html(self.url) | max_per_page = 1000 max_pages = 10 delta = datetime.datetime.now() - self.last_updated_time() hours_ago = math.ceil((delta.seconds / 3600.0) + (delta.days * 24)) for page in range(1, max_pages + 1): url = LIST_URL + '&start=%d&page=%d&num_results=%d' % ( hours_ago, page, max_per_page) yield self.get_html(url) | def list_pages(self): yield self.get_html(self.url) |
unique_fields = self.unique_fields(list_record) qs = NewsItem.objects.filter(schema__id=self.schema.id, **unique_fields) | qs = NewsItem.objects.filter(schema__id=self.schema.id) qs = qs.by_attribute(self.schema_fields['guid'], list_record['id']) | def existing_record(self, list_record): unique_fields = self.unique_fields(list_record) qs = NewsItem.objects.filter(schema__id=self.schema.id, **unique_fields) try: return qs[0] except IndexError: return None |
kwargs = self.unique_fields(list_record) | if old_record is not None: self.logger.info("Stopping, we've already seen %s" % old_record) raise StopScraping() | def save(self, old_record, list_record, detail_record): kwargs = self.unique_fields(list_record) |
location = Point((float(list_record['geo_long']), float(list_record['geo_lat']))) | kwargs = get_unique_fields(list_record) location = self.get_location(list_record) | def save(self, old_record, list_record, detail_record): kwargs = self.unique_fields(list_record) |
print "skipping %r as it has bad location 0,0" % list_record['title'] | self.logger.warn("skipping %r as it has bad location 0,0" % list_record['title']) | def save(self, old_record, list_record, detail_record): kwargs = self.unique_fields(list_record) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.