code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
for i in range(retry):
try:
LOG.debug('Connectint to %s:%d, try %d...', host, port, i + 1)
link = rpyc_classic.connect(host, port)
link.eval('2 + 2')
except socket.error:
time.sleep(1)
continue
else:
LOG.debug('Conn... | def ida_connect(host='localhost', port=18861, retry=10) | Connect to an instance of IDA running our server.py.
:param host: The host to connect to
:param port: The port to connect to
:param retry: How many times to try after errors before giving up | 3.206597 | 3.459229 | 0.926969 |
ida_progname = _which(ida_binary)
if ida_progname is None:
raise IDALinkError('Could not find executable %s' % ida_binary)
if mode not in ('oneshot', 'threaded'):
raise ValueError("Bad mode %s" % mode)
if logfile is None:
logfile = LOGFILE.format(port=port)
ida_realpa... | def ida_spawn(ida_binary, filename, port=18861, mode='oneshot',
processor_type=None, logfile=None) | Open IDA on the the file we want to analyse.
:param ida_binary: The binary name or path to ida
:param filename: The filename to open in IDA
:param port: The port on which to serve rpc from ida
:param mode: The server mode. "oneshot" to close ida when the connection is closed, or
... | 3.792094 | 3.717264 | 1.02013 |
'''
Helper function used by precache and clearcache that clears the cache
of a given URL and type
'''
if ts is None:
# Clears an entire ForeignResource cache
res = ForeignResource(url)
if not os.path.exists(res.cache_path_base):
cli.printerr('%s is not cached (loo... | def _clear_cache(url, ts=None) | Helper function used by precache and clearcache that clears the cache
of a given URL and type | 3.454735 | 2.868796 | 1.204245 |
'''
Helper function used by precache and precache-named which does the
actual precaching
'''
if force:
cli.print('%s: force clearing' % url)
_clear_cache(url)
cli.print('%s: precaching "%s"' % (url, to_type))
with autodrain_worker():
await singletons.workers.async_enq... | async def _precache(url, to_type, force=False) | Helper function used by precache and precache-named which does the
actual precaching | 8.423963 | 5.665979 | 1.486762 |
def expect_exact(self, *args, **kwargs):
response = self._recvline()
self.before = response.strip() | This does not attempt to duplicate the expect_exact API,
but just sets self.before to the latest response line. | null | null | null | |
"Write your forwards methods here."
for category in orm['document_library.DocumentCategory'].objects.all():
for trans_old in orm['document_library.DocumentCategoryTitle'].objects.filter(category=category):
orm['document_library.DocumentCategoryTranslation'].objects.create(
... | def forwards(self, orm) | Write your forwards methods here. | 2.291201 | 2.228686 | 1.02805 |
redis = oz.redis.create_connection()
pipe = redis.pipeline()
# Get all items that match any of the patterns. Put it in a set to
# prevent duplicates.
if oz.settings["s3_bucket"]:
bucket = oz.aws_cdn.get_bucket()
matches = set([oz.aws_cdn.S3File(key) for prefix in prefixes for ... | def cache_busting_scan(*prefixes) | (Re-)generates the cache buster values for all files with the specified
prefixes. | 3.341292 | 3.246197 | 1.029294 |
if params is None:
params = {}
# Instantiate the app controller
index = BWA_index(params)
# call the application, passing the fasta file in
results = index({'fasta_in': fasta_in})
return results | def create_bwa_index_from_fasta_file(fasta_in, params=None) | Create a BWA index from an input fasta file.
fasta_in: the input fasta file from which to create the index
params: dict of bwa index specific paramters
This method returns a dictionary where the keys are the various
output suffixes (.amb, .ann, .bwt, .pac, .sa) and the values
are open file objects... | 7.724964 | 8.171387 | 0.945368 |
my_params = {'algorithm': 'bwasw'}
my_params.update(params)
result = assign_reads_to_database(query_fasta_fp, database_fasta_fp,
out_fp, my_params)
return result | def assign_dna_reads_to_dna_database(query_fasta_fp, database_fasta_fp, out_fp,
params={}) | Wraps assign_reads_to_database, setting various parameters.
The default settings are below, but may be overwritten and/or added to
using the params dict:
algorithm: bwasw | 3.231961 | 3.262721 | 0.990572 |
for k, v in self.Parameters.iteritems():
if self.Parameters[k].isOn():
if k in self._valid_arguments:
if not self._valid_arguments[k](v.Value):
error_message = 'Invalid argument (%s) ' % v.Value
error_messag... | def check_arguments(self) | Sanity check the arguments passed in.
Uses the boolean functions specified in the subclasses in the
_valid_arguments dictionary to determine if an argument is valid
or invalid. | 4.429104 | 4.028725 | 1.099381 |
command_parts = []
# Append a change directory to the beginning of the command to change
# to self.WorkingDir before running the command
# WorkingDir should be in quotes -- filenames might contain spaces
cd_command = ''.join(['cd ', str(self.WorkingDir), ';'])
if... | def _get_base_command(self) | Returns the full command string
Overridden here because there are positional arguments (specifically
the input and output files). | 6.111951 | 5.848739 | 1.045003 |
# clear self._input; ready to receive new input and output files
self._input = {}
# Check that the arguments to the
# subcommand-specific parameters are valid
self.check_arguments()
# Ensure that we have all required input (file I/O)
for k in self._input... | def _input_as_dict(self, data) | Takes dictionary that sets input and output files.
Valid keys for the dictionary are specified in the subclasses. File
paths must be absolute. | 6.727237 | 6.359996 | 1.057742 |
# determine the names of the files. The name will be the same as the
# input fasta file unless overridden with the -p option
if self.Parameters['-p'].isOn():
prefix = self.Parameters['-p'].Value
else:
prefix = data['fasta_in']
# the 5 output fil... | def _get_result_paths(self, data) | Gets the results for a run of bwa index.
bwa index outputs 5 files when the index is created. The filename
prefix will be the same as the input fasta, unless overridden with
the -p option, and the 5 extensions are listed below:
.amb
.ann
.bwt
.pac
.sa
... | 5.461568 | 3.79671 | 1.4385 |
'''
Return a list of all paths to all nodes from a given start node
'''
if seen is None:
seen = frozenset()
results = [(0, (start, ))]
if start in seen or start not in self.edges:
return results
seen = seen | frozenset((start,))
for... | def get_all_paths_from(self, start, seen=None) | Return a list of all paths to all nodes from a given start node | 2.947833 | 2.651047 | 1.11195 |
for operation in operations:
if isinstance(operation, Equal):
#print("Equal: {0}".format(str(a_tokens[operation.a1:operation.a2])))
for t in a_tokens[operation.a1:operation.a2]: yield t
elif isinstance(operation, Insert):
#print("Insert: {0}".format(str(b_t... | def apply(operations, a_tokens, b_tokens) | Applies a sequences of operations to tokens -- copies tokens from
`a_tokens` and `b_tokens` according to `operations`.
:Parameters:
operations : sequence of :~class:`deltas.Operation`
Operations to perform
a_tokens : list of `comparable`
Starting sequence of comparable t... | 2.083417 | 2.221265 | 0.937942 |
shell_command = stress_string.format(cpu_width, time_height)
job = JobBlock(cpu_width, time_height)
job.set_job(subprocess.call, shell_command, shell=True)
return job | def create_job(cpu_width, time_height) | :param cpu_width: number of cpus
:param time_height: amount of time
:return: the instantiated JobBlock object | 6.024185 | 4.893776 | 1.230989 |
aln = Alignment(aln)
if len(structure_string) != aln.SeqLen:
raise ValueError, %(len(structure_string),\
aln.SeqLen)
else:
struct_dict = {'SS_cons':structure_string}
#Make new Cmbuild app instance.
app = Cmbuild(InputHandler='_input_as_paths',WorkingDir='/tmp',\
... | def cmbuild_from_alignment(aln, structure_string, refine=False, \
return_alignment=False,params=None) | Uses cmbuild to build a CM file given an alignment and structure string.
- aln: an Alignment object or something that can be used to construct
one. All sequences must be the same length.
- structure_string: vienna structure string representing the consensus
stucture for the seq... | 5.371391 | 5.066187 | 1.060243 |
#get alignment and structure string from stockholm file.
info, aln, structure_string = \
list(MinimalRfamParser(open(stockholm_file_path,'U'),\
seq_constructor=ChangedSequence))[0]
#call cmbuild_from_alignment.
res = cmbuild_from_alignment(aln, structure_string, refine=refine, ... | def cmbuild_from_file(stockholm_file_path, refine=False,return_alignment=False,\
params=None) | Uses cmbuild to build a CM file given a stockholm file.
- stockholm_file_path: a path to a stockholm file. This file should
contain a multiple sequence alignment formated in Stockholm format.
This must contain a sequence structure line:
#=GC SS_cons <structure string>
... | 6.390484 | 6.2306 | 1.025661 |
#NOTE: Must degap seqs or Infernal well seg fault!
seqs = SequenceCollection(seqs,MolType=moltype).degap()
#Create mapping between abbreviated IDs and full IDs
int_map, int_keys = seqs.getIntMap()
#Create SequenceCollection from int_map.
int_map = SequenceCollection(int_map,MolType=moltype)... | def cmalign_from_alignment(aln, structure_string, seqs, moltype=DNA,\
include_aln=True,refine=False, return_stdout=False,params=None,\
cmbuild_params=None) | Uses cmbuild to build a CM file, then cmalign to build an alignment.
- aln: an Alignment object or something that can be used to construct
one. All sequences must be the same length.
- structure_string: vienna structure string representing the consensus
stucture for the sequenc... | 5.67613 | 5.576432 | 1.017878 |
#NOTE: Must degap seqs or Infernal well seg fault!
seqs = SequenceCollection(seqs,MolType=moltype).degap()
#Create mapping between abbreviated IDs and full IDs
int_map, int_keys = seqs.getIntMap()
#Create SequenceCollection from int_map.
int_map = SequenceCollection(int_map,MolType=moltype... | def cmalign_from_file(cm_file_path, seqs, moltype=DNA, alignment_file_path=None,\
include_aln=False,return_stdout=False,params=None) | Uses cmalign to align seqs to alignment in cm_file_path.
- cm_file_path: path to the file created by cmbuild, containing aligned
sequences. This will be used to align sequences in seqs.
- seqs: unaligned sequendes that are to be aligned to the sequences in
cm_file.
- mol... | 6.344076 | 6.250867 | 1.014911 |
#NOTE: Must degap seqs or Infernal well seg fault!
seqs = SequenceCollection(seqs,MolType=moltype).degap()
#Create mapping between abbreviated IDs and full IDs
int_map, int_keys = seqs.getIntMap()
#Create SequenceCollection from int_map.
int_map = SequenceCollection(int_map,MolType=moltype)... | def cmsearch_from_alignment(aln, structure_string, seqs, moltype, cutoff=0.0,\
refine=False,params=None) | Uses cmbuild to build a CM file, then cmsearch to find homologs.
- aln: an Alignment object or something that can be used to construct
one. All sequences must be the same length.
- structure_string: vienna structure string representing the consensus
stucture for the sequences i... | 6.345842 | 6.099828 | 1.040331 |
#NOTE: Must degap seqs or Infernal well seg fault!
seqs = SequenceCollection(seqs,MolType=moltype).degap()
#Create mapping between abbreviated IDs and full IDs
int_map, int_keys = seqs.getIntMap()
#Create SequenceCollection from int_map.
int_map = SequenceCollection(int_map,MolType=moltype)... | def cmsearch_from_file(cm_file_path, seqs, moltype, cutoff=0.0, params=None) | Uses cmbuild to build a CM file, then cmsearch to find homologs.
- cm_file_path: path to the file created by cmbuild, containing aligned
sequences. This will be used to search sequences in seqs.
- seqs: SequenceCollection object or something that can be used to
construct one, co... | 7.362805 | 7.299292 | 1.008701 |
filename = FilePath(self.getTmpFilename(self.TmpDir))
data_file = open(filename,'w')
data_file.write(data)
data_file.close()
return filename | def _tempfile_as_multiline_string(self, data) | Write a multiline string to a temp file and return the filename.
data: a multiline string to be written to a file.
* Note: the result will be the filename as a FilePath object
(which is a string subclass). | 4.933924 | 4.685529 | 1.053013 |
# We only work with lower case
sound_tuple = SoundTuple._make([s.lower() for s in sound_tuple])
# Words with no vowel are always valid
# FIXME: This looks like it should be toggled by a config key.
if not sound_tuple.vowel:
result = True
elif final_form:
result = \
... | def is_valid_sound_tuple(sound_tuple, final_form=True) | Check if a character combination complies to Vietnamese phonology.
The basic idea is that if one can pronunce a sound_tuple then it's valid.
Sound tuples containing consonants exclusively (almost always
abbreviations) are also valid.
Input:
sound_tuple - a SoundTuple
final_form - wheth... | 3.640843 | 3.488646 | 1.043626 |
'''
Guesses a TypeString from the given path
'''
typestring = UNKNOWN
for detector in self.detectors:
if typestring != UNKNOWN and not detector.can_improve(typestring):
continue
if not detector.can_detect(path):
continue
... | def detect(self, path) | Guesses a TypeString from the given path | 4.832012 | 3.326485 | 1.452588 |
oz.aws_cdn.set_cache_buster(self.redis(), path, hash) | def set_cache_buster(self, path, hash) | Sets the cache buster value for a given file path | 19.513058 | 23.01536 | 0.847828 |
f = self.get_file(path)
f.upload(contents, replace=replace)
self.set_cache_buster(path, f.hash()) | def upload_file(self, path, contents, replace=False) | Uplodas the file to its path with the given `content`, adding the
appropriate parent directories when needed. If the path already exists
and `replace` is `False`, the file will not be uploaded. | 4.614401 | 5.344923 | 0.863324 |
f = self.get_file(from_path)
if f.copy(to_path, replace):
self.set_cache_buster(to_path, f.hash()) | def copy_file(self, from_path, to_path, replace=False) | Copies a file from a given source path to a destination path, adding
appropriate parent directories when needed. If the destination path
already exists and `replace` is `False`, the file will not be
uploaded. | 4.450183 | 4.782108 | 0.93059 |
self.get_file(path).remove()
self.remove_cache_buster(path) | def remove_file(self, path) | Removes the given file | 7.593187 | 8.315965 | 0.913086 |
if add_seq_names:
app = Clustalw(InputHandler='_input_as_seqs',\
WorkingDir=WorkingDir,SuppressStderr=SuppressStderr,\
SuppressStdout=SuppressStdout)
else:
app = Clustalw(InputHandler='_input_as_lines',\
WorkingDir=WorkingDir,SuppressStderr=SuppressStderr... | def alignUnalignedSeqs(seqs,add_seq_names=True,WorkingDir=None,\
SuppressStderr=None,SuppressStdout=None) | Aligns unaligned sequences
seqs: either list of sequence objects or list of strings
add_seq_names: boolean. if True, sequence names are inserted in the list
of sequences. if False, it assumes seqs is a list of lines of some
proper format that the program can handle | 2.466051 | 2.704423 | 0.911858 |
app = Clustalw(WorkingDir=WorkingDir,SuppressStderr=SuppressStderr,\
SuppressStdout=SuppressStdout)
return app(filename) | def alignUnalignedSeqsFromFile(filename,WorkingDir=None,SuppressStderr=None,\
SuppressStdout=None) | Aligns unaligned sequences from some file (file should be right format)
filename: string, the filename of the file containing the sequences
to be aligned in a valid format. | 3.356877 | 4.341588 | 0.773191 |
app = Clustalw({'-profile':None,'-profile1':aln1,\
'-profile2':aln2,'-outfile':outfile},SuppressStderr=\
SuppressStderr,WorkingDir=WorkingDir,SuppressStdout=SuppressStdout)
app.Parameters['-align'].off()
return app() | def alignTwoAlignments(aln1,aln2,outfile,WorkingDir=None,SuppressStderr=None,\
SuppressStdout=None) | Aligns two alignments. Individual sequences are not realigned
aln1: string, name of file containing the first alignment
aln2: string, name of file containing the second alignment
outfile: you're forced to specify an outfile name, because if you don't
aln1 will be overwritten. So, if you want aln1 t... | 7.10951 | 8.383699 | 0.848016 |
app = Clustalw({'-sequences':None,'-profile1':aln1,\
'-profile2':seqs,'-outfile':outfile},SuppressStderr=\
SuppressStderr,WorkingDir=WorkingDir, SuppressStdout=SuppressStdout)
app.Parameters['-align'].off()
return app() | def addSeqsToAlignment(aln1,seqs,outfile,WorkingDir=None,SuppressStderr=None,\
SuppressStdout=None) | Aligns sequences from second profile against first profile
aln1: string, name of file containing the alignment
seqs: string, name of file containing the sequences that should be added
to the alignment.
opoutfile: string, name of the output file (the new alignment) | 9.731916 | 10.022253 | 0.971031 |
app = Clustalw({'-tree':None,'-infile':filename},SuppressStderr=\
SuppressStderr,WorkingDir=WorkingDir)
app.Parameters['-align'].off()
return app() | def buildTreeFromAlignment(filename,WorkingDir=None,SuppressStderr=None) | Builds a new tree from an existing alignment
filename: string, name of file containing the seqs or alignment | 13.756688 | 17.324301 | 0.794069 |
# Create instance of app controller, enable tree, disable alignment
app = Clustalw(InputHandler='_input_as_multiline_string', params=params, \
WorkingDir='/tmp')
app.Parameters['-align'].off()
#Set params to empty dict if None.
if params is None:
params={}
if mo... | def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params=None) | Returns a tree from Alignment object aln.
aln: an cogent.core.alignment.Alignment object, or data that can be used
to build one.
moltype: cogent.core.moltype.MolType object
best_tree: if True (default:False), uses a slower but more accurate
algorithm to build the tree.
params: dict of parame... | 5.206336 | 4.862622 | 1.070685 |
# Create instance of controllor, enable bootstrap, disable alignment,tree
app = Clustalw(InputHandler='_input_as_multiline_string', params=params, \
WorkingDir='/tmp')
app.Parameters['-align'].off()
app.Parameters['-tree'].off()
if app.Parameters['-bootstrap'].isOff():
... | def bootstrap_tree_from_alignment(aln, seed=None, num_trees=None, params=None) | Returns a tree from Alignment object aln with bootstrap support values.
aln: an cogent.core.alignment.Alignment object, or data that can be used
to build one.
seed: an interger, seed value to use
num_trees: an integer, number of trees to bootstrap against
params: dict of parameters to pass in to... | 5.351006 | 5.110139 | 1.047135 |
#create SequenceCollection object from seqs
seq_collection = SequenceCollection(seqs,MolType=moltype)
#Create mapping between abbreviated IDs and full IDs
int_map, int_keys = seq_collection.getIntMap()
#Create SequenceCollection from int_map.
int_map = SequenceCollection(int_map,MolType=mol... | def align_unaligned_seqs(seqs, moltype=DNA, params=None) | Returns an Alignment object from seqs.
seqs: cogent.core.alignment.SequenceCollection object, or data that can be
used to build one.
moltype: a MolType object. DNA, RNA, or PROTEIN.
params: dict of parameters to pass in to the Clustal app controller.
Result will be a cogent.core.alignment.Align... | 4.685443 | 4.65868 | 1.005745 |
#create SequenceCollection object from seqs
seq_collection = SequenceCollection(seqs,MolType=moltype)
#Create mapping between abbreviated IDs and full IDs
seq_int_map, seq_int_keys = seq_collection.getIntMap()
#Create SequenceCollection from int_map.
seq_int_map = SequenceCollection(seq_int... | def add_seqs_to_alignment(seqs, aln, moltype, params=None) | Returns an Alignment object from seqs and existing Alignment.
seqs: a cogent.core.alignment.SequenceCollection object, or data that can
be used to build one.
aln: a cogent.core.alignment.Alignment object, or data that can be used to
build one
params: dict of parameters to pass in to the Clustal a... | 3.345058 | 3.310387 | 1.010473 |
#create SequenceCollection object from seqs
aln1 = Alignment(aln1,MolType=moltype)
#Create mapping between abbreviated IDs and full IDs
aln1_int_map, aln1_int_keys = aln1.getIntMap()
#Create SequenceCollection from int_map.
aln1_int_map = Alignment(aln1_int_map,MolType=moltype)
#create... | def align_two_alignments(aln1, aln2, moltype, params=None) | Returns an Alignment object from two existing Alignments.
aln1, aln2: cogent.core.alignment.Alignment objects, or data that can be
used to build them.
params: dict of parameters to pass in to the Clustal app controller. | 3.320872 | 3.296286 | 1.007458 |
if data:
self.Parameters['-infile']\
.on(super(Clustalw,self)._input_as_multiline_string(data))
return '' | def _input_as_multiline_string(self, data) | Writes data to tempfile and sets -infile parameter
data -- list of lines | 12.239104 | 8.225972 | 1.487861 |
if data:
self.Parameters['-infile']\
.on(super(Clustalw,self)._input_as_lines(data))
return '' | def _input_as_lines(self,data) | Writes data to tempfile and sets -infile parameter
data -- list of lines, ready to be written to file | 12.150107 | 8.991554 | 1.35128 |
_output_formats={'GCG':'.msf',
'GDE':'.gde',
'PHYLIP':'.phy',
'PIR':'.pir',
'NEXUS':'.nxs'}
if self.Parameters['-output'].isOn():
return _output_formats[self.Parameters['-output'].Value]... | def _suffix(self) | Return appropriate suffix for alignment file | 7.09659 | 5.812587 | 1.2209 |
if self.Parameters['-outfile'].isOn():
aln_filename = self._absolute(self.Parameters['-outfile'].Value)
else:
aln_filename = prefix + self._suffix()
return aln_filename | def _aln_filename(self,prefix) | Return name of file containing the alignment
prefix -- str, prefix of alignment file. | 4.761019 | 5.291392 | 0.899767 |
try:
sanic.exceptions.abort(http_status_code, exc)
except sanic.exceptions.SanicException as err:
err.data = kwargs
err.exc = exc
raise err | def abort(http_status_code, exc=None, **kwargs) | Raise a HTTPException for the given http_status_code. Attach any keyword
arguments to the exception for later processing.
From Flask-Restful. See NOTICE file for license information. | 4.052948 | 4.600557 | 0.880969 |
return core.get_value(req.match_info, name, field) | def parse_view_args(self, req, name, field) | Pull a value from the request's ``view_args``. | 9.083139 | 9.239834 | 0.983041 |
if len(args) > 1 and isinstance(args[1], sanic.request.Request):
req = args[1]
else:
req = args[0]
assert isinstance(
req, sanic.request.Request
), "Request argument not found for handler"
return req | def get_request_from_view_args(self, view, args, kwargs) | Get request object from a handler function or method. Used internally by
``use_args`` and ``use_kwargs``. | 3.476586 | 3.582777 | 0.970361 |
if not (req.body and is_json_request(req)):
return core.missing
json_data = req.json
if json_data is None:
return core.missing
return core.get_value(json_data, name, field, allow_many_nested=True) | def parse_json(self, req, name, field) | Pull a json value from the request. | 5.953899 | 5.294671 | 1.124508 |
status_code = getattr(error, "status_code", self.DEFAULT_VALIDATION_STATUS)
abort(status_code, exc=error, messages=error.messages, schema=schema) | def handle_error(self, error, req, schema) | Handles errors during parsing. Aborts the current HTTP request and
responds with a 422 error. | 5.323628 | 5.184836 | 1.026769 |
'''
Walk a directory structure and yield full parallel source and destination
files, munging filenames as necessary
'''
for dirpath, dirnames, filenames in os.walk(source_d):
relpath = os.path.relpath(dirpath, source_d)
if relpath == '.':
relpath = '' # remove implied '.... | def directory_walk(source_d, destination_d) | Walk a directory structure and yield full parallel source and destination
files, munging filenames as necessary | 2.878457 | 1.972468 | 1.459318 |
'''
Create dirs and symlink all files recursively from source_d, ignoring
errors (e.g. existing files)
'''
func = os.symlink
if os.name == 'nt':
# NOTE: need to verify that default perms only allow admins to create
# symlinks on Windows
func = shutil.copy
if os.path.e... | def recursive_symlink_dirs(source_d, destination_d) | Create dirs and symlink all files recursively from source_d, ignoring
errors (e.g. existing files) | 5.866122 | 3.906639 | 1.501578 |
'''
Same as above, except creating hardlinks for all files
'''
func = os.link
if os.name == 'nt':
func = shutil.copy
if os.path.exists(destination_d):
os.rmdir(destination_d)
shutil.copytree(source_d, destination_d, copy_function=func) | def recursive_hardlink_dirs(source_d, destination_d) | Same as above, except creating hardlinks for all files | 3.548404 | 2.611025 | 1.359008 |
'''
Given an array in format:
[
["100644", "blob", "ab3ce...", "748", ".gitignore" ],
["100644", "blob", "ab3ce...", "748", "path/to/thing" ],
...
]
Outputs in a nested format:
{
"path": "/",
"type": "directory",
... | def flat_git_tree_to_nested(flat_tree, prefix='') | Given an array in format:
[
["100644", "blob", "ab3ce...", "748", ".gitignore" ],
["100644", "blob", "ab3ce...", "748", "path/to/thing" ],
...
]
Outputs in a nested format:
{
"path": "/",
"type": "directory",
"children"... | 3.251243 | 2.239331 | 1.451881 |
'''
Import settings key as a dict or list with values of importable paths
If a default constructor is specified, and a path is not importable, it
falls back to running the given constructor.
'''
value = getattr(self, key)
if default is not None:
def lo... | def load_all(self, key, default=None) | Import settings key as a dict or list with values of importable paths
If a default constructor is specified, and a path is not importable, it
falls back to running the given constructor. | 4.905894 | 2.356925 | 2.081481 |
'''
Load and return a given import path to a module or class
'''
containing_module, _, last_item = path.rpartition('.')
if last_item[0].isupper():
# Is a class definition, should do an "import from"
path = containing_module
imported_obj = importlib... | def load_path(self, path) | Load and return a given import path to a module or class | 5.375438 | 4.455515 | 1.206468 |
'''
Same as `load_path(path)', except uses default_constructor on import
errors, or if loaded a auto-generated namespace package (e.g. bare
directory).
'''
try:
imported_obj = self.load_path(path)
except (ImportError, ConfigurationError):
i... | def load_path_with_default(self, path, default_constructor) | Same as `load_path(path)', except uses default_constructor on import
errors, or if loaded a auto-generated namespace package (e.g. bare
directory). | 7.160228 | 3.412784 | 2.098061 |
'''
Override existing settings, taking precedence over both user settings
object and default settings. Useful for specific runtime requirements,
such as overriding PORT or HOST.
'''
for lower_key, value in kwargs.items():
if lower_key.lower() != lower_key:
... | def set(self, **kwargs) | Override existing settings, taking precedence over both user settings
object and default settings. Useful for specific runtime requirements,
such as overriding PORT or HOST. | 6.635597 | 2.783235 | 2.384131 |
'''
Useful for tests for overriding current settings manually
'''
self._previous_settings = self.settings_module
self.settings_module = settings_module
self.reconfigure() | def use_settings(self, settings_module) | Useful for tests for overriding current settings manually | 9.544171 | 3.991734 | 2.390984 |
'''
Slightly cleaner interface to override settings that autogenerates a
settings module based on a given dict.
'''
class SettingsDictModule:
__slots__ = tuple(key.upper() for key in settings_dict.keys())
settings_obj = SettingsDictModule()
for key, va... | def use_settings_dict(self, settings_dict) | Slightly cleaner interface to override settings that autogenerates a
settings module based on a given dict. | 5.25815 | 2.551797 | 2.060568 |
'''
Given a Python import path, convert to a likely absolute filesystem
path, by searching for the given filename marker (such as
'package.json' or '__init__.py') through the Python system path. Do not
return given filename.
'''
path_fragment = import_path.replace... | def import_path_to_absolute_path(import_path, file_marker) | Given a Python import path, convert to a likely absolute filesystem
path, by searching for the given filename marker (such as
'package.json' or '__init__.py') through the Python system path. Do not
return given filename. | 4.313445 | 2.037328 | 2.117207 |
telex = {
"a": "a^",
"o": "o^",
"e": "e^",
"w": ["u*", "o*", "a+"],
"d": "d-",
"f": "\\",
"s": "/",
"r": "?",
"x": "~",
"j": ".",
}
if w_shorthand:
telex["w"].append('<ư')
if brackets_shorthand:
telex.... | def get_telex_definition(w_shorthand=True, brackets_shorthand=True) | Create a definition dictionary for the TELEX input method
Args:
w_shorthand (optional): allow a stand-alone w to be
interpreted as an ư. Default to True.
brackets_shorthand (optional, True): allow typing ][ as
shorthand for ươ. Default to True.
Returns a dictionary to b... | 5.069324 | 5.077522 | 0.998385 |
result = ""
raw = result
result_parts = []
if rules is None:
rules = get_telex_definition()
accepted_chars = _accepted_chars(rules)
for key in sequence:
if key not in accepted_chars:
result_parts.append(result)
result_parts.append(key)
r... | def process_sequence(sequence,
rules=None,
skip_non_vietnamese=True) | \
Convert a key sequence into a Vietnamese string with diacritical marks.
Args:
rules (optional): see docstring for process_key().
skip_non_vietnamese (optional): see docstring for process_key().
It even supports continous key sequences connected by separators.
i.e. process_sequence('c... | 3.396304 | 3.466245 | 0.979822 |
# if key in im:
# lkey = key
# else:
# lkey = key.lower()
lkey = key.lower()
if lkey in im:
if isinstance(im[lkey], list):
trans_list = im[lkey]
else:
trans_list = [im[lkey]]
for i, trans in enumerate(trans_list):
if tran... | def _get_transformation_list(key, im, fallback_sequence) | Return the list of transformations inferred from the entered key. The
map between transform types and keys is given by module
bogo_config (if exists) or by variable simple_telex_im
if entered key is not in im, return "+key", meaning appending
the entered key to current text | 3.830846 | 3.76244 | 1.018181 |
# TODO: VIQR-like convention
mark_action = {
'^': (_Action.ADD_MARK, Mark.HAT),
'+': (_Action.ADD_MARK, Mark.BREVE),
'*': (_Action.ADD_MARK, Mark.HORN),
'-': (_Action.ADD_MARK, Mark.BAR),
}
accent_action = {
'\\': (_Action.ADD_ACCENT, Accent.GRAVE),
... | def _get_action(trans) | Return the action inferred from the transformation `trans`.
and the parameter going with this action
An _Action.ADD_MARK goes with a Mark
while an _Action.ADD_ACCENT goes with an Accent | 3.435173 | 2.930879 | 1.172063 |
logging.debug("== In _transform(%s, %s) ==", comps, trans)
components = list(comps)
action, parameter = _get_action(trans)
if action == _Action.ADD_MARK and \
components[2] == "" and \
mark.strip(components[1]).lower() in ['oe', 'oa'] and trans == "o^":
action, para... | def _transform(comps, trans) | Transform the given string with transform type trans | 4.870468 | 4.833648 | 1.007617 |
action, parameter = _get_action(trans)
comps = list(components)
string = utils.join(comps)
if action == _Action.ADD_CHAR and string[-1].lower() == parameter.lower():
if comps[2]:
i = 2
elif comps[1]:
i = 1
else:
i = 0
comps[i] = ... | def _reverse(components, trans) | Reverse the effect of transformation 'trans' on 'components'
If the transformation does not affect the components, return the original
string. | 3.667306 | 3.555116 | 1.031557 |
comps = list(comps)
accent_list = list(map(accent.get_accent_char, comps[1]))
mark_list = list(map(mark.get_mark_char, utils.join(comps)))
action_list = list(map(lambda x: _get_action(x), trans_list))
def atomic_check(action):
return (action[0] == _Action.ADD_ACCENT and action... | def _can_undo(comps, trans_list) | Return whether a components can be undone with one of the transformation in
trans_list. | 3.872444 | 3.834563 | 1.009879 |
# I can't find a simple explanation for this, so
# I hope this example can help clarify it:
#
# handle_backspace(thương, thuwongw) -> thuwonw
# handle_backspace(thươn, thuwonw) -> thuwow
# handle_backspace(thươ, thuwow) -> thuw
# handle_backspace(thươ, thuw) -> th
#
# The algori... | def handle_backspace(converted_string, raw_sequence, im_rules=None) | Returns a new raw_sequence after a backspace. This raw_sequence should
be pushed back to process_sequence(). | 4.301645 | 4.204877 | 1.023013 |
char = accent.remove_accent_char(char.lower())
if char == "":
return Mark.NONE
if char == "đ":
return Mark.BAR
if char in "ă":
return Mark.BREVE
if char in "ơư":
return Mark.HORN
if char in "âêô":
return Mark.HAT
return Mark.NONE | def get_mark_char(char) | Get the mark of a single char, if any. | 5.244717 | 4.907818 | 1.068645 |
if index == -1:
return string
# Python can handle the case which index is out of range of given string
return string[:index] + add_mark_char(string[index], mark) + string[index+1:] | def add_mark_at(string, index, mark) | Add mark to the index-th character of the given string. Return the new string after applying change.
Notice: index > 0 | 5.825392 | 5.685112 | 1.024675 |
if char == "":
return ""
case = char.isupper()
ac = accent.get_accent_char(char)
char = accent.add_accent_char(char.lower(), Accent.NONE)
new_char = char
if mark == Mark.HAT:
if char in FAMILY_A:
new_char = "â"
elif char in FAMILY_O:
new_char ... | def add_mark_char(char, mark) | Add mark to a single char. | 2.116641 | 2.090427 | 1.01254 |
if mark_trans == "*_":
return True
components = list(comps)
if mark_trans[0] == 'd' and components[0] \
and components[0][-1].lower() in ("d", "đ"):
return True
elif components[1] != "" and \
strip(components[1]).lower().find(mark_trans[0]) != -1:
re... | def is_valid_mark(comps, mark_trans) | Check whether the mark given by mark_trans is valid to add to the components | 5.208168 | 5.119699 | 1.01728 |
return self.session.delete(self._request_url(path),
auth=self.auth, verify=False) | def delete(self, path) | Call the Infoblox device to delete the ref
:param str ref: The reference id
:rtype: requests.Response | 6.218329 | 7.003451 | 0.887895 |
return self.session.get(self._request_url(path, return_fields),
data=json.dumps(data),
auth=self.auth, verify=False) | def get(self, path, data=None, return_fields=None) | Call the Infoblox device to get the obj for the data passed in
:param str obj_reference: The object reference data
:param dict data: The data for the get request
:rtype: requests.Response | 3.949569 | 4.988214 | 0.79178 |
LOGGER.debug('Posting data: %r', data)
return self.session.post(self._request_url(path),
data=json.dumps(data or {}),
headers=self.HEADERS, auth=self.auth,
verify=False) | def post(self, path, data) | Call the Infoblox device to post the obj for the data passed in
:param str obj: The object type
:param dict data: The data for the post
:rtype: requests.Response | 4.170566 | 4.300358 | 0.969818 |
# Hack to make user code available for import
sys.path.append(".")
# Run the specified action
oz.initialize()
retr = optfn.run(list(oz._actions.values()))
if retr == optfn.ERROR_RETURN_CODE:
sys.exit(-1)
elif retr == None:
sys.exit(0)
elif isinstance(retr, int):
... | def main() | Main entry-point for oz's cli | 5.856445 | 5.381131 | 1.08833 |
params['--out'] = get_tmp_filename(working_dir)
# Create instance of app controller, enable tree, disable alignment
app = Clearcut(InputHandler='_input_as_multiline_string', params=params, \
WorkingDir=working_dir, SuppressStdout=True,\
SuppressStderr=True)
#I... | def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params={},\
working_dir='/tmp') | Returns a tree from Alignment object aln.
aln: an cogent.core.alignment.Alignment object, or data that can be used
to build one.
- Clearcut only accepts aligned sequences. Alignment object used to
handle unaligned sequences.
moltype: a cogent.core.moltype object.
- NOTE: If molty... | 7.021948 | 6.249511 | 1.1236 |
params['--out'] = get_tmp_filename(working_dir)
# Create instance of app controller, enable tree, disable alignment
app = Clearcut(InputHandler='_input_as_multiline_string', params=params, \
WorkingDir=working_dir, SuppressStdout=True,\
SuppressStderr=True)
#T... | def build_tree_from_distance_matrix(matrix, best_tree=False, params={},\
working_dir='/tmp') | Returns a tree from a distance matrix.
matrix: a square Dict2D object (cogent.util.dict2d)
best_tree: if True (default:False), uses a slower but more accurate
algorithm to build the tree.
params: dict of parameters to pass in to the Clearcut app controller.
The result will be an cogent.core.tree... | 7.934973 | 7.21807 | 1.099321 |
#clearcut truncates names to 10 char- need to rename before and
#reassign after
#make a dict of env_index:full name
int_keys = dict([('env_' + str(i), k) for i,k in \
enumerate(sorted(matrix.keys()))])
#invert the dict
int_map = {}
for i in int_keys:
int_map[int_key... | def _matrix_input_from_dict2d(matrix) | makes input for running clearcut on a matrix from a dict2D object | 6.30534 | 5.670672 | 1.111921 |
if data:
self.Parameters['--in']\
.on(super(Clearcut,self)._input_as_multiline_string(data))
return '' | def _input_as_multiline_string(self, data) | Writes data to tempfile and sets -infile parameter
data -- list of lines | 15.067573 | 13.261731 | 1.136169 |
if data:
self.Parameters['--in']\
.on(super(Clearcut,self)._input_as_lines(data))
return '' | def _input_as_lines(self,data) | Writes data to tempfile and sets -infile parameter
data -- list of lines, ready to be written to file | 16.120155 | 15.395751 | 1.047052 |
if self.Parameters['--out']:
aln_filename = self._absolute(self.Parameters['--out'].Value)
else:
raise ValueError, "No tree output file specified."
return aln_filename | def _tree_filename(self) | Return name of file containing the alignment
prefix -- str, prefix of alignment file. | 9.047924 | 7.89701 | 1.14574 |
attempts = 0
response = None
while attempts <= self.retries:
try:
response = request(uri, headers=self.headers, proxies=self.proxy, **kwargs)
except (requests.ConnectionError, requests.HTTPError) as ce:
attempts += 1
... | def _make_request(self, request, uri, **kwargs) | This is final step of calling out to the remote API. We set up our
headers, proxy, debugging etc. The only things in **kwargs are
parameters that are overridden on an API method basis (like timeout)
We have a simple attempt/while loop to implement retries w/ delays to
avoid the brittle... | 2.87773 | 2.701746 | 1.065137 |
if not timeout:
timeout = self.timeout
return self._make_request(requests.get, uri, params=parameters, timeout=timeout) | def _make_get_request(self, uri, parameters=None, timeout=None) | Given a request add in the required parameters and return the parsed
XML object. | 3.364689 | 3.11177 | 1.081278 |
if not timeout:
timeout = self.timeout
return self._make_request(requests.post, uri, data=payload, timeout=timeout) | def _make_post_request(self, uri, payload, timeout=None) | Given a request add in the required parameters and return the parsed
XML object. | 3.231802 | 3.051144 | 1.05921 |
if not timeout:
timeout = self.timeout
return self._make_request(requests.delete, uri, timeout=timeout) | def _make_delete_request(self, uri, timeout=None) | Given a request add in the required parameters and return the parsed
XML object. | 3.327106 | 3.111747 | 1.069208 |
'''
Closes aiohttp session and all open file descriptors
'''
if hasattr(self, 'aiohttp'):
if not self.aiohttp.closed:
self.aiohttp.close()
if hasattr(self, 'file_descriptors'):
for fd in self.file_descriptors.values():
if no... | def _close(self) | Closes aiohttp session and all open file descriptors | 3.422441 | 2.238183 | 1.529116 |
if pageNum < 1:
raise ErrPaginationLimits(ErrPaginationLimits.ERR_PAGE_NUM)
if itemsPerPage < Settings.itemsPerPageMin or itemsPerPage > Settings.itemsPerPageMax:
raise ErrPaginationLimits(ErrPaginationLimits.ERR_ITEMS_PER_PAGE) | def checkAndRaise(pageNum, itemsPerPage) | Check and Raise an Exception if needed
Args:
pageNum (int): Page number
itemsPerPage (int): Number of items per Page
Raises:
ErrPaginationLimits: If we are out of limits | 3.51072 | 2.479217 | 1.41606 |
unpacked = struct.unpack(BASE_FORMAT, data[:_FORMAT_SIZE])
psize, protocol, mac, gateway, time, ptype = unpacked
header = Header(psize, protocol, mac, gateway, time, ptype)
return header, data[_FORMAT_SIZE:] | def parse_packet(data, format=None) | Parses a Lifx data packet (as a bytestring), returning into a Header object
for the fields that are common to all data packets, and a bytestring of
payload data for the type-specific fields (suitable for passing to
`parse_payload`). | 5.728282 | 5.621446 | 1.019005 |
payload = struct.unpack(payload_fmt, data)
return dict(zip(payload_names, payload)) | def parse_payload(data, payload_fmt, *payload_names) | Parses a bytestring of Lifx payload data (the bytes after the common
fields), as returned by `parse_packet`. Returns a dictionary where the keys
are from `payload_names` and the values are the corresponding values from
the bytestring. | 2.73943 | 3.419392 | 0.801145 |
protocol = kwargs.get('protocol', COMMAND_PROTOCOL)
packet_fmt = BASE_FORMAT + payload_fmt
packet_size = struct.calcsize(packet_fmt)
return struct.pack(packet_fmt,
packet_size,
protocol,
bulb,
gateway,
... | def build_packet(packet_type, gateway, bulb, payload_fmt, *payload_args,
**kwargs) | Constructs a Lifx packet, returning a bytestring. The arguments are as
follows:
- `packet_type`, an integer
- `gateway`, a 6-byte string containing the mac address of the gateway bulb
- `bulb`, a 6-byte string containing either the mac address of the target
bulb or `ALL_BULBS`
- `payload_fmt`... | 3.512153 | 3.515288 | 0.999108 |
return ''.join(chr(int(bytestr[k:k + 2], 16))
for k in range(0, len(bytestr), 2)) | def _unbytes(bytestr) | Returns a bytestring from the human-friendly string returned by `_bytes`.
>>> _unbytes('123456')
'\x12\x34\x56' | 2.289927 | 2.773977 | 0.825503 |
thr = Thread(target=func, args=args, kwargs=kwargs)
thr.daemon = True
thr.start()
return thr | def _spawn(func, *args, **kwargs) | Calls `func(*args, **kwargs)` in a daemon thread, and returns the (started)
Thread object. | 2.508306 | 2.663436 | 0.941755 |
event.clear()
attempted = 0
while attempted < attempts and not event.is_set():
yield attempted, event.is_set()
if event.wait(delay):
break
yield attempted, event.is_set() | def _retry(event, attempts, delay) | An iterator of pairs of (attempt number, event set), checking whether
`event` is set up to `attempts` number of times, and delaying `delay`
seconds in between.
Terminates as soon as `event` is set, or until `attempts` have been made.
Intended to be used in a loop, as in:
for num, ok in _retry... | 3.989927 | 4.444349 | 0.897753 |
with lock:
state_dict.clear()
event.clear()
yield
event.wait(timeout) | def _blocking(lock, state_dict, event, timeout=None) | A contextmanager that clears `state_dict` and `event`, yields, and waits
for the event to be set. Clearing an yielding are done within `lock`.
Used for blocking request/response semantics on the request side, as in:
with _blocking(lock, state, event):
send_request()
The response side ... | 5.468904 | 6.240737 | 0.876323 |
self._callbacks.setdefault(event, []).append(fn)
return fn | def register(self, event, fn) | Tell the object to run `fn` whenever a message of type `event` is
received. | 4.123458 | 4.66867 | 0.883219 |
self._queue.put((event, args, kwargs)) | def put(self, event, *args, **kwargs) | Schedule a callback for `event`, passing `args` and `kwargs` to each
registered callback handler. | 5.894354 | 5.828637 | 1.011275 |
while True:
msg = self._queue.get()
if msg is _SHUTDOWN:
break
event, args, kwargs = msg
self._logger('<< %s', event)
for func in self._callbacks.get(event, []):
func(*args, **kwargs) | def run(self) | Process all callbacks, until `stop()` is called. Intended to run in
its own thread. | 4.069118 | 4.012659 | 1.01407 |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(self._addr)
sock.settimeout(self._timeout)
with closing(sock):
while not self._shutdown.is_set():
try:
data, addr = sock.recvfrom(self._buffer_size)
... | def run(self) | Process all incoming packets, until `stop()` is called. Intended to run
in its own thread. | 2.845958 | 2.791764 | 1.019412 |
while True:
to_send = self._queue.get()
if to_send is _SHUTDOWN:
break
# If we get a gateway object, connect to it. Otherwise, assume
# it's a bytestring and send it out on the socket.
if isinstance(to_send, Gateway):
... | def run(self) | Process all outgoing packets, until `stop()` is called. Intended to run
in its own thread. | 3.657073 | 3.438492 | 1.063569 |
while True:
msg = self._queue.get()
if msg is _SHUTDOWN:
break
if self._enabled:
print msg | def run(self) | Process all log messages, until `stop()` is called. Intended to run
in its own thread. | 6.549848 | 5.468324 | 1.19778 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.