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
arviz-devs/arviz
17b1a48b577ba9776a31e7e57a8a8af63e826901
arviz/plots/backends/bokeh/densityplot.py
python
plot_density
( ax, all_labels, to_plot, colors, bw, circular, figsize, length_plotters, rows, cols, textsize, labeller, hdi_prob, point_estimate, hdi_markers, outline, shade, n_data, data_labels, backend_kwargs, show, )
return ax
Bokeh density plot.
Bokeh density plot.
[ "Bokeh", "density", "plot", "." ]
def plot_density( ax, all_labels, to_plot, colors, bw, circular, figsize, length_plotters, rows, cols, textsize, labeller, hdi_prob, point_estimate, hdi_markers, outline, shade, n_data, data_labels, backend_kwargs, show, ): """Bokeh density plot.""" if backend_kwargs is None: backend_kwargs = {} backend_kwargs = { **backend_kwarg_defaults(), **backend_kwargs, } if colors == "cycle": colors = [ prop for _, prop in zip( range(n_data), cycle(plt.rcParams["axes.prop_cycle"].by_key()["color"]) ) ] elif isinstance(colors, str): colors = [colors for _ in range(n_data)] colors = vectorized_to_hex(colors) (figsize, _, _, _, line_width, markersize) = _scale_fig_size(figsize, textsize, rows, cols) if ax is None: ax = create_axes_grid( length_plotters, rows, cols, figsize=figsize, squeeze=False, backend_kwargs=backend_kwargs, ) else: ax = np.atleast_2d(ax) axis_map = { label: ax_ for label, ax_ in zip(all_labels, (item for item in ax.flatten() if item is not None)) } if data_labels is None: data_labels = {} legend_items = defaultdict(list) for m_idx, plotters in enumerate(to_plot): for var_name, selection, isel, values in plotters: label = labeller.make_label_vert(var_name, selection, isel) if data_labels: data_label = data_labels[m_idx] else: data_label = None plotted = _d_helper( values.flatten(), label, colors[m_idx], bw, circular, line_width, markersize, hdi_prob, point_estimate, hdi_markers, outline, shade, axis_map[label], ) if data_label is not None: legend_items[axis_map[label]].append((data_label, plotted)) for ax1, legend in legend_items.items(): legend = Legend( items=legend, location="center_right", orientation="horizontal", ) ax1.add_layout(legend, "above") ax1.legend.click_policy = "hide" show_layout(ax, show) return ax
[ "def", "plot_density", "(", "ax", ",", "all_labels", ",", "to_plot", ",", "colors", ",", "bw", ",", "circular", ",", "figsize", ",", "length_plotters", ",", "rows", ",", "cols", ",", "textsize", ",", "labeller", ",", "hdi_prob", ",", "point_estimate", ",",...
https://github.com/arviz-devs/arviz/blob/17b1a48b577ba9776a31e7e57a8a8af63e826901/arviz/plots/backends/bokeh/densityplot.py#L16-L119
androguard/androguard
8d091cbb309c0c50bf239f805cc1e0931b8dcddc
androguard/session.py
python
Session.show
(self)
Print information to stdout about the current session. Gets all APKs, all DEX files and all Analysis objects.
Print information to stdout about the current session. Gets all APKs, all DEX files and all Analysis objects.
[ "Print", "information", "to", "stdout", "about", "the", "current", "session", ".", "Gets", "all", "APKs", "all", "DEX", "files", "and", "all", "Analysis", "objects", "." ]
def show(self): """ Print information to stdout about the current session. Gets all APKs, all DEX files and all Analysis objects. """ print("APKs in Session: {}".format(len(self.analyzed_apk))) for d, a in self.analyzed_apk.items(): print("\t{}: {}".format(d, a)) print("DEXs in Session: {}".format(len(self.analyzed_dex))) for d, dex in self.analyzed_dex.items(): print("\t{}: {}".format(d, dex)) print("Analysis in Session: {}".format(len(self.analyzed_vms))) for d, a in self.analyzed_vms.items(): print("\t{}: {}".format(d, a))
[ "def", "show", "(", "self", ")", ":", "print", "(", "\"APKs in Session: {}\"", ".", "format", "(", "len", "(", "self", ".", "analyzed_apk", ")", ")", ")", "for", "d", ",", "a", "in", "self", ".", "analyzed_apk", ".", "items", "(", ")", ":", "print", ...
https://github.com/androguard/androguard/blob/8d091cbb309c0c50bf239f805cc1e0931b8dcddc/androguard/session.py#L166-L181
Lonero-Team/Decentralized-Internet
3cb157834fcc19ff8c2316e66bf07b103c137068
clusterpost/bigchaindb/bigchaindb/lib.py
python
BigchainDB.get_block
(self, block_id)
return result
Get the block with the specified `block_id`. Returns the block corresponding to `block_id` or None if no match is found. Args: block_id (int): block id of the block to get.
Get the block with the specified `block_id`.
[ "Get", "the", "block", "with", "the", "specified", "block_id", "." ]
def get_block(self, block_id): """Get the block with the specified `block_id`. Returns the block corresponding to `block_id` or None if no match is found. Args: block_id (int): block id of the block to get. """ block = backend.query.get_block(self.connection, block_id) latest_block = self.get_latest_block() latest_block_height = latest_block['height'] if latest_block else 0 if not block and block_id > latest_block_height: return result = {'height': block_id, 'transactions': []} if block: transactions = backend.query.get_transactions(self.connection, block['transactions']) result['transactions'] = [t.to_dict() for t in Transaction.from_db(self, transactions)] return result
[ "def", "get_block", "(", "self", ",", "block_id", ")", ":", "block", "=", "backend", ".", "query", ".", "get_block", "(", "self", ".", "connection", ",", "block_id", ")", "latest_block", "=", "self", ".", "get_latest_block", "(", ")", "latest_block_height", ...
https://github.com/Lonero-Team/Decentralized-Internet/blob/3cb157834fcc19ff8c2316e66bf07b103c137068/clusterpost/bigchaindb/bigchaindb/lib.py#L330-L354
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/ldap3/core/connection.py
python
Connection.search
(self, search_base, search_filter, search_scope=SUBTREE, dereference_aliases=DEREF_ALWAYS, attributes=None, size_limit=0, time_limit=0, types_only=False, get_operational_attributes=False, controls=None, paged_size=None, paged_criticality=False, paged_cookie=None, auto_escape=None)
Perform an ldap search: - If attributes is empty noRFC2696 with the specified size - If paged is 0 and cookie is present the search is abandoned on server attribute is returned - If attributes is ALL_ATTRIBUTES all attributes are returned - If paged_size is an int greater than 0 a simple paged search is tried as described in - Cookie is an opaque string received in the last paged search and must be used on the next paged search response - If lazy == True open and bind will be deferred until another LDAP operation is performed - If mssing_attributes == True then an attribute not returned by the server is set to None - If auto_escape is set it overrides the Connection auto_escape
Perform an ldap search:
[ "Perform", "an", "ldap", "search", ":" ]
def search(self, search_base, search_filter, search_scope=SUBTREE, dereference_aliases=DEREF_ALWAYS, attributes=None, size_limit=0, time_limit=0, types_only=False, get_operational_attributes=False, controls=None, paged_size=None, paged_criticality=False, paged_cookie=None, auto_escape=None): """ Perform an ldap search: - If attributes is empty noRFC2696 with the specified size - If paged is 0 and cookie is present the search is abandoned on server attribute is returned - If attributes is ALL_ATTRIBUTES all attributes are returned - If paged_size is an int greater than 0 a simple paged search is tried as described in - Cookie is an opaque string received in the last paged search and must be used on the next paged search response - If lazy == True open and bind will be deferred until another LDAP operation is performed - If mssing_attributes == True then an attribute not returned by the server is set to None - If auto_escape is set it overrides the Connection auto_escape """ conf_attributes_excluded_from_check = [v.lower() for v in get_config_parameter('ATTRIBUTES_EXCLUDED_FROM_CHECK')] if log_enabled(BASIC): log(BASIC, 'start SEARCH operation via <%s>', self) if self.check_names and search_base: search_base = safe_dn(search_base) if log_enabled(EXTENDED): log(EXTENDED, 'search base sanitized to <%s> for SEARCH operation via <%s>', search_base, self) with self.connection_lock: self._fire_deferred() if not attributes: attributes = [NO_ATTRIBUTES] elif attributes == ALL_ATTRIBUTES: attributes = [ALL_ATTRIBUTES] if isinstance(attributes, STRING_TYPES): attributes = [attributes] if get_operational_attributes and isinstance(attributes, list): attributes.append(ALL_OPERATIONAL_ATTRIBUTES) elif get_operational_attributes and isinstance(attributes, tuple): attributes += (ALL_OPERATIONAL_ATTRIBUTES, ) # concatenate tuple if isinstance(paged_size, int): if log_enabled(PROTOCOL): log(PROTOCOL, 'performing paged search for %d items with cookie <%s> for <%s>', paged_size, escape_bytes(paged_cookie), self) if controls is None: controls = [] else: # Copy the controls to prevent modifying the original object controls = list(controls) controls.append(paged_search_control(paged_criticality, paged_size, paged_cookie)) if self.server and self.server.schema and self.check_names: for attribute_name in attributes: if ';' in attribute_name: # remove tags attribute_name_to_check = attribute_name.split(';')[0] else: attribute_name_to_check = attribute_name if self.server.schema and attribute_name_to_check.lower() not in conf_attributes_excluded_from_check and attribute_name_to_check not in self.server.schema.attribute_types: raise LDAPAttributeError('invalid attribute type ' + attribute_name_to_check) request = search_operation(search_base, search_filter, search_scope, dereference_aliases, attributes, size_limit, time_limit, types_only, self.auto_escape if auto_escape is None else auto_escape, self.auto_encode, self.server.schema if self.server else None, validator=self.server.custom_validator, check_names=self.check_names) if log_enabled(PROTOCOL): log(PROTOCOL, 'SEARCH request <%s> sent via <%s>', search_request_to_dict(request), self) response = self.post_send_search(self.send('searchRequest', request, controls)) self._entries = [] if isinstance(response, int): # asynchronous strategy return_value = response if log_enabled(PROTOCOL): log(PROTOCOL, 'async SEARCH response id <%s> received via <%s>', return_value, self) else: return_value = True if self.result['type'] == 'searchResDone' and len(response) > 0 else False if not return_value and self.result['result'] not in [RESULT_SUCCESS] and not self.last_error: self.last_error = self.result['description'] if log_enabled(PROTOCOL): for entry in response: if entry['type'] == 'searchResEntry': log(PROTOCOL, 'SEARCH response entry <%s> received via <%s>', entry, self) elif entry['type'] == 'searchResRef': log(PROTOCOL, 'SEARCH response reference <%s> received via <%s>', entry, self) if log_enabled(BASIC): log(BASIC, 'done SEARCH operation, result <%s>', return_value) return return_value
[ "def", "search", "(", "self", ",", "search_base", ",", "search_filter", ",", "search_scope", "=", "SUBTREE", ",", "dereference_aliases", "=", "DEREF_ALWAYS", ",", "attributes", "=", "None", ",", "size_limit", "=", "0", ",", "time_limit", "=", "0", ",", "type...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/ldap3/core/connection.py#L729-L841
fluentpython/notebooks
0f6e1e8d1686743dacd9281df7c5b5921812010a
18-asyncio/spinner_thread.py
python
slow_function
()
return 42
[]
def slow_function(): # <7> # pretend waiting a long time for I/O time.sleep(3) # <8> return 42
[ "def", "slow_function", "(", ")", ":", "# <7>", "# pretend waiting a long time for I/O", "time", ".", "sleep", "(", "3", ")", "# <8>", "return", "42" ]
https://github.com/fluentpython/notebooks/blob/0f6e1e8d1686743dacd9281df7c5b5921812010a/18-asyncio/spinner_thread.py#L31-L34
Sense-X/TSD
fb1fdd7f14f3c136f4b849914977fae1d8d49398
mmdet/ops/roi_align/roi_align.py
python
RoIAlign.forward
(self, features, rois)
Args: features: NCHW images rois: Bx5 boxes. First column is the index into N. The other 4 columns are xyxy.
Args: features: NCHW images rois: Bx5 boxes. First column is the index into N. The other 4 columns are xyxy.
[ "Args", ":", "features", ":", "NCHW", "images", "rois", ":", "Bx5", "boxes", ".", "First", "column", "is", "the", "index", "into", "N", ".", "The", "other", "4", "columns", "are", "xyxy", "." ]
def forward(self, features, rois): """ Args: features: NCHW images rois: Bx5 boxes. First column is the index into N. The other 4 columns are xyxy. """ assert rois.dim() == 2 and rois.size(1) == 5 if self.use_torchvision: from torchvision.ops import roi_align as tv_roi_align return tv_roi_align( features, rois, self.out_size, self.spatial_scale, self.sample_num ) else: return roi_align( features, rois, self.out_size, self.spatial_scale, self.sample_num, self.aligned, )
[ "def", "forward", "(", "self", ",", "features", ",", "rois", ")", ":", "assert", "rois", ".", "dim", "(", ")", "==", "2", "and", "rois", ".", "size", "(", "1", ")", "==", "5", "if", "self", ".", "use_torchvision", ":", "from", "torchvision", ".", ...
https://github.com/Sense-X/TSD/blob/fb1fdd7f14f3c136f4b849914977fae1d8d49398/mmdet/ops/roi_align/roi_align.py#L142-L165
internetarchive/openlibrary
33b9b005ecb0adeda690c67952f5ae5f1fe3a8d8
openlibrary/core/models.py
python
User.get_loan_for
(self, ocaid)
Returns the loan object for given ocaid. Returns None if this user hasn't borrowed the given book.
Returns the loan object for given ocaid.
[ "Returns", "the", "loan", "object", "for", "given", "ocaid", "." ]
def get_loan_for(self, ocaid): """Returns the loan object for given ocaid. Returns None if this user hasn't borrowed the given book. """ from ..plugins.upstream import borrow loans = borrow.get_loans(self) for loan in loans: if ocaid == loan['ocaid']: return loan
[ "def", "get_loan_for", "(", "self", ",", "ocaid", ")", ":", "from", ".", ".", "plugins", ".", "upstream", "import", "borrow", "loans", "=", "borrow", ".", "get_loans", "(", "self", ")", "for", "loan", "in", "loans", ":", "if", "ocaid", "==", "loan", ...
https://github.com/internetarchive/openlibrary/blob/33b9b005ecb0adeda690c67952f5ae5f1fe3a8d8/openlibrary/core/models.py#L830-L840
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/visualize/owpythagorastree.py
python
OWPythagorasTree.invalidate_tree
(self)
When the tree needs to be completely recalculated.
When the tree needs to be completely recalculated.
[ "When", "the", "tree", "needs", "to", "be", "completely", "recalculated", "." ]
def invalidate_tree(self): """When the tree needs to be completely recalculated.""" if self.model is not None: self.ptree.set_tree( self.tree_adapter, weight_adjustment=self.SIZE_CALCULATION[self.size_calc_idx][1], target_class_index=self.target_class_index, ) self.ptree.set_depth_limit(self.depth_limit) self._update_main_area()
[ "def", "invalidate_tree", "(", "self", ")", ":", "if", "self", ".", "model", "is", "not", "None", ":", "self", ".", "ptree", ".", "set_tree", "(", "self", ".", "tree_adapter", ",", "weight_adjustment", "=", "self", ".", "SIZE_CALCULATION", "[", "self", "...
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/visualize/owpythagorastree.py#L236-L245
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/venv/lib/python3.7/site-packages/pip/_internal/req/req_file.py
python
join_lines
(lines_enum)
Joins a line ending in '\' with the previous line (except when following comments). The joined line takes on the index of the first line.
Joins a line ending in '\' with the previous line (except when following comments). The joined line takes on the index of the first line.
[ "Joins", "a", "line", "ending", "in", "\\", "with", "the", "previous", "line", "(", "except", "when", "following", "comments", ")", ".", "The", "joined", "line", "takes", "on", "the", "index", "of", "the", "first", "line", "." ]
def join_lines(lines_enum): # type: (ReqFileLines) -> ReqFileLines """Joins a line ending in '\' with the previous line (except when following comments). The joined line takes on the index of the first line. """ primary_line_number = None new_line = [] # type: List[Text] for line_number, line in lines_enum: if not line.endswith('\\') or COMMENT_RE.match(line): if COMMENT_RE.match(line): # this ensures comments are always matched later line = ' ' + line if new_line: new_line.append(line) yield primary_line_number, ''.join(new_line) new_line = [] else: yield line_number, line else: if not new_line: primary_line_number = line_number new_line.append(line.strip('\\')) # last line contains \ if new_line: yield primary_line_number, ''.join(new_line)
[ "def", "join_lines", "(", "lines_enum", ")", ":", "# type: (ReqFileLines) -> ReqFileLines", "primary_line_number", "=", "None", "new_line", "=", "[", "]", "# type: List[Text]", "for", "line_number", ",", "line", "in", "lines_enum", ":", "if", "not", "line", ".", "...
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/venv/lib/python3.7/site-packages/pip/_internal/req/req_file.py#L302-L327
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
medusa/providers/torrent/html/nordicbits.py
python
NordicBitsProvider.__init__
(self)
Initialize the class.
Initialize the class.
[ "Initialize", "the", "class", "." ]
def __init__(self): """Initialize the class.""" super(NordicBitsProvider, self).__init__('NordicBits') # Credentials self.username = None self.password = None # URLs self.url = 'https://nordicb.org' self.urls = { 'login': urljoin(self.url, 'takelogin.php'), 'search': urljoin(self.url, 'browse.php'), } # Proper Strings self.proper_strings = ['PROPER', 'REPACK', 'REAL', 'RERIP'] # Miscellaneous Options self.freeleech = False # Cache self.cache = tv.Cache(self)
[ "def", "__init__", "(", "self", ")", ":", "super", "(", "NordicBitsProvider", ",", "self", ")", ".", "__init__", "(", "'NordicBits'", ")", "# Credentials", "self", ".", "username", "=", "None", "self", ".", "password", "=", "None", "# URLs", "self", ".", ...
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/medusa/providers/torrent/html/nordicbits.py#L28-L50
TalwalkarLab/leaf
09ec454a5675e32e1f0546b456b77857fdece018
models/server.py
python
Server.update_model
(self)
[]
def update_model(self): total_weight = 0. base = [0] * len(self.updates[0][1]) for (client_samples, client_model) in self.updates: total_weight += client_samples for i, v in enumerate(client_model): base[i] += (client_samples * v.astype(np.float64)) averaged_soln = [v / total_weight for v in base] self.model = averaged_soln self.updates = []
[ "def", "update_model", "(", "self", ")", ":", "total_weight", "=", "0.", "base", "=", "[", "0", "]", "*", "len", "(", "self", ".", "updates", "[", "0", "]", "[", "1", "]", ")", "for", "(", "client_samples", ",", "client_model", ")", "in", "self", ...
https://github.com/TalwalkarLab/leaf/blob/09ec454a5675e32e1f0546b456b77857fdece018/models/server.py#L70-L80
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/op2/tables/oes_stressStrain/random/oes_solids.py
python
RandomSolidArray.build
(self)
sizes the vectorized attributes of the RealSolidArray
sizes the vectorized attributes of the RealSolidArray
[ "sizes", "the", "vectorized", "attributes", "of", "the", "RealSolidArray" ]
def build(self): """sizes the vectorized attributes of the RealSolidArray""" #print('ntimes=%s nelements=%s ntotal=%s' % (self.ntimes, self.nelements, self.ntotal)) assert self.ntimes > 0, 'ntimes=%s' % self.ntimes assert self.nelements > 0, 'nelements=%s' % self.nelements assert self.ntotal > 0, 'ntotal=%s' % self.ntotal #self.names = [] self.nelements //= self.ntimes self.itime = 0 self.ielement = 0 self.itotal = 0 #self.ntimes = 0 #self.nelements = 0 #print("ntimes=%s nelements=%s ntotal=%s" % (self.ntimes, self.nelements, self.ntotal)) dtype, idtype, fdtype = get_times_dtype(self.nonlinear_factor, self.size, self.analysis_fmt) if self.is_sort1: ntimes = self.ntimes nelements = self.nelements ntotal = self.ntotal else: nelements = self.ntimes ntimes = self.nelements ntotal = self.ntotal dtype = self._get_analysis_code_dtype() self._times = zeros(ntimes, dtype=dtype) # TODO: could be more efficient by using nelements for cid self.element_node = zeros((ntotal, 2), dtype='int32') self.element_cid = zeros((nelements, 2), dtype='int32') #if self.element_name == 'CTETRA': #nnodes = 4 #elif self.element_name == 'CPENTA': #nnodes = 6 #elif self.element_name == 'CHEXA': #nnodes = 8 #self.element_node = zeros((self.ntotal, nnodes, 2), 'int32') #[oxx, oyy, ozz, txy, tyz, txz] self.data = zeros((self.ntimes, self.ntotal, 6), 'float32') self.nnodes = self.element_node.shape[0] // self.nelements
[ "def", "build", "(", "self", ")", ":", "#print('ntimes=%s nelements=%s ntotal=%s' % (self.ntimes, self.nelements, self.ntotal))", "assert", "self", ".", "ntimes", ">", "0", ",", "'ntimes=%s'", "%", "self", ".", "ntimes", "assert", "self", ".", "nelements", ">", "0", ...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/op2/tables/oes_stressStrain/random/oes_solids.py#L38-L80
JimmXinu/FanFicFare
bc149a2deb2636320fe50a3e374af6eef8f61889
included_dependencies/idna/uts46data.py
python
_seg_70
()
return [ (0x1EC71, 'V'), (0x1ECB5, 'X'), (0x1ED01, 'V'), (0x1ED3E, 'X'), (0x1EE00, 'M', u'ا'), (0x1EE01, 'M', u'ب'), (0x1EE02, 'M', u'ج'), (0x1EE03, 'M', u'د'), (0x1EE04, 'X'), (0x1EE05, 'M', u'و'), (0x1EE06, 'M', u'ز'), (0x1EE07, 'M', u'ح'), (0x1EE08, 'M', u'ط'), (0x1EE09, 'M', u'ي'), (0x1EE0A, 'M', u'ك'), (0x1EE0B, 'M', u'ل'), (0x1EE0C, 'M', u'م'), (0x1EE0D, 'M', u'ن'), (0x1EE0E, 'M', u'س'), (0x1EE0F, 'M', u'ع'), (0x1EE10, 'M', u'ف'), (0x1EE11, 'M', u'ص'), (0x1EE12, 'M', u'ق'), (0x1EE13, 'M', u'ر'), (0x1EE14, 'M', u'ش'), (0x1EE15, 'M', u'ت'), (0x1EE16, 'M', u'ث'), (0x1EE17, 'M', u'خ'), (0x1EE18, 'M', u'ذ'), (0x1EE19, 'M', u'ض'), (0x1EE1A, 'M', u'ظ'), (0x1EE1B, 'M', u'غ'), (0x1EE1C, 'M', u'ٮ'), (0x1EE1D, 'M', u'ں'), (0x1EE1E, 'M', u'ڡ'), (0x1EE1F, 'M', u'ٯ'), (0x1EE20, 'X'), (0x1EE21, 'M', u'ب'), (0x1EE22, 'M', u'ج'), (0x1EE23, 'X'), (0x1EE24, 'M', u'ه'), (0x1EE25, 'X'), (0x1EE27, 'M', u'ح'), (0x1EE28, 'X'), (0x1EE29, 'M', u'ي'), (0x1EE2A, 'M', u'ك'), (0x1EE2B, 'M', u'ل'), (0x1EE2C, 'M', u'م'), (0x1EE2D, 'M', u'ن'), (0x1EE2E, 'M', u'س'), (0x1EE2F, 'M', u'ع'), (0x1EE30, 'M', u'ف'), (0x1EE31, 'M', u'ص'), (0x1EE32, 'M', u'ق'), (0x1EE33, 'X'), (0x1EE34, 'M', u'ش'), (0x1EE35, 'M', u'ت'), (0x1EE36, 'M', u'ث'), (0x1EE37, 'M', u'خ'), (0x1EE38, 'X'), (0x1EE39, 'M', u'ض'), (0x1EE3A, 'X'), (0x1EE3B, 'M', u'غ'), (0x1EE3C, 'X'), (0x1EE42, 'M', u'ج'), (0x1EE43, 'X'), (0x1EE47, 'M', u'ح'), (0x1EE48, 'X'), (0x1EE49, 'M', u'ي'), (0x1EE4A, 'X'), (0x1EE4B, 'M', u'ل'), (0x1EE4C, 'X'), (0x1EE4D, 'M', u'ن'), (0x1EE4E, 'M', u'س'), (0x1EE4F, 'M', u'ع'), (0x1EE50, 'X'), (0x1EE51, 'M', u'ص'), (0x1EE52, 'M', u'ق'), (0x1EE53, 'X'), (0x1EE54, 'M', u'ش'), (0x1EE55, 'X'), (0x1EE57, 'M', u'خ'), (0x1EE58, 'X'), (0x1EE59, 'M', u'ض'), (0x1EE5A, 'X'), (0x1EE5B, 'M', u'غ'), (0x1EE5C, 'X'), (0x1EE5D, 'M', u'ں'), (0x1EE5E, 'X'), (0x1EE5F, 'M', u'ٯ'), (0x1EE60, 'X'), (0x1EE61, 'M', u'ب'), (0x1EE62, 'M', u'ج'), (0x1EE63, 'X'), (0x1EE64, 'M', u'ه'), (0x1EE65, 'X'), (0x1EE67, 'M', u'ح'), (0x1EE68, 'M', u'ط'), (0x1EE69, 'M', u'ي'), (0x1EE6A, 'M', u'ك'), ]
[]
def _seg_70(): return [ (0x1EC71, 'V'), (0x1ECB5, 'X'), (0x1ED01, 'V'), (0x1ED3E, 'X'), (0x1EE00, 'M', u'ا'), (0x1EE01, 'M', u'ب'), (0x1EE02, 'M', u'ج'), (0x1EE03, 'M', u'د'), (0x1EE04, 'X'), (0x1EE05, 'M', u'و'), (0x1EE06, 'M', u'ز'), (0x1EE07, 'M', u'ح'), (0x1EE08, 'M', u'ط'), (0x1EE09, 'M', u'ي'), (0x1EE0A, 'M', u'ك'), (0x1EE0B, 'M', u'ل'), (0x1EE0C, 'M', u'م'), (0x1EE0D, 'M', u'ن'), (0x1EE0E, 'M', u'س'), (0x1EE0F, 'M', u'ع'), (0x1EE10, 'M', u'ف'), (0x1EE11, 'M', u'ص'), (0x1EE12, 'M', u'ق'), (0x1EE13, 'M', u'ر'), (0x1EE14, 'M', u'ش'), (0x1EE15, 'M', u'ت'), (0x1EE16, 'M', u'ث'), (0x1EE17, 'M', u'خ'), (0x1EE18, 'M', u'ذ'), (0x1EE19, 'M', u'ض'), (0x1EE1A, 'M', u'ظ'), (0x1EE1B, 'M', u'غ'), (0x1EE1C, 'M', u'ٮ'), (0x1EE1D, 'M', u'ں'), (0x1EE1E, 'M', u'ڡ'), (0x1EE1F, 'M', u'ٯ'), (0x1EE20, 'X'), (0x1EE21, 'M', u'ب'), (0x1EE22, 'M', u'ج'), (0x1EE23, 'X'), (0x1EE24, 'M', u'ه'), (0x1EE25, 'X'), (0x1EE27, 'M', u'ح'), (0x1EE28, 'X'), (0x1EE29, 'M', u'ي'), (0x1EE2A, 'M', u'ك'), (0x1EE2B, 'M', u'ل'), (0x1EE2C, 'M', u'م'), (0x1EE2D, 'M', u'ن'), (0x1EE2E, 'M', u'س'), (0x1EE2F, 'M', u'ع'), (0x1EE30, 'M', u'ف'), (0x1EE31, 'M', u'ص'), (0x1EE32, 'M', u'ق'), (0x1EE33, 'X'), (0x1EE34, 'M', u'ش'), (0x1EE35, 'M', u'ت'), (0x1EE36, 'M', u'ث'), (0x1EE37, 'M', u'خ'), (0x1EE38, 'X'), (0x1EE39, 'M', u'ض'), (0x1EE3A, 'X'), (0x1EE3B, 'M', u'غ'), (0x1EE3C, 'X'), (0x1EE42, 'M', u'ج'), (0x1EE43, 'X'), (0x1EE47, 'M', u'ح'), (0x1EE48, 'X'), (0x1EE49, 'M', u'ي'), (0x1EE4A, 'X'), (0x1EE4B, 'M', u'ل'), (0x1EE4C, 'X'), (0x1EE4D, 'M', u'ن'), (0x1EE4E, 'M', u'س'), (0x1EE4F, 'M', u'ع'), (0x1EE50, 'X'), (0x1EE51, 'M', u'ص'), (0x1EE52, 'M', u'ق'), (0x1EE53, 'X'), (0x1EE54, 'M', u'ش'), (0x1EE55, 'X'), (0x1EE57, 'M', u'خ'), (0x1EE58, 'X'), (0x1EE59, 'M', u'ض'), (0x1EE5A, 'X'), (0x1EE5B, 'M', u'غ'), (0x1EE5C, 'X'), (0x1EE5D, 'M', u'ں'), (0x1EE5E, 'X'), (0x1EE5F, 'M', u'ٯ'), (0x1EE60, 'X'), (0x1EE61, 'M', u'ب'), (0x1EE62, 'M', u'ج'), (0x1EE63, 'X'), (0x1EE64, 'M', u'ه'), (0x1EE65, 'X'), (0x1EE67, 'M', u'ح'), (0x1EE68, 'M', u'ط'), (0x1EE69, 'M', u'ي'), (0x1EE6A, 'M', u'ك'), ]
[ "def", "_seg_70", "(", ")", ":", "return", "[", "(", "0x1EC71", ",", "'V'", ")", ",", "(", "0x1ECB5", ",", "'X'", ")", ",", "(", "0x1ED01", ",", "'V'", ")", ",", "(", "0x1ED3E", ",", "'X'", ")", ",", "(", "0x1EE00", ",", "'M'", ",", "u'ا')", ...
https://github.com/JimmXinu/FanFicFare/blob/bc149a2deb2636320fe50a3e374af6eef8f61889/included_dependencies/idna/uts46data.py#L7288-L7390
shunyaoshih/TPA-LSTM
598cfc90f778856084f0ca80b463894e7ea26481
lib/model.py
python
PolyRNN._build_graph
(self)
[]
def _build_graph(self): logging.debug("Building graph") # rnn_inputs: [batch_size, max_len, input_size] # rnn_inputs_len: [batch_size] # target_outputs: [batch_size, max_len, output_size] self.rnn_inputs, self.rnn_inputs_len, self.target_outputs = self.data_generator.inputs( self.para.mode, self.para.batch_size) # rnn_inputs_embed: [batch_size, max_len, num_units] self.rnn_inputs_embed = tf.nn.relu( dense(self.rnn_inputs, self.para.num_units)) # all_rnn_states: [batch_size, max_len, num_units] # final_rnn_states: [LSTMStateTuple], len = num_layers # LSTMStateTuple: (c: [batch_size, num_units], # h: [batch_size, num_units]) self.rnn_inputs_embed = tf.unstack(self.rnn_inputs_embed, axis=1) self.all_rnn_states, self.final_rnn_states = tf.nn.static_rnn( cell=self._build_rnn_cell(), inputs=self.rnn_inputs_embed, sequence_length=self.rnn_inputs_len, dtype=self.dtype, ) # final_rnn_states: [batch_size, num_units] self.final_rnn_states = tf.concat( [self.final_rnn_states[i][1] for i in range(self.para.num_layers)], 1, ) # all_rnn_outputs: [batch_size, output_size] self.all_rnn_outputs = dense(self.final_rnn_states, self.para.output_size) if self.para.highway > 0: reg_outputs = tf.transpose( self.rnn_inputs[:, -self.para.highway:, :], [0, 2, 1]) reg_outputs = dense(reg_outputs, 1) self.all_rnn_outputs += tf.squeeze(reg_outputs) if self.para.mode == "train" or self.para.mode == "validation": self.labels = self.target_outputs[:, self.para.max_len - 1, :] self.loss = self._compute_loss( outputs=self.all_rnn_outputs, labels=self.labels) elif self.para.mode == "test": self.labels = self.target_outputs[:, self.para.max_len - 1, :] if not self.para.mts: self.all_rnn_outputs = tf.sigmoid(self.all_rnn_outputs)
[ "def", "_build_graph", "(", "self", ")", ":", "logging", ".", "debug", "(", "\"Building graph\"", ")", "# rnn_inputs: [batch_size, max_len, input_size]", "# rnn_inputs_len: [batch_size]", "# target_outputs: [batch_size, max_len, output_size]", "self", ".", "rnn_inputs", ",", "s...
https://github.com/shunyaoshih/TPA-LSTM/blob/598cfc90f778856084f0ca80b463894e7ea26481/lib/model.py#L20-L68
kamalgill/flask-appengine-template
11760f83faccbb0d0afe416fc58e67ecfb4643c2
src/lib/flask/app.py
python
Flask.handle_http_exception
(self, e)
return handler(e)
Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response. .. versionadded:: 0.3
Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response.
[ "Handles", "an", "HTTP", "exception", ".", "By", "default", "this", "will", "invoke", "the", "registered", "error", "handlers", "and", "fall", "back", "to", "returning", "the", "exception", "as", "response", "." ]
def handle_http_exception(self, e): """Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response. .. versionadded:: 0.3 """ # Proxy exceptions don't have error codes. We want to always return # those unchanged as errors if e.code is None: return e handler = self._find_error_handler(e) if handler is None: return e return handler(e)
[ "def", "handle_http_exception", "(", "self", ",", "e", ")", ":", "# Proxy exceptions don't have error codes. We want to always return", "# those unchanged as errors", "if", "e", ".", "code", "is", "None", ":", "return", "e", "handler", "=", "self", ".", "_find_error_ha...
https://github.com/kamalgill/flask-appengine-template/blob/11760f83faccbb0d0afe416fc58e67ecfb4643c2/src/lib/flask/app.py#L1456-L1471
Robot-Will/Stino
a94831cd1bf40a59587a7b6cc2e9b5c4306b1bf2
libs/serial/serialwin32.py
python
Serial._update_dtr_state
(self)
Set terminal status line: Data Terminal Ready
Set terminal status line: Data Terminal Ready
[ "Set", "terminal", "status", "line", ":", "Data", "Terminal", "Ready" ]
def _update_dtr_state(self): """Set terminal status line: Data Terminal Ready""" if self._dtr_state: win32.EscapeCommFunction(self._port_handle, win32.SETDTR) else: win32.EscapeCommFunction(self._port_handle, win32.CLRDTR)
[ "def", "_update_dtr_state", "(", "self", ")", ":", "if", "self", ".", "_dtr_state", ":", "win32", ".", "EscapeCommFunction", "(", "self", ".", "_port_handle", ",", "win32", ".", "SETDTR", ")", "else", ":", "win32", ".", "EscapeCommFunction", "(", "self", "...
https://github.com/Robot-Will/Stino/blob/a94831cd1bf40a59587a7b6cc2e9b5c4306b1bf2/libs/serial/serialwin32.py#L380-L385
Lapis-Hong/wide_deep
19d4b03daffc0778fa60f9b10ff6844c559dc126
python/train.py
python
dynamic_train
(model)
Dynamic train mode. For example: train_data_files: [0301, 0302, 0303, ...] train mode: first take 0301 as train data, 0302 as test data; then keep training take 0302 as train data, 0303 as test data ...
Dynamic train mode. For example: train_data_files: [0301, 0302, 0303, ...] train mode: first take 0301 as train data, 0302 as test data; then keep training take 0302 as train data, 0303 as test data ...
[ "Dynamic", "train", "mode", ".", "For", "example", ":", "train_data_files", ":", "[", "0301", "0302", "0303", "...", "]", "train", "mode", ":", "first", "take", "0301", "as", "train", "data", "0302", "as", "test", "data", ";", "then", "keep", "training",...
def dynamic_train(model): """Dynamic train mode. For example: train_data_files: [0301, 0302, 0303, ...] train mode: first take 0301 as train data, 0302 as test data; then keep training take 0302 as train data, 0303 as test data ... """ data_files = list_files(FLAGS.train_data) data_files.sort() assert len(data_files) > 1, 'Dynamic train mode need more than 1 data file' for i in range(len(data_files)-1): train_data = data_files[i] test_data = data_files[i+1] tf.logging.info('=' * 30 + ' START TRAINING DATA: {} '.format(train_data) + '=' * 30 + '\n') for n in range(FLAGS.train_epochs): t0 = time.time() tf.logging.info('START TRAIN DATA <{}> <EPOCH {}>'.format(train_data, n + 1)) model.train( input_fn=lambda: input_fn(train_data, FLAGS.image_train_data, 'train', FLAGS.batch_size), hooks=None, steps=None, max_steps=None, saving_listeners=None) tf.logging.info('FINISH TRAIN DATA <{}> <EPOCH {}> take {} mins'.format(train_data, n + 1, elapse_time(t0))) print('-' * 80) tf.logging.info('START EVALUATE TEST DATA <{}> <EPOCH {}>'.format(test_data, n + 1)) t0 = time.time() results = model.evaluate( input_fn=lambda: input_fn(test_data, FLAGS.image_eval_data, 'eval', FLAGS.batch_size), steps=None, # Number of steps for which to evaluate model. hooks=None, checkpoint_path=None, # latest checkpoint in model_dir is used. name=None) tf.logging.info('FINISH EVALUATE TEST DATA <{}> <EPOCH {}>: take {} mins'.format(test_data, n + 1, elapse_time(t0))) print('-' * 80) # Display evaluation metrics for key in sorted(results): print('{}: {}'.format(key, results[key]))
[ "def", "dynamic_train", "(", "model", ")", ":", "data_files", "=", "list_files", "(", "FLAGS", ".", "train_data", ")", "data_files", ".", "sort", "(", ")", "assert", "len", "(", "data_files", ")", ">", "1", ",", "'Dynamic train mode need more than 1 data file'",...
https://github.com/Lapis-Hong/wide_deep/blob/19d4b03daffc0778fa60f9b10ff6844c559dc126/python/train.py#L109-L148
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/notify/v1/service/binding.py
python
BindingList.list
(self, start_date=values.unset, end_date=values.unset, identity=values.unset, tag=values.unset, limit=None, page_size=None)
return list(self.stream( start_date=start_date, end_date=end_date, identity=identity, tag=tag, limit=limit, page_size=page_size, ))
Lists BindingInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param date start_date: Only include usage that has occurred on or after this date :param date end_date: Only include usage that occurred on or before this date :param list[unicode] identity: The `identity` value of the resources to read :param list[unicode] tag: Only list Bindings that have all of the specified Tags :param int limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param int page_size: Number of records to fetch per request, when not set will use the default value of 50 records. If no page_size is defined but a limit is defined, list() will attempt to read the limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results :rtype: list[twilio.rest.notify.v1.service.binding.BindingInstance]
Lists BindingInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning.
[ "Lists", "BindingInstance", "records", "from", "the", "API", "as", "a", "list", ".", "Unlike", "stream", "()", "this", "operation", "is", "eager", "and", "will", "load", "limit", "records", "into", "memory", "before", "returning", "." ]
def list(self, start_date=values.unset, end_date=values.unset, identity=values.unset, tag=values.unset, limit=None, page_size=None): """ Lists BindingInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param date start_date: Only include usage that has occurred on or after this date :param date end_date: Only include usage that occurred on or before this date :param list[unicode] identity: The `identity` value of the resources to read :param list[unicode] tag: Only list Bindings that have all of the specified Tags :param int limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param int page_size: Number of records to fetch per request, when not set will use the default value of 50 records. If no page_size is defined but a limit is defined, list() will attempt to read the limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results :rtype: list[twilio.rest.notify.v1.service.binding.BindingInstance] """ return list(self.stream( start_date=start_date, end_date=end_date, identity=identity, tag=tag, limit=limit, page_size=page_size, ))
[ "def", "list", "(", "self", ",", "start_date", "=", "values", ".", "unset", ",", "end_date", "=", "values", ".", "unset", ",", "identity", "=", "values", ".", "unset", ",", "tag", "=", "values", ".", "unset", ",", "limit", "=", "None", ",", "page_siz...
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/notify/v1/service/binding.py#L103-L131
clinton-hall/nzbToMedia
27669389216902d1085660167e7bda0bd8527ecf
libs/common/mutagen/_file.py
python
FileType.mime
(self)
return mimes
A list of mime types (:class:`mutagen.text`)
A list of mime types (:class:`mutagen.text`)
[ "A", "list", "of", "mime", "types", "(", ":", "class", ":", "mutagen", ".", "text", ")" ]
def mime(self): """A list of mime types (:class:`mutagen.text`)""" mimes = [] for Kind in type(self).__mro__: for mime in getattr(Kind, '_mimes', []): if mime not in mimes: mimes.append(mime) return mimes
[ "def", "mime", "(", "self", ")", ":", "mimes", "=", "[", "]", "for", "Kind", "in", "type", "(", "self", ")", ".", "__mro__", ":", "for", "mime", "in", "getattr", "(", "Kind", ",", "'_mimes'", ",", "[", "]", ")", ":", "if", "mime", "not", "in", ...
https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/mutagen/_file.py#L160-L168
KhronosGroup/NNEF-Tools
c913758ca687dab8cb7b49e8f1556819a2d0ca25
nnef_tools/io/tf/lite/writer.py
python
_ensure_numpy_array
(x, dtype)
[]
def _ensure_numpy_array(x, dtype): if isinstance(x, np.ndarray): assert x.dtype == dtype return x else: return np.array(x, dtype=dtype)
[ "def", "_ensure_numpy_array", "(", "x", ",", "dtype", ")", ":", "if", "isinstance", "(", "x", ",", "np", ".", "ndarray", ")", ":", "assert", "x", ".", "dtype", "==", "dtype", "return", "x", "else", ":", "return", "np", ".", "array", "(", "x", ",", ...
https://github.com/KhronosGroup/NNEF-Tools/blob/c913758ca687dab8cb7b49e8f1556819a2d0ca25/nnef_tools/io/tf/lite/writer.py#L80-L85
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_vendor/pyparsing.py
python
ZeroOrMore.__init__
( self, expr, stopOn=None)
[]
def __init__( self, expr, stopOn=None): super(ZeroOrMore,self).__init__(expr, stopOn=stopOn) self.mayReturnEmpty = True
[ "def", "__init__", "(", "self", ",", "expr", ",", "stopOn", "=", "None", ")", ":", "super", "(", "ZeroOrMore", ",", "self", ")", ".", "__init__", "(", "expr", ",", "stopOn", "=", "stopOn", ")", "self", ".", "mayReturnEmpty", "=", "True" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_vendor/pyparsing.py#L3913-L3915
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/Lacework/Integrations/Lacework/Lacework.py
python
create_entry
(title, data, ec, human_readable=None)
return { 'ContentsFormat': formats['json'], 'Type': entryTypes['note'], 'Contents': data, 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown(title, human_readable) if data else 'No result were found', 'EntryContext': ec }
Simplify the output/contents
Simplify the output/contents
[ "Simplify", "the", "output", "/", "contents" ]
def create_entry(title, data, ec, human_readable=None): """ Simplify the output/contents """ if human_readable is None: human_readable = data return { 'ContentsFormat': formats['json'], 'Type': entryTypes['note'], 'Contents': data, 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown(title, human_readable) if data else 'No result were found', 'EntryContext': ec }
[ "def", "create_entry", "(", "title", ",", "data", ",", "ec", ",", "human_readable", "=", "None", ")", ":", "if", "human_readable", "is", "None", ":", "human_readable", "=", "data", "return", "{", "'ContentsFormat'", ":", "formats", "[", "'json'", "]", ",",...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/Lacework/Integrations/Lacework/Lacework.py#L58-L73
mehulj94/BrainDamage
49a29c2606d5f7c0d9705ae5f4201a6bb25cfe73
eclipse.py
python
help
()
[]
def help(): bot.sendMessage(CHAT_ID, help_text)
[ "def", "help", "(", ")", ":", "bot", ".", "sendMessage", "(", "CHAT_ID", ",", "help_text", ")" ]
https://github.com/mehulj94/BrainDamage/blob/49a29c2606d5f7c0d9705ae5f4201a6bb25cfe73/eclipse.py#L264-L265
gusibi/python-weixin
db997152673b205966146b6aab304ba6e4755bec
weixin/helper.py
python
smart_bytes
(s, encoding="utf-8", strings_only=False, errors="strict")
return force_bytes(s, encoding, strings_only, errors)
Returns a bytestring version of 's', encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects.
Returns a bytestring version of 's', encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects.
[ "Returns", "a", "bytestring", "version", "of", "s", "encoded", "as", "specified", "in", "encoding", ".", "If", "strings_only", "is", "True", "don", "t", "convert", "(", "some", ")", "non", "-", "string", "-", "like", "objects", "." ]
def smart_bytes(s, encoding="utf-8", strings_only=False, errors="strict"): """ Returns a bytestring version of 's', encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, Promise): # The input is the result of a gettext_lazy() call. return s return force_bytes(s, encoding, strings_only, errors)
[ "def", "smart_bytes", "(", "s", ",", "encoding", "=", "\"utf-8\"", ",", "strings_only", "=", "False", ",", "errors", "=", "\"strict\"", ")", ":", "if", "isinstance", "(", "s", ",", "Promise", ")", ":", "# The input is the result of a gettext_lazy() call.", "retu...
https://github.com/gusibi/python-weixin/blob/db997152673b205966146b6aab304ba6e4755bec/weixin/helper.py#L165-L173
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/django/forms/widgets.py
python
Select.use_required_attribute
(self, initial)
return use_required_attribute and first_choice is not None and self._choice_has_empty_value(first_choice)
Don't render 'required' if the first <option> has a value, as that's invalid HTML.
Don't render 'required' if the first <option> has a value, as that's invalid HTML.
[ "Don", "t", "render", "required", "if", "the", "first", "<option", ">", "has", "a", "value", "as", "that", "s", "invalid", "HTML", "." ]
def use_required_attribute(self, initial): """ Don't render 'required' if the first <option> has a value, as that's invalid HTML. """ use_required_attribute = super(Select, self).use_required_attribute(initial) # 'required' is always okay for <select multiple>. if self.allow_multiple_selected: return use_required_attribute first_choice = next(iter(self.choices), None) return use_required_attribute and first_choice is not None and self._choice_has_empty_value(first_choice)
[ "def", "use_required_attribute", "(", "self", ",", "initial", ")", ":", "use_required_attribute", "=", "super", "(", "Select", ",", "self", ")", ".", "use_required_attribute", "(", "initial", ")", "# 'required' is always okay for <select multiple>.", "if", "self", "."...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/forms/widgets.py#L679-L690
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/client/grr_response_client/comms.py
python
ClientCommunicator.InitPrivateKey
(self)
return key
Makes sure this client has a private key set. It first tries to load an RSA key from the certificate. If no certificate is found, or it is invalid, we make a new random RSA key, and store it as our certificate. Returns: An RSA key - either from the certificate or a new random key.
Makes sure this client has a private key set.
[ "Makes", "sure", "this", "client", "has", "a", "private", "key", "set", "." ]
def InitPrivateKey(self): """Makes sure this client has a private key set. It first tries to load an RSA key from the certificate. If no certificate is found, or it is invalid, we make a new random RSA key, and store it as our certificate. Returns: An RSA key - either from the certificate or a new random key. """ if self.private_key: try: self.common_name = rdf_client.ClientURN.FromPrivateKey(self.private_key) logging.info("Starting client %s", self.common_name) return self.private_key except type_info.TypeValueError: pass # We either have an invalid key or no key. We just generate a new one. key = rdf_crypto.RSAPrivateKey.GenerateKey( bits=config.CONFIG["Client.rsa_key_length"]) self.common_name = rdf_client.ClientURN.FromPrivateKey(key) logging.info("Client pending enrolment %s", self.common_name) # Save the keys self.SavePrivateKey(key) return key
[ "def", "InitPrivateKey", "(", "self", ")", ":", "if", "self", ".", "private_key", ":", "try", ":", "self", ".", "common_name", "=", "rdf_client", ".", "ClientURN", ".", "FromPrivateKey", "(", "self", ".", "private_key", ")", "logging", ".", "info", "(", ...
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/client/grr_response_client/comms.py#L1311-L1343
jopohl/urh
9a7836698b8156687c0ed2d16f56d653cb847c22
src/urh/controller/dialogs/ProjectDialog.py
python
ProjectDialog.participants
(self)
return self.participant_table_model.participants
:rtype: list of Participant
[]
def participants(self): """ :rtype: list of Participant """ return self.participant_table_model.participants
[ "def", "participants", "(", "self", ")", ":", "return", "self", ".", "participant_table_model", ".", "participants" ]
https://github.com/jopohl/urh/blob/9a7836698b8156687c0ed2d16f56d653cb847c22/src/urh/controller/dialogs/ProjectDialog.py#L81-L86
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/objc/_properties.py
python
set_proxy.remove
(self, item)
[]
def remove(self, item): if self._ro: raise ValueError("Property '%s' is read-only"%(self._name,)) self._parent.willChangeValueForKey_withSetMutation_usingObjects_( self._name, NSKeyValueMinusSetMutation, set([item]) ) try: self._wrapped.remove(item) finally: self._parent.didChangeValueForKey_withSetMutation_usingObjects_( self._name, NSKeyValueMinusSetMutation, set([item]) )
[ "def", "remove", "(", "self", ",", "item", ")", ":", "if", "self", ".", "_ro", ":", "raise", "ValueError", "(", "\"Property '%s' is read-only\"", "%", "(", "self", ".", "_name", ",", ")", ")", "self", ".", "_parent", ".", "willChangeValueForKey_withSetMutati...
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/objc/_properties.py#L900-L917
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
win32_event_log/datadog_checks/win32_event_log/legacy/win32_event_log.py
python
Win32EventLogWMI.__init__
(self, name, init_config, instances)
[]
def __init__(self, name, init_config, instances): super(Win32EventLogWMI, self).__init__(name, init_config, instances) # Settings self._tag_event_id = is_affirmative(self.instance.get('tag_event_id', init_config.get('tag_event_id'))) self._verbose = init_config.get('verbose', True) self._default_event_priority = init_config.get('default_event_priority', 'normal') # State self.last_ts = {} self.check_initializations.append( lambda: self.warning( 'This version of the check is deprecated and will be removed in a future release. ' 'Set `legacy_mode` to `false` and read about the latest options, such as `query`.' ) ) for new_param in self.NEW_PARAMS: if new_param in self.instance: self.log.warning("%s config option is ignored when running legacy mode. Please remove it", new_param)
[ "def", "__init__", "(", "self", ",", "name", ",", "init_config", ",", "instances", ")", ":", "super", "(", "Win32EventLogWMI", ",", "self", ")", ".", "__init__", "(", "name", ",", "init_config", ",", "instances", ")", "# Settings", "self", ".", "_tag_event...
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/win32_event_log/datadog_checks/win32_event_log/legacy/win32_event_log.py#L43-L61
santhoshkolloju/Abstractive-Summarization-With-Transfer-Learning
97ff2ae3ba9f2d478e174444c4e0f5349f28c319
texar_repo/examples/transformer/bleu_tool.py
python
bleu_tokenize
(string)
return string.split()
r"""Tokenize a string following the official BLEU implementation. See https://github.com/moses-smt/mosesdecoder/" "blob/master/scripts/generic/mteval-v14.pl#L954-L983 In our case, the input string is expected to be just one line and no HTML entities de-escaping is needed. So we just tokenize on punctuation and symbols, except when a punctuation is preceded and followed by a digit (e.g. a comma/dot as a thousand/decimal separator). Note that a numer (e.g. a year) followed by a dot at the end of sentence is NOT tokenized, i.e. the dot stays with the number because `s/(\p{P})(\P{N})/ $1 $2/g` does not match this case (unless we add a space after each sentence). However, this error is already in the original mteval-v14.pl and we want to be consistent with it. Args: string: the input string Returns: a list of tokens
r"""Tokenize a string following the official BLEU implementation.
[ "r", "Tokenize", "a", "string", "following", "the", "official", "BLEU", "implementation", "." ]
def bleu_tokenize(string): r"""Tokenize a string following the official BLEU implementation. See https://github.com/moses-smt/mosesdecoder/" "blob/master/scripts/generic/mteval-v14.pl#L954-L983 In our case, the input string is expected to be just one line and no HTML entities de-escaping is needed. So we just tokenize on punctuation and symbols, except when a punctuation is preceded and followed by a digit (e.g. a comma/dot as a thousand/decimal separator). Note that a numer (e.g. a year) followed by a dot at the end of sentence is NOT tokenized, i.e. the dot stays with the number because `s/(\p{P})(\P{N})/ $1 $2/g` does not match this case (unless we add a space after each sentence). However, this error is already in the original mteval-v14.pl and we want to be consistent with it. Args: string: the input string Returns: a list of tokens """ string = uregex.nondigit_punct_re.sub(r"\1 \2 ", string) string = uregex.punct_nondigit_re.sub(r" \1 \2", string) string = uregex.symbol_re.sub(r" \1 ", string) return string.split()
[ "def", "bleu_tokenize", "(", "string", ")", ":", "string", "=", "uregex", ".", "nondigit_punct_re", ".", "sub", "(", "r\"\\1 \\2 \"", ",", "string", ")", "string", "=", "uregex", ".", "punct_nondigit_re", ".", "sub", "(", "r\" \\1 \\2\"", ",", "string", ")",...
https://github.com/santhoshkolloju/Abstractive-Summarization-With-Transfer-Learning/blob/97ff2ae3ba9f2d478e174444c4e0f5349f28c319/texar_repo/examples/transformer/bleu_tool.py#L160-L187
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/idlelib/RemoteDebugger.py
python
IdbAdapter.frame_globals
(self, fid)
return did
[]
def frame_globals(self, fid): frame = frametable[fid] dict = frame.f_globals did = id(dict) dicttable[did] = dict return did
[ "def", "frame_globals", "(", "self", ",", "fid", ")", ":", "frame", "=", "frametable", "[", "fid", "]", "dict", "=", "frame", ".", "f_globals", "did", "=", "id", "(", "dict", ")", "dicttable", "[", "did", "]", "=", "dict", "return", "did" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/idlelib/RemoteDebugger.py#L127-L132
uqfoundation/multiprocess
028cc73f02655e6451d92e5147d19d8c10aebe50
py3.11/multiprocess/context.py
python
BaseContext.reducer
(self)
return globals().get('reduction')
Controls how objects will be reduced to a form that can be shared with other processes.
Controls how objects will be reduced to a form that can be shared with other processes.
[ "Controls", "how", "objects", "will", "be", "reduced", "to", "a", "form", "that", "can", "be", "shared", "with", "other", "processes", "." ]
def reducer(self): '''Controls how objects will be reduced to a form that can be shared with other processes.''' return globals().get('reduction')
[ "def", "reducer", "(", "self", ")", ":", "return", "globals", "(", ")", ".", "get", "(", "'reduction'", ")" ]
https://github.com/uqfoundation/multiprocess/blob/028cc73f02655e6451d92e5147d19d8c10aebe50/py3.11/multiprocess/context.py#L204-L207
PaddlePaddle/models
511e2e282960ed4c7440c3f1d1e62017acb90e11
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/utils.py
python
SmoothedValue.max
(self)
return max(self.deque)
[]
def max(self): return max(self.deque)
[ "def", "max", "(", "self", ")", ":", "return", "max", "(", "self", ".", "deque", ")" ]
https://github.com/PaddlePaddle/models/blob/511e2e282960ed4c7440c3f1d1e62017acb90e11/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/utils.py#L60-L61
esdalmaijer/markovbot
24f44ba0e9ed29de374be02efeea18a9badd5394
markovbot/markovbot35.py
python
MarkovBot._check_file
(self, filename, allowedext=None)
return ok
Checks whether a file exists, and has a certain extension. Arguments filename - String that indicates the path to a .txt file that should be read by the bot. Keyword Arguments allowedext - List of allowed extensions, or None to allow all extensions. Default value is None. Returns ok - Boolean that indicates whether the file exists, andhas an allowed extension (True), or does not (False)
Checks whether a file exists, and has a certain extension. Arguments filename - String that indicates the path to a .txt file that should be read by the bot. Keyword Arguments allowedext - List of allowed extensions, or None to allow all extensions. Default value is None. Returns ok - Boolean that indicates whether the file exists, andhas an allowed extension (True), or does not (False)
[ "Checks", "whether", "a", "file", "exists", "and", "has", "a", "certain", "extension", ".", "Arguments", "filename", "-", "String", "that", "indicates", "the", "path", "to", "a", ".", "txt", "file", "that", "should", "be", "read", "by", "the", "bot", "."...
def _check_file(self, filename, allowedext=None): """Checks whether a file exists, and has a certain extension. Arguments filename - String that indicates the path to a .txt file that should be read by the bot. Keyword Arguments allowedext - List of allowed extensions, or None to allow all extensions. Default value is None. Returns ok - Boolean that indicates whether the file exists, andhas an allowed extension (True), or does not (False) """ # Check whether the file exists ok = os.path.isfile(filename) # Check whether the extension is allowed if allowedext != None: name, ext = os.path.splitext(filename) if ext not in allowedext: ok = False return ok
[ "def", "_check_file", "(", "self", ",", "filename", ",", "allowedext", "=", "None", ")", ":", "# Check whether the file exists", "ok", "=", "os", ".", "path", ".", "isfile", "(", "filename", ")", "# Check whether the extension is allowed", "if", "allowedext", "!="...
https://github.com/esdalmaijer/markovbot/blob/24f44ba0e9ed29de374be02efeea18a9badd5394/markovbot/markovbot35.py#L1240-L1270
fab-jul/L3C-PyTorch
469d43b74583976895923138145e0bf4436e5dc9
src/criterion/logistic_mixture.py
python
DiscretizedMixLogisticLoss.__init__
(self, rgb_scale: bool, x_min=0, x_max=255, L=256)
:param rgb_scale: Whether this is the loss for the RGB scale. In that case, use_coeffs=True _num_params=_NUM_PARAMS_RGB == 4, since we predict coefficients lambda. See note above. :param x_min: minimum value in targets x :param x_max: maximum value in targets x :param L: number of symbols
:param rgb_scale: Whether this is the loss for the RGB scale. In that case, use_coeffs=True _num_params=_NUM_PARAMS_RGB == 4, since we predict coefficients lambda. See note above. :param x_min: minimum value in targets x :param x_max: maximum value in targets x :param L: number of symbols
[ ":", "param", "rgb_scale", ":", "Whether", "this", "is", "the", "loss", "for", "the", "RGB", "scale", ".", "In", "that", "case", "use_coeffs", "=", "True", "_num_params", "=", "_NUM_PARAMS_RGB", "==", "4", "since", "we", "predict", "coefficients", "lambda", ...
def __init__(self, rgb_scale: bool, x_min=0, x_max=255, L=256): """ :param rgb_scale: Whether this is the loss for the RGB scale. In that case, use_coeffs=True _num_params=_NUM_PARAMS_RGB == 4, since we predict coefficients lambda. See note above. :param x_min: minimum value in targets x :param x_max: maximum value in targets x :param L: number of symbols """ super(DiscretizedMixLogisticLoss, self).__init__() self.rgb_scale = rgb_scale self.x_min = x_min self.x_max = x_max self.L = L # whether to use coefficients lambda to weight means depending on previously outputed means. self.use_coeffs = rgb_scale # P means number of different variables contained in l, l means output of network self._num_params = _NUM_PARAMS_RGB if rgb_scale else _NUM_PARAMS_OTHER # NOTE: in contrast to the original code, we use a sigmoid (instead of a tanh) # The optimizer seems to not care, but it would probably be more principaled to use a tanh # Compare with L55 here: https://github.com/openai/pixel-cnn/blob/master/pixel_cnn_pp/nn.py#L55 self._nonshared_coeffs_act = torch.sigmoid # Adapted bounds for our case. self.bin_width = (x_max - x_min) / (L-1) self.x_lower_bound = x_min + 0.001 self.x_upper_bound = x_max - 0.001 self._extra_repr = 'DMLL: x={}, L={}, coeffs={}, P={}, bin_width={}'.format( (self.x_min, self.x_max), self.L, self.use_coeffs, self._num_params, self.bin_width)
[ "def", "__init__", "(", "self", ",", "rgb_scale", ":", "bool", ",", "x_min", "=", "0", ",", "x_max", "=", "255", ",", "L", "=", "256", ")", ":", "super", "(", "DiscretizedMixLogisticLoss", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "...
https://github.com/fab-jul/L3C-PyTorch/blob/469d43b74583976895923138145e0bf4436e5dc9/src/criterion/logistic_mixture.py#L88-L118
robotframework/RIDE
6e8a50774ff33dead3a2757a11b0b4418ab205c0
src/robotide/lib/robot/libraries/Telnet.py
python
TelnetConnection.set_prompt
(self, prompt, prompt_is_regexp=False)
return old
Sets the prompt used by `Read Until Prompt` and `Login` in the current connection. If ``prompt_is_regexp`` is given a true value (see `Boolean arguments`), the given ``prompt`` is considered to be a regular expression. The old prompt is returned and can be used to restore the prompt later. Example: | ${prompt} | ${regexp} = | `Set Prompt` | $ | | `Do Something` | | `Set Prompt` | ${prompt} | ${regexp} | See the documentation of [http://docs.python.org/library/re.html|Python re module] for more information about the supported regular expression syntax. Notice that possible backslashes need to be escaped in Robot Framework test data. See `Configuration` section for more information about global and connection specific configuration.
Sets the prompt used by `Read Until Prompt` and `Login` in the current connection.
[ "Sets", "the", "prompt", "used", "by", "Read", "Until", "Prompt", "and", "Login", "in", "the", "current", "connection", "." ]
def set_prompt(self, prompt, prompt_is_regexp=False): """Sets the prompt used by `Read Until Prompt` and `Login` in the current connection. If ``prompt_is_regexp`` is given a true value (see `Boolean arguments`), the given ``prompt`` is considered to be a regular expression. The old prompt is returned and can be used to restore the prompt later. Example: | ${prompt} | ${regexp} = | `Set Prompt` | $ | | `Do Something` | | `Set Prompt` | ${prompt} | ${regexp} | See the documentation of [http://docs.python.org/library/re.html|Python re module] for more information about the supported regular expression syntax. Notice that possible backslashes need to be escaped in Robot Framework test data. See `Configuration` section for more information about global and connection specific configuration. """ self._verify_connection() old = self._prompt self._set_prompt(prompt, prompt_is_regexp) if old[1]: return old[0].pattern, True return old
[ "def", "set_prompt", "(", "self", ",", "prompt", ",", "prompt_is_regexp", "=", "False", ")", ":", "self", ".", "_verify_connection", "(", ")", "old", "=", "self", ".", "_prompt", "self", ".", "_set_prompt", "(", "prompt", ",", "prompt_is_regexp", ")", "if"...
https://github.com/robotframework/RIDE/blob/6e8a50774ff33dead3a2757a11b0b4418ab205c0/src/robotide/lib/robot/libraries/Telnet.py#L574-L601
vsjha18/nsetools
b0e99c8decac0cba0bc19427428fd2d7b8836eaf
nse.py
python
Nse.nse_opener
(self)
return build_opener(HTTPCookieProcessor(cj))
builds opener for urllib2 :return: opener object
builds opener for urllib2 :return: opener object
[ "builds", "opener", "for", "urllib2", ":", "return", ":", "opener", "object" ]
def nse_opener(self): """ builds opener for urllib2 :return: opener object """ cj = CookieJar() return build_opener(HTTPCookieProcessor(cj))
[ "def", "nse_opener", "(", "self", ")", ":", "cj", "=", "CookieJar", "(", ")", "return", "build_opener", "(", "HTTPCookieProcessor", "(", "cj", ")", ")" ]
https://github.com/vsjha18/nsetools/blob/b0e99c8decac0cba0bc19427428fd2d7b8836eaf/nse.py#L363-L369
ronreiter/interactive-tutorials
d026d1ae58941863d60eb30a8a94a8650d2bd4bf
suds/sax/element.py
python
PrefixNormalizer.genPrefixes
(self)
return prefixes
Generate a I{reverse} mapping of unique prefixes for all namespaces. @return: A referse dict of prefixes. @rtype: {u, p}
Generate a I{reverse} mapping of unique prefixes for all namespaces.
[ "Generate", "a", "I", "{", "reverse", "}", "mapping", "of", "unique", "prefixes", "for", "all", "namespaces", "." ]
def genPrefixes(self): """ Generate a I{reverse} mapping of unique prefixes for all namespaces. @return: A referse dict of prefixes. @rtype: {u, p} """ prefixes = {} n = 0 for u in self.namespaces: p = 'ns%d' % n prefixes[u] = p n += 1 return prefixes
[ "def", "genPrefixes", "(", "self", ")", ":", "prefixes", "=", "{", "}", "n", "=", "0", "for", "u", "in", "self", ".", "namespaces", ":", "p", "=", "'ns%d'", "%", "n", "prefixes", "[", "u", "]", "=", "p", "n", "+=", "1", "return", "prefixes" ]
https://github.com/ronreiter/interactive-tutorials/blob/d026d1ae58941863d60eb30a8a94a8650d2bd4bf/suds/sax/element.py#L1050-L1062
openstack/cinder
23494a6d6c51451688191e1847a458f1d3cdcaa5
cinder/volume/drivers/dell_emc/powermax/common.py
python
PowerMaxCommon._check_and_add_tags_to_storage_array
( self, serial_number, array_tag_list, extra_specs)
Add tags to a storage group. :param serial_number: the array serial number :param array_tag_list: the array tag list :param extra_specs: the extra specifications
Add tags to a storage group.
[ "Add", "tags", "to", "a", "storage", "group", "." ]
def _check_and_add_tags_to_storage_array( self, serial_number, array_tag_list, extra_specs): """Add tags to a storage group. :param serial_number: the array serial number :param array_tag_list: the array tag list :param extra_specs: the extra specifications """ if array_tag_list: existing_array_tags = self.rest.get_array_tags(serial_number) new_tag_list = self.utils.get_new_tags( self.utils.convert_list_to_string(array_tag_list), self.utils.convert_list_to_string(existing_array_tags)) if not new_tag_list: LOG.warning("No new tags to add. Existing tags " "associated with %(array)s are " "%(tags)s.", {'array': serial_number, 'tags': existing_array_tags}) else: self._validate_array_tag_list(new_tag_list) LOG.info("Adding the tags %(tag_list)s to %(array)s", {'tag_list': new_tag_list, 'array': serial_number}) try: self.rest.add_storage_array_tags( serial_number, new_tag_list, extra_specs) except Exception as ex: LOG.warning("Unexpected error: %(ex)s. If you still " "want to add tags to this storage array, " "please do so on the Unisphere UI.", {'ex': ex})
[ "def", "_check_and_add_tags_to_storage_array", "(", "self", ",", "serial_number", ",", "array_tag_list", ",", "extra_specs", ")", ":", "if", "array_tag_list", ":", "existing_array_tags", "=", "self", ".", "rest", ".", "get_array_tags", "(", "serial_number", ")", "ne...
https://github.com/openstack/cinder/blob/23494a6d6c51451688191e1847a458f1d3cdcaa5/cinder/volume/drivers/dell_emc/powermax/common.py#L7272-L7304
django/django
0a17666045de6739ae1c2ac695041823d5f827f7
django/contrib/gis/gdal/srs.py
python
SpatialReference.projected
(self)
return bool(capi.isprojected(self.ptr))
Return True if this SpatialReference is a projected coordinate system (root node is PROJCS).
Return True if this SpatialReference is a projected coordinate system (root node is PROJCS).
[ "Return", "True", "if", "this", "SpatialReference", "is", "a", "projected", "coordinate", "system", "(", "root", "node", "is", "PROJCS", ")", "." ]
def projected(self): """ Return True if this SpatialReference is a projected coordinate system (root node is PROJCS). """ return bool(capi.isprojected(self.ptr))
[ "def", "projected", "(", "self", ")", ":", "return", "bool", "(", "capi", ".", "isprojected", "(", "self", ".", "ptr", ")", ")" ]
https://github.com/django/django/blob/0a17666045de6739ae1c2ac695041823d5f827f7/django/contrib/gis/gdal/srs.py#L286-L291
out0fmemory/GoAgent-Always-Available
c4254984fea633ce3d1893fe5901debd9f22c2a9
server/lib/google/appengine/_internal/antlr3/recognizers.py
python
Lexer.emit
(self, token=None)
return token
The standard method called to automatically emit a token at the outermost lexical rule. The token object should point into the char buffer start..stop. If there is a text override in 'text', use that to set the token's text. Override this method to emit custom Token objects. If you are building trees, then you should also override Parser or TreeParser.getMissingSymbol().
The standard method called to automatically emit a token at the outermost lexical rule. The token object should point into the char buffer start..stop. If there is a text override in 'text', use that to set the token's text. Override this method to emit custom Token objects.
[ "The", "standard", "method", "called", "to", "automatically", "emit", "a", "token", "at", "the", "outermost", "lexical", "rule", ".", "The", "token", "object", "should", "point", "into", "the", "char", "buffer", "start", "..", "stop", ".", "If", "there", "...
def emit(self, token=None): """ The standard method called to automatically emit a token at the outermost lexical rule. The token object should point into the char buffer start..stop. If there is a text override in 'text', use that to set the token's text. Override this method to emit custom Token objects. If you are building trees, then you should also override Parser or TreeParser.getMissingSymbol(). """ if token is None: token = CommonToken( input=self.input, type=self._state.type, channel=self._state.channel, start=self._state.tokenStartCharIndex, stop=self.getCharIndex()-1 ) token.line = self._state.tokenStartLine token.text = self._state.text token.charPositionInLine = self._state.tokenStartCharPositionInLine self._state.token = token return token
[ "def", "emit", "(", "self", ",", "token", "=", "None", ")", ":", "if", "token", "is", "None", ":", "token", "=", "CommonToken", "(", "input", "=", "self", ".", "input", ",", "type", "=", "self", ".", "_state", ".", "type", ",", "channel", "=", "s...
https://github.com/out0fmemory/GoAgent-Always-Available/blob/c4254984fea633ce3d1893fe5901debd9f22c2a9/server/lib/google/appengine/_internal/antlr3/recognizers.py#L1169-L1195
PyHDI/veriloggen
2382d200deabf59cfcfd741f5eba371010aaf2bb
veriloggen/stream/stream.py
python
Stream.to_module
(self, name, clock='CLK', reset='RST', aswire=False, seq_name=None)
return m
generate a Module definion
generate a Module definion
[ "generate", "a", "Module", "definion" ]
def to_module(self, name, clock='CLK', reset='RST', aswire=False, seq_name=None): """ generate a Module definion """ m = Module(name) clk = m.Input(clock) rst = m.Input(reset) m = self.implement(m, clk, rst, aswire=aswire, seq_name=seq_name) return m
[ "def", "to_module", "(", "self", ",", "name", ",", "clock", "=", "'CLK'", ",", "reset", "=", "'RST'", ",", "aswire", "=", "False", ",", "seq_name", "=", "None", ")", ":", "m", "=", "Module", "(", "name", ")", "clk", "=", "m", ".", "Input", "(", ...
https://github.com/PyHDI/veriloggen/blob/2382d200deabf59cfcfd741f5eba371010aaf2bb/veriloggen/stream/stream.py#L129-L138
flan/staticdhcpd
40ef788908beb9355aa06cabd5ff628a577d8595
libpydhcpserver/libpydhcpserver/dhcp_types/conversion.py
python
ipsToList
(ips)
return output
Converts a IPv4 addresses into a flat list of multiples of four bytes in big-endian order. :param list ips: A list of any valid IPv4 formats (string, 32-bit integer, list of bytes, :class:`IPv4 <dhcp_types.IPv4>`). :return list: The converted addresses. :except ValueError: The IPs could not be processed.
Converts a IPv4 addresses into a flat list of multiples of four bytes in big-endian order. :param list ips: A list of any valid IPv4 formats (string, 32-bit integer, list of bytes, :class:`IPv4 <dhcp_types.IPv4>`). :return list: The converted addresses. :except ValueError: The IPs could not be processed.
[ "Converts", "a", "IPv4", "addresses", "into", "a", "flat", "list", "of", "multiples", "of", "four", "bytes", "in", "big", "-", "endian", "order", ".", ":", "param", "list", "ips", ":", "A", "list", "of", "any", "valid", "IPv4", "formats", "(", "string"...
def ipsToList(ips): """ Converts a IPv4 addresses into a flat list of multiples of four bytes in big-endian order. :param list ips: A list of any valid IPv4 formats (string, 32-bit integer, list of bytes, :class:`IPv4 <dhcp_types.IPv4>`). :return list: The converted addresses. :except ValueError: The IPs could not be processed. """ if isinstance(ips, str): tokens = ips.split(',') elif isinstance(ips, bytes): tokens = ips.split(b',') else: tokens = ips output = [] for ip in tokens: output += ipToList(ip) return output
[ "def", "ipsToList", "(", "ips", ")", ":", "if", "isinstance", "(", "ips", ",", "str", ")", ":", "tokens", "=", "ips", ".", "split", "(", "','", ")", "elif", "isinstance", "(", "ips", ",", "bytes", ")", ":", "tokens", "=", "ips", ".", "split", "("...
https://github.com/flan/staticdhcpd/blob/40ef788908beb9355aa06cabd5ff628a577d8595/libpydhcpserver/libpydhcpserver/dhcp_types/conversion.py#L232-L252
translate/translate
72816df696b5263abfe80ab59129b299b85ae749
translate/storage/tmx.py
python
tmxfile.addtranslation
(self, source, srclang, translation, translang, comment=None)
addtranslation method for testing old unit tests
addtranslation method for testing old unit tests
[ "addtranslation", "method", "for", "testing", "old", "unit", "tests" ]
def addtranslation(self, source, srclang, translation, translang, comment=None): """addtranslation method for testing old unit tests""" unit = self.addsourceunit(source) unit.target = translation if comment is not None and len(comment) > 0: unit.addnote(comment) tuvs = unit.xmlelement.iterdescendants(self.namespaced("tuv")) setXMLlang(next(tuvs), srclang) setXMLlang(next(tuvs), translang)
[ "def", "addtranslation", "(", "self", ",", "source", ",", "srclang", ",", "translation", ",", "translang", ",", "comment", "=", "None", ")", ":", "unit", "=", "self", ".", "addsourceunit", "(", "source", ")", "unit", ".", "target", "=", "translation", "i...
https://github.com/translate/translate/blob/72816df696b5263abfe80ab59129b299b85ae749/translate/storage/tmx.py#L150-L159
nvaccess/nvda
20d5a25dced4da34338197f0ef6546270ebca5d0
source/visionEnhancementProviders/NVDAHighlighter.py
python
NVDAHighlighter.updateContextRect
(self, context, rect=None, obj=None)
Updates the position rectangle of the highlight for the specified context. If rect is specified, the method directly writes the rectangle to the contextToRectMap. Otherwise, it will call L{getContextRect}
Updates the position rectangle of the highlight for the specified context. If rect is specified, the method directly writes the rectangle to the contextToRectMap. Otherwise, it will call L{getContextRect}
[ "Updates", "the", "position", "rectangle", "of", "the", "highlight", "for", "the", "specified", "context", ".", "If", "rect", "is", "specified", "the", "method", "directly", "writes", "the", "rectangle", "to", "the", "contextToRectMap", ".", "Otherwise", "it", ...
def updateContextRect(self, context, rect=None, obj=None): """Updates the position rectangle of the highlight for the specified context. If rect is specified, the method directly writes the rectangle to the contextToRectMap. Otherwise, it will call L{getContextRect} """ if context not in self.enabledContexts: return if rect is None: try: rect = getContextRect(context, obj=obj) except (LookupError, NotImplementedError, RuntimeError, TypeError): rect = None self.contextToRectMap[context] = rect
[ "def", "updateContextRect", "(", "self", ",", "context", ",", "rect", "=", "None", ",", "obj", "=", "None", ")", ":", "if", "context", "not", "in", "self", ".", "enabledContexts", ":", "return", "if", "rect", "is", "None", ":", "try", ":", "rect", "=...
https://github.com/nvaccess/nvda/blob/20d5a25dced4da34338197f0ef6546270ebca5d0/source/visionEnhancementProviders/NVDAHighlighter.py#L462-L474
Scalsol/mega.pytorch
a6aa6e0537b82d70da94228100a51e6a53d98f82
mega_core/modeling/backbone/fbnet_builder.py
python
FBNetBuilder._add_ir_block
( self, dim_in, dim_out, stride, expand_ratio, block_op_type, **kwargs )
return ret, ret.output_depth
[]
def _add_ir_block( self, dim_in, dim_out, stride, expand_ratio, block_op_type, **kwargs ): ret = PRIMITIVES[block_op_type]( dim_in, dim_out, expansion=expand_ratio, stride=stride, bn_type=self.bn_type, width_divisor=self.width_divisor, dw_skip_bn=self.dw_skip_bn, dw_skip_relu=self.dw_skip_relu, **kwargs ) return ret, ret.output_depth
[ "def", "_add_ir_block", "(", "self", ",", "dim_in", ",", "dim_out", ",", "stride", ",", "expand_ratio", ",", "block_op_type", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "PRIMITIVES", "[", "block_op_type", "]", "(", "dim_in", ",", "dim_out", ",", "exp...
https://github.com/Scalsol/mega.pytorch/blob/a6aa6e0537b82d70da94228100a51e6a53d98f82/mega_core/modeling/backbone/fbnet_builder.py#L795-L809
eth-sri/eran
973e3b52d297d079d5402edec8f7922d824b8cc2
tf_verify/deeppoly_nodes.py
python
DeeppolyPoolNode.transformer
(self, nn, man, element, nlb, nub, relu_groups, refine, timeout_lp, timeout_milp, use_default_heuristic, testing)
return element
transformer for a maxpool/averagepool layer, this can't be the first layer of a network Arguments --------- man : ElinaManagerPtr man to which element belongs element : ElinaAbstract0Ptr abstract element onto which the transformer gets applied Return ------ output : ElinaAbstract0Ptr abstract element after the transformer
transformer for a maxpool/averagepool layer, this can't be the first layer of a network Arguments --------- man : ElinaManagerPtr man to which element belongs element : ElinaAbstract0Ptr abstract element onto which the transformer gets applied Return ------ output : ElinaAbstract0Ptr abstract element after the transformer
[ "transformer", "for", "a", "maxpool", "/", "averagepool", "layer", "this", "can", "t", "be", "the", "first", "layer", "of", "a", "network", "Arguments", "---------", "man", ":", "ElinaManagerPtr", "man", "to", "which", "element", "belongs", "element", ":", "...
def transformer(self, nn, man, element, nlb, nub, relu_groups, refine, timeout_lp, timeout_milp, use_default_heuristic, testing): """ transformer for a maxpool/averagepool layer, this can't be the first layer of a network Arguments --------- man : ElinaManagerPtr man to which element belongs element : ElinaAbstract0Ptr abstract element onto which the transformer gets applied Return ------ output : ElinaAbstract0Ptr abstract element after the transformer """ h, w = self.window_size H, W, C = self.input_shape #assert self.pad_top==self.pad_bottom==self.pad_right==self.pad_left==0, "Padded pooling not implemented" handle_pool_layer(man, element, (c_size_t *3)(h,w,1), (c_size_t *3)(H, W, C), (c_size_t *2)(self.strides[0], self.strides[1]), self.pad_top, self.pad_left, self.pad_bottom, self.pad_right, self.output_shape, self.predecessors, len(self.predecessors), self.is_maxpool) calc_bounds(man, element, nn, nlb, nub, relu_groups, is_refine_layer=True, destroy=False) nn.pool_counter += 1 if testing: return element, nlb[-1], nub[-1] return element
[ "def", "transformer", "(", "self", ",", "nn", ",", "man", ",", "element", ",", "nlb", ",", "nub", ",", "relu_groups", ",", "refine", ",", "timeout_lp", ",", "timeout_milp", ",", "use_default_heuristic", ",", "testing", ")", ":", "h", ",", "w", "=", "se...
https://github.com/eth-sri/eran/blob/973e3b52d297d079d5402edec8f7922d824b8cc2/tf_verify/deeppoly_nodes.py#L599-L623
openstack/neutron
fb229fb527ac8b95526412f7762d90826ac41428
neutron/services/logapi/common/db_api.py
python
_create_sg_rule_dict
(rule_in_db)
return rule_dict
Return a dict of a security group rule
Return a dict of a security group rule
[ "Return", "a", "dict", "of", "a", "security", "group", "rule" ]
def _create_sg_rule_dict(rule_in_db): """Return a dict of a security group rule""" direction = rule_in_db['direction'] rule_dict = { 'direction': direction, 'ethertype': rule_in_db['ethertype']} rule_dict.update({ key: rule_in_db[key] for key in ('protocol', 'port_range_min', 'port_range_max', 'remote_group_id') if rule_in_db[key] is not None}) remote_ip_prefix = rule_in_db['remote_ip_prefix'] if remote_ip_prefix is not None: direction_ip_prefix = constants.DIRECTION_IP_PREFIX[direction] rule_dict[direction_ip_prefix] = remote_ip_prefix rule_dict['security_group_id'] = rule_in_db['security_group_id'] return rule_dict
[ "def", "_create_sg_rule_dict", "(", "rule_in_db", ")", ":", "direction", "=", "rule_in_db", "[", "'direction'", "]", "rule_dict", "=", "{", "'direction'", ":", "direction", ",", "'ethertype'", ":", "rule_in_db", "[", "'ethertype'", "]", "}", "rule_dict", ".", ...
https://github.com/openstack/neutron/blob/fb229fb527ac8b95526412f7762d90826ac41428/neutron/services/logapi/common/db_api.py#L118-L137
constverum/ProxyBroker
d21aae8575fc3a95493233ecfd2c7cf47b36b069
proxybroker/proxy.py
python
Proxy.send
(self, req)
[]
async def send(self, req): msg, err = '', None _req = req.encode() if not isinstance(req, bytes) else req try: self.writer.write(_req) await self.writer.drain() except ConnectionResetError: msg = '; Sending: failed' err = ProxySendError(msg) raise err finally: self.log('Request: %s%s' % (req, msg), err=err)
[ "async", "def", "send", "(", "self", ",", "req", ")", ":", "msg", ",", "err", "=", "''", ",", "None", "_req", "=", "req", ".", "encode", "(", ")", "if", "not", "isinstance", "(", "req", ",", "bytes", ")", "else", "req", "try", ":", "self", ".",...
https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/proxy.py#L341-L352
veusz/veusz
5a1e2af5f24df0eb2a2842be51f2997c4999c7fb
veusz/widgets/axisbroken.py
python
AxisBroken.switchBreak
(self, num, posn, otherposition=None)
Switch to break given (or None to disable).
Switch to break given (or None to disable).
[ "Switch", "to", "break", "given", "(", "or", "None", "to", "disable", ")", "." ]
def switchBreak(self, num, posn, otherposition=None): """Switch to break given (or None to disable).""" self.rangeswitch = num if num is None: self.plottedrange = self.orig_plottedrange else: self.plottedrange = [self.breakvstarts[num], self.breakvstops[num]] self.updateAxisLocation(posn, otherposition=otherposition)
[ "def", "switchBreak", "(", "self", ",", "num", ",", "posn", ",", "otherposition", "=", "None", ")", ":", "self", ".", "rangeswitch", "=", "num", "if", "num", "is", "None", ":", "self", ".", "plottedrange", "=", "self", ".", "orig_plottedrange", "else", ...
https://github.com/veusz/veusz/blob/5a1e2af5f24df0eb2a2842be51f2997c4999c7fb/veusz/widgets/axisbroken.py#L66-L73
sethmlarson/virtualbox-python
984a6e2cb0e8996f4df40f4444c1528849f1c70d
virtualbox/library.py
python
IStringFormValue.clipboard_string
(self)
return ret
Get str value for 'clipboardString' Intnded for cases when a read-only string value is used to display information and different string is to be used when copying to the clipboard.
Get str value for 'clipboardString' Intnded for cases when a read-only string value is used to display information and different string is to be used when copying to the clipboard.
[ "Get", "str", "value", "for", "clipboardString", "Intnded", "for", "cases", "when", "a", "read", "-", "only", "string", "value", "is", "used", "to", "display", "information", "and", "different", "string", "is", "to", "be", "used", "when", "copying", "to", ...
def clipboard_string(self): """Get str value for 'clipboardString' Intnded for cases when a read-only string value is used to display information and different string is to be used when copying to the clipboard. """ ret = self._get_attr("clipboardString") return ret
[ "def", "clipboard_string", "(", "self", ")", ":", "ret", "=", "self", ".", "_get_attr", "(", "\"clipboardString\"", ")", "return", "ret" ]
https://github.com/sethmlarson/virtualbox-python/blob/984a6e2cb0e8996f4df40f4444c1528849f1c70d/virtualbox/library.py#L36978-L36985
JetBrains/python-skeletons
95ad24b666e475998e5d1cc02ed53a2188036167
numpy/core/__init__.py
python
int8.__rrshift__
(self, *args, **kwargs)
Return value>>self.
Return value>>self.
[ "Return", "value", ">>", "self", "." ]
def __rrshift__(self, *args, **kwargs): # real signature unknown """ Return value>>self. """ pass
[ "def", "__rrshift__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# real signature unknown", "pass" ]
https://github.com/JetBrains/python-skeletons/blob/95ad24b666e475998e5d1cc02ed53a2188036167/numpy/core/__init__.py#L1253-L1255
unkn0wnh4ckr/hackers-tool-kit
34dbabf3e94825684fd1a684f522d3dc3565eb2d
plugins/discovery/IPy.py
python
IP.__repr__
(self)
return("IP('%s')" % (self.strCompressed(1)))
Print a representation of the Object. >>> IP('10.0.0.0/8') IP('10.0.0.0/8')
Print a representation of the Object.
[ "Print", "a", "representation", "of", "the", "Object", "." ]
def __repr__(self): """Print a representation of the Object. >>> IP('10.0.0.0/8') IP('10.0.0.0/8') """ return("IP('%s')" % (self.strCompressed(1)))
[ "def", "__repr__", "(", "self", ")", ":", "return", "(", "\"IP('%s')\"", "%", "(", "self", ".", "strCompressed", "(", "1", ")", ")", ")" ]
https://github.com/unkn0wnh4ckr/hackers-tool-kit/blob/34dbabf3e94825684fd1a684f522d3dc3565eb2d/plugins/discovery/IPy.py#L944-L951
runfalk/spans
db18d6d6a77c35f513095f47ea6929f609da3dff
spans/types.py
python
Range.lower_inf
(self)
return self._range.lower is None and not self._range.empty
Returns True if lower bound is unbounded. >>> intrange(1, 5).lower_inf False >>> intrange(upper=5).lower_inf True This is the same as the ``lower_inf(self)`` in PostgreSQL.
Returns True if lower bound is unbounded.
[ "Returns", "True", "if", "lower", "bound", "is", "unbounded", "." ]
def lower_inf(self): """ Returns True if lower bound is unbounded. >>> intrange(1, 5).lower_inf False >>> intrange(upper=5).lower_inf True This is the same as the ``lower_inf(self)`` in PostgreSQL. """ return self._range.lower is None and not self._range.empty
[ "def", "lower_inf", "(", "self", ")", ":", "return", "self", ".", "_range", ".", "lower", "is", "None", "and", "not", "self", ".", "_range", ".", "empty" ]
https://github.com/runfalk/spans/blob/db18d6d6a77c35f513095f47ea6929f609da3dff/spans/types.py#L324-L336
ukdtom/ExportTools.bundle
49aba4292a2897f640162a833c2792480aa4f0b6
Contents/Libraries/Shared/xlsxwriter/chart_pie.py
python
ChartPie.__init__
(self, options=None)
Constructor.
Constructor.
[ "Constructor", "." ]
def __init__(self, options=None): """ Constructor. """ super(ChartPie, self).__init__() if options is None: options = {} self.vary_data_color = 1 self.rotation = 0 # Set the available data label positions for this chart type. self.label_position_default = 'best_fit' self.label_positions = { 'center': 'ctr', 'inside_end': 'inEnd', 'outside_end': 'outEnd', 'best_fit': 'bestFit'}
[ "def", "__init__", "(", "self", ",", "options", "=", "None", ")", ":", "super", "(", "ChartPie", ",", "self", ")", ".", "__init__", "(", ")", "if", "options", "is", "None", ":", "options", "=", "{", "}", "self", ".", "vary_data_color", "=", "1", "s...
https://github.com/ukdtom/ExportTools.bundle/blob/49aba4292a2897f640162a833c2792480aa4f0b6/Contents/Libraries/Shared/xlsxwriter/chart_pie.py#L25-L44
standardebooks/tools
f57af3c5938a9aeed9e97e82b2c130424f6033e5
se/se_epub_generate_toc.py
python
TocItem.landmark_link
(self, work_type: str = "fiction", work_title: str = "WORK_TITLE")
return out_string
Generates the landmark item (including list item tags) for the ToC item INPUTS: work_type: ("fiction" or "non-fiction") work_title: the title of the book, eg "Don Quixote" OUTPUTS: the linking string to be included in landmarks section.
Generates the landmark item (including list item tags) for the ToC item
[ "Generates", "the", "landmark", "item", "(", "including", "list", "item", "tags", ")", "for", "the", "ToC", "item" ]
def landmark_link(self, work_type: str = "fiction", work_title: str = "WORK_TITLE") -> str: """ Generates the landmark item (including list item tags) for the ToC item INPUTS: work_type: ("fiction" or "non-fiction") work_title: the title of the book, eg "Don Quixote" OUTPUTS: the linking string to be included in landmarks section. """ out_string = "" if self.place == Position.FRONT: out_string = f"<li>\n<a href=\"text/{self.file_link}\" epub:type=\"frontmatter {self.epub_type}\">{self.title}</a>\n</li>\n" if self.place == Position.BODY: out_string = f"<li>\n<a href=\"text/{self.file_link}\" epub:type=\"bodymatter z3998:{work_type}\">{work_title}</a>\n</li>\n" if self.place == Position.BACK: out_string = f"<li>\n<a href=\"text/{self.file_link}\" epub:type=\"backmatter {self.epub_type}\">{self.title}</a>\n</li>\n" return out_string
[ "def", "landmark_link", "(", "self", ",", "work_type", ":", "str", "=", "\"fiction\"", ",", "work_title", ":", "str", "=", "\"WORK_TITLE\"", ")", "->", "str", ":", "out_string", "=", "\"\"", "if", "self", ".", "place", "==", "Position", ".", "FRONT", ":"...
https://github.com/standardebooks/tools/blob/f57af3c5938a9aeed9e97e82b2c130424f6033e5/se/se_epub_generate_toc.py#L114-L134
inducer/loopy
55143b21711a534c07bbb14aaa63ff3879a93433
loopy/transform/callable.py
python
_inline_call_instruction
(caller_knl, callee_knl, call_insn)
return caller_knl.copy(instructions=new_insns, temporary_variables=new_temps, domains=caller_knl.domains+new_domains, assumptions=(old_assumptions.params() & new_assumptions.params()), inames=new_inames)
Returns a copy of *caller_knl* with the *call_insn* in the *kernel* replaced by inlining *callee_knl* into it within it. :arg call_insn: An instance of `loopy.CallInstruction` of the call-site.
Returns a copy of *caller_knl* with the *call_insn* in the *kernel* replaced by inlining *callee_knl* into it within it.
[ "Returns", "a", "copy", "of", "*", "caller_knl", "*", "with", "the", "*", "call_insn", "*", "in", "the", "*", "kernel", "*", "replaced", "by", "inlining", "*", "callee_knl", "*", "into", "it", "within", "it", "." ]
def _inline_call_instruction(caller_knl, callee_knl, call_insn): """ Returns a copy of *caller_knl* with the *call_insn* in the *kernel* replaced by inlining *callee_knl* into it within it. :arg call_insn: An instance of `loopy.CallInstruction` of the call-site. """ import pymbolic.primitives as prim from pymbolic.mapper.substitutor import make_subst_func from loopy.kernel.data import ValueArg # {{{ sanity checks assert call_insn.expression.function.name == callee_knl.name # }}} callee_label = callee_knl.name[:4] + "_" vng = caller_knl.get_var_name_generator() ing = caller_knl.get_instruction_id_generator() # {{{ construct callee->caller name mappings # name_map: Mapping[str, str] # A mapping from variable names in the callee kernel's namespace to # the ones they would be referred by in the caller's namespace post inlining. name_map = {} # only consider temporary variables and inames, arguments would be mapping # according to the invocation in call_insn. for name in (callee_knl.all_inames() | set(callee_knl.temporary_variables.keys())): new_name = vng(callee_label+name) name_map[name] = new_name # }}} # {{{ iname_to_tags # new_inames: caller's inames post inlining new_inames = caller_knl.inames for old_name, callee_iname in callee_knl.inames.items(): new_name = name_map[old_name] new_inames[new_name] = callee_iname.copy(name=new_name) # }}} # {{{ register callee's temps as caller's # new_temps: caller's temps post inlining new_temps = caller_knl.temporary_variables.copy() for name, tv in callee_knl.temporary_variables.items(): new_temps[name_map[name]] = tv.copy(name=name_map[name]) # }}} # {{{ get callee args -> parameters passed to the call arg_map = {} # callee arg name -> caller symbols (e.g. SubArrayRef) assignees = call_insn.assignees # writes parameters = call_insn.expression.parameters # reads from loopy.kernel.function_interface import get_kw_pos_association kw_to_pos, pos_to_kw = get_kw_pos_association(callee_knl) for i, par in enumerate(parameters): arg_map[pos_to_kw[i]] = par for i, assignee in enumerate(assignees): arg_map[pos_to_kw[-i-1]] = assignee # }}} # {{{ process domains/assumptions # rename inames new_domains = callee_knl.domains.copy() for old_iname in callee_knl.all_inames(): new_domains = [rename_iname(dom, old_iname, name_map[old_iname]) for dom in new_domains] # realize domains' dim params in terms of caller's variables new_assumptions = callee_knl.assumptions for callee_arg_name, param_expr in arg_map.items(): if isinstance(callee_knl.arg_dict[callee_arg_name], ValueArg): new_domains = [ substitute_into_domain( dom, callee_arg_name, param_expr, get_valid_domain_param_names(caller_knl)) for dom in new_domains] new_assumptions = substitute_into_domain( new_assumptions, callee_arg_name, param_expr, get_valid_domain_param_names(caller_knl)) # }}} # {{{ rename inames/temporaries in the program rule_mapping_context = SubstitutionRuleMappingContext(callee_knl.substitutions, vng) subst_func = make_subst_func({old_name: prim.Variable(new_name) for old_name, new_name in name_map.items()}) inames_temps_renamer = RuleAwareSubstitutionMapper(rule_mapping_context, subst_func, within=lambda *args: True) callee_knl = rule_mapping_context.finish_kernel(inames_temps_renamer .map_kernel(callee_knl)) # }}} # {{{ map callee's expressions to get expressions after inlining rule_mapping_context = SubstitutionRuleMappingContext(callee_knl.substitutions, vng) smap = KernelArgumentSubstitutor(rule_mapping_context, caller_knl, callee_knl, arg_map) callee_knl = rule_mapping_context.finish_kernel(smap.map_kernel(callee_knl)) # }}} # {{{ generate new ids for instructions insn_id_map = {} for insn in callee_knl.instructions: insn_id_map[insn.id] = ing(callee_label+insn.id) # }}} # {{{ use NoOp to mark the start and end of callee kernel from loopy.kernel.instruction import NoOpInstruction noop_start = NoOpInstruction( id=ing(callee_label+"_start"), within_inames=call_insn.within_inames, depends_on=call_insn.depends_on ) noop_end = NoOpInstruction( id=call_insn.id, within_inames=call_insn.within_inames, depends_on=frozenset(insn_id_map.values()) ) # }}} # {{{ map callee's instruction ids inlined_insns = [noop_start] for insn in callee_knl.instructions: new_within_inames = (frozenset(name_map[iname] for iname in insn.within_inames) | call_insn.within_inames) new_depends_on = (frozenset(insn_id_map[dep] for dep in insn.depends_on) | {noop_start.id}) new_no_sync_with = frozenset((insn_id_map[id], scope) for id, scope in insn.no_sync_with) new_id = insn_id_map[insn.id] if isinstance(insn, Assignment): new_atomicity = tuple(type(atomicity)(name_map[atomicity.var_name]) for atomicity in insn.atomicity) insn = insn.copy( id=insn_id_map[insn.id], within_inames=new_within_inames, depends_on=new_depends_on, tags=insn.tags | call_insn.tags, atomicity=new_atomicity, no_sync_with=new_no_sync_with ) else: insn = insn.copy( id=new_id, within_inames=new_within_inames, depends_on=new_depends_on, tags=insn.tags | call_insn.tags, no_sync_with=new_no_sync_with ) inlined_insns.append(insn) inlined_insns.append(noop_end) # }}} # {{{ swap out call_insn with inlined_instructions idx = caller_knl.instructions.index(call_insn) new_insns = (caller_knl.instructions[:idx] + inlined_insns + caller_knl.instructions[idx+1:]) # }}} old_assumptions, new_assumptions = isl.align_two( caller_knl.assumptions, new_assumptions) return caller_knl.copy(instructions=new_insns, temporary_variables=new_temps, domains=caller_knl.domains+new_domains, assumptions=(old_assumptions.params() & new_assumptions.params()), inames=new_inames)
[ "def", "_inline_call_instruction", "(", "caller_knl", ",", "callee_knl", ",", "call_insn", ")", ":", "import", "pymbolic", ".", "primitives", "as", "prim", "from", "pymbolic", ".", "mapper", ".", "substitutor", "import", "make_subst_func", "from", "loopy", ".", ...
https://github.com/inducer/loopy/blob/55143b21711a534c07bbb14aaa63ff3879a93433/loopy/transform/callable.py#L245-L455
markovmodel/PyEMMA
e9d08d715dde17ceaa96480a9ab55d5e87d3a4b3
pyemma/coordinates/transform/nystroem_tica.py
python
oASIS_Nystroem.column_indices
(self)
return np.array(self._columns)
The selected column indices
The selected column indices
[ "The", "selected", "column", "indices" ]
def column_indices(self): """ The selected column indices """ return np.array(self._columns)
[ "def", "column_indices", "(", "self", ")", ":", "return", "np", ".", "array", "(", "self", ".", "_columns", ")" ]
https://github.com/markovmodel/PyEMMA/blob/e9d08d715dde17ceaa96480a9ab55d5e87d3a4b3/pyemma/coordinates/transform/nystroem_tica.py#L407-L409
nopernik/mpDNS
b17dc39e7068406df82cb3431b3042e74e520cf9
circuits/protocols/irc/replies.py
python
RPL_UMODEIS
(modes)
return _M(u("221"), modes)
[]
def RPL_UMODEIS(modes): return _M(u("221"), modes)
[ "def", "RPL_UMODEIS", "(", "modes", ")", ":", "return", "_M", "(", "u", "(", "\"221\"", ")", ",", "modes", ")" ]
https://github.com/nopernik/mpDNS/blob/b17dc39e7068406df82cb3431b3042e74e520cf9/circuits/protocols/irc/replies.py#L69-L70
SirFroweey/PyDark
617c2bfda360afa7750c4707ecacd4ec82fa29af
PyDark/engine.py
python
Scene.Update
(self, item=None)
Update all our self.objects on our Scene() view.
Update all our self.objects on our Scene() view.
[ "Update", "all", "our", "self", ".", "objects", "on", "our", "Scene", "()", "view", "." ]
def Update(self, item=None): """Update all our self.objects on our Scene() view.""" if item is None: for item in self.objects: # Handle collisions for DarkSprites. item.Update() if self.surface.internal_collision_checking is True: self.process_collisions(item) for player in self.players: player.Update() else: item.Update()
[ "def", "Update", "(", "self", ",", "item", "=", "None", ")", ":", "if", "item", "is", "None", ":", "for", "item", "in", "self", ".", "objects", ":", "# Handle collisions for DarkSprites.", "item", ".", "Update", "(", ")", "if", "self", ".", "surface", ...
https://github.com/SirFroweey/PyDark/blob/617c2bfda360afa7750c4707ecacd4ec82fa29af/PyDark/engine.py#L908-L919
lohriialo/photoshop-scripting-python
6b97da967a5d0a45e54f7c99631b29773b923f09
api_reference/photoshop_2021.py
python
_SolidColor.IsEqual
(self, Color=defaultNamedNotOptArg)
return self._oleobj_.InvokeTypes(1129406828, LCID, 1, (11, 0), ((9, 1),),Color )
return true if the provided color is visually equal to this color
return true if the provided color is visually equal to this color
[ "return", "true", "if", "the", "provided", "color", "is", "visually", "equal", "to", "this", "color" ]
def IsEqual(self, Color=defaultNamedNotOptArg): 'return true if the provided color is visually equal to this color' return self._oleobj_.InvokeTypes(1129406828, LCID, 1, (11, 0), ((9, 1),),Color )
[ "def", "IsEqual", "(", "self", ",", "Color", "=", "defaultNamedNotOptArg", ")", ":", "return", "self", ".", "_oleobj_", ".", "InvokeTypes", "(", "1129406828", ",", "LCID", ",", "1", ",", "(", "11", ",", "0", ")", ",", "(", "(", "9", ",", "1", ")", ...
https://github.com/lohriialo/photoshop-scripting-python/blob/6b97da967a5d0a45e54f7c99631b29773b923f09/api_reference/photoshop_2021.py#L6294-L6297
earhian/Humpback-Whale-Identification-1st-
2bcb126fb255670b0da57b8a104e47267a8c3a17
models/triplet_loss.py
python
normalize
(x, axis=-1)
return x
Normalizing to unit length along the specified dimension. Args: x: pytorch Variable Returns: x: pytorch Variable, same shape as input
Normalizing to unit length along the specified dimension. Args: x: pytorch Variable Returns: x: pytorch Variable, same shape as input
[ "Normalizing", "to", "unit", "length", "along", "the", "specified", "dimension", ".", "Args", ":", "x", ":", "pytorch", "Variable", "Returns", ":", "x", ":", "pytorch", "Variable", "same", "shape", "as", "input" ]
def normalize(x, axis=-1): """Normalizing to unit length along the specified dimension. Args: x: pytorch Variable Returns: x: pytorch Variable, same shape as input """ x = 1. * x / (torch.norm(x, 2, axis, keepdim=True).expand_as(x) + 1e-12) return x
[ "def", "normalize", "(", "x", ",", "axis", "=", "-", "1", ")", ":", "x", "=", "1.", "*", "x", "/", "(", "torch", ".", "norm", "(", "x", ",", "2", ",", "axis", ",", "keepdim", "=", "True", ")", ".", "expand_as", "(", "x", ")", "+", "1e-12", ...
https://github.com/earhian/Humpback-Whale-Identification-1st-/blob/2bcb126fb255670b0da57b8a104e47267a8c3a17/models/triplet_loss.py#L10-L18
sharppy/SHARPpy
19175269ab11fe06c917b5d10376862a4716e1db
sutils/async.py
python
AsyncThreads.post
(self, func, callback, *args, **kwargs)
return thd_id
Post a thread to be run. func: The function to run in a separate thread callback: The function to run once func() is done. It will be passed the output from func() as a single tuple. background [optional]: Boolean specifying whether to run in the background. Background processes are started only if there are no higher-priority processes to run. The default value is False. *args, **kwargs: Arguments to func()
Post a thread to be run. func: The function to run in a separate thread callback: The function to run once func() is done. It will be passed the output from func() as a single tuple. background [optional]: Boolean specifying whether to run in the background. Background processes are started only if there are no higher-priority processes to run. The default value is False. *args, **kwargs: Arguments to func()
[ "Post", "a", "thread", "to", "be", "run", ".", "func", ":", "The", "function", "to", "run", "in", "a", "separate", "thread", "callback", ":", "The", "function", "to", "run", "once", "func", "()", "is", "done", ".", "It", "will", "be", "passed", "the"...
def post(self, func, callback, *args, **kwargs): """ Post a thread to be run. func: The function to run in a separate thread callback: The function to run once func() is done. It will be passed the output from func() as a single tuple. background [optional]: Boolean specifying whether to run in the background. Background processes are started only if there are no higher-priority processes to run. The default value is False. *args, **kwargs: Arguments to func() """ thd_id = self._genThreadId() logging.debug("Function being posted by Async: " + str(func) + ' ' + str(args)) background = kwargs.get('background', False) if 'background' in kwargs: del kwargs['background'] thd = self._threadFactory(func, thd_id, *args, **kwargs) thd.finished.connect(self.finish) priority = 1 if background else 0 self.queue.put((priority, thd_id)) self.threads[thd_id] = thd if callback is None: callback = lambda x: x self.callbacks[thd_id] = callback if not background or self.running < self.max_threads: self.startNext() return thd_id
[ "def", "post", "(", "self", ",", "func", ",", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "thd_id", "=", "self", ".", "_genThreadId", "(", ")", "logging", ".", "debug", "(", "\"Function being posted by Async: \"", "+", "str", "(", ...
https://github.com/sharppy/SHARPpy/blob/19175269ab11fe06c917b5d10376862a4716e1db/sutils/async.py#L29-L58
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/spc/alarm_control_panel.py
python
SpcAlarm.async_alarm_arm_home
(self, code=None)
Send arm home command.
Send arm home command.
[ "Send", "arm", "home", "command", "." ]
async def async_alarm_arm_home(self, code=None): """Send arm home command.""" await self._api.change_mode(area=self._area, new_mode=AreaMode.PART_SET_A)
[ "async", "def", "async_alarm_arm_home", "(", "self", ",", "code", "=", "None", ")", ":", "await", "self", ".", "_api", ".", "change_mode", "(", "area", "=", "self", ".", "_area", ",", "new_mode", "=", "AreaMode", ".", "PART_SET_A", ")" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/spc/alarm_control_panel.py#L108-L111
KhronosGroup/NNEF-Tools
c913758ca687dab8cb7b49e8f1556819a2d0ca25
nnef_tools/conversion/tflite_to_nnef.py
python
Converter._fix_quantization_attribs
(self, graph)
[]
def _fix_quantization_attribs(self, graph): for tensor in graph.tensors: if tensor.quant: scale = tensor.quant.get('scale') if scale is not None and not self._is_zero(scale): if 'min' in tensor.quant: del tensor.quant['min'] if 'max' in tensor.quant: del tensor.quant['max'] tensor.quant['op-name'] = 'zero_point_linear_quantize' tensor.quant['bits'] = 32 if self._is_conv_bias(tensor) else 8 assert tensor.dtype == np.uint8 or tensor.dtype == np.int8 or \ tensor.dtype == np.uint32 or tensor.dtype == np.int32, \ "unknown quantized dtype '{}'".format(tensor.dtype) tensor.quant['signed'] = tensor.dtype == np.int8 or tensor.dtype == np.int32 tensor.quant['symmetric'] = self._is_conv_filter(tensor)
[ "def", "_fix_quantization_attribs", "(", "self", ",", "graph", ")", ":", "for", "tensor", "in", "graph", ".", "tensors", ":", "if", "tensor", ".", "quant", ":", "scale", "=", "tensor", ".", "quant", ".", "get", "(", "'scale'", ")", "if", "scale", "is",...
https://github.com/KhronosGroup/NNEF-Tools/blob/c913758ca687dab8cb7b49e8f1556819a2d0ca25/nnef_tools/conversion/tflite_to_nnef.py#L119-L134
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/bin/pildriver.py
python
PILDriver.do_difference
(self)
usage: difference <image:pic1> <image:pic2> Pop the two top images, push the difference image
usage: difference <image:pic1> <image:pic2>
[ "usage", ":", "difference", "<image", ":", "pic1", ">", "<image", ":", "pic2", ">" ]
def do_difference(self): """usage: difference <image:pic1> <image:pic2> Pop the two top images, push the difference image """ from PIL import ImageChops image1 = self.do_pop() image2 = self.do_pop() self.push(ImageChops.difference(image1, image2))
[ "def", "do_difference", "(", "self", ")", ":", "from", "PIL", "import", "ImageChops", "image1", "=", "self", ".", "do_pop", "(", ")", "image2", "=", "self", ".", "do_pop", "(", ")", "self", ".", "push", "(", "ImageChops", ".", "difference", "(", "image...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/bin/pildriver.py#L379-L387
PMEAL/OpenPNM
c9514b858d1361b2090b2f9579280cbcd476c9b0
openpnm/utils/_project.py
python
Project.save_object
(self, obj)
r""" Saves the given object or list of objects to a pickle file Parameters ---------- obj : Base or list[Base] The objects to be saved. Depending on the object type, the file extension will be one of 'net', 'geo', 'phase', 'phys' or 'alg'. Returns ------- None
r""" Saves the given object or list of objects to a pickle file
[ "r", "Saves", "the", "given", "object", "or", "list", "of", "objects", "to", "a", "pickle", "file" ]
def save_object(self, obj): r""" Saves the given object or list of objects to a pickle file Parameters ---------- obj : Base or list[Base] The objects to be saved. Depending on the object type, the file extension will be one of 'net', 'geo', 'phase', 'phys' or 'alg'. Returns ------- None """ from openpnm.io import Pickle Pickle.save_object_to_file(objs=obj)
[ "def", "save_object", "(", "self", ",", "obj", ")", ":", "from", "openpnm", ".", "io", "import", "Pickle", "Pickle", ".", "save_object_to_file", "(", "objs", "=", "obj", ")" ]
https://github.com/PMEAL/OpenPNM/blob/c9514b858d1361b2090b2f9579280cbcd476c9b0/openpnm/utils/_project.py#L464-L481
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/pip/commands/wheel.py
python
WheelCommand.check_required_packages
(self)
[]
def check_required_packages(self): import_or_raise( 'wheel.bdist_wheel', CommandError, "'pip wheel' requires the 'wheel' package. To fix this, run: " "pip install wheel" ) pkg_resources = import_or_raise( 'pkg_resources', CommandError, "'pip wheel' requires setuptools >= 0.8 for dist-info support." " To fix this, run: pip install --upgrade setuptools" ) if not hasattr(pkg_resources, 'DistInfoDistribution'): raise CommandError( "'pip wheel' requires setuptools >= 0.8 for dist-info " "support. To fix this, run: pip install --upgrade " "setuptools" )
[ "def", "check_required_packages", "(", "self", ")", ":", "import_or_raise", "(", "'wheel.bdist_wheel'", ",", "CommandError", ",", "\"'pip wheel' requires the 'wheel' package. To fix this, run: \"", "\"pip install wheel\"", ")", "pkg_resources", "=", "import_or_raise", "(", "'pk...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pip/commands/wheel.py#L104-L122
baidu/CUP
79ab2f3ad6eaab1461aa3b4cca37d3262240194a
cup/util/conf.py
python
Configure2Dict._strip_value
(self, value)
return rev
strip the value
strip the value
[ "strip", "the", "value" ]
def _strip_value(self, value): """ strip the value """ if self._remove_comments: rev = value.split('#')[0].strip() else: rev = value return rev
[ "def", "_strip_value", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_remove_comments", ":", "rev", "=", "value", ".", "split", "(", "'#'", ")", "[", "0", "]", ".", "strip", "(", ")", "else", ":", "rev", "=", "value", "return", "rev" ]
https://github.com/baidu/CUP/blob/79ab2f3ad6eaab1461aa3b4cca37d3262240194a/cup/util/conf.py#L567-L575
itailang/SampleNet
442459abc54f9e14f0966a169a094a98febd32eb
classification/utils/plyfile.py
python
PlyElement._get_properties
(self)
return self._properties
[]
def _get_properties(self): return self._properties
[ "def", "_get_properties", "(", "self", ")", ":", "return", "self", ".", "_properties" ]
https://github.com/itailang/SampleNet/blob/442459abc54f9e14f0966a169a094a98febd32eb/classification/utils/plyfile.py#L420-L421
jliljebl/flowblade
995313a509b80e99eb1ad550d945bdda5995093b
flowblade-trunk/Flowblade/keyframeeditor.py
python
PositionNumericalEntries.__init__
(self, geom_editor, parent_editor, editor_buttons)
[]
def __init__(self, geom_editor, parent_editor, editor_buttons): GObject.GObject.__init__(self) self.parent_editor = parent_editor if isinstance(geom_editor, keyframeeditcanvas.RotatingEditCanvas): self.rotating_geom = True self.init_for_roto_geom(editor_buttons) else: self.rotating_geom = False self.init_for_box_geom(editor_buttons)
[ "def", "__init__", "(", "self", ",", "geom_editor", ",", "parent_editor", ",", "editor_buttons", ")", ":", "GObject", ".", "GObject", ".", "__init__", "(", "self", ")", "self", ".", "parent_editor", "=", "parent_editor", "if", "isinstance", "(", "geom_editor",...
https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/keyframeeditor.py#L2196-L2206
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
tokumx/datadog_checks/tokumx/vendor/gridfs/__init__.py
python
GridFS.find
(self, *args, **kwargs)
return GridOutCursor(self.__collection, *args, **kwargs)
Query GridFS for files. Returns a cursor that iterates across files matching arbitrary queries on the files collection. Can be combined with other modifiers for additional control. For example:: for grid_out in fs.find({"filename": "lisa.txt"}, no_cursor_timeout=True): data = grid_out.read() would iterate through all versions of "lisa.txt" stored in GridFS. Note that setting no_cursor_timeout to True may be important to prevent the cursor from timing out during long multi-file processing work. As another example, the call:: most_recent_three = fs.find().sort("uploadDate", -1).limit(3) would return a cursor to the three most recently uploaded files in GridFS. Follows a similar interface to :meth:`~pymongo.collection.Collection.find` in :class:`~pymongo.collection.Collection`. :Parameters: - `filter` (optional): a SON object specifying elements which must be present for a document to be included in the result set - `skip` (optional): the number of files to omit (from the start of the result set) when returning the results - `limit` (optional): the maximum number of results to return - `no_cursor_timeout` (optional): if False (the default), any returned cursor is closed by the server after 10 minutes of inactivity. If set to True, the returned cursor will never time out on the server. Care should be taken to ensure that cursors with no_cursor_timeout turned on are properly closed. - `sort` (optional): a list of (key, direction) pairs specifying the sort order for this query. See :meth:`~pymongo.cursor.Cursor.sort` for details. Raises :class:`TypeError` if any of the arguments are of improper type. Returns an instance of :class:`~gridfs.grid_file.GridOutCursor` corresponding to this query. .. versionchanged:: 3.0 Removed the read_preference, tag_sets, and secondary_acceptable_latency_ms options. .. versionadded:: 2.7 .. mongodoc:: find
Query GridFS for files.
[ "Query", "GridFS", "for", "files", "." ]
def find(self, *args, **kwargs): """Query GridFS for files. Returns a cursor that iterates across files matching arbitrary queries on the files collection. Can be combined with other modifiers for additional control. For example:: for grid_out in fs.find({"filename": "lisa.txt"}, no_cursor_timeout=True): data = grid_out.read() would iterate through all versions of "lisa.txt" stored in GridFS. Note that setting no_cursor_timeout to True may be important to prevent the cursor from timing out during long multi-file processing work. As another example, the call:: most_recent_three = fs.find().sort("uploadDate", -1).limit(3) would return a cursor to the three most recently uploaded files in GridFS. Follows a similar interface to :meth:`~pymongo.collection.Collection.find` in :class:`~pymongo.collection.Collection`. :Parameters: - `filter` (optional): a SON object specifying elements which must be present for a document to be included in the result set - `skip` (optional): the number of files to omit (from the start of the result set) when returning the results - `limit` (optional): the maximum number of results to return - `no_cursor_timeout` (optional): if False (the default), any returned cursor is closed by the server after 10 minutes of inactivity. If set to True, the returned cursor will never time out on the server. Care should be taken to ensure that cursors with no_cursor_timeout turned on are properly closed. - `sort` (optional): a list of (key, direction) pairs specifying the sort order for this query. See :meth:`~pymongo.cursor.Cursor.sort` for details. Raises :class:`TypeError` if any of the arguments are of improper type. Returns an instance of :class:`~gridfs.grid_file.GridOutCursor` corresponding to this query. .. versionchanged:: 3.0 Removed the read_preference, tag_sets, and secondary_acceptable_latency_ms options. .. versionadded:: 2.7 .. mongodoc:: find """ return GridOutCursor(self.__collection, *args, **kwargs)
[ "def", "find", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "GridOutCursor", "(", "self", ".", "__collection", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/tokumx/datadog_checks/tokumx/vendor/gridfs/__init__.py#L266-L321
roclark/sportsipy
c19f545d3376d62ded6304b137dc69238ac620a9
sportsipy/nba/boxscore.py
python
Boxscore.home_free_throw_attempts
(self)
return self._home_free_throw_attempts
Returns an ``int`` of the total number of free throw attempts by the home team.
Returns an ``int`` of the total number of free throw attempts by the home team.
[ "Returns", "an", "int", "of", "the", "total", "number", "of", "free", "throw", "attempts", "by", "the", "home", "team", "." ]
def home_free_throw_attempts(self): """ Returns an ``int`` of the total number of free throw attempts by the home team. """ return self._home_free_throw_attempts
[ "def", "home_free_throw_attempts", "(", "self", ")", ":", "return", "self", ".", "_home_free_throw_attempts" ]
https://github.com/roclark/sportsipy/blob/c19f545d3376d62ded6304b137dc69238ac620a9/sportsipy/nba/boxscore.py#L1344-L1349
lemonhu/open-entity-relation-extraction
760a7cbf583c60896f7d6053e6fb183fb5fabeb8
code/core/extract_by_dsnf.py
python
ExtractByDSNF.build_triple
(self, entity1, entity2, relation)
return True
建立三元组,写入json文件 Args: entity1: WordUnit,实体1 entity2: WordUnit,实体2 relation: str list,关系列表 num: int,知识三元组编号 Returns: True: 获得三元组(True)
建立三元组,写入json文件 Args: entity1: WordUnit,实体1 entity2: WordUnit,实体2 relation: str list,关系列表 num: int,知识三元组编号 Returns: True: 获得三元组(True)
[ "建立三元组,写入json文件", "Args", ":", "entity1", ":", "WordUnit,实体1", "entity2", ":", "WordUnit,实体2", "relation", ":", "str", "list,关系列表", "num", ":", "int,知识三元组编号", "Returns", ":", "True", ":", "获得三元组", "(", "True", ")" ]
def build_triple(self, entity1, entity2, relation): """建立三元组,写入json文件 Args: entity1: WordUnit,实体1 entity2: WordUnit,实体2 relation: str list,关系列表 num: int,知识三元组编号 Returns: True: 获得三元组(True) """ triple = dict() triple['编号'] = self.num self.num += 1 triple['句子'] = self.origin_sentence entity1_str = self.element_connect(entity1) entity2_str = self.element_connect(entity2) relation_str = self.element_connect(relation) triple['知识'] = [entity1_str, relation_str, entity2_str] AppendToJson().append(self.file_path, triple) print('triple: ' + entity1_str + '\t' + relation_str + '\t' + entity2_str) return True
[ "def", "build_triple", "(", "self", ",", "entity1", ",", "entity2", ",", "relation", ")", ":", "triple", "=", "dict", "(", ")", "triple", "[", "'编号'] = ", "s", "l", ".num", "", "", "self", ".", "num", "+=", "1", "triple", "[", "'句子'] = ", "s", "l",...
https://github.com/lemonhu/open-entity-relation-extraction/blob/760a7cbf583c60896f7d6053e6fb183fb5fabeb8/code/core/extract_by_dsnf.py#L101-L121
PMEAL/OpenPNM
c9514b858d1361b2090b2f9579280cbcd476c9b0
openpnm/models/geometry/pore_size/_funcs.py
python
equivalent_diameter
(target, pore_volume='pore.volume', pore_shape='sphere')
return value
r""" Calculate the diameter of a sphere or edge-length of a cube with same volume as the pore. Parameters ---------- %(models.target.parameters)s pore_volume : str Name of the dictionary key on ``target`` where the array containing pore volume values is stored pore_shape : str The shape of the pore body to assume when back-calculating from volume. Options are 'sphere' (default) or 'cube'. Returns ------- diameters : ndarray A number ndarray containing pore diameter values
r""" Calculate the diameter of a sphere or edge-length of a cube with same volume as the pore.
[ "r", "Calculate", "the", "diameter", "of", "a", "sphere", "or", "edge", "-", "length", "of", "a", "cube", "with", "same", "volume", "as", "the", "pore", "." ]
def equivalent_diameter(target, pore_volume='pore.volume', pore_shape='sphere'): r""" Calculate the diameter of a sphere or edge-length of a cube with same volume as the pore. Parameters ---------- %(models.target.parameters)s pore_volume : str Name of the dictionary key on ``target`` where the array containing pore volume values is stored pore_shape : str The shape of the pore body to assume when back-calculating from volume. Options are 'sphere' (default) or 'cube'. Returns ------- diameters : ndarray A number ndarray containing pore diameter values """ from scipy.special import cbrt pore_vols = target[pore_volume] if pore_shape.startswith('sph'): value = cbrt(6*pore_vols/_np.pi) elif pore_shape.startswith('cub'): value = cbrt(pore_vols) return value
[ "def", "equivalent_diameter", "(", "target", ",", "pore_volume", "=", "'pore.volume'", ",", "pore_shape", "=", "'sphere'", ")", ":", "from", "scipy", ".", "special", "import", "cbrt", "pore_vols", "=", "target", "[", "pore_volume", "]", "if", "pore_shape", "."...
https://github.com/PMEAL/OpenPNM/blob/c9514b858d1361b2090b2f9579280cbcd476c9b0/openpnm/models/geometry/pore_size/_funcs.py#L132-L160
Kkevsterrr/geneva
36d3585545d4cb3450ea0b166d8d5f20a64ed8d8
layers/ip_layer.py
python
IPLayer.gen_ip
(self, field)
return RandIP()._fix()
Generates an IP address.
Generates an IP address.
[ "Generates", "an", "IP", "address", "." ]
def gen_ip(self, field): """ Generates an IP address. """ return RandIP()._fix()
[ "def", "gen_ip", "(", "self", ",", "field", ")", ":", "return", "RandIP", "(", ")", ".", "_fix", "(", ")" ]
https://github.com/Kkevsterrr/geneva/blob/36d3585545d4cb3450ea0b166d8d5f20a64ed8d8/layers/ip_layer.py#L64-L68
spesmilo/electrum
bdbd59300fbd35b01605e66145458e5f396108e8
electrum/transaction.py
python
PartialTransaction.inputs
(self)
return self._inputs
[]
def inputs(self) -> Sequence[PartialTxInput]: return self._inputs
[ "def", "inputs", "(", "self", ")", "->", "Sequence", "[", "PartialTxInput", "]", ":", "return", "self", ".", "_inputs" ]
https://github.com/spesmilo/electrum/blob/bdbd59300fbd35b01605e66145458e5f396108e8/electrum/transaction.py#L1851-L1852
Xen0ph0n/YaraGenerator
48f529f0d85e7fff62405d9367901487e29aa28f
modules/pefile.py
python
PE.get_section_by_rva
(self, rva)
return None
Get the section containing the given address.
Get the section containing the given address.
[ "Get", "the", "section", "containing", "the", "given", "address", "." ]
def get_section_by_rva(self, rva): """Get the section containing the given address.""" sections = [s for s in self.sections if s.contains_rva(rva)] if sections: return sections[0] return None
[ "def", "get_section_by_rva", "(", "self", ",", "rva", ")", ":", "sections", "=", "[", "s", "for", "s", "in", "self", ".", "sections", "if", "s", ".", "contains_rva", "(", "rva", ")", "]", "if", "sections", ":", "return", "sections", "[", "0", "]", ...
https://github.com/Xen0ph0n/YaraGenerator/blob/48f529f0d85e7fff62405d9367901487e29aa28f/modules/pefile.py#L3915-L3923
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/wav/v20210129/models.py
python
QueryActivityJoinListResponse.__init__
(self)
r""" :param NextCursor: 分页游标 注意:此字段可能返回 null,表示取不到有效值。 :type NextCursor: str :param PageData: 活码列表响应参数 注意:此字段可能返回 null,表示取不到有效值。 :type PageData: list of ActivityJoinDetail :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
r""" :param NextCursor: 分页游标 注意:此字段可能返回 null,表示取不到有效值。 :type NextCursor: str :param PageData: 活码列表响应参数 注意:此字段可能返回 null,表示取不到有效值。 :type PageData: list of ActivityJoinDetail :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
[ "r", ":", "param", "NextCursor", ":", "分页游标", "注意:此字段可能返回", "null,表示取不到有效值。", ":", "type", "NextCursor", ":", "str", ":", "param", "PageData", ":", "活码列表响应参数", "注意:此字段可能返回", "null,表示取不到有效值。", ":", "type", "PageData", ":", "list", "of", "ActivityJoinDetail", ":",...
def __init__(self): r""" :param NextCursor: 分页游标 注意:此字段可能返回 null,表示取不到有效值。 :type NextCursor: str :param PageData: 活码列表响应参数 注意:此字段可能返回 null,表示取不到有效值。 :type PageData: list of ActivityJoinDetail :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.NextCursor = None self.PageData = None self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "NextCursor", "=", "None", "self", ".", "PageData", "=", "None", "self", ".", "RequestId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/wav/v20210129/models.py#L1150-L1163
pyg-team/pytorch_geometric
b920e9a3a64e22c8356be55301c88444ff051cae
torch_geometric/nn/pool/max_pool.py
python
max_pool_x
(cluster, x, batch, size: Optional[int] = None)
return x, batch
r"""Max-Pools node features according to the clustering defined in :attr:`cluster`. Args: cluster (LongTensor): Cluster vector :math:`\mathbf{c} \in \{ 0, \ldots, N - 1 \}^N`, which assigns each node to a specific cluster. x (Tensor): Node feature matrix :math:`\mathbf{X} \in \mathbb{R}^{(N_1 + \ldots + N_B) \times F}`. batch (LongTensor): Batch vector :math:`\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N`, which assigns each node to a specific example. size (int, optional): The maximum number of clusters in a single example. This property is useful to obtain a batch-wise dense representation, *e.g.* for applying FC layers, but should only be used if the size of the maximum number of clusters per example is known in advance. (default: :obj:`None`) :rtype: (:class:`Tensor`, :class:`LongTensor`) if :attr:`size` is :obj:`None`, else :class:`Tensor`
r"""Max-Pools node features according to the clustering defined in :attr:`cluster`.
[ "r", "Max", "-", "Pools", "node", "features", "according", "to", "the", "clustering", "defined", "in", ":", "attr", ":", "cluster", "." ]
def max_pool_x(cluster, x, batch, size: Optional[int] = None): r"""Max-Pools node features according to the clustering defined in :attr:`cluster`. Args: cluster (LongTensor): Cluster vector :math:`\mathbf{c} \in \{ 0, \ldots, N - 1 \}^N`, which assigns each node to a specific cluster. x (Tensor): Node feature matrix :math:`\mathbf{X} \in \mathbb{R}^{(N_1 + \ldots + N_B) \times F}`. batch (LongTensor): Batch vector :math:`\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N`, which assigns each node to a specific example. size (int, optional): The maximum number of clusters in a single example. This property is useful to obtain a batch-wise dense representation, *e.g.* for applying FC layers, but should only be used if the size of the maximum number of clusters per example is known in advance. (default: :obj:`None`) :rtype: (:class:`Tensor`, :class:`LongTensor`) if :attr:`size` is :obj:`None`, else :class:`Tensor` """ if size is not None: batch_size = int(batch.max().item()) + 1 return _max_pool_x(cluster, x, batch_size * size), None cluster, perm = consecutive_cluster(cluster) x = _max_pool_x(cluster, x) batch = pool_batch(perm, batch) return x, batch
[ "def", "max_pool_x", "(", "cluster", ",", "x", ",", "batch", ",", "size", ":", "Optional", "[", "int", "]", "=", "None", ")", ":", "if", "size", "is", "not", "None", ":", "batch_size", "=", "int", "(", "batch", ".", "max", "(", ")", ".", "item", ...
https://github.com/pyg-team/pytorch_geometric/blob/b920e9a3a64e22c8356be55301c88444ff051cae/torch_geometric/nn/pool/max_pool.py#L15-L43
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/ast.py
python
fix_missing_locations
(node)
return node
When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at *node*.
When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at *node*.
[ "When", "you", "compile", "a", "node", "tree", "with", "compile", "()", "the", "compiler", "expects", "lineno", "and", "col_offset", "attributes", "for", "every", "node", "that", "supports", "them", ".", "This", "is", "rather", "tedious", "to", "fill", "in",...
def fix_missing_locations(node): """ When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at *node*. """ def _fix(node, lineno, col_offset): if 'lineno' in node._attributes: if not hasattr(node, 'lineno'): node.lineno = lineno else: lineno = node.lineno if 'col_offset' in node._attributes: if not hasattr(node, 'col_offset'): node.col_offset = col_offset else: col_offset = node.col_offset for child in iter_child_nodes(node): _fix(child, lineno, col_offset) _fix(node, 1, 0) return node
[ "def", "fix_missing_locations", "(", "node", ")", ":", "def", "_fix", "(", "node", ",", "lineno", ",", "col_offset", ")", ":", "if", "'lineno'", "in", "node", ".", "_attributes", ":", "if", "not", "hasattr", "(", "node", ",", "'lineno'", ")", ":", "nod...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/ast.py#L125-L147
zbyte64/django-hyperadmin
9ac2ae284b76efb3c50a1c2899f383a27154cb54
hyperadmin/resources/wizard/resources.py
python
Wizard.__init__
(self, **kwargs)
[]
def __init__(self, **kwargs): kwargs.setdefault('resource_adaptor', None) super(Wizard, self).__init__(**kwargs)
[ "def", "__init__", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'resource_adaptor'", ",", "None", ")", "super", "(", "Wizard", ",", "self", ")", ".", "__init__", "(", "*", "*", "kwargs", ")" ]
https://github.com/zbyte64/django-hyperadmin/blob/9ac2ae284b76efb3c50a1c2899f383a27154cb54/hyperadmin/resources/wizard/resources.py#L22-L24
ring04h/wyportmap
c4201e2313504e780a7f25238eba2a2d3223e739
sqlalchemy/dialects/drizzle/base.py
python
BIGINT.__init__
(self, **kw)
Construct a BIGINTEGER.
Construct a BIGINTEGER.
[ "Construct", "a", "BIGINTEGER", "." ]
def __init__(self, **kw): """Construct a BIGINTEGER.""" super(BIGINT, self).__init__(**kw)
[ "def", "__init__", "(", "self", ",", "*", "*", "kw", ")", ":", "super", "(", "BIGINT", ",", "self", ")", ".", "__init__", "(", "*", "*", "kw", ")" ]
https://github.com/ring04h/wyportmap/blob/c4201e2313504e780a7f25238eba2a2d3223e739/sqlalchemy/dialects/drizzle/base.py#L180-L183
iGio90/Dwarf
bb3011cdffd209c7e3f5febe558053bf649ca69c
dwarf_debugger/lib/database.py
python
Database.get_module_info
(self, address)
return None
[]
def get_module_info(self, address): address = self.sanify_address(address) if address: try: address = int(address, 16) except ValueError: return None for module_info in self.modules_info: _module = self.modules_info[module_info] if _module: if _module.base <= address <= _module.base + _module.size: return _module return None
[ "def", "get_module_info", "(", "self", ",", "address", ")", ":", "address", "=", "self", ".", "sanify_address", "(", "address", ")", "if", "address", ":", "try", ":", "address", "=", "int", "(", "address", ",", "16", ")", "except", "ValueError", ":", "...
https://github.com/iGio90/Dwarf/blob/bb3011cdffd209c7e3f5febe558053bf649ca69c/dwarf_debugger/lib/database.py#L27-L41
riannevdberg/gc-mc
722f37dde381f9a2c2aa1f91e1e79a63dfba5c03
gcmc/initializations.py
python
orthogonal
(shape, scale=1.1, name=None)
return tf.Variable(scale * q[:shape[0], :shape[1]], name=name, dtype=tf.float32)
From Lasagne. Reference: Saxe et al., http://arxiv.org/abs/1312.6120
From Lasagne. Reference: Saxe et al., http://arxiv.org/abs/1312.6120
[ "From", "Lasagne", ".", "Reference", ":", "Saxe", "et", "al", ".", "http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1312", ".", "6120" ]
def orthogonal(shape, scale=1.1, name=None): """ From Lasagne. Reference: Saxe et al., http://arxiv.org/abs/1312.6120 """ flat_shape = (shape[0], np.prod(shape[1:])) a = np.random.normal(0.0, 1.0, flat_shape) u, _, v = np.linalg.svd(a, full_matrices=False) # pick the one with the correct shape q = u if u.shape == flat_shape else v q = q.reshape(shape) return tf.Variable(scale * q[:shape[0], :shape[1]], name=name, dtype=tf.float32)
[ "def", "orthogonal", "(", "shape", ",", "scale", "=", "1.1", ",", "name", "=", "None", ")", ":", "flat_shape", "=", "(", "shape", "[", "0", "]", ",", "np", ".", "prod", "(", "shape", "[", "1", ":", "]", ")", ")", "a", "=", "np", ".", "random"...
https://github.com/riannevdberg/gc-mc/blob/722f37dde381f9a2c2aa1f91e1e79a63dfba5c03/gcmc/initializations.py#L57-L68
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
snmp/datadog_checks/snmp/snmp.py
python
SnmpCheck._start_discovery
(self)
[]
def _start_discovery(self): # type: () -> None cache = read_persistent_cache(self.check_id) if cache: hosts = json.loads(cache) for host in hosts: try: ipaddress.ip_address(host) except ValueError: write_persistent_cache(self.check_id, json.dumps([])) break self._config.discovered_instances[host] = self._build_autodiscovery_config(self.instance, host) raw_discovery_interval = self._config.instance.get('discovery_interval', 3600) try: discovery_interval = float(raw_discovery_interval) except (ValueError, TypeError): message = 'discovery_interval could not be parsed as a number: {!r}'.format(raw_discovery_interval) raise ConfigurationError(message) # Pass a weakref to the discovery function to not have a reference cycle self._thread = self._thread_factory( target=discover_instances, args=(self._config, discovery_interval, weakref.ref(self)), name=self.name ) self._thread.daemon = True self._thread.start() self._executor = futures.ThreadPoolExecutor(max_workers=self._config.workers)
[ "def", "_start_discovery", "(", "self", ")", ":", "# type: () -> None", "cache", "=", "read_persistent_cache", "(", "self", ".", "check_id", ")", "if", "cache", ":", "hosts", "=", "json", ".", "loads", "(", "cache", ")", "for", "host", "in", "hosts", ":", ...
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/snmp/datadog_checks/snmp/snmp.py#L345-L371
open-mmlab/mmclassification
5232965b17b6c050f9b328b3740c631ed4034624
mmcls/models/builder.py
python
build_head
(cfg)
return HEADS.build(cfg)
Build head.
Build head.
[ "Build", "head", "." ]
def build_head(cfg): """Build head.""" return HEADS.build(cfg)
[ "def", "build_head", "(", "cfg", ")", ":", "return", "HEADS", ".", "build", "(", "cfg", ")" ]
https://github.com/open-mmlab/mmclassification/blob/5232965b17b6c050f9b328b3740c631ed4034624/mmcls/models/builder.py#L27-L29
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/smtplib.py
python
_quote_periods
(bindata)
return re.sub(br'(?m)^\.', b'..', bindata)
[]
def _quote_periods(bindata): return re.sub(br'(?m)^\.', b'..', bindata)
[ "def", "_quote_periods", "(", "bindata", ")", ":", "return", "re", ".", "sub", "(", "br'(?m)^\\.'", ",", "b'..'", ",", "bindata", ")" ]
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/smtplib.py#L167-L168
Bogdanp/dramatiq
53147a39a14bf56d690644d1ef75b206e69e8982
dramatiq/cli.py
python
try_unblock_signals
()
Unblocks HANDLED_SIGNALS on platforms that support it.
Unblocks HANDLED_SIGNALS on platforms that support it.
[ "Unblocks", "HANDLED_SIGNALS", "on", "platforms", "that", "support", "it", "." ]
def try_unblock_signals(): """Unblocks HANDLED_SIGNALS on platforms that support it.""" if hasattr(signal, "pthread_sigmask"): signal.pthread_sigmask(signal.SIG_UNBLOCK, HANDLED_SIGNALS)
[ "def", "try_unblock_signals", "(", ")", ":", "if", "hasattr", "(", "signal", ",", "\"pthread_sigmask\"", ")", ":", "signal", ".", "pthread_sigmask", "(", "signal", ".", "SIG_UNBLOCK", ",", "HANDLED_SIGNALS", ")" ]
https://github.com/Bogdanp/dramatiq/blob/53147a39a14bf56d690644d1ef75b206e69e8982/dramatiq/cli.py#L235-L238
TheSouthFrog/stylealign
910632d2fccc9db61b00c265ae18a88913113c1d
landmark_detection/lib/utils/time_utils.py
python
LossRecorderMeter.min_loss
(self, Train=True)
[]
def min_loss(self, Train=True): if Train: idx = np.argmin(self.epoch_losses[:self.current_epoch, 0]) return idx, self.epoch_losses[idx, 0] else: idx = np.argmin(self.epoch_losses[:self.current_epoch, 1]) if self.epoch_losses[idx, 1] >= sys.float_info.max / 10: return idx, -1. else: return idx, self.epoch_losses[idx, 1]
[ "def", "min_loss", "(", "self", ",", "Train", "=", "True", ")", ":", "if", "Train", ":", "idx", "=", "np", ".", "argmin", "(", "self", ".", "epoch_losses", "[", ":", "self", ".", "current_epoch", ",", "0", "]", ")", "return", "idx", ",", "self", ...
https://github.com/TheSouthFrog/stylealign/blob/910632d2fccc9db61b00c265ae18a88913113c1d/landmark_detection/lib/utils/time_utils.py#L63-L72
CouchPotato/CouchPotatoServer
7260c12f72447ddb6f062367c6dfbda03ecd4e9c
libs/qbittorrent/client.py
python
QBittorrentClient.global_transfer_info
(self)
return self._get('query/transferInfo')
Get JSON data of the global transfer info of qBittorrent.
Get JSON data of the global transfer info of qBittorrent.
[ "Get", "JSON", "data", "of", "the", "global", "transfer", "info", "of", "qBittorrent", "." ]
def global_transfer_info(self): """ Get JSON data of the global transfer info of qBittorrent. """ return self._get('query/transferInfo')
[ "def", "global_transfer_info", "(", "self", ")", ":", "return", "self", ".", "_get", "(", "'query/transferInfo'", ")" ]
https://github.com/CouchPotato/CouchPotatoServer/blob/7260c12f72447ddb6f062367c6dfbda03ecd4e9c/libs/qbittorrent/client.py#L215-L219
urwid/urwid
e2423b5069f51d318ea1ac0f355a0efe5448f7eb
urwid/container.py
python
Columns._set_widget_list
(self, widgets)
[]
def _set_widget_list(self, widgets): focus_position = self.focus_position self.contents = [ (new, options) for (new, (w, options)) in zip(widgets, # need to grow contents list if widgets is longer chain(self.contents, repeat((None, (WEIGHT, 1, False)))))] if focus_position < len(widgets): self.focus_position = focus_position
[ "def", "_set_widget_list", "(", "self", ",", "widgets", ")", ":", "focus_position", "=", "self", ".", "focus_position", "self", ".", "contents", "=", "[", "(", "new", ",", "options", ")", "for", "(", "new", ",", "(", "w", ",", "options", ")", ")", "i...
https://github.com/urwid/urwid/blob/e2423b5069f51d318ea1ac0f355a0efe5448f7eb/urwid/container.py#L1839-L1846
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/idlelib/EditorWindow.py
python
_sphinx_version
()
return release
Format sys.version_info to produce the Sphinx version string used to install the chm docs
Format sys.version_info to produce the Sphinx version string used to install the chm docs
[ "Format", "sys", ".", "version_info", "to", "produce", "the", "Sphinx", "version", "string", "used", "to", "install", "the", "chm", "docs" ]
def _sphinx_version(): "Format sys.version_info to produce the Sphinx version string used to install the chm docs" major, minor, micro, level, serial = sys.version_info release = '%s%s' % (major, minor) if micro: release += '%s' % (micro,) if level == 'candidate': release += 'rc%s' % (serial,) elif level != 'final': release += '%s%s' % (level[0], serial) return release
[ "def", "_sphinx_version", "(", ")", ":", "major", ",", "minor", ",", "micro", ",", "level", ",", "serial", "=", "sys", ".", "version_info", "release", "=", "'%s%s'", "%", "(", "major", ",", "minor", ")", "if", "micro", ":", "release", "+=", "'%s'", "...
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/idlelib/EditorWindow.py#L24-L34
msg-systems/holmes-extractor
fc536f32a5cd02a53d1c32f771adc14227d09f38
holmes_extractor/classification.py
python
SupervisedTopicModelTrainer.filter
(self, labels_to_classification_frequencies, phraselet_infos)
return new_labels_to_classification_frequencies, new_phraselet_infos
Filters the phraselets in memory based on minimum_occurrences and cv_threshold.
Filters the phraselets in memory based on minimum_occurrences and cv_threshold.
[ "Filters", "the", "phraselets", "in", "memory", "based", "on", "minimum_occurrences", "and", "cv_threshold", "." ]
def filter(self, labels_to_classification_frequencies, phraselet_infos): """ Filters the phraselets in memory based on minimum_occurrences and cv_threshold. """ accepted = 0 underminimum_occurrences = 0 under_minimum_cv = 0 new_labels_to_classification_frequencies = {} for label, classification_frequencies in labels_to_classification_frequencies.items(): at_least_minimum = False working_classification_frequencies = classification_frequencies.copy() for classification in working_classification_frequencies: if working_classification_frequencies[classification] >= self.minimum_occurrences: at_least_minimum = True if not at_least_minimum: underminimum_occurrences += 1 continue frequency_list = list(working_classification_frequencies.values()) # We only want to take explicit classification labels into account, i.e. ignore the # classification ontology. number_of_classification_labels = \ len(set( self.training_basis.training_documents_labels_to_classifications_dict.values()) ) frequency_list.extend([0] * number_of_classification_labels) frequency_list = frequency_list[:number_of_classification_labels] if statistics.pstdev(frequency_list) / statistics.mean(frequency_list) >= \ self.cv_threshold: accepted += 1 new_labels_to_classification_frequencies[label] = classification_frequencies else: under_minimum_cv += 1 if self.training_basis.verbose: print( 'Filtered: accepted', accepted, '; removed minimum occurrences', underminimum_occurrences, '; removed cv threshold', under_minimum_cv) new_phraselet_infos = [ phraselet_info for phraselet_info in phraselet_infos if phraselet_info.label in new_labels_to_classification_frequencies.keys()] return new_labels_to_classification_frequencies, new_phraselet_infos
[ "def", "filter", "(", "self", ",", "labels_to_classification_frequencies", ",", "phraselet_infos", ")", ":", "accepted", "=", "0", "underminimum_occurrences", "=", "0", "under_minimum_cv", "=", "0", "new_labels_to_classification_frequencies", "=", "{", "}", "for", "la...
https://github.com/msg-systems/holmes-extractor/blob/fc536f32a5cd02a53d1c32f771adc14227d09f38/holmes_extractor/classification.py#L428-L467
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/key_management/kms_crypto_client.py
python
KmsCryptoClient.decrypt
(self, decrypt_data_details, **kwargs)
Decrypts data using the given `DecryptDataDetails`__ resource. __ https://docs.cloud.oracle.com/api/#/en/key/latest/datatypes/DecryptDataDetails :param oci.key_management.models.DecryptDataDetails decrypt_data_details: (required) DecryptDataDetails :param str opc_request_id: (optional) Unique identifier for the request. If provided, the returned request ID will include this value. Otherwise, a random request ID will be generated by the service. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.key_management.models.DecryptedData` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/keymanagement/decrypt.py.html>`__ to see an example of how to use decrypt API.
Decrypts data using the given `DecryptDataDetails`__ resource.
[ "Decrypts", "data", "using", "the", "given", "DecryptDataDetails", "__", "resource", "." ]
def decrypt(self, decrypt_data_details, **kwargs): """ Decrypts data using the given `DecryptDataDetails`__ resource. __ https://docs.cloud.oracle.com/api/#/en/key/latest/datatypes/DecryptDataDetails :param oci.key_management.models.DecryptDataDetails decrypt_data_details: (required) DecryptDataDetails :param str opc_request_id: (optional) Unique identifier for the request. If provided, the returned request ID will include this value. Otherwise, a random request ID will be generated by the service. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.key_management.models.DecryptedData` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/keymanagement/decrypt.py.html>`__ to see an example of how to use decrypt API. """ resource_path = "/20180608/decrypt" method = "POST" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "opc_request_id" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "decrypt got unknown kwargs: {!r}".format(extra_kwargs)) header_params = { "accept": "application/json", "content-type": "application/json", "opc-request-id": kwargs.get("opc_request_id", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, header_params=header_params, body=decrypt_data_details, response_type="DecryptedData") else: return self.base_client.call_api( resource_path=resource_path, method=method, header_params=header_params, body=decrypt_data_details, response_type="DecryptedData")
[ "def", "decrypt", "(", "self", ",", "decrypt_data_details", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/20180608/decrypt\"", "method", "=", "\"POST\"", "# Don't accept unknown kwargs", "expected_kwargs", "=", "[", "\"retry_strategy\"", ",", "\"opc_req...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/key_management/kms_crypto_client.py#L100-L171
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
Lib/distutils/sysconfig.py
python
customize_compiler
(compiler)
Do any platform-specific customization of a CCompiler instance. Mainly needed on Unix, so we can plug in the information that varies across Unices and is stored in Python's Makefile.
Do any platform-specific customization of a CCompiler instance.
[ "Do", "any", "platform", "-", "specific", "customization", "of", "a", "CCompiler", "instance", "." ]
def customize_compiler(compiler): """Do any platform-specific customization of a CCompiler instance. Mainly needed on Unix, so we can plug in the information that varies across Unices and is stored in Python's Makefile. """ if compiler.compiler_type == "unix": if sys.platform == "darwin": # Perform first-time customization of compiler-related # config vars on OS X now that we know we need a compiler. # This is primarily to support Pythons from binary # installers. The kind and paths to build tools on # the user system may vary significantly from the system # that Python itself was built on. Also the user OS # version and build tools may not support the same set # of CPU architectures for universal builds. global _config_vars # Use get_config_var() to ensure _config_vars is initialized. if not get_config_var('CUSTOMIZED_OSX_COMPILER'): import _osx_support _osx_support.customize_compiler(_config_vars) _config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True' (cc, cxx, opt, cflags, ccshared, ldshared, so_ext, ar, ar_flags) = \ get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS', 'CCSHARED', 'LDSHARED', 'SO', 'AR', 'ARFLAGS') if 'CC' in os.environ: newcc = os.environ['CC'] if (sys.platform == 'darwin' and 'LDSHARED' not in os.environ and ldshared.startswith(cc)): # On OS X, if CC is overridden, use that as the default # command for LDSHARED as well ldshared = newcc + ldshared[len(cc):] cc = newcc if 'CXX' in os.environ: cxx = os.environ['CXX'] if 'LDSHARED' in os.environ: ldshared = os.environ['LDSHARED'] if 'CPP' in os.environ: cpp = os.environ['CPP'] else: cpp = cc + " -E" # not always if 'LDFLAGS' in os.environ: ldshared = ldshared + ' ' + os.environ['LDFLAGS'] if 'CFLAGS' in os.environ: cflags = opt + ' ' + os.environ['CFLAGS'] ldshared = ldshared + ' ' + os.environ['CFLAGS'] if 'CPPFLAGS' in os.environ: cpp = cpp + ' ' + os.environ['CPPFLAGS'] cflags = cflags + ' ' + os.environ['CPPFLAGS'] ldshared = ldshared + ' ' + os.environ['CPPFLAGS'] if 'AR' in os.environ: ar = os.environ['AR'] if 'ARFLAGS' in os.environ: archiver = ar + ' ' + os.environ['ARFLAGS'] else: archiver = ar + ' ' + ar_flags cc_cmd = cc + ' ' + cflags compiler.set_executables( preprocessor=cpp, compiler=cc_cmd, compiler_so=cc_cmd + ' ' + ccshared, compiler_cxx=cxx, linker_so=ldshared, linker_exe=cc, archiver=archiver) compiler.shared_lib_extension = so_ext
[ "def", "customize_compiler", "(", "compiler", ")", ":", "if", "compiler", ".", "compiler_type", "==", "\"unix\"", ":", "if", "sys", ".", "platform", "==", "\"darwin\"", ":", "# Perform first-time customization of compiler-related", "# config vars on OS X now that we know we...
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/Lib/distutils/sysconfig.py#L160-L231
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/manifolds/manifold_homset.py
python
TopologicalManifoldHomset._coerce_map_from_
(self, other)
return False
r""" Determine whether coercion to ``self`` exists from parent ``other``. EXAMPLES:: sage: M = Manifold(2, 'M', structure='topological') sage: X.<x,y> = M.chart() sage: N = Manifold(3, 'N', structure='topological') sage: Y.<u,v,w> = N.chart() sage: H = Hom(M,N) sage: H._coerce_map_from_(ZZ) False sage: H._coerce_map_from_(M) False sage: H._coerce_map_from_(N) False sage: H._coerce_map_from_(H) True
r""" Determine whether coercion to ``self`` exists from parent ``other``.
[ "r", "Determine", "whether", "coercion", "to", "self", "exists", "from", "parent", "other", "." ]
def _coerce_map_from_(self, other): r""" Determine whether coercion to ``self`` exists from parent ``other``. EXAMPLES:: sage: M = Manifold(2, 'M', structure='topological') sage: X.<x,y> = M.chart() sage: N = Manifold(3, 'N', structure='topological') sage: Y.<u,v,w> = N.chart() sage: H = Hom(M,N) sage: H._coerce_map_from_(ZZ) False sage: H._coerce_map_from_(M) False sage: H._coerce_map_from_(N) False sage: H._coerce_map_from_(H) True """ if isinstance(other, TopologicalManifoldHomset): return (other.domain().has_coerce_map_from(self.domain()) and self.codomain().has_coerce_map_from(other.codomain())) return False
[ "def", "_coerce_map_from_", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "TopologicalManifoldHomset", ")", ":", "return", "(", "other", ".", "domain", "(", ")", ".", "has_coerce_map_from", "(", "self", ".", "domain", "(", ")"...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/manifolds/manifold_homset.py#L320-L344
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/layout/ternary/_baxis.py
python
Baxis.showticklabels
(self)
return self["showticklabels"]
Determines whether or not the tick labels are drawn. The 'showticklabels' property must be specified as a bool (either True, or False) Returns ------- bool
Determines whether or not the tick labels are drawn. The 'showticklabels' property must be specified as a bool (either True, or False)
[ "Determines", "whether", "or", "not", "the", "tick", "labels", "are", "drawn", ".", "The", "showticklabels", "property", "must", "be", "specified", "as", "a", "bool", "(", "either", "True", "or", "False", ")" ]
def showticklabels(self): """ Determines whether or not the tick labels are drawn. The 'showticklabels' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showticklabels"]
[ "def", "showticklabels", "(", "self", ")", ":", "return", "self", "[", "\"showticklabels\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/layout/ternary/_baxis.py#L547-L558
XKNX/xknx
1deeeb3dc0978aebacf14492a84e1f1eaf0970ed
xknx/io/gateway_scanner.py
python
GatewayScanFilter.__init__
( self, name: str | None = None, tunnelling: bool | None = None, routing: bool | None = None, )
Initialize GatewayScanFilter class.
Initialize GatewayScanFilter class.
[ "Initialize", "GatewayScanFilter", "class", "." ]
def __init__( self, name: str | None = None, tunnelling: bool | None = None, routing: bool | None = None, ): """Initialize GatewayScanFilter class.""" self.name = name self.tunnelling = tunnelling self.routing = routing
[ "def", "__init__", "(", "self", ",", "name", ":", "str", "|", "None", "=", "None", ",", "tunnelling", ":", "bool", "|", "None", "=", "None", ",", "routing", ":", "bool", "|", "None", "=", "None", ",", ")", ":", "self", ".", "name", "=", "name", ...
https://github.com/XKNX/xknx/blob/1deeeb3dc0978aebacf14492a84e1f1eaf0970ed/xknx/io/gateway_scanner.py#L87-L96
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/ex-submodules/dimagi/utils/dates.py
python
safe_strftime
(val, fmt)
return safe_val.strftime(fmt .replace("%Y", str(val.year)) .replace("%y", str(val.year)[-2:]))
conceptually the same as val.strftime(fmt), but this works even with dates pre-1900. (For some reason, '%Y' and others do not work for pre-1900 dates in python stdlib datetime.[date|datetime].strftime.) This function strictly asserts that fmt does not contain directives whose value is dependent on the year, such as week number of the year ('%W').
conceptually the same as val.strftime(fmt), but this works even with dates pre-1900.
[ "conceptually", "the", "same", "as", "val", ".", "strftime", "(", "fmt", ")", "but", "this", "works", "even", "with", "dates", "pre", "-", "1900", "." ]
def safe_strftime(val, fmt): """ conceptually the same as val.strftime(fmt), but this works even with dates pre-1900. (For some reason, '%Y' and others do not work for pre-1900 dates in python stdlib datetime.[date|datetime].strftime.) This function strictly asserts that fmt does not contain directives whose value is dependent on the year, such as week number of the year ('%W'). """ assert '%a' not in fmt # short weekday name assert '%A' not in fmt # full weekday name assert '%w' not in fmt # weekday (Sun-Sat) as a number (0-6) assert '%U' not in fmt # week number of the year (weeks starting on Sun) assert '%W' not in fmt # week number of the year (weeks starting on Mon) assert '%c' not in fmt # full date and time representation assert '%x' not in fmt # date representation assert '%X' not in fmt # time representation # important that our dummy year is a leap year # so that it has Feb. 29 in it a_leap_year = 2012 if isinstance(val, datetime.datetime): safe_val = datetime.datetime( a_leap_year, val.month, val.day, hour=val.hour, minute=val.minute, second=val.second, microsecond=val.microsecond, tzinfo=val.tzinfo) else: safe_val = datetime.date(a_leap_year, val.month, val.day) return safe_val.strftime(fmt .replace("%Y", str(val.year)) .replace("%y", str(val.year)[-2:]))
[ "def", "safe_strftime", "(", "val", ",", "fmt", ")", ":", "assert", "'%a'", "not", "in", "fmt", "# short weekday name", "assert", "'%A'", "not", "in", "fmt", "# full weekday name", "assert", "'%w'", "not", "in", "fmt", "# weekday (Sun-Sat) as a number (0-6)", "ass...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/ex-submodules/dimagi/utils/dates.py#L450-L481