code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if not format: format = request.POST.get('format', '') if not format: format = request.GET.get('format', '') if format == 'json' or format == '2': return _render_json(data, encrypted) else: return _render_xml(data, encrypted)
def _render(request, data, encrypted, format=None)
Render the data to Geckoboard. If the `format` parameter is passed to the widget it defines the output format. Otherwise the output format is based on the `format` request parameter. A `format` paramater of ``json`` or ``2`` renders JSON output, any other value renders XML.
2.296661
2.092803
1.097409
error_report = collections.defaultdict(list) output_report = collections.defaultdict(list) success_report = list() for runner_info in runner_results: hostname = runner_info['console'] error = runner_info['error'] output = runner_info['output'] if error:...
def print_report(runner_results)
Print collated report with output and errors if any
2.405784
2.283294
1.053646
self.ipmi_method(command="status") if self.output == "Chassis Power is off": command = "on" ipmi.execute(self.ipmi_map[command]) if ipmi.status: self.error = ipmi.error.strip() else: self.output = ipmi.output.strip...
def ipmi_method(self, command): ipmi = ipmitool(self.console, self.password, self.username) if command == "reboot"
Use ipmitool to run commands with ipmi protocol
5.231501
4.958145
1.055133
try: if self.command == "pxer": self.ipmi_method(command="pxe") if self.status == 0 or self.status == None: self.command = "reboot" else: return self.ipmi_method(self.com...
def run(self)
Start thread run here
5.965583
5.643675
1.057039
if 'name' in self._data: obj_ref = self.api.add(self.obj_parent(), self.obj_type(), name=self.obj_name()) else: obj_ref = self.api.add(self.obj_parent(), self.obj_type()) self.api.commit() return self.api.remapIds(obj_ref)
def _create(self)
Create new object on IxNetwork. :return: IXN object reference.
3.985552
3.218352
1.238383
values = [] for entry in args: values = values + list(entry.items()) return dict(values)
def merge(self, *args)
Merge multiple dictionary objects into one. :param variadic args: Multiple dictionary items :return dict
6.59288
7.553363
0.87284
lines = response.splitlines() result = [] pattern = re.compile('([A-Za-z]+):((.(?![A-Za-z]+:))*)') for line in lines: matches = pattern.findall(line) row = {} for match in matches: row[match[0]] = match[1].strip() ...
def parseLegacy(self, response)
Parse a legacy response and try and catch any errors. If we have multiple responses we wont catch any exceptions, we will return the errors row by row :param dict response: The response string returned from request() :return Returns a dictionary or a list (list for multiple responses)
3.6408
3.372746
1.079477
body = json.loads(response) try: error = body['error']['description'] code = body['error']['code'] except Exception: return body['data'] else: raise ClickatellError(error, code);
def parseRest(self, response)
Parse a REST response. If the response contains an error field, we will raise it as an exception.
5.158398
4.850969
1.063375
url = ('https' if self.secure else 'http') + '://' + self.endpoint url = url + '/' + action # Set the User-Agent userAgent = "".join(["ClickatellPython/0.1.2", " ", "Python/", platform.python_version()]) headers = self.merge({ "User-Agent": userAgent }, headers) ...
def request(self, action, data={}, headers={}, method='GET')
Run the HTTP request against the Clickatell API :param str action: The API action :param dict data: The request parameters :param dict headers: The request headers (if any) :param str method: The HTTP method :return: The request response
4.324852
4.310318
1.003372
serialized_ops = [] for operation in operations: serializer = self.get_serializer_class(operation.__class__) serialized_ops.append(serializer(operation).data) return serialized_ops
def serialize_operations(self, operations)
Serialize a list of operations into JSON.
2.962118
2.929375
1.011177
# attempt to get given pzone try: pzone = PZone.objects.get(pk=pzone_pk) except PZone.DoesNotExist: raise Http404("Cannot find given pzone.") # bulid filters filters = {"pzone": pzone} if "from" in request.GET: parsed = date...
def get(self, request, pzone_pk)
Get all the operations for a given pzone.
2.57945
2.363569
1.091337
# attempt to get given content list pzone = None try: pzone = PZone.objects.get(pk=pzone_pk) except PZone.DoesNotExist: raise Http404("Cannot find given pzone.") json_obj = [] http_status = 500 json_op = json.loads(request.body....
def post(self, request, pzone_pk)
Add a new operation to the given pzone, return json of the new operation.
3.195802
3.092881
1.033277
# note : we're not using the pzone_pk here since it's not actually # necessary for getting an operation by pk, but it sure makes the urls # nicer! # attempt to delete operation try: operation = PZoneOperation.objects.get(pk=operation_pk) except ...
def delete(self, request, pzone_pk, operation_pk)
Remove an operation from the given pzone.
5.346258
5.110968
1.046036
instance = serializer.save() # create history object instance.history.create(data=instance.data)
def perform_update(self, serializer)
creates a record in the `bulbs.promotion.PZoneHistory` :param obj: the instance saved :param created: boolean expressing if the object was newly created (`False` if updated)
9.024358
9.660233
0.934176
when_param = get_query_params(self.request).get("preview", None) pk = self.kwargs["pk"] when = None if when_param: try: when = parse_date(when_param) except ValueError: # invalid format, set back to None w...
def retrieve(self, request, *args, **kwargs)
Retrieve pzone as a preview or applied if no preview is provided.
4.718653
3.625281
1.301596
self.designs = [] args = ['-c maxstimuli=%s' % max_stimuli, '-c maxinhibitors=%s' % max_inhibitors, '-Wno-atom-undefined'] clingo = gringo.Control(args) clingo.conf.solve.opt_mode = 'optN' if configure is not None: configure(clingo.conf) clingo.add...
def design(self, max_stimuli=-1, max_inhibitors=-1, max_experiments=10, relax=False, configure=None)
Finds all optimal experimental designs using up to :attr:`max_experiments` experiments, such that each experiment has up to :attr:`max_stimuli` stimuli and :attr:`max_inhibitors` inhibitors. Each optimal experimental design is appended in the attribute :attr:`designs` as an instance of :class:`caspo.cor...
4.623695
4.650438
0.994249
try: return _tls.loop except AttributeError: # create loop only for main thread if threading.current_thread().name == 'MainThread': _tls.loop = cls() return _tls.loop raise RuntimeError('there is no event loop creat...
def current(cls)
Get the current event loop singleton object.
5.850574
4.4509
1.31447
def search_account_domains(self, domain=None, latitude=None, longitude=None, name=None): path = {} data = {} params = {} # OPTIONAL - name if name is not None: params["name"] = name # OPTIONAL - domain if domai...
Search account domains. Returns a list of up to 5 matching account domains Partial match on name / domain are supported
null
null
null
'''Set the volume. Sets the volume to a given percentage (integer between 0 and 100). Args: percentage (int): The percentage (as a 0 to 100 integer) to set the volume to. Raises: ValueError: if the percentage is >100 or <0. ''' if percentage > 100 or percentage < 0: raise ValueError('percentage must b...
def set_volume(percentage)
Set the volume. Sets the volume to a given percentage (integer between 0 and 100). Args: percentage (int): The percentage (as a 0 to 100 integer) to set the volume to. Raises: ValueError: if the percentage is >100 or <0.
3.32049
2.649897
1.253064
'''Get the volume. Get the current volume. Returns: int: The current volume (percentage, between 0 and 100). ''' if system.get_name() == 'windows': # TODO: Implement volume for Windows. Looks like WinAPI is the # solution... pass elif system.get_name() == 'mac': volume = system.get_cmd_out( ['os...
def get_volume()
Get the volume. Get the current volume. Returns: int: The current volume (percentage, between 0 and 100).
4.706821
4.132591
1.138952
'''Increase the volume. Increase the volume by a given percentage. Args: percentage (int): The percentage (as an integer between 0 and 100) to increase the volume by. Raises: ValueError: if the percentage is >100 or <0. ''' if percentage > 100 or percentage < 0: raise ValueError('percentage must be an...
def increase_volume(percentage)
Increase the volume. Increase the volume by a given percentage. Args: percentage (int): The percentage (as an integer between 0 and 100) to increase the volume by. Raises: ValueError: if the percentage is >100 or <0.
3.675446
3.186041
1.153609
'''Mute the volume. Mutes the volume. ''' # NOTE: mute != 0 volume if system.get_name() == 'windows': # TODO: Implement volume for Windows. Looks like WinAPI is the # solution... pass elif system.get_name() == 'mac': sp.Popen(['osascript', '-e', 'set volume output muted true']).wait() else: # Linu...
def mute()
Mute the volume. Mutes the volume.
5.094919
5.113865
0.996295
'''Unmute the volume. Unmutes the system volume. Note: On some systems, volume is restored to its previous level after unmute, or set to 100. ''' if system.get_name() == 'windows': # TODO: Implement volume for Windows. Looks like WinAPI is the # solution... pass elif system.get_name() == 'mac': sp....
def unmute()
Unmute the volume. Unmutes the system volume. Note: On some systems, volume is restored to its previous level after unmute, or set to 100.
5.126104
3.783494
1.35486
acceptable_offers = self.request.accept.acceptable_offers(self.response.supported_mime_types) if len(acceptable_offers) > 0: best_accept_match = acceptable_offers[0][0] else: best_accept_match = self.response.default_serializer.content_type() # best_acce...
def _setup_serializers(self)
Auto set the return serializer based on Accept headers http://docs.webob.org/en/latest/reference.html#header-getters Intersection of requested types and supported types tells us if we can in fact respond in one of the request formats
3.746043
3.471753
1.079006
"Write your forwards methods here." rows = db.execute("select distinct feature_type from content_content") for row in rows: feature_type = row[0] try: ft = orm.FeatureType.objects.get(slug=slugify(feature_type)) except orm.FeatureType.DoesNotE...
def forwards(self, orm)
Write your forwards methods here.
3.060215
2.827955
1.08213
def query_by_login(self, login_id, end_time=None, start_time=None): path = {} data = {} params = {} # REQUIRED - PATH - login_id path["login_id"] = login_id # OPTIONAL - start_time if start_time is not None: pa...
Query by login. List authentication events for a given login.
null
null
null
def query_by_account(self, account_id, end_time=None, start_time=None): path = {} data = {} params = {} # REQUIRED - PATH - account_id path["account_id"] = account_id # OPTIONAL - start_time if start_time is not None: ...
Query by account. List authentication events for a given account.
null
null
null
def query_by_user(self, user_id, end_time=None, start_time=None): path = {} data = {} params = {} # REQUIRED - PATH - user_id path["user_id"] = user_id # OPTIONAL - start_time if start_time is not None: params[...
Query by user. List authentication events for a given user.
null
null
null
if name: if type_filter and self._key_attr == 'type': if name in type_filter and name in self: yield name, self[name] elif name in self: yield name, self[name] elif type_filter and self._key_attr == 'type': ...
def _items(self, type_filter=None, name=None)
Args: type_filter(list): Optional iterable of types to return (GroupDict only) name(str): Only return key by this name Alternative generator for items() method
2.40024
2.288232
1.04895
plugins = DictWithDotNotation() filtered_name = kwargs.get(self._key_attr, None) for key, val in self._items(type_filter, filtered_name): plugin_blacklist = None skip = False if blacklist: # Assume blacklist is correct format since...
def _filter(self, blacklist=None, newest_only=False, type_filter=None, **kwargs)
Args: blacklist(tuple): Iterable of of BlacklistEntry objects newest_only(bool): Only the newest version of each plugin is returned type(str): Plugin type to retrieve name(str): Plugin name to retrieve version(str): Plugin version to retrieve Returns ...
5.067116
4.958929
1.021817
try: keys = self._cache['sorted_keys'] except KeyError: keys = self._cache['sorted_keys'] = sorted(self.keys(), key=parse_version) return keys
def _sorted_keys(self)
Return list of keys sorted by version Sorting is done based on :py:func:`pkg_resources.parse_version`
4.398287
2.841339
1.547963
# Assume blacklist is correct format since it is checked by PluginLoader blacklist_cache = {} blacklist_cache_old = self._cache.get('blacklist', {}) for entry in blacklist: blackkey = (entry.version, entry.operator) if blackkey in blacklist_cache: ...
def _process_blacklist(self, blacklist)
Process blacklist into set of excluded versions
4.074482
3.66222
1.112572
version = kwargs.get('version', None) rtn = None if self: # Dict is not empty if blacklist: blacklist = self._process_blacklist(blacklist) if version: if version not in blacklist: rtn = self.ge...
def _filter(self, blacklist=None, newest_only=False, **kwargs)
Args: blacklist(tuple): Iterable of of BlacklistEntry objects newest_only(bool): Only the newest version of each plugin is returned version(str): Specific version to retrieve Returns dictionary of plugins If a blacklist is supplied, plugins are evaluated against the...
2.966293
3.088371
0.960472
for i, item in enumerate(items): if pred(item): return i
def find(pred, items)
Find the index of the first element in items for which pred returns True >>> find(lambda x: x > 3, range(100)) 4 >>> find(lambda x: x < -3, range(100)) is None True
2.62463
3.476464
0.754971
def nonzero(x): return x != 0 version_len = 3 # strict versions are always a tuple of 3 significant_pos = rfind(nonzero, significant_version.version) significant_pos = version_len + significant_pos + 1 self.version = ( self.version[:significant_pos] + (0,) * (version_len - significant_pos))
def reset_less_significant(self, significant_version)
Reset to zero all version info less significant than the indicated version. >>> ver = SummableVersion('3.1.2') >>> ver.reset_less_significant(SummableVersion('0.1')) >>> str(ver) '3.1'
5.374691
5.570743
0.964807
def combine(subver, ver): return subver / 10 + ver return reduce(combine, reversed(self.version))
def as_number(self)
>>> round(SummableVersion('1.9.3').as_number(), 12) 1.93
11.218371
9.816299
1.142831
tags = list(self.get_tags()) if 'tip' in tags and not self.is_modified(): tags = self.get_parent_tags('tip') versions = self.__versions_from_tags(tags) return self.__best_version(versions)
def get_tagged_version(self)
Get the version of the local working set as a StrictVersion or None if no viable tag exists. If the local working set is itself the tagged commit and the tip and there are no local modifications, use the tag on the parent changeset.
5.209699
3.689521
1.412026
ver = ( self.get_tagged_version() or str(self.get_next_version(increment)) + '.dev0' ) return str(ver)
def get_current_version(self, increment=None)
Return as a string the version of the current state of the repository -- a tagged version, if present, or the next version based on prior tagged releases.
5.782166
5.40768
1.069251
increment = increment or self.increment return self.infer_next_version(self.get_latest_version(), increment)
def get_next_version(self, increment=None)
Return the next version based on prior tagged releases.
5.154465
4.481124
1.150262
if last_version is None: return increment last_version = SummableVersion(str(last_version)) if last_version.prerelease: last_version.prerelease = None return str(last_version) increment = SummableVersion(increment) sum = last_version + increment sum.reset_less_significant(increment) return sum
def infer_next_version(last_version, increment)
Given a simple application version (as a StrictVersion), and an increment (1.0, 0.1, or 0.0.1), guess the next version. Set up a shorthand for examples >>> def VM_infer(*params): ... return str(VersionManagement.infer_next_version(*params)) >>> VM_infer('3.2', '0.0.1') '3.2.1' >>> VM_infer(StrictVe...
4.207927
3.9453
1.066567
def create_global_notification(self, account_id, account_notification_end_at, account_notification_subject, account_notification_message, account_notification_start_at, account_notification_icon=None, account_notification_roles=None): path = {} data = {} params = {} # REQ...
Create a global notification. Create and return a new global notification for an account.
null
null
null
# try and get the adapter and the REST class for the persistent object if target_rest_class is None: adapter_instance = registry.get_adapter_for_persistent_model(persistent_object) else: if inspect.isclass(target_rest_class): target_rest_class = target_rest_class() ...
def adapt_persistent_instance(persistent_object, target_rest_class=None, attribute_filter=None)
Adapts a single persistent instance to a REST model; at present this is a common method for all persistent backends. Refer to: https://groups.google.com/forum/#!topic/prestans-discuss/dO1yx8f60as for discussion on this feature
3.073073
3.114818
0.986598
# convert filter to immutable if it isn't already if isinstance(attribute_filter, parser.AttributeFilter): attribute_filter = attribute_filter.as_immutable() rest_model_instance = self.rest_model_class() for attribute_key in rest_model_instance.get_attribute_keys()...
def adapt_persistent_to_rest(self, persistent_object, attribute_filter=None)
adapts a persistent model to a rest model by inspecting
2.756396
2.76118
0.998267
self.register_adapter(ModelAdapter( rest_model_class=rest_model_class, persistent_model_class=persistent_model_class ))
def register_persistent_rest_pair(self, persistent_model_class, rest_model_class)
:param persistent_model_class: :param rest_model_class:
3.711958
3.327995
1.115374
persistent_signature = self.generate_signature(persistent_model) if persistent_signature in self._persistent_map: sub_map = self._persistent_map[persistent_signature] # return the first match if REST model was not specified if rest_model is None: ...
def get_adapter_for_persistent_model(self, persistent_model, rest_model=None)
:param persistent_model: instance of persistent model :param rest_model: specific REST model :return: the matching model adapter :rtype: ModelAdapter
3.388256
3.508126
0.965831
class_signature = self.generate_signature(rest_model) if class_signature not in self._rest_map: raise TypeError("No registered Data Adapter for class %s" % class_signature) return self._rest_map[class_signature]
def get_adapter_for_rest_model(self, rest_model)
:param rest_model: instance of REST model :return: the matching model adapter :rtype: ModelAdapter
4.96063
4.976496
0.996812
limit = kwargs.get("limit", DEFAULT_LIMIT) popular_ids = get_popular_ids(limit=limit) if not popular_ids: # Return most recent content return Content.search_objects.search().extra(size=limit) return Content.search_objects.search().filter(es_filter.Ids(values=popular_ids))
def popular_content(**kwargs)
Use the get_popular_ids() to retrieve trending content objects. Return recent content on failure.
6.529634
5.812991
1.123283
# Check document language and dispatch to correct core url = _get_url(core_url, "update") try: response = self.req_session.post(url, data=json_command, headers={'Content-Type': 'application/json'}) response.raise_for_status() except requests.RequestExcep...
def _send_solr_command(self, core_url, json_command)
Sends JSON string to Solr instance
3.5606
3.517672
1.012204
if not isinstance(documents, list): documents = [documents] documents = [{'doc': d} for d in documents] if boost: for d in documents: d['boost'] = boost self._add_batch.extend(documents) if len(self._add_batch) > SOLR_ADD_BATCH:...
def add(self, documents, boost=None)
Adds documents to Solr index documents - Single item or list of items to add
3.788566
3.469277
1.092033
if len(self._add_batch) > 0: language_batches = {} # Create command JSONs for each of language endpoints for lang in self.endpoints: # Append documents with languages without endpoint to default endpoint document_jsons = ["\"add\":" +...
def _addFlushBatch(self)
Sends all waiting documents to Solr
6.143721
5.666778
1.084165
for core in self.endpoints: self._send_solr_command(self.endpoints[core], "{\"delete\": { \"query\" : \"*:*\"}}")
def deleteAll(self)
Deletes whole Solr index. Use with care.
12.64561
7.681753
1.646188
for core in self.endpoints: self._send_solr_command(self.endpoints[core], "{\"delete\" : { \"id\" : \"%s\"}}" % (id,))
def delete(self, id)
Deletes document with ID on all Solr cores
11.665194
6.747998
1.72869
self._addFlushBatch() for core in self.endpoints: self._send_solr_command(self.endpoints[core], "{ \"commit\":{} }")
def commit(self)
Flushes all pending changes and commits Solr changes
23.872282
14.724545
1.621258
if self._shards is None: endpoints = [] for endpoint in self.endpoints: # We need to remove and http:// prefixes from URLs url = urlparse.urlparse(self.endpoints[endpoint]) endpoints.append("/".join([url.netloc, url.path])) ...
def _get_shards(self)
Returns comma separated list of configured Solr cores
4.413156
3.755901
1.174993
dict_response = results.get("response") result_obj = SolrResults() result_obj.query_time = results.get("responseHeader").get("QTime", None) result_obj.results_count = dict_response.get("numFound", 0) result_obj.start_index = dict_response.get("start", 0) for do...
def _parse_response(self, results)
Parses result dictionary into a SolrResults object
2.723812
2.606707
1.044925
if not columns: columns = ["*", "score"] fields = {"q": query, "json.nl" :"map", # Return facets as JSON objects "fl": ",".join(columns), # Return score along with results "start": str(start), "rows":...
def query(self, query, filters=None, columns=None, sort=None, start=0, rows=30)
Queries Solr and returns results query - Text query to search for filters - dictionary of filters to apply when searching in form of { "field":"filter_value" } columns - columns to return, list of strings sort - list of fields to sort on in format of ["field asc", "field desc", ... ] ...
3.861542
3.798173
1.016684
if isinstance(fields, basestring): mlt_fields = fields else: mlt_fields = ",".join(fields) if columns is None: columns = ["*", "score"] fields = {'q' : query, 'json.nl': 'map', 'mlt.fl': mlt_fields, ...
def more_like_this(self, query, fields, columns=None, start=0, rows=30)
Retrieves "more like this" results for a passed query document query - query for a document on which to base similar documents fields - fields on which to base similarity estimation (either comma delimited string or a list) columns - columns to return (list of strings) start - start num...
3.118803
3.159506
0.987117
m = importlib.import_module(config['module']) m.set_up() config["name"] = case analysis_data = {} bundle = livvkit.numerics_model_module 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_d...
def run_suite(case, config, summary)
Run the full suite of numerics tests
3.703577
3.66229
1.011274
if time: td = 1.0 / framerate update = self.update for i in range(int(time / td)): update(td)
def run_ahead(self, time, framerate)
Run the particle system for the specified time frame at the specified framerate to move time forward as quickly as possible. Useful for "warming up" the particle system to reach a steady-state before anything is drawn or to simply "skip ahead" in time. time -- The amount of simulation t...
5.584205
7.110967
0.785295
panel_id = "panel_{}".format(self.name) return ["<h2>{}</h2>".format(self.title) + '<a href="{}">Download data</a>'.format(self.tar_fn())] + [ # list of links (" <br />" + os.linesep).join( [ .format( bam_name=...
def get_html_column(self)
Get a HTML column for this panel.
4.669461
4.490139
1.039937
nb_bams = len(self.bams) gp_parts = [ textwrap.dedent( ), os.linesep.join([self._gp_style_func(i, nb_bams) for i in range(nb_bams)]), textwrap.dedent( ), os.linesep.join(self.gp_plots) ...
def create_gp(self)
Create GnuPlot file.
4.853324
4.653361
1.042972
if len(self._svg_fns) > 0: rnftools.utils.shell('"{}" "{}"'.format("gnuplot", self._gp_fn)) if self.render_pdf_method is not None: for svg_fn in self._svg_fns: pdf_fn = re.sub(r'\.svg$', r'.pdf', svg_fn) svg42pdf(svg_fn, ...
def create_graphics(self)
Create images related to this panel.
5.128407
5.179321
0.99017
def add_file_to_tar(tar, orig_fn, new_fn, func=None): tf = tarfile.TarInfo(name=new_fn) with open(orig_fn) as f: tfs = f.read() if func is not None: tfs = func(tfs) tf.size = len(tfs) tfs = io.BytesIO(tfs.enco...
def create_tar(self)
Create a tar file with all the files.
2.022024
2.002651
1.009674
tmp = dict1.copy() tmp.update(dict2) return tmp
def merge_dicts(dict1, dict2)
Merge two dictionaries and return the result
3.644748
3.653003
0.99774
timing_result = dict() if os.path.isfile(file_path): with open(file_path, 'r') as f: for var in var_list: for line in f: if var in line: timing_result[var] = float(line.split()[4])/int(line.split()[2]) b...
def parse_gptl(file_path, var_list)
Read a GPTL timing file and extract some data. Args: file_path: the path to the GPTL timing file var_list: a list of strings to look for in the file Returns: A dict containing key-value pairs of the livvkit and the times associated with them
2.509522
2.677154
0.937384
for root, dirnames, fnames in os.walk(search_dir): for fname in fnames: if fnmatch.fnmatch(fname, file_pattern): return os.path.join(root, fname) return ""
def find_file(search_dir, file_pattern)
Search for a file in a directory, and return the first match. If the file is not found return an empty string Args: search_dir: The root directory to search in file_pattern: A unix-style wildcard pattern representing the file to find Returns: The path to the file if it ...
1.977829
2.759055
0.71685
mkdir_p(os.path.dirname(output_path)) shutil.copy(os.path.join(livvkit.resource_dir, template_file), output_path)
def create_page_from_template(template_file, output_path)
Copy the correct html template file to the output directory
4.238867
3.863448
1.097172
try: with open(file_path, 'r') as f: config = json_tricks.load(f) except ValueError: print(' '+'!'*58) print(' Woops! Looks the JSON syntax is not valid in:') print(' {}'.format(file_path)) print(' Note: commonly this is a result of having...
def read_json(file_path)
Read in a json file and return a dictionary representation
5.943973
6.00912
0.989159
if os.path.exists(path) and not os.path.isdir(path): return elif not os.path.exists(path): mkdir_p(path) with open(os.path.join(path, file_name), 'w') as f: json_tricks.dump(data, f, indent=4, primitives=True, allow_nan=True)
def write_json(data, path, file_name)
Write out data to a json file. Args: data: A dictionary representation of the data to write out path: The directory to output the file in file_name: The name of the file to write out
2.673457
3.031626
0.881856
cases = {} for root, dirs, files in os.walk(data_dir): if not dirs: split_case = os.path.relpath(root, data_dir).split(os.path.sep) if split_case[0] not in cases: cases[split_case[0]] = [] cases[split_case[0]].append("-".join(split_case[1:])) ...
def collect_cases(data_dir)
Find all cases and subcases of a particular run type
2.011165
2.013069
0.999054
# Check if we need to back up an old run if os.path.isdir(livvkit.index_dir): print("-------------------------------------------------------------------") print(' Previous output data found in output directory!') try: f = open(os.path.join(livvkit.index_dir, "data.txt")...
def setup_output(cssd=None, jsd=None, imgd=None)
Set up the directory structure for the output. Copies old run data into a timestamped directory and sets up the new directory
2.226405
2.20818
1.008253
return [ (sub_key, sub_value) for key, value in kwargs.items() for sub_key, sub_value in expand(value, key) if sub_value is not None ]
def prepare_query_params(**kwargs)
Prepares given parameters to be used in querystring.
3.579982
3.36132
1.065052
if '.' not in value: direction = '' if value.startswith('-'): value = value[1:] direction = '-' value = '%s%s.%s' % (direction, model, value) return value
def prepend_model(self, value, model)
Prepends model name if it is not already prepended. For example model is "Offer": key -> Offer.key -key -> -Offer.key Offer.key -> Offer.key -Offer.key -> -Offer.key
3.343238
3.936103
0.849378
global yrot win.clear() glLoadIdentity() glTranslatef(0, 0, -100) glRotatef(yrot, 0.0, 1.0, 0.0) default_system.draw() ''' glBindTexture(GL_TEXTURE_2D, 1) glEnable(GL_TEXTURE_2D) glEnable(GL_POINT_SPRITE) glPointSize(100); glBegin(GL_POINTS) glVertex2f(0,0) glEnd() glBindTexture(GL_TEXTURE_2D, 2) glEnab...
def on_draw()
glBindTexture(GL_TEXTURE_2D, 1) glEnable(GL_TEXTURE_2D) glEnable(GL_POINT_SPRITE) glPointSize(100); glBegin(GL_POINTS) glVertex2f(0,0) glEnd() glBindTexture(GL_TEXTURE_2D, 2) glEnable(GL_TEXTURE_2D) glEnable(GL_POINT_SPRITE) glPointSize(100); glBegin(GL_POINTS) glVertex2f(50,0) glEnd() glBindTexture(GL_TE...
1.887565
1.595597
1.182983
max_age = timezone.now() - timedelta(seconds=max_age) logger.debug("Deleting all callback redirects created before {0}".format(max_age.strftime("%b %d %Y %H:%M:%S"))) CallbackRedirect.objects.filter(created__lte=max_age).delete()
def cleanup_callbackredirect(max_age=300)
Delete old :model:`esi.CallbackRedirect` models. Accepts a max_age parameter, in seconds (default 300).
2.88498
2.81285
1.025643
for token in queryset: if not token.expired: forward_token(token)
def send_token_email(self, request, queryset)
Sends token email(s) for the selected users.
14.742762
18.918756
0.779267
from .models import Content # Gets the count for a tag, hopefully form an in-memory cache. cnt = cls._cache.get(slug) if cnt is None: cnt = Content.search_objects.search(tags=[slug]).count() cls._cache[slug] = cnt return cnt
def count(cls, slug)
get the number of objects in the cache for a given slug :param slug: cache key :return: `int`
6.599357
7.736968
0.852964
dt = DATA_TYPES['varchar'] if type(self.data) is dt['type'] and len(self.data) < dt['max']: self.type = 'VARCHAR' self.len = len(self.data) return True
def is_varchar(self)
Determine if a data record is of the type VARCHAR.
4.343986
3.852013
1.127718
dt = DATA_TYPES[data_type] if type(self.data) is dt['type'] and len(self.data) < dt['max'] and all(type(char) == str for char in self.data): self.type = data_type.upper() self.len = len(self.data) return True
def _is_text_data(self, data_type)
Private method for testing text data types.
4.130902
3.776238
1.09392
def bind_key_name(self, function, object_name): for funcname, name in self.name_map.items(): if funcname == function: self.name_map[ funcname] = object_name
Bind a key to an object name
null
null
null
def bind_keys(self, objects): for object in objects: if object.keys != None: for key in object.keys: if key != None: self.bind_key_name(key, object.name)
Configure name map: My goal here is to associate a named object with a specific function
null
null
null
def configure_keys(self): self.active_functions = set() self.key2func = {} for funcname, key in self.key_map.items(): self.key2func[key] = getattr(self, funcname)
Configure key map
null
null
null
'''Loop through all the modules and parse them.''' for module_meta in module_list: name = module_meta['module'] # Import & parse module module = import_module(name) output = parse_module(module) # Assign to meta.content module_meta['content'] = output
def _parse_module_list(module_list)
Loop through all the modules and parse them.
6.029078
5.182317
1.163394
'''Builds a list of python modules in the current directory.''' out = [] dirs_with_init = set() module_prefix = '' if source_module == '.' else source_module for root, _, filenames in walk('.'): root = root[2:] module_root = root.replace('/', '.') file_names = [filename[:-3]...
def _build_module_list(source_module, index_filename, ignore_modules)
Builds a list of python modules in the current directory.
2.439646
2.39541
1.018467
'''Write the document meta to our output location.''' for module_meta in module_list: directory = module_meta['directory'] # Ensure target directory if directory and not path.isdir(directory): makedirs(directory) # Write the file file = open(module_meta['outp...
def _write_docs(module_list, output_dir)
Write the document meta to our output location.
4.688527
3.629313
1.29185
''' Build markdown documentation from a directory and/or python module. # ignore_modules: takes a list of module names to ignore # index_filename: __init__.py output (default index.md), use README.md for github indexes ''' if root.endswith('/'): root = root[:-1] if ignore_modules i...
def build( root, source_module, output_dir, json_dump=False, ignore_modules=None, index_filename='index' )
Build markdown documentation from a directory and/or python module. # ignore_modules: takes a list of module names to ignore # index_filename: __init__.py output (default index.md), use README.md for github indexes
3.519182
2.619984
1.343207
'''Main in a function in case you place a build.py for pydocs inside the root directory.''' options = ''' pydocs Usage: pydocs SOURCE OUTPUT_DIR pydocs SOURCE OUTPUT_DIR [--json] [--index NAME] [--ignore FILE,NAMES] pydocs --help Options: ...
def main()
Main in a function in case you place a build.py for pydocs inside the root directory.
6.74682
4.775435
1.412818
captions, rows = self._get_pages() name_caption_index = captions.index(self.name_caption) captions.pop(name_caption_index) self.captions = captions self.statistics = OrderedDict() for row in rows: name = row.pop(name_caption_index) self.s...
def read_stats(self)
Reads the statistics view from IXN and saves it in statistics dictionary.
4.253516
3.81347
1.115392
all_stats = OrderedDict() for obj_name in self.statistics: all_stats[obj_name] = dict(zip(self.captions, self.statistics[obj_name])) return all_stats
def get_all_stats(self)
:returns: all statistics values for all objects.
4.573093
3.386363
1.350444
return dict(zip(self.captions, self.statistics[obj_name]))
def get_object_stats(self, obj_name)
:param obj_name: requested object name :returns: all statistics values for the requested object.
13.771037
13.030614
1.056822
return [self.get_stat(r, stat_name) for r in self.statistics.keys()]
def get_stats(self, stat_name)
:param stat_name: requested statistics name. :returns: all values of the requested statistic for all objects.
7.453022
6.901463
1.079919
return self.statistics[obj_name][self.captions.index(stat_name)]
def get_stat(self, obj_name, stat_name)
:param obj_name: requested object name. :param stat_name: requested statistics name. :return: str, the value of the requested statics for the requested object.
9.303767
9.175981
1.013926
from subprocess import Popen, PIPE p = Popen( '{0} --version'.format(cmake_command), shell=True, stdin=PIPE, stdout=PIPE) if not ('cmake version' in p.communicate()[0].decode('UTF-8')): sys.stderr.write(' This code is built using CMake\n\n') sys.stderr...
def check_cmake_exists(cmake_command)
Check whether CMake is installed. If not, print informative error message and quits.
3.594248
3.55266
1.011706
if os.path.isdir(build_path): fname = os.path.join(build_path, 'CMakeCache.txt') if os.path.exists(fname): sys.stderr.write('aborting setup\n') sys.stderr.write( 'build directory {0} which contains CMakeCache.txt already exists\n'. format(...
def setup_build_path(build_path)
Create build directory. If this already exists, print informative error message and quit.
2.594859
2.55453
1.015787
from subprocess import Popen, PIPE from shutil import rmtree topdir = os.getcwd() p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout_coded, stderr_coded = p.communicate() stdout = stdout_coded.decode('UTF-8') stderr = stderr_coded.decode('UTF-8') # print c...
def run_cmake(command, build_path, default_build_path)
Execute CMake command.
4.329754
4.310127
1.004554
print(' configure step is done') print(' now you need to compile the sources:') if (build_path == default_build_path): print(' $ cd build') else: print(' $ cd ' + build_path) print(' $ make')
def print_build_help(build_path, default_build_path)
Print help text after configuration step is done.
4.542654
4.070211
1.116073
file_name = os.path.join(build_path, 'setup_command') with open(file_name, 'w') as f: f.write(' '.join(argv[:]) + '\n')
def save_setup_command(argv, build_path)
Save setup command to a file.
2.356117
2.175176
1.083185
default_build_path = os.path.join(root_directory, 'build') # check that CMake is available, if not stop check_cmake_exists('cmake') # deal with build path if build_path is None: build_path = default_build_path if not only_show: setup_build_path(build_path) cmake_comma...
def configure(root_directory, build_path, cmake_command, only_show)
Main configure function.
3.152348
3.131659
1.006606
from django.utils.hashcompat import sha_constructor hash = sha_constructor(settings.SECRET_KEY + self.url + self.email + unicode(datetime.now()) ).hexdigest() return hash[::2]
def generate_hash(self)
Create a unique SHA token/hash using the project SECRET_KEY, URL, email address and current datetime.
5.257976
3.239974
1.622845
def create_single_poll_session(self, poll_id, poll_sessions_course_id, poll_sessions_course_section_id=None, poll_sessions_has_public_results=None): path = {} data = {} params = {} # REQUIRED - PATH - poll_id path["poll_id"] = poll_id # REQUI...
Create a single poll session. Create a new poll session for this poll
null
null
null