repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
cloudtools/stacker
stacker/hooks/aws_lambda.py
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/aws_lambda.py#L103-L134
def _find_files(root, includes, excludes, follow_symlinks): """List files inside a directory based on include and exclude rules. This is a more advanced version of `glob.glob`, that accepts multiple complex patterns. Args: root (str): base directory to list files from. includes (list[str]): inclusion patterns. Only files matching those patterns will be included in the result. excludes (list[str]): exclusion patterns. Files matching those patterns will be excluded from the result. Exclusions take precedence over inclusions. follow_symlinks (bool): If true, symlinks will be included in the resulting zip file Yields: str: a file name relative to the root. Note: Documentation for the patterns can be found at http://www.aviser.asia/formic/doc/index.html """ root = os.path.abspath(root) file_set = formic.FileSet( directory=root, include=includes, exclude=excludes, symlinks=follow_symlinks, ) for filename in file_set.qualified_files(absolute=False): yield filename
[ "def", "_find_files", "(", "root", ",", "includes", ",", "excludes", ",", "follow_symlinks", ")", ":", "root", "=", "os", ".", "path", ".", "abspath", "(", "root", ")", "file_set", "=", "formic", ".", "FileSet", "(", "directory", "=", "root", ",", "inc...
List files inside a directory based on include and exclude rules. This is a more advanced version of `glob.glob`, that accepts multiple complex patterns. Args: root (str): base directory to list files from. includes (list[str]): inclusion patterns. Only files matching those patterns will be included in the result. excludes (list[str]): exclusion patterns. Files matching those patterns will be excluded from the result. Exclusions take precedence over inclusions. follow_symlinks (bool): If true, symlinks will be included in the resulting zip file Yields: str: a file name relative to the root. Note: Documentation for the patterns can be found at http://www.aviser.asia/formic/doc/index.html
[ "List", "files", "inside", "a", "directory", "based", "on", "include", "and", "exclude", "rules", "." ]
python
train
34.9375
dailymuse/oz
oz/bandit/__init__.py
https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/bandit/__init__.py#L254-L265
def compute_default_choice(self): """Computes and sets the default choice""" choices = self.choices if len(choices) == 0: return None high_choice = max(choices, key=lambda choice: choice.performance) self.redis.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "default-choice", high_choice.name) self.refresh() return high_choice
[ "def", "compute_default_choice", "(", "self", ")", ":", "choices", "=", "self", ".", "choices", "if", "len", "(", "choices", ")", "==", "0", ":", "return", "None", "high_choice", "=", "max", "(", "choices", ",", "key", "=", "lambda", "choice", ":", "ch...
Computes and sets the default choice
[ "Computes", "and", "sets", "the", "default", "choice" ]
python
train
32.333333
jumpscale7/python-consistent-toml
contoml/file/file.py
https://github.com/jumpscale7/python-consistent-toml/blob/a0149c65313ccb8170aa99a0cc498e76231292b9/contoml/file/file.py#L73-L83
def _make_sure_table_exists(self, name_seq): """ Makes sure the table with the full name comprising of name_seq exists. """ t = self for key in name_seq[:-1]: t = t[key] name = name_seq[-1] if name not in t: self.append_elements([element_factory.create_table_header_element(name_seq), element_factory.create_table({})])
[ "def", "_make_sure_table_exists", "(", "self", ",", "name_seq", ")", ":", "t", "=", "self", "for", "key", "in", "name_seq", "[", ":", "-", "1", "]", ":", "t", "=", "t", "[", "key", "]", "name", "=", "name_seq", "[", "-", "1", "]", "if", "name", ...
Makes sure the table with the full name comprising of name_seq exists.
[ "Makes", "sure", "the", "table", "with", "the", "full", "name", "comprising", "of", "name_seq", "exists", "." ]
python
train
38.454545
Guake/guake
guake/boxes.py
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/boxes.py#L323-L329
def add_scroll_bar(self): """Packs the scrollbar. """ adj = self.terminal.get_vadjustment() scroll = Gtk.VScrollbar(adj) scroll.show() self.pack_start(scroll, False, False, 0)
[ "def", "add_scroll_bar", "(", "self", ")", ":", "adj", "=", "self", ".", "terminal", ".", "get_vadjustment", "(", ")", "scroll", "=", "Gtk", ".", "VScrollbar", "(", "adj", ")", "scroll", ".", "show", "(", ")", "self", ".", "pack_start", "(", "scroll", ...
Packs the scrollbar.
[ "Packs", "the", "scrollbar", "." ]
python
train
31
yodle/docker-registry-client
docker_registry_client/_BaseClient.py
https://github.com/yodle/docker-registry-client/blob/8abf6b0200a68bed986f698dcbf02d444257b75c/docker_registry_client/_BaseClient.py#L97-L99
def get_image_layer(self, image_id): """GET /v1/images/(image_id)/json""" return self._http_call(self.IMAGE_JSON, get, image_id=image_id)
[ "def", "get_image_layer", "(", "self", ",", "image_id", ")", ":", "return", "self", ".", "_http_call", "(", "self", ".", "IMAGE_JSON", ",", "get", ",", "image_id", "=", "image_id", ")" ]
GET /v1/images/(image_id)/json
[ "GET", "/", "v1", "/", "images", "/", "(", "image_id", ")", "/", "json" ]
python
train
50.333333
veeti/decent
decent/validators.py
https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L171-L208
def Boolean(): """ Creates a validator that attempts to convert the given value to a boolean or raises an error. The following rules are used: ``None`` is converted to ``False``. ``int`` values are ``True`` except for ``0``. ``str`` values converted in lower- and uppercase: * ``y, yes, t, true`` * ``n, no, f, false`` """ @wraps(Boolean) def built(value): # Already a boolean? if isinstance(value, bool): return value # None if value == None: return False # Integers if isinstance(value, int): return not value == 0 # Strings if isinstance(value, str): if value.lower() in { 'y', 'yes', 't', 'true' }: return True elif value.lower() in { 'n', 'no', 'f', 'false' }: return False # Nope raise Error("Not a boolean value.") return built
[ "def", "Boolean", "(", ")", ":", "@", "wraps", "(", "Boolean", ")", "def", "built", "(", "value", ")", ":", "# Already a boolean?", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "return", "value", "# None", "if", "value", "==", "None", ":", ...
Creates a validator that attempts to convert the given value to a boolean or raises an error. The following rules are used: ``None`` is converted to ``False``. ``int`` values are ``True`` except for ``0``. ``str`` values converted in lower- and uppercase: * ``y, yes, t, true`` * ``n, no, f, false``
[ "Creates", "a", "validator", "that", "attempts", "to", "convert", "the", "given", "value", "to", "a", "boolean", "or", "raises", "an", "error", ".", "The", "following", "rules", "are", "used", ":" ]
python
train
24.342105
kmmbvnr/django-any
django_any/forms.py
https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/forms.py#L168-L179
def datetime_field_data(field, **kwargs): """ Return random value for DateTimeField >>> result = any_form_field(forms.DateTimeField()) >>> type(result) <type 'str'> """ from_date = kwargs.get('from_date', datetime(1990, 1, 1)) to_date = kwargs.get('to_date', datetime.today()) date_format = random.choice(field.input_formats or formats.get_format('DATETIME_INPUT_FORMATS')) return xunit.any_datetime(from_date=from_date, to_date=to_date).strftime(date_format)
[ "def", "datetime_field_data", "(", "field", ",", "*", "*", "kwargs", ")", ":", "from_date", "=", "kwargs", ".", "get", "(", "'from_date'", ",", "datetime", "(", "1990", ",", "1", ",", "1", ")", ")", "to_date", "=", "kwargs", ".", "get", "(", "'to_dat...
Return random value for DateTimeField >>> result = any_form_field(forms.DateTimeField()) >>> type(result) <type 'str'>
[ "Return", "random", "value", "for", "DateTimeField" ]
python
test
40.75
ktbyers/netmiko
netmiko/snmp_autodetect.py
https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/snmp_autodetect.py#L233-L266
def _get_snmpv3(self, oid): """ Try to send an SNMP GET operation using SNMPv3 for the specified OID. Parameters ---------- oid : str The SNMP OID that you want to get. Returns ------- string : str The string as part of the value from the OID you are trying to retrieve. """ snmp_target = (self.hostname, self.snmp_port) cmd_gen = cmdgen.CommandGenerator() (error_detected, error_status, error_index, snmp_data) = cmd_gen.getCmd( cmdgen.UsmUserData( self.user, self.auth_key, self.encrypt_key, authProtocol=self.auth_proto, privProtocol=self.encryp_proto, ), cmdgen.UdpTransportTarget(snmp_target, timeout=1.5, retries=2), oid, lookupNames=True, lookupValues=True, ) if not error_detected and snmp_data[0][1]: return text_type(snmp_data[0][1]) return ""
[ "def", "_get_snmpv3", "(", "self", ",", "oid", ")", ":", "snmp_target", "=", "(", "self", ".", "hostname", ",", "self", ".", "snmp_port", ")", "cmd_gen", "=", "cmdgen", ".", "CommandGenerator", "(", ")", "(", "error_detected", ",", "error_status", ",", "...
Try to send an SNMP GET operation using SNMPv3 for the specified OID. Parameters ---------- oid : str The SNMP OID that you want to get. Returns ------- string : str The string as part of the value from the OID you are trying to retrieve.
[ "Try", "to", "send", "an", "SNMP", "GET", "operation", "using", "SNMPv3", "for", "the", "specified", "OID", "." ]
python
train
30.352941
h2oai/h2o-3
py2/h2o_ray.py
https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/py2/h2o_ray.py#L25-L79
def poll_job(self, job_key, timeoutSecs=10, retryDelaySecs=0.5, key=None, **kwargs): ''' Poll a single job from the /Jobs endpoint until it is "status": "DONE" or "CANCELLED" or "FAILED" or we time out. ''' params_dict = {} # merge kwargs into params_dict h2o_methods.check_params_update_kwargs(params_dict, kwargs, 'poll_job', False) start_time = time.time() pollCount = 0 while True: result = self.do_json_request('3/Jobs.json/' + job_key, timeout=timeoutSecs, params=params_dict) # print 'Job: ', dump_json(result) if key: frames_result = self.frames(key=key) print 'frames_result for key:', key, dump_json(result) jobs = result['jobs'][0] description = jobs['description'] dest = jobs['dest'] dest_name = dest['name'] msec = jobs['msec'] status = jobs['status'] progress = jobs['progress'] print description, \ "dest_name:", dest_name, \ "\tprogress:", "%-10s" % progress, \ "\tstatus:", "%-12s" % status, \ "\tmsec:", msec if status=='DONE' or status=='CANCELLED' or status=='FAILED': h2o_sandbox.check_sandbox_for_errors() return result # what about 'CREATED' # FIX! what are the other legal polling statuses that we should check for? if not h2o_args.no_timeout and (time.time() - start_time > timeoutSecs): h2o_sandbox.check_sandbox_for_errors() emsg = "Job:", job_key, "timed out in:", timeoutSecs # for debug a = h2o.nodes[0].get_cloud() print "cloud.json:", dump_json(a) raise Exception(emsg) print emsg return None # check every other poll, for now if (pollCount % 2) == 0: h2o_sandbox.check_sandbox_for_errors() time.sleep(retryDelaySecs) pollCount += 1
[ "def", "poll_job", "(", "self", ",", "job_key", ",", "timeoutSecs", "=", "10", ",", "retryDelaySecs", "=", "0.5", ",", "key", "=", "None", ",", "*", "*", "kwargs", ")", ":", "params_dict", "=", "{", "}", "# merge kwargs into params_dict", "h2o_methods", "....
Poll a single job from the /Jobs endpoint until it is "status": "DONE" or "CANCELLED" or "FAILED" or we time out.
[ "Poll", "a", "single", "job", "from", "the", "/", "Jobs", "endpoint", "until", "it", "is", "status", ":", "DONE", "or", "CANCELLED", "or", "FAILED", "or", "we", "time", "out", "." ]
python
test
34.909091
Tanganelli/CoAPthon3
coapthon/resources/resource.py
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/resources/resource.py#L315-L327
def add_content_type(self, ct): """ Add a CoRE Link Format ct attribute to the resource. :param ct: the CoRE Link Format ct attribute """ lst = self._attributes.get("ct") if lst is None: lst = [] if isinstance(ct, str): ct = defines.Content_types[ct] lst.append(ct) self._attributes["ct"] = lst
[ "def", "add_content_type", "(", "self", ",", "ct", ")", ":", "lst", "=", "self", ".", "_attributes", ".", "get", "(", "\"ct\"", ")", "if", "lst", "is", "None", ":", "lst", "=", "[", "]", "if", "isinstance", "(", "ct", ",", "str", ")", ":", "ct", ...
Add a CoRE Link Format ct attribute to the resource. :param ct: the CoRE Link Format ct attribute
[ "Add", "a", "CoRE", "Link", "Format", "ct", "attribute", "to", "the", "resource", "." ]
python
train
29.153846
peri-source/peri
peri/opt/optimize.py
https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L258-L328
def separate_particles_into_groups(s, region_size=40, bounds=None, doshift=False): """ Separates particles into convenient groups for optimization. Given a state, returns a list of groups of particles. Each group of particles are located near each other in the image. Every particle located in the desired region is contained in exactly 1 group. Parameters ---------- s : :class:`peri.states.ImageState` The peri state to find particles in. region_size : Int or 3-element list-like of ints, optional The size of the box. Groups particles into boxes of shape (region_size[0], region_size[1], region_size[2]). If region_size is a scalar, the box is a cube of length region_size. Default is 40. bounds : 2-element list-like of 3-element lists, optional The sub-region of the image over which to look for particles. bounds[0]: The lower-left corner of the image region. bounds[1]: The upper-right corner of the image region. Default (None -> ([0,0,0], s.oshape.shape)) is a box of the entire image size, i.e. the default places every particle in the image somewhere in the groups. doshift : {True, False, `'rand'`}, optional Whether or not to shift the tile boxes by half a region size, to prevent the same particles to be chosen every time. If `'rand'`, randomly chooses either True or False. Default is False Returns ------- particle_groups : List Each element of particle_groups is an int numpy.ndarray of the group of nearby particles. Only contains groups with a nonzero number of particles, so the elements don't necessarily correspond to a given image region. """ imtile = s.oshape.translate(-s.pad) bounding_tile = (imtile if bounds is None else Tile(bounds[0], bounds[1])) rs = (np.ones(bounding_tile.dim, dtype='int')*region_size if np.size(region_size) == 1 else np.array(region_size)) n_translate = np.ceil(bounding_tile.shape.astype('float')/rs).astype('int') particle_groups = [] tile = Tile(left=bounding_tile.l, right=bounding_tile.l + rs) if doshift == 'rand': doshift = np.random.choice([True, False]) if doshift: shift = rs // 2 n_translate += 1 else: shift = 0 deltas = np.meshgrid(*[np.arange(i) for i in n_translate]) positions = s.obj_get_positions() if bounds is None: # FIXME this (deliberately) masks a problem where optimization # places particles outside the image. However, it ensures that # all particles are in at least one group when `bounds is None`, # which is the use case within opt. The 1e-3 is to ensure that # they are inside the box and not on the edge. positions = np.clip(positions, imtile.l+1e-3, imtile.r-1e-3) groups = list(map(lambda *args: find_particles_in_tile(positions, tile.translate( np.array(args) * rs - shift)), *[d.ravel() for d in deltas])) for i in range(len(groups)-1, -1, -1): if groups[i].size == 0: groups.pop(i) assert _check_groups(s, groups) return groups
[ "def", "separate_particles_into_groups", "(", "s", ",", "region_size", "=", "40", ",", "bounds", "=", "None", ",", "doshift", "=", "False", ")", ":", "imtile", "=", "s", ".", "oshape", ".", "translate", "(", "-", "s", ".", "pad", ")", "bounding_tile", ...
Separates particles into convenient groups for optimization. Given a state, returns a list of groups of particles. Each group of particles are located near each other in the image. Every particle located in the desired region is contained in exactly 1 group. Parameters ---------- s : :class:`peri.states.ImageState` The peri state to find particles in. region_size : Int or 3-element list-like of ints, optional The size of the box. Groups particles into boxes of shape (region_size[0], region_size[1], region_size[2]). If region_size is a scalar, the box is a cube of length region_size. Default is 40. bounds : 2-element list-like of 3-element lists, optional The sub-region of the image over which to look for particles. bounds[0]: The lower-left corner of the image region. bounds[1]: The upper-right corner of the image region. Default (None -> ([0,0,0], s.oshape.shape)) is a box of the entire image size, i.e. the default places every particle in the image somewhere in the groups. doshift : {True, False, `'rand'`}, optional Whether or not to shift the tile boxes by half a region size, to prevent the same particles to be chosen every time. If `'rand'`, randomly chooses either True or False. Default is False Returns ------- particle_groups : List Each element of particle_groups is an int numpy.ndarray of the group of nearby particles. Only contains groups with a nonzero number of particles, so the elements don't necessarily correspond to a given image region.
[ "Separates", "particles", "into", "convenient", "groups", "for", "optimization", "." ]
python
valid
44.690141
kislyuk/aegea
aegea/packages/github3/repos/repo.py
https://github.com/kislyuk/aegea/blob/94957e9dba036eae3052e2662c208b259c08399a/aegea/packages/github3/repos/repo.py#L414-L438
def contents(self, path, ref=None): """Get the contents of the file pointed to by ``path``. If the path provided is actually a directory, you will receive a dictionary back of the form:: { 'filename.md': Contents(), # Where Contents an instance 'github.py': Contents(), } :param str path: (required), path to file, e.g. github3/repo.py :param str ref: (optional), the string name of a commit/branch/tag. Default: master :returns: :class:`Contents <github3.repos.contents.Contents>` or dict if successful, else None """ url = self._build_url('contents', path, base_url=self._api) json = self._json(self._get(url, params={'ref': ref}), 200) if isinstance(json, dict): return Contents(json, self) elif isinstance(json, list): return dict((j.get('name'), Contents(j, self)) for j in json) return None
[ "def", "contents", "(", "self", ",", "path", ",", "ref", "=", "None", ")", ":", "url", "=", "self", ".", "_build_url", "(", "'contents'", ",", "path", ",", "base_url", "=", "self", ".", "_api", ")", "json", "=", "self", ".", "_json", "(", "self", ...
Get the contents of the file pointed to by ``path``. If the path provided is actually a directory, you will receive a dictionary back of the form:: { 'filename.md': Contents(), # Where Contents an instance 'github.py': Contents(), } :param str path: (required), path to file, e.g. github3/repo.py :param str ref: (optional), the string name of a commit/branch/tag. Default: master :returns: :class:`Contents <github3.repos.contents.Contents>` or dict if successful, else None
[ "Get", "the", "contents", "of", "the", "file", "pointed", "to", "by", "path", "." ]
python
train
39.52
apache/airflow
airflow/ti_deps/deps/base_ti_dep.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/ti_deps/deps/base_ti_dep.py#L110-L125
def is_met(self, ti, session, dep_context=None): """ Returns whether or not this dependency is met for a given task instance. A dependency is considered met if all of the dependency statuses it reports are passing. :param ti: the task instance to see if this dependency is met for :type ti: airflow.models.TaskInstance :param session: database session :type session: sqlalchemy.orm.session.Session :param dep_context: The context this dependency is being checked under that stores state that can be used by this dependency. :type dep_context: BaseDepContext """ return all(status.passed for status in self.get_dep_statuses(ti, session, dep_context))
[ "def", "is_met", "(", "self", ",", "ti", ",", "session", ",", "dep_context", "=", "None", ")", ":", "return", "all", "(", "status", ".", "passed", "for", "status", "in", "self", ".", "get_dep_statuses", "(", "ti", ",", "session", ",", "dep_context", ")...
Returns whether or not this dependency is met for a given task instance. A dependency is considered met if all of the dependency statuses it reports are passing. :param ti: the task instance to see if this dependency is met for :type ti: airflow.models.TaskInstance :param session: database session :type session: sqlalchemy.orm.session.Session :param dep_context: The context this dependency is being checked under that stores state that can be used by this dependency. :type dep_context: BaseDepContext
[ "Returns", "whether", "or", "not", "this", "dependency", "is", "met", "for", "a", "given", "task", "instance", ".", "A", "dependency", "is", "considered", "met", "if", "all", "of", "the", "dependency", "statuses", "it", "reports", "are", "passing", "." ]
python
test
47.625
serhatbolsu/robotframework-appiumlibrary
AppiumLibrary/keywords/_element.py
https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_element.py#L147-L157
def element_should_be_disabled(self, locator, loglevel='INFO'): """Verifies that element identified with locator is disabled. Key attributes for arbitrary elements are `id` and `name`. See `introduction` for details about locating elements. """ if self._element_find(locator, True, True).is_enabled(): self.log_source(loglevel) raise AssertionError("Element '%s' should be disabled " "but did not" % locator) self._info("Element '%s' is disabled ." % locator)
[ "def", "element_should_be_disabled", "(", "self", ",", "locator", ",", "loglevel", "=", "'INFO'", ")", ":", "if", "self", ".", "_element_find", "(", "locator", ",", "True", ",", "True", ")", ".", "is_enabled", "(", ")", ":", "self", ".", "log_source", "(...
Verifies that element identified with locator is disabled. Key attributes for arbitrary elements are `id` and `name`. See `introduction` for details about locating elements.
[ "Verifies", "that", "element", "identified", "with", "locator", "is", "disabled", ".", "Key", "attributes", "for", "arbitrary", "elements", "are", "id", "and", "name", ".", "See", "introduction", "for", "details", "about", "locating", "elements", "." ]
python
train
51.363636
pantsbuild/pants
src/python/pants/reporting/reporting_server.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/reporting/reporting_server.py#L319-L327
def _client_allowed(self): """Check if client is allowed to connect to this server.""" client_ip = self._client_address[0] if not client_ip in self._settings.allowed_clients and \ not 'ALL' in self._settings.allowed_clients: content = 'Access from host {} forbidden.'.format(client_ip).encode('utf-8') self._send_content(content, 'text/html') return False return True
[ "def", "_client_allowed", "(", "self", ")", ":", "client_ip", "=", "self", ".", "_client_address", "[", "0", "]", "if", "not", "client_ip", "in", "self", ".", "_settings", ".", "allowed_clients", "and", "not", "'ALL'", "in", "self", ".", "_settings", ".", ...
Check if client is allowed to connect to this server.
[ "Check", "if", "client", "is", "allowed", "to", "connect", "to", "this", "server", "." ]
python
train
44.444444
lepture/python-livereload
livereload/watcher.py
https://github.com/lepture/python-livereload/blob/f80cb3ae0f8f2cdf38203a712fe25ef7f1899c34/livereload/watcher.py#L53-L68
def watch(self, path, func=None, delay=0, ignore=None): """Add a task to watcher. :param path: a filepath or directory path or glob pattern :param func: the function to be executed when file changed :param delay: Delay sending the reload message. Use 'forever' to not send it. This is useful to compile sass files to css, but reload on changed css files then only. :param ignore: A function return True to ignore a certain pattern of filepath. """ self._tasks[path] = { 'func': func, 'delay': delay, 'ignore': ignore, }
[ "def", "watch", "(", "self", ",", "path", ",", "func", "=", "None", ",", "delay", "=", "0", ",", "ignore", "=", "None", ")", ":", "self", ".", "_tasks", "[", "path", "]", "=", "{", "'func'", ":", "func", ",", "'delay'", ":", "delay", ",", "'ign...
Add a task to watcher. :param path: a filepath or directory path or glob pattern :param func: the function to be executed when file changed :param delay: Delay sending the reload message. Use 'forever' to not send it. This is useful to compile sass files to css, but reload on changed css files then only. :param ignore: A function return True to ignore a certain pattern of filepath.
[ "Add", "a", "task", "to", "watcher", "." ]
python
train
42
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1636-L1642
def plot(self, name, funcname): """Plot item""" sw = self.shellwidget if sw._reading: sw.dbg_exec_magic('varexp', '--%s %s' % (funcname, name)) else: sw.execute("%%varexp --%s %s" % (funcname, name))
[ "def", "plot", "(", "self", ",", "name", ",", "funcname", ")", ":", "sw", "=", "self", ".", "shellwidget", "if", "sw", ".", "_reading", ":", "sw", ".", "dbg_exec_magic", "(", "'varexp'", ",", "'--%s %s'", "%", "(", "funcname", ",", "name", ")", ")", ...
Plot item
[ "Plot", "item" ]
python
train
36.428571
CulturePlex/django-zotero
django_zotero/signals.py
https://github.com/CulturePlex/django-zotero/blob/de31583a80a2bd2459c118fb5aa767a2842e0b00/django_zotero/signals.py#L8-L21
def check_save(sender, **kwargs): """ Checks item type uniqueness, field applicability and multiplicity. """ tag = kwargs['instance'] obj = Tag.get_object(tag) previous_tags = Tag.get_tags(obj) err_uniq = check_item_type_uniqueness(tag, previous_tags) err_appl = check_field_applicability(tag) err_mult = check_field_multiplicity(tag, previous_tags) err_msg = generate_error_message(tag, err_uniq, err_appl, err_mult) if err_uniq or err_appl or err_mult: raise TypeError(err_msg)
[ "def", "check_save", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "tag", "=", "kwargs", "[", "'instance'", "]", "obj", "=", "Tag", ".", "get_object", "(", "tag", ")", "previous_tags", "=", "Tag", ".", "get_tags", "(", "obj", ")", "err_uniq", "="...
Checks item type uniqueness, field applicability and multiplicity.
[ "Checks", "item", "type", "uniqueness", "field", "applicability", "and", "multiplicity", "." ]
python
train
37.357143
kwikteam/phy
phy/traces/waveform.py
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/traces/waveform.py#L271-L337
def get(self, spike_ids, channels=None): """Load the waveforms of the specified spikes.""" if isinstance(spike_ids, slice): spike_ids = _range_from_slice(spike_ids, start=0, stop=self.n_spikes, ) if not hasattr(spike_ids, '__len__'): spike_ids = [spike_ids] if channels is None: channels = slice(None, None, None) nc = self.n_channels else: channels = np.asarray(channels, dtype=np.int32) assert np.all(channels < self.n_channels) nc = len(channels) # Ensure a list of time samples are being requested. spike_ids = _as_array(spike_ids) n_spikes = len(spike_ids) # Initialize the array. # NOTE: last dimension is time to simplify things. shape = (n_spikes, nc, self._n_samples_extract) waveforms = np.zeros(shape, dtype=np.float32) # No traces: return null arrays. if self.n_samples_trace == 0: return np.transpose(waveforms, (0, 2, 1)) # Load all spikes. for i, spike_id in enumerate(spike_ids): assert 0 <= spike_id < self.n_spikes time = self._spike_samples[spike_id] # Extract the waveforms on the unmasked channels. try: w = self._load_at(time, channels) except ValueError as e: # pragma: no cover logger.warn("Error while loading waveform: %s", str(e)) continue assert w.shape == (self._n_samples_extract, nc) waveforms[i, :, :] = w.T # Filter the waveforms. waveforms_f = waveforms.reshape((-1, self._n_samples_extract)) # Only filter the non-zero waveforms. unmasked = waveforms_f.max(axis=1) != 0 waveforms_f[unmasked] = self._filter(waveforms_f[unmasked], axis=1) waveforms_f = waveforms_f.reshape((n_spikes, nc, self._n_samples_extract)) # Remove the margin. margin_before, margin_after = self._filter_margin if margin_after > 0: assert margin_before >= 0 waveforms_f = waveforms_f[:, :, margin_before:-margin_after] assert waveforms_f.shape == (n_spikes, nc, self.n_samples_waveforms, ) # NOTE: we transpose before returning the array. return np.transpose(waveforms_f, (0, 2, 1))
[ "def", "get", "(", "self", ",", "spike_ids", ",", "channels", "=", "None", ")", ":", "if", "isinstance", "(", "spike_ids", ",", "slice", ")", ":", "spike_ids", "=", "_range_from_slice", "(", "spike_ids", ",", "start", "=", "0", ",", "stop", "=", "self"...
Load the waveforms of the specified spikes.
[ "Load", "the", "waveforms", "of", "the", "specified", "spikes", "." ]
python
train
38.686567
tensorflow/mesh
mesh_tensorflow/ops.py
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3875-L3894
def top_1(x, reduced_dim, dtype=tf.int32, name=None): """Argmax and Max. Args: x: a Tensor reduced_dim: a Dimension in x.shape.dims dtype: a tf.dtype (for the output) name: an optional string Returns: indices: a Tensor with given dtype values: optional Tensor equal to mtf.reduce_max(x, reduced_dim=reduced_dim) """ reduced_dim = convert_to_dimension(reduced_dim) with tf.name_scope(name, default_name="top_1"): max_val = reduce_max(x, reduced_dim=reduced_dim) is_max = to_float(equal(x, max_val)) pos = mtf_range(x.mesh, reduced_dim, tf.float32) ret = reduce_max(is_max * pos, reduced_dim=reduced_dim) ret = cast(ret, dtype) return ret, max_val
[ "def", "top_1", "(", "x", ",", "reduced_dim", ",", "dtype", "=", "tf", ".", "int32", ",", "name", "=", "None", ")", ":", "reduced_dim", "=", "convert_to_dimension", "(", "reduced_dim", ")", "with", "tf", ".", "name_scope", "(", "name", ",", "default_name...
Argmax and Max. Args: x: a Tensor reduced_dim: a Dimension in x.shape.dims dtype: a tf.dtype (for the output) name: an optional string Returns: indices: a Tensor with given dtype values: optional Tensor equal to mtf.reduce_max(x, reduced_dim=reduced_dim)
[ "Argmax", "and", "Max", "." ]
python
train
34.35
akissa/spamc
setup.py
https://github.com/akissa/spamc/blob/da50732e276f7ed3d67cb75c31cb017d6a62f066/setup.py#L59-L91
def main(): """Main""" lic = ( 'License :: OSI Approved :: GNU Affero ' 'General Public License v3 or later (AGPLv3+)') version = load_source("version", os.path.join("spamc", "version.py")) opts = dict( name="spamc", version=version.__version__, description="Python spamassassin spamc client library", long_description=get_readme(), keywords="spam spamc spamassassin", author="Andrew Colin Kissa", author_email="andrew@topdog.za.net", url="https://github.com/akissa/spamc", license="AGPLv3+", packages=find_packages(exclude=['tests']), include_package_data=True, zip_safe=False, tests_require=TESTS_REQUIRE, install_requires=INSTALL_REQUIRES, classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', 'Intended Audience :: Developers', lic, 'Natural Language :: English', 'Operating System :: OS Independent'],) setup(**opts)
[ "def", "main", "(", ")", ":", "lic", "=", "(", "'License :: OSI Approved :: GNU Affero '", "'General Public License v3 or later (AGPLv3+)'", ")", "version", "=", "load_source", "(", "\"version\"", ",", "os", ".", "path", ".", "join", "(", "\"spamc\"", ",", "\"versio...
Main
[ "Main" ]
python
train
37.212121
python-bugzilla/python-bugzilla
bugzilla/_cli.py
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/_cli.py#L77-L97
def open_without_clobber(name, *args): """ Try to open the given file with the given mode; if that filename exists, try "name.1", "name.2", etc. until we find an unused filename. """ fd = None count = 1 orig_name = name while fd is None: try: fd = os.open(name, os.O_CREAT | os.O_EXCL, 0o666) except OSError as err: if err.errno == errno.EEXIST: name = "%s.%i" % (orig_name, count) count += 1 else: raise IOError(err.errno, err.strerror, err.filename) fobj = open(name, *args) if fd != fobj.fileno(): os.close(fd) return fobj
[ "def", "open_without_clobber", "(", "name", ",", "*", "args", ")", ":", "fd", "=", "None", "count", "=", "1", "orig_name", "=", "name", "while", "fd", "is", "None", ":", "try", ":", "fd", "=", "os", ".", "open", "(", "name", ",", "os", ".", "O_CR...
Try to open the given file with the given mode; if that filename exists, try "name.1", "name.2", etc. until we find an unused filename.
[ "Try", "to", "open", "the", "given", "file", "with", "the", "given", "mode", ";", "if", "that", "filename", "exists", "try", "name", ".", "1", "name", ".", "2", "etc", ".", "until", "we", "find", "an", "unused", "filename", "." ]
python
train
31.285714
google/grumpy
third_party/stdlib/difflib.py
https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L295-L319
def set_seq1(self, a): """Set the first sequence to be compared. The second sequence to be compared is not changed. >>> s = SequenceMatcher(None, "abcd", "bcde") >>> s.ratio() 0.75 >>> s.set_seq1("bcde") >>> s.ratio() 1.0 >>> SequenceMatcher computes and caches detailed information about the second sequence, so if you want to compare one sequence S against many sequences, use .set_seq2(S) once and call .set_seq1(x) repeatedly for each of the other sequences. See also set_seqs() and set_seq2(). """ if a is self.a: return self.a = a self.matching_blocks = self.opcodes = None
[ "def", "set_seq1", "(", "self", ",", "a", ")", ":", "if", "a", "is", "self", ".", "a", ":", "return", "self", ".", "a", "=", "a", "self", ".", "matching_blocks", "=", "self", ".", "opcodes", "=", "None" ]
Set the first sequence to be compared. The second sequence to be compared is not changed. >>> s = SequenceMatcher(None, "abcd", "bcde") >>> s.ratio() 0.75 >>> s.set_seq1("bcde") >>> s.ratio() 1.0 >>> SequenceMatcher computes and caches detailed information about the second sequence, so if you want to compare one sequence S against many sequences, use .set_seq2(S) once and call .set_seq1(x) repeatedly for each of the other sequences. See also set_seqs() and set_seq2().
[ "Set", "the", "first", "sequence", "to", "be", "compared", "." ]
python
valid
28.64
ryanvarley/ExoData
exodata/assumptions.py
https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/assumptions.py#L82-L92
def planetRadiusType(radius): """ Returns the planet radiustype given the mass and using planetAssumptions['radiusType'] """ if radius is np.nan: return None for radiusLimit, radiusType in planetAssumptions['radiusType']: if radius < radiusLimit: return radiusType
[ "def", "planetRadiusType", "(", "radius", ")", ":", "if", "radius", "is", "np", ".", "nan", ":", "return", "None", "for", "radiusLimit", ",", "radiusType", "in", "planetAssumptions", "[", "'radiusType'", "]", ":", "if", "radius", "<", "radiusLimit", ":", "...
Returns the planet radiustype given the mass and using planetAssumptions['radiusType']
[ "Returns", "the", "planet", "radiustype", "given", "the", "mass", "and", "using", "planetAssumptions", "[", "radiusType", "]" ]
python
train
27.363636
gforcada/haproxy_log_analysis
haproxy/logfile.py
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L406-L419
def _sort_lines(self): """Haproxy writes its logs after having gathered all information related to each specific connection. A simple request can be really quick but others can be really slow, thus even if one connection is logged later, it could have been accepted before others that are already processed and logged. This method sorts all valid log lines by their acceptance date, providing the real order in which connections where made to the server. """ self._valid_lines = sorted( self._valid_lines, key=lambda line: line.accept_date, )
[ "def", "_sort_lines", "(", "self", ")", ":", "self", ".", "_valid_lines", "=", "sorted", "(", "self", ".", "_valid_lines", ",", "key", "=", "lambda", "line", ":", "line", ".", "accept_date", ",", ")" ]
Haproxy writes its logs after having gathered all information related to each specific connection. A simple request can be really quick but others can be really slow, thus even if one connection is logged later, it could have been accepted before others that are already processed and logged. This method sorts all valid log lines by their acceptance date, providing the real order in which connections where made to the server.
[ "Haproxy", "writes", "its", "logs", "after", "having", "gathered", "all", "information", "related", "to", "each", "specific", "connection", ".", "A", "simple", "request", "can", "be", "really", "quick", "but", "others", "can", "be", "really", "slow", "thus", ...
python
train
45.285714
numenta/nupic
src/nupic/swarming/exp_generator/experiment_generator.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/exp_generator/experiment_generator.py#L1619-L1649
def _generateMetricsSubstitutions(options, tokenReplacements): """Generate the token substitution for metrics related fields. This includes: \$METRICS \$LOGGED_METRICS \$PERM_OPTIMIZE_SETTING """ # ----------------------------------------------------------------------- # options['loggedMetrics'] = [".*"] # ----------------------------------------------------------------------- # Generate the required metrics metricList, optimizeMetricLabel = _generateMetricSpecs(options) metricListString = ",\n".join(metricList) metricListString = _indentLines(metricListString, 2, indentFirstLine=False) permOptimizeSettingStr = 'minimize = "%s"' % optimizeMetricLabel # ----------------------------------------------------------------------- # Specify which metrics should be logged loggedMetricsListAsStr = "[%s]" % (", ".join(["'%s'"% ptrn for ptrn in options['loggedMetrics']])) tokenReplacements['\$LOGGED_METRICS'] \ = loggedMetricsListAsStr tokenReplacements['\$METRICS'] = metricListString tokenReplacements['\$PERM_OPTIMIZE_SETTING'] \ = permOptimizeSettingStr
[ "def", "_generateMetricsSubstitutions", "(", "options", ",", "tokenReplacements", ")", ":", "# -----------------------------------------------------------------------", "#", "options", "[", "'loggedMetrics'", "]", "=", "[", "\".*\"", "]", "# --------------------------------------...
Generate the token substitution for metrics related fields. This includes: \$METRICS \$LOGGED_METRICS \$PERM_OPTIMIZE_SETTING
[ "Generate", "the", "token", "substitution", "for", "metrics", "related", "fields", ".", "This", "includes", ":", "\\", "$METRICS", "\\", "$LOGGED_METRICS", "\\", "$PERM_OPTIMIZE_SETTING" ]
python
valid
39
getpelican/pelican-plugins
liquid_tags/giphy.py
https://github.com/getpelican/pelican-plugins/blob/cfc7a3f224f1743063b034561f89a6a712d13587/liquid_tags/giphy.py#L59-L74
def main(api_key, markup): '''Doing the regex parsing and running the create_html function.''' match = GIPHY.search(markup) attrs = None if match: attrs = dict( [(key, value.strip()) for (key, value) in match.groupdict().items() if value]) else: raise ValueError('Error processing input. ' 'Expected syntax: {}'.format(SYNTAX)) return create_html(api_key, attrs)
[ "def", "main", "(", "api_key", ",", "markup", ")", ":", "match", "=", "GIPHY", ".", "search", "(", "markup", ")", "attrs", "=", "None", "if", "match", ":", "attrs", "=", "dict", "(", "[", "(", "key", ",", "value", ".", "strip", "(", ")", ")", "...
Doing the regex parsing and running the create_html function.
[ "Doing", "the", "regex", "parsing", "and", "running", "the", "create_html", "function", "." ]
python
train
27.5625
clalancette/pycdlib
pycdlib/dr.py
https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/dr.py#L516-L541
def new_file(self, vd, length, isoname, parent, seqnum, rock_ridge, rr_name, xa, file_mode): # type: (headervd.PrimaryOrSupplementaryVD, int, bytes, DirectoryRecord, int, str, bytes, bool, int) -> None ''' Create a new file Directory Record. Parameters: vd - The Volume Descriptor this record is part of. length - The length of the data. isoname - The name for this directory record. parent - The parent of this directory record. seqnum - The sequence number for this directory record. rock_ridge - Whether to make this a Rock Ridge directory record. rr_name - The Rock Ridge name for this directory record. xa - True if this is an Extended Attribute record. file_mode - The POSIX file mode for this entry. Returns: Nothing. ''' if self._initialized: raise pycdlibexception.PyCdlibInternalError('Directory Record already initialized') self._new(vd, isoname, parent, seqnum, False, length, xa) if rock_ridge: self._rr_new(rock_ridge, rr_name, b'', False, False, False, file_mode)
[ "def", "new_file", "(", "self", ",", "vd", ",", "length", ",", "isoname", ",", "parent", ",", "seqnum", ",", "rock_ridge", ",", "rr_name", ",", "xa", ",", "file_mode", ")", ":", "# type: (headervd.PrimaryOrSupplementaryVD, int, bytes, DirectoryRecord, int, str, bytes,...
Create a new file Directory Record. Parameters: vd - The Volume Descriptor this record is part of. length - The length of the data. isoname - The name for this directory record. parent - The parent of this directory record. seqnum - The sequence number for this directory record. rock_ridge - Whether to make this a Rock Ridge directory record. rr_name - The Rock Ridge name for this directory record. xa - True if this is an Extended Attribute record. file_mode - The POSIX file mode for this entry. Returns: Nothing.
[ "Create", "a", "new", "file", "Directory", "Record", "." ]
python
train
45.5
Becksteinlab/GromacsWrapper
gromacs/setup.py
https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/setup.py#L317-L359
def get_lipid_vdwradii(outdir=os.path.curdir, libdir=None): """Find vdwradii.dat and add special entries for lipids. See :data:`gromacs.setup.vdw_lipid_resnames` for lipid resnames. Add more if necessary. """ vdwradii_dat = os.path.join(outdir, "vdwradii.dat") if libdir is not None: filename = os.path.join(libdir, 'vdwradii.dat') # canonical name if not os.path.exists(filename): msg = 'No VDW database file found in {filename!r}.'.format(**vars()) logger.exception(msg) raise OSError(msg, errno.ENOENT) else: try: filename = os.path.join(os.environ['GMXLIB'], 'vdwradii.dat') except KeyError: try: filename = os.path.join(os.environ['GMXDATA'], 'top', 'vdwradii.dat') except KeyError: msg = "Cannot find vdwradii.dat. Set GMXLIB (point to 'top') or GMXDATA ('share/gromacs')." logger.exception(msg) raise OSError(msg, errno.ENOENT) if not os.path.exists(filename): msg = "Cannot find {filename!r}; something is wrong with the Gromacs installation.".format(**vars()) logger.exception(msg, errno.ENOENT) raise OSError(msg) # make sure to catch 3 and 4 letter resnames patterns = vdw_lipid_resnames + list({x[:3] for x in vdw_lipid_resnames}) # TODO: should do a tempfile... with open(vdwradii_dat, 'w') as outfile: # write lipid stuff before general outfile.write('; Special larger vdw radii for solvating lipid membranes\n') for resname in patterns: for atom,radius in vdw_lipid_atom_radii.items(): outfile.write('{resname:4!s} {atom:<5!s} {radius:5.3f}\n'.format(**vars())) with open(filename, 'r') as infile: for line in infile: outfile.write(line) logger.debug('Created lipid vdW radii file {vdwradii_dat!r}.'.format(**vars())) return realpath(vdwradii_dat)
[ "def", "get_lipid_vdwradii", "(", "outdir", "=", "os", ".", "path", ".", "curdir", ",", "libdir", "=", "None", ")", ":", "vdwradii_dat", "=", "os", ".", "path", ".", "join", "(", "outdir", ",", "\"vdwradii.dat\"", ")", "if", "libdir", "is", "not", "Non...
Find vdwradii.dat and add special entries for lipids. See :data:`gromacs.setup.vdw_lipid_resnames` for lipid resnames. Add more if necessary.
[ "Find", "vdwradii", ".", "dat", "and", "add", "special", "entries", "for", "lipids", "." ]
python
valid
45.581395
bitesofcode/projexui
projexui/widgets/xnodewidget/xnode.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnode.py#L196-L224
def adjustTitleFont(self): """ Adjusts the font used for the title based on the current with and \ display name. """ left, top, right, bottom = self.contentsMargins() r = self.roundingRadius() # include text padding left += 5 + r / 2 top += 5 + r / 2 right += 5 + r / 2 bottom += 5 + r / 2 r = self.rect() rect_l = r.left() + left rect_r = r.right() - right rect_t = r.top() + top rect_b = r.bottom() - bottom # ensure we have a valid rect rect = QRect(rect_l, rect_t, rect_r - rect_l, rect_b - rect_t) if rect.width() < 10: return font = XFont(QApplication.font()) font.adaptSize(self.displayName(), rect, wordWrap=self.wordWrap()) self._titleFont = font
[ "def", "adjustTitleFont", "(", "self", ")", ":", "left", ",", "top", ",", "right", ",", "bottom", "=", "self", ".", "contentsMargins", "(", ")", "r", "=", "self", ".", "roundingRadius", "(", ")", "# include text padding", "left", "+=", "5", "+", "r", "...
Adjusts the font used for the title based on the current with and \ display name.
[ "Adjusts", "the", "font", "used", "for", "the", "title", "based", "on", "the", "current", "with", "and", "\\", "display", "name", "." ]
python
train
29.655172
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L3873-L3885
def freeze(self): """ Freeze (disable) all settings """ for fields in zip(self.xsll, self.xsul, self.xslr, self.xsur, self.ys, self.nx, self.ny): for field in fields: field.disable() self.nquad.disable() self.xbin.disable() self.ybin.disable() self.sbutt.disable() self.frozen = True
[ "def", "freeze", "(", "self", ")", ":", "for", "fields", "in", "zip", "(", "self", ".", "xsll", ",", "self", ".", "xsul", ",", "self", ".", "xslr", ",", "self", ".", "xsur", ",", "self", ".", "ys", ",", "self", ".", "nx", ",", "self", ".", "n...
Freeze (disable) all settings
[ "Freeze", "(", "disable", ")", "all", "settings" ]
python
train
30.538462
BernardFW/bernard
src/bernard/middleware/_builtins.py
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/middleware/_builtins.py#L121-L146
async def expand(self, request: Request, layer: BaseLayer): """ Expand a layer into a list of layers including the pauses. """ if isinstance(layer, lyr.RawText): t = self.reading_time(layer.text) yield layer yield lyr.Sleep(t) elif isinstance(layer, lyr.MultiText): texts = await render(layer.text, request, True) for text in texts: t = self.reading_time(text) yield lyr.RawText(text) yield lyr.Sleep(t) elif isinstance(layer, lyr.Text): text = await render(layer.text, request) t = self.reading_time(text) yield lyr.RawText(text) yield lyr.Sleep(t) else: yield layer
[ "async", "def", "expand", "(", "self", ",", "request", ":", "Request", ",", "layer", ":", "BaseLayer", ")", ":", "if", "isinstance", "(", "layer", ",", "lyr", ".", "RawText", ")", ":", "t", "=", "self", ".", "reading_time", "(", "layer", ".", "text",...
Expand a layer into a list of layers including the pauses.
[ "Expand", "a", "layer", "into", "a", "list", "of", "layers", "including", "the", "pauses", "." ]
python
train
29.653846
XuShaohua/bcloud
bcloud/CloudPage.py
https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/CloudPage.py#L260-L311
def add_cloud_bt_task(self, source_url, save_path=None): '''从服务器上获取种子, 并建立离线下载任务 source_url - BT 种子在服务器上的绝对路径, 或者是磁链的地址. save_path - 要保存到的路径, 如果为None, 就会弹出目录选择的对话框 ''' def check_vcode(info, error=None): if error or not info: logger.error('CloudPage.check_vcode: %s, %s' % (info, error)) return if info.get('error_code', -1) != 0: logger.error('CloudPage.check_vcode: %s, %s' % (info, error)) if 'task_id' in info or info['error_code'] == 0: self.reload() elif info['error_code'] == -19: vcode_dialog = VCodeDialog(self, self.app, info) response = vcode_dialog.run() vcode_input = vcode_dialog.get_vcode() vcode_dialog.destroy() if response != Gtk.ResponseType.OK: return gutil.async_call(pcs.cloud_add_bt_task, self.app.cookie, self.app.tokens, source_url, save_path, selected_idx, file_sha1, info['vcode'], vcode_input, callback=check_vcode) else: self.app.toast(_('Error: {0}').format(info['error_msg'])) self.check_first() if not save_path: folder_browser = FolderBrowserDialog(self, self.app, _('Save to..')) response = folder_browser.run() save_path = folder_browser.get_path() folder_browser.destroy() if response != Gtk.ResponseType.OK: return if not save_path: return bt_browser = BTBrowserDialog(self, self.app, _('Choose..'), source_url, save_path) response = bt_browser.run() selected_idx, file_sha1 = bt_browser.get_selected() bt_browser.destroy() if response != Gtk.ResponseType.OK or not selected_idx: return gutil.async_call(pcs.cloud_add_bt_task, self.app.cookie, self.app.tokens, source_url, save_path, selected_idx, file_sha1, callback=check_vcode) self.app.blink_page(self.app.cloud_page)
[ "def", "add_cloud_bt_task", "(", "self", ",", "source_url", ",", "save_path", "=", "None", ")", ":", "def", "check_vcode", "(", "info", ",", "error", "=", "None", ")", ":", "if", "error", "or", "not", "info", ":", "logger", ".", "error", "(", "'CloudPa...
从服务器上获取种子, 并建立离线下载任务 source_url - BT 种子在服务器上的绝对路径, 或者是磁链的地址. save_path - 要保存到的路径, 如果为None, 就会弹出目录选择的对话框
[ "从服务器上获取种子", "并建立离线下载任务" ]
python
train
42.769231
bcbio/bcbio-nextgen
bcbio/utils.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L708-L725
def R_package_path(package): """ return the path to an installed R package """ local_sitelib = R_sitelib() rscript = Rscript_cmd() cmd = """{rscript} --no-environ -e '.libPaths(c("{local_sitelib}")); find.package("{package}")'""" try: output = subprocess.check_output(cmd.format(**locals()), shell=True) except subprocess.CalledProcessError as e: return None for line in output.decode().split("\n"): if "[1]" not in line: continue dirname = line.split("[1]")[1].replace("\"", "").strip() if os.path.exists(dirname): return dirname return None
[ "def", "R_package_path", "(", "package", ")", ":", "local_sitelib", "=", "R_sitelib", "(", ")", "rscript", "=", "Rscript_cmd", "(", ")", "cmd", "=", "\"\"\"{rscript} --no-environ -e '.libPaths(c(\"{local_sitelib}\")); find.package(\"{package}\")'\"\"\"", "try", ":", "output...
return the path to an installed R package
[ "return", "the", "path", "to", "an", "installed", "R", "package" ]
python
train
34.944444
mozilla-iot/webthing-python
webthing/action.py
https://github.com/mozilla-iot/webthing-python/blob/65d467c89ed79d0bbc42b8b3c8f9e5a320edd237/webthing/action.py#L90-L95
def start(self): """Start performing the action.""" self.status = 'pending' self.thing.action_notify(self) self.perform_action() self.finish()
[ "def", "start", "(", "self", ")", ":", "self", ".", "status", "=", "'pending'", "self", ".", "thing", ".", "action_notify", "(", "self", ")", "self", ".", "perform_action", "(", ")", "self", ".", "finish", "(", ")" ]
Start performing the action.
[ "Start", "performing", "the", "action", "." ]
python
test
29.5
datascopeanalytics/traces
setup.py
https://github.com/datascopeanalytics/traces/blob/420611151a05fea88a07bc5200fefffdc37cc95b/setup.py#L7-L23
def read_init(key): """Parse the package __init__ file to find a variable so that it's not in multiple places. """ filename = os.path.join("traces", "__init__.py") result = None with open(filename) as stream: for line in stream: if key in line: result = line.split('=')[-1].strip().replace("'", "") # throw error if version isn't in __init__ file if result is None: raise ValueError('must define %s in %s' % (key, filename)) return result
[ "def", "read_init", "(", "key", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "\"traces\"", ",", "\"__init__.py\"", ")", "result", "=", "None", "with", "open", "(", "filename", ")", "as", "stream", ":", "for", "line", "in", "stream", ...
Parse the package __init__ file to find a variable so that it's not in multiple places.
[ "Parse", "the", "package", "__init__", "file", "to", "find", "a", "variable", "so", "that", "it", "s", "not", "in", "multiple", "places", "." ]
python
train
29.705882
wtsi-hgi/python-common
hgicommon/helpers.py
https://github.com/wtsi-hgi/python-common/blob/0376a6b574ff46e82e509e90b6cb3693a3dbb577/hgicommon/helpers.py#L19-L31
def get_open_port() -> int: """ Gets a PORT that will (probably) be available on the machine. It is possible that in-between the time in which the open PORT of found and when it is used, another process may bind to it instead. :return: the (probably) available PORT """ free_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) free_socket.bind(("", 0)) free_socket.listen(1) port = free_socket.getsockname()[1] free_socket.close() return port
[ "def", "get_open_port", "(", ")", "->", "int", ":", "free_socket", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "free_socket", ".", "bind", "(", "(", "\"\"", ",", "0", ")", ")", "free_socket", "."...
Gets a PORT that will (probably) be available on the machine. It is possible that in-between the time in which the open PORT of found and when it is used, another process may bind to it instead. :return: the (probably) available PORT
[ "Gets", "a", "PORT", "that", "will", "(", "probably", ")", "be", "available", "on", "the", "machine", ".", "It", "is", "possible", "that", "in", "-", "between", "the", "time", "in", "which", "the", "open", "PORT", "of", "found", "and", "when", "it", ...
python
valid
37.307692
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/werkzeug/urls.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/werkzeug/urls.py#L548-L576
def url_fix(s, charset='utf-8'): r"""Sometimes you get an URL by a user that just isn't a real URL because it contains unsafe characters like ' ' and so on. This function can fix some of the problems in a similar way browsers handle data entered by the user: >>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)') 'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)' :param s: the string with the URL to fix. :param charset: The target charset for the URL if the url was given as unicode string. """ # First step is to switch to unicode processing and to convert # backslashes (which are invalid in URLs anyways) to slashes. This is # consistent with what Chrome does. s = to_unicode(s, charset, 'replace').replace('\\', '/') # For the specific case that we look like a malformed windows URL # we want to fix this up manually: if s.startswith('file://') and s[7:8].isalpha() and s[8:10] in (':/', '|/'): s = 'file:///' + s[7:] url = url_parse(s) path = url_quote(url.path, charset, safe='/%+$!*\'(),') qs = url_quote_plus(url.query, charset, safe=':&%=+$!*\'(),') anchor = url_quote_plus(url.fragment, charset, safe=':&%=+$!*\'(),') return to_native(url_unparse((url.scheme, url.encode_netloc(), path, qs, anchor)))
[ "def", "url_fix", "(", "s", ",", "charset", "=", "'utf-8'", ")", ":", "# First step is to switch to unicode processing and to convert", "# backslashes (which are invalid in URLs anyways) to slashes. This is", "# consistent with what Chrome does.", "s", "=", "to_unicode", "(", "s",...
r"""Sometimes you get an URL by a user that just isn't a real URL because it contains unsafe characters like ' ' and so on. This function can fix some of the problems in a similar way browsers handle data entered by the user: >>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)') 'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)' :param s: the string with the URL to fix. :param charset: The target charset for the URL if the url was given as unicode string.
[ "r", "Sometimes", "you", "get", "an", "URL", "by", "a", "user", "that", "just", "isn", "t", "a", "real", "URL", "because", "it", "contains", "unsafe", "characters", "like", "and", "so", "on", ".", "This", "function", "can", "fix", "some", "of", "the", ...
python
test
46.896552
explorigin/Rocket
rocket/methods/wsgi.py
https://github.com/explorigin/Rocket/blob/53313677768159d13e6c2b7c69ad69ca59bb8c79/rocket/methods/wsgi.py#L62-L102
def build_environ(self, sock_file, conn): """ Build the execution environment. """ # Grab the request line request = self.read_request_line(sock_file) # Copy the Base Environment environ = self.base_environ.copy() # Grab the headers for k, v in self.read_headers(sock_file).items(): environ[str('HTTP_'+k)] = v # Add CGI Variables environ['REQUEST_METHOD'] = request['method'] environ['PATH_INFO'] = request['path'] environ['SERVER_PROTOCOL'] = request['protocol'] environ['SERVER_PORT'] = str(conn.server_port) environ['REMOTE_PORT'] = str(conn.client_port) environ['REMOTE_ADDR'] = str(conn.client_addr) environ['QUERY_STRING'] = request['query_string'] if 'HTTP_CONTENT_LENGTH' in environ: environ['CONTENT_LENGTH'] = environ['HTTP_CONTENT_LENGTH'] if 'HTTP_CONTENT_TYPE' in environ: environ['CONTENT_TYPE'] = environ['HTTP_CONTENT_TYPE'] # Save the request method for later self.request_method = environ['REQUEST_METHOD'] # Add Dynamic WSGI Variables if conn.ssl: environ['wsgi.url_scheme'] = 'https' environ['HTTPS'] = 'on' else: environ['wsgi.url_scheme'] = 'http' if environ.get('HTTP_TRANSFER_ENCODING', '') == 'chunked': environ['wsgi.input'] = ChunkedReader(sock_file) else: environ['wsgi.input'] = sock_file return environ
[ "def", "build_environ", "(", "self", ",", "sock_file", ",", "conn", ")", ":", "# Grab the request line", "request", "=", "self", ".", "read_request_line", "(", "sock_file", ")", "# Copy the Base Environment", "environ", "=", "self", ".", "base_environ", ".", "copy...
Build the execution environment.
[ "Build", "the", "execution", "environment", "." ]
python
valid
36.487805
IRC-SPHERE/HyperStream
hyperstream/utils/statistics/percentile.py
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/utils/statistics/percentile.py#L33-L90
def percentile(a, q): """ Compute the qth percentile of the data along the specified axis. Simpler version than the numpy version that always flattens input arrays. Examples -------- >>> a = [[10, 7, 4], [3, 2, 1]] >>> percentile(a, 20) 2.0 >>> percentile(a, 50) 3.5 >>> percentile(a, [20, 80]) [2.0, 7.0] >>> a = list(range(40)) >>> percentile(a, 25) 9.75 :param a: Input array or object that can be converted to an array. :param q: Percentile to compute, which must be between 0 and 100 inclusive. :return: the qth percentile(s) of the array elements. """ if not a: return None if isinstance(q, (float, int)): qq = [q] elif isinstance(q, (tuple, list)): qq = q else: raise ValueError("Quantile type {} not understood".format(type(q))) if isinstance(a, (float, int)): a = [a] for i in range(len(qq)): if qq[i] < 0. or qq[i] > 100.: raise ValueError("Percentiles must be in the range [0,100]") qq[i] /= 100. a = sorted(flatten(a)) r = [] for q in qq: k = (len(a) - 1) * q f = math.floor(k) c = math.ceil(k) if f == c: r.append(float(a[int(k)])) continue d0 = a[int(f)] * (c - k) d1 = a[int(c)] * (k - f) r.append(float(d0 + d1)) if len(r) == 1: return r[0] return r
[ "def", "percentile", "(", "a", ",", "q", ")", ":", "if", "not", "a", ":", "return", "None", "if", "isinstance", "(", "q", ",", "(", "float", ",", "int", ")", ")", ":", "qq", "=", "[", "q", "]", "elif", "isinstance", "(", "q", ",", "(", "tuple...
Compute the qth percentile of the data along the specified axis. Simpler version than the numpy version that always flattens input arrays. Examples -------- >>> a = [[10, 7, 4], [3, 2, 1]] >>> percentile(a, 20) 2.0 >>> percentile(a, 50) 3.5 >>> percentile(a, [20, 80]) [2.0, 7.0] >>> a = list(range(40)) >>> percentile(a, 25) 9.75 :param a: Input array or object that can be converted to an array. :param q: Percentile to compute, which must be between 0 and 100 inclusive. :return: the qth percentile(s) of the array elements.
[ "Compute", "the", "qth", "percentile", "of", "the", "data", "along", "the", "specified", "axis", ".", "Simpler", "version", "than", "the", "numpy", "version", "that", "always", "flattens", "input", "arrays", "." ]
python
train
24.017241
quantopian/zipline
zipline/assets/asset_writer.py
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/assets/asset_writer.py#L335-L368
def _split_symbol_mappings(df, exchanges): """Split out the symbol: sid mappings from the raw data. Parameters ---------- df : pd.DataFrame The dataframe with multiple rows for each symbol: sid pair. exchanges : pd.DataFrame The exchanges table. Returns ------- asset_info : pd.DataFrame The asset info with one row per asset. symbol_mappings : pd.DataFrame The dataframe of just symbol: sid mappings. The index will be the sid, then there will be three columns: symbol, start_date, and end_date. """ mappings = df[list(mapping_columns)] with pd.option_context('mode.chained_assignment', None): mappings['sid'] = mappings.index mappings.reset_index(drop=True, inplace=True) # take the most recent sid->exchange mapping based on end date asset_exchange = df[ ['exchange', 'end_date'] ].sort_values('end_date').groupby(level=0)['exchange'].nth(-1) _check_symbol_mappings(mappings, exchanges, asset_exchange) return ( df.groupby(level=0).apply(_check_asset_group), mappings, )
[ "def", "_split_symbol_mappings", "(", "df", ",", "exchanges", ")", ":", "mappings", "=", "df", "[", "list", "(", "mapping_columns", ")", "]", "with", "pd", ".", "option_context", "(", "'mode.chained_assignment'", ",", "None", ")", ":", "mappings", "[", "'sid...
Split out the symbol: sid mappings from the raw data. Parameters ---------- df : pd.DataFrame The dataframe with multiple rows for each symbol: sid pair. exchanges : pd.DataFrame The exchanges table. Returns ------- asset_info : pd.DataFrame The asset info with one row per asset. symbol_mappings : pd.DataFrame The dataframe of just symbol: sid mappings. The index will be the sid, then there will be three columns: symbol, start_date, and end_date.
[ "Split", "out", "the", "symbol", ":", "sid", "mappings", "from", "the", "raw", "data", "." ]
python
train
32.352941
googleapis/google-auth-library-python
google/auth/_helpers.py
https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/_helpers.py#L108-L127
def from_bytes(value): """Converts bytes to a string value, if necessary. Args: value (Union[str, bytes]): The value to be converted. Returns: str: The original value converted to unicode (if bytes) or as passed in if it started out as unicode. Raises: ValueError: If the value could not be converted to unicode. """ result = (value.decode('utf-8') if isinstance(value, six.binary_type) else value) if isinstance(result, six.text_type): return result else: raise ValueError( '{0!r} could not be converted to unicode'.format(value))
[ "def", "from_bytes", "(", "value", ")", ":", "result", "=", "(", "value", ".", "decode", "(", "'utf-8'", ")", "if", "isinstance", "(", "value", ",", "six", ".", "binary_type", ")", "else", "value", ")", "if", "isinstance", "(", "result", ",", "six", ...
Converts bytes to a string value, if necessary. Args: value (Union[str, bytes]): The value to be converted. Returns: str: The original value converted to unicode (if bytes) or as passed in if it started out as unicode. Raises: ValueError: If the value could not be converted to unicode.
[ "Converts", "bytes", "to", "a", "string", "value", "if", "necessary", "." ]
python
train
31.25
brocade/pynos
pynos/versions/ver_7/ver_7_1_0/yang/brocade_fabric_service.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_fabric_service.py#L70-L84
def show_linkinfo_output_show_link_info_linkinfo_version(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_linkinfo = ET.Element("show_linkinfo") config = show_linkinfo output = ET.SubElement(show_linkinfo, "output") show_link_info = ET.SubElement(output, "show-link-info") linkinfo_rbridgeid_key = ET.SubElement(show_link_info, "linkinfo-rbridgeid") linkinfo_rbridgeid_key.text = kwargs.pop('linkinfo_rbridgeid') linkinfo_version = ET.SubElement(show_link_info, "linkinfo-version") linkinfo_version.text = kwargs.pop('linkinfo_version') callback = kwargs.pop('callback', self._callback) return callback(config)
[ "def", "show_linkinfo_output_show_link_info_linkinfo_version", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "show_linkinfo", "=", "ET", ".", "Element", "(", "\"show_linkinfo\"", ")", "config", "=", ...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
48.733333
dereneaton/ipyrad
ipyrad/assemble/write_outfiles.py
https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/write_outfiles.py#L1360-L1374
def maxind_numba(block): """ filter for indels """ ## remove terminal edges inds = 0 for row in xrange(block.shape[0]): where = np.where(block[row] != 45)[0] if len(where) == 0: obs = 100 else: left = np.min(where) right = np.max(where) obs = np.sum(block[row, left:right] == 45) if obs > inds: inds = obs return inds
[ "def", "maxind_numba", "(", "block", ")", ":", "## remove terminal edges", "inds", "=", "0", "for", "row", "in", "xrange", "(", "block", ".", "shape", "[", "0", "]", ")", ":", "where", "=", "np", ".", "where", "(", "block", "[", "row", "]", "!=", "...
filter for indels
[ "filter", "for", "indels" ]
python
valid
27.666667
callowayproject/django-categories
categories/admin.py
https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/admin.py#L18-L23
def label_from_instance(self, obj): """ Creates labels which represent the tree level of each node when generating option labels. """ return '%s %s' % (self.level_indicator * getattr(obj, obj._mptt_meta.level_attr), obj)
[ "def", "label_from_instance", "(", "self", ",", "obj", ")", ":", "return", "'%s %s'", "%", "(", "self", ".", "level_indicator", "*", "getattr", "(", "obj", ",", "obj", ".", "_mptt_meta", ".", "level_attr", ")", ",", "obj", ")" ]
Creates labels which represent the tree level of each node when generating option labels.
[ "Creates", "labels", "which", "represent", "the", "tree", "level", "of", "each", "node", "when", "generating", "option", "labels", "." ]
python
train
42.5
quantmind/dynts
dynts/api/operators.py
https://github.com/quantmind/dynts/blob/21ac57c648bfec402fa6b1fe569496cf098fb5e8/dynts/api/operators.py#L65-L72
def _toVec(shape, val): ''' takes a single value and creates a vecotor / matrix with that value filled in it ''' mat = np.empty(shape) mat.fill(val) return mat
[ "def", "_toVec", "(", "shape", ",", "val", ")", ":", "mat", "=", "np", ".", "empty", "(", "shape", ")", "mat", ".", "fill", "(", "val", ")", "return", "mat" ]
takes a single value and creates a vecotor / matrix with that value filled in it
[ "takes", "a", "single", "value", "and", "creates", "a", "vecotor", "/", "matrix", "with", "that", "value", "filled", "in", "it" ]
python
train
23.375
watson-developer-cloud/python-sdk
ibm_watson/discovery_v1.py
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/discovery_v1.py#L9147-L9154
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'exclude') and self.exclude is not None: _dict['exclude'] = self.exclude if hasattr(self, 'include') and self.include is not None: _dict['include'] = self.include return _dict
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'exclude'", ")", "and", "self", ".", "exclude", "is", "not", "None", ":", "_dict", "[", "'exclude'", "]", "=", "self", ".", "exclude", "if", "hasa...
Return a json dictionary representing this model.
[ "Return", "a", "json", "dictionary", "representing", "this", "model", "." ]
python
train
42
capless/warrant
warrant/__init__.py
https://github.com/capless/warrant/blob/ff2e4793d8479e770f2461ef7cbc0c15ee784395/warrant/__init__.py#L48-L54
def snake_to_camel(snake_str): """ :param snake_str: string :return: string converted from a snake_case to a CamelCase """ components = snake_str.split('_') return ''.join(x.title() for x in components)
[ "def", "snake_to_camel", "(", "snake_str", ")", ":", "components", "=", "snake_str", ".", "split", "(", "'_'", ")", "return", "''", ".", "join", "(", "x", ".", "title", "(", ")", "for", "x", "in", "components", ")" ]
:param snake_str: string :return: string converted from a snake_case to a CamelCase
[ ":", "param", "snake_str", ":", "string", ":", "return", ":", "string", "converted", "from", "a", "snake_case", "to", "a", "CamelCase" ]
python
train
31.428571
Erotemic/utool
utool/util_inspect.py
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inspect.py#L2201-L2219
def exec_func_src3(func, globals_, sentinal=None, verbose=False, start=None, stop=None): """ execs a func and returns requested local vars. Does not modify globals unless update=True (or in IPython) SeeAlso: ut.execstr_funckw """ import utool as ut sourcecode = ut.get_func_sourcecode(func, stripdef=True, stripret=True) if sentinal is not None: sourcecode = ut.replace_between_tags(sourcecode, '', sentinal) if start is not None or stop is not None: sourcecode = '\n'.join(sourcecode.splitlines()[slice(start, stop)]) if verbose: print(ut.color_text(sourcecode, 'python')) six.exec_(sourcecode, globals_)
[ "def", "exec_func_src3", "(", "func", ",", "globals_", ",", "sentinal", "=", "None", ",", "verbose", "=", "False", ",", "start", "=", "None", ",", "stop", "=", "None", ")", ":", "import", "utool", "as", "ut", "sourcecode", "=", "ut", ".", "get_func_sou...
execs a func and returns requested local vars. Does not modify globals unless update=True (or in IPython) SeeAlso: ut.execstr_funckw
[ "execs", "a", "func", "and", "returns", "requested", "local", "vars", "." ]
python
train
36
saltstack/salt
salt/modules/makeconf.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/makeconf.py#L202-L219
def var_contains(var, value): ''' Verify if variable contains a value in make.conf Return True if value is set for var CLI Example: .. code-block:: bash salt '*' makeconf.var_contains 'LINGUAS' 'en' ''' setval = get_var(var) # Remove any escaping that was needed to past through salt value = value.replace('\\', '') if setval is None: return False return value in setval.split()
[ "def", "var_contains", "(", "var", ",", "value", ")", ":", "setval", "=", "get_var", "(", "var", ")", "# Remove any escaping that was needed to past through salt", "value", "=", "value", ".", "replace", "(", "'\\\\'", ",", "''", ")", "if", "setval", "is", "Non...
Verify if variable contains a value in make.conf Return True if value is set for var CLI Example: .. code-block:: bash salt '*' makeconf.var_contains 'LINGUAS' 'en'
[ "Verify", "if", "variable", "contains", "a", "value", "in", "make", ".", "conf" ]
python
train
23.611111
Azure/azure-sdk-for-python
azure-servicebus/azure/servicebus/control_client/servicebusservice.py
https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicebus/azure/servicebus/control_client/servicebusservice.py#L1129-L1151
def update_event_hub(self, hub_name, hub=None): ''' Updates an Event Hub. hub_name: Name of event hub. hub: Optional. Event hub properties. Instance of EventHub class. hub.message_retention_in_days: Number of days to retain the events for this Event Hub. ''' _validate_not_none('hub_name', hub_name) request = HTTPRequest() request.method = 'PUT' request.host = self._get_host() request.path = '/' + _str(hub_name) + '?api-version=2014-01' request.body = _get_request_body(_convert_event_hub_to_xml(hub)) request.path, request.query = self._httpclient._update_request_uri_query(request) # pylint: disable=protected-access request.headers.append(('If-Match', '*')) request.headers = self._update_service_bus_header(request) response = self._perform_request(request) return _convert_response_to_event_hub(response)
[ "def", "update_event_hub", "(", "self", ",", "hub_name", ",", "hub", "=", "None", ")", ":", "_validate_not_none", "(", "'hub_name'", ",", "hub_name", ")", "request", "=", "HTTPRequest", "(", ")", "request", ".", "method", "=", "'PUT'", "request", ".", "hos...
Updates an Event Hub. hub_name: Name of event hub. hub: Optional. Event hub properties. Instance of EventHub class. hub.message_retention_in_days: Number of days to retain the events for this Event Hub.
[ "Updates", "an", "Event", "Hub", "." ]
python
test
41.956522
lrq3000/pyFileFixity
pyFileFixity/lib/profilers/visual/runsnakerun/runsnake.py
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/runsnakerun/runsnake.py#L542-L564
def OnUpView(self, event): """Request to move up the hierarchy to highest-weight parent""" node = self.activated_node parents = [] selected_parent = None if node: if hasattr( self.adapter, 'best_parent' ): selected_parent = self.adapter.best_parent( node ) else: parents = self.adapter.parents( node ) if parents: if not selected_parent: parents.sort(key = lambda a: self.adapter.value(node, a)) selected_parent = parents[-1] class event: node = selected_parent self.OnNodeActivated(event) else: self.SetStatusText(_('No parents for the currently selected node: %(node_name)s') % dict(node_name=self.adapter.label(node))) else: self.SetStatusText(_('No currently selected node'))
[ "def", "OnUpView", "(", "self", ",", "event", ")", ":", "node", "=", "self", ".", "activated_node", "parents", "=", "[", "]", "selected_parent", "=", "None", "if", "node", ":", "if", "hasattr", "(", "self", ".", "adapter", ",", "'best_parent'", ")", ":...
Request to move up the hierarchy to highest-weight parent
[ "Request", "to", "move", "up", "the", "hierarchy", "to", "highest", "-", "weight", "parent" ]
python
train
41.956522
gebn/nibble
nibble/decorators.py
https://github.com/gebn/nibble/blob/e82a2c43509ed38f3d039040591cc630fa676cb0/nibble/decorators.py#L9-L23
def operator_same_class(method): """ Intended to wrap operator methods, this decorator ensures the `other` parameter is of the same type as the `self` parameter. :param method: The method being decorated. :return: The wrapper to replace the method with. """ def wrapper(self, other): if not isinstance(other, self.__class__): raise TypeError( 'unsupported operand types: \'{0}\' and \'{1}\''.format( self.__class__.__name__, other.__class__.__name__)) return method(self, other) return wrapper
[ "def", "operator_same_class", "(", "method", ")", ":", "def", "wrapper", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", ":", "raise", "TypeError", "(", "'unsupported operand types: \\'{0}\\' an...
Intended to wrap operator methods, this decorator ensures the `other` parameter is of the same type as the `self` parameter. :param method: The method being decorated. :return: The wrapper to replace the method with.
[ "Intended", "to", "wrap", "operator", "methods", "this", "decorator", "ensures", "the", "other", "parameter", "is", "of", "the", "same", "type", "as", "the", "self", "parameter", ".", ":", "param", "method", ":", "The", "method", "being", "decorated", ".", ...
python
train
38.666667
learningequality/ricecooker
ricecooker/classes/nodes.py
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/classes/nodes.py#L204-L222
def validate(self): """ validate: Makes sure node is valid Args: None Returns: boolean indicating if node is valid """ from .files import File assert self.source_id is not None, "Assumption Failed: Node must have a source_id" assert isinstance(self.title, str), "Assumption Failed: Node title is not a string" assert isinstance(self.description, str) or self.description is None, "Assumption Failed: Node description is not a string" assert isinstance(self.children, list), "Assumption Failed: Node children is not a list" for f in self.files: assert isinstance(f, File), "Assumption Failed: files must be file class" f.validate() source_ids = [c.source_id for c in self.children] duplicates = set([x for x in source_ids if source_ids.count(x) > 1]) assert len(duplicates) == 0, "Assumption Failed: Node must have unique source id among siblings ({} appears multiple times)".format(duplicates) return True
[ "def", "validate", "(", "self", ")", ":", "from", ".", "files", "import", "File", "assert", "self", ".", "source_id", "is", "not", "None", ",", "\"Assumption Failed: Node must have a source_id\"", "assert", "isinstance", "(", "self", ".", "title", ",", "str", ...
validate: Makes sure node is valid Args: None Returns: boolean indicating if node is valid
[ "validate", ":", "Makes", "sure", "node", "is", "valid", "Args", ":", "None", "Returns", ":", "boolean", "indicating", "if", "node", "is", "valid" ]
python
train
54.368421
rodluger/everest
everest/fits.py
https://github.com/rodluger/everest/blob/6779591f9f8b3556847e2fbf761bdfac7520eaea/everest/fits.py#L362-L398
def MakeFITS(model, fitsfile=None): ''' Generate a FITS file for a given :py:mod:`everest` run. :param model: An :py:mod:`everest` model instance ''' # Get the fits file name if fitsfile is None: outfile = os.path.join(model.dir, model._mission.FITSFile( model.ID, model.season, model.cadence)) else: outfile = os.path.join(model.dir, fitsfile) if os.path.exists(outfile) and not model.clobber: return elif os.path.exists(outfile): os.remove(outfile) log.info('Generating FITS file...') # Create the HDUs primary = PrimaryHDU(model) lightcurve = LightcurveHDU(model) pixels = PixelsHDU(model) aperture = ApertureHDU(model) images = ImagesHDU(model) hires = HiResHDU(model) # Combine to get the HDUList hdulist = pyfits.HDUList( [primary, lightcurve, pixels, aperture, images, hires]) # Output to the FITS file hdulist.writeto(outfile) return
[ "def", "MakeFITS", "(", "model", ",", "fitsfile", "=", "None", ")", ":", "# Get the fits file name", "if", "fitsfile", "is", "None", ":", "outfile", "=", "os", ".", "path", ".", "join", "(", "model", ".", "dir", ",", "model", ".", "_mission", ".", "FIT...
Generate a FITS file for a given :py:mod:`everest` run. :param model: An :py:mod:`everest` model instance
[ "Generate", "a", "FITS", "file", "for", "a", "given", ":", "py", ":", "mod", ":", "everest", "run", "." ]
python
train
25.756757
iqbal-lab-org/cluster_vcf_records
cluster_vcf_records/vcf_merge.py
https://github.com/iqbal-lab-org/cluster_vcf_records/blob/0db26af36b6da97a7361364457d2152dc756055c/cluster_vcf_records/vcf_merge.py#L29-L34
def merge_vcf_files(infiles, ref_seqs, outfile, threads=1): '''infiles: list of input VCF file to be merge. outfile: name of output VCF file. threads: number of input files to read in parallel''' vars_dict = vcf_file_read.vcf_files_to_dict_of_vars(infiles, ref_seqs, threads=threads) _dict_of_vars_to_vcf_file(vars_dict, outfile)
[ "def", "merge_vcf_files", "(", "infiles", ",", "ref_seqs", ",", "outfile", ",", "threads", "=", "1", ")", ":", "vars_dict", "=", "vcf_file_read", ".", "vcf_files_to_dict_of_vars", "(", "infiles", ",", "ref_seqs", ",", "threads", "=", "threads", ")", "_dict_of_...
infiles: list of input VCF file to be merge. outfile: name of output VCF file. threads: number of input files to read in parallel
[ "infiles", ":", "list", "of", "input", "VCF", "file", "to", "be", "merge", ".", "outfile", ":", "name", "of", "output", "VCF", "file", ".", "threads", ":", "number", "of", "input", "files", "to", "read", "in", "parallel" ]
python
train
57.333333
diffeo/py-nilsimsa
nilsimsa/__init__.py
https://github.com/diffeo/py-nilsimsa/blob/c652f4bbfd836f7aebf292dcea676cc925ec315a/nilsimsa/__init__.py#L182-L187
def from_file(self, fname): """read in a file and compute digest""" f = open(fname, "rb") data = f.read() self.update(data) f.close()
[ "def", "from_file", "(", "self", ",", "fname", ")", ":", "f", "=", "open", "(", "fname", ",", "\"rb\"", ")", "data", "=", "f", ".", "read", "(", ")", "self", ".", "update", "(", "data", ")", "f", ".", "close", "(", ")" ]
read in a file and compute digest
[ "read", "in", "a", "file", "and", "compute", "digest" ]
python
train
28
PMEAL/OpenPNM
openpnm/models/physics/thermal_conductance.py
https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/models/physics/thermal_conductance.py#L4-L62
def series_resistors(target, pore_area='pore.area', throat_area='throat.area', pore_thermal_conductivity='pore.thermal_conductivity', throat_thermal_conductivity='throat.thermal_conductivity', conduit_lengths='throat.conduit_lengths', conduit_shape_factors='throat.poisson_shape_factors'): r""" Calculate the thermal conductance of conduits in network, where a conduit is ( 1/2 pore - full throat - 1/2 pore ). See the notes section. Parameters ---------- target : OpenPNM Object The object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary properties. pore_thermal_conductivity : string Dictionary key of the pore thermal conductivity values throat_thermal_conductivity : string Dictionary key of the throat thermal conductivity values pore_area : string Dictionary key of the pore area values throat_area : string Dictionary key of the throat area values conduit_shape_factors : string Dictionary key of the conduit DIFFUSION shape factor values Returns ------- g : ndarray Array containing thermal conductance values for conduits in the geometry attached to the given physics object. Notes ----- (1) This function requires that all the necessary phase properties already be calculated. (2) This function calculates the specified property for the *entire* network then extracts the values for the appropriate throats at the end. (3) This function assumes cylindrical throats with constant cross-section area. Corrections for different shapes and variable cross-section area can be imposed by passing the proper flow_shape_factor argument. """ return generic_conductance(target=target, transport_type='diffusion', pore_area=pore_area, throat_area=throat_area, pore_diffusivity=pore_thermal_conductivity, throat_diffusivity=throat_thermal_conductivity, conduit_lengths=conduit_lengths, conduit_shape_factors=conduit_shape_factors)
[ "def", "series_resistors", "(", "target", ",", "pore_area", "=", "'pore.area'", ",", "throat_area", "=", "'throat.area'", ",", "pore_thermal_conductivity", "=", "'pore.thermal_conductivity'", ",", "throat_thermal_conductivity", "=", "'throat.thermal_conductivity'", ",", "co...
r""" Calculate the thermal conductance of conduits in network, where a conduit is ( 1/2 pore - full throat - 1/2 pore ). See the notes section. Parameters ---------- target : OpenPNM Object The object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary properties. pore_thermal_conductivity : string Dictionary key of the pore thermal conductivity values throat_thermal_conductivity : string Dictionary key of the throat thermal conductivity values pore_area : string Dictionary key of the pore area values throat_area : string Dictionary key of the throat area values conduit_shape_factors : string Dictionary key of the conduit DIFFUSION shape factor values Returns ------- g : ndarray Array containing thermal conductance values for conduits in the geometry attached to the given physics object. Notes ----- (1) This function requires that all the necessary phase properties already be calculated. (2) This function calculates the specified property for the *entire* network then extracts the values for the appropriate throats at the end. (3) This function assumes cylindrical throats with constant cross-section area. Corrections for different shapes and variable cross-section area can be imposed by passing the proper flow_shape_factor argument.
[ "r", "Calculate", "the", "thermal", "conductance", "of", "conduits", "in", "network", "where", "a", "conduit", "is", "(", "1", "/", "2", "pore", "-", "full", "throat", "-", "1", "/", "2", "pore", ")", ".", "See", "the", "notes", "section", "." ]
python
train
39.932203
sony/nnabla
python/src/nnabla/initializer.py
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/initializer.py#L324-L360
def calc_uniform_lim_glorot(inmaps, outmaps, kernel=(1, 1)): r"""Calculates the lower bound and the upper bound of the uniform distribution proposed by Glorot et al. .. math:: b &= \sqrt{\frac{6}{NK + M}}\\ a &= -b Args: inmaps (int): Map size of an input Variable, :math:`N`. outmaps (int): Map size of an output Variable, :math:`M`. kernel (:obj:`tuple` of :obj:`int`): Convolution kernel spatial shape. In above definition, :math:`K` is the product of shape dimensions. In Affine, the default value should be used. Example: .. code-block:: python import nnabla as nn import nnabla.parametric_functions as PF import nnabla.initializer as I x = nn.Variable([60,1,28,28]) lb,ub= I.calc_uniform_lim_glorot(x.shape[1],64) w = I.UniformInitializer((lb,ub)) b = I.ConstantInitializer(0) h = PF.convolution(x, 64, [3, 3], w_init=w, b_init=b, pad=[1, 1], name='conv') References: * `Glorot and Bengio. Understanding the difficulty of training deep feedforward neural networks <http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf>`_ """ d = np.sqrt(6. / (np.prod(kernel) * inmaps + outmaps)) return -d, d
[ "def", "calc_uniform_lim_glorot", "(", "inmaps", ",", "outmaps", ",", "kernel", "=", "(", "1", ",", "1", ")", ")", ":", "d", "=", "np", ".", "sqrt", "(", "6.", "/", "(", "np", ".", "prod", "(", "kernel", ")", "*", "inmaps", "+", "outmaps", ")", ...
r"""Calculates the lower bound and the upper bound of the uniform distribution proposed by Glorot et al. .. math:: b &= \sqrt{\frac{6}{NK + M}}\\ a &= -b Args: inmaps (int): Map size of an input Variable, :math:`N`. outmaps (int): Map size of an output Variable, :math:`M`. kernel (:obj:`tuple` of :obj:`int`): Convolution kernel spatial shape. In above definition, :math:`K` is the product of shape dimensions. In Affine, the default value should be used. Example: .. code-block:: python import nnabla as nn import nnabla.parametric_functions as PF import nnabla.initializer as I x = nn.Variable([60,1,28,28]) lb,ub= I.calc_uniform_lim_glorot(x.shape[1],64) w = I.UniformInitializer((lb,ub)) b = I.ConstantInitializer(0) h = PF.convolution(x, 64, [3, 3], w_init=w, b_init=b, pad=[1, 1], name='conv') References: * `Glorot and Bengio. Understanding the difficulty of training deep feedforward neural networks <http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf>`_
[ "r", "Calculates", "the", "lower", "bound", "and", "the", "upper", "bound", "of", "the", "uniform", "distribution", "proposed", "by", "Glorot", "et", "al", "." ]
python
train
34.378378
d0c-s4vage/pfp
pfp/fields.py
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/fields.py#L1773-L1788
def _pfp__build(self, stream=None, save_offset=False): """Build the String field :stream: TODO :returns: TODO """ if stream is not None and save_offset: self._pfp__offset = stream.tell() data = self._pfp__value + utils.binary("\x00") if stream is None: return data else: stream.write(data) return len(data)
[ "def", "_pfp__build", "(", "self", ",", "stream", "=", "None", ",", "save_offset", "=", "False", ")", ":", "if", "stream", "is", "not", "None", "and", "save_offset", ":", "self", ".", "_pfp__offset", "=", "stream", ".", "tell", "(", ")", "data", "=", ...
Build the String field :stream: TODO :returns: TODO
[ "Build", "the", "String", "field" ]
python
train
25.375
tensorflow/tensor2tensor
tensor2tensor/layers/message_passing_attention.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/message_passing_attention.py#L251-L301
def _compute_edge_transforms(node_states, depth, num_transforms, name="transform"): """Helper function that computes transformation for keys and values. Let B be the number of batches. Let N be the number of nodes in the graph. Let D be the size of the node hidden states. Let K be the size of the attention keys/queries (total_key_depth). Let V be the size of the attention values (total_value_depth). Let T be the total number of transforms (num_transforms). Computes the transforms for keys or values for attention. * For each node N_j and edge type t, a key K_jt of size K is computed. When an edge of type t goes from node N_j to any other node, K_jt is the key that is in the attention process. * For each node N_j and edge type t, a value V_jt of size V is computed. When an edge of type t goes from node N_j to node N_i, Attention(Q_i, K_jt) produces a weight w_ijt. The message sent along this edge is w_ijt * V_jt. Args: node_states: A tensor of shape [B, L, D] depth: An integer (K or V) num_transforms: An integer (T), name: A name for the function Returns: x: A The attention keys or values for each node and edge type (shape [B, N*T, K or V]) """ node_shapes = common_layers.shape_list(node_states) x = common_layers.dense( node_states, depth * num_transforms, use_bias=False, name=name) batch = node_shapes[0] # B. length = node_shapes[1] # N. # Making the fourth dimension explicit by separating the vectors of size # K*T (in k) and V*T (in v) into two-dimensional matrices with shape [K, T] # (in k) and [V, T] in v. # x = tf.reshape(x, [batch, length, num_transforms, depth]) # Flatten out the fourth dimension. x = tf.reshape(x, [batch, length * num_transforms, depth]) return x
[ "def", "_compute_edge_transforms", "(", "node_states", ",", "depth", ",", "num_transforms", ",", "name", "=", "\"transform\"", ")", ":", "node_shapes", "=", "common_layers", ".", "shape_list", "(", "node_states", ")", "x", "=", "common_layers", ".", "dense", "("...
Helper function that computes transformation for keys and values. Let B be the number of batches. Let N be the number of nodes in the graph. Let D be the size of the node hidden states. Let K be the size of the attention keys/queries (total_key_depth). Let V be the size of the attention values (total_value_depth). Let T be the total number of transforms (num_transforms). Computes the transforms for keys or values for attention. * For each node N_j and edge type t, a key K_jt of size K is computed. When an edge of type t goes from node N_j to any other node, K_jt is the key that is in the attention process. * For each node N_j and edge type t, a value V_jt of size V is computed. When an edge of type t goes from node N_j to node N_i, Attention(Q_i, K_jt) produces a weight w_ijt. The message sent along this edge is w_ijt * V_jt. Args: node_states: A tensor of shape [B, L, D] depth: An integer (K or V) num_transforms: An integer (T), name: A name for the function Returns: x: A The attention keys or values for each node and edge type (shape [B, N*T, K or V])
[ "Helper", "function", "that", "computes", "transformation", "for", "keys", "and", "values", "." ]
python
train
36.470588
deep-compute/logagg
logagg/formatters.py
https://github.com/deep-compute/logagg/blob/7863bc1b5ddf3e67c4d4b55746799304180589a0/logagg/formatters.py#L199-L271
def django(line): ''' >>> import pprint >>> input_line1 = '[23/Aug/2017 11:35:25] INFO [app.middleware_log_req:50]View func called:{"exception": null,"processing_time": 0.00011801719665527344, "url": "<url>",host": "localhost", "user": "testing", "post_contents": "", "method": "POST" }' >>> output_line1 = django(input_line1) >>> pprint.pprint(output_line1) {'data': {'loglevel': 'INFO', 'logname': '[app.middleware_log_req:50]', 'message': 'View func called:{"exception": null,"processing_time": 0.00011801719665527344, "url": "<url>",host": "localhost", "user": "testing", "post_contents": "", "method": "POST" }', 'timestamp': '2017-08-23T11:35:25'}, 'level': 'INFO', 'timestamp': '2017-08-23T11:35:25'} >>> input_line2 = '[22/Sep/2017 06:32:15] INFO [app.function:6022] {"UUID": "c47f3530-9f5f-11e7-a559-917d011459f7", "timestamp":1506061932546, "misc": {"status": 200, "ready_state": 4, "end_time_ms": 1506061932546, "url": "/api/function?", "start_time_ms": 1506061932113, "response_length": 31, "status_message": "OK", "request_time_ms": 433}, "user": "root", "host_url": "localhost:8888", "message": "ajax success"}' >>> output_line2 = django(input_line2) >>> pprint.pprint(output_line2) {'data': {'loglevel': 'INFO', 'logname': '[app.function:6022]', 'message': {u'UUID': u'c47f3530-9f5f-11e7-a559-917d011459f7', u'host_url': u'localhost:8888', u'message': u'ajax success', u'misc': {u'end_time_ms': 1506061932546L, u'ready_state': 4, u'request_time_ms': 433, u'response_length': 31, u'start_time_ms': 1506061932113L, u'status': 200, u'status_message': u'OK', u'url': u'/api/function?'}, u'timestamp': 1506061932546L, u'user': u'root'}, 'timestamp': '2017-09-22T06:32:15'}, 'level': 'INFO', 'timestamp': '2017-09-22T06:32:15'} Case2: [18/Sep/2017 05:40:36] ERROR [app.apps:78] failed to get the record, collection = Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True, serverselectiontimeoutms=3000), u'collection_cache'), u'function_dummy_version') Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/mongo_cache/mongocache.py", line 70, in __getitem__ result = self.collection.find_one({"_id": key}) OperationFailure: not authorized on collection_cache to execute command { find: "function", filter: { _id: "zydelig-cosine-20" }, limit: 1, singleBatch: true } ''' #TODO we need to handle case2 logs data = {} log = re.findall(r'^(\[\d+/\w+/\d+ \d+:\d+:\d+\].*)', line) if len(log) == 1: data['timestamp'] = datetime.datetime.strptime(re.findall(r'(\d+/\w+/\d+ \d+:\d+:\d+)',\ log[0])[0],"%d/%b/%Y %H:%M:%S").isoformat() data['loglevel'] = re.findall('[A-Z]+', log[0])[1] data['logname'] = re.findall('\[\D+.\w+:\d+\]', log[0])[0] message = re.findall('\{.+\}', log[0]) try: if len(message) > 0: message = json.loads(message[0]) else: message = re.split(']', log[0]) message = ''.join(message[2:]) except ValueError: message = re.split(']', log[0]) message = ''.join(message[2:]) data['message'] = message return dict( timestamp=data['timestamp'], level=data['loglevel'], data=data, ) else: return dict( timestamp=datetime.datetime.isoformat(datetime.datetime.utcnow()), data={raw:line} )
[ "def", "django", "(", "line", ")", ":", "#TODO we need to handle case2 logs", "data", "=", "{", "}", "log", "=", "re", ".", "findall", "(", "r'^(\\[\\d+/\\w+/\\d+ \\d+:\\d+:\\d+\\].*)'", ",", "line", ")", "if", "len", "(", "log", ")", "==", "1", ":", "data",...
>>> import pprint >>> input_line1 = '[23/Aug/2017 11:35:25] INFO [app.middleware_log_req:50]View func called:{"exception": null,"processing_time": 0.00011801719665527344, "url": "<url>",host": "localhost", "user": "testing", "post_contents": "", "method": "POST" }' >>> output_line1 = django(input_line1) >>> pprint.pprint(output_line1) {'data': {'loglevel': 'INFO', 'logname': '[app.middleware_log_req:50]', 'message': 'View func called:{"exception": null,"processing_time": 0.00011801719665527344, "url": "<url>",host": "localhost", "user": "testing", "post_contents": "", "method": "POST" }', 'timestamp': '2017-08-23T11:35:25'}, 'level': 'INFO', 'timestamp': '2017-08-23T11:35:25'} >>> input_line2 = '[22/Sep/2017 06:32:15] INFO [app.function:6022] {"UUID": "c47f3530-9f5f-11e7-a559-917d011459f7", "timestamp":1506061932546, "misc": {"status": 200, "ready_state": 4, "end_time_ms": 1506061932546, "url": "/api/function?", "start_time_ms": 1506061932113, "response_length": 31, "status_message": "OK", "request_time_ms": 433}, "user": "root", "host_url": "localhost:8888", "message": "ajax success"}' >>> output_line2 = django(input_line2) >>> pprint.pprint(output_line2) {'data': {'loglevel': 'INFO', 'logname': '[app.function:6022]', 'message': {u'UUID': u'c47f3530-9f5f-11e7-a559-917d011459f7', u'host_url': u'localhost:8888', u'message': u'ajax success', u'misc': {u'end_time_ms': 1506061932546L, u'ready_state': 4, u'request_time_ms': 433, u'response_length': 31, u'start_time_ms': 1506061932113L, u'status': 200, u'status_message': u'OK', u'url': u'/api/function?'}, u'timestamp': 1506061932546L, u'user': u'root'}, 'timestamp': '2017-09-22T06:32:15'}, 'level': 'INFO', 'timestamp': '2017-09-22T06:32:15'} Case2: [18/Sep/2017 05:40:36] ERROR [app.apps:78] failed to get the record, collection = Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True, serverselectiontimeoutms=3000), u'collection_cache'), u'function_dummy_version') Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/mongo_cache/mongocache.py", line 70, in __getitem__ result = self.collection.find_one({"_id": key}) OperationFailure: not authorized on collection_cache to execute command { find: "function", filter: { _id: "zydelig-cosine-20" }, limit: 1, singleBatch: true }
[ ">>>", "import", "pprint", ">>>", "input_line1", "=", "[", "23", "/", "Aug", "/", "2017", "11", ":", "35", ":", "25", "]", "INFO", "[", "app", ".", "middleware_log_req", ":", "50", "]", "View", "func", "called", ":", "{", "exception", ":", "null", ...
python
train
54.342466
cloud-custodian/cloud-custodian
c7n/mu.py
https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/mu.py#L254-L277
def custodian_archive(packages=None): """Create a lambda code archive for running custodian. Lambda archive currently always includes `c7n` and `pkg_resources`. Add additional packages in the mode block. Example policy that includes additional packages .. code-block:: yaml policy: name: lambda-archive-example resource: s3 mode: packages: - botocore packages: List of additional packages to include in the lambda archive. """ modules = {'c7n', 'pkg_resources'} if packages: modules = filter(None, modules.union(packages)) return PythonPackageArchive(*sorted(modules))
[ "def", "custodian_archive", "(", "packages", "=", "None", ")", ":", "modules", "=", "{", "'c7n'", ",", "'pkg_resources'", "}", "if", "packages", ":", "modules", "=", "filter", "(", "None", ",", "modules", ".", "union", "(", "packages", ")", ")", "return"...
Create a lambda code archive for running custodian. Lambda archive currently always includes `c7n` and `pkg_resources`. Add additional packages in the mode block. Example policy that includes additional packages .. code-block:: yaml policy: name: lambda-archive-example resource: s3 mode: packages: - botocore packages: List of additional packages to include in the lambda archive.
[ "Create", "a", "lambda", "code", "archive", "for", "running", "custodian", "." ]
python
train
27.625
alexras/pylsdj
pylsdj/kits.py
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/kits.py#L248-L264
def read_wav(self, filename): """Read sample data for this sample from a WAV file. :param filename: the file from which to read """ wave_input = None try: wave_input = wave.open(filename, 'r') wave_frames = bytearray( wave_input.readframes(wave_input.getnframes())) self.sample_data = [x >> 4 for x in wave_frames] finally: if wave_input is not None: wave_input.close()
[ "def", "read_wav", "(", "self", ",", "filename", ")", ":", "wave_input", "=", "None", "try", ":", "wave_input", "=", "wave", ".", "open", "(", "filename", ",", "'r'", ")", "wave_frames", "=", "bytearray", "(", "wave_input", ".", "readframes", "(", "wave_...
Read sample data for this sample from a WAV file. :param filename: the file from which to read
[ "Read", "sample", "data", "for", "this", "sample", "from", "a", "WAV", "file", "." ]
python
train
28.529412
pantsbuild/pants
src/python/pants/pantsd/process_manager.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/process_manager.py#L307-L309
def socket(self): """The running processes socket/port information (or None).""" return self._socket or self.read_metadata_by_name(self._name, 'socket', self._socket_type)
[ "def", "socket", "(", "self", ")", ":", "return", "self", ".", "_socket", "or", "self", ".", "read_metadata_by_name", "(", "self", ".", "_name", ",", "'socket'", ",", "self", ".", "_socket_type", ")" ]
The running processes socket/port information (or None).
[ "The", "running", "processes", "socket", "/", "port", "information", "(", "or", "None", ")", "." ]
python
train
59
chriskiehl/Gooey
gooey/gui/components/widgets/radio_group.py
https://github.com/chriskiehl/Gooey/blob/e598573c6519b953e0ccfc1f3663f827f8cd7e22/gooey/gui/components/widgets/radio_group.py#L136-L142
def createWidgets(self): """ Instantiate the Gooey Widgets that are used within the RadioGroup """ from gooey.gui.components import widgets return [getattr(widgets, item['type'])(self, item) for item in getin(self.widgetInfo, ['data', 'widgets'], [])]
[ "def", "createWidgets", "(", "self", ")", ":", "from", "gooey", ".", "gui", ".", "components", "import", "widgets", "return", "[", "getattr", "(", "widgets", ",", "item", "[", "'type'", "]", ")", "(", "self", ",", "item", ")", "for", "item", "in", "g...
Instantiate the Gooey Widgets that are used within the RadioGroup
[ "Instantiate", "the", "Gooey", "Widgets", "that", "are", "used", "within", "the", "RadioGroup" ]
python
train
43.857143
ruipgil/TrackToTrip
tracktotrip/segment.py
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L101-L119
def smooth(self, noise, strategy=INVERSE_STRATEGY): """ In-place smoothing See smooth_segment function Args: noise (float): Noise expected strategy (int): Strategy to use. Either smooth.INVERSE_STRATEGY or smooth.EXTRAPOLATE_STRATEGY Returns: :obj:`Segment` """ if strategy is INVERSE_STRATEGY: self.points = with_inverse(self.points, noise) elif strategy is EXTRAPOLATE_STRATEGY: self.points = with_extrapolation(self.points, noise, 30) elif strategy is NO_STRATEGY: self.points = with_no_strategy(self.points, noise) return self
[ "def", "smooth", "(", "self", ",", "noise", ",", "strategy", "=", "INVERSE_STRATEGY", ")", ":", "if", "strategy", "is", "INVERSE_STRATEGY", ":", "self", ".", "points", "=", "with_inverse", "(", "self", ".", "points", ",", "noise", ")", "elif", "strategy", ...
In-place smoothing See smooth_segment function Args: noise (float): Noise expected strategy (int): Strategy to use. Either smooth.INVERSE_STRATEGY or smooth.EXTRAPOLATE_STRATEGY Returns: :obj:`Segment`
[ "In", "-", "place", "smoothing" ]
python
train
35.473684
xtuml/pyxtuml
bridgepoint/ooaofooa.py
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/ooaofooa.py#L63-L86
def is_contained_in(pe_pe, root): ''' Determine if a PE_PE is contained within a EP_PKG or a C_C. ''' if not pe_pe: return False if type(pe_pe).__name__ != 'PE_PE': pe_pe = one(pe_pe).PE_PE[8001]() ep_pkg = one(pe_pe).EP_PKG[8000]() c_c = one(pe_pe).C_C[8003]() if root in [ep_pkg, c_c]: return True elif is_contained_in(ep_pkg, root): return True elif is_contained_in(c_c, root): return True else: return False
[ "def", "is_contained_in", "(", "pe_pe", ",", "root", ")", ":", "if", "not", "pe_pe", ":", "return", "False", "if", "type", "(", "pe_pe", ")", ".", "__name__", "!=", "'PE_PE'", ":", "pe_pe", "=", "one", "(", "pe_pe", ")", ".", "PE_PE", "[", "8001", ...
Determine if a PE_PE is contained within a EP_PKG or a C_C.
[ "Determine", "if", "a", "PE_PE", "is", "contained", "within", "a", "EP_PKG", "or", "a", "C_C", "." ]
python
test
21.25
splunk/splunk-sdk-python
examples/conf.py
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/conf.py#L131-L141
def run(self, command, opts): """Dispatch the given command & args.""" handlers = { 'create': self.create, 'delete': self.delete, 'list': self.list } handler = handlers.get(command, None) if handler is None: error("Unrecognized command: %s" % command, 2) handler(opts)
[ "def", "run", "(", "self", ",", "command", ",", "opts", ")", ":", "handlers", "=", "{", "'create'", ":", "self", ".", "create", ",", "'delete'", ":", "self", ".", "delete", ",", "'list'", ":", "self", ".", "list", "}", "handler", "=", "handlers", "...
Dispatch the given command & args.
[ "Dispatch", "the", "given", "command", "&", "args", "." ]
python
train
32.272727
pywbem/pywbem
pywbem/cim_operations.py
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L6625-L6853
def OpenEnumerateInstancePaths(self, ClassName, namespace=None, FilterQueryLanguage=None, FilterQuery=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCount=None, **extra): # pylint: disable=invalid-name """ Open an enumeration session to enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace. *New in pywbem 0.9.* This method performs the OpenEnumerateInstancePaths operation (see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all methods performing such operations. If the operation succeeds, this method returns status on the enumeration session and optionally instance paths. Otherwise, this method raises an exception. Use the :meth:`~pywbem.WBEMConnection.PullInstancePaths` method to retrieve the next set of instance paths or the :meth:`~pywbem.WBEMConnection.CloseEnumeration` method to close the enumeration session before it is exhausted. Parameters: ClassName (:term:`string` or :class:`~pywbem.CIMClassName`): Name of the class to be enumerated (case independent). If specified as a :class:`~pywbem.CIMClassName` object, its `namespace` attribute will be used as a default namespace as described for the `namespace` parameter, and its `host` attribute will be ignored. namespace (:term:`string`): Name of the CIM namespace to be used (case independent). Leading and trailing slash characters will be stripped. The lexical case will be preserved. If `None`, the namespace of the `ClassName` parameter will be used, if specified as a :class:`~pywbem.CIMClassName` object. If that is also `None`, the default namespace of the connection will be used. FilterQueryLanguage (:term:`string`): The name of the filter query language used for the `FilterQuery` parameter. The DMTF-defined Filter Query Language (see :term:`DSP0212`) is specified as "DMTF:FQL". Not all WBEM servers support filtering for this operation because it returns instance paths and the act of the server filtering requires that it generate instances just for that purpose and then discard them. FilterQuery (:term:`string`): The filter query in the query language defined by the `FilterQueryLanguage` parameter. OperationTimeout (:class:`~pywbem.Uint32`): Minimum time in seconds the WBEM Server shall maintain an open enumeration session after a previous Open or Pull request is sent to the client. Once this timeout time has expired, the WBEM server may close the enumeration session. * If not `None`, this parameter is sent to the WBEM server as the proposed timeout for the enumeration session. A value of 0 indicates that the server is expected to never time out. The server may reject the proposed value, causing a :class:`~pywbem.CIMError` to be raised with status code :attr:`~pywbem.CIM_ERR_INVALID_OPERATION_TIMEOUT`. * If `None`, this parameter is not passed to the WBEM server, and causes the server-implemented default timeout to be used. ContinueOnError (:class:`py:bool`): Indicates to the WBEM server to continue sending responses after an error response has been sent. * If `True`, the server is to continue sending responses after sending an error response. Not all servers support continuation on error; a server that does not support it must send an error response if `True` was specified, causing :class:`~pywbem.CIMError` to be raised with status code :attr:`~pywbem.CIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED`. * If `False`, the server is requested to close the enumeration after sending an error response. * If `None`, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. :term:`DSP0200` defines that the server-implemented default is `False`. MaxObjectCount (:class:`~pywbem.Uint32`) Maximum number of instances the WBEM server may return for this request. * If positive, the WBEM server is to return no more than the specified number of instances. * If zero, the WBEM server is to return no instances. This may be used by a client to leave the handling of any returned instances to a loop of Pull operations. * If `None`, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. :term:`DSP0200` defines that the server-implemented default is to return zero instances. **extra : Additional keyword arguments are passed as additional operation parameters to the WBEM server. Note that :term:`DSP0200` does not define any additional parameters for this operation. Returns: A :func:`~py:collections.namedtuple` object containing the following named items: * **paths** (:class:`py:list` of :class:`~pywbem.CIMInstanceName`): Representations of the retrieved instance paths, with their attributes set as follows: * `classname`: Name of the creation class of the instance. * `keybindings`: Keybindings of the instance. * `namespace`: Name of the CIM namespace containing the instance. * `host`: Host and optionally port of the WBEM server containing the CIM namespace. * **eos** (:class:`py:bool`): Indicates whether the enumeration session is exhausted after this operation: - If `True`, the enumeration session is exhausted, and the server has closed the enumeration session. - If `False`, the enumeration session is not exhausted and the `context` item is the context object for the next operation on the enumeration session. * **context** (:func:`py:tuple` of server_context, namespace): A context object identifying the open enumeration session, including its current enumeration state, and the namespace. This object must be supplied with the next pull or close operation for this enumeration session. The tuple items are: * server_context (:term:`string`): Enumeration context string returned by the server if the session is not exhausted, or `None` otherwise. This string is opaque for the client. * namespace (:term:`string`): Name of the CIM namespace that was used for this operation. NOTE: This inner tuple hides the need for a CIM namespace on subsequent operations in the enumeration session. CIM operations always require target namespace, but it never makes sense to specify a different one in subsequent operations on the same enumeration session. Raises: Exceptions described in :class:`~pywbem.WBEMConnection`. Example:: max_object_count = 100 rslt_tuple = conn.OpenEnumerateInstancePaths( 'CIM_Blah', MaxObjectCount=max_object_count) paths = rslt_tuple.paths while not rslt_tuple.eos: rslt_tuple = conn.PullInstancePaths(rslt_tupl.context, max_object_count) paths.extend(rslt_tupl.paths) for path in paths: print('path {0}'.format(path)) """ exc = None result_tuple = None method_name = 'OpenEnumerateInstancePaths' if self._operation_recorders: self.operation_recorder_reset(pull_op=True) self.operation_recorder_stage_pywbem_args( method=method_name, ClassName=ClassName, namespace=namespace, FilterQueryLanguage=FilterQueryLanguage, FilterQuery=FilterQuery, OperationTimeout=OperationTimeout, ContinueOnError=ContinueOnError, MaxObjectCount=MaxObjectCount, **extra) try: stats = self.statistics.start_timer(method_name) if namespace is None and isinstance(ClassName, CIMClassName): namespace = ClassName.namespace namespace = self._iparam_namespace_from_namespace(namespace) classname = self._iparam_classname(ClassName, 'ClassName') result = self._imethodcall( method_name, namespace, ClassName=classname, FilterQueryLanguage=FilterQueryLanguage, FilterQuery=FilterQuery, OperationTimeout=OperationTimeout, ContinueOnError=ContinueOnError, MaxObjectCount=MaxObjectCount, has_out_params=True, **extra) result_tuple = pull_path_result_tuple( *self._get_rslt_params(result, namespace)) return result_tuple except (CIMXMLParseError, XMLParseError) as exce: exce.request_data = self.last_raw_request exce.response_data = self.last_raw_reply exc = exce raise except Exception as exce: exc = exce raise finally: self._last_operation_time = stats.stop_timer( self.last_request_len, self.last_reply_len, self.last_server_response_time, exc) if self._operation_recorders: self.operation_recorder_stage_result(result_tuple, exc)
[ "def", "OpenEnumerateInstancePaths", "(", "self", ",", "ClassName", ",", "namespace", "=", "None", ",", "FilterQueryLanguage", "=", "None", ",", "FilterQuery", "=", "None", ",", "OperationTimeout", "=", "None", ",", "ContinueOnError", "=", "None", ",", "MaxObjec...
Open an enumeration session to enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace. *New in pywbem 0.9.* This method performs the OpenEnumerateInstancePaths operation (see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all methods performing such operations. If the operation succeeds, this method returns status on the enumeration session and optionally instance paths. Otherwise, this method raises an exception. Use the :meth:`~pywbem.WBEMConnection.PullInstancePaths` method to retrieve the next set of instance paths or the :meth:`~pywbem.WBEMConnection.CloseEnumeration` method to close the enumeration session before it is exhausted. Parameters: ClassName (:term:`string` or :class:`~pywbem.CIMClassName`): Name of the class to be enumerated (case independent). If specified as a :class:`~pywbem.CIMClassName` object, its `namespace` attribute will be used as a default namespace as described for the `namespace` parameter, and its `host` attribute will be ignored. namespace (:term:`string`): Name of the CIM namespace to be used (case independent). Leading and trailing slash characters will be stripped. The lexical case will be preserved. If `None`, the namespace of the `ClassName` parameter will be used, if specified as a :class:`~pywbem.CIMClassName` object. If that is also `None`, the default namespace of the connection will be used. FilterQueryLanguage (:term:`string`): The name of the filter query language used for the `FilterQuery` parameter. The DMTF-defined Filter Query Language (see :term:`DSP0212`) is specified as "DMTF:FQL". Not all WBEM servers support filtering for this operation because it returns instance paths and the act of the server filtering requires that it generate instances just for that purpose and then discard them. FilterQuery (:term:`string`): The filter query in the query language defined by the `FilterQueryLanguage` parameter. OperationTimeout (:class:`~pywbem.Uint32`): Minimum time in seconds the WBEM Server shall maintain an open enumeration session after a previous Open or Pull request is sent to the client. Once this timeout time has expired, the WBEM server may close the enumeration session. * If not `None`, this parameter is sent to the WBEM server as the proposed timeout for the enumeration session. A value of 0 indicates that the server is expected to never time out. The server may reject the proposed value, causing a :class:`~pywbem.CIMError` to be raised with status code :attr:`~pywbem.CIM_ERR_INVALID_OPERATION_TIMEOUT`. * If `None`, this parameter is not passed to the WBEM server, and causes the server-implemented default timeout to be used. ContinueOnError (:class:`py:bool`): Indicates to the WBEM server to continue sending responses after an error response has been sent. * If `True`, the server is to continue sending responses after sending an error response. Not all servers support continuation on error; a server that does not support it must send an error response if `True` was specified, causing :class:`~pywbem.CIMError` to be raised with status code :attr:`~pywbem.CIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED`. * If `False`, the server is requested to close the enumeration after sending an error response. * If `None`, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. :term:`DSP0200` defines that the server-implemented default is `False`. MaxObjectCount (:class:`~pywbem.Uint32`) Maximum number of instances the WBEM server may return for this request. * If positive, the WBEM server is to return no more than the specified number of instances. * If zero, the WBEM server is to return no instances. This may be used by a client to leave the handling of any returned instances to a loop of Pull operations. * If `None`, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. :term:`DSP0200` defines that the server-implemented default is to return zero instances. **extra : Additional keyword arguments are passed as additional operation parameters to the WBEM server. Note that :term:`DSP0200` does not define any additional parameters for this operation. Returns: A :func:`~py:collections.namedtuple` object containing the following named items: * **paths** (:class:`py:list` of :class:`~pywbem.CIMInstanceName`): Representations of the retrieved instance paths, with their attributes set as follows: * `classname`: Name of the creation class of the instance. * `keybindings`: Keybindings of the instance. * `namespace`: Name of the CIM namespace containing the instance. * `host`: Host and optionally port of the WBEM server containing the CIM namespace. * **eos** (:class:`py:bool`): Indicates whether the enumeration session is exhausted after this operation: - If `True`, the enumeration session is exhausted, and the server has closed the enumeration session. - If `False`, the enumeration session is not exhausted and the `context` item is the context object for the next operation on the enumeration session. * **context** (:func:`py:tuple` of server_context, namespace): A context object identifying the open enumeration session, including its current enumeration state, and the namespace. This object must be supplied with the next pull or close operation for this enumeration session. The tuple items are: * server_context (:term:`string`): Enumeration context string returned by the server if the session is not exhausted, or `None` otherwise. This string is opaque for the client. * namespace (:term:`string`): Name of the CIM namespace that was used for this operation. NOTE: This inner tuple hides the need for a CIM namespace on subsequent operations in the enumeration session. CIM operations always require target namespace, but it never makes sense to specify a different one in subsequent operations on the same enumeration session. Raises: Exceptions described in :class:`~pywbem.WBEMConnection`. Example:: max_object_count = 100 rslt_tuple = conn.OpenEnumerateInstancePaths( 'CIM_Blah', MaxObjectCount=max_object_count) paths = rslt_tuple.paths while not rslt_tuple.eos: rslt_tuple = conn.PullInstancePaths(rslt_tupl.context, max_object_count) paths.extend(rslt_tupl.paths) for path in paths: print('path {0}'.format(path))
[ "Open", "an", "enumeration", "session", "to", "enumerate", "the", "instance", "paths", "of", "instances", "of", "a", "class", "(", "including", "instances", "of", "its", "subclasses", ")", "in", "a", "namespace", "." ]
python
train
45.0131
booktype/python-ooxml
ooxml/serialize.py
https://github.com/booktype/python-ooxml/blob/b56990a5bee2e1bc46839cec5161ff3726dc4d87/ooxml/serialize.py#L1105-L1120
def get_serializer(self, node): """Returns serializer for specific element. :Args: - node (:class:`ooxml.doc.Element`): Element object :Returns: Returns reference to a function which will be used for serialization. """ return self.options['serializers'].get(type(node), None) if type(node) in self.options['serializers']: return self.options['serializers'][type(node)] return None
[ "def", "get_serializer", "(", "self", ",", "node", ")", ":", "return", "self", ".", "options", "[", "'serializers'", "]", ".", "get", "(", "type", "(", "node", ")", ",", "None", ")", "if", "type", "(", "node", ")", "in", "self", ".", "options", "["...
Returns serializer for specific element. :Args: - node (:class:`ooxml.doc.Element`): Element object :Returns: Returns reference to a function which will be used for serialization.
[ "Returns", "serializer", "for", "specific", "element", "." ]
python
train
28.6875
mbodenhamer/syn
syn/base_utils/py.py
https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/base_utils/py.py#L456-L466
def assert_pickle_idempotent(obj): '''Assert that obj does not change (w.r.t. ==) under repeated picklings ''' from six.moves.cPickle import dumps, loads obj1 = loads(dumps(obj)) obj2 = loads(dumps(obj1)) obj3 = loads(dumps(obj2)) assert_equivalent(obj, obj1) assert_equivalent(obj, obj2) assert_equivalent(obj, obj3) assert type(obj) is type(obj3)
[ "def", "assert_pickle_idempotent", "(", "obj", ")", ":", "from", "six", ".", "moves", ".", "cPickle", "import", "dumps", ",", "loads", "obj1", "=", "loads", "(", "dumps", "(", "obj", ")", ")", "obj2", "=", "loads", "(", "dumps", "(", "obj1", ")", ")"...
Assert that obj does not change (w.r.t. ==) under repeated picklings
[ "Assert", "that", "obj", "does", "not", "change", "(", "w", ".", "r", ".", "t", ".", "==", ")", "under", "repeated", "picklings" ]
python
train
34.363636
fabioz/PyDev.Debugger
_pydevd_bundle/pydevd_process_net_command_json.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_process_net_command_json.py#L605-L618
def on_scopes_request(self, py_db, request): ''' Scopes are the top-level items which appear for a frame (so, we receive the frame id and provide the scopes it has). :param ScopesRequest request: ''' frame_id = request.arguments.frameId variables_reference = frame_id scopes = [Scope('Locals', int(variables_reference), False).to_dict()] body = ScopesResponseBody(scopes) scopes_response = pydevd_base_schema.build_response(request, kwargs={'body':body}) return NetCommand(CMD_RETURN, 0, scopes_response, is_json=True)
[ "def", "on_scopes_request", "(", "self", ",", "py_db", ",", "request", ")", ":", "frame_id", "=", "request", ".", "arguments", ".", "frameId", "variables_reference", "=", "frame_id", "scopes", "=", "[", "Scope", "(", "'Locals'", ",", "int", "(", "variables_r...
Scopes are the top-level items which appear for a frame (so, we receive the frame id and provide the scopes it has). :param ScopesRequest request:
[ "Scopes", "are", "the", "top", "-", "level", "items", "which", "appear", "for", "a", "frame", "(", "so", "we", "receive", "the", "frame", "id", "and", "provide", "the", "scopes", "it", "has", ")", "." ]
python
train
42.5
juju/charm-helpers
charmhelpers/contrib/openstack/audits/openstack_security_guide.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/openstack_security_guide.py#L260-L266
def validate_uses_tls_for_glance(audit_options): """Verify that TLS is used to communicate with Glance.""" section = _config_section(audit_options, 'glance') assert section is not None, "Missing section 'glance'" assert not section.get('insecure') and \ "https://" in section.get("api_servers"), \ "TLS is not used for Glance"
[ "def", "validate_uses_tls_for_glance", "(", "audit_options", ")", ":", "section", "=", "_config_section", "(", "audit_options", ",", "'glance'", ")", "assert", "section", "is", "not", "None", ",", "\"Missing section 'glance'\"", "assert", "not", "section", ".", "get...
Verify that TLS is used to communicate with Glance.
[ "Verify", "that", "TLS", "is", "used", "to", "communicate", "with", "Glance", "." ]
python
train
50.285714
toumorokoshi/jenks
jenks/utils.py
https://github.com/toumorokoshi/jenks/blob/d3333a7b86ba290b7185aa5b8da75e76a28124f5/jenks/utils.py#L27-L33
def generate_valid_keys(): """ create a list of valid keys """ valid_keys = [] for minimum, maximum in RANGES: for i in range(ord(minimum), ord(maximum) + 1): valid_keys.append(chr(i)) return valid_keys
[ "def", "generate_valid_keys", "(", ")", ":", "valid_keys", "=", "[", "]", "for", "minimum", ",", "maximum", "in", "RANGES", ":", "for", "i", "in", "range", "(", "ord", "(", "minimum", ")", ",", "ord", "(", "maximum", ")", "+", "1", ")", ":", "valid...
create a list of valid keys
[ "create", "a", "list", "of", "valid", "keys" ]
python
train
33.142857
cmbruns/pyopenvr
src/openvr/__init__.py
https://github.com/cmbruns/pyopenvr/blob/68395d26bb3df6ab1f0f059c38d441f962938be6/src/openvr/__init__.py#L4920-L4925
def hideOverlay(self, ulOverlayHandle): """Hides the VR overlay. For dashboard overlays, only the Dashboard Manager is allowed to call this.""" fn = self.function_table.hideOverlay result = fn(ulOverlayHandle) return result
[ "def", "hideOverlay", "(", "self", ",", "ulOverlayHandle", ")", ":", "fn", "=", "self", ".", "function_table", ".", "hideOverlay", "result", "=", "fn", "(", "ulOverlayHandle", ")", "return", "result" ]
Hides the VR overlay. For dashboard overlays, only the Dashboard Manager is allowed to call this.
[ "Hides", "the", "VR", "overlay", ".", "For", "dashboard", "overlays", "only", "the", "Dashboard", "Manager", "is", "allowed", "to", "call", "this", "." ]
python
train
42
Kozea/cairocffi
cairocffi/fonts.py
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/fonts.py#L198-L211
def get_ctm(self): """Copies the scaled font’s font current transform matrix. Note that the translation offsets ``(x0, y0)`` of the CTM are ignored by :class:`ScaledFont`. So, the matrix this method returns always has 0 as ``x0`` and ``y0``. :returns: A new :class:`Matrix` object. """ matrix = Matrix() cairo.cairo_scaled_font_get_ctm(self._pointer, matrix._pointer) self._check_status() return matrix
[ "def", "get_ctm", "(", "self", ")", ":", "matrix", "=", "Matrix", "(", ")", "cairo", ".", "cairo_scaled_font_get_ctm", "(", "self", ".", "_pointer", ",", "matrix", ".", "_pointer", ")", "self", ".", "_check_status", "(", ")", "return", "matrix" ]
Copies the scaled font’s font current transform matrix. Note that the translation offsets ``(x0, y0)`` of the CTM are ignored by :class:`ScaledFont`. So, the matrix this method returns always has 0 as ``x0`` and ``y0``. :returns: A new :class:`Matrix` object.
[ "Copies", "the", "scaled", "font’s", "font", "current", "transform", "matrix", "." ]
python
train
33.714286
ampl/amplpy
amplpy/ampl.py
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L691-L708
def display(self, *amplExpressions): """ Writes on the current OutputHandler the outcome of the AMPL statement. .. code-block:: ampl display e1, e2, .., en; where e1, ..., en are the strings passed to the procedure. Args: amplExpressions: Expressions to be evaluated. """ exprs = list(map(str, amplExpressions)) lock_and_call( lambda: self._impl.displayLst(exprs, len(exprs)), self._lock )
[ "def", "display", "(", "self", ",", "*", "amplExpressions", ")", ":", "exprs", "=", "list", "(", "map", "(", "str", ",", "amplExpressions", ")", ")", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "displayLst", "(", "exprs", ",", "len"...
Writes on the current OutputHandler the outcome of the AMPL statement. .. code-block:: ampl display e1, e2, .., en; where e1, ..., en are the strings passed to the procedure. Args: amplExpressions: Expressions to be evaluated.
[ "Writes", "on", "the", "current", "OutputHandler", "the", "outcome", "of", "the", "AMPL", "statement", "." ]
python
train
27.555556
molmod/molmod
molmod/minimizer.py
https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/minimizer.py#L1503-L1514
def _print_header(self): """Print the header for screen logging""" header = " Iter Dir " if self.constraints is not None: header += ' SC CC' header += " Function" if self.convergence_condition is not None: header += self.convergence_condition.get_header() header += " Time" self._screen("-"*(len(header)), newline=True) self._screen(header, newline=True) self._screen("-"*(len(header)), newline=True)
[ "def", "_print_header", "(", "self", ")", ":", "header", "=", "\" Iter Dir \"", "if", "self", ".", "constraints", "is", "not", "None", ":", "header", "+=", "' SC CC'", "header", "+=", "\" Function\"", "if", "self", ".", "convergence_condition", "is", ...
Print the header for screen logging
[ "Print", "the", "header", "for", "screen", "logging" ]
python
train
41.583333
pantsbuild/pants
src/python/pants/backend/jvm/tasks/classpath_products.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/classpath_products.py#L283-L297
def get_artifact_classpath_entries_for_targets(self, targets, respect_excludes=True): """Gets the artifact classpath products for the given targets. Products are returned in order, optionally respecting target excludes, and the products only include external artifact classpath elements (ie: resolved jars). :param targets: The targets to lookup classpath products for. :param bool respect_excludes: `True` to respect excludes; `False` to ignore them. :returns: The ordered (conf, classpath entry) tuples. :rtype: list of (string, :class:`ArtifactClasspathEntry`) """ classpath_tuples = self.get_classpath_entries_for_targets(targets, respect_excludes=respect_excludes) return [(conf, cp_entry) for conf, cp_entry in classpath_tuples if ClasspathEntry.is_artifact_classpath_entry(cp_entry)]
[ "def", "get_artifact_classpath_entries_for_targets", "(", "self", ",", "targets", ",", "respect_excludes", "=", "True", ")", ":", "classpath_tuples", "=", "self", ".", "get_classpath_entries_for_targets", "(", "targets", ",", "respect_excludes", "=", "respect_excludes", ...
Gets the artifact classpath products for the given targets. Products are returned in order, optionally respecting target excludes, and the products only include external artifact classpath elements (ie: resolved jars). :param targets: The targets to lookup classpath products for. :param bool respect_excludes: `True` to respect excludes; `False` to ignore them. :returns: The ordered (conf, classpath entry) tuples. :rtype: list of (string, :class:`ArtifactClasspathEntry`)
[ "Gets", "the", "artifact", "classpath", "products", "for", "the", "given", "targets", "." ]
python
train
59.466667
uw-it-aca/uw-restclients-canvas
uw_canvas/sis_import.py
https://github.com/uw-it-aca/uw-restclients-canvas/blob/9845faf33d49a8f06908efc22640c001116d6ea2/uw_canvas/sis_import.py#L75-L93
def _build_archive(self, dir_path): """ Creates a zip archive from files in path. """ zip_path = os.path.join(dir_path, "import.zip") archive = zipfile.ZipFile(zip_path, "w") for filename in CSV_FILES: filepath = os.path.join(dir_path, filename) if os.path.exists(filepath): archive.write(filepath, filename, zipfile.ZIP_DEFLATED) archive.close() with open(zip_path, "rb") as f: body = f.read() return body
[ "def", "_build_archive", "(", "self", ",", "dir_path", ")", ":", "zip_path", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "\"import.zip\"", ")", "archive", "=", "zipfile", ".", "ZipFile", "(", "zip_path", ",", "\"w\"", ")", "for", "filename...
Creates a zip archive from files in path.
[ "Creates", "a", "zip", "archive", "from", "files", "in", "path", "." ]
python
test
27.210526
HumanCellAtlas/dcp-cli
hca/upload/lib/api_client.py
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/api_client.py#L143-L156
def checksum_status(self, area_uuid, filename): """ Retrieve checksum status and values for a file :param str area_uuid: A RFC4122-compliant ID for the upload area :param str filename: The name of the file within the Upload Area :return: a dict with checksum information :rtype: dict :raises UploadApiException: if information could not be obtained """ url_safe_filename = urlparse.quote(filename) path = "/area/{uuid}/{filename}/checksum".format(uuid=area_uuid, filename=url_safe_filename) response = self._make_request('get', path) return response.json()
[ "def", "checksum_status", "(", "self", ",", "area_uuid", ",", "filename", ")", ":", "url_safe_filename", "=", "urlparse", ".", "quote", "(", "filename", ")", "path", "=", "\"/area/{uuid}/{filename}/checksum\"", ".", "format", "(", "uuid", "=", "area_uuid", ",", ...
Retrieve checksum status and values for a file :param str area_uuid: A RFC4122-compliant ID for the upload area :param str filename: The name of the file within the Upload Area :return: a dict with checksum information :rtype: dict :raises UploadApiException: if information could not be obtained
[ "Retrieve", "checksum", "status", "and", "values", "for", "a", "file" ]
python
train
45.714286
PmagPy/PmagPy
programs/forc_diagram.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/forc_diagram.py#L46-L145
def fit(self, SF, x_range, y_range, matrix_z): ''' #================================================= /the main fitting process /xx,yy,zz = Hb,Ha,p /p is the FORC distribution /m0,n0 is the index of values on Ha = Hb /then loop m0 and n0 /based on smooth factor(SF) /select data grid from the matrix_z for curve fitting #================================================= ''' xx, yy, zz = [], [], [] m0, n0 = [], [] for m, n in itertools.product(np.arange(0, len(x_range), step=SF), np.arange(0, len(y_range), step=SF)): if x_range[m] > y_range[n]: # Ha nearly equal Hb m0.append(m) n0.append(n) aa, bb, cc = [], [], [] for m, n in zip(m0, n0): s = 0 try: grid_data = [] a_ = x_range[m+s] b_ = y_range[n-s] for i, j in itertools.product(np.arange(3*SF+1), np.arange(3*SF+1)): try: grid_data.append( [x_range[m+s+i], y_range[n-s-j], matrix_z.item(n-s-j, m+s+i)]) except: try: for i, j in itertools.product(np.arange(3), np.arange(3)): grid_data.append( [x_range[m+i], y_range[n-j], matrix_z.item(n-j, m+i)]) except: pass # print(grid_data) ''' #================================================= /when SF = n /data grid as (2*n+1)x(2*n+1) /grid_list: convert grid to list /every grid produce on FORC distritution p /the poly fitting use d2_func #================================================= ''' x, y, z = grid_list(grid_data) try: p = d2_func(x, y, z) # print(p) xx.append((a_-b_)/2) yy.append((a_+b_)/2) zz.append(p) except Exception as e: # print(e) pass except: pass ''' #================================================= /the data will be save as pandas dataframe /all the data with nan values will be delete be dropna() #================================================= ''' # print(zz) df = pd.DataFrame({'x': xx, 'y': yy, 'z': zz}) #df = df.replace(0,np.nan) df = df.dropna() ''' #================================================= /due to the space near Bc = zero /the Bi values when Bc <0.003 will be mirrored to -Bc #================================================= ''' df_negative = df[(df.x < 0.03)].copy() df_negative.x = df_negative.x*-1 df = df.append(df_negative) df = df.drop_duplicates(['x', 'y']) df = df.sort_values('x') # plt.scatter(df.x,df.y,c=df.z) # plt.show() ''' #================================================= /reset the Bc and Bi range by X,Y /use linear interpolate to obtain FORC distribution #================================================= ''' xrange = [0, int((np.max(df.x)+0.05)*10)/10] yrange = [int((np.min(df.y)-0.05)*10)/10, int((np.max(df.y)+0.05)*10)/10] X = np.linspace(xrange[0], xrange[1], 200) Y = np.linspace(yrange[0], yrange[1], 200) self.yi, self.xi = np.mgrid[yrange[0]:yrange[1]:200j, xrange[0]:xrange[1]:200j] #self.xi,self.yi = np.mgrid[0:0.2:400j,-0.15:0.15:400j] z = df.z/np.max(df.z) z = np.asarray(z.tolist()) self.zi = griddata((df.x, df.y), z, (self.xi, self.yi), method='cubic')
[ "def", "fit", "(", "self", ",", "SF", ",", "x_range", ",", "y_range", ",", "matrix_z", ")", ":", "xx", ",", "yy", ",", "zz", "=", "[", "]", ",", "[", "]", ",", "[", "]", "m0", ",", "n0", "=", "[", "]", ",", "[", "]", "for", "m", ",", "n...
#================================================= /the main fitting process /xx,yy,zz = Hb,Ha,p /p is the FORC distribution /m0,n0 is the index of values on Ha = Hb /then loop m0 and n0 /based on smooth factor(SF) /select data grid from the matrix_z for curve fitting #=================================================
[ "#", "=================================================", "/", "the", "main", "fitting", "process", "/", "xx", "yy", "zz", "=", "Hb", "Ha", "p", "/", "p", "is", "the", "FORC", "distribution", "/", "m0", "n0", "is", "the", "index", "of", "values", "on", "Ha...
python
train
39.72
vtkiorg/vtki
vtki/utilities.py
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/utilities.py#L212-L218
def trans_from_matrix(matrix): """ Convert a vtk matrix to a numpy.ndarray """ t = np.zeros((4, 4)) for i in range(4): for j in range(4): t[i, j] = matrix.GetElement(i, j) return t
[ "def", "trans_from_matrix", "(", "matrix", ")", ":", "t", "=", "np", ".", "zeros", "(", "(", "4", ",", "4", ")", ")", "for", "i", "in", "range", "(", "4", ")", ":", "for", "j", "in", "range", "(", "4", ")", ":", "t", "[", "i", ",", "j", "...
Convert a vtk matrix to a numpy.ndarray
[ "Convert", "a", "vtk", "matrix", "to", "a", "numpy", ".", "ndarray" ]
python
train
30
gwpy/gwpy
gwpy/plot/axes.py
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/plot/axes.py#L515-L556
def colorbar(self, mappable=None, **kwargs): """Add a `~matplotlib.colorbar.Colorbar` to these `Axes` Parameters ---------- mappable : matplotlib data collection, optional collection against which to map the colouring, default will be the last added mappable artist (collection or image) fraction : `float`, optional fraction of space to steal from these `Axes` to make space for the new axes, default is ``0.`` if ``use_axesgrid=True`` is given (default), otherwise default is ``.15`` to match the upstream matplotlib default. **kwargs other keyword arguments to be passed to the :meth:`Plot.colorbar` generator Returns ------- cbar : `~matplotlib.colorbar.Colorbar` the newly added `Colorbar` See Also -------- Plot.colorbar """ fig = self.get_figure() if kwargs.get('use_axesgrid', True): kwargs.setdefault('fraction', 0.) if kwargs.get('fraction', 0.) == 0.: kwargs.setdefault('use_axesgrid', True) mappable, kwargs = gcbar.process_colorbar_kwargs( fig, mappable=mappable, ax=self, **kwargs) if isinstance(fig, Plot): # either we have created colorbar Axes using axesgrid1, or # the user already gave use_axesgrid=False, so we forcefully # disable axesgrid here in case fraction == 0., which causes # gridspec colorbars to fail. kwargs['use_axesgrid'] = False return fig.colorbar(mappable, **kwargs)
[ "def", "colorbar", "(", "self", ",", "mappable", "=", "None", ",", "*", "*", "kwargs", ")", ":", "fig", "=", "self", ".", "get_figure", "(", ")", "if", "kwargs", ".", "get", "(", "'use_axesgrid'", ",", "True", ")", ":", "kwargs", ".", "setdefault", ...
Add a `~matplotlib.colorbar.Colorbar` to these `Axes` Parameters ---------- mappable : matplotlib data collection, optional collection against which to map the colouring, default will be the last added mappable artist (collection or image) fraction : `float`, optional fraction of space to steal from these `Axes` to make space for the new axes, default is ``0.`` if ``use_axesgrid=True`` is given (default), otherwise default is ``.15`` to match the upstream matplotlib default. **kwargs other keyword arguments to be passed to the :meth:`Plot.colorbar` generator Returns ------- cbar : `~matplotlib.colorbar.Colorbar` the newly added `Colorbar` See Also -------- Plot.colorbar
[ "Add", "a", "~matplotlib", ".", "colorbar", ".", "Colorbar", "to", "these", "Axes" ]
python
train
38.642857
fboender/ansible-cmdb
lib/mako/runtime.py
https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/lib/mako/runtime.py#L111-L118
def _pop_buffer_and_writer(self): """pop the most recent capturing buffer from this Context and return the current writer after the pop. """ buf = self._buffer_stack.pop() return buf, self._buffer_stack[-1].write
[ "def", "_pop_buffer_and_writer", "(", "self", ")", ":", "buf", "=", "self", ".", "_buffer_stack", ".", "pop", "(", ")", "return", "buf", ",", "self", ".", "_buffer_stack", "[", "-", "1", "]", ".", "write" ]
pop the most recent capturing buffer from this Context and return the current writer after the pop.
[ "pop", "the", "most", "recent", "capturing", "buffer", "from", "this", "Context", "and", "return", "the", "current", "writer", "after", "the", "pop", "." ]
python
train
30.875
ultrabug/py3status
py3status/modules/google_calendar.py
https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/google_calendar.py#L256-L316
def _get_events(self): """ Fetches events from the calendar into a list. Returns: The list of events. """ self.last_update = datetime.datetime.now() time_min = datetime.datetime.utcnow() time_max = time_min + datetime.timedelta(hours=self.events_within_hours) events = [] try: eventsResult = ( self.service.events() .list( calendarId="primary", timeMax=time_max.isoformat() + "Z", # 'Z' indicates UTC time timeMin=time_min.isoformat() + "Z", # 'Z' indicates UTC time singleEvents=True, orderBy="startTime", ) .execute(num_retries=5) ) except Exception: return self.events or events else: for event in eventsResult.get("items", []): # filter out events that we did not accept (default) # unless we organized them with no attendees i_organized = event.get("organizer", {}).get("self", False) has_attendees = event.get("attendees", []) for attendee in event.get("attendees", []): if attendee.get("self") is True: if attendee["responseStatus"] in self.response: break else: # we did not organize the event or we did not accept it if not i_organized or has_attendees: continue # strip and lower case output if needed for key in ["description", "location", "summary"]: event[key] = event.get(key, "").strip() if self.force_lowercase is True: event[key] = event[key].lower() # ignore all day events if configured if event["start"].get("date") is not None: if self.ignore_all_day_events: continue # filter out blacklisted event names if event["summary"] is not None: if event["summary"].lower() in map( lambda e: e.lower(), self.blacklist_events ): continue events.append(event) return events[: self.num_events]
[ "def", "_get_events", "(", "self", ")", ":", "self", ".", "last_update", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "time_min", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "time_max", "=", "time_min", "+", "datetime", ".", "...
Fetches events from the calendar into a list. Returns: The list of events.
[ "Fetches", "events", "from", "the", "calendar", "into", "a", "list", "." ]
python
train
39.344262
iclab/centinel
centinel/primitives/dnslib.py
https://github.com/iclab/centinel/blob/9a25dcf30c6a1db3c046f7ccb8ab8873e455c1a4/centinel/primitives/dnslib.py#L159-L261
def lookup_domain(self, domain, nameserver=None, log_prefix=''): """Most basic DNS primitive that looks up a domain, waits for a second response, then returns all of the results :param domain: the domain to lookup :param nameserver: the nameserver to use :param log_prefix: :return: Note: if you want to lookup multiple domains you *should not* use this function, you should use lookup_domains because this does blocking IO to wait for the second response """ if domain not in self.results: self.results[domain] = [] # get the resolver to use if nameserver is None: logging.debug("Nameserver not specified, using %s" % self.nameservers[0]) nameserver = self.nameservers[0] results = {'domain': domain, 'nameserver': nameserver} # construct the socket to use sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.settimeout(self.timeout) # set port number and increment index: interrupt = False with self.port_lock: counter = 1 while True: if counter > 100: logging.warning("Stop trying to get an available port") interrupt = True break try: sock.bind(('', self.port)) break except socket.error: logging.debug("Port {} already in use, try next one".format(self.port)) self.port += 1 counter += 1 self.port += 1 if interrupt: sock.close() results['error'] = 'Failed to run DNS test' self.results[domain].append(results) return results logging.debug("%sQuerying DNS enteries for " "%s (nameserver: %s)." % (log_prefix, domain, nameserver)) # construct and send the request request = dns.message.make_query(domain, dns.rdatatype.from_text(self.rtype)) results['request'] = b64encode(request.to_wire()) sock.sendto(request.to_wire(), (nameserver, 53)) # read the first response from the socket try: response = sock.recvfrom(4096)[0] results['response1'] = b64encode(response) resp = dns.message.from_wire(response) results['response1-ips'] = parse_out_ips(resp) # first domain name in response should be the same with query # domain name for entry in resp.answer: if domain.lower() != entry.name.to_text().lower()[:-1]: logging.debug("%sWrong domain name %s for %s!" % (log_prefix, entry.name.to_text().lower()[:-1], domain)) results['response1-domain'] = entry.name.to_text().lower()[:-1] break except socket.timeout: # if we didn't get anything, then set the results to nothing logging.debug("%sQuerying DNS enteries for " "%s (nameserver: %s) timed out!" % (log_prefix, domain, nameserver)) sock.close() results['response1'] = None self.results[domain].append(results) return results # if we have made it this far, then wait for the next response try: response2 = sock.recvfrom(4096)[0] results['response2'] = b64encode(response2) resp2 = dns.message.from_wire(response2) results['response2-ips'] = parse_out_ips(resp2) # first domain name in response should be the same with query # domain name for entry in resp2.answer: if domain.lower != entry.name.to_text().lower()[:-1]: logging.debug("%sWrong domain name %s for %s!" % (log_prefix, entry.name.to_text().lower()[:-1], domain)) results['response2-domain'] = entry.name.to_text().lower()[:-1] break except socket.timeout: # no second response results['response2'] = None sock.close() self.results[domain].append(results) return results
[ "def", "lookup_domain", "(", "self", ",", "domain", ",", "nameserver", "=", "None", ",", "log_prefix", "=", "''", ")", ":", "if", "domain", "not", "in", "self", ".", "results", ":", "self", ".", "results", "[", "domain", "]", "=", "[", "]", "# get th...
Most basic DNS primitive that looks up a domain, waits for a second response, then returns all of the results :param domain: the domain to lookup :param nameserver: the nameserver to use :param log_prefix: :return: Note: if you want to lookup multiple domains you *should not* use this function, you should use lookup_domains because this does blocking IO to wait for the second response
[ "Most", "basic", "DNS", "primitive", "that", "looks", "up", "a", "domain", "waits", "for", "a", "second", "response", "then", "returns", "all", "of", "the", "results" ]
python
train
41.514563
tylertreat/BigQuery-Python
bigquery/client.py
https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L1440-L1470
def _get_all_tables(self, dataset_id, cache=False, project_id=None): """Retrieve the list of tables for dataset, that respect the formats: * appid_YYYY_MM * YYYY_MM_appid Parameters ---------- dataset_id : str The dataset to retrieve table names for cache : bool, optional To use cached value or not (default False). Timeout value equals CACHE_TIMEOUT. project_id: str Unique ``str`` identifying the BigQuery project contains the dataset Returns ------- dict A ``dict`` of app ids mapped to their table names """ do_fetch = True if cache and self.cache.get(dataset_id): time, result = self.cache.get(dataset_id) if datetime.now() - time < CACHE_TIMEOUT: do_fetch = False if do_fetch: result = self._get_all_tables_for_dataset(dataset_id, project_id) self.cache[dataset_id] = (datetime.now(), result) return self._parse_table_list_response(result)
[ "def", "_get_all_tables", "(", "self", ",", "dataset_id", ",", "cache", "=", "False", ",", "project_id", "=", "None", ")", ":", "do_fetch", "=", "True", "if", "cache", "and", "self", ".", "cache", ".", "get", "(", "dataset_id", ")", ":", "time", ",", ...
Retrieve the list of tables for dataset, that respect the formats: * appid_YYYY_MM * YYYY_MM_appid Parameters ---------- dataset_id : str The dataset to retrieve table names for cache : bool, optional To use cached value or not (default False). Timeout value equals CACHE_TIMEOUT. project_id: str Unique ``str`` identifying the BigQuery project contains the dataset Returns ------- dict A ``dict`` of app ids mapped to their table names
[ "Retrieve", "the", "list", "of", "tables", "for", "dataset", "that", "respect", "the", "formats", ":", "*", "appid_YYYY_MM", "*", "YYYY_MM_appid" ]
python
train
35.096774
nerdvegas/rez
src/rez/vendor/pygraph/classes/hypergraph.py
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/classes/hypergraph.py#L188-L200
def del_node(self, node): """ Delete a given node from the hypergraph. @type node: node @param node: Node identifier. """ if self.has_node(node): for e in self.node_links[node]: self.edge_links[e].remove(node) self.node_links.pop(node) self.graph.del_node((node,'n'))
[ "def", "del_node", "(", "self", ",", "node", ")", ":", "if", "self", ".", "has_node", "(", "node", ")", ":", "for", "e", "in", "self", ".", "node_links", "[", "node", "]", ":", "self", ".", "edge_links", "[", "e", "]", ".", "remove", "(", "node",...
Delete a given node from the hypergraph. @type node: node @param node: Node identifier.
[ "Delete", "a", "given", "node", "from", "the", "hypergraph", "." ]
python
train
28.153846
pudo/mqlparser
mqlparser/util.py
https://github.com/pudo/mqlparser/blob/80f2e8c837a31ff1f5d0b8fb89dba9f3b2fef4bf/mqlparser/util.py#L9-L22
def parse_name(name): """ Split a query name into field name, operator and whether it is inverted. """ inverted, op = False, OP_EQ if name is not None: for op_ in (OP_NIN, OP_IN, OP_NOT, OP_LIKE): if name.endswith(op_): op = op_ name = name[:len(name) - len(op)] break if name.startswith('!'): inverted = True name = name[1:] return name, inverted, op
[ "def", "parse_name", "(", "name", ")", ":", "inverted", ",", "op", "=", "False", ",", "OP_EQ", "if", "name", "is", "not", "None", ":", "for", "op_", "in", "(", "OP_NIN", ",", "OP_IN", ",", "OP_NOT", ",", "OP_LIKE", ")", ":", "if", "name", ".", "e...
Split a query name into field name, operator and whether it is inverted.
[ "Split", "a", "query", "name", "into", "field", "name", "operator", "and", "whether", "it", "is", "inverted", "." ]
python
train
32.714286
Qiskit/qiskit-terra
qiskit/quantum_info/operators/channel/quantum_channel.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/channel/quantum_channel.py#L34-L37
def is_tp(self, atol=None, rtol=None): """Test if a channel is completely-positive (CP)""" choi = _to_choi(self.rep, self._data, *self.dim) return self._is_tp_helper(choi, atol, rtol)
[ "def", "is_tp", "(", "self", ",", "atol", "=", "None", ",", "rtol", "=", "None", ")", ":", "choi", "=", "_to_choi", "(", "self", ".", "rep", ",", "self", ".", "_data", ",", "*", "self", ".", "dim", ")", "return", "self", ".", "_is_tp_helper", "("...
Test if a channel is completely-positive (CP)
[ "Test", "if", "a", "channel", "is", "completely", "-", "positive", "(", "CP", ")" ]
python
test
51
gwastro/pycbc
pycbc/population/rates_functions.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/population/rates_functions.py#L298-L343
def prob_imf(m1, m2, s1z, s2z, **kwargs): ''' Return probability density for power-law Parameters ---------- m1: array Component masses 1 m2: array Component masses 2 s1z: array Aligned spin 1(Not in use currently) s2z: Aligned spin 2(Not in use currently) **kwargs: string Keyword arguments as model parameters Returns ------- p_m1_m2: array the probability density for m1, m2 pair ''' min_mass = kwargs.get('min_mass', 5.) max_mass = kwargs.get('max_mass', 95.) alpha = kwargs.get('alpha', -2.35) max_mtotal = min_mass + max_mass m1, m2 = np.array(m1), np.array(m2) C_imf = max_mass**(alpha + 1)/(alpha + 1) C_imf -= min_mass**(alpha + 1)/(alpha + 1) xx = np.minimum(m1, m2) m1 = np.maximum(m1, m2) m2 = xx bound = np.sign(max_mtotal - m1 - m2) bound += np.sign(max_mass - m1) * np.sign(m2 - min_mass) idx = np.where(bound != 2) p_m1_m2 = np.zeros_like(m1) idx = np.where(m1 <= max_mtotal/2.) p_m1_m2[idx] = (1./C_imf) * m1[idx]**alpha /(m1[idx] - min_mass) idx = np.where(m1 > max_mtotal/2.) p_m1_m2[idx] = (1./C_imf) * m1[idx]**alpha /(max_mass - m1[idx]) p_m1_m2[idx] = 0 return p_m1_m2/2.
[ "def", "prob_imf", "(", "m1", ",", "m2", ",", "s1z", ",", "s2z", ",", "*", "*", "kwargs", ")", ":", "min_mass", "=", "kwargs", ".", "get", "(", "'min_mass'", ",", "5.", ")", "max_mass", "=", "kwargs", ".", "get", "(", "'max_mass'", ",", "95.", ")...
Return probability density for power-law Parameters ---------- m1: array Component masses 1 m2: array Component masses 2 s1z: array Aligned spin 1(Not in use currently) s2z: Aligned spin 2(Not in use currently) **kwargs: string Keyword arguments as model parameters Returns ------- p_m1_m2: array the probability density for m1, m2 pair
[ "Return", "probability", "density", "for", "power", "-", "law", "Parameters", "----------", "m1", ":", "array", "Component", "masses", "1", "m2", ":", "array", "Component", "masses", "2", "s1z", ":", "array", "Aligned", "spin", "1", "(", "Not", "in", "use"...
python
train
28.152174
google/grr
grr/server/grr_response_server/hunts/implementation.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/hunts/implementation.py#L263-L331
def RunStateMethod(self, method_name, request=None, responses=None, event=None, direct_response=None): """Completes the request by calling the state method. Args: method_name: The name of the state method to call. request: A RequestState protobuf. responses: A list of GrrMessages responding to the request. event: A threading.Event() instance to signal completion of this request. direct_response: A flow.Responses() object can be provided to avoid creation of one. """ client_id = None try: self.context.current_state = method_name if request and responses: client_id = request.client_id or self.runner_args.client_id logging.debug("%s Running %s with %d responses from %s", self.session_id, method_name, len(responses), client_id) else: logging.debug("%s Running state method %s", self.session_id, method_name) # Extend our lease if needed. self.hunt_obj.HeartBeat() try: method = getattr(self.hunt_obj, method_name) except AttributeError: raise flow_runner.FlowRunnerError( "Flow %s has no state method %s" % (self.hunt_obj.__class__.__name__, method_name)) if direct_response: method(direct_response) elif method_name == "Start": method() else: # Prepare a responses object for the state method to use: responses = flow_responses.Responses.FromLegacyResponses( request=request, responses=responses) if responses.status: self.SaveResourceUsage(request.client_id, responses.status) stats_collector_instance.Get().IncrementCounter("grr_worker_states_run") method(responses) # We don't know here what exceptions can be thrown in the flow but we have # to continue. Thus, we catch everything. except Exception as e: # pylint: disable=broad-except # TODO(user): Deprecate in favor of 'flow_errors'. stats_collector_instance.Get().IncrementCounter("grr_flow_errors") stats_collector_instance.Get().IncrementCounter( "flow_errors", fields=[self.hunt_obj.Name()]) logging.exception("Hunt %s raised %s.", self.session_id, e) self.Error(traceback.format_exc(), client_id=client_id) finally: if event: event.set()
[ "def", "RunStateMethod", "(", "self", ",", "method_name", ",", "request", "=", "None", ",", "responses", "=", "None", ",", "event", "=", "None", ",", "direct_response", "=", "None", ")", ":", "client_id", "=", "None", "try", ":", "self", ".", "context", ...
Completes the request by calling the state method. Args: method_name: The name of the state method to call. request: A RequestState protobuf. responses: A list of GrrMessages responding to the request. event: A threading.Event() instance to signal completion of this request. direct_response: A flow.Responses() object can be provided to avoid creation of one.
[ "Completes", "the", "request", "by", "calling", "the", "state", "method", "." ]
python
train
35.217391
hozn/stravalib
stravalib/client.py
https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L166-L181
def _utc_datetime_to_epoch(self, activity_datetime): """ Convert the specified datetime value to a unix epoch timestamp (seconds since epoch). :param activity_datetime: A string which may contain tzinfo (offset) or a datetime object (naive datetime will be considered to be UTC). :return: Epoch timestamp. :rtype: int """ if isinstance(activity_datetime, str): activity_datetime = arrow.get(activity_datetime).datetime assert isinstance(activity_datetime, datetime) if activity_datetime.tzinfo: activity_datetime = activity_datetime.astimezone(pytz.utc) return calendar.timegm(activity_datetime.timetuple())
[ "def", "_utc_datetime_to_epoch", "(", "self", ",", "activity_datetime", ")", ":", "if", "isinstance", "(", "activity_datetime", ",", "str", ")", ":", "activity_datetime", "=", "arrow", ".", "get", "(", "activity_datetime", ")", ".", "datetime", "assert", "isinst...
Convert the specified datetime value to a unix epoch timestamp (seconds since epoch). :param activity_datetime: A string which may contain tzinfo (offset) or a datetime object (naive datetime will be considered to be UTC). :return: Epoch timestamp. :rtype: int
[ "Convert", "the", "specified", "datetime", "value", "to", "a", "unix", "epoch", "timestamp", "(", "seconds", "since", "epoch", ")", "." ]
python
train
45.875
twisted/txaws
txaws/client/base.py
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/client/base.py#L705-L714
def get_request_headers(self, *args, **kwds): """ A convenience method for obtaining the headers that were sent to the S3 server. The AWS S3 API depends upon setting headers. This method is provided as a convenience for debugging issues with the S3 communications. """ if self.request_headers: return self._unpack_headers(self.request_headers)
[ "def", "get_request_headers", "(", "self", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "if", "self", ".", "request_headers", ":", "return", "self", ".", "_unpack_headers", "(", "self", ".", "request_headers", ")" ]
A convenience method for obtaining the headers that were sent to the S3 server. The AWS S3 API depends upon setting headers. This method is provided as a convenience for debugging issues with the S3 communications.
[ "A", "convenience", "method", "for", "obtaining", "the", "headers", "that", "were", "sent", "to", "the", "S3", "server", "." ]
python
train
40.3
Azure/blobxfer
cli/settings.py
https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/cli/settings.py#L57-L271
def add_cli_options(cli_options, action): # type: (dict, str) -> None """Adds CLI options to the configuration object :param dict cli_options: CLI options dict :param TransferAction action: action """ cli_options['_action'] = action.name.lower() # if url is present, convert to constituent options if blobxfer.util.is_not_empty(cli_options.get('storage_url')): if (blobxfer.util.is_not_empty(cli_options.get('storage_account')) or blobxfer.util.is_not_empty(cli_options.get('mode')) or blobxfer.util.is_not_empty(cli_options.get('endpoint')) or blobxfer.util.is_not_empty(cli_options.get('remote_path'))): raise ValueError( 'Specified both --storage-url and --storage-account, ' '--mode, --endpoint, or --remote-path') cli_options['storage_account'], mode, \ cli_options['endpoint'], \ cli_options['remote_path'], \ sas = blobxfer.util.explode_azure_storage_url( cli_options['storage_url']) if blobxfer.util.is_not_empty(sas): if blobxfer.util.is_not_empty(cli_options['sas']): raise ValueError( 'Specified both --storage-url with a SAS token and --sas') cli_options['sas'] = sas if mode != 'blob' and mode != 'file': raise ValueError( 'Invalid derived mode from --storage-url: {}'.format(mode)) if mode == 'file': cli_options['mode'] = mode del mode del sas storage_account = cli_options.get('storage_account') azstorage = { 'endpoint': cli_options.get('endpoint') } if blobxfer.util.is_not_empty(storage_account): azstorage['accounts'] = { storage_account: ( cli_options.get('access_key') or cli_options.get('sas') ) } sa_rp = { storage_account: cli_options.get('remote_path') } local_resource = cli_options.get('local_resource') # construct "argument" from cli options if action == TransferAction.Download: arg = { 'source': [sa_rp] if sa_rp[storage_account] is not None else None, 'destination': local_resource if local_resource is not None else None, 'include': cli_options.get('include'), 'exclude': cli_options.get('exclude'), 'options': { 'check_file_md5': cli_options.get('file_md5'), 'chunk_size_bytes': cli_options.get('chunk_size_bytes'), 'delete_extraneous_destination': cli_options.get('delete'), 'max_single_object_concurrency': cli_options.get( 'max_single_object_concurrency'), 'mode': cli_options.get('mode'), 'overwrite': cli_options.get('overwrite'), 'recursive': cli_options.get('recursive'), 'rename': cli_options.get('rename'), 'rsa_private_key': cli_options.get('rsa_private_key'), 'rsa_private_key_passphrase': cli_options.get( 'rsa_private_key_passphrase'), 'restore_file_properties': { 'attributes': cli_options.get('file_attributes'), 'lmt': cli_options.get('restore_file_lmt'), 'md5': None, }, 'strip_components': cli_options.get('strip_components'), 'skip_on': { 'filesize_match': cli_options.get( 'skip_on_filesize_match'), 'lmt_ge': cli_options.get('skip_on_lmt_ge'), 'md5_match': cli_options.get('skip_on_md5_match'), }, }, } elif action == TransferAction.Synccopy: # if url is present, convert to constituent options if blobxfer.util.is_not_empty( cli_options.get('sync_copy_dest_storage_url')): if (blobxfer.util.is_not_empty( cli_options.get('sync_copy_dest_storage_account')) or blobxfer.util.is_not_empty( cli_options.get('sync_copy_dest_mode')) or blobxfer.util.is_not_empty( cli_options.get('sync_copy_dest_remote_path'))): raise ValueError( 'Specified both --sync-copy-dest-storage-url and ' '--sync-copy-dest-storage-account, ' '--sync-copy-dest-mode, or' '--sync-copy-dest-remote-path') cli_options['sync_copy_dest_storage_account'], mode, _, \ cli_options['sync_copy_dest_remote_path'], sas = \ blobxfer.util.explode_azure_storage_url( cli_options['sync_copy_dest_storage_url']) if blobxfer.util.is_not_empty(sas): if blobxfer.util.is_not_empty( cli_options['sync_copy_dest_sas']): raise ValueError( 'Specified both --sync-copy-dest-storage-url with ' 'a SAS token and --sync-copy-dest-sas') cli_options['sync_copy_dest_sas'] = sas if mode != 'blob' and mode != 'file': raise ValueError( 'Invalid derived destination mode from ' '--sync-copy-dest-storage-url: {}'.format(mode)) if mode == 'file': cli_options['dest_mode'] = mode del mode del sas sync_copy_dest_storage_account = cli_options.get( 'sync_copy_dest_storage_account') sync_copy_dest_remote_path = cli_options.get( 'sync_copy_dest_remote_path') if (sync_copy_dest_storage_account is not None and sync_copy_dest_remote_path is not None): sync_copy_dest = [ { sync_copy_dest_storage_account: sync_copy_dest_remote_path } ] azstorage['accounts'][sync_copy_dest_storage_account] = ( cli_options.get('sync_copy_dest_access_key') or cli_options.get('sync_copy_dest_sas') ) else: sync_copy_dest = None arg = { 'source': [sa_rp] if sa_rp[storage_account] is not None else None, 'destination': sync_copy_dest, 'include': cli_options.get('include'), 'exclude': cli_options.get('exclude'), 'options': { 'access_tier': cli_options.get('access_tier'), 'chunk_size_bytes': cli_options.get('chunk_size_bytes'), 'dest_mode': cli_options.get('sync_copy_dest_mode'), 'mode': cli_options.get('mode'), 'overwrite': cli_options.get('overwrite'), 'rename': cli_options.get('rename'), 'skip_on': { 'filesize_match': cli_options.get( 'skip_on_filesize_match'), 'lmt_ge': cli_options.get('skip_on_lmt_ge'), 'md5_match': cli_options.get('skip_on_md5_match'), }, }, } elif action == TransferAction.Upload: arg = { 'source': [local_resource] if local_resource is not None else None, 'destination': [sa_rp] if sa_rp[storage_account] is not None else None, 'include': cli_options.get('include'), 'exclude': cli_options.get('exclude'), 'options': { 'access_tier': cli_options.get('access_tier'), 'chunk_size_bytes': cli_options.get('chunk_size_bytes'), 'delete_extraneous_destination': cli_options.get('delete'), 'mode': cli_options.get('mode'), 'one_shot_bytes': cli_options.get('one_shot_bytes'), 'overwrite': cli_options.get('overwrite'), 'recursive': cli_options.get('recursive'), 'rename': cli_options.get('rename'), 'rsa_private_key': cli_options.get('rsa_private_key'), 'rsa_private_key_passphrase': cli_options.get( 'rsa_private_key_passphrase'), 'rsa_public_key': cli_options.get('rsa_public_key'), 'skip_on': { 'filesize_match': cli_options.get( 'skip_on_filesize_match'), 'lmt_ge': cli_options.get('skip_on_lmt_ge'), 'md5_match': cli_options.get('skip_on_md5_match'), }, 'stdin_as_page_blob_size': cli_options.get( 'stdin_as_page_blob_size'), 'store_file_properties': { 'attributes': cli_options.get('file_attributes'), 'cache_control': cli_options.get('file_cache_control'), 'lmt': None, 'md5': cli_options.get('file_md5'), }, 'strip_components': cli_options.get('strip_components'), 'vectored_io': { 'stripe_chunk_size_bytes': cli_options.get( 'stripe_chunk_size_bytes'), 'distribution_mode': cli_options.get('distribution_mode'), }, }, } count = 0 if arg['source'] is None: arg.pop('source') count += 1 if arg['destination'] is None: arg.pop('destination') count += 1 if count == 1: if action == TransferAction.Synccopy: raise ValueError( '--remote-path and --sync-copy-dest-remote-path must be ' 'specified together through the commandline') else: raise ValueError( '--local-path and --remote-path must be specified together ' 'through the commandline') if 'accounts' in azstorage: cli_options['azure_storage'] = azstorage cli_options[action.name.lower()] = arg
[ "def", "add_cli_options", "(", "cli_options", ",", "action", ")", ":", "# type: (dict, str) -> None", "cli_options", "[", "'_action'", "]", "=", "action", ".", "name", ".", "lower", "(", ")", "# if url is present, convert to constituent options", "if", "blobxfer", "."...
Adds CLI options to the configuration object :param dict cli_options: CLI options dict :param TransferAction action: action
[ "Adds", "CLI", "options", "to", "the", "configuration", "object", ":", "param", "dict", "cli_options", ":", "CLI", "options", "dict", ":", "param", "TransferAction", "action", ":", "action" ]
python
train
46.288372
saltstack/salt
salt/states/flatpak.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/flatpak.py#L124-L177
def add_remote(name, location): ''' Adds a new location to install flatpak packages from. Args: name (str): The repository's name. location (str): The location of the repository. Returns: dict: The ``result`` and ``output``. Example: .. code-block:: yaml add_flathub: flatpack.add_remote: - name: flathub - location: https://flathub.org/repo/flathub.flatpakrepo ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} old = __salt__['flatpak.is_remote_added'](name) if not old: if __opts__['test']: ret['comment'] = 'Remote "{0}" would have been added'.format(name) ret['changes']['new'] = name ret['changes']['old'] = None ret['result'] = None return ret install_ret = __salt__['flatpak.add_remote'](name) if __salt__['flatpak.is_remote_added'](name): ret['comment'] = 'Remote "{0}" was added'.format(name) ret['changes']['new'] = name ret['changes']['old'] = None ret['result'] = True return ret ret['comment'] = 'Failed to add remote "{0}"'.format(name) ret['comment'] += '\noutput:\n' + install_ret['output'] ret['result'] = False return ret ret['comment'] = 'Remote "{0}" already exists'.format(name) if __opts__['test']: ret['result'] = None return ret ret['result'] = True return ret
[ "def", "add_remote", "(", "name", ",", "location", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", "}", "old", "=", "__salt__", "[", "'flatpak.is_remote_added...
Adds a new location to install flatpak packages from. Args: name (str): The repository's name. location (str): The location of the repository. Returns: dict: The ``result`` and ``output``. Example: .. code-block:: yaml add_flathub: flatpack.add_remote: - name: flathub - location: https://flathub.org/repo/flathub.flatpakrepo
[ "Adds", "a", "new", "location", "to", "install", "flatpak", "packages", "from", "." ]
python
train
27.944444
fumitoh/modelx
modelx/core/spacecontainer.py
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/spacecontainer.py#L41-L52
def cur_space(self, name=None): """Set the current space to Space ``name`` and return it. If called without arguments, the current space is returned. Otherwise, the current space is set to the space named ``name`` and the space is returned. """ if name is None: return self._impl.model.currentspace.interface else: self._impl.model.currentspace = self._impl.spaces[name] return self.cur_space()
[ "def", "cur_space", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "return", "self", ".", "_impl", ".", "model", ".", "currentspace", ".", "interface", "else", ":", "self", ".", "_impl", ".", "model", ".", "currents...
Set the current space to Space ``name`` and return it. If called without arguments, the current space is returned. Otherwise, the current space is set to the space named ``name`` and the space is returned.
[ "Set", "the", "current", "space", "to", "Space", "name", "and", "return", "it", "." ]
python
valid
39.666667
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/__init__.py#L1244-L1249
def add_prerequisite(self, prerequisite): """Adds prerequisites""" if self.prerequisites is None: self.prerequisites = SCons.Util.UniqueList() self.prerequisites.extend(prerequisite) self._children_reset()
[ "def", "add_prerequisite", "(", "self", ",", "prerequisite", ")", ":", "if", "self", ".", "prerequisites", "is", "None", ":", "self", ".", "prerequisites", "=", "SCons", ".", "Util", ".", "UniqueList", "(", ")", "self", ".", "prerequisites", ".", "extend",...
Adds prerequisites
[ "Adds", "prerequisites" ]
python
train
40.666667