repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
jaraco/jaraco.windows
jaraco/windows/dpapi.py
https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/dpapi.py#L54-L57
def get_data(self): "Get the data for this blob" array = ctypes.POINTER(ctypes.c_char * len(self)) return ctypes.cast(self.data, array).contents.raw
[ "def", "get_data", "(", "self", ")", ":", "array", "=", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_char", "*", "len", "(", "self", ")", ")", "return", "ctypes", ".", "cast", "(", "self", ".", "data", ",", "array", ")", ".", "contents", ".", ...
Get the data for this blob
[ "Get", "the", "data", "for", "this", "blob" ]
python
train
obulpathi/cdn-fastly-python
fastly/__init__.py
https://github.com/obulpathi/cdn-fastly-python/blob/db2564b047e8af4bce72c3b88d6c27d3d0291425/fastly/__init__.py#L267-L270
def get_condition(self, service_id, version_number, name): """Gets a specified condition.""" content = self._fetch("/service/%s/version/%d/condition/%s" % (service_id, version_number, name)) return FastlyCondition(self, content)
[ "def", "get_condition", "(", "self", ",", "service_id", ",", "version_number", ",", "name", ")", ":", "content", "=", "self", ".", "_fetch", "(", "\"/service/%s/version/%d/condition/%s\"", "%", "(", "service_id", ",", "version_number", ",", "name", ")", ")", "...
Gets a specified condition.
[ "Gets", "a", "specified", "condition", "." ]
python
train
onicagroup/runway
runway/tfenv.py
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/tfenv.py#L127-L139
def get_version_requested(path): """Return string listing requested Terraform version.""" tf_version_path = os.path.join(path, TF_VERSION_FILENAME) if not os.path.isfile(tf_version_path): LOGGER.error("Terraform install attempted and no %s file present to " "dictate the version. Please create it (e.g. write " "\"0.11.13\" (without quotes) to the file and try again", TF_VERSION_FILENAME) sys.exit(1) with open(tf_version_path, 'r') as stream: ver = stream.read().rstrip() return ver
[ "def", "get_version_requested", "(", "path", ")", ":", "tf_version_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "TF_VERSION_FILENAME", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "tf_version_path", ")", ":", "LOGGER", ".", "...
Return string listing requested Terraform version.
[ "Return", "string", "listing", "requested", "Terraform", "version", "." ]
python
train
libtcod/python-tcod
tcod/tileset.py
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/tileset.py#L137-L157
def set_truetype_font(path: str, tile_width: int, tile_height: int) -> None: """Set the default tileset from a `.ttf` or `.otf` file. `path` is the file path for the font file. `tile_width` and `tile_height` are the desired size of the tiles in the new tileset. The font will be scaled to fit the given `tile_height` and `tile_width`. This function will only affect the `SDL2` and `OPENGL2` renderers. This function must be called before :any:`tcod.console_init_root`. Once the root console is setup you may call this funtion again to change the font. The tileset can be changed but the window will not be resized automatically. .. versionadded:: 9.2 """ if not os.path.exists(path): raise RuntimeError("File not found:\n\t%s" % (os.path.realpath(path),)) lib.TCOD_tileset_load_truetype_(path.encode(), tile_width, tile_height)
[ "def", "set_truetype_font", "(", "path", ":", "str", ",", "tile_width", ":", "int", ",", "tile_height", ":", "int", ")", "->", "None", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "RuntimeError", "(", "\"File not ...
Set the default tileset from a `.ttf` or `.otf` file. `path` is the file path for the font file. `tile_width` and `tile_height` are the desired size of the tiles in the new tileset. The font will be scaled to fit the given `tile_height` and `tile_width`. This function will only affect the `SDL2` and `OPENGL2` renderers. This function must be called before :any:`tcod.console_init_root`. Once the root console is setup you may call this funtion again to change the font. The tileset can be changed but the window will not be resized automatically. .. versionadded:: 9.2
[ "Set", "the", "default", "tileset", "from", "a", ".", "ttf", "or", ".", "otf", "file", "." ]
python
train
fr33jc/bang
bang/providers/hpcloud/v12/__init__.py
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/providers/hpcloud/v12/__init__.py#L40-L48
def find_servers(self, *args, **kwargs): """ Wraps :meth:`bang.providers.openstack.Nova.find_servers` to apply hpcloud specialization, namely pulling IP addresses from the hpcloud's non-standard return values. """ servers = super(HPNova, self).find_servers(*args, **kwargs) return map(fix_hp_addrs, servers)
[ "def", "find_servers", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "servers", "=", "super", "(", "HPNova", ",", "self", ")", ".", "find_servers", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "map", "(", "fix_hp_ad...
Wraps :meth:`bang.providers.openstack.Nova.find_servers` to apply hpcloud specialization, namely pulling IP addresses from the hpcloud's non-standard return values.
[ "Wraps", ":", "meth", ":", "bang", ".", "providers", ".", "openstack", ".", "Nova", ".", "find_servers", "to", "apply", "hpcloud", "specialization", "namely", "pulling", "IP", "addresses", "from", "the", "hpcloud", "s", "non", "-", "standard", "return", "val...
python
train
apache/incubator-mxnet
python/mxnet/executor_manager.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/executor_manager.py#L31-L66
def _split_input_slice(batch_size, work_load_list): """Get input slice from the input shape. Parameters ---------- batch_size : int The number of samples in a mini-batch. work_load_list : list of float or int, optional The list of work load for different devices, in the same order as `ctx`. Returns ------- slices : list of slice The split slices to get a specific slice. Raises ------ ValueError In case of too many splits, leading to some empty slices. """ total_work_load = sum(work_load_list) batch_num_list = [round(work_load * batch_size / total_work_load) for work_load in work_load_list] batch_num_sum = sum(batch_num_list) if batch_num_sum < batch_size: batch_num_list[-1] += batch_size - batch_num_sum slices = [] end = 0 for batch_num in batch_num_list: begin = int(min((end, batch_size))) end = int(min((begin + batch_num, batch_size))) if begin >= end: raise ValueError('Too many slices. Some splits are empty.') slices.append(slice(begin, end)) return slices
[ "def", "_split_input_slice", "(", "batch_size", ",", "work_load_list", ")", ":", "total_work_load", "=", "sum", "(", "work_load_list", ")", "batch_num_list", "=", "[", "round", "(", "work_load", "*", "batch_size", "/", "total_work_load", ")", "for", "work_load", ...
Get input slice from the input shape. Parameters ---------- batch_size : int The number of samples in a mini-batch. work_load_list : list of float or int, optional The list of work load for different devices, in the same order as `ctx`. Returns ------- slices : list of slice The split slices to get a specific slice. Raises ------ ValueError In case of too many splits, leading to some empty slices.
[ "Get", "input", "slice", "from", "the", "input", "shape", "." ]
python
train
hazelcast/hazelcast-python-client
hazelcast/proxy/multi_map.py
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/multi_map.py#L173-L195
def lock(self, key, lease_time=-1): """ Acquires the lock for the specified key infinitely or for the specified lease time if provided. If the lock is not available, the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired. Scope of the lock is this map only. Acquired lock is only for the key in this map. Locks are re-entrant; so, if the key is locked N times, it should be unlocked N times before another thread can acquire it. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key to lock. :param lease_time: (int), time in seconds to wait before releasing the lock (optional). """ check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(multi_map_lock_codec, key_data, key=key_data, thread_id=thread_id(), ttl=to_millis(lease_time), reference_id=self.reference_id_generator.get_and_increment())
[ "def", "lock", "(", "self", ",", "key", ",", "lease_time", "=", "-", "1", ")", ":", "check_not_none", "(", "key", ",", "\"key can't be None\"", ")", "key_data", "=", "self", ".", "_to_data", "(", "key", ")", "return", "self", ".", "_encode_invoke_on_key", ...
Acquires the lock for the specified key infinitely or for the specified lease time if provided. If the lock is not available, the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired. Scope of the lock is this map only. Acquired lock is only for the key in this map. Locks are re-entrant; so, if the key is locked N times, it should be unlocked N times before another thread can acquire it. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key to lock. :param lease_time: (int), time in seconds to wait before releasing the lock (optional).
[ "Acquires", "the", "lock", "for", "the", "specified", "key", "infinitely", "or", "for", "the", "specified", "lease", "time", "if", "provided", "." ]
python
train
angr/angr
angr/knowledge_plugins/variables/variable_manager.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/knowledge_plugins/variables/variable_manager.py#L301-L315
def get_phi_variables(self, block_addr): """ Get a dict of phi variables and their corresponding variables. :param int block_addr: Address of the block. :return: A dict of phi variables of an empty dict if there are no phi variables at the block. :rtype: dict """ if block_addr not in self._phi_variables_by_block: return dict() variables = { } for phi in self._phi_variables_by_block[block_addr]: variables[phi] = self._phi_variables[phi] return variables
[ "def", "get_phi_variables", "(", "self", ",", "block_addr", ")", ":", "if", "block_addr", "not", "in", "self", ".", "_phi_variables_by_block", ":", "return", "dict", "(", ")", "variables", "=", "{", "}", "for", "phi", "in", "self", ".", "_phi_variables_by_bl...
Get a dict of phi variables and their corresponding variables. :param int block_addr: Address of the block. :return: A dict of phi variables of an empty dict if there are no phi variables at the block. :rtype: dict
[ "Get", "a", "dict", "of", "phi", "variables", "and", "their", "corresponding", "variables", "." ]
python
train
EasyPost/pystalk
pystalk/client.py
https://github.com/EasyPost/pystalk/blob/96759ad1fda264b9897ee5346eef7926892a3a4c/pystalk/client.py#L268-L298
def put_job(self, data, pri=65536, delay=0, ttr=120): """Insert a new job into whatever queue is currently USEd :param data: Job body :type data: Text (either str which will be encoded as utf-8, or bytes which are already utf-8 :param pri: Priority for the job :type pri: int :param delay: Delay in seconds before the job should be placed on the ready queue :type delay: int :param ttr: Time to reserve (how long a worker may work on this job before we assume the worker is blocked and give the job to another worker :type ttr: int .. seealso:: :func:`put_job_into()` Put a job into a specific tube :func:`using()` Insert a job using an external guard """ with self._sock_ctx() as socket: message = 'put {pri} {delay} {ttr} {datalen}\r\n'.format( pri=pri, delay=delay, ttr=ttr, datalen=len(data), data=data ).encode('utf-8') if not isinstance(data, bytes): data = data.encode('utf-8') message += data message += b'\r\n' self._send_message(message, socket) return self._receive_id(socket)
[ "def", "put_job", "(", "self", ",", "data", ",", "pri", "=", "65536", ",", "delay", "=", "0", ",", "ttr", "=", "120", ")", ":", "with", "self", ".", "_sock_ctx", "(", ")", "as", "socket", ":", "message", "=", "'put {pri} {delay} {ttr} {datalen}\\r\\n'", ...
Insert a new job into whatever queue is currently USEd :param data: Job body :type data: Text (either str which will be encoded as utf-8, or bytes which are already utf-8 :param pri: Priority for the job :type pri: int :param delay: Delay in seconds before the job should be placed on the ready queue :type delay: int :param ttr: Time to reserve (how long a worker may work on this job before we assume the worker is blocked and give the job to another worker :type ttr: int .. seealso:: :func:`put_job_into()` Put a job into a specific tube :func:`using()` Insert a job using an external guard
[ "Insert", "a", "new", "job", "into", "whatever", "queue", "is", "currently", "USEd" ]
python
train
woolfson-group/isambard
isambard/ampal/base_ampal.py
https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/ampal/base_ampal.py#L853-L863
def unique_id(self): """Creates a unique ID for the `Atom` based on its parents. Returns ------- unique_id : (str, str, str) (polymer.id, residue.id, atom.id) """ chain = self.ampal_parent.ampal_parent.id residue = self.ampal_parent.id return chain, residue, self.id
[ "def", "unique_id", "(", "self", ")", ":", "chain", "=", "self", ".", "ampal_parent", ".", "ampal_parent", ".", "id", "residue", "=", "self", ".", "ampal_parent", ".", "id", "return", "chain", ",", "residue", ",", "self", ".", "id" ]
Creates a unique ID for the `Atom` based on its parents. Returns ------- unique_id : (str, str, str) (polymer.id, residue.id, atom.id)
[ "Creates", "a", "unique", "ID", "for", "the", "Atom", "based", "on", "its", "parents", "." ]
python
train
Nic30/hwt
hwt/hdl/statements.py
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/hdl/statements.py#L202-L242
def _on_reduce(self, self_reduced: bool, io_changed: bool, result_statements: List["HdlStatement"]) -> None: """ Update signal IO after reuce atempt :param self_reduced: if True this object was reduced :param io_changed: if True IO of this object may changed and has to be updated :param result_statements: list of statements which are result of reduce operation on this statement """ parentStm = self.parentStm if self_reduced: was_top = parentStm is None # update signal drivers/endpoints if was_top: # disconnect self from signals ctx = self._get_rtl_context() ctx.statements.remove(self) ctx.statements.update(result_statements) for i in self._inputs: i.endpoints.discard(self) for o in self._outputs: o.drivers.remove(self) for stm in result_statements: stm.parentStm = parentStm if parentStm is None: # conect signals to child statements for inp in stm._inputs: inp.endpoints.append(stm) for outp in stm._outputs: outp.drivers.append(stm) else: # parent has to update it's inputs/outputs if io_changed: self._inputs = UniqList() self._outputs = UniqList() self._collect_io()
[ "def", "_on_reduce", "(", "self", ",", "self_reduced", ":", "bool", ",", "io_changed", ":", "bool", ",", "result_statements", ":", "List", "[", "\"HdlStatement\"", "]", ")", "->", "None", ":", "parentStm", "=", "self", ".", "parentStm", "if", "self_reduced",...
Update signal IO after reuce atempt :param self_reduced: if True this object was reduced :param io_changed: if True IO of this object may changed and has to be updated :param result_statements: list of statements which are result of reduce operation on this statement
[ "Update", "signal", "IO", "after", "reuce", "atempt" ]
python
test
hfaran/progressive
progressive/bar.py
https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/bar.py#L339-L408
def draw(self, value, newline=True, flush=True): """Draw the progress bar :type value: int :param value: Progress value relative to ``self.max_value`` :type newline: bool :param newline: If this is set, a newline will be written after drawing """ # This is essentially winch-handling without having # to do winch-handling; cleanly redrawing on winch is difficult # and out of the intended scope of this class; we *can* # however, adjust the next draw to be proper by re-measuring # the terminal since the code is mostly written dynamically # and many attributes and dynamically calculated properties. self._measure_terminal() # To avoid zero division, set amount_complete to 100% if max_value has been stupidly set to 0 amount_complete = 1.0 if self.max_value == 0 else value / self.max_value fill_amount = int(floor(amount_complete * self.max_width)) empty_amount = self.max_width - fill_amount # e.g., '10/20' if 'fraction' or '50%' if 'percentage' amount_complete_str = ( u"{}/{}".format(value, self.max_value) if self._num_rep == "fraction" else u"{}%".format(int(floor(amount_complete * 100))) ) # Write title if supposed to be above if self._title_pos == "above": title_str = u"{}{}\n".format( " " * self._indent, self.title, ) self._write(title_str, ignore_overflow=True) # Construct just the progress bar bar_str = u''.join([ u(self.filled(self._filled_char * fill_amount)), u(self.empty(self._empty_char * empty_amount)), ]) # Wrap with start and end character bar_str = u"{}{}{}".format(self.start_char, bar_str, self.end_char) # Add on title if supposed to be on left or right if self._title_pos == "left": bar_str = u"{} {}".format(self.title, bar_str) elif self._title_pos == "right": bar_str = u"{} {}".format(bar_str, self.title) # Add indent bar_str = u''.join([" " * self._indent, bar_str]) # Add complete percentage or fraction bar_str = u"{} {}".format(bar_str, amount_complete_str) # Set back to normal after printing bar_str = u"{}{}".format(bar_str, self.term.normal) # Finally, write the completed bar_str self._write(bar_str, s_length=self.full_line_width) # Write title if supposed to be below if self._title_pos == "below": title_str = u"\n{}{}".format( " " * self._indent, self.title, ) self._write(title_str, ignore_overflow=True) # Newline to wrap up if newline: self.cursor.newline() if flush: self.cursor.flush()
[ "def", "draw", "(", "self", ",", "value", ",", "newline", "=", "True", ",", "flush", "=", "True", ")", ":", "# This is essentially winch-handling without having", "# to do winch-handling; cleanly redrawing on winch is difficult", "# and out of the intended scope of this class...
Draw the progress bar :type value: int :param value: Progress value relative to ``self.max_value`` :type newline: bool :param newline: If this is set, a newline will be written after drawing
[ "Draw", "the", "progress", "bar" ]
python
train
smarie/python-valid8
valid8/validation_lib/collections.py
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/validation_lib/collections.py#L106-L121
def has_length(ref_length): """ 'length equals' validation function generator. Returns a validation_function to check that `len(x) == ref_length` :param ref_length: :return: """ def has_length_(x): if len(x) == ref_length: return True else: raise WrongLength(wrong_value=x, ref_length=ref_length) has_length_.__name__ = 'length_equals_{}'.format(ref_length) return has_length_
[ "def", "has_length", "(", "ref_length", ")", ":", "def", "has_length_", "(", "x", ")", ":", "if", "len", "(", "x", ")", "==", "ref_length", ":", "return", "True", "else", ":", "raise", "WrongLength", "(", "wrong_value", "=", "x", ",", "ref_length", "="...
'length equals' validation function generator. Returns a validation_function to check that `len(x) == ref_length` :param ref_length: :return:
[ "length", "equals", "validation", "function", "generator", ".", "Returns", "a", "validation_function", "to", "check", "that", "len", "(", "x", ")", "==", "ref_length" ]
python
train
apple/turicreate
deps/src/libxml2-2.9.1/python/libxml2.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L7307-L7310
def registerXPathFunction(self, name, ns_uri, f): """Register a Python written function to the XPath interpreter """ ret = libxml2mod.xmlRegisterXPathFunction(self._o, name, ns_uri, f) return ret
[ "def", "registerXPathFunction", "(", "self", ",", "name", ",", "ns_uri", ",", "f", ")", ":", "ret", "=", "libxml2mod", ".", "xmlRegisterXPathFunction", "(", "self", ".", "_o", ",", "name", ",", "ns_uri", ",", "f", ")", "return", "ret" ]
Register a Python written function to the XPath interpreter
[ "Register", "a", "Python", "written", "function", "to", "the", "XPath", "interpreter" ]
python
train
laf/russound
russound/russound.py
https://github.com/laf/russound/blob/683af823f78ad02111f9966dc7b535dd66a1f083/russound/russound.py#L235-L251
def send_data(self, data, delay=COMMAND_DELAY): """ Send data to connected gateway """ time_since_last_send = time.time() - self._last_send delay = max(0, delay - time_since_last_send) time.sleep(delay) # Ensure minim recommended delay since last send for item in data: data = bytes.fromhex(str(item.zfill(2))) try: self.sock.send(data) except ConnectionResetError as msg: _LOGGER.error("Error trying to connect to Russound controller. " "Check that no other device or system is using the port that " "you are trying to connect to. Try resetting the bridge you are using to connect.") _LOGGER.error(msg) self._last_send = time.time()
[ "def", "send_data", "(", "self", ",", "data", ",", "delay", "=", "COMMAND_DELAY", ")", ":", "time_since_last_send", "=", "time", ".", "time", "(", ")", "-", "self", ".", "_last_send", "delay", "=", "max", "(", "0", ",", "delay", "-", "time_since_last_sen...
Send data to connected gateway
[ "Send", "data", "to", "connected", "gateway" ]
python
train
bihealth/vcfpy
vcfpy/record.py
https://github.com/bihealth/vcfpy/blob/99e2165df30f11e0c95f3170f31bc5191d9e9e15/vcfpy/record.py#L100-L114
def affected_start(self): """Return affected start position in 0-based coordinates For SNVs, MNVs, and deletions, the behaviour is the start position. In the case of insertions, the position behind the insert position is returned, yielding a 0-length interval together with :py:meth:`~Record.affected_end` """ types = {alt.type for alt in self.ALT} # set! BAD_MIX = {INS, SV, BND, SYMBOLIC} # don't mix well with others if (BAD_MIX & types) and len(types) == 1 and list(types)[0] == INS: # Only insertions, return 0-based position right of first base return self.POS # right of first base else: # Return 0-based start position of first REF base return self.POS - 1
[ "def", "affected_start", "(", "self", ")", ":", "types", "=", "{", "alt", ".", "type", "for", "alt", "in", "self", ".", "ALT", "}", "# set!", "BAD_MIX", "=", "{", "INS", ",", "SV", ",", "BND", ",", "SYMBOLIC", "}", "# don't mix well with others", "if",...
Return affected start position in 0-based coordinates For SNVs, MNVs, and deletions, the behaviour is the start position. In the case of insertions, the position behind the insert position is returned, yielding a 0-length interval together with :py:meth:`~Record.affected_end`
[ "Return", "affected", "start", "position", "in", "0", "-", "based", "coordinates" ]
python
train
cloud-custodian/cloud-custodian
tools/c7n_gcp/c7n_gcp/client.py
https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_gcp/c7n_gcp/client.py#L465-L482
def _execute(self, request): """Run execute with retries and rate limiting. Args: request (object): The HttpRequest object to execute. Returns: dict: The response from the API. """ if self._rate_limiter: # Since the ratelimiter library only exposes a context manager # interface the code has to be duplicated to handle the case where # no rate limiter is defined. with self._rate_limiter: return request.execute(http=self.http, num_retries=self._num_retries) return request.execute(http=self.http, num_retries=self._num_retries)
[ "def", "_execute", "(", "self", ",", "request", ")", ":", "if", "self", ".", "_rate_limiter", ":", "# Since the ratelimiter library only exposes a context manager", "# interface the code has to be duplicated to handle the case where", "# no rate limiter is defined.", "with", "self"...
Run execute with retries and rate limiting. Args: request (object): The HttpRequest object to execute. Returns: dict: The response from the API.
[ "Run", "execute", "with", "retries", "and", "rate", "limiting", "." ]
python
train
allelos/vectors
vectors/vectors.py
https://github.com/allelos/vectors/blob/55db2a7e489ae5f4380e70b3c5b7a6ce39de5cee/vectors/vectors.py#L62-L71
def from_list(cls, l): """Return a Point instance from a given list""" if len(l) == 3: x, y, z = map(float, l) return cls(x, y, z) elif len(l) == 2: x, y = map(float, l) return cls(x, y) else: raise AttributeError
[ "def", "from_list", "(", "cls", ",", "l", ")", ":", "if", "len", "(", "l", ")", "==", "3", ":", "x", ",", "y", ",", "z", "=", "map", "(", "float", ",", "l", ")", "return", "cls", "(", "x", ",", "y", ",", "z", ")", "elif", "len", "(", "l...
Return a Point instance from a given list
[ "Return", "a", "Point", "instance", "from", "a", "given", "list" ]
python
train
F-Secure/see
plugins/disk.py
https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/plugins/disk.py#L192-L205
def start_processing_handler(self, event): """Asynchronous handler starting the disk analysis process.""" results_path = os.path.join(self.configuration['results_folder'], "filesystem.json") self.logger.debug("Event %s: start comparing %s with %s.", event, self.checkpoints[0], self.checkpoints[1]) results = compare_disks(self.checkpoints[0], self.checkpoints[1], self.configuration) with open(results_path, 'w') as results_file: json.dump(results, results_file) self.processing_done.set()
[ "def", "start_processing_handler", "(", "self", ",", "event", ")", ":", "results_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "configuration", "[", "'results_folder'", "]", ",", "\"filesystem.json\"", ")", "self", ".", "logger", ".", "debug"...
Asynchronous handler starting the disk analysis process.
[ "Asynchronous", "handler", "starting", "the", "disk", "analysis", "process", "." ]
python
train
tobami/littlechef
littlechef/lib.py
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L271-L348
def get_recipes_in_cookbook(name): """Gets the name of all recipes present in a cookbook Returns a list of dictionaries """ recipes = {} path = None cookbook_exists = False metadata_exists = False for cookbook_path in cookbook_paths: path = os.path.join(cookbook_path, name) path_exists = os.path.exists(path) # cookbook exists if present in any of the cookbook paths cookbook_exists = cookbook_exists or path_exists if not path_exists: continue _generate_metadata(path, cookbook_path, name) # Now try to open metadata.json try: with open(os.path.join(path, 'metadata.json'), 'r') as f: try: cookbook = json.loads(f.read()) except ValueError as e: msg = "Little Chef found the following error in your" msg += " {0} file:\n {1}".format( os.path.join(path, 'metadata.json'), e) abort(msg) # Add each recipe defined in the cookbook metadata_exists = True recipe_defaults = { 'description': '', 'version': cookbook.get('version'), 'dependencies': cookbook.get('dependencies', {}).keys(), 'attributes': cookbook.get('attributes', {}) } for recipe in cookbook.get('recipes', []): recipes[recipe] = dict( recipe_defaults, name=recipe, description=cookbook['recipes'][recipe] ) # Cookbook metadata.json was found, don't try next cookbook path # because metadata.json in site-cookbooks has preference break except IOError: # metadata.json was not found, try next cookbook_path pass if not cookbook_exists: abort('Unable to find cookbook "{0}"'.format(name)) elif not metadata_exists: abort('Cookbook "{0}" has no metadata.json'.format(name)) # Add recipes found in the 'recipes' directory but not listed # in the metadata for cookbook_path in cookbook_paths: recipes_dir = os.path.join(cookbook_path, name, 'recipes') if not os.path.isdir(recipes_dir): continue for basename in os.listdir(recipes_dir): fname, ext = os.path.splitext(basename) if ext != '.rb': continue if fname != 'default': recipe = '%s::%s' % (name, fname) else: recipe = name if recipe not in recipes: recipes[recipe] = dict(recipe_defaults, name=recipe) # When a recipe has no default recipe (libraries?), # add one so that it is listed if not recipes: recipes[name] = dict( recipe_defaults, name=name, description='This cookbook has no default recipe' ) return recipes.values()
[ "def", "get_recipes_in_cookbook", "(", "name", ")", ":", "recipes", "=", "{", "}", "path", "=", "None", "cookbook_exists", "=", "False", "metadata_exists", "=", "False", "for", "cookbook_path", "in", "cookbook_paths", ":", "path", "=", "os", ".", "path", "."...
Gets the name of all recipes present in a cookbook Returns a list of dictionaries
[ "Gets", "the", "name", "of", "all", "recipes", "present", "in", "a", "cookbook", "Returns", "a", "list", "of", "dictionaries" ]
python
train
LonamiWebs/Telethon
telethon/helpers.py
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/helpers.py#L36-L73
def strip_text(text, entities): """ Strips whitespace from the given text modifying the provided entities. This assumes that there are no overlapping entities, that their length is greater or equal to one, and that their length is not out of bounds. """ if not entities: return text.strip() while text and text[-1].isspace(): e = entities[-1] if e.offset + e.length == len(text): if e.length == 1: del entities[-1] if not entities: return text.strip() else: e.length -= 1 text = text[:-1] while text and text[0].isspace(): for i in reversed(range(len(entities))): e = entities[i] if e.offset != 0: e.offset -= 1 continue if e.length == 1: del entities[0] if not entities: return text.lstrip() else: e.length -= 1 text = text[1:] return text
[ "def", "strip_text", "(", "text", ",", "entities", ")", ":", "if", "not", "entities", ":", "return", "text", ".", "strip", "(", ")", "while", "text", "and", "text", "[", "-", "1", "]", ".", "isspace", "(", ")", ":", "e", "=", "entities", "[", "-"...
Strips whitespace from the given text modifying the provided entities. This assumes that there are no overlapping entities, that their length is greater or equal to one, and that their length is not out of bounds.
[ "Strips", "whitespace", "from", "the", "given", "text", "modifying", "the", "provided", "entities", "." ]
python
train
robotools/fontParts
Lib/fontParts/base/contour.py
https://github.com/robotools/fontParts/blob/d2ff106fe95f9d566161d936a645157626568712/Lib/fontParts/base/contour.py#L141-L154
def getIdentifierForPoint(self, point): """ Create a unique identifier for and assign it to ``point``. If the point already has an identifier, the existing identifier will be returned. >>> contour.getIdentifierForPoint(point) 'ILHGJlygfds' ``point`` must be a :class:`BasePoint`. The returned value will be a :ref:`type-identifier`. """ point = normalizers.normalizePoint(point) return self._getIdentifierforPoint(point)
[ "def", "getIdentifierForPoint", "(", "self", ",", "point", ")", ":", "point", "=", "normalizers", ".", "normalizePoint", "(", "point", ")", "return", "self", ".", "_getIdentifierforPoint", "(", "point", ")" ]
Create a unique identifier for and assign it to ``point``. If the point already has an identifier, the existing identifier will be returned. >>> contour.getIdentifierForPoint(point) 'ILHGJlygfds' ``point`` must be a :class:`BasePoint`. The returned value will be a :ref:`type-identifier`.
[ "Create", "a", "unique", "identifier", "for", "and", "assign", "it", "to", "point", ".", "If", "the", "point", "already", "has", "an", "identifier", "the", "existing", "identifier", "will", "be", "returned", "." ]
python
train
edibledinos/pwnypack
pwnypack/elf.py
https://github.com/edibledinos/pwnypack/blob/e0a5a8e6ef3f4f1f7e1b91ee379711f4a49cb0e6/pwnypack/elf.py#L1039-L1194
def checksec_app(_parser, _, args): # pragma: no cover """ Check security features of an ELF file. """ import sys import argparse import csv import os.path def checksec(elf, path, fortifiable_funcs): relro = 0 nx = False pie = 0 rpath = False runpath = False for header in elf.program_headers: if header.type == ELF.ProgramHeader.Type.gnu_relro: relro = 1 elif header.type == ELF.ProgramHeader.Type.gnu_stack: if not header.flags & ELF.ProgramHeader.Flags.x: nx = True if elf.type == ELF.Type.shared: pie = 1 for entry in elf.dynamic_section_entries: if entry.type == ELF.DynamicSectionEntry.Type.bind_now and relro == 1: relro = 2 elif entry.type == ELF.DynamicSectionEntry.Type.flags and \ entry.value & ELF.DynamicSectionEntry.Flags.bind_now: relro = 2 elif entry.type == ELF.DynamicSectionEntry.Type.flags_1 and \ entry.value & ELF.DynamicSectionEntry.Flags_1.now: relro = 2 elif entry.type == ELF.DynamicSectionEntry.Type.debug and pie == 1: pie = 2 elif entry.type == ELF.DynamicSectionEntry.Type.rpath: rpath = True elif entry.type == ELF.DynamicSectionEntry.Type.runpath: runpath = True rtl_symbol_names = set( symbol.name for symbol in elf.symbols if symbol.name and symbol.shndx == ELF.Symbol.SpecialSection.undef ) fortified = fortifiable_funcs & rtl_symbol_names unfortified = fortifiable_funcs & set('__%s_chk' % symbol_name for symbol_name in rtl_symbol_names) canary = '__stack_chk_fail' in rtl_symbol_names return { 'path': path, 'relro': relro, 'nx': nx, 'pie': pie, 'rpath': rpath, 'runpath': runpath, 'canary': canary, 'fortified': len(fortified), 'unfortified': len(unfortified), 'fortifiable': len(fortified | unfortified), } def check_paths(paths, fortifiable_funcs): for path in paths: if os.path.isdir(path): for data in check_paths( (os.path.join(path, fn) for fn in os.listdir(path) if fn not in ('.', '..')), fortifiable_funcs, ): yield data else: try: elf = ELF(path) except: continue yield checksec(elf, path, fortifiable_funcs) parser = argparse.ArgumentParser( prog=_parser.prog, description=_parser.description, ) parser.add_argument('path', nargs='+', help='ELF file to check security features of') parser.add_argument( '-f', '--format', dest='format', choices=['text', 'csv'], default='text', help='set output format' ) parser.add_argument( '-l', '--libc', dest='libc', help='path to the applicable libc.so' ) args = parser.parse_args(args) if args.libc: libc = ELF(args.libc) fortifiable_funcs = set([ symbol.name for symbol in libc.symbols if symbol.name.startswith('__') and symbol.name.endswith('_chk') ]) else: fortifiable_funcs = set('''__wctomb_chk __wcsncat_chk __mbstowcs_chk __strncpy_chk __syslog_chk __mempcpy_chk __fprintf_chk __recvfrom_chk __readlinkat_chk __wcsncpy_chk __fread_chk __getlogin_r_chk __vfwprintf_chk __recv_chk __strncat_chk __printf_chk __confstr_chk __pread_chk __ppoll_chk __ptsname_r_chk __wcscat_chk __snprintf_chk __vwprintf_chk __memset_chk __memmove_chk __gets_chk __fgetws_unlocked_chk __asprintf_chk __poll_chk __fdelt_chk __fgets_unlocked_chk __strcat_chk __vsyslog_chk __stpcpy_chk __vdprintf_chk __strcpy_chk __obstack_printf_chk __getwd_chk __pread64_chk __wcpcpy_chk __fread_unlocked_chk __dprintf_chk __fgets_chk __wcpncpy_chk __obstack_vprintf_chk __wprintf_chk __getgroups_chk __wcscpy_chk __vfprintf_chk __fgetws_chk __vswprintf_chk __ttyname_r_chk __mbsrtowcs_chk __wmempcpy_chk __wcsrtombs_chk __fwprintf_chk __read_chk __getcwd_chk __vsnprintf_chk __memcpy_chk __wmemmove_chk __vasprintf_chk __sprintf_chk __vprintf_chk __mbsnrtowcs_chk __wcrtomb_chk __realpath_chk __vsprintf_chk __wcsnrtombs_chk __gethostname_chk __swprintf_chk __readlink_chk __wmemset_chk __getdomainname_chk __wmemcpy_chk __longjmp_chk __stpncpy_chk __wcstombs_chk'''.split()) if args.format == 'text': print('RELRO CANARY NX PIE RPATH RUNPATH FORTIFIED PATH') for data in check_paths(args.path, fortifiable_funcs): print('{:7} {:6} {:3} {:3} {:5} {:7} {:>9} {}'.format( ('No', 'Partial', 'Full')[data['relro']], 'Yes' if data['canary'] else 'No', 'Yes' if data['nx'] else 'No', ('No', 'DSO', 'Yes')[data['pie']], 'Yes' if data['rpath'] else 'No', 'Yes' if data['runpath'] else 'No', '{}/{}/{}'.format(data['fortified'], data['unfortified'], data['fortifiable']), data['path'] )) else: writer = csv.writer(sys.stdout) writer.writerow(['path', 'relro', 'canary', 'nx', 'pie', 'rpath', 'runpath', 'fortified', 'unfortified', 'fortifiable']) for data in check_paths(args.path, fortifiable_funcs): writer.writerow([ data['path'], ('no', 'partial', 'full')[data['relro']], 'yes' if data['canary'] else 'no', 'yes' if data['nx'] else 'no', ('no', 'dso', 'yes')[data['pie']], 'yes' if data['rpath'] else 'no', 'yes' if data['runpath'] else 'no', data['fortified'], data['unfortified'], data['fortifiable'], ])
[ "def", "checksec_app", "(", "_parser", ",", "_", ",", "args", ")", ":", "# pragma: no cover", "import", "sys", "import", "argparse", "import", "csv", "import", "os", ".", "path", "def", "checksec", "(", "elf", ",", "path", ",", "fortifiable_funcs", ")", ":...
Check security features of an ELF file.
[ "Check", "security", "features", "of", "an", "ELF", "file", "." ]
python
train
pyviz/holoviews
holoviews/core/util.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/util.py#L545-L555
def capitalize_unicode_name(s): """ Turns a string such as 'capital delta' into the shortened, capitalized version, in this case simply 'Delta'. Used as a transform in sanitize_identifier. """ index = s.find('capital') if index == -1: return s tail = s[index:].replace('capital', '').strip() tail = tail[0].upper() + tail[1:] return s[:index] + tail
[ "def", "capitalize_unicode_name", "(", "s", ")", ":", "index", "=", "s", ".", "find", "(", "'capital'", ")", "if", "index", "==", "-", "1", ":", "return", "s", "tail", "=", "s", "[", "index", ":", "]", ".", "replace", "(", "'capital'", ",", "''", ...
Turns a string such as 'capital delta' into the shortened, capitalized version, in this case simply 'Delta'. Used as a transform in sanitize_identifier.
[ "Turns", "a", "string", "such", "as", "capital", "delta", "into", "the", "shortened", "capitalized", "version", "in", "this", "case", "simply", "Delta", ".", "Used", "as", "a", "transform", "in", "sanitize_identifier", "." ]
python
train
DataBiosphere/toil
src/toil/wdl/wdl_analysis.py
https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/wdl/wdl_analysis.py#L334-L385
def parse_task_outputs(self, i): ''' Parse the WDL output section. Outputs are like declarations, with a type, name, and value. Examples: ------------ Simple Cases ------------ 'Int num = 7' var_name: 'num' var_type: 'Int' var_value: 7 String idea = 'Lab grown golden eagle burgers.' var_name: 'idea' var_type: 'String' var_value: 'Lab grown golden eagle burgers.' File ideaFile = 'goldenEagleStemCellStartUpDisrupt.txt' var_name: 'ideaFile' var_type: 'File' var_value: 'goldenEagleStemCellStartUpDisrupt.txt' ------------------- More Abstract Cases ------------------- Array[File] allOfMyTerribleIdeas = glob(*.txt)[0] var_name: 'allOfMyTerribleIdeas' var_type**: 'File' var_value: [*.txt] var_actions: {'index_lookup': '0', 'glob': 'None'} **toilwdl.py converts 'Array[File]' to 'ArrayFile' :return: output_array representing outputs generated by the job/task: e.g. x = [(var_name, var_type, var_value, var_actions), ...] ''' output_array = [] for j in i.attributes['attributes']: if j.name == 'Output': var_name = self.parse_declaration_name(j.attr("name")) var_type = self.parse_declaration_type(j.attr("type")) var_expressn = self.parse_declaration_expressn(j.attr("expression"), es='', output_expressn=True) if not (var_expressn.startswith('(') and var_expressn.endswith(')')): var_expressn = self.translate_wdl_string_to_python_string(var_expressn) output_array.append((var_name, var_type, var_expressn)) else: raise NotImplementedError return output_array
[ "def", "parse_task_outputs", "(", "self", ",", "i", ")", ":", "output_array", "=", "[", "]", "for", "j", "in", "i", ".", "attributes", "[", "'attributes'", "]", ":", "if", "j", ".", "name", "==", "'Output'", ":", "var_name", "=", "self", ".", "parse_...
Parse the WDL output section. Outputs are like declarations, with a type, name, and value. Examples: ------------ Simple Cases ------------ 'Int num = 7' var_name: 'num' var_type: 'Int' var_value: 7 String idea = 'Lab grown golden eagle burgers.' var_name: 'idea' var_type: 'String' var_value: 'Lab grown golden eagle burgers.' File ideaFile = 'goldenEagleStemCellStartUpDisrupt.txt' var_name: 'ideaFile' var_type: 'File' var_value: 'goldenEagleStemCellStartUpDisrupt.txt' ------------------- More Abstract Cases ------------------- Array[File] allOfMyTerribleIdeas = glob(*.txt)[0] var_name: 'allOfMyTerribleIdeas' var_type**: 'File' var_value: [*.txt] var_actions: {'index_lookup': '0', 'glob': 'None'} **toilwdl.py converts 'Array[File]' to 'ArrayFile' :return: output_array representing outputs generated by the job/task: e.g. x = [(var_name, var_type, var_value, var_actions), ...]
[ "Parse", "the", "WDL", "output", "section", "." ]
python
train
TangoAlpha/liffylights
liffylights.py
https://github.com/TangoAlpha/liffylights/blob/7ae9ed947ecf039734014d98b6e18de0f26fa1d3/liffylights.py#L368-L419
def _command_sender(self): """ Command sender. """ sequence = -1 while True: cmd = self._queue.get() ipaddr = cmd["target"] payloadtype = cmd["payloadtype"] if "sequence" not in cmd: # get next sequence number if we haven't got one sequence = (sequence + 1) % SEQUENCE_COUNT cmd["sequence"] = sequence + SEQUENCE_BASE packet = None if payloadtype == PayloadType.SETCOLOR: packet = self._gen_packet_setcolor(cmd["sequence"], cmd["hue"], cmd["sat"], cmd["bri"], cmd["kel"], cmd["fade"]) elif payloadtype == PayloadType.SETPOWER2: packet = self._gen_packet_setpower(cmd["sequence"], cmd["power"], cmd["fade"]) elif payloadtype == PayloadType.GET: packet = self._gen_packet_get(cmd["sequence"]) if packet is not None: try: self._sock.sendto(packet, (ipaddr, UDP_PORT)) now = time.time() # set timeout if "timeout" not in cmd: cmd["timeout"] = now + ACK_TIMEOUT # set earliest resend time cmd["resend"] = now + ACK_RESEND with self._packet_lock: self._packets.append(cmd) # pylint: disable=broad-except except Exception: pass
[ "def", "_command_sender", "(", "self", ")", ":", "sequence", "=", "-", "1", "while", "True", ":", "cmd", "=", "self", ".", "_queue", ".", "get", "(", ")", "ipaddr", "=", "cmd", "[", "\"target\"", "]", "payloadtype", "=", "cmd", "[", "\"payloadtype\"", ...
Command sender.
[ "Command", "sender", "." ]
python
train
scottgigante/tasklogger
tasklogger/logger.py
https://github.com/scottgigante/tasklogger/blob/06a263715d2db0653615c17b2df14b8272967b8d/tasklogger/logger.py#L98-L121
def set_timer(self, timer="wall"): """Set the timer function Parameters ---------- timer : {'wall', 'cpu', or callable} Timer function used to measure task running times. 'wall' uses `time.time`, 'cpu' uses `time.process_time` Returns ------- self """ if timer == "wall": timer = time.time elif timer == "cpu": try: timer = time.process_time except AttributeError: raise RuntimeError( "Python2.7 on Windows does not offer a CPU time function. " "Please upgrade to Python >= 3.5.") self.timer = timer return self
[ "def", "set_timer", "(", "self", ",", "timer", "=", "\"wall\"", ")", ":", "if", "timer", "==", "\"wall\"", ":", "timer", "=", "time", ".", "time", "elif", "timer", "==", "\"cpu\"", ":", "try", ":", "timer", "=", "time", ".", "process_time", "except", ...
Set the timer function Parameters ---------- timer : {'wall', 'cpu', or callable} Timer function used to measure task running times. 'wall' uses `time.time`, 'cpu' uses `time.process_time` Returns ------- self
[ "Set", "the", "timer", "function" ]
python
train
pantsbuild/pants
src/python/pants/option/options.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/options.py#L86-L113
def complete_scopes(cls, scope_infos): """Expand a set of scopes to include all enclosing scopes. E.g., if the set contains `foo.bar.baz`, ensure that it also contains `foo.bar` and `foo`. Also adds any deprecated scopes. """ ret = {GlobalOptionsRegistrar.get_scope_info()} original_scopes = dict() for si in scope_infos: ret.add(si) if si.scope in original_scopes: raise cls.DuplicateScopeError('Scope `{}` claimed by {}, was also claimed by {}.'.format( si.scope, si, original_scopes[si.scope] )) original_scopes[si.scope] = si if si.deprecated_scope: ret.add(ScopeInfo(si.deprecated_scope, si.category, si.optionable_cls)) original_scopes[si.deprecated_scope] = si # TODO: Once scope name validation is enforced (so there can be no dots in scope name # components) we can replace this line with `for si in scope_infos:`, because it will # not be possible for a deprecated_scope to introduce any new intermediate scopes. for si in copy.copy(ret): for scope in all_enclosing_scopes(si.scope, allow_global=False): if scope not in original_scopes: ret.add(ScopeInfo(scope, ScopeInfo.INTERMEDIATE)) return ret
[ "def", "complete_scopes", "(", "cls", ",", "scope_infos", ")", ":", "ret", "=", "{", "GlobalOptionsRegistrar", ".", "get_scope_info", "(", ")", "}", "original_scopes", "=", "dict", "(", ")", "for", "si", "in", "scope_infos", ":", "ret", ".", "add", "(", ...
Expand a set of scopes to include all enclosing scopes. E.g., if the set contains `foo.bar.baz`, ensure that it also contains `foo.bar` and `foo`. Also adds any deprecated scopes.
[ "Expand", "a", "set", "of", "scopes", "to", "include", "all", "enclosing", "scopes", "." ]
python
train
Contraz/demosys-py
demosys/project/base.py
https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/project/base.py#L243-L253
def get_data(self, label: str) -> Any: """ Get a data resource by label Args: label (str): The labvel for the data resource to fetch Returns: The requeted data object """ return self._get_resource(label, self._data, "data")
[ "def", "get_data", "(", "self", ",", "label", ":", "str", ")", "->", "Any", ":", "return", "self", ".", "_get_resource", "(", "label", ",", "self", ".", "_data", ",", "\"data\"", ")" ]
Get a data resource by label Args: label (str): The labvel for the data resource to fetch Returns: The requeted data object
[ "Get", "a", "data", "resource", "by", "label", "Args", ":", "label", "(", "str", ")", ":", "The", "labvel", "for", "the", "data", "resource", "to", "fetch", "Returns", ":", "The", "requeted", "data", "object" ]
python
valid
cocagne/txdbus
txdbus/objects.py
https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L213-L219
def cancelSignalNotification(self, rule_id): """ Cancels a callback previously registered with notifyOnSignal """ if self._signalRules and rule_id in self._signalRules: self.objHandler.conn.delMatch(rule_id) self._signalRules.remove(rule_id)
[ "def", "cancelSignalNotification", "(", "self", ",", "rule_id", ")", ":", "if", "self", ".", "_signalRules", "and", "rule_id", "in", "self", ".", "_signalRules", ":", "self", ".", "objHandler", ".", "conn", ".", "delMatch", "(", "rule_id", ")", "self", "."...
Cancels a callback previously registered with notifyOnSignal
[ "Cancels", "a", "callback", "previously", "registered", "with", "notifyOnSignal" ]
python
train
sethmlarson/virtualbox-python
virtualbox/library.py
https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L14341-L14424
def unregister(self, cleanup_mode): """Unregisters a machine previously registered with :py:func:`IVirtualBox.register_machine` and optionally do additional cleanup before the machine is unregistered. This method does not delete any files. It only changes the machine configuration and the list of registered machines in the VirtualBox object. To delete the files which belonged to the machine, including the XML file of the machine itself, call :py:func:`delete_config` , optionally with the array of IMedium objects which was returned from this method. How thoroughly this method cleans up the machine configuration before unregistering the machine depends on the @a cleanupMode argument. With "UnregisterOnly", the machine will only be unregistered, but no additional cleanup will be performed. The call will fail if the machine is in "Saved" state or has any snapshots or any media attached (see :py:class:`IMediumAttachment` ). It is the responsibility of the caller to delete all such configuration in this mode. In this mode, the API behaves like the former @c IVirtualBox::unregisterMachine() API which it replaces. With "DetachAllReturnNone", the call will succeed even if the machine is in "Saved" state or if it has snapshots or media attached. All media attached to the current machine state or in snapshots will be detached. No medium objects will be returned; all of the machine's media will remain open. With "DetachAllReturnHardDisksOnly", the call will behave like with "DetachAllReturnNone", except that all the hard disk medium objects which were detached from the machine will be returned as an array. This allows for quickly passing them to the :py:func:`delete_config` API for closing and deletion. With "Full", the call will behave like with "DetachAllReturnHardDisksOnly", except that all media will be returned in the array, including removable media like DVDs and floppies. This might be useful if the user wants to inspect in detail which media were attached to the machine. Be careful when passing the media array to :py:func:`delete_config` in that case because users will typically want to preserve ISO and RAW image files. A typical implementation will use "DetachAllReturnHardDisksOnly" and then pass the resulting IMedium array to :py:func:`delete_config` . This way, the machine is completely deleted with all its saved states and hard disk images, but images for removable drives (such as ISO and RAW files) will remain on disk. This API does not verify whether the media files returned in the array are still attached to other machines (i.e. shared between several machines). If such a shared image is passed to :py:func:`delete_config` however, closing the image will fail there and the image will be silently skipped. This API may, however, move media from this machine's media registry to other media registries (see :py:class:`IMedium` for details on media registries). For machines created with VirtualBox 4.0 or later, if media from this machine's media registry are also attached to another machine (shared attachments), each such medium will be moved to another machine's registry. This is because without this machine's media registry, the other machine cannot find its media any more and would become inaccessible. This API implicitly calls :py:func:`save_settings` to save all current machine settings before unregistering it. It may also silently call :py:func:`save_settings` on other machines if media are moved to other machines' media registries. After successful method invocation, the :py:class:`IMachineRegisteredEvent` event is fired. The call will fail if the machine is currently locked (see :py:class:`ISession` ). If the given machine is inaccessible (see :py:func:`accessible` ), it will be unregistered and fully uninitialized right afterwards. As a result, the returned machine object will be unusable and an attempt to call **any** method will return the "Object not ready" error. in cleanup_mode of type :class:`CleanupMode` How to clean up after the machine has been unregistered. return media of type :class:`IMedium` List of media detached from the machine, depending on the @a cleanupMode parameter. raises :class:`VBoxErrorInvalidObjectState` Machine is currently locked for a session. """ if not isinstance(cleanup_mode, CleanupMode): raise TypeError("cleanup_mode can only be an instance of type CleanupMode") media = self._call("unregister", in_p=[cleanup_mode]) media = [IMedium(a) for a in media] return media
[ "def", "unregister", "(", "self", ",", "cleanup_mode", ")", ":", "if", "not", "isinstance", "(", "cleanup_mode", ",", "CleanupMode", ")", ":", "raise", "TypeError", "(", "\"cleanup_mode can only be an instance of type CleanupMode\"", ")", "media", "=", "self", ".", ...
Unregisters a machine previously registered with :py:func:`IVirtualBox.register_machine` and optionally do additional cleanup before the machine is unregistered. This method does not delete any files. It only changes the machine configuration and the list of registered machines in the VirtualBox object. To delete the files which belonged to the machine, including the XML file of the machine itself, call :py:func:`delete_config` , optionally with the array of IMedium objects which was returned from this method. How thoroughly this method cleans up the machine configuration before unregistering the machine depends on the @a cleanupMode argument. With "UnregisterOnly", the machine will only be unregistered, but no additional cleanup will be performed. The call will fail if the machine is in "Saved" state or has any snapshots or any media attached (see :py:class:`IMediumAttachment` ). It is the responsibility of the caller to delete all such configuration in this mode. In this mode, the API behaves like the former @c IVirtualBox::unregisterMachine() API which it replaces. With "DetachAllReturnNone", the call will succeed even if the machine is in "Saved" state or if it has snapshots or media attached. All media attached to the current machine state or in snapshots will be detached. No medium objects will be returned; all of the machine's media will remain open. With "DetachAllReturnHardDisksOnly", the call will behave like with "DetachAllReturnNone", except that all the hard disk medium objects which were detached from the machine will be returned as an array. This allows for quickly passing them to the :py:func:`delete_config` API for closing and deletion. With "Full", the call will behave like with "DetachAllReturnHardDisksOnly", except that all media will be returned in the array, including removable media like DVDs and floppies. This might be useful if the user wants to inspect in detail which media were attached to the machine. Be careful when passing the media array to :py:func:`delete_config` in that case because users will typically want to preserve ISO and RAW image files. A typical implementation will use "DetachAllReturnHardDisksOnly" and then pass the resulting IMedium array to :py:func:`delete_config` . This way, the machine is completely deleted with all its saved states and hard disk images, but images for removable drives (such as ISO and RAW files) will remain on disk. This API does not verify whether the media files returned in the array are still attached to other machines (i.e. shared between several machines). If such a shared image is passed to :py:func:`delete_config` however, closing the image will fail there and the image will be silently skipped. This API may, however, move media from this machine's media registry to other media registries (see :py:class:`IMedium` for details on media registries). For machines created with VirtualBox 4.0 or later, if media from this machine's media registry are also attached to another machine (shared attachments), each such medium will be moved to another machine's registry. This is because without this machine's media registry, the other machine cannot find its media any more and would become inaccessible. This API implicitly calls :py:func:`save_settings` to save all current machine settings before unregistering it. It may also silently call :py:func:`save_settings` on other machines if media are moved to other machines' media registries. After successful method invocation, the :py:class:`IMachineRegisteredEvent` event is fired. The call will fail if the machine is currently locked (see :py:class:`ISession` ). If the given machine is inaccessible (see :py:func:`accessible` ), it will be unregistered and fully uninitialized right afterwards. As a result, the returned machine object will be unusable and an attempt to call **any** method will return the "Object not ready" error. in cleanup_mode of type :class:`CleanupMode` How to clean up after the machine has been unregistered. return media of type :class:`IMedium` List of media detached from the machine, depending on the @a cleanupMode parameter. raises :class:`VBoxErrorInvalidObjectState` Machine is currently locked for a session.
[ "Unregisters", "a", "machine", "previously", "registered", "with", ":", "py", ":", "func", ":", "IVirtualBox", ".", "register_machine", "and", "optionally", "do", "additional", "cleanup", "before", "the", "machine", "is", "unregistered", ".", "This", "method", "...
python
train
arve0/leicaexperiment
leicaexperiment/experiment.py
https://github.com/arve0/leicaexperiment/blob/c0393c4d51984a506f813319efb66e54c4f2a426/leicaexperiment/experiment.py#L276-L295
def compress(self, delete_tif=False, folder=None): """Lossless compress all images in experiment to PNG. If folder is omitted, images will not be moved. Images which already exists in PNG are omitted. Parameters ---------- folder : string Where to store PNGs. Defaults to the folder they are in. delete_tif : bool If set to truthy value, ome.tifs will be deleted after compression. Returns ------- list Filenames of PNG images. Files which already exists before compression are also returned. """ return compress(self.images, delete_tif, folder)
[ "def", "compress", "(", "self", ",", "delete_tif", "=", "False", ",", "folder", "=", "None", ")", ":", "return", "compress", "(", "self", ".", "images", ",", "delete_tif", ",", "folder", ")" ]
Lossless compress all images in experiment to PNG. If folder is omitted, images will not be moved. Images which already exists in PNG are omitted. Parameters ---------- folder : string Where to store PNGs. Defaults to the folder they are in. delete_tif : bool If set to truthy value, ome.tifs will be deleted after compression. Returns ------- list Filenames of PNG images. Files which already exists before compression are also returned.
[ "Lossless", "compress", "all", "images", "in", "experiment", "to", "PNG", ".", "If", "folder", "is", "omitted", "images", "will", "not", "be", "moved", "." ]
python
valid
pypa/pipenv
pipenv/vendor/distlib/locators.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/locators.py#L305-L319
def _get_digest(self, info): """ Get a digest from a dictionary by looking at keys of the form 'algo_digest'. Returns a 2-tuple (algo, digest) if found, else None. Currently looks only for SHA256, then MD5. """ result = None for algo in ('sha256', 'md5'): key = '%s_digest' % algo if key in info: result = (algo, info[key]) break return result
[ "def", "_get_digest", "(", "self", ",", "info", ")", ":", "result", "=", "None", "for", "algo", "in", "(", "'sha256'", ",", "'md5'", ")", ":", "key", "=", "'%s_digest'", "%", "algo", "if", "key", "in", "info", ":", "result", "=", "(", "algo", ",", ...
Get a digest from a dictionary by looking at keys of the form 'algo_digest'. Returns a 2-tuple (algo, digest) if found, else None. Currently looks only for SHA256, then MD5.
[ "Get", "a", "digest", "from", "a", "dictionary", "by", "looking", "at", "keys", "of", "the", "form", "algo_digest", "." ]
python
train
mental32/spotify.py
spotify/models/player.py
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/player.py#L162-L197
async def play(self, *uris: SomeURIs, offset: Optional[Offset] = 0, device: Optional[SomeDevice] = None): """Start a new context or resume current playback on the user’s active device. The method treats a single argument as a Spotify context, such as a Artist, Album and playlist objects/URI. When called with multiple positional arguments they are interpreted as a array of Spotify Track objects/URIs. Parameters ---------- *uris : :obj:`SomeURIs` When a single argument is passed in that argument is treated as a context. Valid contexts are: albums, artists, playlists. Album, Artist and Playlist objects are accepted too. Otherwise when multiple arguments are passed in they, A sequence of Spotify Tracks or Track URIs to play. offset : Optional[:obj:`Offset`] Indicates from where in the context playback should start. Only available when `context` corresponds to an album or playlist object, or when the `uris` parameter is used. when an integer offset is zero based and can’t be negative. device : Optional[:obj:`SomeDevice`] The Device object or id of the device this command is targeting. If not supplied, the user’s currently active device is the target. """ if len(uris) > 1: # Regular uris paramter context_uri = list(str(uri) for uri in uris) else: # Treat it as a context URI context_uri = str(uris[0]) if device is not None: if not isinstance(device, (Device, str)): raise TypeError('Expected `device` to either be a spotify.Device or a string. got {type(0)!r}'.format(device)) else: device = device.id await self._user.http.play_playback(context_uri, offset=offset, device_id=device)
[ "async", "def", "play", "(", "self", ",", "*", "uris", ":", "SomeURIs", ",", "offset", ":", "Optional", "[", "Offset", "]", "=", "0", ",", "device", ":", "Optional", "[", "SomeDevice", "]", "=", "None", ")", ":", "if", "len", "(", "uris", ")", ">...
Start a new context or resume current playback on the user’s active device. The method treats a single argument as a Spotify context, such as a Artist, Album and playlist objects/URI. When called with multiple positional arguments they are interpreted as a array of Spotify Track objects/URIs. Parameters ---------- *uris : :obj:`SomeURIs` When a single argument is passed in that argument is treated as a context. Valid contexts are: albums, artists, playlists. Album, Artist and Playlist objects are accepted too. Otherwise when multiple arguments are passed in they, A sequence of Spotify Tracks or Track URIs to play. offset : Optional[:obj:`Offset`] Indicates from where in the context playback should start. Only available when `context` corresponds to an album or playlist object, or when the `uris` parameter is used. when an integer offset is zero based and can’t be negative. device : Optional[:obj:`SomeDevice`] The Device object or id of the device this command is targeting. If not supplied, the user’s currently active device is the target.
[ "Start", "a", "new", "context", "or", "resume", "current", "playback", "on", "the", "user’s", "active", "device", "." ]
python
test
cggh/scikit-allel
allel/stats/distance.py
https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/stats/distance.py#L291-L309
def condensed_coords_within(pop, n): """Return indices into a condensed distance matrix for all pairwise comparisons within the given population. Parameters ---------- pop : array_like, int Indices of samples or haplotypes within the population. n : int Size of the square matrix (length of first or second dimension). Returns ------- indices : ndarray, int """ return [condensed_coords(i, j, n) for i, j in itertools.combinations(sorted(pop), 2)]
[ "def", "condensed_coords_within", "(", "pop", ",", "n", ")", ":", "return", "[", "condensed_coords", "(", "i", ",", "j", ",", "n", ")", "for", "i", ",", "j", "in", "itertools", ".", "combinations", "(", "sorted", "(", "pop", ")", ",", "2", ")", "]"...
Return indices into a condensed distance matrix for all pairwise comparisons within the given population. Parameters ---------- pop : array_like, int Indices of samples or haplotypes within the population. n : int Size of the square matrix (length of first or second dimension). Returns ------- indices : ndarray, int
[ "Return", "indices", "into", "a", "condensed", "distance", "matrix", "for", "all", "pairwise", "comparisons", "within", "the", "given", "population", "." ]
python
train
ph4r05/monero-serialize
monero_serialize/core/erefs.py
https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/core/erefs.py#L56-L73
def set_elem(elem_ref, elem): """ Sets element referenced by the elem_ref. Returns the elem. :param elem_ref: :param elem: :return: """ if elem_ref is None or elem_ref == elem or not is_elem_ref(elem_ref): return elem elif elem_ref[0] == ElemRefObj: setattr(elem_ref[1], elem_ref[2], elem) return elem elif elem_ref[0] == ElemRefArr: elem_ref[1][elem_ref[2]] = elem return elem
[ "def", "set_elem", "(", "elem_ref", ",", "elem", ")", ":", "if", "elem_ref", "is", "None", "or", "elem_ref", "==", "elem", "or", "not", "is_elem_ref", "(", "elem_ref", ")", ":", "return", "elem", "elif", "elem_ref", "[", "0", "]", "==", "ElemRefObj", "...
Sets element referenced by the elem_ref. Returns the elem. :param elem_ref: :param elem: :return:
[ "Sets", "element", "referenced", "by", "the", "elem_ref", ".", "Returns", "the", "elem", "." ]
python
train
saltstack/salt
salt/pillar/nodegroups.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/nodegroups.py#L49-L73
def ext_pillar(minion_id, pillar, pillar_name=None): ''' A salt external pillar which provides the list of nodegroups of which the minion is a member. :param minion_id: used for compound matching nodegroups :param pillar: provided by salt, but not used by nodegroups ext_pillar :param pillar_name: optional name to use for the pillar, defaults to 'nodegroups' :return: a dictionary which is included by the salt master in the pillars returned to the minion ''' pillar_name = pillar_name or 'nodegroups' all_nodegroups = __opts__['nodegroups'] nodegroups_minion_is_in = [] ckminions = None for nodegroup_name in six.iterkeys(all_nodegroups): ckminions = ckminions or CkMinions(__opts__) _res = ckminions.check_minions( all_nodegroups[nodegroup_name], 'compound') match = _res['minions'] if minion_id in match: nodegroups_minion_is_in.append(nodegroup_name) return {pillar_name: nodegroups_minion_is_in}
[ "def", "ext_pillar", "(", "minion_id", ",", "pillar", ",", "pillar_name", "=", "None", ")", ":", "pillar_name", "=", "pillar_name", "or", "'nodegroups'", "all_nodegroups", "=", "__opts__", "[", "'nodegroups'", "]", "nodegroups_minion_is_in", "=", "[", "]", "ckmi...
A salt external pillar which provides the list of nodegroups of which the minion is a member. :param minion_id: used for compound matching nodegroups :param pillar: provided by salt, but not used by nodegroups ext_pillar :param pillar_name: optional name to use for the pillar, defaults to 'nodegroups' :return: a dictionary which is included by the salt master in the pillars returned to the minion
[ "A", "salt", "external", "pillar", "which", "provides", "the", "list", "of", "nodegroups", "of", "which", "the", "minion", "is", "a", "member", "." ]
python
train
frasertweedale/ledgertools
ltlib/config.py
https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/config.py#L33-L60
def format_outpat(outpat, xn): """ Format an outpat for the given transaction. Format the given output filename pattern. The pattern should be a format string with any combination of the following named fields: ``year`` The year of the transaction. ``month`` The month of the transaction, with leading zero for single-digit months. ``fy`` The financial year of the transaction (being the year in which the financial year of the transaction *ends*). A financial year runs from 1 July to 30 June. ``date`` The date object itself. The format string may specify any attribute of the date object, e.g. ``{date.day}``. This field is deprecated. """ return outpat.format( year=str(xn.date.year), month='{:02}'.format(xn.date.month), fy=str(xn.date.year if xn.date.month < 7 else xn.date.year + 1), date=xn.date )
[ "def", "format_outpat", "(", "outpat", ",", "xn", ")", ":", "return", "outpat", ".", "format", "(", "year", "=", "str", "(", "xn", ".", "date", ".", "year", ")", ",", "month", "=", "'{:02}'", ".", "format", "(", "xn", ".", "date", ".", "month", "...
Format an outpat for the given transaction. Format the given output filename pattern. The pattern should be a format string with any combination of the following named fields: ``year`` The year of the transaction. ``month`` The month of the transaction, with leading zero for single-digit months. ``fy`` The financial year of the transaction (being the year in which the financial year of the transaction *ends*). A financial year runs from 1 July to 30 June. ``date`` The date object itself. The format string may specify any attribute of the date object, e.g. ``{date.day}``. This field is deprecated.
[ "Format", "an", "outpat", "for", "the", "given", "transaction", "." ]
python
train
mikedh/trimesh
trimesh/path/path.py
https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/path/path.py#L138-L151
def crc(self): """ A CRC of the current vertices and entities. Returns ------------ crc: int, CRC of entity points and vertices """ # first CRC the points in every entity target = caching.crc32(bytes().join(e._bytes() for e in self.entities)) # add the CRC for the vertices target ^= self.vertices.crc() return target
[ "def", "crc", "(", "self", ")", ":", "# first CRC the points in every entity", "target", "=", "caching", ".", "crc32", "(", "bytes", "(", ")", ".", "join", "(", "e", ".", "_bytes", "(", ")", "for", "e", "in", "self", ".", "entities", ")", ")", "# add t...
A CRC of the current vertices and entities. Returns ------------ crc: int, CRC of entity points and vertices
[ "A", "CRC", "of", "the", "current", "vertices", "and", "entities", "." ]
python
train
taizilongxu/douban.fm
doubanfm/player.py
https://github.com/taizilongxu/douban.fm/blob/d65126d3bd3e12d8a7109137caff8da0efc22b2f/doubanfm/player.py#L259-L294
def _send_command(self, cmd, expect=None): """Send a command to MPlayer. cmd: the command string expect: expect the output starts with a certain string The result, if any, is returned as a string. """ if not self.is_alive: raise NotPlayingError() logger.debug("Send command to mplayer: " + cmd) cmd = cmd + "\n" # In Py3k, TypeErrors will be raised because cmd is a string but stdin # expects bytes. In Python 2.x on the other hand, UnicodeEncodeErrors # will be raised if cmd is unicode. In both cases, encoding the string # will fix the problem. try: self.sub_proc.stdin.write(cmd) except (TypeError, UnicodeEncodeError): self.sub_proc.stdin.write(cmd.encode('utf-8', 'ignore')) time.sleep(0.1) # wait for mplayer (better idea?) # Expect a response for 'get_property' only if not expect: return while True: try: output = self.sub_proc.stdout.readline().rstrip() output = output.decode('utf-8') except IOError: return None # print output split_output = output.split('=') # print(split_output) if len(split_output) == 2 and split_output[0].strip() == expect: # We found it value = split_output[1] return value.strip()
[ "def", "_send_command", "(", "self", ",", "cmd", ",", "expect", "=", "None", ")", ":", "if", "not", "self", ".", "is_alive", ":", "raise", "NotPlayingError", "(", ")", "logger", ".", "debug", "(", "\"Send command to mplayer: \"", "+", "cmd", ")", "cmd", ...
Send a command to MPlayer. cmd: the command string expect: expect the output starts with a certain string The result, if any, is returned as a string.
[ "Send", "a", "command", "to", "MPlayer", "." ]
python
train
Kronuz/pyScss
scss/extension/compass/sprites.py
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/extension/compass/sprites.py#L428-L440
def sprite_map_name(map): """ Returns the name of a sprite map The name is derived from the folder than contains the sprites. """ map = map.render() sprite_maps = _get_cache('sprite_maps') sprite_map = sprite_maps.get(map) if not sprite_map: log.error("No sprite map found: %s", map, extra={'stack': True}) if sprite_map: return String.unquoted(sprite_map['*n*']) return String.unquoted('')
[ "def", "sprite_map_name", "(", "map", ")", ":", "map", "=", "map", ".", "render", "(", ")", "sprite_maps", "=", "_get_cache", "(", "'sprite_maps'", ")", "sprite_map", "=", "sprite_maps", ".", "get", "(", "map", ")", "if", "not", "sprite_map", ":", "log",...
Returns the name of a sprite map The name is derived from the folder than contains the sprites.
[ "Returns", "the", "name", "of", "a", "sprite", "map", "The", "name", "is", "derived", "from", "the", "folder", "than", "contains", "the", "sprites", "." ]
python
train
keenlabs/KeenClient-Python
keen/Padding.py
https://github.com/keenlabs/KeenClient-Python/blob/266387c3376d1e000d117e17c45045ae3439d43f/keen/Padding.py#L167-L173
def appendNullPadding(str, blocksize=AES_blocksize): 'Pad with null bytes' pad_len = paddingLength(len(str), blocksize) padding = '\0'*pad_len return str + padding
[ "def", "appendNullPadding", "(", "str", ",", "blocksize", "=", "AES_blocksize", ")", ":", "pad_len", "=", "paddingLength", "(", "len", "(", "str", ")", ",", "blocksize", ")", "padding", "=", "'\\0'", "*", "pad_len", "return", "str", "+", "padding" ]
Pad with null bytes
[ "Pad", "with", "null", "bytes" ]
python
train
openego/ding0
ding0/tools/geo.py
https://github.com/openego/ding0/blob/e2d6528f96255e4bb22ba15514a4f1883564ed5d/ding0/tools/geo.py#L119-L152
def calc_geo_dist_vincenty(node_source, node_target): """ Calculates the geodesic distance between `node_source` and `node_target` incorporating the detour factor specified in :file:`ding0/ding0/config/config_calc.cfg`. Parameters ---------- node_source: LVStationDing0, GeneratorDing0, or CableDistributorDing0 source node, member of GridDing0._graph node_target: LVStationDing0, GeneratorDing0, or CableDistributorDing0 target node, member of GridDing0._graph Returns ------- :any:`float` Distance in m """ branch_detour_factor = cfg_ding0.get('assumptions', 'branch_detour_factor') # notice: vincenty takes (lat,lon) branch_length = branch_detour_factor * vincenty((node_source.geo_data.y, node_source.geo_data.x), (node_target.geo_data.y, node_target.geo_data.x)).m # ========= BUG: LINE LENGTH=0 WHEN CONNECTING GENERATORS =========== # When importing generators, the geom_new field is used as position. If it is empty, EnergyMap's geom # is used and so there are a couple of generators at the same position => length of interconnecting # line is 0. See issue #76 if branch_length == 0: branch_length = 1 logger.warning('Geo distance is zero, check objects\' positions. ' 'Distance is set to 1m') # =================================================================== return branch_length
[ "def", "calc_geo_dist_vincenty", "(", "node_source", ",", "node_target", ")", ":", "branch_detour_factor", "=", "cfg_ding0", ".", "get", "(", "'assumptions'", ",", "'branch_detour_factor'", ")", "# notice: vincenty takes (lat,lon)", "branch_length", "=", "branch_detour_fact...
Calculates the geodesic distance between `node_source` and `node_target` incorporating the detour factor specified in :file:`ding0/ding0/config/config_calc.cfg`. Parameters ---------- node_source: LVStationDing0, GeneratorDing0, or CableDistributorDing0 source node, member of GridDing0._graph node_target: LVStationDing0, GeneratorDing0, or CableDistributorDing0 target node, member of GridDing0._graph Returns ------- :any:`float` Distance in m
[ "Calculates", "the", "geodesic", "distance", "between", "node_source", "and", "node_target", "incorporating", "the", "detour", "factor", "specified", "in", ":", "file", ":", "ding0", "/", "ding0", "/", "config", "/", "config_calc", ".", "cfg", "." ]
python
train
jeffknupp/sandman2
sandman2/service.py
https://github.com/jeffknupp/sandman2/blob/1ce21d6f7a6df77fa96fab694b0f9bb8469c166b/sandman2/service.py#L191-L200
def _resource(self, resource_id): """Return the ``sandman2.model.Model`` instance with the given *resource_id*. :rtype: :class:`sandman2.model.Model` """ resource = self.__model__.query.get(resource_id) if not resource: raise NotFoundException() return resource
[ "def", "_resource", "(", "self", ",", "resource_id", ")", ":", "resource", "=", "self", ".", "__model__", ".", "query", ".", "get", "(", "resource_id", ")", "if", "not", "resource", ":", "raise", "NotFoundException", "(", ")", "return", "resource" ]
Return the ``sandman2.model.Model`` instance with the given *resource_id*. :rtype: :class:`sandman2.model.Model`
[ "Return", "the", "sandman2", ".", "model", ".", "Model", "instance", "with", "the", "given", "*", "resource_id", "*", "." ]
python
train
SheffieldML/GPyOpt
GPyOpt/acquisitions/LP.py
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LP.py#L112-L132
def d_acquisition_function(self, x): """ Returns the gradient of the acquisition function at x. """ x = np.atleast_2d(x) if self.transform=='softplus': fval = -self.acq.acquisition_function(x)[:,0] scale = 1./(np.log1p(np.exp(fval))*(1.+np.exp(-fval))) elif self.transform=='none': fval = -self.acq.acquisition_function(x)[:,0] scale = 1./fval else: scale = 1. if self.X_batch is None: _, grad_acq_x = self.acq.acquisition_function_withGradients(x) return scale*grad_acq_x else: _, grad_acq_x = self.acq.acquisition_function_withGradients(x) return scale*grad_acq_x - self._d_hammer_function(x, self.X_batch, self.r_x0, self.s_x0)
[ "def", "d_acquisition_function", "(", "self", ",", "x", ")", ":", "x", "=", "np", ".", "atleast_2d", "(", "x", ")", "if", "self", ".", "transform", "==", "'softplus'", ":", "fval", "=", "-", "self", ".", "acq", ".", "acquisition_function", "(", "x", ...
Returns the gradient of the acquisition function at x.
[ "Returns", "the", "gradient", "of", "the", "acquisition", "function", "at", "x", "." ]
python
train
evhub/coconut
coconut/command/command.py
https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/command/command.py#L453-L458
def create_package(self, dirpath): """Set up a package directory.""" dirpath = fixpath(dirpath) filepath = os.path.join(dirpath, "__coconut__.py") with openfile(filepath, "w") as opened: writefile(opened, self.comp.getheader("__coconut__"))
[ "def", "create_package", "(", "self", ",", "dirpath", ")", ":", "dirpath", "=", "fixpath", "(", "dirpath", ")", "filepath", "=", "os", ".", "path", ".", "join", "(", "dirpath", ",", "\"__coconut__.py\"", ")", "with", "openfile", "(", "filepath", ",", "\"...
Set up a package directory.
[ "Set", "up", "a", "package", "directory", "." ]
python
train
gmr/infoblox
infoblox/cli.py
https://github.com/gmr/infoblox/blob/163dd9cff5f77c08751936c56aa8428acfd2d208/infoblox/cli.py#L41-L49
def delete_old_host(self, hostname): """Remove all records for the host. :param str hostname: Hostname to remove :rtype: bool """ host = Host(self.session, name=hostname) return host.delete()
[ "def", "delete_old_host", "(", "self", ",", "hostname", ")", ":", "host", "=", "Host", "(", "self", ".", "session", ",", "name", "=", "hostname", ")", "return", "host", ".", "delete", "(", ")" ]
Remove all records for the host. :param str hostname: Hostname to remove :rtype: bool
[ "Remove", "all", "records", "for", "the", "host", "." ]
python
train
gamechanger/dusty
dusty/payload.py
https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/payload.py#L52-L59
def init_yaml_constructor(): """ This dark magic is used to make yaml.safe_load encode all strings as utf-8, where otherwise python unicode strings would be returned for non-ascii chars """ def utf_encoding_string_constructor(loader, node): return loader.construct_scalar(node).encode('utf-8') yaml.SafeLoader.add_constructor(u'tag:yaml.org,2002:str', utf_encoding_string_constructor)
[ "def", "init_yaml_constructor", "(", ")", ":", "def", "utf_encoding_string_constructor", "(", "loader", ",", "node", ")", ":", "return", "loader", ".", "construct_scalar", "(", "node", ")", ".", "encode", "(", "'utf-8'", ")", "yaml", ".", "SafeLoader", ".", ...
This dark magic is used to make yaml.safe_load encode all strings as utf-8, where otherwise python unicode strings would be returned for non-ascii chars
[ "This", "dark", "magic", "is", "used", "to", "make", "yaml", ".", "safe_load", "encode", "all", "strings", "as", "utf", "-", "8", "where", "otherwise", "python", "unicode", "strings", "would", "be", "returned", "for", "non", "-", "ascii", "chars" ]
python
valid
sorgerlab/indra
indra/sources/tees/processor.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/tees/processor.py#L265-L309
def process_phosphorylation_statements(self): """Looks for Phosphorylation events in the graph and extracts them into INDRA statements. In particular, looks for a Positive_regulation event node with a child Phosphorylation event node. If Positive_regulation has an outgoing Cause edge, that's the subject If Phosphorylation has an outgoing Theme edge, that's the object If Phosphorylation has an outgoing Site edge, that's the site """ G = self.G statements = [] pwcs = self.find_event_parent_with_event_child('Positive_regulation', 'Phosphorylation') for pair in pwcs: (pos_reg, phos) = pair cause = self.get_entity_text_for_relation(pos_reg, 'Cause') theme = self.get_entity_text_for_relation(phos, 'Theme') print('Cause:', cause, 'Theme:', theme) # If the trigger word is dephosphorylate or similar, then we # extract a dephosphorylation statement trigger_word = self.get_entity_text_for_relation(phos, 'Phosphorylation') if 'dephos' in trigger_word: deph = True else: deph = False site = self.get_entity_text_for_relation(phos, 'Site') theme_node = self.get_related_node(phos, 'Theme') assert(theme_node is not None) evidence = self.node_to_evidence(theme_node, is_direct=False) if theme is not None: if deph: statements.append(Dephosphorylation(s2a(cause), s2a(theme), site, evidence=evidence)) else: statements.append(Phosphorylation(s2a(cause), s2a(theme), site, evidence=evidence)) return statements
[ "def", "process_phosphorylation_statements", "(", "self", ")", ":", "G", "=", "self", ".", "G", "statements", "=", "[", "]", "pwcs", "=", "self", ".", "find_event_parent_with_event_child", "(", "'Positive_regulation'", ",", "'Phosphorylation'", ")", "for", "pair",...
Looks for Phosphorylation events in the graph and extracts them into INDRA statements. In particular, looks for a Positive_regulation event node with a child Phosphorylation event node. If Positive_regulation has an outgoing Cause edge, that's the subject If Phosphorylation has an outgoing Theme edge, that's the object If Phosphorylation has an outgoing Site edge, that's the site
[ "Looks", "for", "Phosphorylation", "events", "in", "the", "graph", "and", "extracts", "them", "into", "INDRA", "statements", "." ]
python
train
asweigart/moosegesture
moosegesture/__init__.py
https://github.com/asweigart/moosegesture/blob/7d7998ac7c91b5a006c48bfd1efddbef85c11e0e/moosegesture/__init__.py#L123-L154
def levenshteinDistance(s1, s2): """ Returns the Levenshtein Distance between two strings, `s1` and `s2` as an integer. http://en.wikipedia.org/wiki/Levenshtein_distance The Levenshtein Distance (aka edit distance) is how many changes (i.e. insertions, deletions, substitutions) have to be made to convert one string into another. For example, the Levenshtein distance between "kitten" and "sitting" is 3, since the following three edits change one into the other, and there is no way to do it with fewer than three edits: kitten -> sitten -> sittin -> sitting """ singleLetterMapping = {DOWNLEFT: '1', DOWN:'2', DOWNRIGHT:'3', LEFT:'4', RIGHT:'6', UPLEFT:'7', UP:'8', UPRIGHT:'9'} len1 = len([singleLetterMapping[letter] for letter in s1]) len2 = len([singleLetterMapping[letter] for letter in s2]) matrix = list(range(len1 + 1)) * (len2 + 1) for i in range(len2 + 1): matrix[i] = list(range(i, i + len1 + 1)) for i in range(len2): for j in range(len1): if s1[j] == s2[i]: matrix[i+1][j+1] = min(matrix[i+1][j] + 1, matrix[i][j+1] + 1, matrix[i][j]) else: matrix[i+1][j+1] = min(matrix[i+1][j] + 1, matrix[i][j+1] + 1, matrix[i][j] + 1) return matrix[len2][len1]
[ "def", "levenshteinDistance", "(", "s1", ",", "s2", ")", ":", "singleLetterMapping", "=", "{", "DOWNLEFT", ":", "'1'", ",", "DOWN", ":", "'2'", ",", "DOWNRIGHT", ":", "'3'", ",", "LEFT", ":", "'4'", ",", "RIGHT", ":", "'6'", ",", "UPLEFT", ":", "'7'"...
Returns the Levenshtein Distance between two strings, `s1` and `s2` as an integer. http://en.wikipedia.org/wiki/Levenshtein_distance The Levenshtein Distance (aka edit distance) is how many changes (i.e. insertions, deletions, substitutions) have to be made to convert one string into another. For example, the Levenshtein distance between "kitten" and "sitting" is 3, since the following three edits change one into the other, and there is no way to do it with fewer than three edits: kitten -> sitten -> sittin -> sitting
[ "Returns", "the", "Levenshtein", "Distance", "between", "two", "strings", "s1", "and", "s2", "as", "an", "integer", "." ]
python
train
dbcli/cli_helpers
tasks.py
https://github.com/dbcli/cli_helpers/blob/3ebd891ac0c02bad061182dbcb54a47fb21980ae/tasks.py#L64-L68
def initialize_options(self): """Set the default options.""" self.branch = 'master' self.fix = False super(lint, self).initialize_options()
[ "def", "initialize_options", "(", "self", ")", ":", "self", ".", "branch", "=", "'master'", "self", ".", "fix", "=", "False", "super", "(", "lint", ",", "self", ")", ".", "initialize_options", "(", ")" ]
Set the default options.
[ "Set", "the", "default", "options", "." ]
python
test
lsbardel/python-stdnet
stdnet/odm/query.py
https://github.com/lsbardel/python-stdnet/blob/78db5320bdedc3f28c5e4f38cda13a4469e35db7/stdnet/odm/query.py#L621-L626
def backend_query(self, **kwargs): '''Build and return the :class:`stdnet.utils.async.BackendQuery`. This is a lazy method in the sense that it is evaluated once only and its result stored for future retrieval.''' q = self.construct() return q if isinstance(q, EmptyQuery) else q.backend_query(**kwargs)
[ "def", "backend_query", "(", "self", ",", "*", "*", "kwargs", ")", ":", "q", "=", "self", ".", "construct", "(", ")", "return", "q", "if", "isinstance", "(", "q", ",", "EmptyQuery", ")", "else", "q", ".", "backend_query", "(", "*", "*", "kwargs", "...
Build and return the :class:`stdnet.utils.async.BackendQuery`. This is a lazy method in the sense that it is evaluated once only and its result stored for future retrieval.
[ "Build", "and", "return", "the", ":", "class", ":", "stdnet", ".", "utils", ".", "async", ".", "BackendQuery", ".", "This", "is", "a", "lazy", "method", "in", "the", "sense", "that", "it", "is", "evaluated", "once", "only", "and", "its", "result", "sto...
python
train
moonso/vcf_parser
vcf_parser/utils/build_info.py
https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/utils/build_info.py#L10-L33
def build_info_string(info): """ Build a new vcf INFO string based on the information in the info_dict. The info is a dictionary with vcf info keys as keys and lists of vcf values as values. If there is no value False is value in info Args: info (dict): A dictionary with information from the vcf file Returns: String: A string that is on the proper vcf format for the INFO column """ info_list = [] for annotation in info: if info[annotation]: info_list.append('='.join([annotation, ','.join(info[annotation])])) else: info_list.append(annotation) return ';'.join(info_list)
[ "def", "build_info_string", "(", "info", ")", ":", "info_list", "=", "[", "]", "for", "annotation", "in", "info", ":", "if", "info", "[", "annotation", "]", ":", "info_list", ".", "append", "(", "'='", ".", "join", "(", "[", "annotation", ",", "','", ...
Build a new vcf INFO string based on the information in the info_dict. The info is a dictionary with vcf info keys as keys and lists of vcf values as values. If there is no value False is value in info Args: info (dict): A dictionary with information from the vcf file Returns: String: A string that is on the proper vcf format for the INFO column
[ "Build", "a", "new", "vcf", "INFO", "string", "based", "on", "the", "information", "in", "the", "info_dict", ".", "The", "info", "is", "a", "dictionary", "with", "vcf", "info", "keys", "as", "keys", "and", "lists", "of", "vcf", "values", "as", "values", ...
python
train
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L273-L288
def get_emails(self, limit=100, offset=0, conditions={}): """ Get all certified emails """ url = self.EMAILS_URL + "?limit=%s&offset=%s" % (limit, offset) for key, value in conditions.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
[ "def", "get_emails", "(", "self", ",", "limit", "=", "100", ",", "offset", "=", "0", ",", "conditions", "=", "{", "}", ")", ":", "url", "=", "self", ".", "EMAILS_URL", "+", "\"?limit=%s&offset=%s\"", "%", "(", "limit", ",", "offset", ")", "for", "key...
Get all certified emails
[ "Get", "all", "certified", "emails" ]
python
train
timothyb0912/pylogit
pylogit/mixed_logit_calcs.py
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/mixed_logit_calcs.py#L243-L348
def calc_mixed_log_likelihood(params, design_3d, alt_IDs, rows_to_obs, rows_to_alts, rows_to_mixers, choice_vector, utility_transform, ridge=None, weights=None): """ Parameters ---------- params : 1D ndarray. All elements should by ints, floats, or longs. Should have 1 element for each utility coefficient being estimated (i.e. num_features + num_coefs_being_mixed). design_3d : 3D ndarray. All elements should be ints, floats, or longs. Should have one row per observation per available alternative. The second axis should have as many elements as there are draws from the mixing distributions of the coefficients. The last axis should have one element per index coefficient being estimated. alt_IDs : 1D ndarray. All elements should be ints. There should be one row per obervation per available alternative for the given observation. Elements denote the alternative corresponding to the given row of the design matrix. rows_to_obs : 2D scipy sparse array. All elements should be zeros and ones. There should be one row per observation per available alternative and one column per observation. This matrix maps the rows of the design matrix to the unique observations (on the columns). rows_to_alts : 2D scipy sparse array. All elements should be zeros and ones. There should be one row per observation per available alternative and one column per possible alternative. This matrix maps the rows of the design matrix to the possible alternatives for this dataset. rows_to_mixers : 2D scipy sparse array. All elements should be zeros and ones. Will map the rows of the design matrix to the particular units that the mixing is being performed over. Note that in the case of panel data, this matrix will be different from `rows_to_obs`. choice_vector : 1D ndarray. All elements should be either ones or zeros. There should be one row per observation per available alternative for the given observation. Elements denote the alternative which is chosen by the given observation with a 1 and a zero otherwise. utility_transform : callable. Should accept a 1D array of systematic utility values, a 1D array of alternative IDs, and miscellaneous args and kwargs. Should return a 2D array whose elements contain the appropriately transformed systematic utility values, based on the current model being evaluated and the given draw of the random coefficients. There should be one column for each draw of the random coefficients. There should have one row per individual per choice situation per available alternative. ridge : scalar or None, optional. Determines whether or not ridge regression is performed. If a scalar is passed, then that scalar determines the ridge penalty for the optimization. Default = None. weights : 1D ndarray or None. Allows for the calculation of weighted log-likelihoods. The weights can represent various things. In stratified samples, the weights may be the proportion of the observations in a given strata for a sample in relation to the proportion of observations in that strata in the population. In latent class models, the weights may be the probability of being a particular class. Returns ------- log_likelihood: float. The log-likelihood of the mixed logit model evaluated at the passed values of `params`. """ # Calculate the weights for the sample if weights is None: weights = np.ones(design_3d.shape[0]) weights_per_obs =\ np.max(rows_to_mixers.toarray() * weights[:, None], axis=0) # Calculate the regular probability array. Note the implicit assumption # that params == index coefficients. prob_array = general_calc_probabilities(params, design_3d, alt_IDs, rows_to_obs, rows_to_alts, utility_transform, return_long_probs=True) # Calculate the simulated probability of correctly predicting each persons # sequence of choices. Note that this function implicitly assumes that the # mixing unit is the individual simulated_sequence_probs = calc_choice_sequence_probs(prob_array, choice_vector, rows_to_mixers) # Calculate the log-likelihood of the dataset log_likelihood = weights_per_obs.dot(np.log(simulated_sequence_probs)) # Adujust for the presence of a ridge estimator. Again, note that we are # implicitly assuming that the only model being mixed is the MNL model, # such that params == index coefficients. if ridge is None: return log_likelihood else: return log_likelihood - ridge * np.square(params).sum()
[ "def", "calc_mixed_log_likelihood", "(", "params", ",", "design_3d", ",", "alt_IDs", ",", "rows_to_obs", ",", "rows_to_alts", ",", "rows_to_mixers", ",", "choice_vector", ",", "utility_transform", ",", "ridge", "=", "None", ",", "weights", "=", "None", ")", ":",...
Parameters ---------- params : 1D ndarray. All elements should by ints, floats, or longs. Should have 1 element for each utility coefficient being estimated (i.e. num_features + num_coefs_being_mixed). design_3d : 3D ndarray. All elements should be ints, floats, or longs. Should have one row per observation per available alternative. The second axis should have as many elements as there are draws from the mixing distributions of the coefficients. The last axis should have one element per index coefficient being estimated. alt_IDs : 1D ndarray. All elements should be ints. There should be one row per obervation per available alternative for the given observation. Elements denote the alternative corresponding to the given row of the design matrix. rows_to_obs : 2D scipy sparse array. All elements should be zeros and ones. There should be one row per observation per available alternative and one column per observation. This matrix maps the rows of the design matrix to the unique observations (on the columns). rows_to_alts : 2D scipy sparse array. All elements should be zeros and ones. There should be one row per observation per available alternative and one column per possible alternative. This matrix maps the rows of the design matrix to the possible alternatives for this dataset. rows_to_mixers : 2D scipy sparse array. All elements should be zeros and ones. Will map the rows of the design matrix to the particular units that the mixing is being performed over. Note that in the case of panel data, this matrix will be different from `rows_to_obs`. choice_vector : 1D ndarray. All elements should be either ones or zeros. There should be one row per observation per available alternative for the given observation. Elements denote the alternative which is chosen by the given observation with a 1 and a zero otherwise. utility_transform : callable. Should accept a 1D array of systematic utility values, a 1D array of alternative IDs, and miscellaneous args and kwargs. Should return a 2D array whose elements contain the appropriately transformed systematic utility values, based on the current model being evaluated and the given draw of the random coefficients. There should be one column for each draw of the random coefficients. There should have one row per individual per choice situation per available alternative. ridge : scalar or None, optional. Determines whether or not ridge regression is performed. If a scalar is passed, then that scalar determines the ridge penalty for the optimization. Default = None. weights : 1D ndarray or None. Allows for the calculation of weighted log-likelihoods. The weights can represent various things. In stratified samples, the weights may be the proportion of the observations in a given strata for a sample in relation to the proportion of observations in that strata in the population. In latent class models, the weights may be the probability of being a particular class. Returns ------- log_likelihood: float. The log-likelihood of the mixed logit model evaluated at the passed values of `params`.
[ "Parameters", "----------", "params", ":", "1D", "ndarray", ".", "All", "elements", "should", "by", "ints", "floats", "or", "longs", ".", "Should", "have", "1", "element", "for", "each", "utility", "coefficient", "being", "estimated", "(", "i", ".", "e", "...
python
train
Microsoft/nni
src/sdk/pynni/nni/metis_tuner/Regression_GMM/Selection.py
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/Regression_GMM/Selection.py#L63-L77
def selection(x_bounds, x_types, clusteringmodel_gmm_good, clusteringmodel_gmm_bad, minimize_starting_points, minimize_constraints_fun=None): ''' Select the lowest mu value ''' results = lib_acquisition_function.next_hyperparameter_lowest_mu(\ _ratio_scores, [clusteringmodel_gmm_good, clusteringmodel_gmm_bad],\ x_bounds, x_types, minimize_starting_points, \ minimize_constraints_fun=minimize_constraints_fun) return results
[ "def", "selection", "(", "x_bounds", ",", "x_types", ",", "clusteringmodel_gmm_good", ",", "clusteringmodel_gmm_bad", ",", "minimize_starting_points", ",", "minimize_constraints_fun", "=", "None", ")", ":", "results", "=", "lib_acquisition_function", ".", "next_hyperparam...
Select the lowest mu value
[ "Select", "the", "lowest", "mu", "value" ]
python
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3089-L3213
def qteGetMacroObject(self, macroName: str, widgetObj: QtGui.QWidget): """ Return macro that is name- and signature compatible with ``macroName`` and ``widgetObj``. The method considers all macros with name ``macroName`` and returns the one that matches 'best'. To determine this best match, the applet-and widget signatures of the macro are compared to those of ``widgetObj`` and picked in the following order: 1. Applet- and widget signature of both match. 2. Widget signature matches, applet signature in macro is "*" 3. Applet signature matches, widget signature in macro is "*" 4. Macro reports "*" for both its applet- and widget signature. If the macro does not fit any of these four criteria, then no compatible macro is available and the method returns **None**. |Args| * ``macroName`` (**str**): name of macro. * ``widgetObj`` (**QWidget**): widget for which a compatible macro is sought. |Returns| * **QtmacsMacro**: best matching macro, or **None**. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Determine the applet- and widget signature. This is trivial # if the widget was registered with Qtmacs because its # '_qteAdmin' attribute will provide this information. If, on # the other hand, the widget was not registered with Qtmacs # then it has no signature, yet its parent applet must because # every applet has one. The only exception when the applet # signature is therefore when there are no applets to begin # with, ie. the the window is empty. if hasattr(widgetObj, '_qteAdmin'): app_signature = widgetObj._qteAdmin.appletSignature wid_signature = widgetObj._qteAdmin.widgetSignature # Return immediately if the applet signature is None # (should be impossible). if app_signature is None: msg = 'Applet has no signature.' self.qteLogger.error(msg, stack_info=True) return None else: wid_signature = None app = qteGetAppletFromWidget(widgetObj) if app is None: app_signature = None else: app_signature = app._qteAdmin.appletSignature # Find all macros with name 'macroName'. This will produce a list of # tuples with entries (macroName, app_sig, wid_sig). name_match = [m for m in self._qteRegistryMacros if m[0] == macroName] # Find all macros with a compatible applet signature. This is # produce another list of tuples with the same format as # the name_match list (see above). app_sig_match = [_ for _ in name_match if _[1] in (app_signature, '*')] if wid_signature is None: wid_sig_match = [_ for _ in app_sig_match if _[2] == '*'] else: # Find all macros with a compatible widget signature. This is # a list of tuples, each tuple consisting of (macroName, # app_sig, wid_sig). wid_sig_match = [_ for _ in app_sig_match if _[2] in (wid_signature, '*')] # Pick a macro. if len(wid_sig_match) == 0: # No macro is compatible with either the applet- or widget # signature. return None elif len(wid_sig_match) == 1: match = wid_sig_match[0] # Exactly one macro is compatible with either the applet- # or widget signature. return self._qteRegistryMacros[match] else: # Found multiple matches. For any given macro 'name', # applet signature 'app', and widget signature 'wid' there # can be at most four macros in the list: *:*:name, # wid:*:name, *:app:name, and wid:app:name. # See if there is a macro for which both the applet and # widget signature match. tmp = [match for match in wid_sig_match if (match[1] != '*') and (match[2] != '*')] if len(tmp) > 0: match = tmp[0] return self._qteRegistryMacros[match] # See if there is a macro with a matching widget signature. tmp = [match for match in wid_sig_match if match[2] != '*'] if len(tmp) > 0: match = tmp[0] return self._qteRegistryMacros[match] # See if there is a macro with a matching applet signature. tmp = [match for match in wid_sig_match if match[1] != '*'] if len(tmp) > 0: match = tmp[0] return self._qteRegistryMacros[match] # At this point only one possibility is left, namely a # generic macro that is applicable to arbitrary applets # and widgets, eg. NextApplet. tmp = [match for match in wid_sig_match if (match[1] == '*') and (match[2] == '*')] if len(tmp) > 0: match = tmp[0] return self._qteRegistryMacros[match] # This should be impossible. msg = 'No compatible macro found - should be impossible.' self.qteLogger.error(msg, stack_info=True)
[ "def", "qteGetMacroObject", "(", "self", ",", "macroName", ":", "str", ",", "widgetObj", ":", "QtGui", ".", "QWidget", ")", ":", "# Determine the applet- and widget signature. This is trivial", "# if the widget was registered with Qtmacs because its", "# '_qteAdmin' attribute wil...
Return macro that is name- and signature compatible with ``macroName`` and ``widgetObj``. The method considers all macros with name ``macroName`` and returns the one that matches 'best'. To determine this best match, the applet-and widget signatures of the macro are compared to those of ``widgetObj`` and picked in the following order: 1. Applet- and widget signature of both match. 2. Widget signature matches, applet signature in macro is "*" 3. Applet signature matches, widget signature in macro is "*" 4. Macro reports "*" for both its applet- and widget signature. If the macro does not fit any of these four criteria, then no compatible macro is available and the method returns **None**. |Args| * ``macroName`` (**str**): name of macro. * ``widgetObj`` (**QWidget**): widget for which a compatible macro is sought. |Returns| * **QtmacsMacro**: best matching macro, or **None**. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Return", "macro", "that", "is", "name", "-", "and", "signature", "compatible", "with", "macroName", "and", "widgetObj", "." ]
python
train
bwhite/hadoopy
hadoopy/thirdparty/pyinstaller/PyInstaller/loader/iu.py
https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/loader/iu.py#L646-L713
def _os_bootstrap(): """ Set up 'os' module replacement functions for use during import bootstrap. """ global _os_stat, _os_getcwd, _os_environ, _os_listdir global _os_path_join, _os_path_dirname, _os_path_basename global _os_sep names = sys.builtin_module_names join = dirname = environ = listdir = basename = None mindirlen = 0 # Only 'posix' and 'nt' os specific modules are supported. # 'dos', 'os2' and 'mac' (MacOS 9) are not supported. if 'posix' in names: from posix import stat, getcwd, environ, listdir sep = _os_sep = '/' mindirlen = 1 elif 'nt' in names: from nt import stat, getcwd, environ, listdir sep = _os_sep = '\\' mindirlen = 3 else: raise ImportError('no os specific module found') if join is None: def join(a, b, sep=sep): if a == '': return b lastchar = a[-1:] if lastchar == '/' or lastchar == sep: return a + b return a + sep + b if dirname is None: def dirname(a, sep=sep, mindirlen=mindirlen): for i in range(len(a) - 1, -1, -1): c = a[i] if c == '/' or c == sep: if i < mindirlen: return a[:i + 1] return a[:i] return '' if basename is None: def basename(p): i = p.rfind(sep) if i == -1: return p else: return p[i + len(sep):] def _listdir(dir, cache={}): # since this function is only used by caseOk, it's fine to cache the # results and avoid reading the whole contents of a directory each time # we just want to check the case of a filename. if not dir in cache: cache[dir] = listdir(dir) return cache[dir] _os_stat = stat _os_getcwd = getcwd _os_path_join = join _os_path_dirname = dirname _os_environ = environ _os_listdir = _listdir _os_path_basename = basename
[ "def", "_os_bootstrap", "(", ")", ":", "global", "_os_stat", ",", "_os_getcwd", ",", "_os_environ", ",", "_os_listdir", "global", "_os_path_join", ",", "_os_path_dirname", ",", "_os_path_basename", "global", "_os_sep", "names", "=", "sys", ".", "builtin_module_names...
Set up 'os' module replacement functions for use during import bootstrap.
[ "Set", "up", "os", "module", "replacement", "functions", "for", "use", "during", "import", "bootstrap", "." ]
python
train
h2oai/h2o-3
h2o-bindings/bin/pymagic.py
https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-bindings/bin/pymagic.py#L70-L80
def main(): """Executed when script is run as-is.""" # magic_files = {} for filename in locate_files(ROOT_DIR): print("Processing %s" % filename) with open(filename, "rt") as f: tokens = list(tokenize.generate_tokens(f.readline)) text1 = tokenize.untokenize(tokens) ntokens = normalize_tokens(tokens) text2 = tokenize.untokenize(ntokens) assert text1 == text2
[ "def", "main", "(", ")", ":", "# magic_files = {}", "for", "filename", "in", "locate_files", "(", "ROOT_DIR", ")", ":", "print", "(", "\"Processing %s\"", "%", "filename", ")", "with", "open", "(", "filename", ",", "\"rt\"", ")", "as", "f", ":", "tokens", ...
Executed when script is run as-is.
[ "Executed", "when", "script", "is", "run", "as", "-", "is", "." ]
python
test
tensorflow/cleverhans
cleverhans/future/tf2/attacks/fast_gradient_method.py
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/future/tf2/attacks/fast_gradient_method.py#L7-L59
def fast_gradient_method(model_fn, x, eps, ord, clip_min=None, clip_max=None, y=None, targeted=False, sanity_checks=False): """ Tensorflow 2.0 implementation of the Fast Gradient Method. :param model_fn: a callable that takes an input tensor and returns the model logits. :param x: input tensor. :param eps: epsilon (input variation parameter); see https://arxiv.org/abs/1412.6572. :param ord: Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2. :param clip_min: (optional) float. Minimum float value for adversarial example components. :param clip_max: (optional) float. Maximum float value for adversarial example components. :param y: (optional) Tensor with true labels. If targeted is true, then provide the target label. Otherwise, only provide this parameter if you'd like to use true labels when crafting adversarial samples. Otherwise, model predictions are used as labels to avoid the "label leaking" effect (explained in this paper: https://arxiv.org/abs/1611.01236). Default is None. :param targeted: (optional) bool. Is the attack targeted or untargeted? Untargeted, the default, will try to make the label incorrect. Targeted will instead try to move in the direction of being more like y. :param sanity_checks: bool, if True, include asserts (Turn them off to use less runtime / memory or for unit tests that intentionally pass strange input) :return: a tensor for the adversarial example """ if ord not in [np.inf, 1, 2]: raise ValueError("Norm order must be either np.inf, 1, or 2.") asserts = [] # If a data range was specified, check that the input was in that range if clip_min is not None: asserts.append(tf.math.greater_equal(x, clip_min)) if clip_max is not None: asserts.append(tf.math.less_equal(x, clip_max)) if y is None: # Using model predictions as ground truth to avoid label leaking y = tf.argmax(model_fn(x), 1) grad = compute_gradient(model_fn, x, y, targeted) optimal_perturbation = optimize_linear(grad, eps, ord) # Add perturbation to original example to obtain adversarial example adv_x = x + optimal_perturbation # If clipping is needed, reset all values outside of [clip_min, clip_max] if (clip_min is not None) or (clip_max is not None): # We don't currently support one-sided clipping assert clip_min is not None and clip_max is not None adv_x = tf.clip_by_value(adv_x, clip_min, clip_max) if sanity_checks: assert np.all(asserts) return adv_x
[ "def", "fast_gradient_method", "(", "model_fn", ",", "x", ",", "eps", ",", "ord", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "y", "=", "None", ",", "targeted", "=", "False", ",", "sanity_checks", "=", "False", ")", ":", "if", "o...
Tensorflow 2.0 implementation of the Fast Gradient Method. :param model_fn: a callable that takes an input tensor and returns the model logits. :param x: input tensor. :param eps: epsilon (input variation parameter); see https://arxiv.org/abs/1412.6572. :param ord: Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2. :param clip_min: (optional) float. Minimum float value for adversarial example components. :param clip_max: (optional) float. Maximum float value for adversarial example components. :param y: (optional) Tensor with true labels. If targeted is true, then provide the target label. Otherwise, only provide this parameter if you'd like to use true labels when crafting adversarial samples. Otherwise, model predictions are used as labels to avoid the "label leaking" effect (explained in this paper: https://arxiv.org/abs/1611.01236). Default is None. :param targeted: (optional) bool. Is the attack targeted or untargeted? Untargeted, the default, will try to make the label incorrect. Targeted will instead try to move in the direction of being more like y. :param sanity_checks: bool, if True, include asserts (Turn them off to use less runtime / memory or for unit tests that intentionally pass strange input) :return: a tensor for the adversarial example
[ "Tensorflow", "2", ".", "0", "implementation", "of", "the", "Fast", "Gradient", "Method", ".", ":", "param", "model_fn", ":", "a", "callable", "that", "takes", "an", "input", "tensor", "and", "returns", "the", "model", "logits", ".", ":", "param", "x", "...
python
train
mushkevych/scheduler
synergy/db/dao/job_dao.py
https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/synergy/db/dao/job_dao.py#L68-L77
def get_one(self, process_name, timeperiod): """ method finds a single job record and returns it to the caller""" collection_name = self._get_job_collection_name(process_name) collection = self.ds.connection(collection_name) document = collection.find_one({job.PROCESS_NAME: process_name, job.TIMEPERIOD: timeperiod}) if document is None: raise LookupError('MongoDB has no job record in collection {0} for {1}@{2}' .format(collection, process_name, timeperiod)) return Job.from_json(document)
[ "def", "get_one", "(", "self", ",", "process_name", ",", "timeperiod", ")", ":", "collection_name", "=", "self", ".", "_get_job_collection_name", "(", "process_name", ")", "collection", "=", "self", ".", "ds", ".", "connection", "(", "collection_name", ")", "d...
method finds a single job record and returns it to the caller
[ "method", "finds", "a", "single", "job", "record", "and", "returns", "it", "to", "the", "caller" ]
python
train
sosy-lab/benchexec
benchexec/baseexecutor.py
https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/baseexecutor.py#L49-L57
def handle_basic_executor_options(options, parser): """Handle the options specified by add_basic_executor_options().""" # setup logging logLevel = logging.INFO if options.debug: logLevel = logging.DEBUG elif options.quiet: logLevel = logging.WARNING util.setup_logging(level=logLevel)
[ "def", "handle_basic_executor_options", "(", "options", ",", "parser", ")", ":", "# setup logging", "logLevel", "=", "logging", ".", "INFO", "if", "options", ".", "debug", ":", "logLevel", "=", "logging", ".", "DEBUG", "elif", "options", ".", "quiet", ":", "...
Handle the options specified by add_basic_executor_options().
[ "Handle", "the", "options", "specified", "by", "add_basic_executor_options", "()", "." ]
python
train
apache/incubator-heron
heron/tools/cli/src/python/version.py
https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/cli/src/python/version.py#L68-L112
def run(command, parser, cl_args, unknown_args): ''' :param command: :param parser: :param args: :param unknown_args: :return: ''' cluster = cl_args['cluster'] # server mode if cluster: config_file = config.heron_rc_file() client_confs = dict() # Read the cluster definition, if not found client_confs = cdefs.read_server_mode_cluster_definition(cluster, cl_args, config_file) if not client_confs[cluster]: Log.error('Neither service url nor %s cluster definition in %s file', cluster, config_file) return SimpleResult(Status.HeronError) # if cluster definition exists, but service_url is not set, it is an error if not 'service_url' in client_confs[cluster]: Log.error('No service url for %s cluster in %s', cluster, config_file) sys.exit(1) service_endpoint = cl_args['service_url'] service_apiurl = service_endpoint + rest.ROUTE_SIGNATURES[command][1] service_method = rest.ROUTE_SIGNATURES[command][0] try: r = service_method(service_apiurl) if r.status_code != requests.codes.ok: Log.error(r.json().get('message', "Unknown error from API server %d" % r.status_code)) sorted_items = sorted(r.json().items(), key=lambda tup: tup[0]) for key, value in sorted_items: print("%s : %s" % (key, value)) except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as err: Log.error(err) return SimpleResult(Status.HeronError) else: config.print_build_info() return SimpleResult(Status.Ok)
[ "def", "run", "(", "command", ",", "parser", ",", "cl_args", ",", "unknown_args", ")", ":", "cluster", "=", "cl_args", "[", "'cluster'", "]", "# server mode", "if", "cluster", ":", "config_file", "=", "config", ".", "heron_rc_file", "(", ")", "client_confs",...
:param command: :param parser: :param args: :param unknown_args: :return:
[ ":", "param", "command", ":", ":", "param", "parser", ":", ":", "param", "args", ":", ":", "param", "unknown_args", ":", ":", "return", ":" ]
python
valid
kensho-technologies/graphql-compiler
graphql_compiler/compiler/sql_context_helpers.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/sql_context_helpers.py#L16-L24
def get_node_selectable(node, context): """Return the Selectable Union[Table, CTE] associated with the node.""" query_path = node.query_path if query_path not in context.query_path_to_selectable: raise AssertionError( u'Unable to find selectable for query path {} with context {}.'.format( query_path, context)) selectable = context.query_path_to_selectable[query_path] return selectable
[ "def", "get_node_selectable", "(", "node", ",", "context", ")", ":", "query_path", "=", "node", ".", "query_path", "if", "query_path", "not", "in", "context", ".", "query_path_to_selectable", ":", "raise", "AssertionError", "(", "u'Unable to find selectable for query ...
Return the Selectable Union[Table, CTE] associated with the node.
[ "Return", "the", "Selectable", "Union", "[", "Table", "CTE", "]", "associated", "with", "the", "node", "." ]
python
train
T-002/pycast
pycast/common/timeseries.py
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/common/timeseries.py#L850-L879
def to_gnuplot_datafile(self, datafilepath): """Dumps the TimeSeries into a gnuplot compatible data file. :param string datafilepath: Path used to create the file. If that file already exists, it will be overwritten! :return: Returns :py:const:`True` if the data could be written, :py:const:`False` otherwise. :rtype: boolean """ try: datafile = file(datafilepath, "wb") except Exception: return False if self._timestampFormat is None: self._timestampFormat = _STR_EPOCHS datafile.write("# time_as_<%s> value..." % self._timestampFormat) convert = TimeSeries.convert_epoch_to_timestamp for datapoint in self._timeseriesData: timestamp = datapoint[0] values = datapoint[1:] if self._timestampFormat is not None: timestamp = convert(timestamp, self._timestampFormat) datafile.write("%s %s" % (timestamp, " ".join([str(entry) for entry in values]))) datafile.close() return True
[ "def", "to_gnuplot_datafile", "(", "self", ",", "datafilepath", ")", ":", "try", ":", "datafile", "=", "file", "(", "datafilepath", ",", "\"wb\"", ")", "except", "Exception", ":", "return", "False", "if", "self", ".", "_timestampFormat", "is", "None", ":", ...
Dumps the TimeSeries into a gnuplot compatible data file. :param string datafilepath: Path used to create the file. If that file already exists, it will be overwritten! :return: Returns :py:const:`True` if the data could be written, :py:const:`False` otherwise. :rtype: boolean
[ "Dumps", "the", "TimeSeries", "into", "a", "gnuplot", "compatible", "data", "file", "." ]
python
train
Gandi/gandi.cli
gandi/cli/modules/hostedcert.py
https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/hostedcert.py#L44-L59
def infos(cls, fqdn): """ Display information about hosted certificates for a fqdn. """ if isinstance(fqdn, (list, tuple)): ids = [] for fqd_ in fqdn: ids.extend(cls.infos(fqd_)) return ids ids = cls.usable_id(fqdn) if not ids: return [] if not isinstance(ids, (list, tuple)): ids = [ids] return [cls.info(id_) for id_ in ids]
[ "def", "infos", "(", "cls", ",", "fqdn", ")", ":", "if", "isinstance", "(", "fqdn", ",", "(", "list", ",", "tuple", ")", ")", ":", "ids", "=", "[", "]", "for", "fqd_", "in", "fqdn", ":", "ids", ".", "extend", "(", "cls", ".", "infos", "(", "f...
Display information about hosted certificates for a fqdn.
[ "Display", "information", "about", "hosted", "certificates", "for", "a", "fqdn", "." ]
python
train
saltstack/salt
salt/crypt.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/crypt.py#L847-L915
def decrypt_aes(self, payload, master_pub=True): ''' This function is used to decrypt the AES seed phrase returned from the master server. The seed phrase is decrypted with the SSH RSA host key. Pass in the encrypted AES key. Returns the decrypted AES seed key, a string :param dict payload: The incoming payload. This is a dictionary which may have the following keys: 'aes': The shared AES key 'enc': The format of the message. ('clear', 'pub', etc) 'sig': The message signature 'publish_port': The TCP port which published the message 'token': The encrypted token used to verify the message. 'pub_key': The public key of the sender. :rtype: str :return: The decrypted token that was provided, with padding. :rtype: str :return: The decrypted AES seed key ''' if self.opts.get('auth_trb', False): log.warning('Auth Called: %s', ''.join(traceback.format_stack())) else: log.debug('Decrypting the current master AES key') key = self.get_keys() if HAS_M2: key_str = key.private_decrypt(payload['aes'], RSA.pkcs1_oaep_padding) else: cipher = PKCS1_OAEP.new(key) key_str = cipher.decrypt(payload['aes']) if 'sig' in payload: m_path = os.path.join(self.opts['pki_dir'], self.mpub) if os.path.exists(m_path): try: mkey = get_rsa_pub_key(m_path) except Exception: return '', '' digest = hashlib.sha256(key_str).hexdigest() if six.PY3: digest = salt.utils.stringutils.to_bytes(digest) if HAS_M2: m_digest = public_decrypt(mkey, payload['sig']) else: m_digest = public_decrypt(mkey.publickey(), payload['sig']) if m_digest != digest: return '', '' else: return '', '' if six.PY3: key_str = salt.utils.stringutils.to_str(key_str) if '_|-' in key_str: return key_str.split('_|-') else: if 'token' in payload: if HAS_M2: token = key.private_decrypt(payload['token'], RSA.pkcs1_oaep_padding) else: token = cipher.decrypt(payload['token']) return key_str, token elif not master_pub: return key_str, '' return '', ''
[ "def", "decrypt_aes", "(", "self", ",", "payload", ",", "master_pub", "=", "True", ")", ":", "if", "self", ".", "opts", ".", "get", "(", "'auth_trb'", ",", "False", ")", ":", "log", ".", "warning", "(", "'Auth Called: %s'", ",", "''", ".", "join", "(...
This function is used to decrypt the AES seed phrase returned from the master server. The seed phrase is decrypted with the SSH RSA host key. Pass in the encrypted AES key. Returns the decrypted AES seed key, a string :param dict payload: The incoming payload. This is a dictionary which may have the following keys: 'aes': The shared AES key 'enc': The format of the message. ('clear', 'pub', etc) 'sig': The message signature 'publish_port': The TCP port which published the message 'token': The encrypted token used to verify the message. 'pub_key': The public key of the sender. :rtype: str :return: The decrypted token that was provided, with padding. :rtype: str :return: The decrypted AES seed key
[ "This", "function", "is", "used", "to", "decrypt", "the", "AES", "seed", "phrase", "returned", "from", "the", "master", "server", ".", "The", "seed", "phrase", "is", "decrypted", "with", "the", "SSH", "RSA", "host", "key", "." ]
python
train
titusjan/argos
argos/collect/collector.py
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L193-L204
def _setAxesNames(self, axisNames): """ Sets the axesnames, combobox lables and updates the headers. Removes old values first. The comboLables is the axes name + '-axis' """ for col, _ in enumerate(self._fullAxisNames, self.COL_FIRST_COMBO): self._setHeaderLabel(col, '') self._axisNames = tuple(axisNames) self._fullAxisNames = tuple([axName + self.AXIS_POST_FIX for axName in axisNames]) for col, label in enumerate(self._fullAxisNames, self.COL_FIRST_COMBO): self._setHeaderLabel(col, label)
[ "def", "_setAxesNames", "(", "self", ",", "axisNames", ")", ":", "for", "col", ",", "_", "in", "enumerate", "(", "self", ".", "_fullAxisNames", ",", "self", ".", "COL_FIRST_COMBO", ")", ":", "self", ".", "_setHeaderLabel", "(", "col", ",", "''", ")", "...
Sets the axesnames, combobox lables and updates the headers. Removes old values first. The comboLables is the axes name + '-axis'
[ "Sets", "the", "axesnames", "combobox", "lables", "and", "updates", "the", "headers", ".", "Removes", "old", "values", "first", ".", "The", "comboLables", "is", "the", "axes", "name", "+", "-", "axis" ]
python
train
EventTeam/beliefs
src/beliefs/cells/lists.py
https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/lists.py#L268-L275
def append(self, el): """ Idiosynractic method for adding an element to a list """ if self.value is None: self.value = [el] else: self.value.append(el)
[ "def", "append", "(", "self", ",", "el", ")", ":", "if", "self", ".", "value", "is", "None", ":", "self", ".", "value", "=", "[", "el", "]", "else", ":", "self", ".", "value", ".", "append", "(", "el", ")" ]
Idiosynractic method for adding an element to a list
[ "Idiosynractic", "method", "for", "adding", "an", "element", "to", "a", "list" ]
python
train
Riminder/python-riminder-api
riminder/profile.py
https://github.com/Riminder/python-riminder-api/blob/01279f0ece08cf3d1dd45f76de6d9edf7fafec90/riminder/profile.py#L68-L110
def list(self, source_ids=None, seniority="all", stage=None, date_start="1494539999", date_end=TIMESTAMP_NOW, filter_id=None, page=1, limit=30, sort_by='ranking', filter_reference=None, order_by=None): """ Retreive all profiles that match the query param. Args: date_end: <string> REQUIRED (default to timestamp of now) profiles' last date of reception date_start: <string> REQUIRED (default to "1494539999") profiles' first date of reception filter_id: <string> limit: <int> (default to 30) number of fetched profiles/page page: <int> REQUIRED default to 1 number of the page associated to the pagination seniority: <string> defaut to "all" profiles' seniority ("all", "senior", "junior") sort_by: <string> source_ids: <array of strings> REQUIRED stage: <string> Returns Retrieve the profiles data as <dict> """ query_params = {} query_params["date_end"] = _validate_timestamp(date_end, "date_end") query_params["date_start"] = _validate_timestamp(date_start, "date_start") if filter_id: query_params["filter_id"] = _validate_filter_id(filter_id) if filter_reference: query_params["filter_reference"] = _validate_filter_reference(filter_reference) query_params["limit"] = _validate_limit(limit) query_params["page"] = _validate_page(page) query_params["seniority"] = _validate_seniority(seniority) query_params["sort_by"] = _validate_sort_by(sort_by) query_params["source_ids"] = json.dumps(_validate_source_ids(source_ids)) query_params["stage"] = _validate_stage(stage) query_params["order_by"] = order_by response = self.client.get("profiles", query_params) return response.json()
[ "def", "list", "(", "self", ",", "source_ids", "=", "None", ",", "seniority", "=", "\"all\"", ",", "stage", "=", "None", ",", "date_start", "=", "\"1494539999\"", ",", "date_end", "=", "TIMESTAMP_NOW", ",", "filter_id", "=", "None", ",", "page", "=", "1"...
Retreive all profiles that match the query param. Args: date_end: <string> REQUIRED (default to timestamp of now) profiles' last date of reception date_start: <string> REQUIRED (default to "1494539999") profiles' first date of reception filter_id: <string> limit: <int> (default to 30) number of fetched profiles/page page: <int> REQUIRED default to 1 number of the page associated to the pagination seniority: <string> defaut to "all" profiles' seniority ("all", "senior", "junior") sort_by: <string> source_ids: <array of strings> REQUIRED stage: <string> Returns Retrieve the profiles data as <dict>
[ "Retreive", "all", "profiles", "that", "match", "the", "query", "param", "." ]
python
train
joke2k/faker
faker/providers/person/pl_PL/__init__.py
https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/person/pl_PL/__init__.py#L6-L21
def checksum_identity_card_number(characters): """ Calculates and returns a control digit for given list of characters basing on Identity Card Number standards. """ weights_for_check_digit = [7, 3, 1, 0, 7, 3, 1, 7, 3] check_digit = 0 for i in range(3): check_digit += weights_for_check_digit[i] * (ord(characters[i]) - 55) for i in range(4, 9): check_digit += weights_for_check_digit[i] * characters[i] check_digit %= 10 return check_digit
[ "def", "checksum_identity_card_number", "(", "characters", ")", ":", "weights_for_check_digit", "=", "[", "7", ",", "3", ",", "1", ",", "0", ",", "7", ",", "3", ",", "1", ",", "7", ",", "3", "]", "check_digit", "=", "0", "for", "i", "in", "range", ...
Calculates and returns a control digit for given list of characters basing on Identity Card Number standards.
[ "Calculates", "and", "returns", "a", "control", "digit", "for", "given", "list", "of", "characters", "basing", "on", "Identity", "Card", "Number", "standards", "." ]
python
train
iotaledger/iota.lib.py
iota/api.py
https://github.com/iotaledger/iota.lib.py/blob/97cdd1e241498446b46157b79b2a1ea2ec6d387a/iota/api.py#L171-L202
def attach_to_tangle( self, trunk_transaction, # type: TransactionHash branch_transaction, # type: TransactionHash trytes, # type: Iterable[TryteString] min_weight_magnitude=None, # type: Optional[int] ): # type: (...) -> dict """ Attaches the specified transactions (trytes) to the Tangle by doing Proof of Work. You need to supply branchTransaction as well as trunkTransaction (basically the tips which you're going to validate and reference with this transaction) - both of which you'll get through the getTransactionsToApprove API call. The returned value is a different set of tryte values which you can input into :py:meth:`broadcast_transactions` and :py:meth:`store_transactions`. References: - https://iota.readme.io/docs/attachtotangle """ if min_weight_magnitude is None: min_weight_magnitude = self.default_min_weight_magnitude return core.AttachToTangleCommand(self.adapter)( trunkTransaction=trunk_transaction, branchTransaction=branch_transaction, minWeightMagnitude=min_weight_magnitude, trytes=trytes, )
[ "def", "attach_to_tangle", "(", "self", ",", "trunk_transaction", ",", "# type: TransactionHash", "branch_transaction", ",", "# type: TransactionHash", "trytes", ",", "# type: Iterable[TryteString]", "min_weight_magnitude", "=", "None", ",", "# type: Optional[int]", ")", ":",...
Attaches the specified transactions (trytes) to the Tangle by doing Proof of Work. You need to supply branchTransaction as well as trunkTransaction (basically the tips which you're going to validate and reference with this transaction) - both of which you'll get through the getTransactionsToApprove API call. The returned value is a different set of tryte values which you can input into :py:meth:`broadcast_transactions` and :py:meth:`store_transactions`. References: - https://iota.readme.io/docs/attachtotangle
[ "Attaches", "the", "specified", "transactions", "(", "trytes", ")", "to", "the", "Tangle", "by", "doing", "Proof", "of", "Work", ".", "You", "need", "to", "supply", "branchTransaction", "as", "well", "as", "trunkTransaction", "(", "basically", "the", "tips", ...
python
test
davenquinn/Attitude
attitude/orientation/pca.py
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/pca.py#L361-L385
def strike_dip(self, degrees=True): """ Computes strike and dip from a normal vector. Results are usually the same as LLSQ in strike (to a few decimal places) and close in dip. Sometimes, dips are greater by as much as 45 degrees, reflecting inclusion of errors in x-y plane. """ n = self.axes[2] r = N.linalg.norm(n) strike = N.degrees(N.arctan2(n[0],n[1]))-90 dip = N.degrees(N.arccos(n[2]/r)) # Since PCA errors are not pinned to the XYZ plane, # we need to make sure our results are in the # right quadrant. if dip > 90: dip = 180 - dip strike += 180 # Proper azimuth notation if strike < 0: strike += 360 return strike, dip
[ "def", "strike_dip", "(", "self", ",", "degrees", "=", "True", ")", ":", "n", "=", "self", ".", "axes", "[", "2", "]", "r", "=", "N", ".", "linalg", ".", "norm", "(", "n", ")", "strike", "=", "N", ".", "degrees", "(", "N", ".", "arctan2", "("...
Computes strike and dip from a normal vector. Results are usually the same as LLSQ in strike (to a few decimal places) and close in dip. Sometimes, dips are greater by as much as 45 degrees, reflecting inclusion of errors in x-y plane.
[ "Computes", "strike", "and", "dip", "from", "a", "normal", "vector", ".", "Results", "are", "usually", "the", "same", "as", "LLSQ", "in", "strike", "(", "to", "a", "few", "decimal", "places", ")", "and", "close", "in", "dip", ".", "Sometimes", "dips", ...
python
train
ewiger/mlab
src/mlab/matlabpipe.py
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/matlabpipe.py#L41-L62
def _list_releases(): ''' Tries to guess matlab process release version and location path on osx machines. The paths we will search are in the format: /Applications/MATLAB_R[YEAR][VERSION].app/bin/matlab We will try the latest version first. If no path is found, None is reutrned. ''' if is_linux(): base_path = '/usr/local/MATLAB/R%d%s/bin/matlab' else: # assume mac base_path = '/Applications/MATLAB_R%d%s.app/bin/matlab' years = range(2050,1990,-1) release_letters = ('h', 'g', 'f', 'e', 'd', 'c', 'b', 'a') for year in years: for letter in release_letters: release = 'R%d%s' % (year, letter) matlab_path = base_path % (year, letter) if os.path.exists(matlab_path): yield (release, matlab_path)
[ "def", "_list_releases", "(", ")", ":", "if", "is_linux", "(", ")", ":", "base_path", "=", "'/usr/local/MATLAB/R%d%s/bin/matlab'", "else", ":", "# assume mac", "base_path", "=", "'/Applications/MATLAB_R%d%s.app/bin/matlab'", "years", "=", "range", "(", "2050", ",", ...
Tries to guess matlab process release version and location path on osx machines. The paths we will search are in the format: /Applications/MATLAB_R[YEAR][VERSION].app/bin/matlab We will try the latest version first. If no path is found, None is reutrned.
[ "Tries", "to", "guess", "matlab", "process", "release", "version", "and", "location", "path", "on", "osx", "machines", "." ]
python
train
bsmurphy/PyKrige
pykrige/uk.py
https://github.com/bsmurphy/PyKrige/blob/a4db3003b0b5688658c12faeb95a5a8b2b14b433/pykrige/uk.py#L398-L498
def _calculate_data_point_zscalars(self, x, y, type_='array'): """Determines the Z-scalar values at the specified coordinates for use when setting up the kriging matrix. Uses bilinear interpolation. Currently, the Z scalar values are extracted from the input Z grid exactly at the specified coordinates. This means that if the Z grid resolution is finer than the resolution of the desired kriged grid, there is no averaging of the scalar values to return an average Z value for that cell in the kriged grid. Rather, the exact Z value right at the coordinate is used.""" if type_ == 'scalar': nx = 1 ny = 1 z_scalars = None else: if x.ndim == 1: nx = x.shape[0] ny = 1 else: ny = x.shape[0] nx = x.shape[1] z_scalars = np.zeros(x.shape) for m in range(ny): for n in range(nx): if type_ == 'scalar': xn = x yn = y else: if x.ndim == 1: xn = x[n] yn = y[n] else: xn = x[m, n] yn = y[m, n] if xn > np.amax(self.external_Z_array_x) or \ xn < np.amin(self.external_Z_array_x) or \ yn > np.amax(self.external_Z_array_y) or \ yn < np.amin(self.external_Z_array_y): raise ValueError("External drift array does not cover " "specified kriging domain.") # bilinear interpolation external_x2_index = \ np.amin(np.where(self.external_Z_array_x >= xn)[0]) external_x1_index = \ np.amax(np.where(self.external_Z_array_x <= xn)[0]) external_y2_index = \ np.amin(np.where(self.external_Z_array_y >= yn)[0]) external_y1_index = \ np.amax(np.where(self.external_Z_array_y <= yn)[0]) if external_y1_index == external_y2_index: if external_x1_index == external_x2_index: z = self.external_Z_array[external_y1_index, external_x1_index] else: z = (self.external_Z_array[external_y1_index, external_x1_index] * (self.external_Z_array_x[external_x2_index] - xn) + self.external_Z_array[external_y2_index, external_x2_index] * (xn - self.external_Z_array_x[external_x1_index])) / \ (self.external_Z_array_x[external_x2_index] - self.external_Z_array_x[external_x1_index]) elif external_x1_index == external_x2_index: if external_y1_index == external_y2_index: z = self.external_Z_array[external_y1_index, external_x1_index] else: z = (self.external_Z_array[external_y1_index, external_x1_index] * (self.external_Z_array_y[external_y2_index] - yn) + self.external_Z_array[external_y2_index, external_x2_index] * (yn - self.external_Z_array_y[external_y1_index])) / \ (self.external_Z_array_y[external_y2_index] - self.external_Z_array_y[external_y1_index]) else: z = (self.external_Z_array[external_y1_index, external_x1_index] * (self.external_Z_array_x[external_x2_index] - xn) * (self.external_Z_array_y[external_y2_index] - yn) + self.external_Z_array[external_y1_index, external_x2_index] * (xn - self.external_Z_array_x[external_x1_index]) * (self.external_Z_array_y[external_y2_index] - yn) + self.external_Z_array[external_y2_index, external_x1_index] * (self.external_Z_array_x[external_x2_index] - xn) * (yn - self.external_Z_array_y[external_y1_index]) + self.external_Z_array[external_y2_index, external_x2_index] * (xn - self.external_Z_array_x[external_x1_index]) * (yn - self.external_Z_array_y[external_y1_index])) / \ ((self.external_Z_array_x[external_x2_index] - self.external_Z_array_x[external_x1_index]) * (self.external_Z_array_y[external_y2_index] - self.external_Z_array_y[external_y1_index])) if type_ == 'scalar': z_scalars = z else: if z_scalars.ndim == 1: z_scalars[n] = z else: z_scalars[m, n] = z return z_scalars
[ "def", "_calculate_data_point_zscalars", "(", "self", ",", "x", ",", "y", ",", "type_", "=", "'array'", ")", ":", "if", "type_", "==", "'scalar'", ":", "nx", "=", "1", "ny", "=", "1", "z_scalars", "=", "None", "else", ":", "if", "x", ".", "ndim", "...
Determines the Z-scalar values at the specified coordinates for use when setting up the kriging matrix. Uses bilinear interpolation. Currently, the Z scalar values are extracted from the input Z grid exactly at the specified coordinates. This means that if the Z grid resolution is finer than the resolution of the desired kriged grid, there is no averaging of the scalar values to return an average Z value for that cell in the kriged grid. Rather, the exact Z value right at the coordinate is used.
[ "Determines", "the", "Z", "-", "scalar", "values", "at", "the", "specified", "coordinates", "for", "use", "when", "setting", "up", "the", "kriging", "matrix", ".", "Uses", "bilinear", "interpolation", ".", "Currently", "the", "Z", "scalar", "values", "are", ...
python
train
numenta/nupic
src/nupic/frameworks/opf/opf_basic_environment.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/opf_basic_environment.py#L346-L457
def __openDatafile(self, modelResult): """Open the data file and write the header row""" # Write reset bit resetFieldMeta = FieldMetaInfo( name="reset", type=FieldMetaType.integer, special = FieldMetaSpecial.reset) self.__outputFieldsMeta.append(resetFieldMeta) # ----------------------------------------------------------------------- # Write each of the raw inputs that go into the encoders rawInput = modelResult.rawInput rawFields = rawInput.keys() rawFields.sort() for field in rawFields: if field.startswith('_') or field == 'reset': continue value = rawInput[field] meta = FieldMetaInfo(name=field, type=FieldMetaType.string, special=FieldMetaSpecial.none) self.__outputFieldsMeta.append(meta) self._rawInputNames.append(field) # ----------------------------------------------------------------------- # Handle each of the inference elements for inferenceElement, value in modelResult.inferences.iteritems(): inferenceLabel = InferenceElement.getLabel(inferenceElement) # TODO: Right now we assume list inferences are associated with # The input field metadata if type(value) in (list, tuple): # Append input and prediction field meta-info self.__outputFieldsMeta.extend(self.__getListMetaInfo(inferenceElement)) elif isinstance(value, dict): self.__outputFieldsMeta.extend(self.__getDictMetaInfo(inferenceElement, value)) else: if InferenceElement.getInputElement(inferenceElement): self.__outputFieldsMeta.append(FieldMetaInfo(name=inferenceLabel+".actual", type=FieldMetaType.string, special = '')) self.__outputFieldsMeta.append(FieldMetaInfo(name=inferenceLabel, type=FieldMetaType.string, special = '')) if self.__metricNames: for metricName in self.__metricNames: metricField = FieldMetaInfo( name = metricName, type = FieldMetaType.float, special = FieldMetaSpecial.none) self.__outputFieldsMeta.append(metricField) # Create the inference directory for our experiment inferenceDir = _FileUtils.createExperimentInferenceDir(self.__experimentDir) # Consctruct the prediction dataset file path filename = (self.__label + "." + opf_utils.InferenceType.getLabel(self.__inferenceType) + ".predictionLog.csv") self.__datasetPath = os.path.join(inferenceDir, filename) # Create the output dataset print "OPENING OUTPUT FOR PREDICTION WRITER AT: %r" % self.__datasetPath print "Prediction field-meta: %r" % ([tuple(i) for i in self.__outputFieldsMeta],) self.__dataset = FileRecordStream(streamID=self.__datasetPath, write=True, fields=self.__outputFieldsMeta) # Copy data from checkpoint cache if self.__checkpointCache is not None: self.__checkpointCache.seek(0) reader = csv.reader(self.__checkpointCache, dialect='excel') # Skip header row try: header = reader.next() except StopIteration: print "Empty record checkpoint initializer for %r" % (self.__datasetPath,) else: assert tuple(self.__dataset.getFieldNames()) == tuple(header), \ "dataset.getFieldNames(): %r; predictionCheckpointFieldNames: %r" % ( tuple(self.__dataset.getFieldNames()), tuple(header)) # Copy the rows from checkpoint numRowsCopied = 0 while True: try: row = reader.next() except StopIteration: break #print "DEBUG: restoring row from checkpoint: %r" % (row,) self.__dataset.appendRecord(row) numRowsCopied += 1 self.__dataset.flush() print "Restored %d rows from checkpoint for %r" % ( numRowsCopied, self.__datasetPath) # Dispose of our checkpoint cache self.__checkpointCache.close() self.__checkpointCache = None return
[ "def", "__openDatafile", "(", "self", ",", "modelResult", ")", ":", "# Write reset bit", "resetFieldMeta", "=", "FieldMetaInfo", "(", "name", "=", "\"reset\"", ",", "type", "=", "FieldMetaType", ".", "integer", ",", "special", "=", "FieldMetaSpecial", ".", "rese...
Open the data file and write the header row
[ "Open", "the", "data", "file", "and", "write", "the", "header", "row" ]
python
valid
datamachine/twx.botapi
twx/botapi/botapi.py
https://github.com/datamachine/twx.botapi/blob/c85184da738169e8f9d6d8e62970540f427c486e/twx/botapi/botapi.py#L4402-L4404
def unban_chat_member(self, *args, **kwargs): """See :func:`unban_chat_member`""" return unban_chat_member(*args, **self._merge_overrides(**kwargs)).run()
[ "def", "unban_chat_member", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "unban_chat_member", "(", "*", "args", ",", "*", "*", "self", ".", "_merge_overrides", "(", "*", "*", "kwargs", ")", ")", ".", "run", "(", ")" ]
See :func:`unban_chat_member`
[ "See", ":", "func", ":", "unban_chat_member" ]
python
train
materials-data-facility/toolbox
mdf_toolbox/sub_helpers.py
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/sub_helpers.py#L99-L140
def aggregate(self, q=None, scroll_size=SEARCH_LIMIT, reset_query=True, **kwargs): """Perform an advanced query, and return *all* matching results. Will automatically perform multiple queries in order to retrieve all results. Note: All ``aggregate`` queries run in advanced mode, and ``info`` is not available. Arguments: q (str): The query to execute. **Default:** The current helper-formed query, if any. There must be some query to execute. scroll_size (int): Maximum number of records returned per query. Must be between one and the ``SEARCH_LIMIT`` (inclusive). **Default:** ``SEARCH_LIMIT``. reset_query (bool): If ``True``, will destroy the current query after execution and start a fresh one. If ``False``, will keep the current query set. **Default:** ``True``. Keyword Arguments: scroll_field (str): The field on which to scroll. This should be a field that counts/indexes the entries. This should be set in ``self.scroll_field``, but if your application requires separate scroll fields for a single client, it can be set in this way as well. **Default**: ``self.scroll_field``. Returns: list of dict: All matching records. """ scroll_field = kwargs.get("scroll_field", self.scroll_field) # If q not specified, use internal, helper-built query if q is None: res = self._aggregate(scroll_field=scroll_field, scroll_size=scroll_size) if reset_query: self.reset_query() return res # Otherwise, run an independent query as SearchHelper.search() does. else: return self.__class__(index=self.index, q=q, advanced=True, search_client=self._SearchHelper__search_client ).aggregate(scroll_size=scroll_size, reset_query=reset_query)
[ "def", "aggregate", "(", "self", ",", "q", "=", "None", ",", "scroll_size", "=", "SEARCH_LIMIT", ",", "reset_query", "=", "True", ",", "*", "*", "kwargs", ")", ":", "scroll_field", "=", "kwargs", ".", "get", "(", "\"scroll_field\"", ",", "self", ".", "...
Perform an advanced query, and return *all* matching results. Will automatically perform multiple queries in order to retrieve all results. Note: All ``aggregate`` queries run in advanced mode, and ``info`` is not available. Arguments: q (str): The query to execute. **Default:** The current helper-formed query, if any. There must be some query to execute. scroll_size (int): Maximum number of records returned per query. Must be between one and the ``SEARCH_LIMIT`` (inclusive). **Default:** ``SEARCH_LIMIT``. reset_query (bool): If ``True``, will destroy the current query after execution and start a fresh one. If ``False``, will keep the current query set. **Default:** ``True``. Keyword Arguments: scroll_field (str): The field on which to scroll. This should be a field that counts/indexes the entries. This should be set in ``self.scroll_field``, but if your application requires separate scroll fields for a single client, it can be set in this way as well. **Default**: ``self.scroll_field``. Returns: list of dict: All matching records.
[ "Perform", "an", "advanced", "query", "and", "return", "*", "all", "*", "matching", "results", ".", "Will", "automatically", "perform", "multiple", "queries", "in", "order", "to", "retrieve", "all", "results", "." ]
python
train
sentinel-hub/eo-learn
ml_tools/eolearn/ml_tools/classifier.py
https://github.com/sentinel-hub/eo-learn/blob/b8c390b9f553c561612fe9eb64e720611633a035/ml_tools/eolearn/ml_tools/classifier.py#L60-L70
def _check_classifier(classifier): """ Check if the classifier implements predict and predict_proba methods. """ predict = getattr(classifier, "predict", None) if not callable(predict): raise ValueError('Classifier does not have predict method!') predict_proba = getattr(classifier, "predict_proba", None) if not callable(predict_proba): raise ValueError('Classifier does not have predict_proba method!')
[ "def", "_check_classifier", "(", "classifier", ")", ":", "predict", "=", "getattr", "(", "classifier", ",", "\"predict\"", ",", "None", ")", "if", "not", "callable", "(", "predict", ")", ":", "raise", "ValueError", "(", "'Classifier does not have predict method!'"...
Check if the classifier implements predict and predict_proba methods.
[ "Check", "if", "the", "classifier", "implements", "predict", "and", "predict_proba", "methods", "." ]
python
train
maximkulkin/lollipop
lollipop/utils.py
https://github.com/maximkulkin/lollipop/blob/042e8a24508cc3b28630863253c38ffbfc52c882/lollipop/utils.py#L59-L64
def call_with_context(func, context, *args): """ Check if given function has more arguments than given. Call it with context as last argument or without it. """ return make_context_aware(func, len(args))(*args + (context,))
[ "def", "call_with_context", "(", "func", ",", "context", ",", "*", "args", ")", ":", "return", "make_context_aware", "(", "func", ",", "len", "(", "args", ")", ")", "(", "*", "args", "+", "(", "context", ",", ")", ")" ]
Check if given function has more arguments than given. Call it with context as last argument or without it.
[ "Check", "if", "given", "function", "has", "more", "arguments", "than", "given", ".", "Call", "it", "with", "context", "as", "last", "argument", "or", "without", "it", "." ]
python
train
lesscpy/lesscpy
lesscpy/plib/call.py
https://github.com/lesscpy/lesscpy/blob/51e392fb4a3cd4ccfb6175e0e42ce7d2f6b78126/lesscpy/plib/call.py#L184-L193
def add(self, *args): """ Add integers args: args (list): target returns: str """ if (len(args) <= 1): return 0 return sum([int(v) for v in args])
[ "def", "add", "(", "self", ",", "*", "args", ")", ":", "if", "(", "len", "(", "args", ")", "<=", "1", ")", ":", "return", "0", "return", "sum", "(", "[", "int", "(", "v", ")", "for", "v", "in", "args", "]", ")" ]
Add integers args: args (list): target returns: str
[ "Add", "integers", "args", ":", "args", "(", "list", ")", ":", "target", "returns", ":", "str" ]
python
valid
opencobra/cobrapy
cobra/flux_analysis/moma.py
https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/moma.py#L49-L148
def add_moma(model, solution=None, linear=True): r"""Add constraints and objective representing for MOMA. This adds variables and constraints for the minimization of metabolic adjustment (MOMA) to the model. Parameters ---------- model : cobra.Model The model to add MOMA constraints and objective to. solution : cobra.Solution, optional A previous solution to use as a reference. If no solution is given, one will be computed using pFBA. linear : bool, optional Whether to use the linear MOMA formulation or not (default True). Notes ----- In the original MOMA [1]_ specification one looks for the flux distribution of the deletion (v^d) closest to the fluxes without the deletion (v). In math this means: minimize \sum_i (v^d_i - v_i)^2 s.t. Sv^d = 0 lb_i <= v^d_i <= ub_i Here, we use a variable transformation v^t := v^d_i - v_i. Substituting and using the fact that Sv = 0 gives: minimize \sum_i (v^t_i)^2 s.t. Sv^d = 0 v^t = v^d_i - v_i lb_i <= v^d_i <= ub_i So basically we just re-center the flux space at the old solution and then find the flux distribution closest to the new zero (center). This is the same strategy as used in cameo. In the case of linear MOMA [2]_, we instead minimize \sum_i abs(v^t_i). The linear MOMA is typically significantly faster. Also quadratic MOMA tends to give flux distributions in which all fluxes deviate from the reference fluxes a little bit whereas linear MOMA tends to give flux distributions where the majority of fluxes are the same reference with few fluxes deviating a lot (typical effect of L2 norm vs L1 norm). The former objective function is saved in the optlang solver interface as ``"moma_old_objective"`` and this can be used to immediately extract the value of the former objective after MOMA optimization. See Also -------- pfba : parsimonious FBA References ---------- .. [1] Segrè, Daniel, Dennis Vitkup, and George M. Church. “Analysis of Optimality in Natural and Perturbed Metabolic Networks.” Proceedings of the National Academy of Sciences 99, no. 23 (November 12, 2002): 15112. https://doi.org/10.1073/pnas.232349399. .. [2] Becker, Scott A, Adam M Feist, Monica L Mo, Gregory Hannum, Bernhard Ø Palsson, and Markus J Herrgard. “Quantitative Prediction of Cellular Metabolism with Constraint-Based Models: The COBRA Toolbox.” Nature Protocols 2 (March 29, 2007): 727. """ if 'moma_old_objective' in model.solver.variables: raise ValueError('model is already adjusted for MOMA') # Fall back to default QP solver if current one has no QP capability if not linear: model.solver = sutil.choose_solver(model, qp=True) if solution is None: solution = pfba(model) prob = model.problem v = prob.Variable("moma_old_objective") c = prob.Constraint(model.solver.objective.expression - v, lb=0.0, ub=0.0, name="moma_old_objective_constraint") to_add = [v, c] model.objective = prob.Objective(Zero, direction="min", sloppy=True) obj_vars = [] for r in model.reactions: flux = solution.fluxes[r.id] if linear: components = sutil.add_absolute_expression( model, r.flux_expression, name="moma_dist_" + r.id, difference=flux, add=False) to_add.extend(components) obj_vars.append(components.variable) else: dist = prob.Variable("moma_dist_" + r.id) const = prob.Constraint(r.flux_expression - dist, lb=flux, ub=flux, name="moma_constraint_" + r.id) to_add.extend([dist, const]) obj_vars.append(dist ** 2) model.add_cons_vars(to_add) if linear: model.objective.set_linear_coefficients({v: 1.0 for v in obj_vars}) else: model.objective = prob.Objective( add(obj_vars), direction="min", sloppy=True)
[ "def", "add_moma", "(", "model", ",", "solution", "=", "None", ",", "linear", "=", "True", ")", ":", "if", "'moma_old_objective'", "in", "model", ".", "solver", ".", "variables", ":", "raise", "ValueError", "(", "'model is already adjusted for MOMA'", ")", "# ...
r"""Add constraints and objective representing for MOMA. This adds variables and constraints for the minimization of metabolic adjustment (MOMA) to the model. Parameters ---------- model : cobra.Model The model to add MOMA constraints and objective to. solution : cobra.Solution, optional A previous solution to use as a reference. If no solution is given, one will be computed using pFBA. linear : bool, optional Whether to use the linear MOMA formulation or not (default True). Notes ----- In the original MOMA [1]_ specification one looks for the flux distribution of the deletion (v^d) closest to the fluxes without the deletion (v). In math this means: minimize \sum_i (v^d_i - v_i)^2 s.t. Sv^d = 0 lb_i <= v^d_i <= ub_i Here, we use a variable transformation v^t := v^d_i - v_i. Substituting and using the fact that Sv = 0 gives: minimize \sum_i (v^t_i)^2 s.t. Sv^d = 0 v^t = v^d_i - v_i lb_i <= v^d_i <= ub_i So basically we just re-center the flux space at the old solution and then find the flux distribution closest to the new zero (center). This is the same strategy as used in cameo. In the case of linear MOMA [2]_, we instead minimize \sum_i abs(v^t_i). The linear MOMA is typically significantly faster. Also quadratic MOMA tends to give flux distributions in which all fluxes deviate from the reference fluxes a little bit whereas linear MOMA tends to give flux distributions where the majority of fluxes are the same reference with few fluxes deviating a lot (typical effect of L2 norm vs L1 norm). The former objective function is saved in the optlang solver interface as ``"moma_old_objective"`` and this can be used to immediately extract the value of the former objective after MOMA optimization. See Also -------- pfba : parsimonious FBA References ---------- .. [1] Segrè, Daniel, Dennis Vitkup, and George M. Church. “Analysis of Optimality in Natural and Perturbed Metabolic Networks.” Proceedings of the National Academy of Sciences 99, no. 23 (November 12, 2002): 15112. https://doi.org/10.1073/pnas.232349399. .. [2] Becker, Scott A, Adam M Feist, Monica L Mo, Gregory Hannum, Bernhard Ø Palsson, and Markus J Herrgard. “Quantitative Prediction of Cellular Metabolism with Constraint-Based Models: The COBRA Toolbox.” Nature Protocols 2 (March 29, 2007): 727.
[ "r", "Add", "constraints", "and", "objective", "representing", "for", "MOMA", "." ]
python
valid
fermiPy/fermipy
fermipy/jobs/link.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/link.py#L786-L795
def get_jobs(self, recursive=True): """Return a dictionary with all the jobs For sub-classes, if recursive is True this will include jobs from any internal `Link` """ if recursive: ret_dict = self.jobs.copy() return ret_dict return self.jobs
[ "def", "get_jobs", "(", "self", ",", "recursive", "=", "True", ")", ":", "if", "recursive", ":", "ret_dict", "=", "self", ".", "jobs", ".", "copy", "(", ")", "return", "ret_dict", "return", "self", ".", "jobs" ]
Return a dictionary with all the jobs For sub-classes, if recursive is True this will include jobs from any internal `Link`
[ "Return", "a", "dictionary", "with", "all", "the", "jobs" ]
python
train
memphis-iis/GLUDB
gludb/backends/mongodb.py
https://github.com/memphis-iis/GLUDB/blob/25692528ff6fe8184a3570f61f31f1a90088a388/gludb/backends/mongodb.py#L55-L60
def find_one(self, cls, id): """Required functionality.""" one = self._find(cls, {"_id": id}) if not one: return None return one[0]
[ "def", "find_one", "(", "self", ",", "cls", ",", "id", ")", ":", "one", "=", "self", ".", "_find", "(", "cls", ",", "{", "\"_id\"", ":", "id", "}", ")", "if", "not", "one", ":", "return", "None", "return", "one", "[", "0", "]" ]
Required functionality.
[ "Required", "functionality", "." ]
python
train
openai/universe
universe/vncdriver/vendor/pydes.py
https://github.com/openai/universe/blob/cc9ce6ec241821bfb0f3b85dd455bd36e4ee7a8c/universe/vncdriver/vendor/pydes.py#L751-L755
def setPadMode(self, mode): """Sets the type of padding mode, pyDes.PAD_NORMAL or pyDes.PAD_PKCS5""" _baseDes.setPadMode(self, mode) for key in (self.__key1, self.__key2, self.__key3): key.setPadMode(mode)
[ "def", "setPadMode", "(", "self", ",", "mode", ")", ":", "_baseDes", ".", "setPadMode", "(", "self", ",", "mode", ")", "for", "key", "in", "(", "self", ".", "__key1", ",", "self", ".", "__key2", ",", "self", ".", "__key3", ")", ":", "key", ".", "...
Sets the type of padding mode, pyDes.PAD_NORMAL or pyDes.PAD_PKCS5
[ "Sets", "the", "type", "of", "padding", "mode", "pyDes", ".", "PAD_NORMAL", "or", "pyDes", ".", "PAD_PKCS5" ]
python
train
openstax/cnx-publishing
cnxpublishing/db.py
https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/db.py#L638-L658
def set_publication_failure(cursor, exc): """Given a publication exception, set the publication as failed and append the failure message to the publication record. """ publication_id = exc.publication_id if publication_id is None: raise ValueError("Exception must have a ``publication_id`` value.") cursor.execute("""\ SELECT "state_messages" FROM publications WHERE id = %s""", (publication_id,)) state_messages = cursor.fetchone()[0] if state_messages is None: state_messages = [] entry = exc.__dict__ entry['message'] = exc.message state_messages.append(entry) state_messages = json.dumps(state_messages) cursor.execute("""\ UPDATE publications SET ("state", "state_messages") = (%s, %s) WHERE id = %s""", ('Failed/Error', state_messages, publication_id,))
[ "def", "set_publication_failure", "(", "cursor", ",", "exc", ")", ":", "publication_id", "=", "exc", ".", "publication_id", "if", "publication_id", "is", "None", ":", "raise", "ValueError", "(", "\"Exception must have a ``publication_id`` value.\"", ")", "cursor", "."...
Given a publication exception, set the publication as failed and append the failure message to the publication record.
[ "Given", "a", "publication", "exception", "set", "the", "publication", "as", "failed", "and", "append", "the", "failure", "message", "to", "the", "publication", "record", "." ]
python
valid
SmokinCaterpillar/pypet
pypet/storageservice.py
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/storageservice.py#L4075-L4108
def _prm_write_shared_table(self, key, hdf5_group, fullname, **kwargs): """Creates a new empty table""" first_row = None description = None if 'first_row' in kwargs: first_row = kwargs.pop('first_row') if not 'description' in kwargs: description = {} for colname in first_row: data = first_row[colname] column = self._all_get_table_col(key, [data], fullname) description[colname] = column if 'description' in kwargs: description = kwargs.pop('description') if 'filters' in kwargs: filters = kwargs.pop('filters') else: filters = self._all_get_filters(kwargs) table = self._hdf5file.create_table(where=hdf5_group, name=key, description=description, filters=filters, **kwargs) table.flush() if first_row is not None: row = table.row for key in description: row[key] = first_row[key] row.append() table.flush()
[ "def", "_prm_write_shared_table", "(", "self", ",", "key", ",", "hdf5_group", ",", "fullname", ",", "*", "*", "kwargs", ")", ":", "first_row", "=", "None", "description", "=", "None", "if", "'first_row'", "in", "kwargs", ":", "first_row", "=", "kwargs", "....
Creates a new empty table
[ "Creates", "a", "new", "empty", "table" ]
python
test
python-diamond/Diamond
src/collectors/nvidia_gpu/nvidia_gpu.py
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/nvidia_gpu/nvidia_gpu.py#L119-L129
def collect(self): """ Collector GPU stats """ stats_config = self.config['stats'] if USE_PYTHON_BINDING: collect_metrics = self.collect_via_pynvml else: collect_metrics = self.collect_via_nvidia_smi collect_metrics(stats_config)
[ "def", "collect", "(", "self", ")", ":", "stats_config", "=", "self", ".", "config", "[", "'stats'", "]", "if", "USE_PYTHON_BINDING", ":", "collect_metrics", "=", "self", ".", "collect_via_pynvml", "else", ":", "collect_metrics", "=", "self", ".", "collect_via...
Collector GPU stats
[ "Collector", "GPU", "stats" ]
python
train
pylast/pylast
src/pylast/__init__.py
https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L505-L512
def get_artist_by_mbid(self, mbid): """Looks up an artist by its MusicBrainz ID""" params = {"mbid": mbid} doc = _Request(self, "artist.getInfo", params).execute(True) return Artist(_extract(doc, "name"), self)
[ "def", "get_artist_by_mbid", "(", "self", ",", "mbid", ")", ":", "params", "=", "{", "\"mbid\"", ":", "mbid", "}", "doc", "=", "_Request", "(", "self", ",", "\"artist.getInfo\"", ",", "params", ")", ".", "execute", "(", "True", ")", "return", "Artist", ...
Looks up an artist by its MusicBrainz ID
[ "Looks", "up", "an", "artist", "by", "its", "MusicBrainz", "ID" ]
python
train
matousc89/padasip
padasip/filters/base_filter.py
https://github.com/matousc89/padasip/blob/c969eadd7fa181a84da0554d737fc13c6450d16f/padasip/filters/base_filter.py#L205-L224
def check_int(self, param, error_msg): """ This function check if the parameter is int. If yes, the function returns the parameter, if not, it raises error message. **Args:** * `param` : parameter to check (int or similar) * `error_ms` : lowest allowed value (int), or None **Returns:** * `param` : parameter (int) """ if type(param) == int: return int(param) else: raise ValueError(error_msg)
[ "def", "check_int", "(", "self", ",", "param", ",", "error_msg", ")", ":", "if", "type", "(", "param", ")", "==", "int", ":", "return", "int", "(", "param", ")", "else", ":", "raise", "ValueError", "(", "error_msg", ")" ]
This function check if the parameter is int. If yes, the function returns the parameter, if not, it raises error message. **Args:** * `param` : parameter to check (int or similar) * `error_ms` : lowest allowed value (int), or None **Returns:** * `param` : parameter (int)
[ "This", "function", "check", "if", "the", "parameter", "is", "int", ".", "If", "yes", "the", "function", "returns", "the", "parameter", "if", "not", "it", "raises", "error", "message", ".", "**", "Args", ":", "**", "*", "param", ":", "parameter", "to", ...
python
train
dlon/html2markdown
html2markdown.py
https://github.com/dlon/html2markdown/blob/5946da7136e69a67b3dd37fd0e896be4d6a5b482/html2markdown.py#L332-L347
def convert(html): """converts an html string to markdown while preserving unsupported markup.""" bs = BeautifulSoup(html, 'html.parser') _markdownify(bs) ret = unicode(bs).replace(u'\xa0', '&nbsp;') ret = re.sub(r'\n{3,}', r'\n\n', ret) # ! FIXME: hack ret = re.sub(r'&lt;&lt;&lt;FLOATING LINK: (.+)&gt;&gt;&gt;', r'<\1>', ret) # ! FIXME: hack sp = re.split(r'(&lt;&lt;&lt;BLOCKQUOTE: .*?&gt;&gt;&gt;)', ret, flags=re.DOTALL) for i,e in enumerate(sp): if e[:len('&lt;&lt;&lt;BLOCKQUOTE:')] == '&lt;&lt;&lt;BLOCKQUOTE:': sp[i] = '> ' + e[len('&lt;&lt;&lt;BLOCKQUOTE:') : -len('&gt;&gt;&gt;')] sp[i] = sp[i].replace('\n', '\n> ') ret = ''.join(sp) return ret.strip('\n')
[ "def", "convert", "(", "html", ")", ":", "bs", "=", "BeautifulSoup", "(", "html", ",", "'html.parser'", ")", "_markdownify", "(", "bs", ")", "ret", "=", "unicode", "(", "bs", ")", ".", "replace", "(", "u'\\xa0'", ",", "'&nbsp;'", ")", "ret", "=", "re...
converts an html string to markdown while preserving unsupported markup.
[ "converts", "an", "html", "string", "to", "markdown", "while", "preserving", "unsupported", "markup", "." ]
python
train
NewKnowledge/punk
punk/preppy/encoders.py
https://github.com/NewKnowledge/punk/blob/b5c96aeea74728fc64290bb0f6dabc97b827e4e9/punk/preppy/encoders.py#L7-L46
def encode_df(df, data_types={}): """ Encode columns so their values are usable in vector operations. Making a few assumptions here, like that datetime should be an integer, and that it's acceptable to fill NaNs with 0. """ numbers = [] categories = [] datetimes = [] for column, series in df.iteritems(): if column in data_types: dtypes = data_types[column] else: dtypes = {} if 'datetime' in dtypes: index = pd.DatetimeIndex(pd.to_datetime(series.values)) df[column] = index.astype(np.int64).astype(float) datetimes.append(column) elif any([dtype in dtypes for dtype in ['category', 'label']]): # If this can be treated as a category, encode it df = pd.get_dummies(df,columns=[column]) categories.append(column) elif 'numeric' in dtypes: df[column] = clean_numbers(df[column].values) df[column] = df[column].astype(float) numbers.append(column) else: df.drop(column,1,inplace=True) # Scale continuous columns scaler = MinMaxScaler() df[numbers + datetimes] = scaler.fit_transform(df[numbers + datetimes]) return df, categories, numbers, datetimes
[ "def", "encode_df", "(", "df", ",", "data_types", "=", "{", "}", ")", ":", "numbers", "=", "[", "]", "categories", "=", "[", "]", "datetimes", "=", "[", "]", "for", "column", ",", "series", "in", "df", ".", "iteritems", "(", ")", ":", "if", "colu...
Encode columns so their values are usable in vector operations. Making a few assumptions here, like that datetime should be an integer, and that it's acceptable to fill NaNs with 0.
[ "Encode", "columns", "so", "their", "values", "are", "usable", "in", "vector", "operations", ".", "Making", "a", "few", "assumptions", "here", "like", "that", "datetime", "should", "be", "an", "integer", "and", "that", "it", "s", "acceptable", "to", "fill", ...
python
train
facelessuser/soupsieve
soupsieve/css_match.py
https://github.com/facelessuser/soupsieve/blob/24859cc3e756ebf46b75547d49c6b4a7bf35ee82/soupsieve/css_match.py#L1376-L1379
def closest(self, tag): """Match closest ancestor.""" return CSSMatch(self.selectors, tag, self.namespaces, self.flags).closest()
[ "def", "closest", "(", "self", ",", "tag", ")", ":", "return", "CSSMatch", "(", "self", ".", "selectors", ",", "tag", ",", "self", ".", "namespaces", ",", "self", ".", "flags", ")", ".", "closest", "(", ")" ]
Match closest ancestor.
[ "Match", "closest", "ancestor", "." ]
python
train
wmayner/pyphi
pyphi/distribution.py
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/distribution.py#L65-L78
def independent(repertoire): """Check whether the repertoire is independent.""" marginals = [marginal(repertoire, i) for i in range(repertoire.ndim)] # TODO: is there a way to do without an explicit iteration? joint = marginals[0] for m in marginals[1:]: joint = joint * m # TODO: should we round here? # repertoire = repertoire.round(config.PRECISION) # joint = joint.round(config.PRECISION) return np.array_equal(repertoire, joint)
[ "def", "independent", "(", "repertoire", ")", ":", "marginals", "=", "[", "marginal", "(", "repertoire", ",", "i", ")", "for", "i", "in", "range", "(", "repertoire", ".", "ndim", ")", "]", "# TODO: is there a way to do without an explicit iteration?", "joint", "...
Check whether the repertoire is independent.
[ "Check", "whether", "the", "repertoire", "is", "independent", "." ]
python
train
suds-community/suds
suds/wsdl.py
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsdl.py#L696-L710
def do_resolve(self, definitions): """ Resolve named references to other WSDL objects. This includes cross-linking information (from) the portType (to) the I{SOAP} protocol information on the binding for each operation. @param definitions: A definitions object. @type definitions: L{Definitions} """ self.__resolveport(definitions) for op in self.operations.values(): self.__resolvesoapbody(definitions, op) self.__resolveheaders(definitions, op) self.__resolvefaults(definitions, op)
[ "def", "do_resolve", "(", "self", ",", "definitions", ")", ":", "self", ".", "__resolveport", "(", "definitions", ")", "for", "op", "in", "self", ".", "operations", ".", "values", "(", ")", ":", "self", ".", "__resolvesoapbody", "(", "definitions", ",", ...
Resolve named references to other WSDL objects. This includes cross-linking information (from) the portType (to) the I{SOAP} protocol information on the binding for each operation. @param definitions: A definitions object. @type definitions: L{Definitions}
[ "Resolve", "named", "references", "to", "other", "WSDL", "objects", ".", "This", "includes", "cross", "-", "linking", "information", "(", "from", ")", "the", "portType", "(", "to", ")", "the", "I", "{", "SOAP", "}", "protocol", "information", "on", "the", ...
python
train
atlassian-api/atlassian-python-api
atlassian/jira.py
https://github.com/atlassian-api/atlassian-python-api/blob/540d269905c3e7547b666fe30c647b2d512cf358/atlassian/jira.py#L1021-L1035
def tempo_account_get_customers(self, query=None, count_accounts=None): """ Gets all or some Attribute whose key or name contain a specific substring. Attributes can be a Category or Customer. :param query: OPTIONAL: query for search :param count_accounts: bool OPTIONAL: provide how many associated Accounts with Customer :return: list of customers """ params = {} if query is not None: params['query'] = query if count_accounts is not None: params['countAccounts'] = count_accounts url = 'rest/tempo-accounts/1/customer' return self.get(url, params=params)
[ "def", "tempo_account_get_customers", "(", "self", ",", "query", "=", "None", ",", "count_accounts", "=", "None", ")", ":", "params", "=", "{", "}", "if", "query", "is", "not", "None", ":", "params", "[", "'query'", "]", "=", "query", "if", "count_accoun...
Gets all or some Attribute whose key or name contain a specific substring. Attributes can be a Category or Customer. :param query: OPTIONAL: query for search :param count_accounts: bool OPTIONAL: provide how many associated Accounts with Customer :return: list of customers
[ "Gets", "all", "or", "some", "Attribute", "whose", "key", "or", "name", "contain", "a", "specific", "substring", ".", "Attributes", "can", "be", "a", "Category", "or", "Customer", ".", ":", "param", "query", ":", "OPTIONAL", ":", "query", "for", "search", ...
python
train
pymc-devs/pymc
pymc/InstantiationDecorators.py
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/InstantiationDecorators.py#L300-L351
def robust_init(stochclass, tries, *args, **kwds): """Robust initialization of a Stochastic. If the evaluation of the log-probability returns a ZeroProbability error, due for example to a parent being outside of the support for this Stochastic, the values of parents are randomly sampled until a valid log-probability is obtained. If the log-probability is still not valid after `tries` attempts, the original ZeroProbability error is raised. :Parameters: stochclass : Stochastic, eg. Normal, Uniform, ... The Stochastic distribution to instantiate. tries : int Maximum number of times parents will be sampled. *args, **kwds Positional and keyword arguments to declare the Stochastic variable. :Example: >>> lower = pymc.Uniform('lower', 0., 2., value=1.5, rseed=True) >>> pymc.robust_init(pymc.Uniform, 100, 'data', lower=lower, upper=5, value=[1,2,3,4], observed=True) """ # Find the direct parents stochs = [arg for arg in (list(args) + list(kwds.values())) if isinstance(arg.__class__, StochasticMeta)] # Find the extended parents parents = stochs for s in stochs: parents.extend(s.extended_parents) extended_parents = set(parents) # Select the parents with a random method. random_parents = [ p for p in extended_parents if p.rseed is True and hasattr( p, 'random')] for i in range(tries): try: return stochclass(*args, **kwds) except ZeroProbability: exc = sys.exc_info() for parent in random_parents: try: parent.random() except: six.reraise(*exc) six.reraise(*exc)
[ "def", "robust_init", "(", "stochclass", ",", "tries", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "# Find the direct parents", "stochs", "=", "[", "arg", "for", "arg", "in", "(", "list", "(", "args", ")", "+", "list", "(", "kwds", ".", "value...
Robust initialization of a Stochastic. If the evaluation of the log-probability returns a ZeroProbability error, due for example to a parent being outside of the support for this Stochastic, the values of parents are randomly sampled until a valid log-probability is obtained. If the log-probability is still not valid after `tries` attempts, the original ZeroProbability error is raised. :Parameters: stochclass : Stochastic, eg. Normal, Uniform, ... The Stochastic distribution to instantiate. tries : int Maximum number of times parents will be sampled. *args, **kwds Positional and keyword arguments to declare the Stochastic variable. :Example: >>> lower = pymc.Uniform('lower', 0., 2., value=1.5, rseed=True) >>> pymc.robust_init(pymc.Uniform, 100, 'data', lower=lower, upper=5, value=[1,2,3,4], observed=True)
[ "Robust", "initialization", "of", "a", "Stochastic", "." ]
python
train
thoughtworksarts/EmoPy
EmoPy/src/directory_data_loader.py
https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/directory_data_loader.py#L86-L96
def _check_directory_arguments(self): """ Validates arguments for loading from directories, including static image and time series directories. """ if not os.path.isdir(self.datapath): raise (NotADirectoryError('Directory does not exist: %s' % self.datapath)) if self.time_delay: if self.time_delay < 1: raise ValueError('Time step argument must be greater than 0, but gave: %i' % self.time_delay) if not isinstance(self.time_delay, int): raise ValueError('Time step argument must be an integer, but gave: %s' % str(self.time_delay))
[ "def", "_check_directory_arguments", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "self", ".", "datapath", ")", ":", "raise", "(", "NotADirectoryError", "(", "'Directory does not exist: %s'", "%", "self", ".", "datapath", ")", ")...
Validates arguments for loading from directories, including static image and time series directories.
[ "Validates", "arguments", "for", "loading", "from", "directories", "including", "static", "image", "and", "time", "series", "directories", "." ]
python
train
fermiPy/fermipy
fermipy/sourcefind_utils.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/sourcefind_utils.py#L206-L225
def estimate_pos_and_err_parabolic(tsvals): """Solve for the position and uncertainty of source in one dimension assuming that you are near the maximum and the errors are parabolic Parameters ---------- tsvals : `~numpy.ndarray` The TS values at the maximum TS, and for each pixel on either side Returns ------- The position and uncertainty of the source, in pixel units w.r.t. the center of the maximum pixel """ a = tsvals[2] - tsvals[0] bc = 2. * tsvals[1] - tsvals[0] - tsvals[2] s = a / (2 * bc) err = np.sqrt(2 / bc) return s, err
[ "def", "estimate_pos_and_err_parabolic", "(", "tsvals", ")", ":", "a", "=", "tsvals", "[", "2", "]", "-", "tsvals", "[", "0", "]", "bc", "=", "2.", "*", "tsvals", "[", "1", "]", "-", "tsvals", "[", "0", "]", "-", "tsvals", "[", "2", "]", "s", "...
Solve for the position and uncertainty of source in one dimension assuming that you are near the maximum and the errors are parabolic Parameters ---------- tsvals : `~numpy.ndarray` The TS values at the maximum TS, and for each pixel on either side Returns ------- The position and uncertainty of the source, in pixel units w.r.t. the center of the maximum pixel
[ "Solve", "for", "the", "position", "and", "uncertainty", "of", "source", "in", "one", "dimension", "assuming", "that", "you", "are", "near", "the", "maximum", "and", "the", "errors", "are", "parabolic" ]
python
train
tanghaibao/jcvi
jcvi/compara/reconstruct.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/reconstruct.py#L241-L280
def zipbed(args): """ %prog zipbed species.bed collinear.anchors Build ancestral contig from collinear blocks. For example, to build pre-rho order, use `zipbed rice.bed rice.rice.1x1.collinear.anchors`. The algorithms proceeds by interleaving the genes together. """ p = OptionParser(zipbed.__doc__) p.add_option("--prefix", default="b", help="Prefix for the new seqid [default: %default]") opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) bedfile, anchorfile = args prefix = opts.prefix bed = Bed(bedfile) order = bed.order newbedfile = prefix + ".bed" fw = open(newbedfile, "w") af = AnchorFile(anchorfile) blocks = af.blocks pad = len(str(len(blocks))) for i, block in enumerate(blocks): block_id = "{0}{1:0{2}d}".format(prefix, i + 1, pad) pairs = [] for q, s, score in block: qi, q = order[q] si, s = order[s] pairs.append((qi, si)) newbed = list(interleave_pairs(pairs)) for i, b in enumerate(newbed): accn = bed[b].accn print("\t".join(str(x) for x in (block_id, i, i + 1, accn)), file=fw) logging.debug("Reconstructed bedfile written to `{0}`.".format(newbedfile))
[ "def", "zipbed", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "zipbed", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--prefix\"", ",", "default", "=", "\"b\"", ",", "help", "=", "\"Prefix for the new seqid [default: %default]\"", ")", "opts", ...
%prog zipbed species.bed collinear.anchors Build ancestral contig from collinear blocks. For example, to build pre-rho order, use `zipbed rice.bed rice.rice.1x1.collinear.anchors`. The algorithms proceeds by interleaving the genes together.
[ "%prog", "zipbed", "species", ".", "bed", "collinear", ".", "anchors" ]
python
train