nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
qiucheng025/zao-
3a5edf3607b3a523f95746bc69b688090c76d89a
plugins/convert/mask/_base.py
python
BlurMask.blurred
(self)
return blurred
The final blurred mask
The final blurred mask
[ "The", "final", "blurred", "mask" ]
def blurred(self): """ The final blurred mask """ func = self.func_mapping[self.blur_type] kwargs = self.get_kwargs() blurred = self.mask for i in range(self.passes): ksize = int(kwargs["ksize"][0]) logger.trace("Pass: %s, kernel_size: %s", i + 1, (ksize, ksize)) blurred = func(blurred, **kwargs) ksize = int(round(ksize * self.multipass_factor)) kwargs["ksize"] = self.get_kernel_tuple(ksize) logger.trace("Returning blurred mask. Shape: %s", blurred.shape) return blurred
[ "def", "blurred", "(", "self", ")", ":", "func", "=", "self", ".", "func_mapping", "[", "self", ".", "blur_type", "]", "kwargs", "=", "self", ".", "get_kwargs", "(", ")", "blurred", "=", "self", ".", "mask", "for", "i", "in", "range", "(", "self", ...
https://github.com/qiucheng025/zao-/blob/3a5edf3607b3a523f95746bc69b688090c76d89a/plugins/convert/mask/_base.py#L93-L105
plotdevice/plotdevice
598f66a19cd58b8cfea8295024998b322ed66adf
plotdevice/gfx/effects.py
python
_inversionFilter
(identity, img)
return _matrixFilter(transmat, img)
Conditionally turn black to white and up to down
Conditionally turn black to white and up to down
[ "Conditionally", "turn", "black", "to", "white", "and", "up", "to", "down" ]
def _inversionFilter(identity, img): """Conditionally turn black to white and up to down""" # set up a matrix that's either identity or an r/g/b inversion polarity = -1.0 if not identity else 1.0 bias = 0 if polarity>0 else 1 transmat = [(polarity, 0, 0, 0), (0, polarity, 0, 0), (0, 0, polarity, 0), (0, 0, 0, 0), (bias, bias, bias, 1)] return _matrixFilter(transmat, img)
[ "def", "_inversionFilter", "(", "identity", ",", "img", ")", ":", "# set up a matrix that's either identity or an r/g/b inversion", "polarity", "=", "-", "1.0", "if", "not", "identity", "else", "1.0", "bias", "=", "0", "if", "polarity", ">", "0", "else", "1", "t...
https://github.com/plotdevice/plotdevice/blob/598f66a19cd58b8cfea8295024998b322ed66adf/plotdevice/gfx/effects.py#L371-L379
giswqs/geemap
ba8de85557a8a1bc9c8d19e75bac69416afe7fea
geemap/geemap.py
python
Map.plot
( self, x, y, plot_type=None, overlay=False, position="bottomright", min_width=None, max_width=None, min_height=None, max_height=None, **kwargs, )
Creates a plot based on x-array and y-array data. Args: x (numpy.ndarray or list): The x-coordinates of the plotted line. y (numpy.ndarray or list): The y-coordinates of the plotted line. plot_type (str, optional): The plot type can be one of "None", "bar", "scatter" or "hist". Defaults to None. overlay (bool, optional): Whether to overlay plotted lines on the figure. Defaults to False. position (str, optional): Position of the control, can be ‘bottomleft’, ‘bottomright’, ‘topleft’, or ‘topright’. Defaults to 'bottomright'. min_width (int, optional): Min width of the widget (in pixels), if None it will respect the content size. Defaults to None. max_width (int, optional): Max width of the widget (in pixels), if None it will respect the content size. Defaults to None. min_height (int, optional): Min height of the widget (in pixels), if None it will respect the content size. Defaults to None. max_height (int, optional): Max height of the widget (in pixels), if None it will respect the content size. Defaults to None.
Creates a plot based on x-array and y-array data.
[ "Creates", "a", "plot", "based", "on", "x", "-", "array", "and", "y", "-", "array", "data", "." ]
def plot( self, x, y, plot_type=None, overlay=False, position="bottomright", min_width=None, max_width=None, min_height=None, max_height=None, **kwargs, ): """Creates a plot based on x-array and y-array data. Args: x (numpy.ndarray or list): The x-coordinates of the plotted line. y (numpy.ndarray or list): The y-coordinates of the plotted line. plot_type (str, optional): The plot type can be one of "None", "bar", "scatter" or "hist". Defaults to None. overlay (bool, optional): Whether to overlay plotted lines on the figure. Defaults to False. position (str, optional): Position of the control, can be ‘bottomleft’, ‘bottomright’, ‘topleft’, or ‘topright’. Defaults to 'bottomright'. min_width (int, optional): Min width of the widget (in pixels), if None it will respect the content size. Defaults to None. max_width (int, optional): Max width of the widget (in pixels), if None it will respect the content size. Defaults to None. min_height (int, optional): Min height of the widget (in pixels), if None it will respect the content size. Defaults to None. max_height (int, optional): Max height of the widget (in pixels), if None it will respect the content size. Defaults to None. """ if self.plot_widget is not None: plot_widget = self.plot_widget else: plot_widget = widgets.Output(layout={"border": "1px solid black"}) plot_control = ipyleaflet.WidgetControl( widget=plot_widget, position=position, min_width=min_width, max_width=max_width, min_height=min_height, max_height=max_height, ) self.plot_widget = plot_widget self.plot_control = plot_control self.add_control(plot_control) if max_width is None: max_width = 500 if max_height is None: max_height = 300 if (plot_type is None) and ("markers" not in kwargs.keys()): kwargs["markers"] = "circle" with plot_widget: try: fig = plt.figure(1, **kwargs) if max_width is not None: fig.layout.width = str(max_width) + "px" if max_height is not None: fig.layout.height = str(max_height) + "px" plot_widget.clear_output(wait=True) if not overlay: plt.clear() if plot_type is None: if "marker" not in kwargs.keys(): kwargs["marker"] = "circle" plt.plot(x, y, **kwargs) elif plot_type == "bar": plt.bar(x, y, **kwargs) elif plot_type == "scatter": plt.scatter(x, y, **kwargs) elif plot_type == "hist": plt.hist(y, **kwargs) plt.show() except Exception as e: print("Failed to create plot.") raise Exception(e)
[ "def", "plot", "(", "self", ",", "x", ",", "y", ",", "plot_type", "=", "None", ",", "overlay", "=", "False", ",", "position", "=", "\"bottomright\"", ",", "min_width", "=", "None", ",", "max_width", "=", "None", ",", "min_height", "=", "None", ",", "...
https://github.com/giswqs/geemap/blob/ba8de85557a8a1bc9c8d19e75bac69416afe7fea/geemap/geemap.py#L1960-L2037
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/apscheduler/triggers/cron/expressions.py
python
AllExpression.__str__
(self)
return '*'
[]
def __str__(self): if self.step: return '*/%d' % self.step return '*'
[ "def", "__str__", "(", "self", ")", ":", "if", "self", ".", "step", ":", "return", "'*/%d'", "%", "self", ".", "step", "return", "'*'" ]
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/apscheduler/triggers/cron/expressions.py#L40-L43
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit /tools/inject/lib/core/option.py
python
_setOS
()
Force the back-end DBMS operating system option.
Force the back-end DBMS operating system option.
[ "Force", "the", "back", "-", "end", "DBMS", "operating", "system", "option", "." ]
def _setOS(): """ Force the back-end DBMS operating system option. """ if not conf.os: return if conf.os.lower() not in SUPPORTED_OS: errMsg = "you provided an unsupported back-end DBMS operating " errMsg += "system. The supported DBMS operating systems for OS " errMsg += "and file system access are %s. " % ', '.join([o.capitalize() for o in SUPPORTED_OS]) errMsg += "If you do not know the back-end DBMS underlying OS, " errMsg += "do not provide it and sqlmap will fingerprint it for " errMsg += "you." raise SqlmapUnsupportedDBMSException(errMsg) debugMsg = "forcing back-end DBMS operating system to user defined " debugMsg += "value '%s'" % conf.os logger.debug(debugMsg) Backend.setOs(conf.os)
[ "def", "_setOS", "(", ")", ":", "if", "not", "conf", ".", "os", ":", "return", "if", "conf", ".", "os", ".", "lower", "(", ")", "not", "in", "SUPPORTED_OS", ":", "errMsg", "=", "\"you provided an unsupported back-end DBMS operating \"", "errMsg", "+=", "\"sy...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /tools/inject/lib/core/option.py#L854-L875
GoogleCloudPlatform/PerfKitBenchmarker
6e3412d7d5e414b8ca30ed5eaf970cef1d919a67
perfkitbenchmarker/providers/azure/azure_relational_db.py
python
AzureRelationalDb._Reboot
(self)
Reboot the managed db.
Reboot the managed db.
[ "Reboot", "the", "managed", "db", "." ]
def _Reboot(self): """Reboot the managed db.""" cmd = [ azure.AZURE_PATH, self.GetAzCommandForEngine(), 'server', 'restart', '--resource-group', self.resource_group.name, '--name', self.instance_id ] vm_util.IssueCommand(cmd) if not self._IsInstanceReady(): raise Exception('Instance could not be set to ready after ' 'reboot')
[ "def", "_Reboot", "(", "self", ")", ":", "cmd", "=", "[", "azure", ".", "AZURE_PATH", ",", "self", ".", "GetAzCommandForEngine", "(", ")", ",", "'server'", ",", "'restart'", ",", "'--resource-group'", ",", "self", ".", "resource_group", ".", "name", ",", ...
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/6e3412d7d5e414b8ca30ed5eaf970cef1d919a67/perfkitbenchmarker/providers/azure/azure_relational_db.py#L484-L498
AXErunners/electrum-axe
7ef05088c0edaf0688fb167df353d6da619ebf2f
electrum_axe/wallet.py
python
Abstract_Wallet.set_frozen_state_of_addresses
(self, addrs, freeze: bool)
return False
Set frozen state of the addresses to FREEZE, True or False
Set frozen state of the addresses to FREEZE, True or False
[ "Set", "frozen", "state", "of", "the", "addresses", "to", "FREEZE", "True", "or", "False" ]
def set_frozen_state_of_addresses(self, addrs, freeze: bool): """Set frozen state of the addresses to FREEZE, True or False""" if all(self.is_mine(addr) for addr in addrs): # FIXME take lock? if freeze: self.frozen_addresses |= set(addrs) else: self.frozen_addresses -= set(addrs) self.storage.put('frozen_addresses', list(self.frozen_addresses)) return True return False
[ "def", "set_frozen_state_of_addresses", "(", "self", ",", "addrs", ",", "freeze", ":", "bool", ")", ":", "if", "all", "(", "self", ".", "is_mine", "(", "addr", ")", "for", "addr", "in", "addrs", ")", ":", "# FIXME take lock?", "if", "freeze", ":", "self"...
https://github.com/AXErunners/electrum-axe/blob/7ef05088c0edaf0688fb167df353d6da619ebf2f/electrum_axe/wallet.py#L884-L894
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
pypy/objspace/std/unicodeobject.py
python
UnicodeDocstrings.startswith
()
S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
S.startswith(prefix[, start[, end]]) -> bool
[ "S", ".", "startswith", "(", "prefix", "[", "start", "[", "end", "]]", ")", "-", ">", "bool" ]
def startswith(): """S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try. """
[ "def", "startswith", "(", ")", ":" ]
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/pypy/objspace/std/unicodeobject.py#L918-L925
cannatag/ldap3
040e09fe37cf06801960d494dfadf0a6ed94e38f
ldap3/abstract/cursor.py
python
Cursor._get_attributes
(self, response, attr_defs, entry)
return attributes
Assign the result of the LDAP query to the Entry object dictionary. If the optional 'post_query' callable is present in the AttrDef it is called with each value of the attribute and the callable result is stored in the attribute. Returns the default value for missing attributes. If the 'dereference_dn' in AttrDef is a ObjectDef then the attribute values are treated as distinguished name and the relevant entry is retrieved and stored in the attribute value.
Assign the result of the LDAP query to the Entry object dictionary.
[ "Assign", "the", "result", "of", "the", "LDAP", "query", "to", "the", "Entry", "object", "dictionary", "." ]
def _get_attributes(self, response, attr_defs, entry): """Assign the result of the LDAP query to the Entry object dictionary. If the optional 'post_query' callable is present in the AttrDef it is called with each value of the attribute and the callable result is stored in the attribute. Returns the default value for missing attributes. If the 'dereference_dn' in AttrDef is a ObjectDef then the attribute values are treated as distinguished name and the relevant entry is retrieved and stored in the attribute value. """ conf_operational_attribute_prefix = get_config_parameter('ABSTRACTION_OPERATIONAL_ATTRIBUTE_PREFIX') conf_attributes_excluded_from_object_def = [v.lower() for v in get_config_parameter('ATTRIBUTES_EXCLUDED_FROM_OBJECT_DEF')] attributes = CaseInsensitiveWithAliasDict() used_attribute_names = set() for attr in attr_defs: attr_def = attr_defs[attr] attribute_name = None for attr_name in response['attributes']: if attr_def.name.lower() == attr_name.lower(): attribute_name = attr_name break if attribute_name or attr_def.default is not NotImplemented: # attribute value found in result or default value present - NotImplemented allows use of None as default attribute = self.attribute_class(attr_def, entry, self) attribute.response = response attribute.raw_values = response['raw_attributes'][attribute_name] if attribute_name else None if attr_def.post_query and attr_def.name in response['attributes'] and response['raw_attributes'] != list(): attribute.values = attr_def.post_query(attr_def.key, response['attributes'][attribute_name]) else: if attr_def.default is NotImplemented or (attribute_name and response['raw_attributes'][attribute_name] != list()): attribute.values = response['attributes'][attribute_name] else: attribute.values = attr_def.default if isinstance(attr_def.default, SEQUENCE_TYPES) else [attr_def.default] if not isinstance(attribute.values, list): # force attribute values to list (if attribute is single-valued) attribute.values = [attribute.values] if attr_def.dereference_dn: # try to get object referenced in value if attribute.values: temp_reader = Reader(self.connection, attr_def.dereference_dn, base='', get_operational_attributes=self.get_operational_attributes, controls=self.controls) temp_values = [] for element in attribute.values: if entry.entry_dn != element: temp_values.append(temp_reader.search_object(element)) else: error_message = 'object %s is referencing itself in the \'%s\' attribute' % (entry.entry_dn, attribute.definition.name) if log_enabled(ERROR): log(ERROR, '%s for <%s>', error_message, self) raise LDAPObjectDereferenceError(error_message) del temp_reader # remove the temporary Reader attribute.values = temp_values attributes[attribute.key] = attribute if attribute.other_names: attributes.set_alias(attribute.key, attribute.other_names) if attr_def.other_names: attributes.set_alias(attribute.key, attr_def.other_names) used_attribute_names.add(attribute_name) if self.attributes: used_attribute_names.update(self.attributes) for attribute_name in response['attributes']: if attribute_name not in used_attribute_names: operational_attribute = False # check if the type is an operational attribute if attribute_name in self.schema.attribute_types: if self.schema.attribute_types[attribute_name].no_user_modification or self.schema.attribute_types[attribute_name].usage in [ATTRIBUTE_DIRECTORY_OPERATION, ATTRIBUTE_DISTRIBUTED_OPERATION, ATTRIBUTE_DSA_OPERATION]: operational_attribute = True else: operational_attribute = True if not operational_attribute and attribute_name not in attr_defs and attribute_name.lower() not in conf_attributes_excluded_from_object_def: error_message = 'attribute \'%s\' not in object class \'%s\' for entry %s' % (attribute_name, ', '.join(entry.entry_definition._object_class), entry.entry_dn) if log_enabled(ERROR): log(ERROR, '%s for <%s>', error_message, self) raise LDAPCursorError(error_message) attribute = OperationalAttribute(AttrDef(conf_operational_attribute_prefix + attribute_name), entry, self) attribute.raw_values = response['raw_attributes'][attribute_name] attribute.values = response['attributes'][attribute_name] if isinstance(response['attributes'][attribute_name], SEQUENCE_TYPES) else [response['attributes'][attribute_name]] if (conf_operational_attribute_prefix + attribute_name) not in attributes: attributes[conf_operational_attribute_prefix + attribute_name] = attribute return attributes
[ "def", "_get_attributes", "(", "self", ",", "response", ",", "attr_defs", ",", "entry", ")", ":", "conf_operational_attribute_prefix", "=", "get_config_parameter", "(", "'ABSTRACTION_OPERATIONAL_ATTRIBUTE_PREFIX'", ")", "conf_attributes_excluded_from_object_def", "=", "[", ...
https://github.com/cannatag/ldap3/blob/040e09fe37cf06801960d494dfadf0a6ed94e38f/ldap3/abstract/cursor.py#L187-L265
refraction-ray/xalpha
943d7746e22c764d46cb8b55f53f4591d7912b54
xalpha/info.py
python
fundinfo.get_industry_holdings
(self, year="", season="", month="", threhold=0.5)
return d
持仓行业占比 :param year: :param season: :param month: :param threhold: float, 持仓小于该百分数的个股行业不再统计,加快速度 :return: Dict
持仓行业占比
[ "持仓行业占比" ]
def get_industry_holdings(self, year="", season="", month="", threhold=0.5): """ 持仓行业占比 :param year: :param season: :param month: :param threhold: float, 持仓小于该百分数的个股行业不再统计,加快速度 :return: Dict """ # 注意该 API 未直接使用天天基金的行业数据,其数据行业划分比较奇怪,大量行业都划分进了笼统的制造业, # 用于分析代表性不强,甚至没有消费,医药等行业划分方式 from xalpha.universal import ttjjcode, get_industry_fromxq df = self.get_stock_holdings(year=year, season=season, month=month) if df is None: logger.warning( "%s has no stock holdings in %s y %s s. (Possible reason: 链接基金,债券基金)" % (self.code, year, season) ) return d = {} for i, row in df.iterrows(): if row["ratio"] < threhold: continue code = ttjjcode(row["code"]) industry = get_industry_fromxq(code)["industryname"] if not industry.strip(): logger.warning( "%s has no industry information, cannot be classfied" % code ) else: if industry not in d: d[industry] = 0 d[industry] += row["ratio"] return d
[ "def", "get_industry_holdings", "(", "self", ",", "year", "=", "\"\"", ",", "season", "=", "\"\"", ",", "month", "=", "\"\"", ",", "threhold", "=", "0.5", ")", ":", "# 注意该 API 未直接使用天天基金的行业数据,其数据行业划分比较奇怪,大量行业都划分进了笼统的制造业,", "# 用于分析代表性不强,甚至没有消费,医药等行业划分方式", "from", "xal...
https://github.com/refraction-ray/xalpha/blob/943d7746e22c764d46cb8b55f53f4591d7912b54/xalpha/info.py#L1061-L1097
fooof-tools/fooof
14d6196e0b60c7e6da95b5cf858b20adcc5fc0ac
fooof/objs/group.py
python
FOOOFGroup.add_data
(self, freqs, power_spectra, freq_range=None)
Add data (frequencies and power spectrum values) to the current object. Parameters ---------- freqs : 1d array Frequency values for the power spectra, in linear space. power_spectra : 2d array, shape=[n_power_spectra, n_freqs] Matrix of power values, in linear space. freq_range : list of [float, float], optional Frequency range to restrict power spectra to. If not provided, keeps the entire range. Notes ----- If called on an object with existing data and/or results these will be cleared by this method call.
Add data (frequencies and power spectrum values) to the current object.
[ "Add", "data", "(", "frequencies", "and", "power", "spectrum", "values", ")", "to", "the", "current", "object", "." ]
def add_data(self, freqs, power_spectra, freq_range=None): """Add data (frequencies and power spectrum values) to the current object. Parameters ---------- freqs : 1d array Frequency values for the power spectra, in linear space. power_spectra : 2d array, shape=[n_power_spectra, n_freqs] Matrix of power values, in linear space. freq_range : list of [float, float], optional Frequency range to restrict power spectra to. If not provided, keeps the entire range. Notes ----- If called on an object with existing data and/or results these will be cleared by this method call. """ # If any data is already present, then clear data & results # This is to ensure object consistency of all data & results if np.any(self.freqs): self._reset_data_results(True, True, True, True) self._reset_group_results() self.freqs, self.power_spectra, self.freq_range, self.freq_res = \ self._prepare_data(freqs, power_spectra, freq_range, 2)
[ "def", "add_data", "(", "self", ",", "freqs", ",", "power_spectra", ",", "freq_range", "=", "None", ")", ":", "# If any data is already present, then clear data & results", "# This is to ensure object consistency of all data & results", "if", "np", ".", "any", "(", "self"...
https://github.com/fooof-tools/fooof/blob/14d6196e0b60c7e6da95b5cf858b20adcc5fc0ac/fooof/objs/group.py#L200-L225
openatx/uiautomator2
a6ebc2446a8babb4ce14dc62cfdb5590ea95c709
uiautomator2/image.py
python
ImageX.getpixel
(self, x, y)
return screenshot.convert("RGB").getpixel((x, y))
Returns: (r, g, b)
Returns: (r, g, b)
[ "Returns", ":", "(", "r", "g", "b", ")" ]
def getpixel(self, x, y): """ Returns: (r, g, b) """ screenshot = self.screenshot() return screenshot.convert("RGB").getpixel((x, y))
[ "def", "getpixel", "(", "self", ",", "x", ",", "y", ")", ":", "screenshot", "=", "self", ".", "screenshot", "(", ")", "return", "screenshot", ".", "convert", "(", "\"RGB\"", ")", ".", "getpixel", "(", "(", "x", ",", "y", ")", ")" ]
https://github.com/openatx/uiautomator2/blob/a6ebc2446a8babb4ce14dc62cfdb5590ea95c709/uiautomator2/image.py#L236-L242
microsoft/ptvsd
99c8513921021d2cc7cd82e132b65c644c256768
src/ptvsd/_vendored/pydevd/pydevd.py
python
PyDB.process_internal_commands
(self)
This function processes internal commands.
This function processes internal commands.
[ "This", "function", "processes", "internal", "commands", "." ]
def process_internal_commands(self): ''' This function processes internal commands. ''' # If this method is being called before the debugger is ready to run we should not notify # about threads and should only process commands sent to all threads. ready_to_run = self.ready_to_run dispose = False with self._main_lock: program_threads_alive = {} if ready_to_run: self.check_output_redirect() all_threads = threadingEnumerate() program_threads_dead = [] with self._lock_running_thread_ids: reset_cache = not self._running_thread_ids for t in all_threads: if getattr(t, 'is_pydev_daemon_thread', False): pass # I.e.: skip the DummyThreads created from pydev daemon threads elif isinstance(t, PyDBDaemonThread): pydev_log.error_once('Error in debugger: Found PyDBDaemonThread not marked with is_pydev_daemon_thread=True.') elif is_thread_alive(t): if reset_cache: # Fix multiprocessing debug with breakpoints in both main and child processes # (https://youtrack.jetbrains.com/issue/PY-17092) When the new process is created, the main # thread in the new process already has the attribute 'pydevd_id', so the new thread doesn't # get new id with its process number and the debugger loses access to both threads. # Therefore we should update thread_id for every main thread in the new process. clear_cached_thread_id(t) thread_id = get_thread_id(t) program_threads_alive[thread_id] = t self.notify_thread_created(thread_id, t, use_lock=False) # Compute and notify about threads which are no longer alive. thread_ids = list(self._running_thread_ids.keys()) for thread_id in thread_ids: if thread_id not in program_threads_alive: program_threads_dead.append(thread_id) for thread_id in program_threads_dead: self.notify_thread_not_alive(thread_id, use_lock=False) # Without self._lock_running_thread_ids if len(program_threads_alive) == 0 and ready_to_run: dispose = True else: # Actually process the commands now (make sure we don't have a lock for _lock_running_thread_ids # acquired at this point as it could lead to a deadlock if some command evaluated tried to # create a thread and wait for it -- which would try to notify about it getting that lock). curr_thread_id = get_current_thread_id(threadingCurrentThread()) if ready_to_run: process_thread_ids = (curr_thread_id, '*') else: process_thread_ids = ('*',) for thread_id in process_thread_ids: queue = self.get_internal_queue(thread_id) # some commands must be processed by the thread itself... if that's the case, # we will re-add the commands to the queue after executing. cmds_to_add_back = [] try: while True: int_cmd = queue.get(False) if not self.mpl_hooks_in_debug_console and isinstance(int_cmd, InternalConsoleExec): # add import hooks for matplotlib patches if only debug console was started try: self.init_matplotlib_in_debug_console() self.mpl_in_use = True except: pydev_log.debug("Matplotlib support in debug console failed", traceback.format_exc()) self.mpl_hooks_in_debug_console = True if int_cmd.can_be_executed_by(curr_thread_id): pydev_log.verbose("processing internal command ", int_cmd) int_cmd.do_it(self) else: pydev_log.verbose("NOT processing internal command ", int_cmd) cmds_to_add_back.append(int_cmd) except _queue.Empty: # @UndefinedVariable # this is how we exit for int_cmd in cmds_to_add_back: queue.put(int_cmd) if dispose: # Note: must be called without the main lock to avoid deadlocks. self.dispose_and_kill_all_pydevd_threads()
[ "def", "process_internal_commands", "(", "self", ")", ":", "# If this method is being called before the debugger is ready to run we should not notify", "# about threads and should only process commands sent to all threads.", "ready_to_run", "=", "self", ".", "ready_to_run", "dispose", "=...
https://github.com/microsoft/ptvsd/blob/99c8513921021d2cc7cd82e132b65c644c256768/src/ptvsd/_vendored/pydevd/pydevd.py#L1409-L1503
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/src/ansible/oc_pvc.py
python
main
()
return module.exit_json(**rval)
ansible oc module for pvc
ansible oc module for pvc
[ "ansible", "oc", "module", "for", "pvc" ]
def main(): ''' ansible oc module for pvc ''' module = AnsibleModule( argument_spec=dict( kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'), state=dict(default='present', type='str', choices=['present', 'absent', 'list']), debug=dict(default=False, type='bool'), name=dict(default=None, required=True, type='str'), namespace=dict(default=None, required=True, type='str'), volume_capacity=dict(default='1G', type='str'), storage_class_name=dict(default=None, required=False, type='str'), selector=dict(default=None, required=False, type='dict'), access_modes=dict(default=['ReadWriteOnce'], type='list'), ), supports_check_mode=True, ) rval = OCPVC.run_ansible(module.params, module.check_mode) if 'failed' in rval: module.fail_json(**rval) return module.exit_json(**rval)
[ "def", "main", "(", ")", ":", "module", "=", "AnsibleModule", "(", "argument_spec", "=", "dict", "(", "kubeconfig", "=", "dict", "(", "default", "=", "'/etc/origin/master/admin.kubeconfig'", ",", "type", "=", "'str'", ")", ",", "state", "=", "dict", "(", "...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/src/ansible/oc_pvc.py#L5-L31
uber-research/learning-to-reweight-examples
0b616c99ecf8a1c99925322167694272a966ed00
cifar/cifar_train.py
python
evaluate_train
(sess, model, num_batches, data=None)
return acc_clean, num_clean, acc_noise, num_noise
evaluate training model on clean and noisy data
evaluate training model on clean and noisy data
[ "evaluate", "training", "model", "on", "clean", "and", "noisy", "data" ]
def evaluate_train(sess, model, num_batches, data=None): """evaluate training model on clean and noisy data""" num_correct_clean = 0.0 num_clean = 0.0 num_correct_noise = 0.0 num_noise = 0.0 for ii in six.moves.xrange(num_batches): if data is not None: inp, label, clean_flag = sess.run([data.inputs, data.labels, data.clean_flag]) else: inp, label = None, None correct, _ = model.eval_step(sess, inp=inp, label=label) result_clean = correct * clean_flag result_noise = correct * (1 - clean_flag) num_correct_clean += result_clean.sum() num_correct_noise += result_noise.sum() num_clean += clean_flag.sum() num_noise += (1 - clean_flag).sum() acc_clean = (num_correct_clean / num_clean) acc_noise = (num_correct_noise / num_noise) return acc_clean, num_clean, acc_noise, num_noise
[ "def", "evaluate_train", "(", "sess", ",", "model", ",", "num_batches", ",", "data", "=", "None", ")", ":", "num_correct_clean", "=", "0.0", "num_clean", "=", "0.0", "num_correct_noise", "=", "0.0", "num_noise", "=", "0.0", "for", "ii", "in", "six", ".", ...
https://github.com/uber-research/learning-to-reweight-examples/blob/0b616c99ecf8a1c99925322167694272a966ed00/cifar/cifar_train.py#L318-L338
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/categories/polyhedra.py
python
PolyhedralSets.super_categories
(self)
return [Magmas().Commutative(), AdditiveMonoids()]
EXAMPLES:: sage: PolyhedralSets(QQ).super_categories() [Category of commutative magmas, Category of additive monoids]
EXAMPLES::
[ "EXAMPLES", "::" ]
def super_categories(self): """ EXAMPLES:: sage: PolyhedralSets(QQ).super_categories() [Category of commutative magmas, Category of additive monoids] """ from sage.categories.magmas import Magmas from sage.categories.additive_monoids import AdditiveMonoids return [Magmas().Commutative(), AdditiveMonoids()]
[ "def", "super_categories", "(", "self", ")", ":", "from", "sage", ".", "categories", ".", "magmas", "import", "Magmas", "from", "sage", ".", "categories", ".", "additive_monoids", "import", "AdditiveMonoids", "return", "[", "Magmas", "(", ")", ".", "Commutativ...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/categories/polyhedra.py#L62-L71
lRomul/argus-freesound
4faf8f192035b413e8946bda3555474cb9ad8237
src/utils.py
python
load_folds_data
(use_corrections=True)
return folds_data
[]
def load_folds_data(use_corrections=True): if use_corrections: with open(config.corrections_json_path) as file: corrections = json.load(file) print("Corrections:", corrections) pkl_name = f'{config.audio.get_hash(corrections=corrections)}.pkl' else: corrections = None pkl_name = f'{config.audio.get_hash()}.pkl' folds_data_pkl_path = config.folds_data_pkl_dir / pkl_name if folds_data_pkl_path.exists(): folds_data = pickle_load(folds_data_pkl_path) else: folds_data = get_folds_data(corrections) if not config.folds_data_pkl_dir.exists(): config.folds_data_pkl_dir.mkdir(parents=True, exist_ok=True) pickle_save(folds_data, folds_data_pkl_path) return folds_data
[ "def", "load_folds_data", "(", "use_corrections", "=", "True", ")", ":", "if", "use_corrections", ":", "with", "open", "(", "config", ".", "corrections_json_path", ")", "as", "file", ":", "corrections", "=", "json", ".", "load", "(", "file", ")", "print", ...
https://github.com/lRomul/argus-freesound/blob/4faf8f192035b413e8946bda3555474cb9ad8237/src/utils.py#L50-L69
tanghaibao/jcvi
5e720870c0928996f8b77a38208106ff0447ccb6
jcvi/graphics/assembly.py
python
covlen
(args)
%prog covlen covfile fastafile Plot coverage vs length. `covfile` is two-column listing contig id and depth of coverage.
%prog covlen covfile fastafile
[ "%prog", "covlen", "covfile", "fastafile" ]
def covlen(args): """ %prog covlen covfile fastafile Plot coverage vs length. `covfile` is two-column listing contig id and depth of coverage. """ import numpy as np import pandas as pd import seaborn as sns from jcvi.formats.base import DictFile p = OptionParser(covlen.__doc__) p.add_option("--maxsize", default=1000000, type="int", help="Max contig size") p.add_option("--maxcov", default=100, type="int", help="Max contig size") p.add_option("--color", default="m", help="Color of the data points") p.add_option( "--kind", default="scatter", choices=("scatter", "reg", "resid", "kde", "hex"), help="Kind of plot to draw", ) opts, args, iopts = p.set_image_options(args, figsize="8x8") if len(args) != 2: sys.exit(not p.print_help()) covfile, fastafile = args cov = DictFile(covfile, cast=float) s = Sizes(fastafile) data = [] maxsize, maxcov = opts.maxsize, opts.maxcov for ctg, size in s.iter_sizes(): c = cov.get(ctg, 0) if size > maxsize: continue if c > maxcov: continue data.append((size, c)) x, y = zip(*data) x = np.array(x) y = np.array(y) logging.debug("X size {0}, Y size {1}".format(x.size, y.size)) df = pd.DataFrame() xlab, ylab = "Length", "Coverage of depth (X)" df[xlab] = x df[ylab] = y sns.jointplot( xlab, ylab, kind=opts.kind, data=df, xlim=(0, maxsize), ylim=(0, maxcov), stat_func=None, edgecolor="w", color=opts.color, ) figname = covfile + ".pdf" savefig(figname, dpi=iopts.dpi, iopts=iopts)
[ "def", "covlen", "(", "args", ")", ":", "import", "numpy", "as", "np", "import", "pandas", "as", "pd", "import", "seaborn", "as", "sns", "from", "jcvi", ".", "formats", ".", "base", "import", "DictFile", "p", "=", "OptionParser", "(", "covlen", ".", "_...
https://github.com/tanghaibao/jcvi/blob/5e720870c0928996f8b77a38208106ff0447ccb6/jcvi/graphics/assembly.py#L34-L96
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/IPython/core/prefilter.py
python
PrefilterHandler.handle
(self, line_info)
return line
Handle normal input lines. Use as a template for handlers.
Handle normal input lines. Use as a template for handlers.
[ "Handle", "normal", "input", "lines", ".", "Use", "as", "a", "template", "for", "handlers", "." ]
def handle(self, line_info): # print "normal: ", line_info """Handle normal input lines. Use as a template for handlers.""" # With autoindent on, we need some way to exit the input loop, and I # don't want to force the user to have to backspace all the way to # clear the line. The rule will be in this case, that either two # lines of pure whitespace in a row, or a line of pure whitespace but # of a size different to the indent level, will exit the input loop. line = line_info.line continue_prompt = line_info.continue_prompt if (continue_prompt and self.shell.autoindent and line.isspace() and 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2): line = '' return line
[ "def", "handle", "(", "self", ",", "line_info", ")", ":", "# print \"normal: \", line_info", "# With autoindent on, we need some way to exit the input loop, and I", "# don't want to force the user to have to backspace all the way to", "# clear the line. The rule will be in this case, that eit...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/IPython/core/prefilter.py#L549-L567
SforAiDl/Neural-Voice-Cloning-With-Few-Samples
33fb609427657c9492f46507184ecba4dcc272b0
train_dv3.py
python
load_checkpoint
(path, model, optimizer, reset_optimizer)
return model
[]
def load_checkpoint(path, model, optimizer, reset_optimizer): global global_step global global_epoch print("Load checkpoint from: {}".format(path)) checkpoint = torch.load(path) model.load_state_dict(checkpoint["state_dict"]) if not reset_optimizer: optimizer_state = checkpoint["optimizer"] if optimizer_state is not None: print("Load optimizer state from {}".format(path)) optimizer.load_state_dict(checkpoint["optimizer"]) global_step = checkpoint["global_step"] global_epoch = checkpoint["global_epoch"] return model
[ "def", "load_checkpoint", "(", "path", ",", "model", ",", "optimizer", ",", "reset_optimizer", ")", ":", "global", "global_step", "global", "global_epoch", "print", "(", "\"Load checkpoint from: {}\"", ".", "format", "(", "path", ")", ")", "checkpoint", "=", "to...
https://github.com/SforAiDl/Neural-Voice-Cloning-With-Few-Samples/blob/33fb609427657c9492f46507184ecba4dcc272b0/train_dv3.py#L796-L811
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v9/services/services/ad_group_customizer_service/client.py
python
AdGroupCustomizerServiceClient.from_service_account_file
(cls, filename: str, *args, **kwargs)
return cls(*args, **kwargs)
Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: AdGroupCustomizerServiceClient: The constructed client.
Creates an instance of this client using the provided credentials file.
[ "Creates", "an", "instance", "of", "this", "client", "using", "the", "provided", "credentials", "file", "." ]
def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: AdGroupCustomizerServiceClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file( filename ) kwargs["credentials"] = credentials return cls(*args, **kwargs)
[ "def", "from_service_account_file", "(", "cls", ",", "filename", ":", "str", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "credentials", "=", "service_account", ".", "Credentials", ".", "from_service_account_file", "(", "filename", ")", "kwargs", "[", ...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/ad_group_customizer_service/client.py#L136-L153
Map-A-Droid/MAD
81375b5c9ccc5ca3161eb487aa81469d40ded221
mapadroid/ocr/screenPath.py
python
WordToScreenMatching.__handle_login_timeout
(self, diff, global_dict)
[]
def __handle_login_timeout(self, diff, global_dict) -> None: self._nextscreen = ScreenType.UNDEFINED click_text = 'SIGNOUT,SIGN,ABMELDEN,_DECONNECTER' n_boxes = len(global_dict['text']) for i in range(n_boxes): if any(elem in (global_dict['text'][i]) for elem in click_text.split(",")): self._click_center_button(diff, global_dict, i) time.sleep(2)
[ "def", "__handle_login_timeout", "(", "self", ",", "diff", ",", "global_dict", ")", "->", "None", ":", "self", ".", "_nextscreen", "=", "ScreenType", ".", "UNDEFINED", "click_text", "=", "'SIGNOUT,SIGN,ABMELDEN,_DECONNECTER'", "n_boxes", "=", "len", "(", "global_d...
https://github.com/Map-A-Droid/MAD/blob/81375b5c9ccc5ca3161eb487aa81469d40ded221/mapadroid/ocr/screenPath.py#L389-L396
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
site-packages/sqlalchemy/ext/declarative/api.py
python
declarative_base
(bind=None, metadata=None, mapper=None, cls=object, name='Base', constructor=_declarative_constructor, class_registry=None, metaclass=DeclarativeMeta)
return metaclass(name, bases, class_dict)
r"""Construct a base class for declarative class definitions. The new base class will be given a metaclass that produces appropriate :class:`~sqlalchemy.schema.Table` objects and makes the appropriate :func:`~sqlalchemy.orm.mapper` calls based on the information provided declaratively in the class and any subclasses of the class. :param bind: An optional :class:`~sqlalchemy.engine.Connectable`, will be assigned the ``bind`` attribute on the :class:`~sqlalchemy.schema.MetaData` instance. :param metadata: An optional :class:`~sqlalchemy.schema.MetaData` instance. All :class:`~sqlalchemy.schema.Table` objects implicitly declared by subclasses of the base will share this MetaData. A MetaData instance will be created if none is provided. The :class:`~sqlalchemy.schema.MetaData` instance will be available via the `metadata` attribute of the generated declarative base class. :param mapper: An optional callable, defaults to :func:`~sqlalchemy.orm.mapper`. Will be used to map subclasses to their Tables. :param cls: Defaults to :class:`object`. A type to use as the base for the generated declarative base class. May be a class or tuple of classes. :param name: Defaults to ``Base``. The display name for the generated class. Customizing this is not required, but can improve clarity in tracebacks and debugging. :param constructor: Defaults to :func:`~sqlalchemy.ext.declarative.base._declarative_constructor`, an __init__ implementation that assigns \**kwargs for declared fields and relationships to an instance. If ``None`` is supplied, no __init__ will be provided and construction will fall back to cls.__init__ by way of the normal Python semantics. :param class_registry: optional dictionary that will serve as the registry of class names-> mapped classes when string names are used to identify classes inside of :func:`.relationship` and others. Allows two or more declarative base classes to share the same registry of class names for simplified inter-base relationships. :param metaclass: Defaults to :class:`.DeclarativeMeta`. A metaclass or __metaclass__ compatible callable to use as the meta type of the generated declarative base class. .. versionchanged:: 1.1 if :paramref:`.declarative_base.cls` is a single class (rather than a tuple), the constructed base class will inherit its docstring. .. seealso:: :func:`.as_declarative`
r"""Construct a base class for declarative class definitions.
[ "r", "Construct", "a", "base", "class", "for", "declarative", "class", "definitions", "." ]
def declarative_base(bind=None, metadata=None, mapper=None, cls=object, name='Base', constructor=_declarative_constructor, class_registry=None, metaclass=DeclarativeMeta): r"""Construct a base class for declarative class definitions. The new base class will be given a metaclass that produces appropriate :class:`~sqlalchemy.schema.Table` objects and makes the appropriate :func:`~sqlalchemy.orm.mapper` calls based on the information provided declaratively in the class and any subclasses of the class. :param bind: An optional :class:`~sqlalchemy.engine.Connectable`, will be assigned the ``bind`` attribute on the :class:`~sqlalchemy.schema.MetaData` instance. :param metadata: An optional :class:`~sqlalchemy.schema.MetaData` instance. All :class:`~sqlalchemy.schema.Table` objects implicitly declared by subclasses of the base will share this MetaData. A MetaData instance will be created if none is provided. The :class:`~sqlalchemy.schema.MetaData` instance will be available via the `metadata` attribute of the generated declarative base class. :param mapper: An optional callable, defaults to :func:`~sqlalchemy.orm.mapper`. Will be used to map subclasses to their Tables. :param cls: Defaults to :class:`object`. A type to use as the base for the generated declarative base class. May be a class or tuple of classes. :param name: Defaults to ``Base``. The display name for the generated class. Customizing this is not required, but can improve clarity in tracebacks and debugging. :param constructor: Defaults to :func:`~sqlalchemy.ext.declarative.base._declarative_constructor`, an __init__ implementation that assigns \**kwargs for declared fields and relationships to an instance. If ``None`` is supplied, no __init__ will be provided and construction will fall back to cls.__init__ by way of the normal Python semantics. :param class_registry: optional dictionary that will serve as the registry of class names-> mapped classes when string names are used to identify classes inside of :func:`.relationship` and others. Allows two or more declarative base classes to share the same registry of class names for simplified inter-base relationships. :param metaclass: Defaults to :class:`.DeclarativeMeta`. A metaclass or __metaclass__ compatible callable to use as the meta type of the generated declarative base class. .. versionchanged:: 1.1 if :paramref:`.declarative_base.cls` is a single class (rather than a tuple), the constructed base class will inherit its docstring. .. seealso:: :func:`.as_declarative` """ lcl_metadata = metadata or MetaData() if bind: lcl_metadata.bind = bind if class_registry is None: class_registry = weakref.WeakValueDictionary() bases = not isinstance(cls, tuple) and (cls,) or cls class_dict = dict(_decl_class_registry=class_registry, metadata=lcl_metadata) if isinstance(cls, type): class_dict['__doc__'] = cls.__doc__ if constructor: class_dict['__init__'] = constructor if mapper: class_dict['__mapper_cls__'] = mapper return metaclass(name, bases, class_dict)
[ "def", "declarative_base", "(", "bind", "=", "None", ",", "metadata", "=", "None", ",", "mapper", "=", "None", ",", "cls", "=", "object", ",", "name", "=", "'Base'", ",", "constructor", "=", "_declarative_constructor", ",", "class_registry", "=", "None", "...
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/site-packages/sqlalchemy/ext/declarative/api.py#L249-L334
benedekrozemberczki/DANMF
6726fbfb9a1d4f8a19650ee89773e1c544329321
src/danmf.py
python
DANMF.update_U
(self, i)
Updating left hand factors. :param i: Layer index.
Updating left hand factors. :param i: Layer index.
[ "Updating", "left", "hand", "factors", ".", ":", "param", "i", ":", "Layer", "index", "." ]
def update_U(self, i): """ Updating left hand factors. :param i: Layer index. """ if i == 0: R = self.U_s[0].dot(self.Q_s[1].dot(self.VpVpT).dot(self.Q_s[1].T)) R = R+self.A_sq.dot(self.U_s[0].dot(self.Q_s[1].dot(self.Q_s[1].T))) Ru = 2*self.A.dot(self.V_s[self.p-1].T.dot(self.Q_s[1].T)) self.U_s[0] = (self.U_s[0]*Ru)/np.maximum(R, 10**-10) else: R = self.P.T.dot(self.P).dot(self.U_s[i]).dot(self.Q_s[i+1]).dot(self.VpVpT).dot(self.Q_s[i+1].T) R = R+self.A_sq.dot(self.P).T.dot(self.P).dot(self.U_s[i]).dot(self.Q_s[i+1]).dot(self.Q_s[i+1].T) Ru = 2*self.A.dot(self.P).T.dot(self.V_s[self.p-1].T).dot(self.Q_s[i+1].T) self.U_s[i] = (self.U_s[i]*Ru)/np.maximum(R, 10**-10)
[ "def", "update_U", "(", "self", ",", "i", ")", ":", "if", "i", "==", "0", ":", "R", "=", "self", ".", "U_s", "[", "0", "]", ".", "dot", "(", "self", ".", "Q_s", "[", "1", "]", ".", "dot", "(", "self", ".", "VpVpT", ")", ".", "dot", "(", ...
https://github.com/benedekrozemberczki/DANMF/blob/6726fbfb9a1d4f8a19650ee89773e1c544329321/src/danmf.py#L72-L86
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
lib-python/3.5.1/random.py
python
Random.normalvariate
(self, mu, sigma)
return mu + z*sigma
Normal distribution. mu is the mean, and sigma is the standard deviation.
Normal distribution.
[ "Normal", "distribution", "." ]
def normalvariate(self, mu, sigma): """Normal distribution. mu is the mean, and sigma is the standard deviation. """ # mu = mean, sigma = standard deviation # Uses Kinderman and Monahan method. Reference: Kinderman, # A.J. and Monahan, J.F., "Computer generation of random # variables using the ratio of uniform deviates", ACM Trans # Math Software, 3, (1977), pp257-260. random = self.random while 1: u1 = random() u2 = 1.0 - random() z = NV_MAGICCONST*(u1-0.5)/u2 zz = z*z/4.0 if zz <= -_log(u2): break return mu + z*sigma
[ "def", "normalvariate", "(", "self", ",", "mu", ",", "sigma", ")", ":", "# mu = mean, sigma = standard deviation", "# Uses Kinderman and Monahan method. Reference: Kinderman,", "# A.J. and Monahan, J.F., \"Computer generation of random", "# variables using the ratio of uniform deviates\", ...
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/random.py#L370-L391
timy90022/One-Shot-Object-Detection
26ca16238f2c4f17685ea57b646d58a2d7542fdb
lib/datasets/imagenet.py
python
imagenet._load_imagenet_annotation
(self, index)
return {'boxes' : boxes, 'gt_classes': gt_classes, 'gt_overlaps' : overlaps, 'flipped' : False}
Load image and bounding boxes info from txt files of imagenet.
Load image and bounding boxes info from txt files of imagenet.
[ "Load", "image", "and", "bounding", "boxes", "info", "from", "txt", "files", "of", "imagenet", "." ]
def _load_imagenet_annotation(self, index): """ Load image and bounding boxes info from txt files of imagenet. """ filename = os.path.join(self._data_path, 'Annotations', self._image_set, index + '.xml') # print 'Loading: {}'.format(filename) def get_data_from_tag(node, tag): return node.getElementsByTagName(tag)[0].childNodes[0].data with open(filename) as f: data = minidom.parseString(f.read()) objs = data.getElementsByTagName('object') num_objs = len(objs) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) # Load object bounding boxes into a data frame. for ix, obj in enumerate(objs): x1 = float(get_data_from_tag(obj, 'xmin')) y1 = float(get_data_from_tag(obj, 'ymin')) x2 = float(get_data_from_tag(obj, 'xmax')) y2 = float(get_data_from_tag(obj, 'ymax')) cls = self._wnid_to_ind[ str(get_data_from_tag(obj, "name")).lower().strip()] boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes' : boxes, 'gt_classes': gt_classes, 'gt_overlaps' : overlaps, 'flipped' : False}
[ "def", "_load_imagenet_annotation", "(", "self", ",", "index", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_data_path", ",", "'Annotations'", ",", "self", ".", "_image_set", ",", "index", "+", "'.xml'", ")", "# print 'Load...
https://github.com/timy90022/One-Shot-Object-Detection/blob/26ca16238f2c4f17685ea57b646d58a2d7542fdb/lib/datasets/imagenet.py#L172-L209
kbandla/ImmunityDebugger
2abc03fb15c8f3ed0914e1175c4d8933977c73e3
1.74/Servers/ssl_listener.py
python
ssl_listener.setupXMLRPCSocket
(self)
return
Listen for XML-RPC requests on a socket
Listen for XML-RPC requests on a socket
[ "Listen", "for", "XML", "-", "RPC", "requests", "on", "a", "socket" ]
def setupXMLRPCSocket(self): """ Listen for XML-RPC requests on a socket """ host="0.0.0.0" if self.XMLRPCport==0: return try: server = SimpleXMLRPCServer.SimpleXMLRPCServer((host, self.XMLRPCport),allow_none=True) except TypeError: print "2.4 Python did not allow allow_none=True!" server = SimpleXMLRPCServer.SimpleXMLRPCServer((host, self.XMLRPCport)) self.log("Set up XMLRPC Socket on %s port %d"%(host, self.XMLRPCport)) listener_object=listener_instance(self) server.register_instance(listener_object) #start new thread. lt=listener_thread(server, listener_object) lt.start() self.listener_thread=lt self.listener=listener_object return
[ "def", "setupXMLRPCSocket", "(", "self", ")", ":", "host", "=", "\"0.0.0.0\"", "if", "self", ".", "XMLRPCport", "==", "0", ":", "return", "try", ":", "server", "=", "SimpleXMLRPCServer", ".", "SimpleXMLRPCServer", "(", "(", "host", ",", "self", ".", "XMLRP...
https://github.com/kbandla/ImmunityDebugger/blob/2abc03fb15c8f3ed0914e1175c4d8933977c73e3/1.74/Servers/ssl_listener.py#L275-L295
igraph/python-igraph
e9f83e8af08f24ea025596e745917197d8b44d94
src/igraph/app/shell.py
python
ConsoleProgressBarMixin._status_handler
(cls, message)
Status message handler, called when C{igraph} sends a status message to be displayed. @param message: message provided by C{igraph}
Status message handler, called when C{igraph} sends a status message to be displayed.
[ "Status", "message", "handler", "called", "when", "C", "{", "igraph", "}", "sends", "a", "status", "message", "to", "be", "displayed", "." ]
def _status_handler(cls, message): """Status message handler, called when C{igraph} sends a status message to be displayed. @param message: message provided by C{igraph} """ cls.progress_bar.update_message(message)
[ "def", "_status_handler", "(", "cls", ",", "message", ")", ":", "cls", ".", "progress_bar", ".", "update_message", "(", "message", ")" ]
https://github.com/igraph/python-igraph/blob/e9f83e8af08f24ea025596e745917197d8b44d94/src/igraph/app/shell.py#L405-L411
NordicSemiconductor/pc-nrfutil
d08e742128f2a3dac522601bc6b9f9b2b63952df
nordicsemi/zigbee/prod_config.py
python
ProductionConfigTooLargeException.__init__
(self, length)
[]
def __init__(self, length): self.length = length
[ "def", "__init__", "(", "self", ",", "length", ")", ":", "self", ".", "length", "=", "length" ]
https://github.com/NordicSemiconductor/pc-nrfutil/blob/d08e742128f2a3dac522601bc6b9f9b2b63952df/nordicsemi/zigbee/prod_config.py#L49-L50
ipython/ipykernel
0ab288fe42f3155c7c7d9257c9be8cf093d175e0
ipykernel/inprocess/client.py
python
InProcessKernelClient.comm_info
(self, target_name=None)
return msg['header']['msg_id']
Request a dictionary of valid comms and their targets.
Request a dictionary of valid comms and their targets.
[ "Request", "a", "dictionary", "of", "valid", "comms", "and", "their", "targets", "." ]
def comm_info(self, target_name=None): """Request a dictionary of valid comms and their targets.""" if target_name is None: content = {} else: content = dict(target_name=target_name) msg = self.session.msg('comm_info_request', content) self._dispatch_to_kernel(msg) return msg['header']['msg_id']
[ "def", "comm_info", "(", "self", ",", "target_name", "=", "None", ")", ":", "if", "target_name", "is", "None", ":", "content", "=", "{", "}", "else", ":", "content", "=", "dict", "(", "target_name", "=", "target_name", ")", "msg", "=", "self", ".", "...
https://github.com/ipython/ipykernel/blob/0ab288fe42f3155c7c7d9257c9be8cf093d175e0/ipykernel/inprocess/client.py#L148-L156
weewx/weewx
cb594fce224560bd8696050fc5c7843c7839320e
bin/weewx/xtypes.py
python
ArchiveTable.get_series
(obs_type, timespan, db_manager, aggregate_type=None, aggregate_interval=None)
return (ValueTuple(start_vec, 'unix_epoch', 'group_time'), ValueTuple(stop_vec, 'unix_epoch', 'group_time'), ValueTuple(data_vec, unit, unit_group))
Get a series, possibly with aggregation, from the main archive database. The general strategy is that if aggregation is asked for, chop the series up into separate chunks, calculating the aggregate for each chunk. Then assemble the results. If no aggregation is called for, just return the data directly out of the database.
Get a series, possibly with aggregation, from the main archive database.
[ "Get", "a", "series", "possibly", "with", "aggregation", "from", "the", "main", "archive", "database", "." ]
def get_series(obs_type, timespan, db_manager, aggregate_type=None, aggregate_interval=None): """Get a series, possibly with aggregation, from the main archive database. The general strategy is that if aggregation is asked for, chop the series up into separate chunks, calculating the aggregate for each chunk. Then assemble the results. If no aggregation is called for, just return the data directly out of the database. """ startstamp, stopstamp = timespan start_vec = list() stop_vec = list() data_vec = list() if aggregate_type: # With aggregation unit, unit_group = None, None if aggregate_type == 'cumulative': do_aggregate = 'sum' total = 0 else: do_aggregate = aggregate_type for stamp in weeutil.weeutil.intervalgen(startstamp, stopstamp, aggregate_interval): # Get the aggregate as a ValueTuple agg_vt = get_aggregate(obs_type, stamp, do_aggregate, db_manager) if agg_vt[0] is None: continue if unit: # It's OK if the unit is unknown (=None). if agg_vt[1] is not None and (unit != agg_vt[1] or unit_group != agg_vt[2]): raise weewx.UnsupportedFeature("Cannot change unit groups " "within an aggregation.") else: unit, unit_group = agg_vt[1], agg_vt[2] start_vec.append(stamp.start) stop_vec.append(stamp.stop) if aggregate_type == 'cumulative': if agg_vt[0] is not None: total += agg_vt[0] data_vec.append(total) else: data_vec.append(agg_vt[0]) else: # No aggregation sql_str = "SELECT dateTime, %s, usUnits, `interval` FROM %s " \ "WHERE dateTime > ? AND dateTime <= ?" % (obs_type, db_manager.table_name) std_unit_system = None # Hit the database. It's possible the type is not in the database, so be prepared # to catch a NoColumnError: try: for record in db_manager.genSql(sql_str, (startstamp, stopstamp)): # Unpack the record timestamp, value, unit_system, interval = record if std_unit_system: if std_unit_system != unit_system: raise weewx.UnsupportedFeature("Unit type cannot change " "within an aggregation interval.") else: std_unit_system = unit_system start_vec.append(timestamp - interval * 60) stop_vec.append(timestamp) data_vec.append(value) except weedb.NoColumnError: # The sql type doesn't exist. Convert to an UnknownType error raise weewx.UnknownType(obs_type) unit, unit_group = weewx.units.getStandardUnitType(std_unit_system, obs_type, aggregate_type) return (ValueTuple(start_vec, 'unix_epoch', 'group_time'), ValueTuple(stop_vec, 'unix_epoch', 'group_time'), ValueTuple(data_vec, unit, unit_group))
[ "def", "get_series", "(", "obs_type", ",", "timespan", ",", "db_manager", ",", "aggregate_type", "=", "None", ",", "aggregate_interval", "=", "None", ")", ":", "startstamp", ",", "stopstamp", "=", "timespan", "start_vec", "=", "list", "(", ")", "stop_vec", "...
https://github.com/weewx/weewx/blob/cb594fce224560bd8696050fc5c7843c7839320e/bin/weewx/xtypes.py#L119-L196
Nuitka/Nuitka
39262276993757fa4e299f497654065600453fc9
nuitka/optimizations/TraceCollections.py
python
TraceCollectionBase.mergeBranches
(self, collection_yes, collection_no)
Merge two alternative branches into this trace. This is mostly for merging conditional branches, or other ways of having alternative control flow. This deals with up to two alternative branches to both change this collection.
Merge two alternative branches into this trace.
[ "Merge", "two", "alternative", "branches", "into", "this", "trace", "." ]
def mergeBranches(self, collection_yes, collection_no): """Merge two alternative branches into this trace. This is mostly for merging conditional branches, or other ways of having alternative control flow. This deals with up to two alternative branches to both change this collection. """ # Many branches due to inlining the actual merge and preparing it # pylint: disable=too-many-branches if collection_yes is None: if collection_no is not None: # Handle one branch case, we need to merge versions backwards as # they may make themselves obsolete. collection1 = self collection2 = collection_no else: # Refuse to do stupid work return elif collection_no is None: # Handle one branch case, we need to merge versions backwards as # they may make themselves obsolete. collection1 = self collection2 = collection_yes else: # Handle two branch case, they may or may not do the same things. collection1 = collection_yes collection2 = collection_no variable_versions = {} for variable, version in iterItems(collection1.variable_actives): variable_versions[variable] = version for variable, version in iterItems(collection2.variable_actives): if variable not in variable_versions: variable_versions[variable] = 0, version else: other = variable_versions[variable] if other != version: variable_versions[variable] = other, version else: variable_versions[variable] = other for variable in variable_versions: if variable not in collection2.variable_actives: variable_versions[variable] = variable_versions[variable], 0 self.variable_actives = {} for variable, versions in iterItems(variable_versions): if type(versions) is tuple: trace1 = self.getVariableTrace(variable, versions[0]) trace2 = self.getVariableTrace(variable, versions[1]) if trace1.isEscapeTrace() and trace1.previous is trace2: version = versions[0] elif trace2 is trace1.isEscapeTrace() and trace2.previous is trace1: version = versions[1] else: version = self.addVariableMergeMultipleTrace( variable=variable, traces=( trace1, trace2, ), ) else: version = versions self.markCurrentVariableTrace(variable, version)
[ "def", "mergeBranches", "(", "self", ",", "collection_yes", ",", "collection_no", ")", ":", "# Many branches due to inlining the actual merge and preparing it", "# pylint: disable=too-many-branches", "if", "collection_yes", "is", "None", ":", "if", "collection_no", "is", "not...
https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/optimizations/TraceCollections.py#L699-L771
misterch0c/shadowbroker
e3a069bea47a2c1009697941ac214adc6f90aa8d
windows/fuzzbunch/pyreadline/console/console.py
python
event.__init__
(self, console, input)
Initialize an event from the Windows input structure.
Initialize an event from the Windows input structure.
[ "Initialize", "an", "event", "from", "the", "Windows", "input", "structure", "." ]
def __init__(self, console, input): '''Initialize an event from the Windows input structure.''' self.type = '??' self.serial = console.next_serial() self.width = 0 self.height = 0 self.x = 0 self.y = 0 self.char = '' self.keycode = 0 self.keysym = '??' self.keyinfo = None # a tuple with (control, meta, shift, keycode) for dispatch self.width = None if input.EventType == KEY_EVENT: if input.Event.KeyEvent.bKeyDown: self.type = "KeyPress" else: self.type = "KeyRelease" self.char = input.Event.KeyEvent.uChar.AsciiChar self.keycode = input.Event.KeyEvent.wVirtualKeyCode self.state = input.Event.KeyEvent.dwControlKeyState self.keyinfo=make_KeyPress(self.char,self.state,self.keycode) elif input.EventType == MOUSE_EVENT: if input.Event.MouseEvent.dwEventFlags & MOUSE_MOVED: self.type = "Motion" else: self.type = "Button" self.x = input.Event.MouseEvent.dwMousePosition.X self.y = input.Event.MouseEvent.dwMousePosition.Y self.state = input.Event.MouseEvent.dwButtonState elif input.EventType == WINDOW_BUFFER_SIZE_EVENT: self.type = "Configure" self.width = input.Event.WindowBufferSizeEvent.dwSize.X self.height = input.Event.WindowBufferSizeEvent.dwSize.Y elif input.EventType == FOCUS_EVENT: if input.Event.FocusEvent.bSetFocus: self.type = "FocusIn" else: self.type = "FocusOut" elif input.EventType == MENU_EVENT: self.type = "Menu" self.state = input.Event.MenuEvent.dwCommandId
[ "def", "__init__", "(", "self", ",", "console", ",", "input", ")", ":", "self", ".", "type", "=", "'??'", "self", ".", "serial", "=", "console", ".", "next_serial", "(", ")", "self", ".", "width", "=", "0", "self", ".", "height", "=", "0", "self", ...
https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/fuzzbunch/pyreadline/console/console.py#L599-L642
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/team_log.py
python
EventDetails.get_member_set_profile_photo_details
(self)
return self._value
Only call this if :meth:`is_member_set_profile_photo_details` is true. :rtype: MemberSetProfilePhotoDetails
Only call this if :meth:`is_member_set_profile_photo_details` is true.
[ "Only", "call", "this", "if", ":", "meth", ":", "is_member_set_profile_photo_details", "is", "true", "." ]
def get_member_set_profile_photo_details(self): """ Only call this if :meth:`is_member_set_profile_photo_details` is true. :rtype: MemberSetProfilePhotoDetails """ if not self.is_member_set_profile_photo_details(): raise AttributeError("tag 'member_set_profile_photo_details' not set") return self._value
[ "def", "get_member_set_profile_photo_details", "(", "self", ")", ":", "if", "not", "self", ".", "is_member_set_profile_photo_details", "(", ")", ":", "raise", "AttributeError", "(", "\"tag 'member_set_profile_photo_details' not set\"", ")", "return", "self", ".", "_value"...
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team_log.py#L18649-L18657
bjmayor/hacker
e3ce2ad74839c2733b27dac6c0f495e0743e1866
venv/lib/python3.5/site-packages/pip/_vendor/distlib/_backport/tarfile.py
python
TarInfo.get_info
(self)
return info
Return the TarInfo's attributes as a dictionary.
Return the TarInfo's attributes as a dictionary.
[ "Return", "the", "TarInfo", "s", "attributes", "as", "a", "dictionary", "." ]
def get_info(self): """Return the TarInfo's attributes as a dictionary. """ info = { "name": self.name, "mode": self.mode & 0o7777, "uid": self.uid, "gid": self.gid, "size": self.size, "mtime": self.mtime, "chksum": self.chksum, "type": self.type, "linkname": self.linkname, "uname": self.uname, "gname": self.gname, "devmajor": self.devmajor, "devminor": self.devminor } if info["type"] == DIRTYPE and not info["name"].endswith("/"): info["name"] += "/" return info
[ "def", "get_info", "(", "self", ")", ":", "info", "=", "{", "\"name\"", ":", "self", ".", "name", ",", "\"mode\"", ":", "self", ".", "mode", "&", "0o7777", ",", "\"uid\"", ":", "self", ".", "uid", ",", "\"gid\"", ":", "self", ".", "gid", ",", "\"...
https://github.com/bjmayor/hacker/blob/e3ce2ad74839c2733b27dac6c0f495e0743e1866/venv/lib/python3.5/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L978-L1000
PyMVPA/PyMVPA
76c476b3de8264b0bb849bf226da5674d659564e
tools/bib2rst_ref.py
python
compare_bib_by_author
(a,b)
Sorting helper.
Sorting helper.
[ "Sorting", "helper", "." ]
def compare_bib_by_author(a,b): """Sorting helper.""" x = a[1][1] y = b[1][1] if 'author' in x: if 'author' in y: return cmp(join_author_list(x['author']), join_author_list(y['author'])) else: # only x has author return 1 else: if 'author' in y: return -1 else: # neither nor y have authors return 0
[ "def", "compare_bib_by_author", "(", "a", ",", "b", ")", ":", "x", "=", "a", "[", "1", "]", "[", "1", "]", "y", "=", "b", "[", "1", "]", "[", "1", "]", "if", "'author'", "in", "x", ":", "if", "'author'", "in", "y", ":", "return", "cmp", "("...
https://github.com/PyMVPA/PyMVPA/blob/76c476b3de8264b0bb849bf226da5674d659564e/tools/bib2rst_ref.py#L53-L69
wandb/client
3963364d8112b7dedb928fa423b6878ea1b467d9
wandb/sdk/internal/tb_watcher.py
python
TBDirWatcher._thread_body
(self)
Check for new events every second
Check for new events every second
[ "Check", "for", "new", "events", "every", "second" ]
def _thread_body(self) -> None: """Check for new events every second""" shutdown_time: "Optional[float]" = None while True: self._process_events() if self._shutdown.is_set(): now = time.time() if not shutdown_time: shutdown_time = now + SHUTDOWN_DELAY elif now > shutdown_time: break time.sleep(1)
[ "def", "_thread_body", "(", "self", ")", "->", "None", ":", "shutdown_time", ":", "\"Optional[float]\"", "=", "None", "while", "True", ":", "self", ".", "_process_events", "(", ")", "if", "self", ".", "_shutdown", ".", "is_set", "(", ")", ":", "now", "="...
https://github.com/wandb/client/blob/3963364d8112b7dedb928fa423b6878ea1b467d9/wandb/sdk/internal/tb_watcher.py#L280-L291
BillBillBillBill/Tickeys-linux
2df31b8665004c58a5d4ab05277f245267d96364
tickeys/kivy/uix/filechooser.py
python
FileChooserController.cancel
(self, *largs)
Cancel any background action started by filechooser, such as loading a new directory. .. versionadded:: 1.2.0
Cancel any background action started by filechooser, such as loading a new directory.
[ "Cancel", "any", "background", "action", "started", "by", "filechooser", "such", "as", "loading", "a", "new", "directory", "." ]
def cancel(self, *largs): '''Cancel any background action started by filechooser, such as loading a new directory. .. versionadded:: 1.2.0 ''' Clock.unschedule(self._create_files_entries) self._hide_progress() if len(self._previous_path) > 1: # if we cancel any action, the path will be set same as the # previous one, so we can safely cancel the update of the previous # path. self.path = self._previous_path[-2] Clock.unschedule(self._update_files)
[ "def", "cancel", "(", "self", ",", "*", "largs", ")", ":", "Clock", ".", "unschedule", "(", "self", ".", "_create_files_entries", ")", "self", ".", "_hide_progress", "(", ")", "if", "len", "(", "self", ".", "_previous_path", ")", ">", "1", ":", "# if w...
https://github.com/BillBillBillBill/Tickeys-linux/blob/2df31b8665004c58a5d4ab05277f245267d96364/tickeys/kivy/uix/filechooser.py#L679-L692
mitmproxy/mitmproxy
1abb8f69217910c8623bd1339da2502aed98ff0d
mitmproxy/tools/console/keymap.py
python
Keymap.add
( self, key: str, command: str, contexts: typing.Sequence[str], help="" )
Add a key to the key map.
Add a key to the key map.
[ "Add", "a", "key", "to", "the", "key", "map", "." ]
def add( self, key: str, command: str, contexts: typing.Sequence[str], help="" ) -> None: """ Add a key to the key map. """ self._check_contexts(contexts) for b in self.bindings: if b.key == key and b.command.strip() == command.strip(): b.contexts = sorted(list(set(b.contexts + contexts))) if help: b.help = help self.bind(b) break else: self.remove(key, contexts) b = Binding(key=key, command=command, contexts=contexts, help=help) self.bindings.append(b) self.bind(b) signals.keybindings_change.send(self)
[ "def", "add", "(", "self", ",", "key", ":", "str", ",", "command", ":", "str", ",", "contexts", ":", "typing", ".", "Sequence", "[", "str", "]", ",", "help", "=", "\"\"", ")", "->", "None", ":", "self", ".", "_check_contexts", "(", "contexts", ")",...
https://github.com/mitmproxy/mitmproxy/blob/1abb8f69217910c8623bd1339da2502aed98ff0d/mitmproxy/tools/console/keymap.py#L73-L97
trakt/Plex-Trakt-Scrobbler
aeb0bfbe62fad4b06c164f1b95581da7f35dce0b
Trakttv.bundle/Contents/Libraries/Linux/i386/ucs2/cryptography/hazmat/primitives/asymmetric/rsa.py
python
rsa_crt_dmq1
(private_exponent, q)
return private_exponent % (q - 1)
Compute the CRT private_exponent % (q - 1) value from the RSA private_exponent (d) and q.
Compute the CRT private_exponent % (q - 1) value from the RSA private_exponent (d) and q.
[ "Compute", "the", "CRT", "private_exponent", "%", "(", "q", "-", "1", ")", "value", "from", "the", "RSA", "private_exponent", "(", "d", ")", "and", "q", "." ]
def rsa_crt_dmq1(private_exponent, q): """ Compute the CRT private_exponent % (q - 1) value from the RSA private_exponent (d) and q. """ return private_exponent % (q - 1)
[ "def", "rsa_crt_dmq1", "(", "private_exponent", ",", "q", ")", ":", "return", "private_exponent", "%", "(", "q", "-", "1", ")" ]
https://github.com/trakt/Plex-Trakt-Scrobbler/blob/aeb0bfbe62fad4b06c164f1b95581da7f35dce0b/Trakttv.bundle/Contents/Libraries/Linux/i386/ucs2/cryptography/hazmat/primitives/asymmetric/rsa.py#L207-L212
google/rekall
55d1925f2df9759a989b35271b4fa48fc54a1c86
rekall-core/rekall/plugins/linux/heap_analysis.py
python
HeapAnalysis.get_all_allocated_chunks_for_arena
(self, arena)
Returns all allocated chunks for a given arena. This function is basically a wrapper around _allocated_chunks_for_main_arena and allocated_chunks_for_thread_arena.
Returns all allocated chunks for a given arena. This function is basically a wrapper around _allocated_chunks_for_main_arena and allocated_chunks_for_thread_arena.
[ "Returns", "all", "allocated", "chunks", "for", "a", "given", "arena", ".", "This", "function", "is", "basically", "a", "wrapper", "around", "_allocated_chunks_for_main_arena", "and", "allocated_chunks_for_thread_arena", "." ]
def get_all_allocated_chunks_for_arena(self, arena): """Returns all allocated chunks for a given arena. This function is basically a wrapper around _allocated_chunks_for_main_arena and allocated_chunks_for_thread_arena. """ if not arena: self.session.logging.error( "Error: allocated_chunks_for_arena called with an empty arena") if self.session.GetParameter("debug"): pdb.post_mortem() return if arena.freed_fast_chunks is None or arena.freed_chunks is None: self.session.logging.error( "Unexpected error: freed chunks seem to not be initialized.") if self.session.GetParameter("debug"): pdb.post_mortem() return if arena.is_main_arena: for i in self._allocated_chunks_for_main_arena(): yield i else: # not main_arena for chunk in self._allocated_chunks_for_thread_arena(arena): yield chunk
[ "def", "get_all_allocated_chunks_for_arena", "(", "self", ",", "arena", ")", ":", "if", "not", "arena", ":", "self", ".", "session", ".", "logging", ".", "error", "(", "\"Error: allocated_chunks_for_arena called with an empty arena\"", ")", "if", "self", ".", "sessi...
https://github.com/google/rekall/blob/55d1925f2df9759a989b35271b4fa48fc54a1c86/rekall-core/rekall/plugins/linux/heap_analysis.py#L965-L994
dipy/dipy
be956a529465b28085f8fc435a756947ddee1c89
dipy/core/geometry.py
python
vector_norm
(vec, axis=-1, keepdims=False)
return vec_norm
Return vector Euclidean (L2) norm See :term:`unit vector` and :term:`Euclidean norm` Parameters ------------- vec : array_like Vectors to norm. axis : int Axis over which to norm. By default norm over last axis. If `axis` is None, `vec` is flattened then normed. keepdims : bool If True, the output will have the same number of dimensions as `vec`, with shape 1 on `axis`. Returns --------- norm : array Euclidean norms of vectors. Examples -------- >>> import numpy as np >>> vec = [[8, 15, 0], [0, 36, 77]] >>> vector_norm(vec) array([ 17., 85.]) >>> vector_norm(vec, keepdims=True) array([[ 17.], [ 85.]]) >>> vector_norm(vec, axis=0) array([ 8., 39., 77.])
Return vector Euclidean (L2) norm
[ "Return", "vector", "Euclidean", "(", "L2", ")", "norm" ]
def vector_norm(vec, axis=-1, keepdims=False): """ Return vector Euclidean (L2) norm See :term:`unit vector` and :term:`Euclidean norm` Parameters ------------- vec : array_like Vectors to norm. axis : int Axis over which to norm. By default norm over last axis. If `axis` is None, `vec` is flattened then normed. keepdims : bool If True, the output will have the same number of dimensions as `vec`, with shape 1 on `axis`. Returns --------- norm : array Euclidean norms of vectors. Examples -------- >>> import numpy as np >>> vec = [[8, 15, 0], [0, 36, 77]] >>> vector_norm(vec) array([ 17., 85.]) >>> vector_norm(vec, keepdims=True) array([[ 17.], [ 85.]]) >>> vector_norm(vec, axis=0) array([ 8., 39., 77.]) """ vec = np.asarray(vec) vec_norm = np.sqrt((vec * vec).sum(axis)) if keepdims: if axis is None: shape = [1] * vec.ndim else: shape = list(vec.shape) shape[axis] = 1 vec_norm = vec_norm.reshape(shape) return vec_norm
[ "def", "vector_norm", "(", "vec", ",", "axis", "=", "-", "1", ",", "keepdims", "=", "False", ")", ":", "vec", "=", "np", ".", "asarray", "(", "vec", ")", "vec_norm", "=", "np", ".", "sqrt", "(", "(", "vec", "*", "vec", ")", ".", "sum", "(", "...
https://github.com/dipy/dipy/blob/be956a529465b28085f8fc435a756947ddee1c89/dipy/core/geometry.py#L177-L219
tooksoi/ScraXBRL
93d8ff3226c27f1592942462711954e0dbc267da
XMLExtract.py
python
ExtractFilingData.build_ins
(self)
Build instance reference with dates in descending order.
Build instance reference with dates in descending order.
[ "Build", "instance", "reference", "with", "dates", "in", "descending", "order", "." ]
def build_ins(self): """Build instance reference with dates in descending order.""" self.data['ins']['facts'] = OrderedDict() pfx_keys = self.data['ins_t']['facts'].keys() for pfx in pfx_keys: self.make_pfx(pfx, 'ins') name_keys = self.data['ins_t']['facts'][pfx].keys() for name in name_keys: self.data['ins']['facts'][pfx][name] = OrderedDict() ctx_keys = self.data['ins_t']['facts'][pfx][name].keys() unsorted_ctx = [] ctx_exmem = [] for ctx in ctx_keys: ctx_val = self.data['ins_t']['facts'][pfx][name][ctx] ctx_dec = self.data['ins_t']['facts'][pfx][name][ctx]['decimals'] ctx_conv_val = self.val_to_pre_conv(ctx_val['val'], ctx_dec) ctx_date = ctx_val['date'] if len(ctx_date) == 2: ctx_date_begin = ctx_date['startdate'] ctx_date_end = ctx_date['enddate'] unsorted_ctx.append(((ctx_date_begin, ctx_date_end), ctx_val['val'], ctx, ctx_dec, ctx_conv_val)) else: unsorted_ctx.append(((ctx_date), ctx_val['val'], ctx, ctx_dec, ctx_conv_val)) name_val = self.sort_by_date(unsorted_ctx) self.data['ins']['facts'][pfx][name] = name_val
[ "def", "build_ins", "(", "self", ")", ":", "self", ".", "data", "[", "'ins'", "]", "[", "'facts'", "]", "=", "OrderedDict", "(", ")", "pfx_keys", "=", "self", ".", "data", "[", "'ins_t'", "]", "[", "'facts'", "]", ".", "keys", "(", ")", "for", "p...
https://github.com/tooksoi/ScraXBRL/blob/93d8ff3226c27f1592942462711954e0dbc267da/XMLExtract.py#L754-L779
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/pipes.py
python
Template.open
(self, file, rw)
t.open(file, rw) returns a pipe or file object open for reading or writing; the file is the other end of the pipeline.
t.open(file, rw) returns a pipe or file object open for reading or writing; the file is the other end of the pipeline.
[ "t", ".", "open", "(", "file", "rw", ")", "returns", "a", "pipe", "or", "file", "object", "open", "for", "reading", "or", "writing", ";", "the", "file", "is", "the", "other", "end", "of", "the", "pipeline", "." ]
def open(self, file, rw): """t.open(file, rw) returns a pipe or file object open for reading or writing; the file is the other end of the pipeline.""" if rw == 'r': return self.open_r(file) if rw == 'w': return self.open_w(file) raise ValueError, \ 'Template.open: rw must be \'r\' or \'w\', not %r' % (rw,)
[ "def", "open", "(", "self", ",", "file", ",", "rw", ")", ":", "if", "rw", "==", "'r'", ":", "return", "self", ".", "open_r", "(", "file", ")", "if", "rw", "==", "'w'", ":", "return", "self", ".", "open_w", "(", "file", ")", "raise", "ValueError",...
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/pipes.py#L152-L160
quic/aimet
dae9bae9a77ca719aa7553fefde4768270fc3518
Docs/tf_code_examples/post_training_techniques_examples.py
python
get_layer_pairs_Resnet50_for_folding
(sess: tf.compat.v1.Session)
return layer_pairs
Helper function to pick example conv-batchnorm layer pairs for folding. :param sess: tensorflow session as tf.compat.v1.Session :return: pairs of conv and batchnorm layers for batch norm folding in Resnet50 model.
Helper function to pick example conv-batchnorm layer pairs for folding. :param sess: tensorflow session as tf.compat.v1.Session :return: pairs of conv and batchnorm layers for batch norm folding in Resnet50 model.
[ "Helper", "function", "to", "pick", "example", "conv", "-", "batchnorm", "layer", "pairs", "for", "folding", ".", ":", "param", "sess", ":", "tensorflow", "session", "as", "tf", ".", "compat", ".", "v1", ".", "Session", ":", "return", ":", "pairs", "of",...
def get_layer_pairs_Resnet50_for_folding(sess: tf.compat.v1.Session): """ Helper function to pick example conv-batchnorm layer pairs for folding. :param sess: tensorflow session as tf.compat.v1.Session :return: pairs of conv and batchnorm layers for batch norm folding in Resnet50 model. """ # pick conv and bn op pairs conv_op_1 = sess.graph.get_operation_by_name('res2a_branch2a/Conv2D') bn_op_1 = sess.graph.get_operation_by_name('bn2a_branch2a/cond/FusedBatchNorm_1') conv_op_2 = sess.graph.get_operation_by_name('res2a_branch2b/Conv2D') bn_op_2 = sess.graph.get_operation_by_name('bn2a_branch2b/cond/FusedBatchNorm_1') conv_op_3 = sess.graph.get_operation_by_name('res2a_branch2c/Conv2D') bn_op_3 = sess.graph.get_operation_by_name('bn2a_branch2c/cond/FusedBatchNorm_1') # make a layer pair list with potential the conv op and bn_op pair along with a flag # to indicate if given bn op can be folded upstream or downstream. # example of two pairs of conv and bn op shown below layer_pairs = [(conv_op_1, bn_op_1, True), (conv_op_2, bn_op_2, True), (conv_op_3, bn_op_3, True)] return layer_pairs
[ "def", "get_layer_pairs_Resnet50_for_folding", "(", "sess", ":", "tf", ".", "compat", ".", "v1", ".", "Session", ")", ":", "# pick conv and bn op pairs", "conv_op_1", "=", "sess", ".", "graph", ".", "get_operation_by_name", "(", "'res2a_branch2a/Conv2D'", ")", "bn_o...
https://github.com/quic/aimet/blob/dae9bae9a77ca719aa7553fefde4768270fc3518/Docs/tf_code_examples/post_training_techniques_examples.py#L107-L131
NVIDIA/NeMo
5b0c0b4dec12d87d3cd960846de4105309ce938e
nemo/collections/nlp/data/data_utils/data_preprocessing.py
python
DataProcessor._read_tsv
(cls, input_file, quotechar=None)
Reads a tab separated value file.
Reads a tab separated value file.
[ "Reads", "a", "tab", "separated", "value", "file", "." ]
def _read_tsv(cls, input_file, quotechar=None): """Reads a tab separated value file.""" with open(input_file, "r", encoding="utf-8-sig") as f: reader = csv.reader(f, delimiter="\t", quotechar=quotechar) lines = [] for line in reader: # if sys.version_info[0] == 2: # line = list(unicode(cell, 'utf-8') for cell in line) lines.append(line) return lines
[ "def", "_read_tsv", "(", "cls", ",", "input_file", ",", "quotechar", "=", "None", ")", ":", "with", "open", "(", "input_file", ",", "\"r\"", ",", "encoding", "=", "\"utf-8-sig\"", ")", "as", "f", ":", "reader", "=", "csv", ".", "reader", "(", "f", ",...
https://github.com/NVIDIA/NeMo/blob/5b0c0b4dec12d87d3cd960846de4105309ce938e/nemo/collections/nlp/data/data_utils/data_preprocessing.py#L86-L95
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v7/services/services/customer_asset_service/transports/grpc.py
python
CustomerAssetServiceGrpcTransport.__init__
( self, *, host: str = "googleads.googleapis.com", credentials: credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, )
Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for grpc channel. It is ignored if ``channel`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason.
Instantiate the transport.
[ "Instantiate", "the", "transport", "." ]
def __init__( self, *, host: str = "googleads.googleapis.com", credentials: credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, quota_project_id: Optional[str] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for grpc channel. It is ignored if ``channel`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ self._ssl_channel_credentials = ssl_channel_credentials if channel: # Sanity check: Ensure that channel and credentials are not both # provided. credentials = False # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None elif api_mtls_endpoint: warnings.warn( "api_mtls_endpoint and client_cert_source are deprecated", DeprecationWarning, ) host = ( api_mtls_endpoint if ":" in api_mtls_endpoint else api_mtls_endpoint + ":443" ) if credentials is None: credentials, _ = auth.default( scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id ) # Create SSL credentials with client_cert_source or application # default SSL credentials. if client_cert_source: cert, key = client_cert_source() ssl_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) else: ssl_credentials = SslCredentials().ssl_credentials # create a new channel. The provided one is ignored. self._grpc_channel = type(self).create_channel( host, credentials=credentials, credentials_file=credentials_file, ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) self._ssl_channel_credentials = ssl_credentials else: host = host if ":" in host else host + ":443" if credentials is None: credentials, _ = auth.default(scopes=self.AUTH_SCOPES) # create a new channel. The provided one is ignored. self._grpc_channel = type(self).create_channel( host, credentials=credentials, ssl_credentials=ssl_channel_credentials, scopes=self.AUTH_SCOPES, options=[ ("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1), ], ) self._stubs = {} # type: Dict[str, Callable] # Run the base constructor. super().__init__( host=host, credentials=credentials, client_info=client_info, )
[ "def", "__init__", "(", "self", ",", "*", ",", "host", ":", "str", "=", "\"googleads.googleapis.com\"", ",", "credentials", ":", "credentials", ".", "Credentials", "=", "None", ",", "credentials_file", ":", "str", "=", "None", ",", "scopes", ":", "Sequence",...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v7/services/services/customer_asset_service/transports/grpc.py#L45-L173
Jenyay/outwiker
50530cf7b3f71480bb075b2829bc0669773b835b
src/outwiker/utilites/textfile.py
python
readTextFile
(fname)
Read text content. Content must be in utf-8 encoding. The function return unicode object
Read text content. Content must be in utf-8 encoding. The function return unicode object
[ "Read", "text", "content", ".", "Content", "must", "be", "in", "utf", "-", "8", "encoding", ".", "The", "function", "return", "unicode", "object" ]
def readTextFile(fname): """ Read text content. Content must be in utf-8 encoding. The function return unicode object """ with open(fname, "r", encoding="utf-8", errors='surrogatepass') as fp: return fp.read()
[ "def", "readTextFile", "(", "fname", ")", ":", "with", "open", "(", "fname", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ",", "errors", "=", "'surrogatepass'", ")", "as", "fp", ":", "return", "fp", ".", "read", "(", ")" ]
https://github.com/Jenyay/outwiker/blob/50530cf7b3f71480bb075b2829bc0669773b835b/src/outwiker/utilites/textfile.py#L4-L10
openstack/cinder
23494a6d6c51451688191e1847a458f1d3cdcaa5
cinder/volume/drivers/dell_emc/powermax/rest.py
python
PowerMaxRest.is_snapvx_licensed
(self, array)
return snap_capability
Check if the snapVx feature is licensed and enabled. :param array: the array serial number :returns: True if licensed and enabled; False otherwise.
Check if the snapVx feature is licensed and enabled.
[ "Check", "if", "the", "snapVx", "feature", "is", "licensed", "and", "enabled", "." ]
def is_snapvx_licensed(self, array): """Check if the snapVx feature is licensed and enabled. :param array: the array serial number :returns: True if licensed and enabled; False otherwise. """ snap_capability = False capabilities = self.get_replication_capabilities(array) if capabilities: snap_capability = capabilities['snapVxCapable'] else: LOG.error("Cannot access replication capabilities " "for array %(array)s", {'array': array}) return snap_capability
[ "def", "is_snapvx_licensed", "(", "self", ",", "array", ")", ":", "snap_capability", "=", "False", "capabilities", "=", "self", ".", "get_replication_capabilities", "(", "array", ")", "if", "capabilities", ":", "snap_capability", "=", "capabilities", "[", "'snapVx...
https://github.com/openstack/cinder/blob/23494a6d6c51451688191e1847a458f1d3cdcaa5/cinder/volume/drivers/dell_emc/powermax/rest.py#L2058-L2071
openstack/cinder
23494a6d6c51451688191e1847a458f1d3cdcaa5
cinder/volume/drivers/hpe/hpe_3par_base.py
python
HPE3PARDriverBase.check_for_setup_error
(self)
Setup errors are already checked for in do_setup so return pass.
Setup errors are already checked for in do_setup so return pass.
[ "Setup", "errors", "are", "already", "checked", "for", "in", "do_setup", "so", "return", "pass", "." ]
def check_for_setup_error(self): """Setup errors are already checked for in do_setup so return pass.""" pass
[ "def", "check_for_setup_error", "(", "self", ")", ":", "pass" ]
https://github.com/openstack/cinder/blob/23494a6d6c51451688191e1847a458f1d3cdcaa5/cinder/volume/drivers/hpe/hpe_3par_base.py#L145-L147
ShuLiu1993/PANet
f055f716a21896dab8907c46c12e216323baefdb
lib/datasets/task_evaluation.py
python
evaluate_boxes
(dataset, all_boxes, output_dir, use_matlab=False)
return OrderedDict([(dataset.name, box_results)])
Evaluate bounding box detection.
Evaluate bounding box detection.
[ "Evaluate", "bounding", "box", "detection", "." ]
def evaluate_boxes(dataset, all_boxes, output_dir, use_matlab=False): """Evaluate bounding box detection.""" logger.info('Evaluating detections') not_comp = not cfg.TEST.COMPETITION_MODE if _use_json_dataset_evaluator(dataset): coco_eval = json_dataset_evaluator.evaluate_boxes( dataset, all_boxes, output_dir, use_salt=not_comp, cleanup=not_comp ) box_results = _coco_eval_to_box_results(coco_eval) elif _use_cityscapes_evaluator(dataset): logger.warn('Cityscapes bbox evaluated using COCO metrics/conversions') coco_eval = json_dataset_evaluator.evaluate_boxes( dataset, all_boxes, output_dir, use_salt=not_comp, cleanup=not_comp ) box_results = _coco_eval_to_box_results(coco_eval) elif _use_voc_evaluator(dataset): # For VOC, always use salt and always cleanup because results are # written to the shared VOCdevkit results directory voc_eval = voc_dataset_evaluator.evaluate_boxes( dataset, all_boxes, output_dir, use_matlab=use_matlab ) box_results = _voc_eval_to_box_results(voc_eval) else: raise NotImplementedError( 'No evaluator for dataset: {}'.format(dataset.name) ) return OrderedDict([(dataset.name, box_results)])
[ "def", "evaluate_boxes", "(", "dataset", ",", "all_boxes", ",", "output_dir", ",", "use_matlab", "=", "False", ")", ":", "logger", ".", "info", "(", "'Evaluating detections'", ")", "not_comp", "=", "not", "cfg", ".", "TEST", ".", "COMPETITION_MODE", "if", "_...
https://github.com/ShuLiu1993/PANet/blob/f055f716a21896dab8907c46c12e216323baefdb/lib/datasets/task_evaluation.py#L73-L99
mu-editor/mu
5a5d7723405db588f67718a63a0ec0ecabebae33
mu/settings.py
python
SettingsBase._expanded_value
(value)
return os.path.expandvars(value) if isinstance(value, str) else value
Return a value with env vars expanded
Return a value with env vars expanded
[ "Return", "a", "value", "with", "env", "vars", "expanded" ]
def _expanded_value(value): """Return a value with env vars expanded""" return os.path.expandvars(value) if isinstance(value, str) else value
[ "def", "_expanded_value", "(", "value", ")", ":", "return", "os", ".", "path", ".", "expandvars", "(", "value", ")", "if", "isinstance", "(", "value", ",", "str", ")", "else", "value" ]
https://github.com/mu-editor/mu/blob/5a5d7723405db588f67718a63a0ec0ecabebae33/mu/settings.py#L85-L87
matrix-org/synapse
8e57584a5859a9002759963eb546d523d2498a01
synapse/handlers/presence.py
python
handle_update
( prev_state: UserPresenceState, new_state: UserPresenceState, is_mine: bool, wheel_timer: WheelTimer, now: int, )
return new_state, persist_and_notify, federation_ping
Given a presence update: 1. Add any appropriate timers. 2. Check if we should notify anyone. Args: prev_state new_state is_mine: Whether the user is ours wheel_timer now: Time now in ms Returns: 3-tuple: `(new_state, persist_and_notify, federation_ping)` where: - new_state: is the state to actually persist - persist_and_notify: whether to persist and notify people - federation_ping: whether we should send a ping over federation
Given a presence update: 1. Add any appropriate timers. 2. Check if we should notify anyone.
[ "Given", "a", "presence", "update", ":", "1", ".", "Add", "any", "appropriate", "timers", ".", "2", ".", "Check", "if", "we", "should", "notify", "anyone", "." ]
def handle_update( prev_state: UserPresenceState, new_state: UserPresenceState, is_mine: bool, wheel_timer: WheelTimer, now: int, ) -> Tuple[UserPresenceState, bool, bool]: """Given a presence update: 1. Add any appropriate timers. 2. Check if we should notify anyone. Args: prev_state new_state is_mine: Whether the user is ours wheel_timer now: Time now in ms Returns: 3-tuple: `(new_state, persist_and_notify, federation_ping)` where: - new_state: is the state to actually persist - persist_and_notify: whether to persist and notify people - federation_ping: whether we should send a ping over federation """ user_id = new_state.user_id persist_and_notify = False federation_ping = False # If the users are ours then we want to set up a bunch of timers # to time things out. if is_mine: if new_state.state == PresenceState.ONLINE: # Idle timer wheel_timer.insert( now=now, obj=user_id, then=new_state.last_active_ts + IDLE_TIMER ) active = now - new_state.last_active_ts < LAST_ACTIVE_GRANULARITY new_state = new_state.copy_and_replace(currently_active=active) if active: wheel_timer.insert( now=now, obj=user_id, then=new_state.last_active_ts + LAST_ACTIVE_GRANULARITY, ) if new_state.state != PresenceState.OFFLINE: # User has stopped syncing wheel_timer.insert( now=now, obj=user_id, then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT, ) last_federate = new_state.last_federation_update_ts if now - last_federate > FEDERATION_PING_INTERVAL: # Been a while since we've poked remote servers new_state = new_state.copy_and_replace(last_federation_update_ts=now) federation_ping = True else: wheel_timer.insert( now=now, obj=user_id, then=new_state.last_federation_update_ts + FEDERATION_TIMEOUT, ) # Check whether the change was something worth notifying about if should_notify(prev_state, new_state): new_state = new_state.copy_and_replace(last_federation_update_ts=now) persist_and_notify = True return new_state, persist_and_notify, federation_ping
[ "def", "handle_update", "(", "prev_state", ":", "UserPresenceState", ",", "new_state", ":", "UserPresenceState", ",", "is_mine", ":", "bool", ",", "wheel_timer", ":", "WheelTimer", ",", "now", ":", "int", ",", ")", "->", "Tuple", "[", "UserPresenceState", ",",...
https://github.com/matrix-org/synapse/blob/8e57584a5859a9002759963eb546d523d2498a01/synapse/handlers/presence.py#L1901-L1975
mysql/mysql-connector-python
c5460bcbb0dff8e4e48bf4af7a971c89bf486d85
lib/mysqlx/connection.py
python
Connection._set_tls_capabilities
(self, caps)
Set the TLS capabilities. Args: caps (dict): Dictionary with the server capabilities. Raises: :class:`mysqlx.OperationalError`: If SSL is not enabled at the server. :class:`mysqlx.RuntimeError`: If support for SSL is not available in Python. .. versionadded:: 8.0.21
Set the TLS capabilities.
[ "Set", "the", "TLS", "capabilities", "." ]
def _set_tls_capabilities(self, caps): """Set the TLS capabilities. Args: caps (dict): Dictionary with the server capabilities. Raises: :class:`mysqlx.OperationalError`: If SSL is not enabled at the server. :class:`mysqlx.RuntimeError`: If support for SSL is not available in Python. .. versionadded:: 8.0.21 """ if self.settings.get("ssl-mode") == SSLMode.DISABLED: return if self.stream.is_socket(): if self.settings.get("ssl-mode"): _LOGGER.warning("SSL not required when using Unix socket.") return if "tls" not in caps: self.close_connection() raise OperationalError("SSL not enabled at server") is_ol7 = False if platform.system() == "Linux": distname, version, _ = linux_distribution() try: is_ol7 = "Oracle Linux" in distname and \ version.split(".")[0] == "7" except IndexError: is_ol7 = False if sys.version_info < (2, 7, 9) and not is_ol7: self.close_connection() raise RuntimeError("The support for SSL is not available for " "this Python version") self.protocol.set_capabilities(tls=True) self.stream.set_ssl(self.settings.get("tls-versions", None), self.settings.get("ssl-mode", SSLMode.REQUIRED), self.settings.get("ssl-ca"), self.settings.get("ssl-crl"), self.settings.get("ssl-cert"), self.settings.get("ssl-key"), self.settings.get("tls-ciphersuites")) if "attributes" in self.settings: conn_attrs = self.settings["attributes"] self.protocol.set_capabilities(session_connect_attrs=conn_attrs)
[ "def", "_set_tls_capabilities", "(", "self", ",", "caps", ")", ":", "if", "self", ".", "settings", ".", "get", "(", "\"ssl-mode\"", ")", "==", "SSLMode", ".", "DISABLED", ":", "return", "if", "self", ".", "stream", ".", "is_socket", "(", ")", ":", "if"...
https://github.com/mysql/mysql-connector-python/blob/c5460bcbb0dff8e4e48bf4af7a971c89bf486d85/lib/mysqlx/connection.py#L742-L792
pointhi/kicad-footprint-generator
76fedd51e8680e6cd3b729dcbd6f1a56af53b12c
KicadModTree/util/geometric_util.py
python
geometricCircle.rotate
(self, angle, origin=(0, 0), use_degrees=True)
return self
r""" Rotate around given origin :params: * *angle* (``float``) rotation angle * *origin* (``Vector2D``) origin point for the rotation. default: (0, 0) * *use_degrees* (``boolean``) rotation angle is given in degrees. default:True
r""" Rotate around given origin
[ "r", "Rotate", "around", "given", "origin" ]
def rotate(self, angle, origin=(0, 0), use_degrees=True): r""" Rotate around given origin :params: * *angle* (``float``) rotation angle * *origin* (``Vector2D``) origin point for the rotation. default: (0, 0) * *use_degrees* (``boolean``) rotation angle is given in degrees. default:True """ self.center_pos.rotate(angle=angle, origin=origin, use_degrees=use_degrees) return self
[ "def", "rotate", "(", "self", ",", "angle", ",", "origin", "=", "(", "0", ",", "0", ")", ",", "use_degrees", "=", "True", ")", ":", "self", ".", "center_pos", ".", "rotate", "(", "angle", "=", "angle", ",", "origin", "=", "origin", ",", "use_degree...
https://github.com/pointhi/kicad-footprint-generator/blob/76fedd51e8680e6cd3b729dcbd6f1a56af53b12c/KicadModTree/util/geometric_util.py#L176-L189
qLab/qLib
a34f45d22fe7315991bb822824c035fbc9a2a5e8
scripts/python/qlibutils.py
python
paste_existing_image
(kwargs)
.
.
[ "." ]
def paste_existing_image(kwargs): """. """ images = sorted(get_existing_images(kwargs)) pane = kwargs.get('editor', None) sel = hou.ui.selectFromList(images, exclusive=True, title="Paste Existing Image", message="Select Image to Paste") if len(sel)>0 and pane: image_name = images[sel[0]] pwd = pane.pwd() add_image_to_netview(embedded_img_prefix(image_name), pane, pwd) pane.flashMessage("COP2_still", "Pasted existing image: %s (Ctrl+I to edit)" % image_name, 8)
[ "def", "paste_existing_image", "(", "kwargs", ")", ":", "images", "=", "sorted", "(", "get_existing_images", "(", "kwargs", ")", ")", "pane", "=", "kwargs", ".", "get", "(", "'editor'", ",", "None", ")", "sel", "=", "hou", ".", "ui", ".", "selectFromList...
https://github.com/qLab/qLib/blob/a34f45d22fe7315991bb822824c035fbc9a2a5e8/scripts/python/qlibutils.py#L882-L894
Zardinality/TF_Deformable_Net
00c86380fd2725ebe7ae22f41d460ffc0bca378d
lib/roi_data_layer/minibatch.py
python
_get_bbox_regression_labels
(bbox_target_data, num_classes)
return bbox_targets, bbox_inside_weights
Bounding-box regression targets are stored in a compact form in the roidb. This function expands those targets into the 4-of-4*K representation used by the network (i.e. only one class has non-zero targets). The loss weights are similarly expanded. Returns: bbox_target_data (ndarray): N x 4K blob of regression targets bbox_inside_weights (ndarray): N x 4K blob of loss weights
Bounding-box regression targets are stored in a compact form in the roidb.
[ "Bounding", "-", "box", "regression", "targets", "are", "stored", "in", "a", "compact", "form", "in", "the", "roidb", "." ]
def _get_bbox_regression_labels(bbox_target_data, num_classes): """Bounding-box regression targets are stored in a compact form in the roidb. This function expands those targets into the 4-of-4*K representation used by the network (i.e. only one class has non-zero targets). The loss weights are similarly expanded. Returns: bbox_target_data (ndarray): N x 4K blob of regression targets bbox_inside_weights (ndarray): N x 4K blob of loss weights """ clss = bbox_target_data[:, 0] bbox_targets = np.zeros((clss.size, 4 * num_classes), dtype=np.float32) bbox_inside_weights = np.zeros(bbox_targets.shape, dtype=np.float32) inds = np.where(clss > 0)[0] for ind in inds: cls = clss[ind] start = 4 * cls end = start + 4 bbox_targets[ind, start:end] = bbox_target_data[ind, 1:] bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS return bbox_targets, bbox_inside_weights
[ "def", "_get_bbox_regression_labels", "(", "bbox_target_data", ",", "num_classes", ")", ":", "clss", "=", "bbox_target_data", "[", ":", ",", "0", "]", "bbox_targets", "=", "np", ".", "zeros", "(", "(", "clss", ".", "size", ",", "4", "*", "num_classes", ")"...
https://github.com/Zardinality/TF_Deformable_Net/blob/00c86380fd2725ebe7ae22f41d460ffc0bca378d/lib/roi_data_layer/minibatch.py#L168-L190
microsoft/azure-devops-python-api
451cade4c475482792cbe9e522c1fee32393139e
azure-devops/azure/devops/v6_0/git/git_client_base.py
python
GitClientBase.create_attachment
(self, upload_stream, file_name, repository_id, pull_request_id, project=None, **kwargs)
return self._deserialize('Attachment', response)
CreateAttachment. [Preview API] Attach a new file to a pull request. :param object upload_stream: Stream to upload :param str file_name: The name of the file. :param str repository_id: The repository ID of the pull request’s target branch. :param int pull_request_id: ID of the pull request. :param str project: Project ID or project name :rtype: :class:`<Attachment> <azure.devops.v6_0.git.models.Attachment>`
CreateAttachment. [Preview API] Attach a new file to a pull request. :param object upload_stream: Stream to upload :param str file_name: The name of the file. :param str repository_id: The repository ID of the pull request’s target branch. :param int pull_request_id: ID of the pull request. :param str project: Project ID or project name :rtype: :class:`<Attachment> <azure.devops.v6_0.git.models.Attachment>`
[ "CreateAttachment", ".", "[", "Preview", "API", "]", "Attach", "a", "new", "file", "to", "a", "pull", "request", ".", ":", "param", "object", "upload_stream", ":", "Stream", "to", "upload", ":", "param", "str", "file_name", ":", "The", "name", "of", "the...
def create_attachment(self, upload_stream, file_name, repository_id, pull_request_id, project=None, **kwargs): """CreateAttachment. [Preview API] Attach a new file to a pull request. :param object upload_stream: Stream to upload :param str file_name: The name of the file. :param str repository_id: The repository ID of the pull request’s target branch. :param int pull_request_id: ID of the pull request. :param str project: Project ID or project name :rtype: :class:`<Attachment> <azure.devops.v6_0.git.models.Attachment>` """ route_values = {} if project is not None: route_values['project'] = self._serialize.url('project', project, 'str') if file_name is not None: route_values['fileName'] = self._serialize.url('file_name', file_name, 'str') if repository_id is not None: route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str') if pull_request_id is not None: route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int') if "callback" in kwargs: callback = kwargs["callback"] else: callback = None content = self._client.stream_upload(upload_stream, callback=callback) response = self._send(http_method='POST', location_id='965d9361-878b-413b-a494-45d5b5fd8ab7', version='6.0-preview.1', route_values=route_values, content=content, media_type='application/octet-stream') return self._deserialize('Attachment', response)
[ "def", "create_attachment", "(", "self", ",", "upload_stream", ",", "file_name", ",", "repository_id", ",", "pull_request_id", ",", "project", "=", "None", ",", "*", "*", "kwargs", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "Non...
https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/v6_0/git/git_client_base.py#L1200-L1230
Azure/azure-linux-extensions
a42ef718c746abab2b3c6a21da87b29e76364558
DSC/azure/__init__.py
python
_parse_enum_results_list
(response, return_type, resp_type, item_type)
return return_obj
resp_body is the XML we received resp_type is a string, such as Containers, return_type is the type we're constructing, such as ContainerEnumResults item_type is the type object of the item to be created, such as Container This function then returns a ContainerEnumResults object with the containers member populated with the results.
resp_body is the XML we received resp_type is a string, such as Containers, return_type is the type we're constructing, such as ContainerEnumResults item_type is the type object of the item to be created, such as Container
[ "resp_body", "is", "the", "XML", "we", "received", "resp_type", "is", "a", "string", "such", "as", "Containers", "return_type", "is", "the", "type", "we", "re", "constructing", "such", "as", "ContainerEnumResults", "item_type", "is", "the", "type", "object", "...
def _parse_enum_results_list(response, return_type, resp_type, item_type): """resp_body is the XML we received resp_type is a string, such as Containers, return_type is the type we're constructing, such as ContainerEnumResults item_type is the type object of the item to be created, such as Container This function then returns a ContainerEnumResults object with the containers member populated with the results. """ # parsing something like: # <EnumerationResults ... > # <Queues> # <Queue> # <Something /> # <SomethingElse /> # </Queue> # </Queues> # </EnumerationResults> respbody = response.body return_obj = return_type() doc = minidom.parseString(respbody) items = [] for enum_results in _get_child_nodes(doc, 'EnumerationResults'): # path is something like Queues, Queue for child in _get_children_from_path(enum_results, resp_type, resp_type[:-1]): items.append(_fill_instance_element(child, item_type)) for name, value in vars(return_obj).items(): # queues, Queues, this is the list its self which we populated # above if name == resp_type.lower(): # the list its self. continue value = _fill_data_minidom(enum_results, name, value) if value is not None: setattr(return_obj, name, value) setattr(return_obj, resp_type.lower(), items) return return_obj
[ "def", "_parse_enum_results_list", "(", "response", ",", "return_type", ",", "resp_type", ",", "item_type", ")", ":", "# parsing something like:", "# <EnumerationResults ... >", "# <Queues>", "# <Queue>", "# <Something />", "# <SomethingElse />", "# ...
https://github.com/Azure/azure-linux-extensions/blob/a42ef718c746abab2b3c6a21da87b29e76364558/DSC/azure/__init__.py#L641-L683
DIYer22/boxx
d271bc375a33e01e616a0f74ce028e6d77d1820e
boxx/tool/toolStructObj.py
python
withattr.__init__
(self, obj, attrs_or_key, value=None)
[]
def __init__(self, obj, attrs_or_key, value=None): self.obj = obj if isinstance(attrs_or_key, str): attrs = {attrs_or_key: value} else: attrs = attrs_or_key d = obj sett = ( (lambda d, k, v: d.__setitem__(k, v)) if isinstance(obj, dict) else setattr ) get = (lambda d, k: d[k]) if isinstance(obj, dict) else getattr pop = (lambda d, k: d.pop(k)) if isinstance(obj, dict) else delattr has = (lambda d, k: k in d) if isinstance(obj, dict) else hasattr def enter_func(): self.old = {} for k, v in attrs.items(): if has(d, k): self.old[k] = get(d, k) sett(d, k, v) return d def exit_func(): for k in attrs.keys(): if k in self.old: sett(d, k, self.old[k]) else: pop(d, k) self.enter_func = enter_func self.exit_func = exit_func
[ "def", "__init__", "(", "self", ",", "obj", ",", "attrs_or_key", ",", "value", "=", "None", ")", ":", "self", ".", "obj", "=", "obj", "if", "isinstance", "(", "attrs_or_key", ",", "str", ")", ":", "attrs", "=", "{", "attrs_or_key", ":", "value", "}",...
https://github.com/DIYer22/boxx/blob/d271bc375a33e01e616a0f74ce028e6d77d1820e/boxx/tool/toolStructObj.py#L455-L488
aceisace/Inkycal
552744bc5d80769c1015d48fd8b13201683ee679
inkycal/display/drivers/epdconfig.py
python
RaspberryPi.digital_write
(self, pin, value)
[]
def digital_write(self, pin, value): self.GPIO.output(pin, value)
[ "def", "digital_write", "(", "self", ",", "pin", ",", "value", ")", ":", "self", ".", "GPIO", ".", "output", "(", "pin", ",", "value", ")" ]
https://github.com/aceisace/Inkycal/blob/552744bc5d80769c1015d48fd8b13201683ee679/inkycal/display/drivers/epdconfig.py#L54-L55
dingjiansw101/AerialDetection
fbb7726bc0c6898fc00e50a418a3f5e0838b30d4
mmdet/core/bbox/transforms_rbbox.py
python
hbb2obb_v2
(boxes)
return dbboxes
fix a bug :param boxes: shape (n, 4) (xmin, ymin, xmax, ymax) :return: dbboxes: shape (n, 5) (x_ctr, y_ctr, w, h, angle)
fix a bug :param boxes: shape (n, 4) (xmin, ymin, xmax, ymax) :return: dbboxes: shape (n, 5) (x_ctr, y_ctr, w, h, angle)
[ "fix", "a", "bug", ":", "param", "boxes", ":", "shape", "(", "n", "4", ")", "(", "xmin", "ymin", "xmax", "ymax", ")", ":", "return", ":", "dbboxes", ":", "shape", "(", "n", "5", ")", "(", "x_ctr", "y_ctr", "w", "h", "angle", ")" ]
def hbb2obb_v2(boxes): """ fix a bug :param boxes: shape (n, 4) (xmin, ymin, xmax, ymax) :return: dbboxes: shape (n, 5) (x_ctr, y_ctr, w, h, angle) """ num_boxes = boxes.size(0) ex_heights = boxes[..., 2] - boxes[..., 0] + 1.0 ex_widths = boxes[..., 3] - boxes[..., 1] + 1.0 ex_ctr_x = boxes[..., 0] + 0.5 * (ex_heights - 1.0) ex_ctr_y = boxes[..., 1] + 0.5 * (ex_widths - 1.0) c_bboxes = torch.cat((ex_ctr_x.unsqueeze(1), ex_ctr_y.unsqueeze(1), ex_widths.unsqueeze(1), ex_heights.unsqueeze(1)), 1) initial_angles = -c_bboxes.new_ones((num_boxes, 1)) * np.pi / 2 # initial_angles = -torch.ones((num_boxes, 1)) * np.pi/2 dbboxes = torch.cat((c_bboxes, initial_angles), 1) return dbboxes
[ "def", "hbb2obb_v2", "(", "boxes", ")", ":", "num_boxes", "=", "boxes", ".", "size", "(", "0", ")", "ex_heights", "=", "boxes", "[", "...", ",", "2", "]", "-", "boxes", "[", "...", ",", "0", "]", "+", "1.0", "ex_widths", "=", "boxes", "[", "...",...
https://github.com/dingjiansw101/AerialDetection/blob/fbb7726bc0c6898fc00e50a418a3f5e0838b30d4/mmdet/core/bbox/transforms_rbbox.py#L734-L750
radio-t/rt-bot
6ee5f955e908b1de5d0f996f36591ac7409b4bf4
rtnumber-bot/main.py
python
hours_word
(hours)
return word
[]
def hours_word(hours): word = 'часов' if 11 <= hours <= 14: pass elif hours % 10 == 1: word = 'час' elif hours % 10 in [2, 3, 4]: word = 'часа' return word
[ "def", "hours_word", "(", "hours", ")", ":", "word", "=", "'часов'", "if", "11", "<=", "hours", "<=", "14", ":", "pass", "elif", "hours", "%", "10", "==", "1", ":", "word", "=", "'час'", "elif", "hours", "%", "10", "in", "[", "2", ",", "3", ","...
https://github.com/radio-t/rt-bot/blob/6ee5f955e908b1de5d0f996f36591ac7409b4bf4/rtnumber-bot/main.py#L44-L52
Qiskit/qiskit-terra
b66030e3b9192efdd3eb95cf25c6545fe0a13da4
qiskit/quantum_info/operators/symplectic/pauli_list.py
python
PauliList._noncommutation_graph
(self)
return list(zip(*np.where(np.triu(np.logical_not(mat3), k=1))))
Create an edge list representing the qubit-wise non-commutation graph. An edge (i, j) is present if i and j are not commutable. Returns: List[Tuple(int,int)]: A list of pairs of indices of the PauliList that are not commutable.
Create an edge list representing the qubit-wise non-commutation graph.
[ "Create", "an", "edge", "list", "representing", "the", "qubit", "-", "wise", "non", "-", "commutation", "graph", "." ]
def _noncommutation_graph(self): """Create an edge list representing the qubit-wise non-commutation graph. An edge (i, j) is present if i and j are not commutable. Returns: List[Tuple(int,int)]: A list of pairs of indices of the PauliList that are not commutable. """ # convert a Pauli operator into int vector where {I: 0, X: 2, Y: 3, Z: 1} mat1 = np.array( [op.z + 2 * op.x for op in self], dtype=np.int8, ) mat2 = mat1[:, None] # mat3[i, j] is True if i and j are qubit-wise commutable mat3 = (((mat1 * mat2) * (mat1 - mat2)) == 0).all(axis=2) # convert into list where tuple elements are qubit-wise non-commuting operators return list(zip(*np.where(np.triu(np.logical_not(mat3), k=1))))
[ "def", "_noncommutation_graph", "(", "self", ")", ":", "# convert a Pauli operator into int vector where {I: 0, X: 2, Y: 3, Z: 1}", "mat1", "=", "np", ".", "array", "(", "[", "op", ".", "z", "+", "2", "*", "op", ".", "x", "for", "op", "in", "self", "]", ",", ...
https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/quantum_info/operators/symplectic/pauli_list.py#L1069-L1086
fonttools/fonttools
892322aaff6a89bea5927379ec06bc0da3dfb7df
Lib/fontTools/subset/__init__.py
python
Subsetter._prune_post_subset
(self, font)
[]
def _prune_post_subset(self, font): for tag in font.keys(): if tag == 'GlyphOrder': continue if tag == 'OS/2' and self.options.prune_unicode_ranges: old_uniranges = font[tag].getUnicodeRanges() new_uniranges = font[tag].recalcUnicodeRanges(font, pruneOnly=True) if old_uniranges != new_uniranges: log.info("%s Unicode ranges pruned: %s", tag, sorted(new_uniranges)) if self.options.recalc_average_width: widths = [m[0] for m in font["hmtx"].metrics.values() if m[0] > 0] avg_width = otRound(sum(widths) / len(widths)) if avg_width != font[tag].xAvgCharWidth: font[tag].xAvgCharWidth = avg_width log.info("%s xAvgCharWidth updated: %d", tag, avg_width) if self.options.recalc_max_context: max_context = maxCtxFont(font) if max_context != font[tag].usMaxContext: font[tag].usMaxContext = max_context log.info("%s usMaxContext updated: %d", tag, max_context) clazz = ttLib.getTableClass(tag) if hasattr(clazz, 'prune_post_subset'): with timer("prune '%s'" % tag): table = font[tag] retain = table.prune_post_subset(font, self.options) if not retain: log.info("%s pruned to empty; dropped", tag) del font[tag] else: log.info("%s pruned", tag)
[ "def", "_prune_post_subset", "(", "self", ",", "font", ")", ":", "for", "tag", "in", "font", ".", "keys", "(", ")", ":", "if", "tag", "==", "'GlyphOrder'", ":", "continue", "if", "tag", "==", "'OS/2'", "and", "self", ".", "options", ".", "prune_unicode...
https://github.com/fonttools/fonttools/blob/892322aaff6a89bea5927379ec06bc0da3dfb7df/Lib/fontTools/subset/__init__.py#L2958-L2986
natashamjaques/neural_chat
ddb977bb4602a67c460d02231e7bbf7b2cb49a97
ParlAI/parlai/agents/legacy_agents/seq2seq/dict_v1.py
python
DictionaryAgent.txt2vec
(self, text, vec_type=list)
return res
Converts a string to a vector (list of ints). First runs a sentence tokenizer, then a word tokenizer. ``vec_type`` is the type of the returned vector if the input is a string.
Converts a string to a vector (list of ints).
[ "Converts", "a", "string", "to", "a", "vector", "(", "list", "of", "ints", ")", "." ]
def txt2vec(self, text, vec_type=list): """Converts a string to a vector (list of ints). First runs a sentence tokenizer, then a word tokenizer. ``vec_type`` is the type of the returned vector if the input is a string. """ if vec_type == list or vec_type == tuple or vec_type == set: res = vec_type((self[token] for token in self.tokenize(str(text)))) elif vec_type == np.ndarray: res = np.fromiter((self[token] for token in self.tokenize(text)), np.int) else: raise RuntimeError('Type {} not supported by dict'.format(vec_type)) return res
[ "def", "txt2vec", "(", "self", ",", "text", ",", "vec_type", "=", "list", ")", ":", "if", "vec_type", "==", "list", "or", "vec_type", "==", "tuple", "or", "vec_type", "==", "set", ":", "res", "=", "vec_type", "(", "(", "self", "[", "token", "]", "f...
https://github.com/natashamjaques/neural_chat/blob/ddb977bb4602a67c460d02231e7bbf7b2cb49a97/ParlAI/parlai/agents/legacy_agents/seq2seq/dict_v1.py#L603-L616
ceph/teuthology
6fc2011361437a9dfe4e45b50de224392eed8abc
teuthology/orchestra/remote.py
python
RemoteShell.copy_file
(self, src, dst, sudo=False, mode=None, owner=None, mkdir=False, append=False)
Copy data to remote file :param src: source file path on remote host :param dst: destination file path on remote host :param sudo: use sudo to write file, defaults False :param mode: set file mode bits if provided :param owner: set file owner if provided :param mkdir: ensure the destination directory exists, defaults False :param append: append data to the file, defaults False
Copy data to remote file
[ "Copy", "data", "to", "remote", "file" ]
def copy_file(self, src, dst, sudo=False, mode=None, owner=None, mkdir=False, append=False): """ Copy data to remote file :param src: source file path on remote host :param dst: destination file path on remote host :param sudo: use sudo to write file, defaults False :param mode: set file mode bits if provided :param owner: set file owner if provided :param mkdir: ensure the destination directory exists, defaults False :param append: append data to the file, defaults False """ dd = 'sudo dd' if sudo else 'dd' args = dd + ' if=' + src + ' of=' + dst if append: args += ' conv=notrunc oflag=append' if mkdir: mkdirp = 'sudo mkdir -p' if sudo else 'mkdir -p' dirpath = os.path.dirname(dst) if dirpath: args = mkdirp + ' ' + dirpath + '\n' + args if mode: chmod = 'sudo chmod' if sudo else 'chmod' args += '\n' + chmod + ' ' + mode + ' ' + dst if owner: chown = 'sudo chown' if sudo else 'chown' args += '\n' + chown + ' ' + owner + ' ' + dst args = 'set -ex' + '\n' + args self.run(args=args)
[ "def", "copy_file", "(", "self", ",", "src", ",", "dst", ",", "sudo", "=", "False", ",", "mode", "=", "None", ",", "owner", "=", "None", ",", "mkdir", "=", "False", ",", "append", "=", "False", ")", ":", "dd", "=", "'sudo dd'", "if", "sudo", "els...
https://github.com/ceph/teuthology/blob/6fc2011361437a9dfe4e45b50de224392eed8abc/teuthology/orchestra/remote.py#L160-L190
materialsproject/pymatgen
8128f3062a334a2edd240e4062b5b9bdd1ae6f58
pymatgen/analysis/eos.py
python
EOSBase.b1
(self)
return self._params[2]
Returns the derivative of bulk modulus wrt pressure(dimensionless)
Returns the derivative of bulk modulus wrt pressure(dimensionless)
[ "Returns", "the", "derivative", "of", "bulk", "modulus", "wrt", "pressure", "(", "dimensionless", ")" ]
def b1(self): """ Returns the derivative of bulk modulus wrt pressure(dimensionless) """ return self._params[2]
[ "def", "b1", "(", "self", ")", ":", "return", "self", ".", "_params", "[", "2", "]" ]
https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/analysis/eos.py#L152-L156
wucng/TensorExpand
4ea58f64f5c5082b278229b799c9f679536510b7
TensorExpand/Object detection/faster rcnn/CharlesShang-TFFRCNN-master/experiments/profiling/gprof2dot.py
python
OprofileParser.parse_entry
(self)
[]
def parse_entry(self): callers = self.parse_subentries() if self.match_primary(): function = self.parse_subentry() if function is not None: callees = self.parse_subentries() self.add_entry(callers, function, callees) self.skip_separator()
[ "def", "parse_entry", "(", "self", ")", ":", "callers", "=", "self", ".", "parse_subentries", "(", ")", "if", "self", ".", "match_primary", "(", ")", ":", "function", "=", "self", ".", "parse_subentry", "(", ")", "if", "function", "is", "not", "None", ...
https://github.com/wucng/TensorExpand/blob/4ea58f64f5c5082b278229b799c9f679536510b7/TensorExpand/Object detection/faster rcnn/CharlesShang-TFFRCNN-master/experiments/profiling/gprof2dot.py#L2130-L2137
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/api/appinfo_includes.py
python
_MergeBuiltinsIncludes
(appinfo_path, appyaml, open_fn=open)
return ( appinfo.AppInclude.MergeAppYamlAppInclude(appyaml, aggregate_appinclude), include_paths)
Merges app.yaml files from builtins and includes directives in appyaml. Args: appinfo_path: the application directory. appyaml: the yaml file to obtain builtins and includes directives from. open_fn: file opening function to pass to _ResolveIncludes, used when reading yaml files. Returns: the modified appyaml object which incorporates referenced yaml files.
Merges app.yaml files from builtins and includes directives in appyaml.
[ "Merges", "app", ".", "yaml", "files", "from", "builtins", "and", "includes", "directives", "in", "appyaml", "." ]
def _MergeBuiltinsIncludes(appinfo_path, appyaml, open_fn=open): """Merges app.yaml files from builtins and includes directives in appyaml. Args: appinfo_path: the application directory. appyaml: the yaml file to obtain builtins and includes directives from. open_fn: file opening function to pass to _ResolveIncludes, used when reading yaml files. Returns: the modified appyaml object which incorporates referenced yaml files. """ if not appyaml.builtins: appyaml.builtins = [appinfo.BuiltinHandler(default='on')] else: if not appinfo.BuiltinHandler.IsDefined(appyaml.builtins, 'default'): appyaml.builtins.append(appinfo.BuiltinHandler(default='on')) runtime_for_including = appyaml.runtime if runtime_for_including == 'vm': runtime_for_including = appyaml.vm_settings.get('vm_runtime', 'python27') aggregate_appinclude, include_paths = ( _ResolveIncludes(appinfo_path, appinfo.AppInclude(builtins=appyaml.builtins, includes=appyaml.includes), os.path.dirname(appinfo_path), runtime_for_including, open_fn=open_fn)) return ( appinfo.AppInclude.MergeAppYamlAppInclude(appyaml, aggregate_appinclude), include_paths)
[ "def", "_MergeBuiltinsIncludes", "(", "appinfo_path", ",", "appyaml", ",", "open_fn", "=", "open", ")", ":", "if", "not", "appyaml", ".", "builtins", ":", "appyaml", ".", "builtins", "=", "[", "appinfo", ".", "BuiltinHandler", "(", "default", "=", "'on'", ...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/api/appinfo_includes.py#L86-L124
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/files.py
python
RelocationBatchLaunch.get_complete
(self)
return self._value
Only call this if :meth:`is_complete` is true. :rtype: RelocationBatchResult
Only call this if :meth:`is_complete` is true.
[ "Only", "call", "this", "if", ":", "meth", ":", "is_complete", "is", "true", "." ]
def get_complete(self): """ Only call this if :meth:`is_complete` is true. :rtype: RelocationBatchResult """ if not self.is_complete(): raise AttributeError("tag 'complete' not set") return self._value
[ "def", "get_complete", "(", "self", ")", ":", "if", "not", "self", ".", "is_complete", "(", ")", ":", "raise", "AttributeError", "(", "\"tag 'complete' not set\"", ")", "return", "self", ".", "_value" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/files.py#L6503-L6511
programa-stic/barf-project
9547ef843b8eb021c2c32c140e36173c0b4eafa3
barf/analysis/codeanalyzer/codeanalyzer.py
python
CodeAnalyzer.get_memory
(self, mode)
return mem[mode]
Return a smt bit vector that represents a memory location.
Return a smt bit vector that represents a memory location.
[ "Return", "a", "smt", "bit", "vector", "that", "represents", "a", "memory", "location", "." ]
def get_memory(self, mode): """Return a smt bit vector that represents a memory location. """ mem = { "pre": self._translator.get_memory_init(), "post": self._translator.get_memory_curr(), } return mem[mode]
[ "def", "get_memory", "(", "self", ",", "mode", ")", ":", "mem", "=", "{", "\"pre\"", ":", "self", ".", "_translator", ".", "get_memory_init", "(", ")", ",", "\"post\"", ":", "self", ".", "_translator", ".", "get_memory_curr", "(", ")", ",", "}", "retur...
https://github.com/programa-stic/barf-project/blob/9547ef843b8eb021c2c32c140e36173c0b4eafa3/barf/analysis/codeanalyzer/codeanalyzer.py#L106-L114
jquast/x84
11f445bb82e6e895d7cce57d4c6d8572d1981162
x84/engine.py
python
session_recv
(locks, terminals, log, tap_events)
Receive data waiting for terminal sessions. All data received from subprocess is handled here.
Receive data waiting for terminal sessions.
[ "Receive", "data", "waiting", "for", "terminal", "sessions", "." ]
def session_recv(locks, terminals, log, tap_events): """ Receive data waiting for terminal sessions. All data received from subprocess is handled here. """ for sid, tty in terminals: while tty.master_read.poll(): try: event, data = tty.master_read.recv() except (EOFError, IOError) as err: # sub-process unexpectedly closed log.exception('master_read pipe: {0}'.format(err)) kill_session(tty.client, 'master_read pipe: {0}'.format(err)) break except TypeError as err: log.exception('unpickling error: {0}'.format(err)) break # 'exit' event, unregisters client if event == 'exit': kill_session(tty.client, 'client exit') break # 'logger' event, prefix log message with handle and IP address elif event == 'logger': data.msg = ('{data.handle}[{tty.sid}] {data.msg}' .format(data=data, tty=tty)) log.handle(data) # 'output' event, buffer for tcp socket elif event == 'output': tty.client.send_unicode(ucs=data[0], encoding=data[1]) # 'remote-disconnect' event, hunt and destroy elif event == 'remote-disconnect': for _sid, _tty in terminals: # data[0] is 'send-to' address. if data[0] == _sid: kill_session( tty.client, 'remote-disconnect by {0}'.format(sid)) break # 'route': message passing directly from one session to another elif event == 'route': if tap_events: log.debug('route {0!r}'.format(data)) tgt_sid, send_event, send_val = data[0], data[1], data[2:] for _sid, _tty in terminals: if tgt_sid == _sid: _tty.master_write.send((send_event, send_val)) break # 'global': message broadcasting to all sessions elif event == 'global': if tap_events: log.debug('broadcast: {data!r}'.format(data=data)) for _sid, _tty in terminals: if sid != _sid: _tty.master_write.send((event, data,)) # 'set-timeout': set user-preferred timeout elif event == 'set-timeout': if tap_events: log.debug('[{tty.sid}] set-timeout {data}' .format(tty=tty, data=data)) tty.timeout = data # 'db*': access DBProxy API for shared sqlitedict elif event.startswith('db'): DBHandler(tty.master_write, event, data).start() # 'lock': access fine-grained bbs-global locking elif event.startswith('lock'): handle_lock(locks, tty, event, data, tap_events, log) else: log.error('[{tty.sid}] unhandled event, data: ' '({event}, {data})' .format(tty=tty, event=event, data=data))
[ "def", "session_recv", "(", "locks", ",", "terminals", ",", "log", ",", "tap_events", ")", ":", "for", "sid", ",", "tty", "in", "terminals", ":", "while", "tty", ".", "master_read", ".", "poll", "(", ")", ":", "try", ":", "event", ",", "data", "=", ...
https://github.com/jquast/x84/blob/11f445bb82e6e895d7cce57d4c6d8572d1981162/x84/engine.py#L353-L432
NoneGG/aredis
b46e67163692cd0796763e5c9e17394821d9280c
aredis/lock.py
python
Lock.release
(self)
Releases the already acquired lock
Releases the already acquired lock
[ "Releases", "the", "already", "acquired", "lock" ]
async def release(self): """Releases the already acquired lock""" expected_token = self.local.get() if expected_token is None: raise LockError("Cannot release an unlocked lock") self.local.set(None) await self.do_release(expected_token)
[ "async", "def", "release", "(", "self", ")", ":", "expected_token", "=", "self", ".", "local", ".", "get", "(", ")", "if", "expected_token", "is", "None", ":", "raise", "LockError", "(", "\"Cannot release an unlocked lock\"", ")", "self", ".", "local", ".", ...
https://github.com/NoneGG/aredis/blob/b46e67163692cd0796763e5c9e17394821d9280c/aredis/lock.py#L132-L138
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
lib-python/2.7/decimal.py
python
Decimal._power_modulo
(self, other, modulo, context=None)
return _dec_from_triple(sign, str(base), 0)
Three argument version of __pow__
Three argument version of __pow__
[ "Three", "argument", "version", "of", "__pow__" ]
def _power_modulo(self, other, modulo, context=None): """Three argument version of __pow__""" # if can't convert other and modulo to Decimal, raise # TypeError; there's no point returning NotImplemented (no # equivalent of __rpow__ for three argument pow) other = _convert_other(other, raiseit=True) modulo = _convert_other(modulo, raiseit=True) if context is None: context = getcontext() # deal with NaNs: if there are any sNaNs then first one wins, # (i.e. behaviour for NaNs is identical to that of fma) self_is_nan = self._isnan() other_is_nan = other._isnan() modulo_is_nan = modulo._isnan() if self_is_nan or other_is_nan or modulo_is_nan: if self_is_nan == 2: return context._raise_error(InvalidOperation, 'sNaN', self) if other_is_nan == 2: return context._raise_error(InvalidOperation, 'sNaN', other) if modulo_is_nan == 2: return context._raise_error(InvalidOperation, 'sNaN', modulo) if self_is_nan: return self._fix_nan(context) if other_is_nan: return other._fix_nan(context) return modulo._fix_nan(context) # check inputs: we apply same restrictions as Python's pow() if not (self._isinteger() and other._isinteger() and modulo._isinteger()): return context._raise_error(InvalidOperation, 'pow() 3rd argument not allowed ' 'unless all arguments are integers') if other < 0: return context._raise_error(InvalidOperation, 'pow() 2nd argument cannot be ' 'negative when 3rd argument specified') if not modulo: return context._raise_error(InvalidOperation, 'pow() 3rd argument cannot be 0') # additional restriction for decimal: the modulus must be less # than 10**prec in absolute value if modulo.adjusted() >= context.prec: return context._raise_error(InvalidOperation, 'insufficient precision: pow() 3rd ' 'argument must not have more than ' 'precision digits') # define 0**0 == NaN, for consistency with two-argument pow # (even though it hurts!) if not other and not self: return context._raise_error(InvalidOperation, 'at least one of pow() 1st argument ' 'and 2nd argument must be nonzero ;' '0**0 is not defined') # compute sign of result if other._iseven(): sign = 0 else: sign = self._sign # convert modulo to a Python integer, and self and other to # Decimal integers (i.e. force their exponents to be >= 0) modulo = abs(int(modulo)) base = _WorkRep(self.to_integral_value()) exponent = _WorkRep(other.to_integral_value()) # compute result using integer pow() base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo for i in xrange(exponent.exp): base = pow(base, 10, modulo) base = pow(base, exponent.int, modulo) return _dec_from_triple(sign, str(base), 0)
[ "def", "_power_modulo", "(", "self", ",", "other", ",", "modulo", ",", "context", "=", "None", ")", ":", "# if can't convert other and modulo to Decimal, raise", "# TypeError; there's no point returning NotImplemented (no", "# equivalent of __rpow__ for three argument pow)", "other...
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib-python/2.7/decimal.py#L1851-L1933
bilelmoussaoui/Hardcode-Tray
8b264ca2386cabe595b027933a9c80c41adc1ea4
HardcodeTray/modules/applications/qt.py
python
QtApplication.install_icon
(self, icon, icon_path)
Install icon to the current directory.
Install icon to the current directory.
[ "Install", "icon", "to", "the", "current", "directory", "." ]
def install_icon(self, icon, icon_path): """Install icon to the current directory.""" icon.original = "{}.{}".format(icon.original, icon.theme_ext) base_icon = icon.original theme_icon = icon.theme output_icon = path.join(str(icon_path), base_icon) symlink_file(theme_icon, output_icon)
[ "def", "install_icon", "(", "self", ",", "icon", ",", "icon_path", ")", ":", "icon", ".", "original", "=", "\"{}.{}\"", ".", "format", "(", "icon", ".", "original", ",", "icon", ".", "theme_ext", ")", "base_icon", "=", "icon", ".", "original", "theme_ico...
https://github.com/bilelmoussaoui/Hardcode-Tray/blob/8b264ca2386cabe595b027933a9c80c41adc1ea4/HardcodeTray/modules/applications/qt.py#L39-L47
GoogleCloudPlatform/PerfKitBenchmarker
6e3412d7d5e414b8ca30ed5eaf970cef1d919a67
perfkitbenchmarker/linux_packages/mutilate.py
python
GetMetadata
()
return metadata
Returns mutilate metadata.
Returns mutilate metadata.
[ "Returns", "mutilate", "metadata", "." ]
def GetMetadata(): """Returns mutilate metadata.""" metadata = { 'protocol': FLAGS.mutilate_protocol, 'qps': FLAGS.mutilate_qps or 'peak', 'time': FLAGS.mutilate_time, 'keysize': FLAGS.mutilate_keysize, 'valuesize': FLAGS.mutilate_valuesize, 'records': FLAGS.mutilate_records, 'ratio': FLAGS.mutilate_ratio } if FLAGS.mutilate_options: metadata['options'] = FLAGS.mutilate_options return metadata
[ "def", "GetMetadata", "(", ")", ":", "metadata", "=", "{", "'protocol'", ":", "FLAGS", ".", "mutilate_protocol", ",", "'qps'", ":", "FLAGS", ".", "mutilate_qps", "or", "'peak'", ",", "'time'", ":", "FLAGS", ".", "mutilate_time", ",", "'keysize'", ":", "FLA...
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/6e3412d7d5e414b8ca30ed5eaf970cef1d919a67/perfkitbenchmarker/linux_packages/mutilate.py#L135-L149
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/email/message.py
python
Message.get_charset
(self)
return self._charset
Return the Charset instance associated with the message's payload.
Return the Charset instance associated with the message's payload.
[ "Return", "the", "Charset", "instance", "associated", "with", "the", "message", "s", "payload", "." ]
def get_charset(self): """Return the Charset instance associated with the message's payload. """ return self._charset
[ "def", "get_charset", "(", "self", ")", ":", "return", "self", ".", "_charset" ]
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/email/message.py#L371-L374
werner-duvaud/muzero-general
23a1f6910e97d78475ccd29576cdd107c5afefd2
muzero.py
python
MuZero.train
(self, log_in_tensorboard=True)
Spawn ray workers and launch the training. Args: log_in_tensorboard (bool): Start a testing worker and log its performance in TensorBoard.
Spawn ray workers and launch the training.
[ "Spawn", "ray", "workers", "and", "launch", "the", "training", "." ]
def train(self, log_in_tensorboard=True): """ Spawn ray workers and launch the training. Args: log_in_tensorboard (bool): Start a testing worker and log its performance in TensorBoard. """ if log_in_tensorboard or self.config.save_model: os.makedirs(self.config.results_path, exist_ok=True) # Manage GPUs if 0 < self.num_gpus: num_gpus_per_worker = self.num_gpus / ( self.config.train_on_gpu + self.config.num_workers * self.config.selfplay_on_gpu + log_in_tensorboard * self.config.selfplay_on_gpu + self.config.use_last_model_value * self.config.reanalyse_on_gpu ) if 1 < num_gpus_per_worker: num_gpus_per_worker = math.floor(num_gpus_per_worker) else: num_gpus_per_worker = 0 # Initialize workers self.training_worker = trainer.Trainer.options( num_cpus=0, num_gpus=num_gpus_per_worker if self.config.train_on_gpu else 0, ).remote(self.checkpoint, self.config) self.shared_storage_worker = shared_storage.SharedStorage.remote( self.checkpoint, self.config, ) self.shared_storage_worker.set_info.remote("terminate", False) self.replay_buffer_worker = replay_buffer.ReplayBuffer.remote( self.checkpoint, self.replay_buffer, self.config ) if self.config.use_last_model_value: self.reanalyse_worker = replay_buffer.Reanalyse.options( num_cpus=0, num_gpus=num_gpus_per_worker if self.config.reanalyse_on_gpu else 0, ).remote(self.checkpoint, self.config) self.self_play_workers = [ self_play.SelfPlay.options( num_cpus=0, num_gpus=num_gpus_per_worker if self.config.selfplay_on_gpu else 0, ).remote( self.checkpoint, self.Game, self.config, self.config.seed + seed, ) for seed in range(self.config.num_workers) ] # Launch workers [ self_play_worker.continuous_self_play.remote( self.shared_storage_worker, self.replay_buffer_worker ) for self_play_worker in self.self_play_workers ] self.training_worker.continuous_update_weights.remote( self.replay_buffer_worker, self.shared_storage_worker ) if self.config.use_last_model_value: self.reanalyse_worker.reanalyse.remote( self.replay_buffer_worker, self.shared_storage_worker ) if log_in_tensorboard: self.logging_loop( num_gpus_per_worker if self.config.selfplay_on_gpu else 0, )
[ "def", "train", "(", "self", ",", "log_in_tensorboard", "=", "True", ")", ":", "if", "log_in_tensorboard", "or", "self", ".", "config", ".", "save_model", ":", "os", ".", "makedirs", "(", "self", ".", "config", ".", "results_path", ",", "exist_ok", "=", ...
https://github.com/werner-duvaud/muzero-general/blob/23a1f6910e97d78475ccd29576cdd107c5afefd2/muzero.py#L127-L198
fonttools/fonttools
892322aaff6a89bea5927379ec06bc0da3dfb7df
Lib/fontTools/mtiLib/__init__.py
python
parseCoverage
(lines, font, klass=ot.Coverage)
return makeCoverage(glyphs, font, klass)
[]
def parseCoverage(lines, font, klass=ot.Coverage): glyphs = [] with lines.between('coverage definition'): for line in lines: glyphs.append(makeGlyph(line[0])) return makeCoverage(glyphs, font, klass)
[ "def", "parseCoverage", "(", "lines", ",", "font", ",", "klass", "=", "ot", ".", "Coverage", ")", ":", "glyphs", "=", "[", "]", "with", "lines", ".", "between", "(", "'coverage definition'", ")", ":", "for", "line", "in", "lines", ":", "glyphs", ".", ...
https://github.com/fonttools/fonttools/blob/892322aaff6a89bea5927379ec06bc0da3dfb7df/Lib/fontTools/mtiLib/__init__.py#L664-L669
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
option/ctp/__init__.py
python
MdApi.SubscribeForQuoteRsp
(self, pInstrumentIDs)
return 0
订阅询价。 @param pInstrumentIDs 合约ID列表 @remark
订阅询价。
[ "订阅询价。" ]
def SubscribeForQuoteRsp(self, pInstrumentIDs): """订阅询价。 @param pInstrumentIDs 合约ID列表 @remark """ return 0
[ "def", "SubscribeForQuoteRsp", "(", "self", ",", "pInstrumentIDs", ")", ":", "return", "0" ]
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/option/ctp/__init__.py#L87-L92
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/donations/models.py
python
Donation.get_payment_description
(self, inv)
return 'Tendenci Invoice %d Payment for Donation %d' % ( inv.id, inv.object_id, )
The description will be sent to payment gateway and displayed on invoice. If not supplied, the default description will be generated.
The description will be sent to payment gateway and displayed on invoice. If not supplied, the default description will be generated.
[ "The", "description", "will", "be", "sent", "to", "payment", "gateway", "and", "displayed", "on", "invoice", ".", "If", "not", "supplied", "the", "default", "description", "will", "be", "generated", "." ]
def get_payment_description(self, inv): """ The description will be sent to payment gateway and displayed on invoice. If not supplied, the default description will be generated. """ return 'Tendenci Invoice %d Payment for Donation %d' % ( inv.id, inv.object_id, )
[ "def", "get_payment_description", "(", "self", ",", "inv", ")", ":", "return", "'Tendenci Invoice %d Payment for Donation %d'", "%", "(", "inv", ".", "id", ",", "inv", ".", "object_id", ",", ")" ]
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/donations/models.py#L64-L72
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/build/lib.linux-x86_64-2.7/flaskbb/management/views.py
python
DisablePlugin.post
(self, name)
return redirect(url_for("management.plugins"))
[]
def post(self, name): validate_plugin(name) plugin = PluginRegistry.query.filter_by(name=name).first_or_404() if not plugin.enabled: flash( _("Plugin %(plugin)s is already disabled.", plugin=plugin.name), "info" ) return redirect(url_for("management.plugins")) plugin.enabled = False plugin.save() flash( _( "Plugin %(plugin)s disabled. Please restart FlaskBB now.", plugin=plugin.name ), "success" ) return redirect(url_for("management.plugins"))
[ "def", "post", "(", "self", ",", "name", ")", ":", "validate_plugin", "(", "name", ")", "plugin", "=", "PluginRegistry", ".", "query", ".", "filter_by", "(", "name", "=", "name", ")", ".", "first_or_404", "(", ")", "if", "not", "plugin", ".", "enabled"...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/build/lib.linux-x86_64-2.7/flaskbb/management/views.py#L974-L993
sametmax/Django--an-app-at-a-time
99eddf12ead76e6dfbeb09ce0bae61e282e22f8a
ignore_this_directory/django/contrib/gis/geos/collections.py
python
GeometryCollection.__init__
(self, *args, **kwargs)
Initialize a Geometry Collection from a sequence of Geometry objects.
Initialize a Geometry Collection from a sequence of Geometry objects.
[ "Initialize", "a", "Geometry", "Collection", "from", "a", "sequence", "of", "Geometry", "objects", "." ]
def __init__(self, *args, **kwargs): "Initialize a Geometry Collection from a sequence of Geometry objects." # Checking the arguments if len(args) == 1: # If only one geometry provided or a list of geometries is provided # in the first argument. if isinstance(args[0], (tuple, list)): init_geoms = args[0] else: init_geoms = args else: init_geoms = args # Ensuring that only the permitted geometries are allowed in this collection # this is moved to list mixin super class self._check_allowed(init_geoms) # Creating the geometry pointer array. collection = self._create_collection(len(init_geoms), init_geoms) super().__init__(collection, **kwargs)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Checking the arguments", "if", "len", "(", "args", ")", "==", "1", ":", "# If only one geometry provided or a list of geometries is provided", "# in the first argument.", "if", ...
https://github.com/sametmax/Django--an-app-at-a-time/blob/99eddf12ead76e6dfbeb09ce0bae61e282e22f8a/ignore_this_directory/django/contrib/gis/geos/collections.py#L19-L38
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/models/convbert/modeling_convbert.py
python
ConvBertOutput.__init__
(self, config)
[]
def __init__(self, config): super().__init__() if config.num_groups == 1: self.dense = nn.Linear(config.intermediate_size, config.hidden_size) else: self.dense = GroupedLinearLayer( input_size=config.intermediate_size, output_size=config.hidden_size, num_groups=config.num_groups ) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob)
[ "def", "__init__", "(", "self", ",", "config", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "if", "config", ".", "num_groups", "==", "1", ":", "self", ".", "dense", "=", "nn", ".", "Linear", "(", "config", ".", "intermediate_size", ",", ...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/convbert/modeling_convbert.py#L530-L539
karanchahal/distiller
a17ec06cbeafcdd2aea19d7c7663033c951392f5
distillers/uda_distiller.py
python
UDATrainer.uda_loss
(self, n_out, aug_out)
return self.kd_fun(n_out, aug_out) / batch_size
[]
def uda_loss(self, n_out, aug_out): batch_size = n_out.shape[0] n_out = torch_func.log_softmax(n_out, dim=1) aug_out = torch_func.softmax(aug_out, dim=1) return self.kd_fun(n_out, aug_out) / batch_size
[ "def", "uda_loss", "(", "self", ",", "n_out", ",", "aug_out", ")", ":", "batch_size", "=", "n_out", ".", "shape", "[", "0", "]", "n_out", "=", "torch_func", ".", "log_softmax", "(", "n_out", ",", "dim", "=", "1", ")", "aug_out", "=", "torch_func", "....
https://github.com/karanchahal/distiller/blob/a17ec06cbeafcdd2aea19d7c7663033c951392f5/distillers/uda_distiller.py#L201-L205
scott-griffiths/bitstring
c84ad7f02818caf7102d556c6dcbdef153b0cf11
bitstring.py
python
ConstBitStream._getbytepos
(self)
return self._pos // 8
Return the current position in the stream in bytes. Must be byte aligned.
Return the current position in the stream in bytes. Must be byte aligned.
[ "Return", "the", "current", "position", "in", "the", "stream", "in", "bytes", ".", "Must", "be", "byte", "aligned", "." ]
def _getbytepos(self): """Return the current position in the stream in bytes. Must be byte aligned.""" if self._pos % 8: raise ByteAlignError("Not byte aligned in _getbytepos().") return self._pos // 8
[ "def", "_getbytepos", "(", "self", ")", ":", "if", "self", ".", "_pos", "%", "8", ":", "raise", "ByteAlignError", "(", "\"Not byte aligned in _getbytepos().\"", ")", "return", "self", ".", "_pos", "//", "8" ]
https://github.com/scott-griffiths/bitstring/blob/c84ad7f02818caf7102d556c6dcbdef153b0cf11/bitstring.py#L3863-L3867
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/numpy/core/defchararray.py
python
chararray.splitlines
(self, keepends=None)
return splitlines(self, keepends)
For each element in `self`, return a list of the lines in the element, breaking at line boundaries. See also -------- char.splitlines
For each element in `self`, return a list of the lines in the element, breaking at line boundaries.
[ "For", "each", "element", "in", "self", "return", "a", "list", "of", "the", "lines", "in", "the", "element", "breaking", "at", "line", "boundaries", "." ]
def splitlines(self, keepends=None): """ For each element in `self`, return a list of the lines in the element, breaking at line boundaries. See also -------- char.splitlines """ return splitlines(self, keepends)
[ "def", "splitlines", "(", "self", ",", "keepends", "=", "None", ")", ":", "return", "splitlines", "(", "self", ",", "keepends", ")" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/numpy/core/defchararray.py#L2353-L2363
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
txdav/idav.py
python
IStoreNotifier.clone
(storeObject)
Called by the store when a home child is created and used to give the home child a notifier "inherited" from the home. @param label: a new label to use for the home child. @type label: C{str} @param storeObject: the store object associated with the notifier. @type storeObject: L{CommonHome} or L{CommonHomeChild}
Called by the store when a home child is created and used to give the home child a notifier "inherited" from the home.
[ "Called", "by", "the", "store", "when", "a", "home", "child", "is", "created", "and", "used", "to", "give", "the", "home", "child", "a", "notifier", "inherited", "from", "the", "home", "." ]
def clone(storeObject): # @NoSelf """ Called by the store when a home child is created and used to give the home child a notifier "inherited" from the home. @param label: a new label to use for the home child. @type label: C{str} @param storeObject: the store object associated with the notifier. @type storeObject: L{CommonHome} or L{CommonHomeChild} """
[ "def", "clone", "(", "storeObject", ")", ":", "# @NoSelf" ]
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txdav/idav.py#L326-L335
CSAILVision/gandissect
f55fc5683bebe2bd6c598d703efa6f4e6fb488bf
netdissect/nethook.py
python
make_matching_tensor
(valuedict, name, data)
return v
Converts `valuedict[name]` to be a tensor with the same dtype, device, and dimension count as `data`, and caches the converted tensor.
Converts `valuedict[name]` to be a tensor with the same dtype, device, and dimension count as `data`, and caches the converted tensor.
[ "Converts", "valuedict", "[", "name", "]", "to", "be", "a", "tensor", "with", "the", "same", "dtype", "device", "and", "dimension", "count", "as", "data", "and", "caches", "the", "converted", "tensor", "." ]
def make_matching_tensor(valuedict, name, data): ''' Converts `valuedict[name]` to be a tensor with the same dtype, device, and dimension count as `data`, and caches the converted tensor. ''' v = valuedict.get(name, None) if v is None: return None if not isinstance(v, torch.Tensor): # Accept non-torch data. v = torch.from_numpy(numpy.array(v)) valuedict[name] = v if not v.device == data.device or not v.dtype == data.dtype: # Ensure device and type matches. assert not v.requires_grad, '%s wrong device or type' % (name) v = v.to(device=data.device, dtype=data.dtype) valuedict[name] = v if len(v.shape) < len(data.shape): # Ensure dimensions are unsqueezed as needed. assert not v.requires_grad, '%s wrong dimensions' % (name) v = v.view((1,) + tuple(v.shape) + (1,) * (len(data.shape) - len(v.shape) - 1)) valuedict[name] = v return v
[ "def", "make_matching_tensor", "(", "valuedict", ",", "name", ",", "data", ")", ":", "v", "=", "valuedict", ".", "get", "(", "name", ",", "None", ")", "if", "v", "is", "None", ":", "return", "None", "if", "not", "isinstance", "(", "v", ",", "torch", ...
https://github.com/CSAILVision/gandissect/blob/f55fc5683bebe2bd6c598d703efa6f4e6fb488bf/netdissect/nethook.py#L218-L241
mlrun/mlrun
4c120719d64327a34b7ee1ab08fb5e01b258b00a
mlrun/serving/states.py
python
BaseStep.path_to_step
(self, path: str)
return next_level
return step object from step relative/fullname
return step object from step relative/fullname
[ "return", "step", "object", "from", "step", "relative", "/", "fullname" ]
def path_to_step(self, path: str): """return step object from step relative/fullname""" path = path or "" tree = path.split(path_splitter) next_level = self for step in tree: if step not in next_level: raise GraphError( f"step {step} doesnt exist in the graph under {next_level.fullname}" ) next_level = next_level[step] return next_level
[ "def", "path_to_step", "(", "self", ",", "path", ":", "str", ")", ":", "path", "=", "path", "or", "\"\"", "tree", "=", "path", ".", "split", "(", "path_splitter", ")", "next_level", "=", "self", "for", "step", "in", "tree", ":", "if", "step", "not", ...
https://github.com/mlrun/mlrun/blob/4c120719d64327a34b7ee1ab08fb5e01b258b00a/mlrun/serving/states.py#L201-L212
pallets/click
051d57cef4ce59212dc1175ad4550743bf47d840
src/click/utils.py
python
open_file
( filename: str, mode: str = "r", encoding: t.Optional[str] = None, errors: t.Optional[str] = "strict", lazy: bool = False, atomic: bool = False, )
return f
Open a file, with extra behavior to handle ``'-'`` to indicate a standard stream, lazy open on write, and atomic write. Similar to the behavior of the :class:`~click.File` param type. If ``'-'`` is given to open ``stdout`` or ``stdin``, the stream is wrapped so that using it in a context manager will not close it. This makes it possible to use the function without accidentally closing a standard stream: .. code-block:: python with open_file(filename) as f: ... :param filename: The name of the file to open, or ``'-'`` for ``stdin``/``stdout``. :param mode: The mode in which to open the file. :param encoding: The encoding to decode or encode a file opened in text mode. :param errors: The error handling mode. :param lazy: Wait to open the file until it is accessed. For read mode, the file is temporarily opened to raise access errors early, then closed until it is read again. :param atomic: Write to a temporary file and replace the given file on close. .. versionadded:: 3.0
Open a file, with extra behavior to handle ``'-'`` to indicate a standard stream, lazy open on write, and atomic write. Similar to the behavior of the :class:`~click.File` param type.
[ "Open", "a", "file", "with", "extra", "behavior", "to", "handle", "-", "to", "indicate", "a", "standard", "stream", "lazy", "open", "on", "write", "and", "atomic", "write", ".", "Similar", "to", "the", "behavior", "of", "the", ":", "class", ":", "~click"...
def open_file( filename: str, mode: str = "r", encoding: t.Optional[str] = None, errors: t.Optional[str] = "strict", lazy: bool = False, atomic: bool = False, ) -> t.IO: """Open a file, with extra behavior to handle ``'-'`` to indicate a standard stream, lazy open on write, and atomic write. Similar to the behavior of the :class:`~click.File` param type. If ``'-'`` is given to open ``stdout`` or ``stdin``, the stream is wrapped so that using it in a context manager will not close it. This makes it possible to use the function without accidentally closing a standard stream: .. code-block:: python with open_file(filename) as f: ... :param filename: The name of the file to open, or ``'-'`` for ``stdin``/``stdout``. :param mode: The mode in which to open the file. :param encoding: The encoding to decode or encode a file opened in text mode. :param errors: The error handling mode. :param lazy: Wait to open the file until it is accessed. For read mode, the file is temporarily opened to raise access errors early, then closed until it is read again. :param atomic: Write to a temporary file and replace the given file on close. .. versionadded:: 3.0 """ if lazy: return t.cast(t.IO, LazyFile(filename, mode, encoding, errors, atomic=atomic)) f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic) if not should_close: f = t.cast(t.IO, KeepOpenFile(f)) return f
[ "def", "open_file", "(", "filename", ":", "str", ",", "mode", ":", "str", "=", "\"r\"", ",", "encoding", ":", "t", ".", "Optional", "[", "str", "]", "=", "None", ",", "errors", ":", "t", ".", "Optional", "[", "str", "]", "=", "\"strict\"", ",", "...
https://github.com/pallets/click/blob/051d57cef4ce59212dc1175ad4550743bf47d840/src/click/utils.py#L335-L379
laughingman7743/PyAthena
417749914247cabca2325368c6eda337b28b47f0
pyathena/pandas/result_set.py
python
AthenaPandasResultSet.converters
( self, )
return { d[0]: self._converter.mappings[d[1]] for d in description if d[1] in self._converter.mappings }
[]
def converters( self, ) -> Dict[Optional[Any], Callable[[Optional[str]], Optional[Any]]]: description = self.description if self.description else [] return { d[0]: self._converter.mappings[d[1]] for d in description if d[1] in self._converter.mappings }
[ "def", "converters", "(", "self", ",", ")", "->", "Dict", "[", "Optional", "[", "Any", "]", ",", "Callable", "[", "[", "Optional", "[", "str", "]", "]", ",", "Optional", "[", "Any", "]", "]", "]", ":", "description", "=", "self", ".", "description"...
https://github.com/laughingman7743/PyAthena/blob/417749914247cabca2325368c6eda337b28b47f0/pyathena/pandas/result_set.py#L78-L86
astropy/astroquery
11c9c83fa8e5f948822f8f73c854ec4b72043016
astroquery/utils/commons.py
python
TableList.pprint
(self, **kwargs)
Helper function to make API more similar to astropy.Tables
Helper function to make API more similar to astropy.Tables
[ "Helper", "function", "to", "make", "API", "more", "similar", "to", "astropy", ".", "Tables" ]
def pprint(self, **kwargs): """ Helper function to make API more similar to astropy.Tables """ if kwargs != {}: warnings.warn("TableList is a container of astropy.Tables.", InputWarning) self.print_table_list()
[ "def", "pprint", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", "!=", "{", "}", ":", "warnings", ".", "warn", "(", "\"TableList is a container of astropy.Tables.\"", ",", "InputWarning", ")", "self", ".", "print_table_list", "(", ")" ]
https://github.com/astropy/astroquery/blob/11c9c83fa8e5f948822f8f73c854ec4b72043016/astroquery/utils/commons.py#L298-L302
freyja-dev/unity-tweak-tool
ad254288d2e0fed94c59277de3f21ef399e3197f
setup.py
python
update_config_new
(libdir, values = {})
return oldvalues
[]
def update_config_new(libdir, values = {}): filename = os.path.join(libdir, 'UnityTweakTool/config/data.py') oldvalues = {} try: fin = open(filename, 'r') fout = open(filename + '.new', 'w') for line in fin: fields = line.split(' = ') # Separate variable from value if fields[0] in values: oldvalues[fields[0]] = fields[1].strip() line = "%s = %s\n" % (fields[0], values[fields[0]]) fout.write(line) fout.flush() fout.close() fin.close() os.rename(fout.name, fin.name) except IOError as e: print ("ERROR: Can't find %s" % filename) sys.exit(1) return oldvalues
[ "def", "update_config_new", "(", "libdir", ",", "values", "=", "{", "}", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "libdir", ",", "'UnityTweakTool/config/data.py'", ")", "oldvalues", "=", "{", "}", "try", ":", "fin", "=", "open", ...
https://github.com/freyja-dev/unity-tweak-tool/blob/ad254288d2e0fed94c59277de3f21ef399e3197f/setup.py#L68-L90
aleju/imgaug
0101108d4fed06bc5056c4a03e2bcb0216dac326
imgaug/augmenters/geometric.py
python
PerspectiveTransform._augment_maps_by_samples
(self, augmentables, arr_attr_name, samples, samples_images, cval, mode, flags)
return result
[]
def _augment_maps_by_samples(self, augmentables, arr_attr_name, samples, samples_images, cval, mode, flags): result = augmentables # estimate max_heights/max_widths for the underlying images # this is only necessary if keep_size is False as then the underlying # image sizes change and we need to update them here # TODO this was re-used from before _augment_batch_() -- reoptimize if self.keep_size: max_heights_imgs = samples.max_heights max_widths_imgs = samples.max_widths else: max_heights_imgs = samples_images.max_heights max_widths_imgs = samples_images.max_widths gen = enumerate(zip(augmentables, samples.matrices, samples.max_heights, samples.max_widths)) for i, (augmentable_i, matrix, max_height, max_width) in gen: arr = getattr(augmentable_i, arr_attr_name) mode_i = mode if mode is None: mode_i = samples.modes[i] cval_i = cval if cval is None: cval_i = samples.cvals[i] nb_channels = arr.shape[2] image_has_zero_sized_axis = (0 in augmentable_i.shape) map_has_zero_sized_axis = (arr.size == 0) if not image_has_zero_sized_axis: if not map_has_zero_sized_axis: warped = [ cv2.warpPerspective( _normalize_cv2_input_arr_(arr[..., c]), matrix, (max_width, max_height), borderValue=cval_i, borderMode=mode_i, flags=flags ) for c in sm.xrange(nb_channels) ] warped = np.stack(warped, axis=-1) setattr(augmentable_i, arr_attr_name, warped) if self.keep_size: h, w = arr.shape[0:2] augmentable_i = augmentable_i.resize((h, w)) else: new_shape = ( max_heights_imgs[i], max_widths_imgs[i] ) + augmentable_i.shape[2:] augmentable_i.shape = new_shape result[i] = augmentable_i return result
[ "def", "_augment_maps_by_samples", "(", "self", ",", "augmentables", ",", "arr_attr_name", ",", "samples", ",", "samples_images", ",", "cval", ",", "mode", ",", "flags", ")", ":", "result", "=", "augmentables", "# estimate max_heights/max_widths for the underlying image...
https://github.com/aleju/imgaug/blob/0101108d4fed06bc5056c4a03e2bcb0216dac326/imgaug/augmenters/geometric.py#L3853-L3914
healpy/healpy
c34d032edaef6e1b755929aa76cf0cc933fcc677
setup.py
python
build_external_clib.env
(self)
return env
Construct an environment dictionary suitable for having pkg-config pick up .pc files in the build_clib directory.
Construct an environment dictionary suitable for having pkg-config pick up .pc files in the build_clib directory.
[ "Construct", "an", "environment", "dictionary", "suitable", "for", "having", "pkg", "-", "config", "pick", "up", ".", "pc", "files", "in", "the", "build_clib", "directory", "." ]
def env(self): """Construct an environment dictionary suitable for having pkg-config pick up .pc files in the build_clib directory.""" # Test if pkg-config is present. If not, fall back to pykg-config. try: env = self._env except AttributeError: env = dict(os.environ) try: check_output(["pkg-config", "--version"]) except OSError as e: if e.errno != errno.ENOENT: raise log.warn("pkg-config is not installed, falling back to pykg-config") env["PKG_CONFIG"] = ( sys.executable + " " + os.path.abspath("run_pykg_config.py") ) else: env["PKG_CONFIG"] = "pkg-config" build_clib = os.path.realpath(self.build_clib) pkg_config_path = ( os.path.join(build_clib, "lib64", "pkgconfig") + ":" + os.path.join(build_clib, "lib", "pkgconfig") ) try: pkg_config_path += ":" + env["PKG_CONFIG_PATH"] except KeyError: pass env["PKG_CONFIG_PATH"] = pkg_config_path self._env = env return env
[ "def", "env", "(", "self", ")", ":", "# Test if pkg-config is present. If not, fall back to pykg-config.", "try", ":", "env", "=", "self", ".", "_env", "except", "AttributeError", ":", "env", "=", "dict", "(", "os", ".", "environ", ")", "try", ":", "check_output...
https://github.com/healpy/healpy/blob/c34d032edaef6e1b755929aa76cf0cc933fcc677/setup.py#L59-L93
pycalphad/pycalphad
631c41c3d041d4e8a47c57d0f25d078344b9da52
pycalphad/model.py
python
Model.ast
(self)
return Add(*list(self.models.values()))
Return the full abstract syntax tree of the model.
Return the full abstract syntax tree of the model.
[ "Return", "the", "full", "abstract", "syntax", "tree", "of", "the", "model", "." ]
def ast(self): "Return the full abstract syntax tree of the model." return Add(*list(self.models.values()))
[ "def", "ast", "(", "self", ")", ":", "return", "Add", "(", "*", "list", "(", "self", ".", "models", ".", "values", "(", ")", ")", ")" ]
https://github.com/pycalphad/pycalphad/blob/631c41c3d041d4e8a47c57d0f25d078344b9da52/pycalphad/model.py#L283-L285
pytorch/fairseq
1575f30dd0a9f7b3c499db0b4767aa4e9f79056c
examples/wav2vec/unsupervised/scripts/wav2vec_extract_features.py
python
Wav2VecFeatureReader.read_audio
(self, fname)
return wav
Load an audio file and return PCM along with the sample rate
Load an audio file and return PCM along with the sample rate
[ "Load", "an", "audio", "file", "and", "return", "PCM", "along", "with", "the", "sample", "rate" ]
def read_audio(self, fname): """Load an audio file and return PCM along with the sample rate""" wav, sr = sf.read(fname) assert sr == 16e3 return wav
[ "def", "read_audio", "(", "self", ",", "fname", ")", ":", "wav", ",", "sr", "=", "sf", ".", "read", "(", "fname", ")", "assert", "sr", "==", "16e3", "return", "wav" ]
https://github.com/pytorch/fairseq/blob/1575f30dd0a9f7b3c499db0b4767aa4e9f79056c/examples/wav2vec/unsupervised/scripts/wav2vec_extract_features.py#L48-L53
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/site-packages/django/contrib/gis/gdal/layer.py
python
Layer.__init__
(self, layer_ptr, ds)
Initializes on an OGR C pointer to the Layer and the `DataSource` object that owns this layer. The `DataSource` object is required so that a reference to it is kept with this Layer. This prevents garbage collection of the `DataSource` while this Layer is still active.
Initializes on an OGR C pointer to the Layer and the `DataSource` object that owns this layer. The `DataSource` object is required so that a reference to it is kept with this Layer. This prevents garbage collection of the `DataSource` while this Layer is still active.
[ "Initializes", "on", "an", "OGR", "C", "pointer", "to", "the", "Layer", "and", "the", "DataSource", "object", "that", "owns", "this", "layer", ".", "The", "DataSource", "object", "is", "required", "so", "that", "a", "reference", "to", "it", "is", "kept", ...
def __init__(self, layer_ptr, ds): """ Initializes on an OGR C pointer to the Layer and the `DataSource` object that owns this layer. The `DataSource` object is required so that a reference to it is kept with this Layer. This prevents garbage collection of the `DataSource` while this Layer is still active. """ if not layer_ptr: raise OGRException('Cannot create Layer, invalid pointer given') self.ptr = layer_ptr self._ds = ds self._ldefn = capi.get_layer_defn(self._ptr) # Does the Layer support random reading? self._random_read = self.test_capability('RandomRead')
[ "def", "__init__", "(", "self", ",", "layer_ptr", ",", "ds", ")", ":", "if", "not", "layer_ptr", ":", "raise", "OGRException", "(", "'Cannot create Layer, invalid pointer given'", ")", "self", ".", "ptr", "=", "layer_ptr", "self", ".", "_ds", "=", "ds", "sel...
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/site-packages/django/contrib/gis/gdal/layer.py#L25-L38