rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
self.main_widget().error_box) | self.main_widget().show_error) | def accept(self): QtGui.QDialog.accept(self) # Store input for later use. server = unicode(self.server.text()) port = self.port.value() username = unicode(self.username.text()) password = unicode(self.password.text()) self.config()["server_for_sync_as_client"] = server self.config()["port_for_sync_as_client"] = port se... |
self.threaded_question_box) | self.threaded_show_question) | def accept(self): QtGui.QDialog.accept(self) # Store input for later use. server = unicode(self.server.text()) port = self.port.value() username = unicode(self.username.text()) password = unicode(self.password.text()) self.config()["server_for_sync_as_client"] = server self.config()["port_for_sync_as_client"] = port se... |
mutex.lock() | def run(self): import select while not self.stopped: if select.select([self.socket], [], [], 0.25)[0]: self.handle_request() self.socket.close() | |
self.terminate_all_sessions() self.database().release_connection() database_released.wakeAll() mutex.unlock() | mutex.lock() if not self.server_has_connection: database_released.wait(mutex) server_hanging = (len(self.sessions) != 0) mutex.unlock() if server_hanging: self.terminate_all_sessions() self.database().release_connection() self.server_has_connection = False database_released.wakeAll() | def run(self): import select while not self.stopped: if select.select([self.socket], [], [], 0.25)[0]: self.handle_request() self.socket.close() |
if self.database().is_loaded(): database_released.wait(mutex) mutex.unlock() | if not self.server_has_connection: database_released.wait(mutex) | def open_database(self, database_name): mutex.lock() self.sync_started_signal.emit() if self.database().is_loaded(): database_released.wait(mutex) mutex.unlock() previous_database = self.config()["path"] if previous_database != database_name: if not os.path.exists(expand_path(database_name, self.config().basedir)): sel... |
mutex.lock() | def unload_database(self): mutex.lock() self.previous_database = self.config()["path"] self.database().release_connection() database_released.wakeAll() mutex.unlock() | |
self.database().release_connection() database_released.wakeAll() mutex.unlock() | self.release_database_if_needed() | def unload_database(self): mutex.lock() self.previous_database = self.config()["path"] self.database().release_connection() database_released.wakeAll() mutex.unlock() |
def stop_server(self): mutex.lock() self.thread.stopped = True if self.database().is_loaded(): database_released.wait(mutex) mutex.unlock() self.thread.wait() self.thread = None | def server_is_hanging(self): mutex.lock() hanging = (len(self.thread.sessions) != 0) mutex.unlock() return hanging | def stop_server(self): mutex.lock() self.thread.stopped = True if self.database().is_loaded(): database_released.wait(mutex) mutex.unlock() self.thread.wait() self.thread = None |
if not self.thread or len(self.thread.sessions) == 0: | if not self.thread or not self.server_is_hanging(): | def flush_sync_server(self): if not self.thread or len(self.thread.sessions) == 0: return # The server has the database. self.stop_server() self.activate() |
self.stop_server() | self.deactivate() | def flush_sync_server(self): if not self.thread or len(self.thread.sessions) == 0: return # The server has the database. self.stop_server() self.activate() |
self.stop_server() | self.release_database_if_needed() mutex.lock() self.thread.stopped = True mutex.unlock() self.thread.wait() self.thread = None | def deactivate(self): # We have the database. if not self.thread: return self.stop_server() |
datetime.datetime.today().strftime("%Y%m%d-%H:%M.db") | datetime.datetime.today().strftime("%Y%m%d-%H%M.db") | def backup(self): self.save() if self.config()["backups_to_keep"] == 0: return backupdir = os.path.join(self.config().basedir, "backups") # Make a copy. Create only a single file per day. db_name = os.path.basename(self._path).rsplit(".", 1)[0] backupfile = db_name + "-" + \ datetime.datetime.today().strftime("%Y%m%d-%... |
TRAITS = etsdep('Traits', '3.2.1') | TRAITS = etsdep('Traits', '3.3.0') | def etsdep(p, min, max=None, literal=False): require = '%s >=%s.dev' % (p, min) if max is not None: if literal is False: require = '%s, <%s.a' % (require, max) else: require = '%s, <%s' % (require, max) return require |
raise "you should use RingBuffer" def append(self,x): | raise Exception("you should use RingBuffer") def append(self,x): | def __init__(self,n): raise "you should use RingBuffer" |
str = "{spaces}<{attr}>{value}</{attr}>" xml_elements.append(str.format(spaces=" "*4,attr=attr, value=value)) | str = "%(spaces)s<%(attr)s>%(value)s</%(attr)s>" xml_elements.append(str % dict(spaces=" "*4,attr=attr, value=value)) | def get_xml(self): xml_elements = [] for attr in ['name', 'version', 'checksum', 'description']: value = getattr(self, attr) str = "{spaces}<{attr}>{value}</{attr}>" xml_elements.append(str.format(spaces=" "*4,attr=attr, value=value)) return xml_elements |
app = get_app_qt4() | app = get_app_qt4(['']) | def is_event_loop_running_qt4(app=None): """Is the qt4 event loop running.""" if app is None: app = get_app_qt4() if hasattr(app, '_in_event_loop'): return app._in_event_loop else: # Does qt4 provide a other way to detect this? return False |
app = get_app_qt4() | app = get_app_qt4(['']) | def start_event_loop_qt4(app=None): """Start the qt4 event loop in a consistent manner.""" if app is None: app = get_app_qt4() if not is_event_loop_running_qt4(app): app._in_event_loop = True app.exec_() app._in_event_loop = False else: app._in_event_loop = True |
edir, bin = hndlr.binarypaths(file) self.assertTrue(os.path.isdir(edir)) self.assertTrue(os.path.isfile(bin)) self.assertEquals(open(bin, 'rb').read(), data) | self.assertTrue(os.path.isdir(hndlr.executable.dirpath)) self.assertTrue(os.path.isfile(hndlr.executable.binpath)) self.assertEquals(open(hndlr.executable.binpath, 'rb').read(), data) | def runTest(self): data = b"ExecSetPostTest" |
self.inst = Instance(self.ex, self.inst_name, self.environ) | self.inst = Instance(self.ex, self.inst_name, environ=self.environ) | def setUp(self): self.environ = {'env0':'abc', 'env1':'123'} self.ex = Executable("testinstanceEnviron", mediatype="text/x-python") self.ex.writeimage(io.StringIO(self.source)) self.inst_name = Instance.createname() self.inst_dir = os.path.join(self.ex.dirpath, self.inst_name) self.inst = Instance(self.ex, self.inst_na... |
def tearDown(self): shutil.rmtree(self.ex.dirpath) | #def tearDown(self): | |
"git://github.com/tpope/vim-ragtag.git" | "git://github.com/tpope/vim-ragtag.git", | def remove_readonly(fn, path, excinfo): if fn is rmdir: chmod(path, S_IWRITE) rmdir(path) elif fn is remove: chmod(path, S_IWRITE) remove(path) |
def nextURL(self, clear=True): | def nextURL(self, clear=False): | def nextURL(self, clear=True): request = self.request |
nextURL = self.nextURL() | nextURL = self.nextURL(True) | def success(self): actions = [(action.order, action) for name, action in getAdapters((self.request.principal, self.request), ISuccessLoginAction)] actions.sort() |
order = 9999999 | order = 1 | def isProcessed(self): return 'form.zojax-auth-login' in self.request |
return True | return False | def __call__(self, nextURL=u''): request = self.request response = request.response |
w.writerow( ("ontology", "concept precision", "concept recall", "concept F1", "relation precision", "relation recall", "relation F1") ) | def computeOntologyStatistics( ff, cc, rc, ccCutOffCount, rcCutOffCount): """ computes per ontology statistics (R, P, F1) @param[in] ff list of ontology files @param[in] cc concept counts dictionary @param[in] rc relation counts dictionary @param[in] ccCutOffCount min cc required for a term to be considered @param[in] ... | |
return filter( [ GeoNames.getGeoEntity( GeoEntity.factory( id = e['geonameId'] )) for e in jsonData['geonames'] ] ) | return filter( None, [ GeoNames.getGeoEntity( GeoEntity.factory( id = e['geonameId'] )) for e in jsonData['geonames'] ] ) | def getNeighbors(geo_entity): """ returns all neighbours for the given geo id (currently only implemented on a country level) @param[in] geo_entity @returns a list containing the neighbours of the given country """ |
return self['id'] == o['id'] | return self['id'] == o['id'] or self['geoUrl'] == o['geoUrl'] | def __eq__(self, o): """ add's support for comparisons using == """ return self['id'] == o['id'] |
RE_CHOICES = re.compile("(\w{2,})\s*/\s*(\w{2,})\s+(.*)") | RE_CHOICES = re.compile("(\w{2,})\s*/\s*(\w{2,})\s*(.*)") | def __class__(self, ph): """ @param[in] ph a list of phrases to cleanup """ raise NotImplemented |
def getRelatedTags( tag ): | def getRelatedTags( tags ): | def getRelatedTags( tag ): """ fetches the related tags with their overall count @param tags list of tags @returns list of related tags """ |
if type(tag) == 'list': raise ValueError('getRelatedTags is limited to single tag at the moment!') url = Flickr.FLICKR_TAG_URL % "+".join(tag) | url = Flickr.FLICKR_TAG_URL % "+".join(tags) print url | def getRelatedTags( tag ): """ fetches the related tags with their overall count @param tags list of tags @returns list of related tags """ |
related_tags = re.sub('<.*?b>', '', tag_container[0]) | related_tags = re.sub('</?b>', '', tag_container[0]) | def getRelatedTags( tag ): """ fetches the related tags with their overall count @param tags list of tags @returns list of related tags """ |
related_tags_with_count.append((tag, Flickr.getTagInfo(tag))) | related_tags_with_count.append((tag, Flickr.getTagInfo( (tag,) ))) | def getRelatedTags( tag ): """ fetches the related tags with their overall count @param tags list of tags @returns list of related tags """ |
if m: return m.group(1) else: return 0 | return int(m.group(1).replace(",","")) if m else 0 | def _parse_tag_counts( content ): """ parses flickrs html content and returns the number of counts for the tags """ m=Flickr.RE_TAG_COUNT.search( content ) if m: return m.group(1) else: return 0 |
print Flickr.getRelatedTags( "berlin" ), "counts" | print Flickr.getRelatedTags( ("berlin", "dom", ) ), "counts" | def get_content( url ): """ returns the content from Flickr """ assert( url.startswith("http") ) |
content = Delicious.get_content(url) return Delicious._parse_counts(content) | try: content = Delicious._get_content(url) return Delicious._parse_counts(content) except urllib2.HTTPError: return 0 | def getTagInfo( tags ): """ @param tags A list of tags to retrieve information for @returns the number of bookmarks using the given tags """ assert( isinstance(tags, tuple) or isinstance(tags, list) ) url = Delicious._parse_tag_url(tags) content = Delicious.get_content(url) return Delicious._parse_counts(con... |
content = Delicious.get_content( tag_url ) | content = Delicious._get_content( tag_url ) | def getRelatedTags( tags, retrieveTagInfo=False, pageNum=0 ): """ returns related tags for the given ones. @param tags list of tags @param retrieveTagInfo determines whether we will retrieve the tagInfo for the related tags @returns list of related tags """ |
return Delicious._parse_counts( Delicious.get_content(request) ) | return Delicious._parse_counts( Delicious._get_content(request) ) | def delicious_info_retrieve( url ): assert( url.startswith("http") ) |
def get_content( url ): | def _get_content( url ): | def get_content( url ): """ returns the content from delicious """ assert( url.startswith("http") ) |
related_tags = re.findall('class="m relatedTag" title="">(\w*?)<em>', content, re.IGNORECASE|re.DOTALL) | related_tags = re.findall('<span class="m" title="(\w*?)">', content, re.IGNORECASE|re.DOTALL) | def getRelatedTags( tags ): """ returns a the count of related tags @param list/tuple of tags @returns list of related tags with a count of their occurence """ |
key = (args, tuple(kargs.items()) ) | key = self.getKey(*args, **kargs) | def fetch(self, fetch_function, *args, **kargs): key = (args, tuple(kargs.items()) ) return self.fetchObjectId(key, fetch_function, *args, **kargs) |
strCleanupPipe = (unicode.lower, RemovePossessive(), FixDashSpace(), RemovePunctationAndBrakets(), ) | strCleanupPipe = (unicode.lower, RemovePossessive(), FixDashSpace() ) | def getFullCleanupProfile(): """ returns the full cleanup profile using all cleanup modules """ strCleanupPipe = (unicode.lower, RemovePossessive(), FixDashSpace(), RemovePunctationAndBrakets(), ) phrCleanupPipe = (SplitEnumerations(), SplitMultiTerms(), ) wrdCleanupPipe = (FixSpelling(), ) return PhraseCleanup(strClea... |
wrdCleanupPipe = (FixSpelling(), ) | wrdCleanupPipe = (FixSpelling(), RemovePunctationAndBrakets(),) | def getFullCleanupProfile(): """ returns the full cleanup profile using all cleanup modules """ strCleanupPipe = (unicode.lower, RemovePossessive(), FixDashSpace(), RemovePunctationAndBrakets(), ) phrCleanupPipe = (SplitEnumerations(), SplitMultiTerms(), ) wrdCleanupPipe = (FixSpelling(), ) return PhraseCleanup(strClea... |
class RemovePunctationAndBrakets(StringCleanupModule): """ @class RemovePunctationAndBrakets this should be the last string module to call, as it removes too much for many other modules to work correctly """ def __call__(self, s): return s.replace(")", "").replace("(","").replace(".", "").replace("'", "").replace("!", ... | def __call__(self, s): """ cleans the following list of words @param[in] s the string to clean """ raise NotImplemented | |
strCleanupPipe = (unicode.lower, RemovePunctationAndBrakets(), RemovePossessive(), FixDashSpace() ) | strCleanupPipe = (unicode.lower, RemoveEnumerations(), RemovePossessive(), FixDashSpace(), RemovePunctationAndBrakets(), ) | def getFullCleanupProfile(): """ returns the full cleanup profile using all cleanup modules """ strCleanupPipe = (unicode.lower, RemovePunctationAndBrakets(), RemovePossessive(), FixDashSpace() ) phrCleanupPipe = (SplitMultiTerms(), ) wrdCleanupPipe = (FixSpeeling(), ) return PhraseCleanup(strCleanupPipe, phrCleanupPip... |
objectId = (args, tuple(kargs.items())) | objectId = self.getKey(*args, **kargs) | def fetch(self, fetch_function, *args, **kargs): """ fetches the object with the given id, querying a) the cache and b) the fetch_function if the fetch_function is called, the functions result is saved in the cache |
class StringCleanupModule(object): | class CleanupPipeEntry(object): | def clean(self, phrase): """ @param[in] the input phrase to clean @returns a list of elementary cleaned phrases """ |
class PhraseCleanupModule(object): | class PhraseCleanupModule(CleanupPipeEntry): | def __call__(self, s): return FixDashSpace.RE_DASH.sub(r"\1-\2", s) |
def __call__(self, ph): """ @param[in] ph a list of phrases to cleanup """ | def __call__(self, l): """ @param[in] l a list of phrases to cleanup """ | def __call__(self, ph): """ @param[in] ph a list of phrases to cleanup """ raise NotImplemented |
class WordCleanupModule(object): | class WordCleanupModule(CleanupPipeEntry): | def __call__(self, l): result = [] for p in l: for pp in p.split(", "): if "/" in p: m = SplitMultiTerms.RE_CHOICES.search(pp) if m: result.append("%s%s %s" % (m.group(1), m.group(2), m.group(4)) ) result.append("%s%s %s" % (m.group(1), m.group(3), m.group(4)) ) continue |
@attr("remote") | def getDailyTrends(): raise NotImplementedError | |
def __init__(self, cache_dir, cache_nesting_level=0, cache_file_suffix="", max_processes=8): | def __init__(self, cache_dir, cache_nesting_level=0, cache_file_suffix="", max_processes=8, debug_dir=None): | def __init__(self, cache_dir, cache_nesting_level=0, cache_file_suffix="", max_processes=8): """ initializes the Cache object @param[in] cache_dir the cache base directory @param[in] cache_nesting_level optional number of nesting level (0) @param[in] cache_file_suffix optional suffix for cache files @param[in] max_proc... |
pObj = Popen( cmd ) | if self.debug_dir: fname_base = join(self.debug_dir, str(time.time()) ) stdout = open(fname_base+".out", "w") stderr = open(fname_base+".err", "w") pObj = Popen( cmd, stdout=stdout, stderr=stderr ) os.rename( fname_base+".out", join(self.debug_dir, "debug_%d.out" % pObj.pid )) os.rename( fname_base+".err", join(self.de... | def _execute(self, cmd): while self.has_processes_limit_reached(): time.sleep(5) |
os.removedirs( TestAsync.TEST_CACHE_DIR ) | rmtree( TestAsync.TEST_CACHE_DIR ) | def _delCacheDir(): if exists( TestAsync.TEST_CACHE_DIR ): os.removedirs( TestAsync.TEST_CACHE_DIR ) |
def getText(text, encoding="utf8"): html = HtmlToText.execute( CMD_HTML_CONV, text ) | def getText(html_content, encoding="utf8"): """ @param[in] html_content the content of the html page to convert @param[in] encoding the document encoding @returns the text representation of the Web page """ if not "<" in html_content or not ">" in html_content: return html_content html = HtmlToText.execute( CMD_HTML_... | def getText(text, encoding="utf8"): html = HtmlToText.execute( CMD_HTML_CONV, text ) return html[1] |
return (args, tuple(kargs.items()) | return (args, tuple(kargs.items()) ) | def getKey( *args, **kargs): """ returns the key for a set of function parameters """ return (args, tuple(kargs.items()) |
return [ GeoEntity.factory( id = e['geonameId'] )[0] for e in jsonData['geonames'] if e ] | return [ GeoNames.getGeoEntity( GeoEntity.factory( id = e['geonameId'] )) for e in jsonData['geonames'] if e ] | def getNeighbors(geo_entity): """ returns all neighbours for the given geo id (currently only implemented on a country level) @param[in] geo_entity @returns a list containing the neighbours of the given country """ |
def _get_fname( self, obj_id ): """ computes the filename of the file with the given object identifier and creates the required directory structure (if necessary). """ assert( len(obj_id) >= self.cache_nesting_level ) obj_dir = join( *( [self.cache_dir] + list( obj_id[:self.cache_nesting_level] )) ) if not exists(obj_... | def _get_fname( self, obj_id ): """ computes the filename of the file with the given object identifier and creates the required directory structure (if necessary). """ assert( len(obj_id) >= self.cache_nesting_level ) | |
def __init__(self, cache_dir, cache_nesting_level=0, cache_file_suffix=""): | def __init__(self, cache_dir, cache_nesting_level=0, cache_file_suffix="", fn=None): | def __init__(self, cache_dir, cache_nesting_level=0, cache_file_suffix=""): """ initializes the Cache object @param[in] cache_dir the cache base directory @param[in] cache_nesting_level optional number of nesting level (0) @param[in] cache_file_suffix optional suffix for cache files """ |
""" | @param[in] fn function to cache (optional; required for directly calling the class using __call__ """ Cache.__init__(self, fn) | def __init__(self, cache_dir, cache_nesting_level=0, cache_file_suffix=""): """ initializes the Cache object @param[in] cache_dir the cache base directory @param[in] cache_nesting_level optional number of nesting level (0) @param[in] cache_file_suffix optional suffix for cache files """ |
class DiskCached(DiskCache): | def _get_fname( self, obj_id ): """ computes the filename of the file with the given object identifier and creates the required directory structure (if necessary). """ assert( len(obj_id) >= self.cache_nesting_level ) obj_dir = join( *( [self.cache_dir] + list( obj_id[:self.cache_nesting_level] )) ) if not exists(obj_... | def getCacheStatistics(self): """ returns statistics regarding the cache's hit/miss ratio """ return {'cache_hits': self._cache_hit, 'cache_misses': self._cache_miss} |
DiskCache.__init__(self, cache_dir, cache_nesting_level, cache_file_suffix) | self.cache = DiskCache(cache_dir, cache_nesting_level, cache_file_suffix) | def __init__(self, cache_dir, cache_nesting_level=0, cache_file_suffix=""): """ initializes the Cache object @param[in] fn the function to cache @param[in] cache_dir the cache base directory @param[in] cache_nesting_level optional number of nesting level (0) @param[in] cache_file_suffix opt... |
def wrapped_fn(*args, **kargs): wrapped_fn.cache = self return self.fetch(fn, *args, **kargs) return wrapped_fn | self.cache.fn = fn return self.cache | def wrapped_fn(*args, **kargs): wrapped_fn.cache = self return self.fetch(fn, *args, **kargs) |
def __init__(self, max_cache_size =0): | def __init__(self, max_cache_size =0, fn=None): | def __init__(self, max_cache_size =0): """ initializes the Cache object """ self._cacheData = {} self._usage = {} self.max_cache_size = max_cache_size |
class IterableCache(Cache): | class IterableCache(DiskCache): | def wrapped_fn(*args, **kargs): return self.fetch(fn, *args, **kargs) |
_cls = None _fetch_function = None _cached = False _pickle_iterator = None | def wrapped_fn(*args, **kargs): return self.fetch(fn, *args, **kargs) | |
def fetch(self, obj_id, fetch_function, cls): """ checks whether the object with the given id exists """ cache_file = self._get_fname( self.getObjectId(obj_id) ) | def fetchObjectId(self, key, function, *args, **kargs): """ fetches the object with the given id, querying a) the cache and b) the function if the function is called, the functions result is saved in the cache @param[in] key key to fetch @param[in] function to call if the result is not in the cache @param[in] arg... | def __iter__(self): return self |
self._cls = cls self._fetch_function = fetch_function(self, obj_id) | self._fetch_function_iterator = function(*args, **kargs).__iter__() | def fetch(self, obj_id, fetch_function, cls): """ checks whether the object with the given id exists """ cache_file = self._get_fname( self.getObjectId(obj_id) ) |
if self._cached: return self._read_next_element() else: return self._cache_next_element() | return self._read_next_element() if self._cached else self._cache_next_element() | def next(self): if self._cached: return self._read_next_element() else: return self._cache_next_element() |
obj = attrgetter('next')(self._cls)(self) | obj = self._fetch_function_iterator.next() | def _cache_next_element(self): """ a) retrieves the next element from the fetch function b) writes the data to the cache c) passes the data through to the calling element """ self._cache_miss += 1 try: obj = attrgetter('next')(self._cls)(self) self._pickle_iterator.dump( obj ) return obj except StopIteration: self._pic... |
for cacheDirNo in range(5): | for cacheDirNo in range(6): | def teardown(self): """ remove the cache directories """ from shutil import rmtree |
CACHE_DIR = "./.unittest-temp0" d = DiskCache(CACHE_DIR) d.fetchObjectId(1, str, 1) assert 1 in d assert 2 not in d def testDelItemDiskCached(self): """ test delitem for classes using the DiskCached decorator """ result = self.add(12,13) print dir(self.add) assert result == 25 | assert self.diskCache.fetchObjectId(1, str, 1 ) == "1" assert 1 in self.diskCache assert 2 not in self.diskCache assert self.add(12,14) == 26 assert ((12,14),()) in self.add assert 9 not in self.add def testDelItem(self): """ verifies that delitem works """ assert self.diskCache.fetch(str, 2) == "2" key = ((2,),()... | def testContains(self): """ ensures that the contains code works """ CACHE_DIR = "./.unittest-temp0" d = DiskCache(CACHE_DIR) |
assert key in self.add.cache del self.add.cache[key] assert key not in self.add.cache def testDelItemDiskCache(self): | assert key in self.add del self.add[key] assert key not in self.add def testDirectCall(self): """ tests directly calling the cache object using __call__ """ | def testDelItemDiskCached(self): """ test delitem for classes using the DiskCached decorator """ result = self.add(12,13) |
d = DiskCache(CACHE_DIR) d.fetch(str, 2) key = ((2,),()) assert key in d del d[key] assert key not in d d.fetchObjectId(2, str, 2) assert 2 in d del d[2] assert 2 not in d | cached_str = DiskCache(CACHE_DIR, fn=str) assert cached_str(7) == "7" assert ((7,),()) in cached_str def testIterableCache(self): """ tests the iterable cache """ CACHE_DIR = "./.unittest-temp5" i = IterableCache(CACHE_DIR) getTestIterator = lambda x: xrange(x) for iteratorSize in (4,5,6): cachedIterator = i.fetch... | def testDelItemDiskCache(self): CACHE_DIR = "./.unittest-temp4" d = DiskCache(CACHE_DIR) # using function arguments and fetch d.fetch(str, 2) key = ((2,),()) assert key in d del d[key] assert key not in d # using cache labels and fetchObjectId d.fetchObjectId(2, str, 2) assert 2 in d del d[2] assert 2 not in d |
RE_CHOICES = re.compile("(\w{2,})\s*/\s*(\w{2,})\s*(.*)") | RE_CHOICES = re.compile("(.*?)(\w{2,}[^-])\s*/\s*(\w{2,})\s*(.*)") | def __call__(self, l): result = [] for p in l: result.extend( [ s.strip() for s in SplitBracketExplanations.RE_BRACKET.split(p) if s ] ) |
result.append("%s %s" % (m.group(1), m.group(3)) ) result.append("%s %s" % (m.group(2), m.group(3)) ) | result.append("%s%s %s" % (m.group(1), m.group(2), m.group(4)) ) result.append("%s%s %s" % (m.group(1), m.group(3), m.group(4)) ) | def __call__(self, l): result = [] for p in l: for pp in p.split(", "): if "/" in p: m = SplitMultiTerms.RE_CHOICES.search(pp) if m: result.append("%s %s" % (m.group(1), m.group(3)) ) result.append("%s %s" % (m.group(2), m.group(3)) ) continue |
return re.findall('<span class="tag-chain-item-span">(\w*?)</span>', content, re.IGNORECASE|re.DOTALL) | return re.findall('<span class="(?:tag-chain-item-span|tagItem)">(\w*?)</span>', content, re.IGNORECASE|re.DOTALL) | def _getNGramRelatedTags( content ): """ returns the related tags for the given n-gram @param content of the tags' page @return a list of related tags """ return re.findall('<span class="tag-chain-item-span">(\w*?)</span>', content, re.IGNORECASE|re.DOTALL) |
return [ GeoNames.getGeoEntity( GeoEntity.factory( id = e['geonameId'] )) for e in jsonData['geonames'] if e ] | return filter( [ GeoNames.getGeoEntity( GeoEntity.factory( id = e['geonameId'] )) for e in jsonData['geonames'] ] ) | def getNeighbors(geo_entity): """ returns all neighbours for the given geo id (currently only implemented on a country level) @param[in] geo_entity @returns a list containing the neighbours of the given country """ |
faces = cmd.ls(cmd.polyListComponentConversion(obj,toFace=True),flatten=True) | faces = cmd.polyListComponentConversion( obj, toFace=True ) if not faces: return flipped faces = cmd.ls( faces, flatten=True ) | def findFlipped( obj ): flipped = [] faces = cmd.ls(cmd.polyListComponentConversion(obj,toFace=True),flatten=True) for face in faces: uvNormal = getUVFaceNormal(face) #if the uv face normal is facing into screen then its flipped - add it to the list if uvNormal * Vector([0, 0, 1]) < 0: flipped.append(face) return fli... |
uvAB = Vector( [uvBPos[0]-uvAPos[0], uvBPos[1]-uvAPos[1]] ) uvBC = Vector( [uvCPos[0]-uvBPos[0], uvCPos[1]-uvBPos[1]] ) uvNormal = (uvAB ^ uvBC).normalize() | uvAB = Vector( [uvBPos[0]-uvAPos[0], uvBPos[1]-uvAPos[1], 0] ) uvBC = Vector( [uvCPos[0]-uvBPos[0], uvCPos[1]-uvBPos[1], 0] ) uvNormal = uvAB.cross( uvBC ).normalize() | def getUVFaceNormal( facepath ): uvs = getWindingOrder(facepath) if len(uvs) < 3: return (1,0,0) #if there are less than 3 uvs we have no uv area so bail #get edge vectors and cross them to get the uv face normal uvAPos = cmd.polyEditUV(uvs[0], query=True, uValue=True, vValue=True) uvBPos = cmd.polyEditUV(uvs[1], que... |
volumeBasis = map(mayaVectors.MayaVector, api.getObjectBases(volume)) | volumeBasis = [ Vector( (v.x, v.y, v.z) ) for v in api.getObjectBases( volume ) ] | def __init__( self, x, y, z, vertIdx=None ): vectors.Vector.__init__(self, [x, y, z]) self.id = vertIdx |
''' clsName = 'Labelled_%s' % baseCls.__name__.replace( 'Mel', '' ) | NOTE: the following constructor keywords can be used: llabel, ll sets the text label for the widget llabelWidth, llw sets the label width llabelAlign, lla sets the label alignment the keyword "label" isn't used because the class might be wrapping a widget that validly has a label such as MelButton or MelCheckbox '''... | def labelledUIClassFactory( baseCls ): ''' this class factory creates "labelled" widget classes. a labelled widget class acts just like the baseCls instance except that it has a label ''' clsName = 'Labelled_%s' % baseCls.__name__.replace( 'Mel', '' ) class _tmp(MelHSingleStretchLayout): IS_SETUP = False def __new__(... |
label = kw.pop( 'label', kw.pop( 'l', '<-no label->' ) ) labelWidth = kw.pop( 'labelWidth', kw.pop( 'lw', None ) ) labelAlign = kw.pop( 'labelAlign', kw.pop( 'la', 'left' ) ) | label = kw.pop( 'llabel', kw.pop( 'll', '<-no label->' ) ) labelWidth = kw.pop( 'llabelWidth', kw.pop( 'llw', None ) ) labelAlign = kw.pop( 'llabelAlign', kw.pop( 'lla', 'left' ) ) | def __new__( cls, parent, *a, **kw ): |
raise AttributeError( "No attribute '%s' was found on the object or its '%s' widget member" % (attr, superCls) ) | raise AttributeError( "No attribute '%s' was found on the object or its '%s' widget member" % (attr, baseCls) ) | def _get( self, attr ): if attr in self.__dict__: return self.__dict__[ attr ] |
def getLabel( self ): self.lbl.getValue() def setLabel( self, label ): self.lbl.setValue( label ) def getLabelWidth( self ): self.lbl.setWidth() def setLabelWidth( self, width ): self.lbl.setWidth( width ) | def getLlabel( self ): self.UI_lbl.getValue() def setLlabel( self, label ): self.UI_lbl.setValue( label ) def getLlabelWidth( self ): self.UI_lbl.setWidth() def setLlabelWidth( self, width ): self.UI_lbl.setWidth( width ) | def __setattr__( self, attr, value ): if self.IS_SETUP: self._set( self, attr, value ) return |
projA_B = vec0_2.normalize() * ( (vec0_1 * vec0_2) / vec0_1.length() ) | projA_B = vec0_2.normalize() * ( (vec0_1 * vec0_2) / vec0_2.length() ) | def findPolePosition( end, mid=None, start=None, distanceMultiplier=1 ): if not objExists( end ): return Vector.Zero() try: if mid is None: mid = listRelatives( end, p=True, pa=True )[0] if start is None: start = listRelatives( mid, p=True, pa=True )[0] except TypeError: return Vector.Zero() joint0, joint1, joint2 =... |
uniqueName = formatTokens % (baseName, n) | uniqueName = formatStr % (baseName, n) | def __new__( cls, parent, *a, **kw ): WIDGET_CMD = cls.WIDGET_CMD kw.pop( 'p', None ) #pop any parent specified in teh kw dict - set it explicitly to the parent specified if parent is not None: kw[ 'parent' ] = parent |
class MelHLayout(MelForm): | class _AlignedFormLayout(MelForm): _EDGES = 'left', 'right' def layoutExpand( self, children ): edge1, edge2 = self._EDGES try: padding = self.padding except AttributeError: padding = 0 otherEdges = list( MelFormLayout.ALL_EDGES ) otherEdges.remove( edge1 ) otherEdges.remove( edge2 ) otherEdge1, otherEdge2 = otherEd... | def layout( self ): children = self.getChildren() |
_EDGES = 'left', 'right' | def layout( self ): children = self.getChildren() | |
otherEdges = list( MelFormLayout.ALL_EDGES ) otherEdges.remove( edge1 ) otherEdges.remove( edge2 ) otherEdge1, otherEdge2 = otherEdges for child in children: self( e=True, af=((child, otherEdge1, padding), (child, otherEdge2, padding)) ) | self.layoutExpand( children ) | def layout( self ): padding = self.padding children = self.getChildren() |
class MelHSingleStretchLayout(MelForm): | class MelHRowLayout(_AlignedFormLayout): ''' Simple row layout - the rowLayout mel command isn't so hot because you have to know ahead of time how many columns to build, and dynamic sizing is rubbish. This makes writing a simple row of widgets super easy. NOTE: like all subclasses of MelFormLayout, make sure to call ... | def layout( self ): padding = self.padding children = self.getChildren() |
_EDGES = 'left', 'right' | def layout( self ): padding = self.padding children = self.getChildren() | |
otherEdges = list( MelFormLayout.ALL_EDGES ) otherEdges.remove( edge1 ) otherEdges.remove( edge2 ) otherEdge1, otherEdge2 = otherEdges for child in children: self( e=True, af=((child, otherEdge1, 0), (child, otherEdge2, 0)) ) | self.layoutExpand( children ) | def layout( self ): padding = self.padding children = self.getChildren() |
print e | def netcdf_datatype(type_name): """ converts numpy datatype to NetCDF datatype all floats are converted to doubles all integers are converted to 4 byte int all chars are converted to NetCDF byte-type """ if 'float' in type_name: return 'd' if 'int' in type_name: return 'i' if 'long' in type_name: return 'i' if 'strin... | |
bfr = pybufr.BUFRFile(bufr_fn) | bfr = bufr.BUFRFile(bufr_fn) | def netcdf_datatype(type_name): """ converts numpy datatype to NetCDF datatype all floats are converted to doubles all integers are converted to 4 byte int all chars are converted to NetCDF byte-type """ if 'float' in type_name: return 'd' if 'int' in type_name: return 'i' if 'long' in type_name: return 'i' if 'strin... |
data = pybufr.pack_record(record) | data = bufr.pack_record(record) | def netcdf_datatype(type_name): """ converts numpy datatype to NetCDF datatype all floats are converted to doubles all integers are converted to 4 byte int all chars are converted to NetCDF byte-type """ if 'float' in type_name: return 'd' if 'int' in type_name: return 'i' if 'long' in type_name: return 'i' if 'strin... |
except pybufr.RecordPackError, e: | except bufr.RecordPackError, e: | def netcdf_datatype(type_name): """ converts numpy datatype to NetCDF datatype all floats are converted to doubles all integers are converted to 4 byte int all chars are converted to NetCDF byte-type """ if 'float' in type_name: return 'd' if 'int' in type_name: return 'i' if 'long' in type_name: return 'i' if 'strin... |
data = pybufr.pad_record(data, size, fillvalue) | data = bufr.pad_record(data, size, fillvalue) | def netcdf_datatype(type_name): """ converts numpy datatype to NetCDF datatype all floats are converted to doubles all integers are converted to 4 byte int all chars are converted to NetCDF byte-type """ if 'float' in type_name: return 'd' if 'int' in type_name: return 'i' if 'long' in type_name: return 'i' if 'strin... |
name = '%s%s::%s:%s:%s:%s | name = '%s%s:%s:%s:%s:%s | def parse(path): if path[-3:] == '.gz': handle = gzip.open(path) else: handle = open(path) for line in handle: line = line.strip() if not line: continue fields = line.split() if fields[10] == '0': continue name = '%s%s::%s:%s:%s:%s#%s/%s' % tuple(fields[:8]) print '@%s' % name print fields[8].replace('.', 'N') print '+... |
handle = open(path) | handle = None if path == '-': handle = sys.stdin else: handle = open(path) | def parseCG(path, name): handle = open(path) inContig = False for line in handle: if line[0] == '>': if inContig: #inContig = False break elif line.find(name) > -1: inContig = True print line.strip() else: if inContig: print line.strip() handle.close() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.