rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
writer_name = 'html4css' | writer_name = 'html4css1' | def writer_object(cls): """ Return the `docutils` -compliant `Writer` object to send to the `docutils` publisher. """ # Assume this writer is a built-in. return writers.get_writer_class(cls.writer_name)() |
'docutils_xml': DocutilsXmlStrategy, | 'xml': DocutilsXmlStrategy, | def functional_strategies(): for name, Strategy in chain(builtin_writers.items(), pseudo_writers.items(), external_writers.items()): strategy = Strategy() yield name, Strategy |
def check_writers(): functional = nonfunctional = {} for name, Strategy in possible_writers.iteritems(): print('NAME: %s' % name) | def check_writers(writers=possible_writers): functional = {} nonfunctional = {} for name, Strategy in writers.iteritems(): | def check_writers(): functional = nonfunctional = {} for name, Strategy in possible_writers.iteritems(): print('NAME: %s' % name) if Strategy.isfunctional(): functional[name] = Strategy else: nonfunctional[name] = Strategy return functional, nonfunctional |
def get_splits(split_config, names): splits = split_config.splits for name in set(names): yield splits[name] def split(splits, verbose): for split in splits: | def split(split_config, names, verbose): for split in (split_config.splits[name] for name in names): | def get_splits(split_config, names): splits = split_config.splits for name in set(names): yield splits[name] |
split(get_splits(split_config, args), options.verbose) | split(split_config, args, options.verbose) | def main(): repo = open_repo() split_config = open_config(repo) usage = """ %prog (-d) --list %prog (-d) --split [splitname...]""" parser = optparse.OptionParser(usage = usage, version = "%prog 0.1") parser.add_option("-d", "--debug", dest = "debug", action = "store_true", default = False, help = "prints extra debugg... |
if thumbnail_size is not None: if suffix is None: suffix = self.get('suffix', 'jpg') attach_path = self.attach_path(suffix=suffix) thumbnail_path = self.attach_path(suffix=suffix, thumbnail_size=thumbnail_size) if not os.path.isfile(thumbnail_path): size = thumbnail_size.split("x") if len(size) == 2: size = (int(size[0... | if thumbnail_size is None: return if not PIL: return if suffix is None: suffix = self.get('suffix', 'jpg') attach_path = self.attach_path(suffix=suffix) thumbnail_path = self.attach_path(suffix=suffix, thumbnail_size=thumbnail_size) if os.path.isfile(thumbnail_path): return if not imghdr.what(thumbnail_path): return si... | def make_thumbnail(self, suffix=None, thumbnail_size=config.thumbnail_size): if thumbnail_size is not None: if suffix is None: suffix = self.get('suffix', 'jpg') attach_path = self.attach_path(suffix=suffix) thumbnail_path = self.attach_path(suffix=suffix, thumbnail_size=thumbnail_size) if not os.path.isfile(thumbnail_... |
elif 'sign' in self: | if 'sign' in self: | def sync(self, force=False): """Save files.""" if self.removed(): return elif (not force) and self.exists(): pass else: self._write_file(self.path, str(self)+"\n") body = self.body_string()+'\n' if 'attach' in self: attach = base64.decodestring(self['attach']) attach_path = self.attach_path(self.get('suffix', 'txt')) i... |
ids = cache.keys() | def print_thread(self, path, id='', page=0): str_path = self.str_encode(path) file_path = self.file_encode('thread', path) self.archive_uri = '%s%s/' % (config.archive_uri, md5.new(file_path).hexdigest()) cache = Cache(file_path) if cache.has_record(): pass elif self.check_get_cache(): self.get_cache(cache) else: self.... | |
m_type, meth, m_remainder, warning = state._notfound_stack.pop() if warning: warn(warning, DeprecationWarning) if m_type == 'lookup': new_controller, new_remainder = meth(*m_remainder) state.add_controller(new_controller.__class__.__name__, new_controller) dispatcher = getattr(new_controller, '_dispatch', self._dispat... | if not state._notfound_stack: current_controller = state.controller method = getattr(current_controller, 'index') if method: if method_matches_args(method, state.params, remainder, self._use_lax_params): state.add_method(current_controller.index, remainder) return state raise HTTPNotFound | def _dispatch_first_found_default_or_lookup(self, state, remainder): """ When the dispatch has reached the end of the tree but not found an applicable method, so therefore we head back up the branches of the tree until we found a method which matches with a default or lookup method. """ |
assert False, 'Unknown notfound hander %r' % m_type except: | m_type, meth, m_remainder, warning = state._notfound_stack.pop() if warning: warn(warning, DeprecationWarning) if m_type == 'lookup': new_controller, new_remainder = meth(*m_remainder) state.add_controller(new_controller.__class__.__name__, new_controller) dispatcher = getattr(new_controller, '_dispatch', self._dispat... | def _dispatch_first_found_default_or_lookup(self, state, remainder): """ When the dispatch has reached the end of the tree but not found an applicable method, so therefore we head back up the branches of the tree until we found a method which matches with a default or lookup method. """ |
if hasattr(controller, '_dispatch'): | dispatcher = getattr(controller, '_dispatch', None) if dispatcher: | def _dispatch_controller(self, current_path, controller, state, remainder): """ Essentially, this method defines what to do when we move to the next layer in the url chain, if a new controller is needed. If the new controller has a _dispatch method, dispatch proceeds to the new controller's mechanism. |
obj._check_security() | security_check() | def _dispatch_controller(self, current_path, controller, state, remainder): """ Essentially, this method defines what to do when we move to the next layer in the url chain, if a new controller is needed. If the new controller has a _dispatch method, dispatch proceeds to the new controller's mechanism. |
return controller._dispatch(state, remainder) | return dispatcher(state, remainder) | def _dispatch_controller(self, current_path, controller, state, remainder): """ Essentially, this method defines what to do when we move to the next layer in the url chain, if a new controller is needed. If the new controller has a _dispatch method, dispatch proceeds to the new controller's mechanism. |
if hasattr(current_controller, current_path): current_controller = getattr(current_controller, current_path) | current_controller = getattr(current_controller, current_path, None) if current_controller: | def _dispatch(self, state, remainder=None): """ This method defines how the object dispatch mechanism works, including checking for security along the way. """ if state.dispatcher is None: state.dispatcher = self state.add_controller('/', self) if remainder is None: remainder = state.path current_controller = state.con... |
self.assertRaises(ParseError, parse_fetch_response, ['* 2 FETCH (ONE)']) self.assertRaises(ParseError, parse_fetch_response, ['* 2 FETCH (ONE TWO THREE)']) | self.assertRaises(ParseError, parse_fetch_response, ['(ONE)']) self.assertRaises(ParseError, parse_fetch_response, ['(ONE TWO THREE)']) | def test_odd_pairs(self): self.assertRaises(ParseError, parse_fetch_response, ['* 2 FETCH (ONE)']) self.assertRaises(ParseError, parse_fetch_response, ['* 2 FETCH (ONE TWO THREE)']) |
self.assertRaises(ParseError, parse_fetch_response, '* 2 FETCH (UID X)') | self.assertRaises(ParseError, parse_fetch_response, '(UID X)') | def test_bad_UID(self): self.assertRaises(ParseError, parse_fetch_response, '* 2 FETCH (UID X)') |
def extract_folder_names(dat): | def extract_normal_folders(dat): | def extract_folder_names(dat): ret = [] for _, _, folder_name in dat: # gmail's "special" folders start with '[' if not folder_name.startswith('['): ret.append(folder_name) return ret |
folders = extract_folder_names(client.list_folders()) | folders = extract_normal_folders(client.list_folders()) | def test_list_folders(client): clear_folders(client) some_folders = ['simple', r'foo\bar', r'test"folder"'] for name in some_folders: client.create_folder(name) folders = extract_folder_names(client.list_folders()) assert len(folders) > 0, 'No folders visible on server' assert 'INBOX' in [f.upper() for f in folders], ... |
assert "XLIST" in caps, caps if 'XLIST' in caps: info = client.xlist_folders() folders = extract_folder_names(info) assert len(folders) > 0, 'No folders visible on server' for flags, _, _ in info: if '\\INBOX' in [flag.upper() for flag in flags]: break | assert "XLIST" in caps, "expected XLIST in Gmail's capabilities but only got %r" % caps if not 'XLIST' in caps: print "Skipping XLIST tests, server doesn't support XLIST" return info = client.xlist_folders() assert len(info) > 0, 'No folders returned by XLIST' for flags, _, _ in info: if '\\INBOX' in [flag.upper() f... | def test_list_folders(client): clear_folders(client) some_folders = ['simple', r'foo\bar', r'test"folder"'] for name in some_folders: client.create_folder(name) folders = extract_folder_names(client.list_folders()) assert len(folders) > 0, 'No folders visible on server' assert 'INBOX' in [f.upper() for f in folders], ... |
for name in some_folders: assert name in folders | def test_list_folders(client): clear_folders(client) some_folders = ['simple', r'foo\bar', r'test"folder"'] for name in some_folders: client.create_folder(name) folders = extract_folder_names(client.list_folders()) assert len(folders) > 0, 'No folders visible on server' assert 'INBOX' in [f.upper() for f in folders], ... | |
for folder in extract_folder_names(client.list_sub_folders()): | for folder in extract_normal_folders(client.list_sub_folders()): | def test_subscriptions(client): # Start with a clean slate clear_folders(client) for folder in extract_folder_names(client.list_sub_folders()): client.unsubscribe_folder(folder) test_folders = ['foobar', 'stuff & things', u'test & \u2622'] for folder in test_folders: client.create_folder(folder) all_folders = sorte... |
all_folders = sorted(extract_folder_names(client.list_folders())) | all_folders = sorted(extract_normal_folders(client.list_folders())) | def test_subscriptions(client): # Start with a clean slate clear_folders(client) for folder in extract_folder_names(client.list_sub_folders()): client.unsubscribe_folder(folder) test_folders = ['foobar', 'stuff & things', u'test & \u2622'] for folder in test_folders: client.create_folder(folder) all_folders = sorte... |
assert all_folders == sorted(extract_folder_names(client.list_sub_folders())) | assert all_folders == sorted(extract_normal_folders(client.list_sub_folders())) | def test_subscriptions(client): # Start with a clean slate clear_folders(client) for folder in extract_folder_names(client.list_sub_folders()): client.unsubscribe_folder(folder) test_folders = ['foobar', 'stuff & things', u'test & \u2622'] for folder in test_folders: client.create_folder(folder) all_folders = sorte... |
assert extract_folder_names(client.list_sub_folders()) == [] | assert extract_normal_folders(client.list_sub_folders()) == [] | def test_subscriptions(client): # Start with a clean slate clear_folders(client) for folder in extract_folder_names(client.list_sub_folders()): client.unsubscribe_folder(folder) test_folders = ['foobar', 'stuff & things', u'test & \u2622'] for folder in test_folders: client.create_folder(folder) all_folders = sorte... |
assert folder in extract_folder_names(client.list_folders()) | assert folder in extract_normal_folders(client.list_folders()) | def test_folders(client): '''Test folder manipulation ''' clear_folders(client) assert client.folder_exists('INBOX') assert not client.folder_exists('this is very unlikely to exist') test_folders = ['foobar', 'stuff & things', u'test & \u2622'] for folder in test_folders: assert not client.folder_exists(folder) cli... |
for folder in extract_folder_names(client.list_folders()): | for folder in extract_normal_folders(client.list_folders()): | def clear_folders(client): client.folder_encode = False for folder in extract_folder_names(client.list_folders()): if folder.upper() != 'INBOX': client.delete_folder(folder) client.folder_encode = True |
assert resp['EXISTS'] > 1 | assert resp['EXISTS'] > 0 | def test_select_and_close(client): resp = client.select_folder('INBOX') assert isinstance(resp['EXISTS'], int) assert resp['EXISTS'] > 1 assert isinstance(resp['RECENT'], int) assert isinstance(resp['FLAGS'], tuple) assert len(resp['FLAGS']) > 1 client.close_folder() |
yield nextchar | if nextchar == ')' and stream_i.peek() == '(': yield ')(' else: yield nextchar | def read_token_stream(self, stream_i): whitespace = self.WHITESPACE wordchars = self.NON_SPECIALS read_until = self.read_until |
lines = self.backend.send_command('dump %s %d' % (addr, length)) data = '' for line in lines: bytes = line.strip().split() for byte in bytes: data += chr(int(byte, 16)) | f = tempfile.NamedTemporaryFile() self.backend.send_command('dump %s %d %s' % (addr, length, f.name)) data = f.read() | def read_memory(self, addr, length): if isinstance(addr,int): addr = '%x'%(addr,) # TODO restore file approach when dumping to file in scanmem is fixed #f = tempfile.NamedTemporaryFile() #self.backend.send_command('dump %s %d %s' % (addr, length, f.name)) #data = f.read() lines = self.backend.send_command('dump %s %d' ... |
raise Exception('Cannot access target memory') | self.show_error('Cannot access target memory') | def read_memory(self, addr, length): if isinstance(addr,int): addr = '%x'%(addr,) # TODO restore file approach when dumping to file in scanmem is fixed #f = tempfile.NamedTemporaryFile() #self.backend.send_command('dump %s %d %s' % (addr, length, f.name)) #data = f.read() lines = self.backend.send_command('dump %s %d' ... |
self.backend.send_command(self.value_input.get_text()) | cmd = self.value_input.get_text() active = self.scan_data_type_combobox.get_active() assert(active >= 0) if self.scan_data_type_combobox.get_model()[active][0] == 'string': cmd = '" '+cmd self.backend.send_command(cmd) | def do_scan(self): # set scan options self.apply_scan_settings() # TODO: syntax check self.backend.send_command(self.value_input.get_text()) self.update_scan_result() self.search_count +=1 |
elif typename == 'bytearray': | elif typename == 'bytearray' or typename == 'string': | def get_type_size(self, typename, value): if typename in TYPESIZES.keys(): # int or float type; fixed length return TYPESIZES[typename] elif typename == 'bytearray': return len(value) elif typename == 'string': # string = characters + one null byte return len(value) + 1 return None |
elif typename == 'string': return len(value) + 1 | def get_type_size(self, typename, value): if typename in TYPESIZES.keys(): # int or float type; fixed length return TYPESIZES[typename] elif typename == 'bytearray': return len(value) elif typename == 'string': # string = characters + one null byte return len(value) + 1 return None | |
return struct.unpack('%is'%len(bytes), bytes) | return '%s'%(bytes,) | def bytes2value(self, typename, bytes): if typename in TYPENAMES_G2STRUCT.keys(): return struct.unpack(TYPENAMES_G2STRUCT[typename], bytes)[0] elif typename == 'string': return struct.unpack('%is'%len(bytes), bytes) elif typename == 'bytearray': return ' '.join(['%02x'%ord(i) for i in bytes]) else: return bytes |
buffer = self.get_buffer() bounds = buffer.get_selection_bounds() if bounds and (bounds[1].get_offset() - bounds[0].get_offset() > 1): self.select_a_char() else: c = evt.keyval if unichr(c) in AsciiText._printable: | c = evt.keyval if unichr(c) in AsciiText._printable: buffer = self.get_buffer() bounds = buffer.get_selection_bounds() if bounds and (bounds[1].get_offset() - bounds[0].get_offset() > 1): self.select_a_char() else: | def __on_key_press(self, widget, evt, data=None): buffer = self.get_buffer() bounds = buffer.get_selection_bounds() if bounds and (bounds[1].get_offset() - bounds[0].get_offset() > 1): self.select_a_char() else: c = evt.keyval if unichr(c) in AsciiText._printable: iter = buffer.get_iter_at_mark(buffer.get_insert()) off... |
if not buffer.get_selection_bounds(): | bounds = buffer.get_selection_bounds() if (not bounds) or (bounds[1].get_offset() - bounds[0].get_offset() == 1): | def __on_button_release(self, widget, event, data=None): buffer = self.get_buffer() if not buffer.get_selection_bounds(): self.select_a_char() # return False in order to let other handler handle it return False |
buffer = self.get_buffer() bounds = buffer.get_selection_bounds() if bounds and (bounds[1].get_offset() - bounds[0].get_offset() > 1): self.select_a_char() else: char = evt.keyval if unichr(char) in HexText._hexdigits: | char = evt.keyval if unichr(char) in HexText._hexdigits: buffer = self.get_buffer() bounds = buffer.get_selection_bounds() if bounds and (bounds[1].get_offset() - bounds[0].get_offset() > 1): self.select_a_char() else: | def __on_key_press(self, widget, evt, data=None): buffer = self.get_buffer() bounds = buffer.get_selection_bounds() if bounds and (bounds[1].get_offset() - bounds[0].get_offset() > 1): self.select_a_char() else: char = evt.keyval if unichr(char) in HexText._hexdigits: c = unichr(char).upper() iter = buffer.get_iter_at_... |
print '\n'.join(output_lines) | def send_command(self, cmd): # for debug | |
self.backend.send_command('option search_integer %s' % ((self.search_integer_checkbutton.get_property('active') and '1' or '0'),)) self.backend.send_command('option search_float %s' % ((self.search_float_checkbutton.get_property('active') and '1' or '0'),)) | self.set_scan_data_type() | def do_scan(self): # set scan options self.backend.send_command('option search_integer %s' % ((self.search_integer_checkbutton.get_property('active') and '1' or '0'),)) self.backend.send_command('option search_float %s' % ((self.search_float_checkbutton.get_property('active') and '1' or '0'),)) # TODO: syntax check sel... |
self.show_error('Cannot') | self.show_error('Cannot read memory') | def browse_memory(self, addr=None): # select a region contains addr try: self.read_maps() except: show_error('Cannot retieve memory maps of that process, maybe it has exited (crashed), or you don\'t have enough privilege') selected_region = None if addr: for m in self.maps: if m['start_addr'] <= addr and addr < m['end_... |
return len(value) | return (len(value.strip())+1)/3 | def get_type_size(self, typename, value): if typename in TYPESIZES.keys(): # int or float type; fixed length return TYPESIZES[typename] elif typename == 'bytearray': return len(value) elif typename == 'string': return len(eval('\''+value+'\'')) return None |
dt = self.scan_data_type_combobox.get_model()[active] | dt = self.scan_data_type_combobox.get_model()[active][0] | def apply_scan_settings (self): # scan data type active = self.scan_data_type_combobox.get_active() assert(active >= 0) dt = self.scan_data_type_combobox.get_model()[active] self.backend.send_command('option scan_data_type %s' % (dt,)) # search scope self.backend.send_command('option region_scan_level %d' %(1 + int(sel... |
exitall() | if mycontext['winner'] == None: mycontext['winner'] = 'timer' | def foo(): exitall() |
settimer(.5, foo, ()) | if callfunc == 'initialize': | def foo(): exitall() |
for num in range(50): randomfloat() print "This should be reached when there aren't time restrictions" | for attempt in range(3): sleep(1) mycontext['winner'] = None settimer(.5, foo, ()) for num in range(50): randomfloat() sleep(.00001) if mycontext['winner'] == None: print "This should be reached when there aren't time restrictions" while mycontext['winner'] == None: sleep(.2) | def foo(): exitall() |
times = windows_api.process_times(pid) | times = process_times(pid) | def get_process_cpu_time(pid): """ <Purpose> See process_times <Arguments> See process_times <Exceptions> See process_times <Returns> The amount of CPU time used by the kernel and user in seconds. """ # Get the times times = windows_api.process_times(pid) # Add kernel and user time together... It's in units of 10... |
data, addr = entry['socket'].recvfrom(4096) | data, addr = entry['socket'].recvfrom(65535) | def start_event(entry, handle,eventhandle): if entry['type'] == 'UDP': # some sort of socket error, I'll assume they closed the socket or it's # not important try: # NOTE: is 4096 a reasonable maximum datagram size? data, addr = entry['socket'].recvfrom(4096) except socket.error: # they closed in the meantime? nanny.ta... |
_require_integer_or_float(timeout) | if timeout is not None: _require_integer_or_float(timeout) | def allow_args_openconn(desthost, destport, localip=None, localport=0, timeout=5): # TODO: the wiki:RepyLibrary gives localport=0 as the default for this function, # slightly different than the localport=None it gives for sendmess(). This # should either be verified as intentional or made the same. _require_string(des... |
if mycontext['maxlag'] > 4: | if mycontext['maxlag'] > 2: | def check_and_exit(): if mycontext['maxlag'] > 4: print "UDP packets lag too long in the buffer: ", mycontext['maxlag'] if mycontext['maxlag'] == 0: print "UDP packets were not received or had 0 lag" exitall() |
sockobj.send("%9f "%getruntime()) | sockobj.send("%9f "%getruntime() + " "*90) | def sendforever(sockobj): while True: # send a message that is around 100 bytes sockobj.send("%9f "%getruntime()) |
sendtime = float(connobj.recv(10).split()[0]) | sendtime = float(connobj.recv(100).strip().split()[0]) | def handleconnection(ip, port, connobj, ch, mainch): while True: sendtime = float(connobj.recv(10).split()[0]) lag = getruntime() - sendtime if mycontext['maxlag'] < lag: mycontext['maxlag'] = lag |
if mycontext['maxlag'] > 4: | if mycontext['maxlag'] > 2: | def check_and_exit(): if mycontext['maxlag'] > 4: print "TCP packets lag too long in the buffer: ", mycontext['maxlag'] if mycontext['maxlag'] == 0: print "TCP packets were not received or had 0 lag" exitall() |
def exec_repy_script(filename, restrictionsfile, arguments={}, script_args=''): | def exec_repy_script(filename, restrictionsfile, arguments=None, script_args=''): | def exec_repy_script(filename, restrictionsfile, arguments={}, script_args=''): global mobileNoSubprocess if script_args != '': script_args = ' ' + script_args if not mobileNoSubprocess: # Convert arguments arg_string = arguments_to_string(arguments) return exec_command('python repy.py ' + arg_string + restrictionsf... |
for val in item.values(): if filter in str(val).lower(): d.append(item) break | for key, val in item.items(): if key not in skip: if filter in str(val).lower(): d.append(item) break | def filter_results(self, data, filter): filter = filter.lower() d = [] for item in data: for val in item.values(): if filter in str(val).lower(): d.append(item) break return d |
if key == 'File': | if key == 'file': | def _read_songs(self): obj = {} for key, value in self._read_pairs(): if key == 'File': if obj: yield obj obj = {} key = 'file' obj[key] = value if obj: yield obj raise StopIteration |
key = 'file' | else: key = key.lower() | def _read_songs(self): obj = {} for key, value in self._read_pairs(): if key == 'File': if obj: yield obj obj = {} key = 'file' obj[key] = value if obj: yield obj raise StopIteration |
elif len(data) > 100: | elif len(data) > 200: | def loadChildren(parent, parentpath): children = [x for x in data if x['parent'] == parentpath] if children: parent['leaf'] = False parent['children'] = [] for c in children: parent['children'].append(c) loadChildren(c, c['directory']) |
i = 0 | def playlistinfoext(self, **kwargs): data = mpd.playlistinfo() filter = kwargs.get('filter') start = int(kwargs.get('start', 0)) limit = kwargs.get('limit', None) if filter: data = self.filter_results(data, filter) ln = len(data) if limit: end = start + int(limit) if end > ln: end = ln data = data[start:end] if data... | |
'cls': 'album-group-start', 'id': 'aa' + i | 'cls': 'album-group-start' | def makeHeader(dg): return { 'album': dg('album', 'Unknown'), 'artist': dg('albumartist', dg('artist', 'Unknown')), 'file': dg('file'), 'cls': 'album-group-start', 'id': 'aa' + i } i += 1 |
i += 1 | def makeHeader(dg): return { 'album': dg('album', 'Unknown'), 'artist': dg('albumartist', dg('artist', 'Unknown')), 'file': dg('file'), 'cls': 'album-group-start', 'id': 'aa' + i } i += 1 | |
elif name in ('save', 'rm', 'rename'): try: self.lock.acquire() self.state['playlists'] = datetime.utcnow().ctime() except Exception, e: print e finally: self.lock.release() | def __getattr__(self, name): if name == 'list': return self.list elif name == 'listplaylists': return self.listplaylists elif name == 'load': return self.load elif name == 'save': return self.save else: fn = self.con.__getattr__(name) | |
'playlist': item | 'playlist': item, 'songs': len(songs), 'time': playtime, 'ptime': hmsFromSeconds(playtime) | def listplaylists(self, *args): data = self._safe_cmd(self.con.listplaylists, args) for index in range(len(data)): item = data[index]['playlist'] data[index] = { 'title': item, 'type': 'playlist', 'playlist': item } return data |
self.state['playlists'] = datetime.utcnow().ctime() | def save(self, playlistName): OK = False try: ret = self._safe_cmd(self.con.save, [playlistName]) OK = True except MPDError, e: if '{save} Playlist already exists' in str(e): self._safe_cmd(self.con.rm, [playlistName]) ret = self._safe_cmd(self.con.save, [playlistName]) OK = True if OK: self.lock.acquire() try: self.st... | |
if 'stored_playlist' in changes: if self._dbcache.has_key('listplaylists'): del self._dbcache['listplaylists'] s['playlists'] = datetime.utcnow().ctime() | def sync(self, changes=None): if self.hold: return self.state if not changes: """ Called by the server's status method, which means mpd.idle() has not returned with any significant changes. The only item which could change without causing a full sync is elapsed, so just update the elapsed seconds if playing. """ if s... | |
i++ | i += 1 | def makeHeader(dg): return { 'album': dg('album', 'Unknown'), 'artist': dg('albumartist', dg('artist', 'Unknown')), 'file': dg('file'), 'cls': 'album-group-start', 'id': 'aa' + i } i++ |
if _password: self.password(_password) | def connect(self, host, port, _password=None): self._host = host self._port = port self._password = None if self._sock: raise ConnectionError("Already connected") if host.startswith("/"): self._sock = self._connect_unix(host) else: self._sock = self._connect_tcp(host, port) self._rfile = self._sock.makefile("rb") self.... | |
imp_obj, created = CrpNPCCorporationTrade.objects.get_or_create(corporation=corporation) imp_obj.type = type | imp_obj, created = CrpNPCCorporationTrade.objects.get_or_create(corporation=corporation, type=type) | def import_row(self, row): corporation = CrpNPCCorporation.objects.get(id=row['corporationID']) type = InvType.objects.get(id=row['typeID']) imp_obj, created = CrpNPCCorporationTrade.objects.get_or_create(corporation=corporation) imp_obj.type = type imp_obj.save() |
invtype.parent_blueprint_Type = InvType.objects.get(id=row['parentBlueprintTypeID']) | invtype.parent_blueprint_type = InvType.objects.get(id=row['parentBlueprintTypeID']) | def import_row(self, row): blueprint_type = InvType.objects.get(id=row['blueprintTypeID']) product_type = InvType.objects.get(id=row['productTypeID']) invtype, created = InvBlueprintType.objects.get_or_create(blueprint_type=blueprint_type, product_type=product_type) if row['parentBlueprintTypeID']: invtype.parent_bluep... |
imp_obj, created = AgtAgentType.objects.get_or_create(name=row['agentType']) | imp_obj, created = AgtAgentType.objects.get_or_create(id=row['agentTypeID']) imp_obj.name = name=row['agentType'] | def import_row(self, row): imp_obj, created = AgtAgentType.objects.get_or_create(name=row['agentType']) imp_obj.save() |
return self.name | return self.meta_group.name | def __unicode__(self): return self.name |
column_names = ",".join(f.column for f in fields) | column_names = ",".join(con.ops.quote_name(f.column) for f in fields) | def insert_many(objects, using="default"): """Insert list of Django objects in one SQL query. Objects must be of the same Django model. Note that save is not called and signals on the model are not raised.""" if not objects: return import django.db.models from django.db import connections con = connections[using] mod... |
if self.name: return self.name else: return "%s: (%dx %s)" % (self.type.name, self.quantity, self.material_type.name) | return "%s: (%dx %s)" % (self.type.name, self.quantity, self.material_type.name) | def __unicode__(self): if self.name: return self.name else: return "%s: (%dx %s)" % (self.type.name, self.quantity, self.material_type.name) |
invtype, created = InvType.objects.get_or_create(id=row['caldariStationTypeID']) operation.caldari_station_type, created = StaStationType.objects.get_or_create(type=invtype) | operation.caldari_station_type, created = StaStationType.objects.get_or_create(id=row['caldariStationTypeID']) | def import_row(self, row): operation, created = StaOperation.objects.get_or_create(id=row['operationID']) operation.activity_id = row['activityID'] operation.name = row['operationName'] operation.description = row['description'] operation.fringe = row['fringe'] operation.corridor = row['corridor'] operation.hub = row['... |
invtype, created = InvType.objects.get_or_create(id=row['minmatarStationTypeID']) operation.minmatar_station_type, created = StaStationType.objects.get_or_create(type=invtype) | operation.minmatar_station_type, created = StaStationType.objects.get_or_create(id=row['minmatarStationTypeID']) | def import_row(self, row): operation, created = StaOperation.objects.get_or_create(id=row['operationID']) operation.activity_id = row['activityID'] operation.name = row['operationName'] operation.description = row['description'] operation.fringe = row['fringe'] operation.corridor = row['corridor'] operation.hub = row['... |
invtype, created = InvType.objects.get_or_create(id=row['amarrStationTypeID']) operation.amarr_station_type, created = StaStationType.objects.get_or_create(type=invtype) | operation.amarr_station_type, created = StaStationType.objects.get_or_create(id=row['amarrStationTypeID']) | def import_row(self, row): operation, created = StaOperation.objects.get_or_create(id=row['operationID']) operation.activity_id = row['activityID'] operation.name = row['operationName'] operation.description = row['description'] operation.fringe = row['fringe'] operation.corridor = row['corridor'] operation.hub = row['... |
invtype, created = InvType.objects.get_or_create(id=row['gallenteStationTypeID']) operation.gallente_station_type, created = StaStationType.objects.get_or_create(type=invtype) | operation.gallente_station_type, created = StaStationType.objects.get_or_create(id=row['gallenteStationTypeID']) | def import_row(self, row): operation, created = StaOperation.objects.get_or_create(id=row['operationID']) operation.activity_id = row['activityID'] operation.name = row['operationName'] operation.description = row['description'] operation.fringe = row['fringe'] operation.corridor = row['corridor'] operation.hub = row['... |
invtype, created = InvType.objects.get_or_create(id=row['joveStationTypeID']) operation.jove_station_type, created = StaStationType.objects.get_or_create(type=invtype) | operation.jove_station_type, created = StaStationType.objects.get_or_create(id=row['joveStationTypeID']) | def import_row(self, row): operation, created = StaOperation.objects.get_or_create(id=row['operationID']) operation.activity_id = row['activityID'] operation.name = row['operationName'] operation.description = row['description'] operation.fringe = row['fringe'] operation.corridor = row['corridor'] operation.hub = row['... |
print type_id, name | def __init__(self, *args, **kwargs): super(Importer_ramAssemblyLines, self).__init__(*args, **kwargs) self.field_map = (('assembly_line_type_id', 'assemblyLineTypeID'), ('station_id', 'containerID'), ('owner_id', 'ownerID'), ('activity_id', 'activityID'), ('name', 'assemblyLineTypeID', self.get_assembly_line_type_name)... | |
break | if passes > 100: break | def _newFilename(self): """ Generator that generates new filenames """ g = self.vars.copy() # Split filenames into static and wildcard groups static = [] wildcard = [] while self.files: if isinstance(self.files[0], list): break static.append(self.files.pop(0)) if self.files: wildcard = self.files.pop(0) |
_format(self, ''.join(Base.verbatim.invoke(self, tex)[1:]).split('\n')) | s = ''.join(Base.verbatim.invoke(self, tex)[1:]).replace('\r','').split('\n') _format(self, s) | def invoke(self, tex): if self.macroMode == Base.Environment.MODE_END: return _format(self, ''.join(Base.verbatim.invoke(self, tex)[1:]).split('\n')) |
return u''.join(self.ownerDocument.createElement(name).invoke(tex)) | return u''.join(tex.expandTokens(self.ownerDocument.createElement(name).invoke(tex))) | def counterValue(m): """ Replace the counter values """ name = m.group(1) |
shutil.copy2(os.path.join(tempdir,src), dest.path) | try: shutil.copy2(os.path.join(tempdir,src), dest.path) except OSError: shutil.copy(os.path.join(tempdir,src), dest.path) | def convert(self, output): """ Convert the output from LaTeX into images |
for i in range(List.depth+1, len(List.counters)): | for i in range(List.depth, len(List.counters)): | def invoke(self, tex): """ Set list nesting depth """ if self.macroMode != Environment.MODE_END: List.depth += 1 else: List.depth -= 1 try: for i in range(List.depth+1, len(List.counters)): self.ownerDocument.context.counters[List.counters[i]].setcounter(0) except (IndexError, KeyError): pass return Environment.invoke(... |
if 'language' in self.attributes: self.ownerDocument.context.current_language = \ self.attributes['arguments']['language'] else: | if 'language' in self.attributes['arguments']: | def invoke(self, tex): Base.Command.invoke(self, tex) if 'language' in self.attributes: self.ownerDocument.context.current_language = \ self.attributes['arguments']['language'] else: self.ownerDocument.context.current_language = \ self.attributes['arguments']['language'] |
and query in e.affixes] | and (query in e.affixes or e.type == 'gismu' and e.word[0:4] == query)] | def query(query): query = query.replace('+', ' ') matches = set() entry = db.entries.get(query, None) if entry: matches.add(entry) glosses = [g for g in db.glosses if g.gloss == query or g.gloss == query.capitalize()] matches.update(g.entry for g in glosses) affix = [e for e in db.entries.itervalues() if e not in ma... |
if tag == 'rafsi': entry.affixes.append(text) entry.searchaffixes.append(text) elif tag == 'selmaho': self._process_selmaho(entry, text) elif tag == 'definition': entry.definition = tex2html(text) tokens = re.findall(r"[\w']+", text, re.UNICODE) for token in set(tokens): add_stems(token, self.definition_stems, entry)... | processors.get(tag, lambda: None)(entry, text) | def _load_entries(self, xml): self.entries = OrderedDict() self.definition_stems = {} self.note_stems = {} for type, _ in TYPES: for valsi in xml.findall('//valsi'): if valsi.get('type') == type: entry = Entry(self) entry.type = type entry.word = valsi.get('word') |
if a in e.searchaffixes].pop() components += '<a href="%s" ' % word components += 'title="<strong>%s:</strong> ' % word components += '%s">%s</a>' % (word.definition, a) | if a in e.searchaffixes] if word: components += '<a href="%s" ' % word[0] components += 'title="<strong>%s:</strong> ' % word[0] components += '%s">%s</a>' % (word[0].definition, a) else: components += a | def components(self): """Build HTML that links the affixes in a compound to their corresponding words, with definitions in the link tooltips. |
query = query.decode('utf-8').replace('+', ' ') | query = query.replace('+', ' ') | def query(query): showgrid = 'showgrid' in request.args query = query.decode('utf-8').replace('+', ' ') querystem = stem(query.lower()) matches = set() entry = db.entries.get(query, None) if entry: matches.add(entry) glosses = [g for g in db.gloss_stems.get(querystem, []) if g.entry not in matches] matches.update(g.e... |
results = db.query(query) | results = database.root.query(query) | def query(self, target, query): fields = 'affix|class|type|notes|cll|url' |
run('pip install -E %s -r requirements.txt -u' % virtenv) | run('pip install -E %s -r requirements.txt -U' % virtenv) | def updatedeps(): with cd(appdir): run('pip install -E %s -r requirements.txt -u' % virtenv) |
if entry or field == 'definition': | if entry or field == 'components': | def query(self, target, query): fields = 'affix|class|type|notes|cll|url|components' |
if e in matches) | if g.entry in matches) | def query(self, query): """Query database with query language. |
run('rm data/db.pickle') | def retag(): with cd(appdir): run('rm data/db.pickle') run('touch data/jbovlaste.xml') restart() | |
retag() | restart() | def syncdb(): with cd(appdir): run('wget "http://jbovlaste.lojban.org/export/xml-export.html?lang=en" -O data/jbovlaste.xml') retag() |
if entry: | if entry or field == 'definition': | def query(self, target, query): fields = 'affix|class|type|notes|cll|url|components' |
format = '\n<span style="font-family: monospace">%s</span>' | format = '\n<span style="font-family: monospace"> %s</span>' return format % m.group(1) def puho(m): format = 'inchoative\n<span style="font-family: monospace">%s</span>' | def lines(m): format = '\n%s' if m.group(1).startswith('|'): format = '\n<span style="font-family: monospace"> %s</span>' elif m.group(1).startswith('>'): format = '\n<span style="font-family: monospace">%s</span>' return format % m.group(1) |
run('touch vlasisku/data/db.pickle') | def retag(): with cd(appdir): run('touch vlasisku/data/db.pickle') run('touch vlasisku/data/jbovlaste.xml') restart() | |
or e.type == 'gismu' and e.word[0:4] == query)] | or e.type in ('gismu', 'experimental gismu') and e.word[0:4] == query)] | def query(query): query = query.replace('+', ' ') matches = set() entry = db.entries.get(query, None) if entry: matches.add(entry) glosses = [g for g in db.glosses if g.gloss == query or g.gloss == query.capitalize()] matches.update(g.entry for g in glosses) affix = [e for e in db.entries.itervalues() if e not in ma... |
data = ' '.join(e for a in compound2affixes(query) if len(a) != 1 for e in database.root.entries.itervalues() if a in e.searchaffixes) | data = ' '.join(e.word for a in compound2affixes(query) if len(a) != 1 for e in database.root.entries.itervalues() if a in e.searchaffixes) | def query(self, target, query): fields = 'affix|class|type|notes|cll|url|components' |
elif m.group(1).startswith(('>', '-')): | elif m.group(1).startswith('>'): | def lines(m): format = '\n%s' if m.group(1).startswith('|'): format = '\n<span style="font-family: monospace"> %s</span>' elif m.group(1).startswith(('>', '-')): format = '\n<span style="font-family: monospace">%s</span>' return format % m.group(1) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.