code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
route = self.routes.get(resource, Route(resource)) self.routes.update({resource: route}) return route
def route(self, resource)
route
4.143169
3.809316
1.087641
def _route(resource, handler, schema=None): route = self.routes.get(resource, Route(resource)) route.__getattribute__(method)(handler, schema) self.routes.update({resource: route}) return self return _route
def create_route_func(self, method)
create_route_func
5.250297
5.215235
1.006723
results = [] # match routes for resource, route in self.routes.items(): __message = message.match(route) if __message is None: continue route_result = route.dispatch(__message) if len(route_result) == 0: co...
def dispatch(self, message)
dispatch
4.256403
4.269925
0.996833
if not data_id: data_id = data_type # instantiate handlers for data type if they havent been yet if data_id not in _handlers: _handlers[data_id] = dict( [(h.handle, h) for h in handlers.instantiate_for_data_type(data_type, data_id=data_id)]) for handler in list(_handl...
def handle(data_type, data, data_id=None, caller=None)
execute all data handlers on the specified data according to data type Args: data_type (str): data type handle data (dict or list): data Kwargs: data_id (str): can be used to differentiate between different data sets of the same data type. If not specified will default to ...
3.453013
3.245849
1.063824
if query is None: return query query = self.update_reading_list(query) return query
def validate_query(self, query)
Confirm query exists given common filters.
9.556895
8.122631
1.176576
augment_query = self.validate_query(augment_query) # Given an invalid query, reach for a Sponsored query. if not augment_query: augment_query = self.validate_query(Content.search_objects.sponsored()) # Given an invalid Sponsored query, reach for a Video query. ...
def get_validated_augment_query(self, augment_query=None)
Common rules for reading list augmentation hierarchy. 1. Sponsored Content. 2. Video Content.
4.023298
3.699323
1.087577
primary_query = self.validate_query(primary_query) augment_query = self.get_validated_augment_query(augment_query=augment_query) try: # We use this for cases like recent where queries are vague. if reverse_negate: primary_query = primary_query.fi...
def augment_reading_list(self, primary_query, augment_query=None, reverse_negate=False)
Apply injected logic for slicing reading lists with additional content.
5.215054
4.96649
1.050048
# remove the current piece of content from the query. reading_list = reading_list.filter( ~es_filter.Ids(values=[self.id]) ) # remove excluded document types from the query. reading_list_config = getattr(settings, "READING_LIST_CONFIG", {}) excluded...
def update_reading_list(self, reading_list)
Generic behaviors for reading lists before being rendered.
4.234457
4.195857
1.0092
reading_list = None context = { "name": "", "content": reading_list, "targeting": {}, "videos": [] } if self.reading_list_identifier == "popular": reading_list = popular_content() context.update({"name": se...
def get_reading_list_context(self, **kwargs)
Returns the context dictionary for a given reading list.
2.983343
2.987611
0.998572
with open(path, encoding="utf-8") as file: file_contents = file.read() return cls.read(file_contents)
def read_file(cls, path)
Reads file at path and returns dict with separated frontmatter. See read() for more info on dict return value.
3.060919
2.482382
1.233057
fmatter = "" body = "" result = cls._regex.search(string) if result: fmatter = result.group(1) body = result.group(2) return { "attributes": yaml.load(fmatter), "body": body, "frontmatter": fmatter, }
def read(cls, string)
Returns dict with separated frontmatter from string. Returned dict keys: attributes -- extracted YAML attributes in dict form. body -- string contents below the YAML separators frontmatter -- string representation of YAML
4.984157
3.54769
1.404902
config["name"] = case timing_data = dict() model_dir = os.path.join(livvkit.model_dir, config['data_dir'], case) bench_dir = os.path.join(livvkit.bench_dir, config['data_dir'], case) plot_dir = os.path.join(livvkit.output_dir, "performance", "imgs") model_cases = functions.collect_cases(mod...
def run_suite(case, config, summary)
Run the full suite of performance tests
2.877419
2.854689
1.007962
model_timings = set(glob.glob(os.path.join(model_dir, "*" + config["timing_ext"]))) if bench_dir is not None: bench_timings = set(glob.glob(os.path.join(bench_dir, "*" + config["timing_ext"]))) else: bench_timings = set() if not len(model_timings): return dict() model_st...
def _analyze_case(model_dir, bench_dir, config)
Generates statistics from the timing summaries
2.22787
2.103187
1.059283
for case, case_data in summary.items(): for dof, data in case_data.items(): print(" " + case + " " + dof) print(" -------------------") for header, val in data.items(): print(" " + header + " : " + str(val)) print("")
def _print_result(case, summary)
Show some statistics from the run
3.378033
3.159747
1.069083
timing_var = config['scaling_var'] summary = LIVVDict() for size, res in result.items(): proc_counts = [] bench_times = [] model_times = [] for proc, data in res.items(): proc_counts.append(int(proc[1:])) try: bench_times.append(da...
def _summarize_result(result, config)
Trim out some data to return for the index page
3.623469
3.654967
0.991382
timing_result = dict() timing_summary = dict() for file in file_list: timing_result[file] = functions.parse_gptl(file, var_list) for var in var_list: var_time = [] for f, data in timing_result.items(): try: var_time.append(data[var]) e...
def generate_timing_stats(file_list, var_list)
Parse all of the timing files, and generate some statistics about the run. Args: file_list: A list of timing files to parse var_list: A list of variables to look for in the timing file Returns: A dict containing values that have the form: [mean, min, max, mean, standard...
2.325194
2.494791
0.93202
timing_data = dict() proc_counts = [] bench_means = [] bench_mins = [] bench_maxs = [] model_means = [] model_mins = [] model_maxs = [] for point in data_points: size = point[0] proc = point[1] try: model_data = timing_stats[size][proc]['model...
def weak_scaling(timing_stats, scaling_var, data_points)
Generate data for plotting weak scaling. The data points keep a constant amount of work per processor for each data point. Args: timing_stats: the result of the generate_timing_stats function scaling_var: the variable to select from the timing_stats dictionary (can be prov...
1.852111
1.541853
1.201224
proc_counts = timing_data['proc_counts'] if len(proc_counts) > 2: plt.figure(figsize=(10, 8), dpi=150) plt.title(title) plt.xlabel("Number of processors") plt.ylabel(ylabel) for case, case_color in zip(['bench', 'model'], ['#91bfdb', '#fc8d59']): case_da...
def generate_scaling_plot(timing_data, title, ylabel, description, plot_file)
Generate a scaling plot. Args: timing_data: data returned from a `*_scaling` method title: the title of the plot ylabel: the y-axis label of the plot description: a description of the plot plot_file: the file to write out to Returns: an image element containing ...
3.329801
3.327779
1.000608
# noinspection PyProtectedMember cmap_data = colormaps._viridis_data n_subplots = len(six.viewkeys(timing_stats)) fig, ax = plt.subplots(1, n_subplots+1, figsize=(3*(n_subplots+2), 5)) for plot_num, p_count in enumerate( sorted(six.iterkeys(timing_stats), key=functions.sort_processo...
def generate_timing_breakdown_plot(timing_stats, scaling_var, title, description, plot_file)
Description Args: timing_stats: a dictionary of the form {proc_count : {model||bench : { var : { stat : val }}}} scaling_var: the variable that accounts for the total runtime title: the title of the plot description: the description of the plot plot_file: the fil...
2.964441
2.821576
1.050633
# Get the id id = int(len(self.catalog)+1) # Check the coordinates ra = ra.to(q.deg) dec = dec.to(q.deg) datasets = 0 # Search the catalogs for this source for cat_name,params in self.catalogs.items(): self.Vizier_que...
def add_source(self, ra, dec, flag='', radius=10*q.arcsec)
Add a source to the catalog manually and find data in existing catalogs Parameters ---------- ra: astropy.units.quantity.Quantity The RA of the source dec: astropy.units.quantity.Quantity The Dec of the source flag: str A flag for the ...
4.557436
4.451382
1.023825
# Set the index self.catalog.set_index('id') # Exclude the unwanted source self.catalog = self.catalog[self.catalog.id!=id] # Remove the records from the catalogs for cat_name in self.catalogs: new_cat = getattr(self, cat_name)[getat...
def delete_source(self, id)
Delete a source from the catalog Parameters ---------- id: int The id of the source in the catalog
3.553632
3.571087
0.995112
# Check if the catalog is already ingested if not append and cat_name in self.catalogs: print('Catalog {} already ingested.'.format(cat_name)) else: if isinstance(data, str): cat_loc = cat_loc or data ...
def ingest_data(self, data, cat_name, id_col, ra_col='_RAJ2000', dec_col='_DEJ2000', cat_loc='', append=False, count=-1)
Ingest a data file and regroup sources Parameters ---------- data: str, pandas.DataFrame, astropy.table.Table The path to the exported VizieR data or the data table cat_name: str The name of the added catalog id_col: str The name of th...
2.878924
2.879872
0.999671
if self.n_sources==0: print('Please run group_sources() to create the catalog first.') else: if source_id>self.n_sources or source_id<1 or not isinstance(source_id, int): print('Please enter an integer between 1 and',self.n_sources) ...
def inventory(self, source_id)
Look at the inventory for a given source Parameters ---------- source_id: int The id of the source to inspect
3.56777
3.655589
0.975977
good = True # Make sure the attribute name is good if cat_name[0].isdigit(): print("No names beginning with numbers please!") good = False # Make sure catalog is unique if not append and cat_name in self.catalogs: ...
def _catalog_check(self, cat_name, append=False)
Check to see if the name of the ingested catalog is valid Parameters ---------- cat_name: str The name of the catalog in the Catalog object append: bool Append the catalog rather than replace Returns ------- bool ...
5.422347
5.956153
0.910377
# Verify the cat_name if self._catalog_check(cat_name): # Prep the current catalog as an astropy.QTable tab = at.Table.from_pandas(self.catalog) # Cone search Vizier print("Searching SDSS for sources within {} of ({}, {})...
def SDSS_spectra_query(self, cat_name, ra, dec, radius, group=True, **kwargs)
Use astroquery to search SDSS for sources within a search cone Parameters ---------- cat_name: str A name for the imported catalog (e.g. '2MASS') ra: astropy.units.quantity.Quantity The RA of the center of the cone search dec: astropy.units.quanti...
5.632663
5.430189
1.037287
# Verify the cat_name if self._catalog_check(cat_name, append=append): # Cone search Vizier print("Searching {} for sources within {} of ({}, {}). Please be patient...".format(viz_cat, radius, ra, dec)) crds = coord.SkyCoord(ra=ra, dec=dec, frame...
def Vizier_query(self, viz_cat, cat_name, ra, dec, radius, ra_col='RAJ2000', dec_col='DEJ2000', columns=["**"], append=False, group=True, **kwargs)
Use astroquery to search a catalog for sources within a search cone Parameters ---------- viz_cat: str The catalog string from Vizier (e.g. 'II/246' for 2MASS PSC) cat_name: str A name for the imported catalog (e.g. '2MASS') ra: astropy.units.quan...
3.626518
3.714523
0.976308
# Make sure sources have been grouped if self.catalog.empty: print('Please run group_sources() before cross matching.') return if self._catalog_check(cat_name): # Verify the cat_name viz_cat = "vizier:{}".format(v...
def Vizier_xmatch(self, viz_cat, cat_name, ra_col='_RAJ2000', dec_col='_DEJ2000', radius='', group=True)
Use astroquery to pull in and cross match a catalog with sources in self.catalog Parameters ---------- viz_cat: str The catalog string from Vizier (e.g. 'II/246' for 2MASS PSC) cat_name: str A name for the imported catalog (e.g. '2MASS') radius: a...
4.865795
4.937375
0.985503
if len(self.catalogs)==0: print("No catalogs to start grouping! Add one with the ingest_data() method first.") else: # Gather the catalogs print('Grouping sources from the following catalogs:',list(self.catalogs.keys())) ...
def group_sources(self, radius='', plot=False)
Calculate the centers of the point clusters given the radius and minimum number of points Parameters ---------- coords: array-like The list of (x,y) coordinates of all clicks radius: int The distance threshold in degrees for cluster membership ...
3.179644
3.230632
0.984217
# Delete the name and data self.catalogs.pop(cat_name) delattr(self, cat_name) # Update history print("Deleted {} catalog.".format(cat_name)) self.history += "\n{}: Deleted {} catalog.".format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), cat_na...
def drop_catalog(self, cat_name)
Remove an imported catalog from the Dataset object Parameters ---------- cat_name: str The name given to the catalog
3.492064
3.851239
0.906738
# Get the object DB = joblib.load(path) # Load the attributes self.catalog = DB.catalog self.n_sources = DB.n_sources self.name = DB.name self.history = DB.history del DB
def load(self, path)
Load the catalog from file Parameters ---------- path: str The path to the file
5.783292
6.028366
0.959347
# Must be grouped! if not self.xmatch_radius: print("Please run group_sources() before running correct_offsets().") else: # First, remove any previous catalog correction self.catalog.loc[self.catalog['cat_name']=...
def correct_offsets(self, cat_name, truth='ACS')
Function to determine systematic, linear offsets between catalogs FUTURE -- do this with TweakReg, which also accounts for rotation/scaling See thread at https://github.com/spacetelescope/drizzlepac/issues/77 Parameters ---------- cat_name: str Name ...
2.572549
2.607558
0.986574
if self._jinja_env is None: self._jinja_env = SandboxedEnvironment( extensions=[ 'jinja2.ext.autoescape', 'jinja2.ext.with_', ], autoescape=True, ) self._jinja_env.globals['url_for'] = url_for # Load whi...
def jinja_env(self)
Create a sandboxed Jinja environment.
2.99188
2.739141
1.09227
r return self.jinja_env.from_string(source).render(kwargs_context)
def render_template(self, source, **kwargs_context)
r"""Render a template string using sandboxed environment. :param source: A string containing the page source. :param \*\*kwargs_context: The context associated with the page. :returns: The rendered template.
6.900891
8.164614
0.84522
try: existing_handler = app.error_handler_spec[None][404][NotFound] except (KeyError, TypeError): existing_handler = None if existing_handler: app.error_handler_spec[None][404][NotFound] = \ lambda error: handle_not_found(error, wrapp...
def wrap_errorhandler(app)
Wrap error handler. :param app: The Flask application.
2.630139
2.702456
0.97324
self.init_config(app) self.wrap_errorhandler(app) app.extensions['invenio-pages'] = _InvenioPagesState(app) return app.extensions['invenio-pages']
def init_app(self, app)
Flask application initialization. :param app: The Flask application. :returns: The :class:`invenio_pages.ext.InvenioPages` instance initialized.
6.082259
5.201778
1.169265
def list_conferences_groups(self, group_id): path = {} data = {} params = {} # REQUIRED - PATH - group_id path["group_id"] = group_id self.logger.debug("GET /api/v1/groups/{group_id}/conferences with query params: {params} and form data: {dat...
List conferences. Retrieve the list of conferences for this context This API returns a JSON object containing the list of conferences, the key for the list of conferences is "conferences"
null
null
null
def retrieve_assignment_overridden_dates_for_quizzes(self, course_id, quiz_assignment_overrides_0_quiz_ids=None): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # OPTIONAL - quiz_assignment_overrid...
Retrieve assignment-overridden dates for quizzes. Retrieve the actual due-at, unlock-at, and available-at dates for quizzes based on the assignment overrides active for the current API user.
null
null
null
self._data = X self._classes = np.unique(y) self._labels = y self._is_fitted = True
def fit(self, X, y)
Fit the model using X as training data and y as target values
3.967991
4.420322
0.89767
# TODO: Make classification of multiple samples a bit more effective... if X.ndim > 1 and X.shape[1] != 1: out = [] for x in X: out += self.predict(x) return out X = X.flatten() if self.metric == 'minkowski': dists...
def predict(self, X)
Predict the class labels for the provided data Parameters ---------- X : array-like, shape (n_query, n_features). Test samples. Returns ------- y : array of shape [n_samples] Class labels for each data sample.
3.274491
3.397683
0.963742
lookup_result = overlay_url_for(endpoint, filename, **values) if lookup_result is not None: return lookup_result return url_for(endpoint, filename=filename, **values)
def replaced_url_for(endpoint, filename=None, **values)
This function acts as "replacement" for the default url_for() and intercepts if it is a request for bower assets If the file is not available in bower, the result is passed to flasks url_for(). This is useful - but not recommended - for "overlaying" the static directory (see README.rst).
3.739365
3.680953
1.015869
url = overlay_url_for(endpoint, **values) if url is None: exc_type, exc_value, tb = sys.exc_info() if exc_value is error: reraise(exc_type, exc_value, tb) else: raise error # url_for will use this result, instead of raising BuildError. return url
def handle_url_error(error, endpoint, values)
Intercept BuildErrors of url_for() using flasks build_error_handler API
5.001929
4.093061
1.222051
default_url_for_args = values.copy() if filename: default_url_for_args['filename'] = filename if endpoint == 'static' or endpoint.endswith('.static'): if os.path.sep in filename: filename_parts = filename.split(os.path.sep) component = filename_parts[0] ...
def overlay_url_for(endpoint, filename=None, **values)
Replace flasks url_for() function to allow usage without template changes If the requested endpoint is static or ending in .static, it tries to serve a bower asset, otherwise it will pass the arguments to flask.url_for() See http://flask.pocoo.org/docs/0.10/api/#flask.url_for
4.330171
4.336585
0.998521
root = current_app.config['BOWER_COMPONENTS_ROOT'] bower_data = None package_data = None # check if component exists in bower_components directory if not os.path.isdir(os.path.join(current_app.root_path, root, component)): # FallBack to default url_for flask return None # ...
def build_url(component, filename, **values)
search bower asset and build url :param component: bower component (package) :type component: str :param filename: filename in bower component - can contain directories (like dist/jquery.js) :type filename: str :param values: additional url parameters :type values: dict[str, str] :return: u...
2.274048
2.257418
1.007367
if api == ApiType.tcl: api_wrapper = IxnTclWrapper(logger, install_dir) elif api == ApiType.python: api_wrapper = IxnPythonWrapper(logger, install_dir) elif api == ApiType.rest: api_wrapper = IxnRestWrapper(logger) else: raise TgnError('{} API not supported - use Tc...
def init_ixn(api, logger, install_dir=None)
Create IXN object. :param api: tcl/python/rest :type api: trafficgenerator.tgn_utils.ApiType :param logger: logger object :param install_dir: IXN installation directory :return: IXN object
3.154864
2.712321
1.16316
if self.root.ref is not None: self.api.disconnect() self.root = None
def disconnect(self)
Disconnect from chassis and server.
10.778625
9.452158
1.140335
if force: for port in ports: port.release() for port, location in ports.items(): port.reserve(location, False, wait_for_up, timeout)
def reserve(self, ports, force=False, wait_for_up=True, timeout=80)
Reserve port and optionally wait for port to come up. :param ports: dict of <port, ip/module/port'>. :param force: whether to revoke existing reservation (True) or not (False). :param wait_for_up: True - wait for port to come up, False - return immediately. :param timeout: how long (sec...
4.290901
4.469234
0.960098
assert not self._timer, '%r is already started; to restart it, cancel it first' % self loop = evergreen.current.loop current = evergreen.current.task if self.seconds is None or self.seconds < 0: # "fake" timeout (never expires) self._timer = None ...
def start(self)
Schedule the timeout. This is called on construction, so it should not be called explicitly, unless the timer has been canceled.
5.636015
4.976953
1.132423
if not self.is_empty(): suffix_comment_buffer = [] if self._info_simulator is not None: suffix_comment_buffer.append(self._info_simulator) if self._info_reads_in_tuple: # todo: orientation (FF, FR, etc.) # orientation="...
def flush_read_tuple(self)
Flush the internal buffer of reads.
3.715556
3.684475
1.008436
assert type(bases) is str, "Wrong type of bases: '{}'".format(bases) assert type(qualities) is str, "Wrong type of qualities: '{}'".format(qualities) assert type(segments) is tuple or type(segments) is list if self.current_read_tuple_id != read_tuple_id: self.flush...
def add_read( self, read_tuple_id, bases, qualities, segments, )
Add a new read to the current buffer. If it is a new read tuple (detected from ID), the buffer will be flushed. Args: read_tuple_id (int): ID of the read tuple. bases (str): Sequence of bases. qualities (str): Sequence of FASTQ qualities. segments (list of rnftools.rnfformat.segment): List of segments co...
2.251038
2.198621
1.023841
category = BayesCategory(name) self.categories[name] = category return category
def add_category(self, name)
Adds a bayes category that we can later train :param name: name of the category :type name: str :return: the requested category :rtype: BayesCategory
5.74126
5.614989
1.022488
if line.startswith('Name'): return None if line.startswith('--------'): return None if line.startswith('TOTAL'): return None if '100%' in line: return False if line == '\n': return None if self._last_line_was_pr...
def line_is_interesting(self, line)
Return True, False, or None. True means always output, False means never output, None means output only if there are interesting lines.
4.889771
4.739477
1.031711
return cls(it.imap(lambda (source, target, sign): (source, target, {'sign': sign}), tuples))
def from_tuples(cls, tuples)
Creates a graph from an iterable of tuples describing edges like (source, target, sign) Parameters ---------- tuples : iterable[(str,str,int))] Tuples describing signed and directed edges Returns ------- caspo.core.graph.Graph Created object inst...
11.208282
7.578629
1.478933
df = pd.read_csv(path, delim_whitespace=True, names=['source', 'sign', 'target']).drop_duplicates() edges = [(source, target, {'sign': sign}) for _, source, sign, target in df.itertuples()] return cls(data=edges)
def read_sif(cls, path)
Creates a graph from a `simple interaction format (SIF)`_ file Parameters ---------- path : str Absolute path to a SIF file Returns ------- caspo.core.graph.Graph Created object instance .. _simple interaction format (SIF): http://wiki....
4.392917
4.604321
0.954086
preds = super(Graph, self).predecessors(node) if exclude_compressed: return [n for n in preds if not self.node[n].get('compressed', False)] else: return preds
def predecessors(self, node, exclude_compressed=True)
Returns the list of predecessors of a given node Parameters ---------- node : str The target node exclude_compressed : boolean If true, compressed nodes are excluded from the predecessors list Returns ------- list List of pre...
2.50936
3.225088
0.778075
succs = super(Graph, self).successors(node) if exclude_compressed: return [n for n in succs if not self.node[n].get('compressed', False)] else: return succs
def successors(self, node, exclude_compressed=True)
Returns the list of successors of a given node Parameters ---------- node : str The target node exclude_compressed : boolean If true, compressed nodes are excluded from the successors list Returns ------- list List of success...
2.491533
3.127864
0.79656
designated = set(setup.nodes) zipped = self.copy() marked = [(n, d) for n, d in self.nodes(data=True) if n not in designated and not d.get('compressed', False)] while marked: for node, _ in sorted(marked): backward = zipped.predecessors(node) ...
def compress(self, setup)
Returns the compressed graph according to the given experimental setup Parameters ---------- setup : :class:`caspo.core.setup.Setup` Experimental setup used to compress the graph Returns ------- caspo.core.graph.Graph Compressed graph
2.633909
2.692566
0.978215
for rnf_profile in rnf_profiles: self.prefix_width = max(self.prefix_width, rnf_profile.prefix_width) self.read_tuple_id_width = max(self.read_tuple_id_width, rnf_profile.read_tuple_id_width) self.genome_id_width = max(self.genome_id_width, rnf_profile.genome_id_wid...
def combine(*rnf_profiles)
Combine more profiles and set their maximal values. Args: *rnf_profiles (rnftools.rnfformat.RnfProfile): RNF profile.
2.025026
2.069322
0.978594
self.prefix_width = 0 self.read_tuple_id_width = 0 self.genome_id_width = 0 self.chr_id_width = 0 self.coor_width = 0 parts = read_tuple_name.split("__") self.prefix_width = len(parts[0]) self.read_tuple_id_width = len(parts[1]) segments...
def load(self, read_tuple_name)
Load RNF values from a read tuple name. Args: read_tuple_name (str): Read tuple name which the values are taken from.
2.200265
2.283486
0.963555
parts = read_tuple_name.split("__") parts[0] = self._fill_right(parts[0], "-", self.prefix_width) if read_tuple_id is not None: parts[1] = "{:x}".format(read_tuple_id) parts[1] = self._fill_left(parts[1], "0", self.read_tuple_id_width) if synchronize_widths:...
def apply(self, read_tuple_name, read_tuple_id=None, synchronize_widths=True)
Apply profile on a read tuple name and update read tuple ID. Args: read_tuple_name (str): Read tuple name to be updated. read_tuple_id (id): New read tuple ID. synchronize_widths (bool): Update widths (in accordance to this profile).
2.401541
2.494584
0.962702
parts = read_tuple_name.split("__") if len(parts[0]) != self.prefix_width or len(parts[1]) != self.read_tuple_id_width: return False segments = parts[2][1:-1].split("),(") for segment in segments: int_widths = list(map(len, segment.split(","))) ...
def check(self, read_tuple_name)
Check if the given read tuple name satisfies this profile. Args: read_tuple_name (str): Read tuple name.
3.200181
3.250072
0.984649
# Get complete table definition col_defs = self.get_table_definition(table).split('\n') # Return only column definitions return [i[0:-1].strip().replace(',', ', ') for i in col_defs if i.strip().startswith('`')]
def get_column_definition_all(self, table)
Retrieve the column definition statement for all columns in a table.
5.317658
5.276754
1.007752
# Parse column definitions for match for col in self.get_column_definition_all(table): if col.strip('`').startswith(column): return col.strip(',')
def get_column_definition(self, table, column)
Retrieve the column definition statement for a column from a table.
11.462329
10.644151
1.076866
# note that it's not necessary to temporarily install unpatched # versions of all patchable modules during the import of the # module; this is because none of them import each other, except # for threading which imports thread original_name = '__original_module_' + modname if original_name ...
def original(modname)
This returns an unpatched version of a module.
5.860497
5.656797
1.03601
accepted_args = set(('select', 'socket', 'time')) default_on = on.pop("all", None) for k in on.keys(): if k not in accepted_args: raise TypeError("patch() got an unexpected keyword argument %r" % k) if default_on is None: default_on = not (True in list(on.values())) ...
def patch(**on)
Globally patches certain system modules to be 'cooperaive'. The keyword arguments afford some control over which modules are patched. If no keyword arguments are supplied, all possible modules are patched. If keywords are set to True, only the specified modules are patched. E.g., ``monkey_patch(socket...
2.296333
2.113215
1.086654
patched_name = '__patched_module_' + module_name if patched_name in sys.modules: # returning already-patched module so as not to destroy existing # references to patched modules return sys.modules[patched_name] if not additional_modules: # supply some defaults a...
def inject(module_name, new_globals, *additional_modules)
Base method for "injecting" greened modules into an imported module. It imports the module specified in *module_name*, arranging things so that the already-imported modules in *additional_modules* are used when *module_name* makes its imports. *new_globals* is either None or a globals dictionary that ...
5.600737
5.70499
0.981726
if srckeys is None: srckeys = source.__all__ destination.update(dict([(name, getattr(source, name)) for name in srckeys if not (name.startswith('__') or name in ignore) ]))
def slurp_properties(source, destination, ignore=[], srckeys=None)
Copy properties from *source* (assumed to be a module) to *destination* (assumed to be a dict). *ignore* lists properties that should not be thusly copied. *srckeys* is a list of keys to copy, if the source's __all__ is untrustworthy.
3.110835
3.380172
0.920319
for modname in module_names: self._saved[modname] = sys.modules.get(modname, None)
def save(self, *module_names)
Saves the named modules to the object.
3.766908
3.417819
1.102138
try: for modname, mod in self._saved.items(): if mod is not None: sys.modules[modname] = mod else: try: del sys.modules[modname] except KeyError: pass ...
def restore(self)
Restores the modules that the saver knows about into sys.modules.
3.267429
2.699389
1.210432
if len(item_list) == 1: self[item_list[0]] = LIVVDict() elif len(item_list) > 1: if item_list[0] not in self: self[item_list[0]] = LIVVDict() self[item_list[0]].nested_insert(item_list[1:])
def nested_insert(self, item_list)
Create a series of nested LIVVDicts given a list
2.337661
1.602897
1.458398
if len(key_list) == 1: self[key_list[0]] = value elif len(key_list) > 1: if key_list[0] not in self: self[key_list[0]] = LIVVDict() self[key_list[0]].nested_assign(key_list[1:], value)
def nested_assign(self, key_list, value)
Set the value of nested LIVVDicts given a list
2.057789
1.505977
1.366415
# Only create order model instances for # those modules specified in settings. model_label = '.'.join([sender._meta.app_label, sender._meta.object_name]) labels = resolve_labels(model_label) order_field_names = is_orderable(model_label) if order_field_names: orderitem_set = getattr...
def post_save(sender, instance, created, **kwargs)
After save create order instance for sending instance for orderable models.
5.129614
4.662771
1.100122
components = [] for tag in parent.children: matched = parse_tag(tag) if matched: components.append(matched) elif hasattr(tag, 'contents'): components += parse_children(tag) return components
def parse_children(parent)
Recursively parse child tags until match is found
3.768427
3.243588
1.161808
file_handle = open(path, 'wb') file_handle.write(self._file_contents) file_handle.close()
def save(self, path)
Writes file to a particular location This won't work for cloud environments like Google's App Engine, use with caution ensure to catch exceptions so you can provide informed feedback. prestans does not mask File IO exceptions so your handler can respond better.
3.696543
3.266986
1.131484
def query_by_assignment(self, assignment_id, end_time=None, start_time=None): path = {} data = {} params = {} # REQUIRED - PATH - assignment_id path["assignment_id"] = assignment_id # OPTIONAL - start_time if start_time is ...
Query by assignment. List grade change events for a given assignment.
null
null
null
def query_by_student(self, student_id, end_time=None, start_time=None): path = {} data = {} params = {} # REQUIRED - PATH - student_id path["student_id"] = student_id # OPTIONAL - start_time if start_time is not None: ...
Query by student. List grade change events for a given student.
null
null
null
def query_by_grader(self, grader_id, end_time=None, start_time=None): path = {} data = {} params = {} # REQUIRED - PATH - grader_id path["grader_id"] = grader_id # OPTIONAL - start_time if start_time is not None: ...
Query by grader. List grade change events for a given grader.
null
null
null
if argv is None: argv = sys.argv[1:] usage = '\n\n\n'.join(__doc__.split('\n\n\n')[1:]) version = 'Nosey ' + __version__ # Parse options args = docopt(usage, argv=argv, version=version) # Execute return watch(args['<directory>'], args['--clear'])
def main(argv=None)
The entry point of the application.
4.800098
4.726371
1.015599
# ignore if binary response if isinstance(self._app_iter, BinaryResponse): self.logger.info("ignoring setting serializer for binary response") return for available_serializer in self._serializers: if available_serializer.content_type() == mime_type:...
def _set_serializer_by_mime_type(self, mime_type)
:param mime_type: :return: used by content_type_set to set get a reference to the appropriate serializer
4.048484
3.708729
1.09161
for new_serializer in serializers: if not isinstance(new_serializer, serializer.Base): msg = "registered serializer %s.%s does not inherit from prestans.serializer.Serializer" % ( new_serializer.__module__, new_serializer.__class__.__...
def register_serializers(self, serializers)
Adds extra serializers; generally registered during the handler lifecycle
4.0765
3.937655
1.035261
if not self.total: return False if not self.contributor.freelanceprofile.is_freelance: return False return True
def is_valid(self)
returns `True` if the report should be sent.
10.069316
9.077277
1.109288
if self._contributions is None: self._contributions = self.contributor.contributions.filter( content__published__gte=self.start, content__published__lt=self.end ) return self._contributions
def contributions(self)
Apply a datetime filter against the contributor's contribution queryset.
3.610065
2.818666
1.280771
if self._line_items is None: self._line_items = self.contributor.line_items.filter( payment_date__range=(self.start, self.end) ) return self._line_items
def line_items(self)
Apply a datetime filter against the contributors's line item queryset.
3.629796
2.483212
1.461735
if not self._deadline: self._deadline = self.now + timezone.timedelta(days=1) return self._deadline
def deadline(self)
Return next day as deadline if no deadline provided.
4.674087
3.230729
1.446759
ContributorReport( contributor, month=self.month, year=self.year, deadline=self._deadline, start=self._start, end=self._end ).send()
def send_contributor_email(self, contributor)
Send an EmailMessage object for a given contributor.
5.78476
5.620132
1.029293
# If the report configuration is not active we only send to the debugging user. for contributor in self.contributors: if contributor.email not in EMAIL_SETTINGS.get("EXCLUDED", []): self.send_contributor_email(contributor)
def send_mass_contributor_emails(self)
Send report email to all relevant contributors.
9.544995
7.677547
1.243235
return User.objects.filter( freelanceprofile__is_freelance=True ).filter( contributions__content__published__gte=self.start, contributions__content__published__lt=self.end ).distinct()
def get_contributors(self)
Return a list of contributors with contributions between the start/end dates.
5.328207
4.322279
1.232731
if not self._contributors: self._contributors = self.get_contributors() return self._contributors
def contributors(self)
Property to retrieve or access the list of contributors.
4.023757
3.23731
1.242932
self._strategies = [] clingo = gringo.Control(['-c maxsize=%s' % size]) clingo.conf.solve.models = '0' if configure: def overwrite(args, proxy): for i in xrange(args.threads): proxy.solver[i].no_lookback = 'false' ...
def control(self, size=0, configure=None)
Finds all inclusion-minimal intervention strategies up to the given size. Intervention strategies found are saved in the attribute :attr:`strategies` as a :class:`caspo.core.clamping.ClampingList` object instance. Example:: >>> from caspo import core, control >>> netwo...
5.733817
5.137454
1.116081
def open_url(self, url, stale_after, parse_as_html = True, **kwargs): _LOGGER.info('open_url() received url: %s', url) today = datetime.date.today() threshold_date = today - datetime.timedelta(stale_after) downloaded = False with self._get_conn() as conn: rs = conn.execute(''' select conte...
Download or retrieve from cache. url -- The URL to be downloaded, as a string. stale_after -- A network request for the url will be performed if the cached copy does not exist or if it exists but its age (in days) is larger or equal to the stale_after value. A non-positive value will force re-downloa...
null
null
null
def xpath_pick_one(self, xpaths): for xpathi, xpath in enumerate(xpaths): try: return self.xpath(xpath, [1, 1])[0] except UnexpectedContentException as e: if xpathi == len(xpaths) - 1: raise
Try each of the xpaths successively until a single element is found. If no xpath succeeds then raise the last UnexpectedContentException caught.
null
null
null
return Content.objects.get(id=obj.content.id).title
def get_content_title(self, obj)
Get content's title.
5.701058
4.250141
1.341381
dt = DATA_TYPES['date'] if type(self.data) is dt['type'] and '-' in str(self.data) and str(self.data).count('-') == 2: # Separate year, month and day date_split = str(self.data).split('-') y, m, d = date_split[0], date_split[1], date_split[2] # V...
def is_date(self)
Determine if a data record is of type DATE.
3.303776
3.199645
1.032544
dt = DATA_TYPES['time'] if type(self.data) is dt['type'] and ':' in str(self.data) and str(self.data).count(':') == 2: # Separate hour, month, second date_split = str(self.data).split(':') h, m, s = date_split[0], date_split[1], date_split[2] # V...
def is_time(self)
Determine if a data record is of type TIME.
3.637422
3.434693
1.059024
dt = DATA_TYPES['year'] if dt['min'] and dt['max']: if type(self.data) is dt['type'] and dt['min'] < self.data < dt['max']: self.type = 'year'.upper() self.len = None return True
def is_year(self)
Determine if a data record is of type YEAR.
5.744324
4.97122
1.155516
dt = DATA_TYPES[data_type] if isinstance(self.data, dt['type']): self.type = data_type.upper() self.len = None return True
def _is_date_data(self, data_type)
Private method for determining if a data record is of type DATE.
6.188732
5.444817
1.136628
if timeout is None: timeout = self._timeout with self._cond: self._enter() # Block while the barrier drains. index = self._count self._count += 1 try: if index + 1 == self._parties: # We release t...
def wait(self, timeout=None)
Wait for the barrier. When the specified number of threads have started waiting, they are all simultaneously awoken. If an 'action' was provided for the barrier, one of the threads will have executed that callback prior to returning. Returns an individual index number from 0 to 'parties...
5.448224
5.016817
1.085992
with self._cond: if self._count > 0: if self._state == 0: #reset the barrier, waking up threads self._state = -1 elif self._state == -2: #was broken, set it to reset state #which ...
def reset(self)
Reset the barrier to the initial state. Any threads currently waiting will get the BrokenBarrier exception raised.
6.010109
5.267946
1.140883
self.object = self.get_object() allow_anonymous = kwargs.get("allow_anonymous", False) # We only want to redirect is that setting is true, and we're not allowing anonymous users if self.redirect_correct_path and not allow_anonymous: # Also we obviously only want ...
def get(self, request, *args, **kwargs)
Override default get function to use token if there is one to retrieve object. If a subclass should use their own GET implementation, token_from_kwargs should be called if that detail view should be accessible via token.
3.869134
3.876839
0.998013
if not value: return (True, "") try: host,port = value.split(":") except ValueError as _: return (False, "value needs to be <host>:<port>") try: int(port) except ValueError as _: return (False, "port component of the host address needs to be a number") ...
def host(value)
Validates that the value is a valid network location
3.426248
3.617179
0.947215
def retrieve_all_quiz_reports(self, quiz_id, course_id, includes_all_versions=None): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # REQUIRED - PATH - quiz_id path["quiz_id"] = ...
Retrieve all quiz reports. Returns a list of all available reports.
null
null
null