code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
accents = list(filter(lambda accent: accent != Accent.NONE, map(get_accent_char, string))) return accents[-1] if accents else Accent.NONE
def get_accent_string(string)
Get the first accent from the right of a string.
4.817664
4.131996
1.165941
vowel = components[1] last_consonant = components[2] if accent == Accent.NONE: vowel = remove_accent_string(vowel) return [components[0], vowel, last_consonant] if vowel == "": return components #raw_string is a list, not a str object raw_string = remove_accent_stri...
def add_accent(components, accent)
Add accent to the given components. The parameter components is the result of function separate()
2.880828
2.861643
1.006704
if char == "": return "" case = char.isupper() char = char.lower() index = utils.VOWELS.find(char) if (index != -1): index = index - index % 6 + 5 char = utils.VOWELS[index - accent] return utils.change_case(char, case)
def add_accent_char(char, accent)
Add accent to a single char. Parameter accent is member of class Accent
4.546269
4.828185
0.94161
if index == -1: return string # Python can handle the case which index is out of range of given string return string[:index] + \ accent.accent.add_accent_char(string[index], accent) + \ string[index+1:]
def add_accent_at(string, accent, index)
Add mark to the index-th character of the given string. Return the new string after applying change. (unused)
6.629671
6.731386
0.984889
return utils.join([add_accent_char(c, Accent.NONE) for c in string])
def remove_accent_string(string)
Remove all accent from a whole string.
16.813503
16.200514
1.037838
usage =\ 'usage: %prog [options] input_sequences_filepath' version = 'Version: %prog ' + __version__ parser = OptionParser(usage=usage, version=version) parser.add_option('-o', '--output_fp', action='store', type='string', dest='output_fp', help='Path to store ' + ...
def parse_command_line_parameters(argv=None)
Parses command line arguments
2.866606
2.820347
1.016402
# Going to iterate through this twice in succession, best to force # evaluation now data = list(data) # RDP classifier doesn't preserve identifiers with spaces # Use lookup table seq_id_lookup = {} for seq_id, seq in parse_fasta(data): seq_id_lookup[seq_id.split()[0]] = seq_id ...
def assign_taxonomy( data, min_confidence=0.80, output_fp=None, training_data_fp=None, fixrank=True, max_memory=None, tmp_dir=tempfile.gettempdir())
Assign taxonomy to each sequence in data with the RDP classifier data: open fasta file object or list of fasta lines confidence: minimum support threshold to assign taxonomy to a sequence output_fp: path to write output; if not provided, result will be returned in a dict of {seq_id:(ta...
3.256969
3.115402
1.045441
app_kwargs = {} if tmp_dir is not None: app_kwargs['TmpDir'] = tmp_dir app = RdpTrainer(**app_kwargs) if max_memory is not None: app.Parameters['-Xmx'].on(max_memory) temp_taxonomy_file = tempfile.NamedTemporaryFile( prefix='RdpTaxonomy_', suffix='.txt', dir=tmp_dir) ...
def train_rdp_classifier( training_seqs_file, taxonomy_file, model_output_dir, max_memory=None, tmp_dir=tempfile.gettempdir())
Train RDP Classifier, saving to model_output_dir training_seqs_file, taxonomy_file: file-like objects used to train the RDP Classifier (see RdpTrainer documentation for format of training data) model_output_dir: directory in which to save the files necessary to clas...
2.6104
2.781934
0.93834
if model_output_dir is None: training_dir = tempfile.mkdtemp(prefix='RdpTrainer_', dir=tmp_dir) else: training_dir = model_output_dir training_results = train_rdp_classifier( training_seqs_file, taxonomy_file, training_dir, max_memory=max_memory, tmp_dir=tmp_dir) tr...
def train_rdp_classifier_and_assign_taxonomy( training_seqs_file, taxonomy_file, seqs_to_classify, min_confidence=0.80, model_output_dir=None, classification_output_fp=None, max_memory=None, tmp_dir=tempfile.gettempdir())
Train RDP Classifier and assign taxonomy in one fell swoop The file objects training_seqs_file and taxonomy_file are used to train the RDP Classifier (see RdpTrainer documentation for details). Model data is stored in model_output_dir. If model_output_dir is not provided, a temporary directory is cre...
3.856062
3.949111
0.976438
toks = line.strip().split('\t') seq_id = toks.pop(0) direction = toks.pop(0) if ((len(toks) % 3) != 0): raise ValueError( "Expected assignments in a repeating series of (rank, name, " "confidence), received %s" % toks) assignments = [] # Fancy way to create l...
def parse_rdp_assignment(line)
Returns a list of assigned taxa from an RDP classification line
5.583953
5.287798
1.056007
if not (os.path.exists('java') or which('java')): raise ApplicationNotFoundError( "Cannot find java runtime. Is it installed? Is it in your " "path?") jar_fp = self._get_jar_fp() if jar_fp is None: raise ApplicationNotFoundError( ...
def _error_on_missing_application(self, params)
Raise an ApplicationNotFoundError if the app is not accessible In this case, checks for the java runtime and the RDP jar file.
3.65629
3.030375
1.206547
# handles case where the jar file is in the current working directory if os.path.exists(self._command): return self._command # handles the case where the user has specified the location via # an environment variable elif 'RDP_JAR_PATH' in environ: ...
def _get_jar_fp(self)
Returns the full path to the JAR file. If the JAR file cannot be found in the current directory and the environment variable RDP_JAR_PATH is not set, returns None.
5.340556
4.148679
1.287291
cd_command = ''.join(['cd ', str(self.WorkingDir), ';']) jvm_command = "java" jvm_arguments = self._commandline_join( [self.Parameters[k] for k in self._jvm_parameters]) jar_arguments = '-jar "%s"' % self._get_jar_fp() rdp_arguments = self._commandline_join( ...
def _get_base_command(self)
Returns the base command plus command-line options. Does not include input file, output file, and training set.
4.328709
4.252244
1.017982
commands = filter(None, map(str, tokens)) return self._command_delimiter.join(commands).strip()
def _commandline_join(self, tokens)
Formats a list of tokens as a shell command This seems to be a repeated pattern; may be useful in superclass.
7.645688
7.08284
1.079466
assignment_fp = str(self.Parameters['-o'].Value).strip('"') if not os.path.isabs(assignment_fp): assignment_fp = os.path.relpath(assignment_fp, self.WorkingDir) return {'Assignments': ResultPath(assignment_fp, IsWritten=True)}
def _get_result_paths(self, data)
Return a dict of ResultPath objects representing all possible output
7.284994
5.528931
1.317613
cd_command = ''.join(['cd ', str(self.WorkingDir), ';']) jvm_command = "java" jvm_args = self._commandline_join( [self.Parameters[k] for k in self._jvm_parameters]) cp_args = '-cp "%s" %s' % (self._get_jar_fp(), self.TrainingClass) command_parts = [cd_comman...
def _get_base_command(self)
Returns the base command plus command-line options. Handles everything up to and including the classpath. The positional training parameters are added by the _input_handler_decorator method.
5.16269
4.677039
1.103837
model_dir = self.Parameters['model_output_dir'].Value absolute_model_dir = os.path.abspath(model_dir) return FilePath(absolute_model_dir)
def ModelDir(self)
Absolute FilePath to the training output directory.
5.284524
4.340837
1.217397
input_handler = getattr(self, self.__InputHandler) input_parts = [ self.Parameters['taxonomy_file'], input_handler(data), self.Parameters['training_set_id'], self.Parameters['taxonomy_version'], self.Parameters['modification_info'], ...
def _input_handler_decorator(self, data)
Adds positional parameters to selected input_handler's results.
7.785461
7.231151
1.076656
# Only include the properties file here. Add the other result # paths in the __call__ method, so we can catch errors if an # output file is not written. self._write_properties_file() properties_fp = os.path.join(self.ModelDir, self.PropertiesFile) result_paths = ...
def _get_result_paths(self, output_dir)
Return a dict of output files.
8.889609
8.093778
1.098326
# The properties file specifies the names of the files in the # training directory. We use the example properties file # directly from the rdp_classifier distribution, which lists # the default set of files created by the application. We # must write this file manually...
def _write_properties_file(self)
Write an RDP training properties file manually.
9.112023
8.440275
1.079588
host = Host(self.session, name=hostname) return host.delete()
def delete_old_host(self, hostname)
Remove all records for the host. :param str hostname: Hostname to remove :rtype: bool
6.200165
11.420095
0.542917
host = Host(self.session, name=hostname) if host.ipv4addrs: host.ipv4addrs = [] host.add_ipv4addr(ipv4addr) host.comment = comment return host.save()
def add_new_host(self, hostname, ipv4addr, comment=None)
Add or update a host in the infoblox, overwriting any IP address entries. :param str hostname: Hostname to add/set :param str ipv4addr: IP Address to add/set :param str comment: The comment for the record
3.222174
3.936664
0.818504
# Create Mafft app. app = Mafft(InputHandler='_input_as_path', params=params) # Turn on correct sequence type app.Parameters[MOLTYPE_MAP[moltype]].on() # Do not report progress app.Parameters['--quiet'].on() # More accurate alignment, sacrificing performance. if accurate: ...
def align_unaligned_seqs(seqs_fp, moltype=DNA, params=None, accurate=False)
Aligns unaligned sequences Parameters ---------- seqs_fp : string file path of the input fasta file moltype : {skbio.DNA, skbio.RNA, skbio.Protein} params : dict-like type It pass the additional parameter settings to the application. Default is None. accurate : boolean ...
9.229999
9.787478
0.943042
if params is None: params = {'--seed': aln_fp} else: params['--seed'] = aln_fp return align_unaligned_seqs(seqs_fp, moltype, params, accurate)
def add_seqs_to_alignment(seqs_fp, aln_fp, moltype=DNA, params=None, accurate=False)
Returns an Alignment object from seqs and existing Alignment. The "--seed" option can be used for adding unaligned sequences into a highly reliable alignment (seed) consisting of a small number of sequences. Parameters ---------- seqs_fp : string file path of the unaligned sequences ...
3.328245
3.219796
1.033682
# Create Mafft app. app = Mafft(InputHandler='_input_as_paths', params=params, SuppressStderr=False) app._command = 'mafft-profile' # Get results using int_map as input to app res = app([aln1_fp, aln2_fp]) return Alignment.read(res['StdOut'], constructor=m...
def align_two_alignments(aln1_fp, aln2_fp, moltype, params=None)
Returns an Alignment object from two existing Alignments. Parameters ---------- aln1_fp : string file path of 1st alignment aln2_fp : string file path of 2nd alignment params : dict of parameters to pass in to the Mafft app controller. Returns ------- The aligned se...
12.016181
11.33486
1.060108
lines = [] for i, s in enumerate(data): # will number the sequences 1,2,3,etc. lines.append(''.join(['>', str(i+1)])) lines.append(s) return self._input_as_lines(lines)
def _input_as_seqs(self, data)
Format a list of seq as input. Parameters ---------- data: list of strings Each string is a sequence to be aligned. Returns ------- A temp file name that contains the sequences. See Also -------- burrito.util.CommandLineApplication
4.868778
5.091825
0.956195
section = config[section_key][name] segmenter_class_path = section['class'] Segmenter = yamlconf.import_module(segmenter_class_path) return Segmenter.from_config(config, name, section_key=section_key)
def from_config(cls, config, name, section_key="segmenters")
Constructs a segmenter from a configuration doc.
3.381554
3.137443
1.077806
return escape.to_unicode(binascii.hexlify(os.urandom(length))[length:])
def random_hex(length)
Generates a random hex string
9.794003
9.944529
0.984863
password_salt = password_salt or oz.settings["session_salt"] salted_password = password_salt + password return "sha256!%s" % hashlib.sha256(salted_password.encode("utf-8")).hexdigest()
def password_hash(password, password_salt=None)
Hashes a specified password
3.893445
3.97207
0.980205
fa = func(a) if fa == 0.: return a fb = func(b) if fb == 0.: return b assert sign(fa) != sign(fb) for i in xrange(maxiter): c = (a + b) / 2. fc = func(c) if fc == 0. or abs(b - a) / 2. < xtol: return c if sign(fc) == sign(func(a...
def bisect(func, a, b, xtol=1e-12, maxiter=100)
Finds the root of `func` using the bisection method. Requirements ------------ - func must be continuous function that accepts a single number input and returns a single number - `func(a)` and `func(b)` must have opposite sign Parameters ---------- func : function the functio...
2.250121
2.532086
0.888643
''' Parses a foreign resource URL into the URL string itself and any relevant args and kwargs ''' matched_obj = SPLIT_URL_RE.match(s) if not matched_obj: raise URLParseException('Invalid Resource URL: "%s"' % s) url_string, arguments_string = matched_...
def parse_string(s)
Parses a foreign resource URL into the URL string itself and any relevant args and kwargs
3.51826
2.698695
1.303689
redis = oz.redis.create_connection() oz.bandit.add_experiment(redis, experiment)
def add_experiment(experiment)
Adds a new experiment
11.466957
12.072448
0.949845
redis = oz.redis.create_connection() oz.bandit.Experiment(redis, experiment).archive()
def archive_experiment(experiment)
Archives an experiment
14.520783
15.410249
0.942281
redis = oz.redis.create_connection() oz.bandit.Experiment(redis, experiment).add_choice(choice)
def add_experiment_choice(experiment, choice)
Adds an experiment choice
12.007925
12.003137
1.000399
redis = oz.redis.create_connection() oz.bandit.Experiment(redis, experiment).remove_choice(choice)
def remove_experiment_choice(experiment, choice)
Removes an experiment choice
11.683171
11.630999
1.004486
redis = oz.redis.create_connection() for experiment in oz.bandit.get_experiments(redis): experiment.compute_default_choice() csq, confident = experiment.confidence() print("%s:" % experiment.name) print("- creation date: %s" % experiment.metadata["creation_date"]) ...
def get_experiment_results()
Computes the results of all experiments, stores it in redis, and prints it out
4.432621
4.316081
1.027001
redis = oz.redis.create_connection() with open(filename, "r") as f: schema = escape.json_decode(f.read()) oz.bandit.sync_from_spec(redis, schema)
def sync_experiments_from_spec(filename)
Takes the path to a JSON file declaring experiment specifications, and modifies the experiments stored in redis to match the spec. A spec looks like this: { "experiment 1": ["choice 1", "choice 2", "choice 3"], "experiment 2": ["choice 1", "choice 2"] }
7.101751
6.469227
1.097774
''' Adds a new chapter to the report. :param str title: Title of the chapter. ''' chap_id = 'chap%s' % self.chap_counter self.chap_counter += 1 self.sidebar += '<a href="#%s" class="list-group-item">%s</a>\n' % ( chap_id, title) self.body += '...
def add_chapter(self, title)
Adds a new chapter to the report. :param str title: Title of the chapter.
2.916361
2.64942
1.100755
''' Adds an image to the last chapter/section. The image will be stored in the `{self.title}_files` directory. :param matplotlib.figure figure: A matplotlib figure to be saved into the report ''' name = os.path.join(self._dir, '/fig%s.png' % self.fig_counter)...
def add_image(self, figure, dpi=72)
Adds an image to the last chapter/section. The image will be stored in the `{self.title}_files` directory. :param matplotlib.figure figure: A matplotlib figure to be saved into the report
4.980441
2.364464
2.106372
''' Writes the report to a file. ''' path = self.title + '.html' value = self._template.format( title=self.title, body=self.body, sidebar=self.sidebar) write_file(path, value, force=force) plt.ion()
def write_report(self, force=False)
Writes the report to a file.
5.585674
5.161201
1.082243
if params is None: params = {} if moltype == DNA or moltype == RNA: params['-nt'] = True elif moltype == PROTEIN: params['-nt'] = False else: raise ValueError, \ "FastTree does not support moltype: %s" % moltype.label app = FastTree(params=param...
def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params=None)
Returns a tree from alignment Will check MolType of aln object
4.037031
4.057235
0.99502
db_cfg = {} cfg_dir = 'datasource' cfg_files = pkg_resources.resource_listdir('oceansdb', cfg_dir) cfg_files = [f for f in cfg_files if f[-5:] == '.json'] for src_cfg in cfg_files: text = pkg_resources.resource_string( 'oceansdb', os.path.join(cfg_dir, src_cfg)) ...
def dbsource(dbname, var, resolution=None, tscale=None)
Return which file(s) to use according to dbname, var, etc
2.928727
2.894547
1.011808
a, b = list(a), list(b) opcodes = SM(None, a, b).get_opcodes() return parse_opcodes(opcodes)
def diff(a, b)
Performs a longest common substring diff. :Parameters: a : sequence of `comparable` Initial sequence b : sequence of `comparable` Changed sequence :Returns: An `iterable` of operations.
6.516882
9.534562
0.683501
''' Main logic for HTTP endpoint. ''' response = singletons.server.response # Prep ForeignResource and ensure does not validate security settings singletons.settings foreign_res = ForeignResource(url_string) target_ts = TypeString(ts) target_resource = TypedResource(url_string, tar...
async def convert_endpoint(url_string, ts, is_just_checking)
Main logic for HTTP endpoint.
7.174781
6.747154
1.063379
''' Perform necessary substitutions on a command list to create a CLI-ready list to launch a conversion or download process via system binary. ''' replacements = { '$IN': in_path, '$OUT': out_path, } # Add in positional arguments ($0, $1, etc) for i, arg in enumerate(arg...
def apply_command_list_template(command_list, in_path, out_path, args)
Perform necessary substitutions on a command list to create a CLI-ready list to launch a conversion or download process via system binary.
6.495713
3.494176
1.859011
''' Given an absolute path to a local file, convert to a given to_type ''' # Now find path between types typed_foreign_res = TypedLocalResource(path) original_ts = typed_foreign_res.typestring conversion_path = singletons.converter_graph.find_path( original_ts, to_type) # print('...
async def convert_local(path, to_type)
Given an absolute path to a local file, convert to a given to_type
6.067441
5.455855
1.112097
''' Given a URL string that has already been downloaded, enqueue necessary conversion to get to target type ''' target_ts = TypeString(to_type) foreign_res = ForeignResource(url_string) # Determine the file type of the foreign resource typed_foreign_res = foreign_res.guess_typed() ...
def enqueue_conversion_path(url_string, to_type, enqueue_convert)
Given a URL string that has already been downloaded, enqueue necessary conversion to get to target type
5.35096
4.632563
1.155076
if os.path.exists(path): print("WARNING: Path '%s' already exists; skipping" % path) else: otherwise(path)
def check_path(path, otherwise)
Checks if a path exists. If it does, print a warning message; if not, execute the `otherwise` callback argument.
5.590261
3.590665
1.556887
with open(skeleton_path("config.py"), "r") as config_source: config_content = config_source.read() config_content = config_content.replace("__PROJECT_NAME__", project_name) with open(path, "w") as config_dest: config_dest.write(config_content)
def config_maker(project_name, path)
Creates a config file based on the project name
2.470238
2.556531
0.966246
return os.path.join(os.path.dirname(oz.__file__), "skeleton", parts)
def skeleton_path(parts)
Gets the path to a skeleton asset
7.052071
6.933137
1.017154
if not VALID_PROJECT_NAME.match(project_name): print("Invalid project name. It may only contain letters, numbers and underscores.", file=sys.stderr) return check_path(project_name, functools.partial(shutil.copytree, skeleton_path("plugin"))) check_path("static", os.mkdir) check_pa...
def init(project_name)
Creates a new project
4.499589
4.695065
0.958366
tornado.log.enable_pretty_logging() # Get and validate the server_type server_type = oz.settings["server_type"] if server_type not in [None, "wsgi", "asyncio", "twisted"]: raise Exception("Unknown server type: %s" % server_type) # Install the correct ioloop if necessary if server...
def server()
Runs the server
2.360329
2.355333
1.002121
try: import IPython except: print("ERROR: IPython is not installed. Please install it to use the repl.", file=sys.stderr) raise IPython.embed(user_ns=dict( settings=oz.settings, actions=oz._actions, uimodules=oz._uimodules, routes=oz._routes, ...
def repl()
Runs an IPython repl with some context
5.834526
5.434892
1.073531
''' Figure out path basename for given resource_url ''' scheme = resource_url.parsed.scheme if scheme in ('http', 'https', 'file'): return _get_basename_based_on_url(resource_url) elif scheme in ('git', 'git+https', 'git+http'): if len(resource_ur...
def find_resource_url_basename(self, resource_url)
Figure out path basename for given resource_url
5.141952
4.422564
1.162663
''' Given a resource_url, figure out what it would resolve into ''' resolvers = self.converters.values() for resolver in resolvers: # Not all resolvers are opinionated about destination types if not hasattr(resolver, 'get_destination_type'): ...
def find_destination_type(self, resource_url)
Given a resource_url, figure out what it would resolve into
4.180642
3.158813
1.323485
''' Download given Resource URL by finding path through graph and applying each step ''' resolver_path = self.find_path_from_url(resource_url) await self.apply_resolver_path(resource_url, resolver_path)
async def download(self, resource_url)
Download given Resource URL by finding path through graph and applying each step
12.309027
3.799318
3.239799
# convert aln to phy since seq_names need fixed to run through parsinsert new_aln=get_align_for_phylip(StringIO(aln)) # convert aln to fasta in case it is not already a fasta file aln2 = Alignment(new_aln) seqs = aln2.toFasta() parsinsert_app = ParsInsert(params=params) result = parsi...
def insert_sequences_into_tree(aln, moltype, params={})
Returns a tree from placement of sequences
10.136716
10.261359
0.987853
result = {} result['Tree'] = ResultPath(Path=splitext(self._input_filename)[0] + \ '.tree') return result
def _get_result_paths(self,data)
Get the resulting tree
17.557724
14.408658
1.218554
''' Download given resource_url ''' scheme = resource_url.parsed.scheme if scheme in ('http', 'https'): await download_http(resource_url) elif scheme in ('git', 'git+https', 'git+http'): await download_git(resource_url) else: raise ValueError('Unknown URL scheme: "%s"...
async def download(resource_url)
Download given resource_url
3.389871
3.027469
1.119705
if dir_name[0] == '/': dir_name = dir_name[1:len(dir_name)] self.url = "http://<Region>.file.myqcloud.com" + "/files/v2/<appid>/<bucket_name>/<dir_name>/" self.url = self.url.replace("<Region>", self.config.region).replace("<appid>", str(self.config.app_id)) self.url...
def create_folder(self, dir_name)
创建目录(https://www.qcloud.com/document/product/436/6061) :param dir_name:要创建的目录的目录的名称 :return 返回True创建成功,返回False创建失败
3.530062
3.348667
1.054169
if dir_name[0] == '/': dir_name = dir_name[1:len(dir_name)] self.url = 'http://<Region>.file.myqcloud.com/files/v2/<appid>/<bucket_name>/' self.url = self.url.replace("<Region>", self.config.region).replace("<appid>", str(self.config.app_id)).replace("<bucket_name>", self.co...
def list_folder(self, dir_name=None, prefix=None, num=1000, context=None)
列目录(https://www.qcloud.com/document/product/436/6062) :param dir_name:文件夹名称 :param prefix:前缀 :param num:查询的文件的数量,最大支持1000,默认查询数量为1000 :param context:翻页标志,将上次查询结果的context的字段传入,即可实现翻页的功能 :return 查询结果,为json格式
2.617751
2.56078
1.022248
if dir_name[0] == '/': dir_name = dir_name[1:len(dir_name)] self.url = 'http://' + self.config.region + '.file.myqcloud.com' + '/files/v2/' + str(self.config.app_id) + '/' + self.config.bucket + '/' + dir_name + '/?op=stat' self.headers['Authorization'] = CosAuth(self.config...
def query_folder(self, dir_name)
查询目录属性(https://www.qcloud.com/document/product/436/6063) :param dir_name:查询的目录的名称 :return:查询出来的结果,为json格式
3.658899
3.502807
1.044562
if dir_name is not None and dir_name[0] == '/': dir_name = dir_name[1:len(dir_name)] if dir_name is None: dir_name = "" self.url = 'http://' + self.config.region + '.file.myqcloud.com/files/v2/' + str(self.config.app_id) + '/' + self.config.bucket if dir...
def upload_file(self, real_file_path, file_name, dir_name=None)
简单上传文件(https://www.qcloud.com/document/product/436/6066) :param real_file_path: 文件的物理地址 :param file_name: 文件名称 :param dir_name: 文件夹名称(可选) :return:json数据串
2.791757
2.713664
1.028778
if dir_name is not None and dir_name[0] == '/': dir_name = dir_name[1:len(dir_name)] if dir_name is None: dir_name = "" self.url = 'http://' + self.config.region + '.file.myqcloud.com/files/v2/' + str( self.config.app_id) + '/' + self.config.bucket ...
def upload_slice_file(self, real_file_path, slice_size, file_name, offset=0, dir_name=None)
此分片上传代码由GitHub用户a270443177(https://github.com/a270443177)友情提供 :param real_file_path: :param slice_size: :param file_name: :param offset: :param dir_name: :return:
2.191593
2.183057
1.00391
real_file_name = str(int(time.time()*1000)) urllib.request.urlretrieve(url, real_file_name) data = self.upload_file(real_file_name, file_name, dir_name) os.remove(real_file_name) return data
def upload_file_from_url(self, url, file_name, dir_name=None)
简单上传文件(https://www.qcloud.com/document/product/436/6066) :param url: 文件url地址 :param file_name: 文件名称 :param dir_name: 文件夹名称(可选) :return:json数据串
2.401221
2.475358
0.97005
return self.app_sign(bucket, cos_path, expired)
def sign_more(self, bucket, cos_path, expired)
多次签名(针对上传文件,创建目录, 获取文件目录属性, 拉取目录列表) :param bucket: bucket名称 :param cos_path: 要操作的cos路径, 以'/'开始 :param expired: 签名过期时间, UNIX时间戳, 如想让签名在30秒后过期, 即可将expired设成当前时间加上30秒 :return: 签名字符串
6.039532
9.671966
0.624437
return self.app_sign(bucket, cos_path, expired, False)
def sign_download(self, bucket, cos_path, expired)
下载签名(用于获取后拼接成下载链接,下载私有bucket的文件) :param bucket: bucket名称 :param cos_path: 要下载的cos文件路径, 以'/'开始 :param expired: 签名过期时间, UNIX时间戳, 如想让签名在30秒后过期, 即可将expired设成当前时间加上30秒 :return: 签名字符串
6.913284
11.522728
0.599969
''' Returns an instance of ``IIIVZincBlendeStrained001``, which is a biaxial-strained III-V zinc blende binary alloy grown on a (001) surface. Parameters ---------- target : Alloy with ``a`` parameter or float Growth substrate, assumed to have...
def strained_001(self, target)
Returns an instance of ``IIIVZincBlendeStrained001``, which is a biaxial-strained III-V zinc blende binary alloy grown on a (001) surface. Parameters ---------- target : Alloy with ``a`` parameter or float Growth substrate, assumed to have a (001) surface, or...
9.845976
1.47455
6.677273
''' Returns the bandgap, Eg, in eV at a given temperature, T, in K (default=300.). ''' return min(self.Eg_Gamma(**kwargs), self.Eg_L(**kwargs), self.Eg_X(**kwargs))
def Eg(self, **kwargs)
Returns the bandgap, Eg, in eV at a given temperature, T, in K (default=300.).
9.302733
3.345397
2.780756
''' Returns the Kane remote-band parameter, `F`, calculated from `Eg_Gamma_0`, `Delta_SO`, `Ep`, and `meff_e_Gamma_0`. ''' Eg = self.Eg_Gamma_0(**kwargs) Delta_SO = self.Delta_SO(**kwargs) Ep = self.Ep(**kwargs) meff = self.meff_e_Gamma_0(**kwargs) ...
def F(self, **kwargs)
Returns the Kane remote-band parameter, `F`, calculated from `Eg_Gamma_0`, `Delta_SO`, `Ep`, and `meff_e_Gamma_0`.
7.646446
2.307881
3.313188
''' Returns the lattice parameter, a, in Angstroms at a given temperature, `T`, in Kelvin (default: 300 K). ''' T = kwargs.get('T', 300.) return (self.a_300K(**kwargs) + self.thermal_expansion(**kwargs) * (T - 300.))
def a(self, **kwargs)
Returns the lattice parameter, a, in Angstroms at a given temperature, `T`, in Kelvin (default: 300 K).
5.772675
2.801562
2.06052
''' Returns the split-off hole effective mass calculated from Eg_Gamma(T), Delta_SO, Ep and F. Interpolation of Eg_Gamma(T), Delta_SO, Ep and luttinger1, and then calculation of meff_SO is recommended for alloys. ''' Eg = self.Eg_Gamma(**kwargs) D...
def meff_SO(self, **kwargs)
Returns the split-off hole effective mass calculated from Eg_Gamma(T), Delta_SO, Ep and F. Interpolation of Eg_Gamma(T), Delta_SO, Ep and luttinger1, and then calculation of meff_SO is recommended for alloys.
9.106693
1.937501
4.700226
''' Returns the electron effective mass in the Gamma-valley calculated from Eg_Gamma(T), Delta_SO, Ep and F. Interpolation of Eg_Gamma(T), Delta_SO, Ep and F, and then calculation of meff_e_Gamma is recommended for alloys. ''' Eg = self.Eg_Gamma(**kwargs)...
def meff_e_Gamma(self, **kwargs)
Returns the electron effective mass in the Gamma-valley calculated from Eg_Gamma(T), Delta_SO, Ep and F. Interpolation of Eg_Gamma(T), Delta_SO, Ep and F, and then calculation of meff_e_Gamma is recommended for alloys.
6.426341
1.93717
3.317387
''' Returns the heavy-hole band effective mass in the [110] direction, meff_hh_110, in units of electron mass. ''' return 2. / (2 * self.luttinger1(**kwargs) - self.luttinger2(**kwargs) - 3 * self.luttinger3(**kwargs))
def meff_hh_110(self, **kwargs)
Returns the heavy-hole band effective mass in the [110] direction, meff_hh_110, in units of electron mass.
10.778972
4.373691
2.464503
''' Returns the light-hole band effective mass in the [110] direction, meff_lh_110, in units of electron mass. ''' return 2. / (2 * self.luttinger1(**kwargs) + self.luttinger2(**kwargs) + 3 * self.luttinger3(**kwargs))
def meff_lh_110(self, **kwargs)
Returns the light-hole band effective mass in the [110] direction, meff_lh_110, in units of electron mass.
10.584632
4.11703
2.570939
''' Returns the Kane band nonparabolicity parameter for the Gamma-valley. ''' Eg = self.Eg_Gamma(**kwargs) meff = self.meff_e_Gamma(**kwargs) T = kwargs.get('T', 300.) return k*T/Eg * (1 - meff)**2
def nonparabolicity(self, **kwargs)
Returns the Kane band nonparabolicity parameter for the Gamma-valley.
12.13786
5.252522
2.310863
dims, idx = cropIndices(self.dims, lat, lon) subset = {} for v in var: subset = {v: self.ncs[0][v][idx['yn'], idx['xn']]} return subset, dims
def crop(self, lat, lon, var)
Crop a subset of the dataset for each var Given doy, depth, lat and lon, it returns the smallest subset that still contains the requested coordinates inside it. It handels special cases like a region around greenwich and the international date line. Accep...
8.972349
11.163544
0.803719
subset, dims = self.crop(lat, lon, var) if np.all([y in dims['lat'] for y in lat]) & \ np.all([x in dims['lon'] for x in lon]): yn = np.nonzero([y in lat for y in dims['lat']])[0] xn = np.nonzero([x in lon for x in dims['lon']])[0] ...
def interpolate(self, lat, lon, var)
Interpolate each var on the coordinates requested
3.527144
3.484421
1.012261
''' Set up directed conversion graph, pruning unavailable converters as necessary ''' for converter in converter_list: if prune_converters: try: converter.configure() except ConverterUnavailable as e: ...
def _setup_converter_graph(self, converter_list, prune_converters)
Set up directed conversion graph, pruning unavailable converters as necessary
4.424517
3.315512
1.33449
''' Add given valid preferred conversion paths ''' for path in preferred_conversion_paths: for pair in pair_looper(path): if pair not in self.converters: log.warning('Invalid conversion path %s, unknown step %s' % ...
def _setup_preferred_paths(self, preferred_conversion_paths)
Add given valid preferred conversion paths
7.68646
6.204551
1.238842
''' Add given conversion profiles checking for invalid profiles ''' # Check for invalid profiles for key, path in conversion_profiles.items(): if isinstance(path, str): path = (path, ) for left, right in pair_looper(path): p...
def _setup_profiles(self, conversion_profiles)
Add given conversion profiles checking for invalid profiles
5.837576
4.650294
1.255313
''' Given a converter, set up the direct_output routes for conversions, which is used for transcoding between similar datatypes. ''' inputs = ( converter.direct_inputs if hasattr(converter, 'direct_inputs') else converter.inputs ) ...
def _setup_direct_converter(self, converter)
Given a converter, set up the direct_output routes for conversions, which is used for transcoding between similar datatypes.
6.373807
2.508702
2.540679
''' Given an input and output TypeString, produce a graph traversal, keeping in mind special options like Conversion Profiles, Preferred Paths, and Direct Conversions. ''' if in_.arguments: raise ValueError('Cannot originate path in argumented TypeString') ...
def find_path(self, in_, out)
Given an input and output TypeString, produce a graph traversal, keeping in mind special options like Conversion Profiles, Preferred Paths, and Direct Conversions.
6.586575
4.833444
1.362708
''' Like find_path, except forces the conversion profiles to be the given conversion profile setting. Useful for "temporarily overriding" the global conversion profiles with your own. ''' original_profiles = dict(self.conversion_profiles) self._setup_profiles(conv...
def find_path_with_profiles(self, conversion_profiles, in_, out)
Like find_path, except forces the conversion profiles to be the given conversion profile setting. Useful for "temporarily overriding" the global conversion profiles with your own.
5.776065
2.124857
2.718332
def get_lines(start, end): return [linecache.getline(filename, l).rstrip() for l in range(start, end)] lower_bound = max(1, lineno - context_lines) upper_bound = lineno + context_lines linecache.checkcache(filename) pre_context = get_lines(lower_bound, lineno) context_line = linec...
def get_lines_from_file(filename, lineno, context_lines)
Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context).
2.335789
2.111578
1.106182
frames = [] while tback is not None: if tback.tb_next is None and is_breakpoint: break filename = tback.tb_frame.f_code.co_filename function = tback.tb_frame.f_code.co_name context = tback.tb_frame.f_locals lineno = tback.tb_lineno - 1 tback_id...
def get_frames(tback, is_breakpoint)
Builds a list of ErrorFrame objects from a traceback
2.442578
2.2525
1.084385
try: return pprint.pformat(str(obj)) except UnicodeDecodeError as e: raise except Exception as e: return "[could not display: <%s: %s>]" % (e.__class__.__name__, str(e))
def prettify_object(obj)
Makes a pretty string for an object for nice output
4.402779
4.124832
1.067384
REPO_PREFIX = "djangodeployer-cache-" REPO_POSTFIX_UUID = str(uuid.uuid4()).split('-')[-1] REPO_CACHE_NAME = REPO_PREFIX + REPO_POSTFIX_UUID REPO_CACHE_LOCATION = '/tmp/%s' % REPO_CACHE_NAME repo = git.Repo.clone_from(repo_url, REPO_CACHE_LOCATION) return REPO_CACHE_LOCATION
def clone_git_repo(repo_url)
input: repo_url output: path of the cloned repository steps: 1. clone the repo 2. parse 'site' into for templating assumptions: repo_url = "git@github.com:littleq0903/django-deployer-template-openshift-experiment.git" repo_local_location = "/tmp/djangodeployer-cache-xxxx" # ...
3.088236
2.484285
1.243108
default_ignore_files = ['.gitignore'] default_ignore_folders = ['.git'] ignore_files += default_ignore_files ignore_folders += default_ignore_folders filelist = [] for root, folders, files in os.walk(repo_path): for ignore_file in ignore_files: if ignore_file in file...
def get_template_filelist(repo_path, ignore_files=[], ignore_folders=[])
input: local repo path output: path list of files which need to be rendered
1.668271
1.703915
0.979081
TEMPLATE_PROJECT_FOLDER_PLACEHOLDER_NAME = 'deployer_project' repo_path = repo_path.rstrip('/') to_path = to_path.rstrip('/') files_to_render = get_template_filelist(repo_path, ignore_folders=[TEMPLATE_PROJECT_FOLDER_PLACEHOLDER_NAME]) # rendering generic deploy files for single_file_pat...
def render_from_repo(repo_path, to_path, template_params, settings_dir)
rendering all files into the target directory
2.529879
2.455624
1.030239
logger = logging.getLogger(name) logger.setLevel(log_level) shandler: logging.StreamHandler = logging.StreamHandler(sys.stdout) fmt: str = '\033[1;32m%(levelname)-5s %(module)s:%(funcName)s():' fmt += '%(lineno)d %(asctime)s\033[0m| %(message)s' shandler.setFormatter(logging.Formatter(fmt))...
def gen_logger(name: str, log_level: int=logging.INFO) -> logging.Logger
Create a logger to be used between processes. :returns: Logging instance.
2.114751
2.238616
0.944669
ua_list: List[str] = ['Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36'] headers: Dict[str, str] = {'User-Agent': ua_list[random.randint(0, len(ua_list) - 1)]} return headers
def gen_headers() -> Dict[str, str]
Generate a header pairing.
1.846941
1.771252
1.042732
pattern: Pattern = re.compile(r'([\w.-]+@[\w.-]+)') hits: List[str] = pattern.findall(results) if fuzzy: seed = domain.split('.')[0] emails: List[str] = [x.lower() for x in hits if x.split('@')[1].__contains__(seed)] else: emails: List[str] = [x.lower() for x in hits if x.en...
def extract_emails(results: str, domain: str, fuzzy: bool) -> List[str]
Grab email addresses from raw text data.
2.58558
2.507459
1.031155
if ih == '_input_as_multiline_string': recs = FastaFinder(seqs.split('\n')) elif ih == '_input_as_string': recs = FastaFinder(open(seqs)) elif ih == '_input_as_seqs': recs = [['>'+str(i), s] for i, s in enumerate(seqs)] elif ih == '_input_as_lines': recs = FastaFinde...
def seqs_to_stream(seqs, ih)
Converts seqs into stream of FASTA records, depending on input handler. Each FASTA record will be a list of lines.
3.764661
3.382352
1.113031
# set num keep if blast_db: params["-d"] = blast_db if out_filename: params["-o"] = out_filename ih = input_handler or guess_input_handler(seqs, add_seq_names) blast_app = blast_constructor( params=params, blast_mat_root=blast_mat_root,...
def blast_seqs(seqs, blast_constructor, blast_db=None, blast_mat_root=None, params={}, add_seq_names=True, out_filename=None, WorkingDir=None, SuppressStderr=None, Sup...
Blast list of sequences. seqs: either file name or list of sequence objects or list of strings or single multiline string containing sequences. WARNING: DECISION RULES FOR INPUT HANDLING HAVE CHANGED. Decision rules for data are as follows. If it's s list, treat as lines, unless add_seq_names is t...
2.997221
3.139425
0.954704
if is_protein is None: params["-p"] = 'G' elif is_protein: params["-p"] = 'T' else: params["-p"] = 'F' if blast_db: params["-d"] = blast_db if out_filename: params["-o"] = out_filename # turn off duplicate accessions params["-a"] = "F" # ...
def fasta_cmd_get_seqs(acc_list, blast_db=None, is_protein=None, out_filename=None, params={}, WorkingDir=tempfile.gettempdir(), SuppressStderr=None, SuppressStdout=None)
Retrieve sequences for list of accessions
3.255448
3.267134
0.996423
fasta_cmd_res = fasta_cmd_get_seqs(acc_list, blast_db=blast_db, \ is_protein=is_protein) recs = FastaCmdFinder(fasta_cmd_res['StdOut']) result = {} for rec in recs: try: result[rec[0][1:].strip()] = ''.join(map(strip, rec[1:])) except IndexError: #maybe we didn'...
def seqs_from_fastacmd(acc_list, blast_db,is_protein=True)
Get dict of description:seq from fastacmd.
4.579432
4.418171
1.036499
if blast_db: params["-d"] = blast_db ih = input_handler or guess_input_handler(seqs, add_seq_names) recs = seqs_to_stream(seqs, ih) #checkpointing can only handle one seq... #set up the parameters for the core and additional runs max_iterations = params['-j'] params['-j'] = 2 #...
def psiblast_n_neighbors(seqs, n=100, blast_db=None, core_threshold=1e-50, extra_threshold=1e-10, lower_threshold=1e-6, step=100, method="two-step", blast_mat_root=None, ...
PsiBlasts sequences, stopping when n neighbors are reached. core_threshold: threshold for the core profile (default: 1e-50) extra_threshold: threshold for pulling in additional seqs (default:1e-10) lower_threshold: threshold for seqs in final round (default:1e-6) seqs: either file name or list of sequ...
4.550301
4.671235
0.974111
#first time through: reset 'h' and 'e' to core #-h is the e-value threshold for including seqs in the score matrix model app.Parameters['-h'].on(core_threshold) #-e is the e-value threshold for the final blast app.Parameters['-e'].on(core_threshold) checkpoints = [] ids = [] last_nu...
def ids_from_seq_two_step(seq, n, max_iterations, app, core_threshold, \ extra_threshold, lower_threshold, second_db=None)
Returns ids that match a seq, using a 2-tiered strategy. Optionally uses a second database for the second search.
3.410914
3.460774
0.985593
last_num_ids = None checkpoints = [] cp_name_base = make_unique_str() # cache ides for each iteration # store { iteration_num:(core_threshold, [list of matching ids]) } all_ids = {} try: i=0 while 1: #-h is the e-value threshold for inclusion in the score ma...
def ids_from_seq_lower_threshold(seq, n, max_iterations, app, core_threshold, \ lower_threshold, step=100)
Returns ids that match a seq, decreasing the sensitivity.
6.097102
6.064103
1.005442