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
PaddlePaddle/PaddleX
2bab73f81ab54e328204e7871e6ae4a82e719f5d
paddlex/tools/dataset_conversion/x2coco.py
python
LabelMe2COCO.generate_images_field
(self, json_info, image_file, image_id)
return image
[]
def generate_images_field(self, json_info, image_file, image_id): image = {} image["height"] = json_info["imageHeight"] image["width"] = json_info["imageWidth"] image["id"] = image_id + 1 json_img_path = path_normalization(json_info["imagePath"]) json_info["imagePath"] = osp.join( osp.split(json_img_path)[0], image_file) image["file_name"] = osp.split(json_info["imagePath"])[-1] return image
[ "def", "generate_images_field", "(", "self", ",", "json_info", ",", "image_file", ",", "image_id", ")", ":", "image", "=", "{", "}", "image", "[", "\"height\"", "]", "=", "json_info", "[", "\"imageHeight\"", "]", "image", "[", "\"width\"", "]", "=", "json_...
https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/paddlex/tools/dataset_conversion/x2coco.py#L99-L108
solarwinds/orionsdk-python
97168451ddbc68db1773717f592a42f78be0eefe
orionsdk/solarwinds.py
python
SolarWinds.get_node_uri
(self, node_name)
Returns the NodeURI for the given NodeName. Uses a SWIS query to the SolarWinds database to retrieve this information. Args: node_name(string): A node name which should equal the caption used in SolarWinds for the node object. Returns: node_id (string): The node URI that corresponds to the specified node name.
Returns the NodeURI for the given NodeName. Uses a SWIS query to the SolarWinds database to retrieve this information.
[ "Returns", "the", "NodeURI", "for", "the", "given", "NodeName", ".", "Uses", "a", "SWIS", "query", "to", "the", "SolarWinds", "database", "to", "retrieve", "this", "information", "." ]
def get_node_uri(self, node_name): """ Returns the NodeURI for the given NodeName. Uses a SWIS query to the SolarWinds database to retrieve this information. Args: node_name(string): A node name which should equal the caption used in SolarWinds for the node object. Returns: node_id (string): The node URI that corresponds to the specified node name. """ node_uri = self.swis.query("SELECT Caption, Uri FROM Orion.Nodes WHERE Caption = @caption", caption=node_name) self.logger.info("get_node_uri - node uri query results: %s.", node_uri) if node_uri['results']: return node_uri['results'][0]['Uri'] else: return ""
[ "def", "get_node_uri", "(", "self", ",", "node_name", ")", ":", "node_uri", "=", "self", ".", "swis", ".", "query", "(", "\"SELECT Caption, Uri FROM Orion.Nodes WHERE Caption = @caption\"", ",", "caption", "=", "node_name", ")", "self", ".", "logger", ".", "info",...
https://github.com/solarwinds/orionsdk-python/blob/97168451ddbc68db1773717f592a42f78be0eefe/orionsdk/solarwinds.py#L63-L82
dropbox/changes
37e23c3141b75e4785cf398d015e3dbca41bdd56
changes/lib/mesos_lib.py
python
_update_maintenance_schedule
(master, maint_data)
Overwrite maintenance schedule on a Mesos master
Overwrite maintenance schedule on a Mesos master
[ "Overwrite", "maintenance", "schedule", "on", "a", "Mesos", "master" ]
def _update_maintenance_schedule(master, maint_data): """ Overwrite maintenance schedule on a Mesos master """ _master_api_request(master, SCHEDULE_ENDPOINT, post_data=json.dumps(maint_data))
[ "def", "_update_maintenance_schedule", "(", "master", ",", "maint_data", ")", ":", "_master_api_request", "(", "master", ",", "SCHEDULE_ENDPOINT", ",", "post_data", "=", "json", ".", "dumps", "(", "maint_data", ")", ")" ]
https://github.com/dropbox/changes/blob/37e23c3141b75e4785cf398d015e3dbca41bdd56/changes/lib/mesos_lib.py#L92-L96
statsmodels/statsmodels
debbe7ea6ba28fe5bdb78f09f8cac694bef98722
statsmodels/duration/hazard_regression.py
python
PHRegResults.martingale_residuals
(self)
return mart_resid
The martingale residuals.
The martingale residuals.
[ "The", "martingale", "residuals", "." ]
def martingale_residuals(self): """ The martingale residuals. """ surv = self.model.surv # Initialize at NaN since rows that belong to strata with no # events have undefined residuals. mart_resid = np.nan*np.ones(len(self.model.endog), dtype=np.float64) cumhaz_f_list = self.baseline_cumulative_hazard_function # Loop over strata for stx in range(surv.nstrat): cumhaz_f = cumhaz_f_list[stx] exog_s = surv.exog_s[stx] time_s = surv.time_s[stx] linpred = np.dot(exog_s, self.params) if surv.offset_s is not None: linpred += surv.offset_s[stx] e_linpred = np.exp(linpred) ii = surv.stratum_rows[stx] chaz = cumhaz_f(time_s) mart_resid[ii] = self.model.status[ii] - e_linpred * chaz return mart_resid
[ "def", "martingale_residuals", "(", "self", ")", ":", "surv", "=", "self", ".", "model", ".", "surv", "# Initialize at NaN since rows that belong to strata with no", "# events have undefined residuals.", "mart_resid", "=", "np", ".", "nan", "*", "np", ".", "ones", "("...
https://github.com/statsmodels/statsmodels/blob/debbe7ea6ba28fe5bdb78f09f8cac694bef98722/statsmodels/duration/hazard_regression.py#L1541-L1571
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/string.py
python
capwords
(s, sep=None)
return (sep or ' ').join(map(str.capitalize, s.split(sep)))
capwords(s [,sep]) -> string Split the argument into words using split, capitalize each word using capitalize, and join the capitalized words using join. If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words.
capwords(s [,sep]) -> string
[ "capwords", "(", "s", "[", "sep", "]", ")", "-", ">", "string" ]
def capwords(s, sep=None): """capwords(s [,sep]) -> string Split the argument into words using split, capitalize each word using capitalize, and join the capitalized words using join. If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words. """ return (sep or ' ').join(map(str.capitalize, s.split(sep)))
[ "def", "capwords", "(", "s", ",", "sep", "=", "None", ")", ":", "return", "(", "sep", "or", "' '", ")", ".", "join", "(", "map", "(", "str", ".", "capitalize", ",", "s", ".", "split", "(", "sep", ")", ")", ")" ]
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/string.py#L37-L48
OpenMDAO/OpenMDAO
f47eb5485a0bb5ea5d2ae5bd6da4b94dc6b296bd
openmdao/jacobians/jacobian.py
python
Jacobian._randomize_subjac
(self, subjac, key)
return r
Return a subjac that is the given subjac filled with random values. Parameters ---------- subjac : ndarray or csc_matrix Sub-jacobian to be randomized. key : tuple (of, wrt) Key for subjac within the jacobian. Returns ------- ndarray or csc_matrix Randomized version of the subjac.
Return a subjac that is the given subjac filled with random values.
[ "Return", "a", "subjac", "that", "is", "the", "given", "subjac", "filled", "with", "random", "values", "." ]
def _randomize_subjac(self, subjac, key): """ Return a subjac that is the given subjac filled with random values. Parameters ---------- subjac : ndarray or csc_matrix Sub-jacobian to be randomized. key : tuple (of, wrt) Key for subjac within the jacobian. Returns ------- ndarray or csc_matrix Randomized version of the subjac. """ if isinstance(subjac, sparse_types): # sparse sparse = subjac.copy() sparse.data = rand(sparse.data.size) sparse.data += 1.0 return sparse # if a subsystem has computed a dynamic partial or semi-total coloring, # we use that sparsity information to set the sparsity of the randomized # subjac. Otherwise all subjacs that didn't have sparsity declared by the # user will appear completely dense, which will lead to a total jacobian that # is more dense than it should be, causing any total coloring that we compute # to be overly conservative. subjac_info = self._subjacs_info[key] if 'sparsity' in subjac_info: assert subjac_info['rows'] is None rows, cols, shape = subjac_info['sparsity'] r = np.zeros(shape) val = rand(len(rows)) val += 1.0 r[rows, cols] = val else: r = rand(*subjac.shape) r += 1.0 return r
[ "def", "_randomize_subjac", "(", "self", ",", "subjac", ",", "key", ")", ":", "if", "isinstance", "(", "subjac", ",", "sparse_types", ")", ":", "# sparse", "sparse", "=", "subjac", ".", "copy", "(", ")", "sparse", ".", "data", "=", "rand", "(", "sparse...
https://github.com/OpenMDAO/OpenMDAO/blob/f47eb5485a0bb5ea5d2ae5bd6da4b94dc6b296bd/openmdao/jacobians/jacobian.py#L260-L299
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/django/views/decorators/cache.py
python
cache_control
(**kwargs)
return _cache_controller
[]
def cache_control(**kwargs): def _cache_controller(viewfunc): @wraps(viewfunc, assigned=available_attrs(viewfunc)) def _cache_controlled(request, *args, **kw): response = viewfunc(request, *args, **kw) patch_cache_control(response, **kwargs) return response return _cache_controlled return _cache_controller
[ "def", "cache_control", "(", "*", "*", "kwargs", ")", ":", "def", "_cache_controller", "(", "viewfunc", ")", ":", "@", "wraps", "(", "viewfunc", ",", "assigned", "=", "available_attrs", "(", "viewfunc", ")", ")", "def", "_cache_controlled", "(", "request", ...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/views/decorators/cache.py#L39-L47
barseghyanartur/django-elasticsearch-dsl-drf
8fe35265d44501269b2603570773be47f20fa471
examples/simple/settings/core.py
python
project_dir
(base)
return os.path.abspath( os.path.join(os.path.dirname(__file__), base).replace('\\', '/') )
Absolute path to a file from current directory.
Absolute path to a file from current directory.
[ "Absolute", "path", "to", "a", "file", "from", "current", "directory", "." ]
def project_dir(base): """Absolute path to a file from current directory.""" return os.path.abspath( os.path.join(os.path.dirname(__file__), base).replace('\\', '/') )
[ "def", "project_dir", "(", "base", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "base", ")", ".", "replace", "(", "'\\\\'", ",", "'/...
https://github.com/barseghyanartur/django-elasticsearch-dsl-drf/blob/8fe35265d44501269b2603570773be47f20fa471/examples/simple/settings/core.py#L10-L14
tahoe-lafs/tahoe-lafs
766a53b5208c03c45ca0a98e97eee76870276aa1
src/allmydata/frontends/sftpd.py
python
_convert_error
(res, request)
If res is not a Failure, return it, otherwise reraise the appropriate SFTPError.
If res is not a Failure, return it, otherwise reraise the appropriate SFTPError.
[ "If", "res", "is", "not", "a", "Failure", "return", "it", "otherwise", "reraise", "the", "appropriate", "SFTPError", "." ]
def _convert_error(res, request): """If res is not a Failure, return it, otherwise reraise the appropriate SFTPError.""" if not isinstance(res, Failure): logged_res = res if isinstance(res, (bytes, str)): logged_res = "<data of length %r>" % (len(res),) logmsg("SUCCESS %r %r" % (request, logged_res,), level=OPERATIONAL) return res err = res logmsg("RAISE %r %r" % (request, err.value), level=OPERATIONAL) try: if noisy: logmsg(traceback.format_exc(err.value), level=NOISY) except Exception: # pragma: no cover pass # The message argument to SFTPError must not reveal information that # might compromise anonymity, if we are running over an anonymous network. if err.check(SFTPError): # original raiser of SFTPError has responsibility to ensure anonymity raise err if err.check(NoSuchChildError): childname = _utf8(err.value.args[0]) raise createSFTPError(FX_NO_SUCH_FILE, childname) if err.check(NotWriteableError) or err.check(ChildOfWrongTypeError): msg = _utf8(err.value.args[0]) raise createSFTPError(FX_PERMISSION_DENIED, msg) if err.check(ExistingChildError): # Versions of SFTP after v3 (which is what twisted.conch implements) # define a specific error code for this case: FX_FILE_ALREADY_EXISTS. # However v3 doesn't; instead, other servers such as sshd return # FX_FAILURE. The gvfs SFTP backend, for example, depends on this # to translate the error to the equivalent of POSIX EEXIST, which is # necessary for some picky programs (such as gedit). msg = _utf8(err.value.args[0]) raise createSFTPError(FX_FAILURE, msg) if err.check(NotImplementedError): raise createSFTPError(FX_OP_UNSUPPORTED, _utf8(err.value)) if err.check(EOFError): raise createSFTPError(FX_EOF, "end of file reached") if err.check(defer.FirstError): _convert_error(err.value.subFailure, request) # We assume that the error message is not anonymity-sensitive. raise createSFTPError(FX_FAILURE, _utf8(err.value))
[ "def", "_convert_error", "(", "res", ",", "request", ")", ":", "if", "not", "isinstance", "(", "res", ",", "Failure", ")", ":", "logged_res", "=", "res", "if", "isinstance", "(", "res", ",", "(", "bytes", ",", "str", ")", ")", ":", "logged_res", "=",...
https://github.com/tahoe-lafs/tahoe-lafs/blob/766a53b5208c03c45ca0a98e97eee76870276aa1/src/allmydata/frontends/sftpd.py#L92-L138
GoogleCloudPlatform/gsutil
5be882803e76608e2fd29cf8c504ccd1fe0a7746
gslib/commands/acl.py
python
AclCommand.ApplyAclChanges
(self, name_expansion_result, thread_state=None)
Applies the changes in self.changes to the provided URL. Args: name_expansion_result: NameExpansionResult describing the target object. thread_state: If present, gsutil Cloud API instance to apply the changes.
Applies the changes in self.changes to the provided URL.
[ "Applies", "the", "changes", "in", "self", ".", "changes", "to", "the", "provided", "URL", "." ]
def ApplyAclChanges(self, name_expansion_result, thread_state=None): """Applies the changes in self.changes to the provided URL. Args: name_expansion_result: NameExpansionResult describing the target object. thread_state: If present, gsutil Cloud API instance to apply the changes. """ if thread_state: gsutil_api = thread_state else: gsutil_api = self.gsutil_api url = name_expansion_result.expanded_storage_url if url.IsBucket(): bucket = gsutil_api.GetBucket(url.bucket_name, provider=url.scheme, fields=['acl', 'metageneration']) current_acl = bucket.acl elif url.IsObject(): gcs_object = encoding.JsonToMessage(apitools_messages.Object, name_expansion_result.expanded_result) current_acl = gcs_object.acl if not current_acl: self._RaiseForAccessDenied(url) if self._ApplyAclChangesAndReturnChangeCount(url, current_acl) == 0: self.logger.info('No changes to %s', url) return try: if url.IsBucket(): preconditions = Preconditions(meta_gen_match=bucket.metageneration) bucket_metadata = apitools_messages.Bucket(acl=current_acl) gsutil_api.PatchBucket(url.bucket_name, bucket_metadata, preconditions=preconditions, provider=url.scheme, fields=['id']) else: # Object preconditions = Preconditions(gen_match=gcs_object.generation, meta_gen_match=gcs_object.metageneration) object_metadata = apitools_messages.Object(acl=current_acl) try: gsutil_api.PatchObjectMetadata(url.bucket_name, url.object_name, object_metadata, preconditions=preconditions, provider=url.scheme, generation=url.generation, fields=['id']) except PreconditionException as e: # Special retry case where we want to do an additional step, the read # of the read-modify-write cycle, to fetch the correct object # metadata before reattempting ACL changes. self._RefetchObjectMetadataAndApplyAclChanges(url, gsutil_api) self.logger.info('Updated ACL on %s', url) except BadRequestException as e: # Don't retry on bad requests, e.g. invalid email address. raise CommandException('Received bad request from server: %s' % str(e)) except AccessDeniedException: self._RaiseForAccessDenied(url) except PreconditionException as e: # For objects, retry attempts should have already been handled. if url.IsObject(): raise CommandException(str(e)) # For buckets, raise PreconditionException and continue to next retry. raise e
[ "def", "ApplyAclChanges", "(", "self", ",", "name_expansion_result", ",", "thread_state", "=", "None", ")", ":", "if", "thread_state", ":", "gsutil_api", "=", "thread_state", "else", ":", "gsutil_api", "=", "self", ".", "gsutil_api", "url", "=", "name_expansion_...
https://github.com/GoogleCloudPlatform/gsutil/blob/5be882803e76608e2fd29cf8c504ccd1fe0a7746/gslib/commands/acl.py#L426-L493
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/_xmlplus/parsers/xmlproc/xmldtd.py
python
FNDABuilder.new_transition_cur2rem
(self,label)
Adds a new transition from the current state to the last remembered state.
Adds a new transition from the current state to the last remembered state.
[ "Adds", "a", "new", "transition", "from", "the", "current", "state", "to", "the", "last", "remembered", "state", "." ]
def new_transition_cur2rem(self,label): """Adds a new transition from the current state to the last remembered state.""" self.__transitions[self.__current].append((self.__mem[-1],label))
[ "def", "new_transition_cur2rem", "(", "self", ",", "label", ")", ":", "self", ".", "__transitions", "[", "self", ".", "__current", "]", ".", "append", "(", "(", "self", ".", "__mem", "[", "-", "1", "]", ",", "label", ")", ")" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/_xmlplus/parsers/xmlproc/xmldtd.py#L571-L574
out0fmemory/GoAgent-Always-Available
c4254984fea633ce3d1893fe5901debd9f22c2a9
server/lib/google/appengine/ext/ndb/query.py
python
Query._fetch_page_async
(self, page_size, **q_options)
Internal version of fetch_page_async().
Internal version of fetch_page_async().
[ "Internal", "version", "of", "fetch_page_async", "()", "." ]
def _fetch_page_async(self, page_size, **q_options): """Internal version of fetch_page_async().""" q_options.setdefault('batch_size', page_size) q_options.setdefault('produce_cursors', True) it = self.iter(limit=page_size + 1, **q_options) results = [] while (yield it.has_next_async()): results.append(it.next()) if len(results) >= page_size: break try: cursor = it.cursor_after() except datastore_errors.BadArgumentError: cursor = None raise tasklets.Return(results, cursor, it.probably_has_next())
[ "def", "_fetch_page_async", "(", "self", ",", "page_size", ",", "*", "*", "q_options", ")", ":", "q_options", ".", "setdefault", "(", "'batch_size'", ",", "page_size", ")", "q_options", ".", "setdefault", "(", "'produce_cursors'", ",", "True", ")", "it", "="...
https://github.com/out0fmemory/GoAgent-Always-Available/blob/c4254984fea633ce3d1893fe5901debd9f22c2a9/server/lib/google/appengine/ext/ndb/query.py#L1359-L1373
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/polys/polyclasses.py
python
DMP.compose
(f, g)
return per(dmp_compose(F, G, lev, dom))
Computes functional composition of ``f`` and ``g``.
Computes functional composition of ``f`` and ``g``.
[ "Computes", "functional", "composition", "of", "f", "and", "g", "." ]
def compose(f, g): """Computes functional composition of ``f`` and ``g``. """ lev, dom, per, F, G = f.unify(g) return per(dmp_compose(F, G, lev, dom))
[ "def", "compose", "(", "f", ",", "g", ")", ":", "lev", ",", "dom", ",", "per", ",", "F", ",", "G", "=", "f", ".", "unify", "(", "g", ")", "return", "per", "(", "dmp_compose", "(", "F", ",", "G", ",", "lev", ",", "dom", ")", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/polys/polyclasses.py#L723-L726
Ledger-Donjon/lascar
7a1fc2187a9b642efcdda5d9177f86ec2345d7ba
lascar/engine/engine.py
python
Engine.__init__
(self, name)
:param name: the name chosen for the Engine
:param name: the name chosen for the Engine
[ ":", "param", "name", ":", "the", "name", "chosen", "for", "the", "Engine" ]
def __init__(self, name): """ :param name: the name chosen for the Engine """ if name is None: name = hex(id(self))[2:] self.name = name self.logger = logging.getLogger(__name__) self.size_in_memory = 0 self.result = {} self.finalize_step = [] self.is_initialized = False self.output_parser_mode = "basic"
[ "def", "__init__", "(", "self", ",", "name", ")", ":", "if", "name", "is", "None", ":", "name", "=", "hex", "(", "id", "(", "self", ")", ")", "[", "2", ":", "]", "self", ".", "name", "=", "name", "self", ".", "logger", "=", "logging", ".", "g...
https://github.com/Ledger-Donjon/lascar/blob/7a1fc2187a9b642efcdda5d9177f86ec2345d7ba/lascar/engine/engine.py#L39-L55
josiah-wolf-oberholtzer/supriya
5ca725a6b97edfbe016a75666d420ecfdf49592f
dev/etc/pending_ugens/DynKlank.py
python
DynKlank.specifications_array_ref
(self)
return self._inputs[index]
Gets `specifications_array_ref` input of DynKlank. :: >>> dyn_klank = supriya.ugens.DynKlank.ar( ... decayscale=1, ... freqoffset=0, ... freqscale=1, ... input=input, ... specifications_array_ref=specifications_array_ref, ... ) >>> dyn_klank.specifications_array_ref Returns ugen input.
Gets `specifications_array_ref` input of DynKlank.
[ "Gets", "specifications_array_ref", "input", "of", "DynKlank", "." ]
def specifications_array_ref(self): """ Gets `specifications_array_ref` input of DynKlank. :: >>> dyn_klank = supriya.ugens.DynKlank.ar( ... decayscale=1, ... freqoffset=0, ... freqscale=1, ... input=input, ... specifications_array_ref=specifications_array_ref, ... ) >>> dyn_klank.specifications_array_ref Returns ugen input. """ index = self._ordered_input_names.index('specifications_array_ref') return self._inputs[index]
[ "def", "specifications_array_ref", "(", "self", ")", ":", "index", "=", "self", ".", "_ordered_input_names", ".", "index", "(", "'specifications_array_ref'", ")", "return", "self", ".", "_inputs", "[", "index", "]" ]
https://github.com/josiah-wolf-oberholtzer/supriya/blob/5ca725a6b97edfbe016a75666d420ecfdf49592f/dev/etc/pending_ugens/DynKlank.py#L226-L244
google-research/language
61fa7260ac7d690d11ef72ca863e45a37c0bdc80
language/templama/sling2facts.py
python
SlingExtractor.as_string
(self, x)
Return a string based on x.id or x.id[x.name].
Return a string based on x.id or x.id[x.name].
[ "Return", "a", "string", "based", "on", "x", ".", "id", "or", "x", ".", "id", "[", "x", ".", "name", "]", "." ]
def as_string(self, x): """Return a string based on x.id or x.id[x.name].""" x_name = self.get_name(x) if x is None: x_str = 'None' elif isinstance(x, sling.Frame) and 'id' in x: x_str = x.id else: try: x_str = str(x) except UnicodeDecodeError: x_str = 'None' if FLAGS.show_names: return ('%s[%s]' % (x_str, x_name)) if x_name else ('%s[]' % x_str) else: return x_str
[ "def", "as_string", "(", "self", ",", "x", ")", ":", "x_name", "=", "self", ".", "get_name", "(", "x", ")", "if", "x", "is", "None", ":", "x_str", "=", "'None'", "elif", "isinstance", "(", "x", ",", "sling", ".", "Frame", ")", "and", "'id'", "in"...
https://github.com/google-research/language/blob/61fa7260ac7d690d11ef72ca863e45a37c0bdc80/language/templama/sling2facts.py#L370-L385
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
pypy/module/cpyext/stubs.py
python
_PyImport_FindExtension
(space, name, filename)
For internal use only.
For internal use only.
[ "For", "internal", "use", "only", "." ]
def _PyImport_FindExtension(space, name, filename): """For internal use only.""" raise NotImplementedError
[ "def", "_PyImport_FindExtension", "(", "space", ",", "name", ",", "filename", ")", ":", "raise", "NotImplementedError" ]
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/pypy/module/cpyext/stubs.py#L654-L656
rhinstaller/anaconda
63edc8680f1b05cbfe11bef28703acba808c5174
pyanaconda/input_checking.py
python
CheckResult.error_message
(self)
return self._error_message
Optional error message describing why the input is not valid. :returns: why the input is bad (provided it is bad) or None :rtype: str or None
Optional error message describing why the input is not valid.
[ "Optional", "error", "message", "describing", "why", "the", "input", "is", "not", "valid", "." ]
def error_message(self): """Optional error message describing why the input is not valid. :returns: why the input is bad (provided it is bad) or None :rtype: str or None """ return self._error_message
[ "def", "error_message", "(", "self", ")", ":", "return", "self", ".", "_error_message" ]
https://github.com/rhinstaller/anaconda/blob/63edc8680f1b05cbfe11bef28703acba808c5174/pyanaconda/input_checking.py#L218-L224
pypr/pysph
9cb9a859934939307c65a25cbf73e4ecc83fea4a
pysph/sph/integrator_cython_helper.py
python
IntegratorCythonHelper._check_arrays_for_properties
(self, dest, args)
Given a particle array name and a set of arguments used by an integrator stepper method, check if the particle array has the required props.
Given a particle array name and a set of arguments used by an integrator stepper method, check if the particle array has the required props.
[ "Given", "a", "particle", "array", "name", "and", "a", "set", "of", "arguments", "used", "by", "an", "integrator", "stepper", "method", "check", "if", "the", "particle", "array", "has", "the", "required", "props", "." ]
def _check_arrays_for_properties(self, dest, args): """Given a particle array name and a set of arguments used by an integrator stepper method, check if the particle array has the required props. """ pa = self._particle_arrays[dest] # Remove the 's_' or 'd_' props = set([x[2:] for x in args]) available_props = set(pa.properties.keys()).union(pa.constants.keys()) if not props.issubset(available_props): diff = props.difference(available_props) integrator_name = self.object.steppers[dest].__class__.__name__ names = ', '.join([x for x in sorted(diff)]) msg = "ERROR: {integrator_name} requires the following "\ "properties:\n\t{names}\n"\ "Please add them to the particle array '{dest}'.".format( integrator_name=integrator_name, names=names, dest=dest ) self._runtime_error(msg)
[ "def", "_check_arrays_for_properties", "(", "self", ",", "dest", ",", "args", ")", ":", "pa", "=", "self", ".", "_particle_arrays", "[", "dest", "]", "# Remove the 's_' or 'd_'", "props", "=", "set", "(", "[", "x", "[", "2", ":", "]", "for", "x", "in", ...
https://github.com/pypr/pysph/blob/9cb9a859934939307c65a25cbf73e4ecc83fea4a/pysph/sph/integrator_cython_helper.py#L189-L208
openstack/octavia
27e5b27d31c695ba72fb6750de2bdafd76e0d7d9
octavia/db/repositories.py
python
ListenerRepository.create
(self, session, **model_kwargs)
return model.to_data_model()
Creates a new Listener with some validation.
Creates a new Listener with some validation.
[ "Creates", "a", "new", "Listener", "with", "some", "validation", "." ]
def create(self, session, **model_kwargs): """Creates a new Listener with some validation.""" with session.begin(subtransactions=True): listener_id = model_kwargs.get('id') allowed_cidrs = set(model_kwargs.pop('allowed_cidrs', []) or []) model_kwargs['allowed_cidrs'] = [ models.ListenerCidr(listener_id=listener_id, cidr=cidr) for cidr in allowed_cidrs] model = self.model_class(**model_kwargs) if model.default_pool_id: model.default_pool = self._pool_check( session, model.default_pool_id, lb_id=model.load_balancer_id) if model.peer_port is None: model.peer_port = self._find_next_peer_port( session, lb_id=model.load_balancer_id) session.add(model) return model.to_data_model()
[ "def", "create", "(", "self", ",", "session", ",", "*", "*", "model_kwargs", ")", ":", "with", "session", ".", "begin", "(", "subtransactions", "=", "True", ")", ":", "listener_id", "=", "model_kwargs", ".", "get", "(", "'id'", ")", "allowed_cidrs", "=",...
https://github.com/openstack/octavia/blob/27e5b27d31c695ba72fb6750de2bdafd76e0d7d9/octavia/db/repositories.py#L1188-L1205
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/rh_ip.py
python
get_network_settings
()
return _read_file(_RH_NETWORK_FILE)
Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings
Return the contents of the global network script.
[ "Return", "the", "contents", "of", "the", "global", "network", "script", "." ]
def get_network_settings(): """ Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings """ return _read_file(_RH_NETWORK_FILE)
[ "def", "get_network_settings", "(", ")", ":", "return", "_read_file", "(", "_RH_NETWORK_FILE", ")" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/rh_ip.py#L1205-L1215
Komodo/KomodoEdit
61edab75dce2bdb03943b387b0608ea36f548e8e
src/codeintel/play/core.py
python
NotifyEvent.Veto
(*args, **kwargs)
return _core.NotifyEvent_Veto(*args, **kwargs)
Veto()
Veto()
[ "Veto", "()" ]
def Veto(*args, **kwargs): """Veto()""" return _core.NotifyEvent_Veto(*args, **kwargs)
[ "def", "Veto", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core", ".", "NotifyEvent_Veto", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/src/codeintel/play/core.py#L3180-L3182
canonical/cloud-init
dc1aabfca851e520693c05322f724bd102c76364
cloudinit/sources/helpers/openstack.py
python
ConfigDriveReader.read_v1
(self)
return results
Reads a version 1 formatted location. Return a dict with metadata, userdata, dsmode, files and version (1). If not a valid path, raise a NonReadable exception.
Reads a version 1 formatted location.
[ "Reads", "a", "version", "1", "formatted", "location", "." ]
def read_v1(self): """Reads a version 1 formatted location. Return a dict with metadata, userdata, dsmode, files and version (1). If not a valid path, raise a NonReadable exception. """ found = {} for name in FILES_V1.keys(): path = self._path_join(self.base_path, name) if os.path.exists(path): found[name] = path if len(found) == 0: raise NonReadable("%s: no files found" % (self.base_path)) md = {} for (name, (key, translator, default)) in FILES_V1.items(): if name in found: path = found[name] try: contents = self._path_read(path) except IOError as e: raise BrokenMetadata("Failed to read: %s" % path) from e try: # Disable not-callable pylint check; pylint isn't able to # determine that every member of FILES_V1 has a callable in # the appropriate position md[key] = translator(contents) # pylint: disable=E1102 except Exception as e: raise BrokenMetadata( "Failed to process path %s: %s" % (path, e) ) from e else: md[key] = copy.deepcopy(default) keydata = md["authorized_keys"] meta_js = md["meta_js"] # keydata in meta_js is preferred over "injected" keydata = meta_js.get("public-keys", keydata) if keydata: lines = keydata.splitlines() md["public-keys"] = [ line for line in lines if len(line) and not line.startswith("#") ] # config-drive-v1 has no way for openstack to provide the instance-id # so we copy that into metadata from the user input if "instance-id" in meta_js: md["instance-id"] = meta_js["instance-id"] results = { "version": 1, "metadata": md, } # allow the user to specify 'dsmode' in a meta tag if "dsmode" in meta_js: results["dsmode"] = meta_js["dsmode"] # config-drive-v1 has no way of specifying user-data, so the user has # to cheat and stuff it in a meta tag also. results["userdata"] = meta_js.get("user-data", "") # this implementation does not support files other than # network/interfaces and authorized_keys... results["files"] = {} return results
[ "def", "read_v1", "(", "self", ")", ":", "found", "=", "{", "}", "for", "name", "in", "FILES_V1", ".", "keys", "(", ")", ":", "path", "=", "self", ".", "_path_join", "(", "self", ".", "base_path", ",", "name", ")", "if", "os", ".", "path", ".", ...
https://github.com/canonical/cloud-init/blob/dc1aabfca851e520693c05322f724bd102c76364/cloudinit/sources/helpers/openstack.py#L394-L465
hasanirtiza/Pedestron
3bdcf8476edc0741f28a80dd4cb161ac532507ee
tools/ECPB/eval.py
python
evaluate_detection
(results_path, det_path, gt_path, det_method_name, eval_type='pedestrian')
[]
def evaluate_detection(results_path, det_path, gt_path, det_method_name, eval_type='pedestrian'): # print ('Start evaluation for {}'.format(det_method_name)) results = [] for difficulty in ['reasonable', 'small', 'occluded', 'all']: # False is the default case used by the benchmark server, # use [True, False] if you want to compare the enforce with the ignore setting for ignore_other_vru in [True,]: result = evaluate(difficulty, ignore_other_vru, results_path, det_path, gt_path, det_method_name, use_cache=False, eval_type=eval_type) results.append(result) print(['reasonable', 'small', 'occluded', 'all'], results)
[ "def", "evaluate_detection", "(", "results_path", ",", "det_path", ",", "gt_path", ",", "det_method_name", ",", "eval_type", "=", "'pedestrian'", ")", ":", "# print ('Start evaluation for {}'.format(det_method_name))", "results", "=", "[", "]", "for", "difficulty", "in"...
https://github.com/hasanirtiza/Pedestron/blob/3bdcf8476edc0741f28a80dd4cb161ac532507ee/tools/ECPB/eval.py#L111-L121
kerlomz/captcha_trainer
72b0cd02c66a9b44073820098155b3278c8bde61
optimizer/AdaBound.py
python
AdaBoundOptimizer._resource_apply_sparse
(self, grad, var, indices)
return self._apply_sparse_shared( grad, var, indices, self._resource_scatter_add)
[]
def _resource_apply_sparse(self, grad, var, indices): return self._apply_sparse_shared( grad, var, indices, self._resource_scatter_add)
[ "def", "_resource_apply_sparse", "(", "self", ",", "grad", ",", "var", ",", "indices", ")", ":", "return", "self", ".", "_apply_sparse_shared", "(", "grad", ",", "var", ",", "indices", ",", "self", ".", "_resource_scatter_add", ")" ]
https://github.com/kerlomz/captcha_trainer/blob/72b0cd02c66a9b44073820098155b3278c8bde61/optimizer/AdaBound.py#L240-L242
romanz/amodem
883ecb433415a7f8398e903acbd1e2bb537bf822
amodem/levinson.py
python
solver
(t, y)
return x
Solve Mx = y for x, where M[i,j] = t[|i-j|], in O(N^2) steps. See http://en.wikipedia.org/wiki/Levinson_recursion for details.
Solve Mx = y for x, where M[i,j] = t[|i-j|], in O(N^2) steps. See http://en.wikipedia.org/wiki/Levinson_recursion for details.
[ "Solve", "Mx", "=", "y", "for", "x", "where", "M", "[", "i", "j", "]", "=", "t", "[", "|i", "-", "j|", "]", "in", "O", "(", "N^2", ")", "steps", ".", "See", "http", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Levinson_...
def solver(t, y): """ Solve Mx = y for x, where M[i,j] = t[|i-j|], in O(N^2) steps. See http://en.wikipedia.org/wiki/Levinson_recursion for details. """ N = len(t) assert len(y) == N t0 = np.array([1.0 / t[0]]) f = [t0] # forward vectors b = [t0] # backward vectors for n in range(1, N): prev_f = f[-1] prev_b = b[-1] ef = sum(t[n-i] * prev_f[i] for i in range(n)) eb = sum(t[i+1] * prev_b[i] for i in range(n)) f_ = np.concatenate([prev_f, [0]]) b_ = np.concatenate([[0], prev_b]) det = 1.0 - ef * eb f.append((f_ - ef * b_) / det) b.append((b_ - eb * f_) / det) x = [] for n in range(N): x = np.concatenate([x, [0]]) ef = sum(t[n-i] * x[i] for i in range(n)) x = x + (y[n] - ef) * b[n] return x
[ "def", "solver", "(", "t", ",", "y", ")", ":", "N", "=", "len", "(", "t", ")", "assert", "len", "(", "y", ")", "==", "N", "t0", "=", "np", ".", "array", "(", "[", "1.0", "/", "t", "[", "0", "]", "]", ")", "f", "=", "[", "t0", "]", "# ...
https://github.com/romanz/amodem/blob/883ecb433415a7f8398e903acbd1e2bb537bf822/amodem/levinson.py#L4-L30
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
lib-python/2.7/logging/__init__.py
python
Handler.close
(self)
Tidy up any resources used by the handler. This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods.
Tidy up any resources used by the handler.
[ "Tidy", "up", "any", "resources", "used", "by", "the", "handler", "." ]
def close(self): """ Tidy up any resources used by the handler. This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods. """ #get the module data lock, as we're updating a shared structure. _acquireLock() try: #unlikely to raise an exception, but you never know... if self._name and self._name in _handlers: del _handlers[self._name] finally: _releaseLock()
[ "def", "close", "(", "self", ")", ":", "#get the module data lock, as we're updating a shared structure.", "_acquireLock", "(", ")", "try", ":", "#unlikely to raise an exception, but you never know...", "if", "self", ".", "_name", "and", "self", ".", "_name", "in", "_hand...
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib-python/2.7/logging/__init__.py#L792-L807
spesmilo/electrum
bdbd59300fbd35b01605e66145458e5f396108e8
electrum/lnpeer.py
python
can_send_shutdown
(self, chan: Channel)
return False
[]
def can_send_shutdown(self, chan: Channel): if chan.get_state() >= ChannelState.OPENING: return True if chan.constraints.is_initiator and chan.channel_id in self.funding_created_sent: return True if not chan.constraints.is_initiator and chan.channel_id in self.funding_signed_sent: return True return False
[ "def", "can_send_shutdown", "(", "self", ",", "chan", ":", "Channel", ")", ":", "if", "chan", ".", "get_state", "(", ")", ">=", "ChannelState", ".", "OPENING", ":", "return", "True", "if", "chan", ".", "constraints", ".", "is_initiator", "and", "chan", "...
https://github.com/spesmilo/electrum/blob/bdbd59300fbd35b01605e66145458e5f396108e8/electrum/lnpeer.py#L1729-L1736
log2timeline/plaso
fe2e316b8c76a0141760c0f2f181d84acb83abc2
plaso/engine/worker.py
python
EventExtractionWorker._AnalyzeDataStream
( self, file_entry, data_stream_name, display_name, event_data_stream)
Analyzes the contents of a specific data stream of a file entry. The results of the analyzers are set in the event data stream as attributes that are added to produced event objects. Note that some file systems allow directories to have data streams, such as NTFS. Args: file_entry (dfvfs.FileEntry): file entry whose data stream is to be analyzed. data_stream_name (str): name of the data stream. display_name (str): human readable representation of the file entry currently being analyzed. event_data_stream (EventDataStream): event data stream attribute container. Raises: RuntimeError: if the file-like object cannot be retrieved from the file entry.
Analyzes the contents of a specific data stream of a file entry.
[ "Analyzes", "the", "contents", "of", "a", "specific", "data", "stream", "of", "a", "file", "entry", "." ]
def _AnalyzeDataStream( self, file_entry, data_stream_name, display_name, event_data_stream): """Analyzes the contents of a specific data stream of a file entry. The results of the analyzers are set in the event data stream as attributes that are added to produced event objects. Note that some file systems allow directories to have data streams, such as NTFS. Args: file_entry (dfvfs.FileEntry): file entry whose data stream is to be analyzed. data_stream_name (str): name of the data stream. display_name (str): human readable representation of the file entry currently being analyzed. event_data_stream (EventDataStream): event data stream attribute container. Raises: RuntimeError: if the file-like object cannot be retrieved from the file entry. """ logger.debug('[AnalyzeDataStream] analyzing file: {0:s}'.format( display_name)) if self._processing_profiler: self._processing_profiler.StartTiming('analyzing') try: file_object = file_entry.GetFileObject(data_stream_name=data_stream_name) if not file_object: raise RuntimeError(( 'Unable to retrieve file-like object for file entry: ' '{0:s}.').format(display_name)) self._AnalyzeFileObject(file_object, display_name, event_data_stream) finally: if self._processing_profiler: self._processing_profiler.StopTiming('analyzing') logger.debug('[AnalyzeDataStream] completed analyzing file: {0:s}'.format( display_name))
[ "def", "_AnalyzeDataStream", "(", "self", ",", "file_entry", ",", "data_stream_name", ",", "display_name", ",", "event_data_stream", ")", ":", "logger", ".", "debug", "(", "'[AnalyzeDataStream] analyzing file: {0:s}'", ".", "format", "(", "display_name", ")", ")", "...
https://github.com/log2timeline/plaso/blob/fe2e316b8c76a0141760c0f2f181d84acb83abc2/plaso/engine/worker.py#L129-L170
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/agw/aui/framemanager.py
python
AuiCenterDockingGuide.HitTest
(self, x, y)
return -1
Checks if the mouse position is inside the target windows rect. :param integer `x`: the `x` mouse position; :param integer `y`: the `y` mouse position.
Checks if the mouse position is inside the target windows rect.
[ "Checks", "if", "the", "mouse", "position", "is", "inside", "the", "target", "windows", "rect", "." ]
def HitTest(self, x, y): """ Checks if the mouse position is inside the target windows rect. :param integer `x`: the `x` mouse position; :param integer `y`: the `y` mouse position. """ if not self._useAero: if self.targetLeft.GetScreenRect().Contains((x, y)): return wx.LEFT if self.targetTop.GetScreenRect().Contains((x, y)): return wx.UP if self.targetRight.GetScreenRect().Contains((x, y)): return wx.RIGHT if self.targetBottom.GetScreenRect().Contains((x, y)): return wx.DOWN if self.targetCenter.IsValid() and self.targetCenter.GetScreenRect().Contains((x, y)): return wx.CENTER else: constants = [wx.LEFT, wx.UP, wx.RIGHT, wx.DOWN, wx.CENTER] lenRects = len(self._aeroRects) for indx, rect in enumerate(self._aeroRects): if rect.Contains((x, y)): if indx < lenRects or (indx == lenRects - 1 and self._valid): return constants[indx] return -1
[ "def", "HitTest", "(", "self", ",", "x", ",", "y", ")", ":", "if", "not", "self", ".", "_useAero", ":", "if", "self", ".", "targetLeft", ".", "GetScreenRect", "(", ")", ".", "Contains", "(", "(", "x", ",", "y", ")", ")", ":", "return", "wx", "....
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/aui/framemanager.py#L2411-L2438
pygae/clifford
0b6cffb9a6d44ecb7a666f6b08b1788fc94a0ab6
clifford/tools/g3c/__init__.py
python
get_radius_from_sphere
(sphere)
return math.sqrt(abs(dual_sphere * dual_sphere))
Returns the radius of a sphere
Returns the radius of a sphere
[ "Returns", "the", "radius", "of", "a", "sphere" ]
def get_radius_from_sphere(sphere): """ Returns the radius of a sphere """ dual_sphere = sphere * I5 dual_sphere = dual_sphere / (-dual_sphere | ninf)[()] return math.sqrt(abs(dual_sphere * dual_sphere))
[ "def", "get_radius_from_sphere", "(", "sphere", ")", ":", "dual_sphere", "=", "sphere", "*", "I5", "dual_sphere", "=", "dual_sphere", "/", "(", "-", "dual_sphere", "|", "ninf", ")", "[", "(", ")", "]", "return", "math", ".", "sqrt", "(", "abs", "(", "d...
https://github.com/pygae/clifford/blob/0b6cffb9a6d44ecb7a666f6b08b1788fc94a0ab6/clifford/tools/g3c/__init__.py#L992-L998
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/verify/v2/service/rate_limit/bucket.py
python
BucketContext.update
(self, max=values.unset, interval=values.unset)
return BucketInstance( self._version, payload, service_sid=self._solution['service_sid'], rate_limit_sid=self._solution['rate_limit_sid'], sid=self._solution['sid'], )
Update the BucketInstance :param unicode max: Max number of requests. :param unicode interval: Number of seconds that the rate limit will be enforced over. :returns: The updated BucketInstance :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketInstance
Update the BucketInstance
[ "Update", "the", "BucketInstance" ]
def update(self, max=values.unset, interval=values.unset): """ Update the BucketInstance :param unicode max: Max number of requests. :param unicode interval: Number of seconds that the rate limit will be enforced over. :returns: The updated BucketInstance :rtype: twilio.rest.verify.v2.service.rate_limit.bucket.BucketInstance """ data = values.of({'Max': max, 'Interval': interval, }) payload = self._version.update(method='POST', uri=self._uri, data=data, ) return BucketInstance( self._version, payload, service_sid=self._solution['service_sid'], rate_limit_sid=self._solution['rate_limit_sid'], sid=self._solution['sid'], )
[ "def", "update", "(", "self", ",", "max", "=", "values", ".", "unset", ",", "interval", "=", "values", ".", "unset", ")", ":", "data", "=", "values", ".", "of", "(", "{", "'Max'", ":", "max", ",", "'Interval'", ":", "interval", ",", "}", ")", "pa...
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/verify/v2/service/rate_limit/bucket.py#L241-L261
grow/grow
97fc21730b6a674d5d33948d94968e79447ce433
grow/translations/catalog_holder.py
python
Catalogs.init
(self, locales, include_header=None)
[]
def init(self, locales, include_header=None): _, _, include_header, _ = \ self.get_extract_config(include_header=include_header) for locale in locales: catalog = self.get(locale) catalog.init(template_path=self.template_path, include_header=include_header)
[ "def", "init", "(", "self", ",", "locales", ",", "include_header", "=", "None", ")", ":", "_", ",", "_", ",", "include_header", ",", "_", "=", "self", ".", "get_extract_config", "(", "include_header", "=", "include_header", ")", "for", "locale", "in", "l...
https://github.com/grow/grow/blob/97fc21730b6a674d5d33948d94968e79447ce433/grow/translations/catalog_holder.py#L154-L160
nortikin/sverchok
7b460f01317c15f2681bfa3e337c5e7346f3711b
data_structure.py
python
socket_id
(socket)
return socket.socket_id
return an usable and semi stable hash
return an usable and semi stable hash
[ "return", "an", "usable", "and", "semi", "stable", "hash" ]
def socket_id(socket): """return an usable and semi stable hash""" return socket.socket_id
[ "def", "socket_id", "(", "socket", ")", ":", "return", "socket", ".", "socket_id" ]
https://github.com/nortikin/sverchok/blob/7b460f01317c15f2681bfa3e337c5e7346f3711b/data_structure.py#L1446-L1448
mjwestcott/Goodrich
dc2516591bd28488516c0337a62e64248debe47c
ch10/sorted_table_map.py
python
SortedTableMap._find_index
(self, k, low, high)
Return index of the leftmost item with key greater than or equal to k. Return high + 1 if no such item qualifies. That is, j will be returned such that: all items of slice table[low:j] have key < k all items of slice table[j:high+1] have key >= k
Return index of the leftmost item with key greater than or equal to k.
[ "Return", "index", "of", "the", "leftmost", "item", "with", "key", "greater", "than", "or", "equal", "to", "k", "." ]
def _find_index(self, k, low, high): """Return index of the leftmost item with key greater than or equal to k. Return high + 1 if no such item qualifies. That is, j will be returned such that: all items of slice table[low:j] have key < k all items of slice table[j:high+1] have key >= k """ if high < low: return high + 1 # no element qualifies else: mid = (low + high) // 2 if k == self._table[mid]._key: return mid # found exact match elif k < self._table[mid]._key: return self._find_index(k, low, mid - 1) # Note: may return mid else: return self._find_index(k, mid + 1, high)
[ "def", "_find_index", "(", "self", ",", "k", ",", "low", ",", "high", ")", ":", "if", "high", "<", "low", ":", "return", "high", "+", "1", "# no element qualifies", "else", ":", "mid", "=", "(", "low", "+", "high", ")", "//", "2", "if", "k", "=="...
https://github.com/mjwestcott/Goodrich/blob/dc2516591bd28488516c0337a62e64248debe47c/ch10/sorted_table_map.py#L28-L46
MTG/freesound
72f234a656ce31f5f625f0bba5376dd4160b478d
sounds/models.py
python
BulkUploadProgress.has_global_validation_errors
(self)
return False
Returns True if the validation finished with global errors
Returns True if the validation finished with global errors
[ "Returns", "True", "if", "the", "validation", "finished", "with", "global", "errors" ]
def has_global_validation_errors(self): """ Returns True if the validation finished with global errors """ if self.validation_output is not None: return len(self.validation_output['global_errors']) > 0 return False
[ "def", "has_global_validation_errors", "(", "self", ")", ":", "if", "self", ".", "validation_output", "is", "not", "None", ":", "return", "len", "(", "self", ".", "validation_output", "[", "'global_errors'", "]", ")", ">", "0", "return", "False" ]
https://github.com/MTG/freesound/blob/72f234a656ce31f5f625f0bba5376dd4160b478d/sounds/models.py#L262-L268
fandoghpaas/fandogh-cli
8bb3e4e49ebcfea3a3defb1db1b1831e27ba8af7
fandogh_cli/service_commands.py
python
service_destroy
(service_name, archived)
Destroy service
Destroy service
[ "Destroy", "service" ]
def service_destroy(service_name, archived): """Destroy service""" click.echo( 'you are about to destroy service with name {}.'.format(service_name)) click.echo('It might take a while!') message = present(lambda: destroy_service(service_name, archived)) click.echo(message)
[ "def", "service_destroy", "(", "service_name", ",", "archived", ")", ":", "click", ".", "echo", "(", "'you are about to destroy service with name {}.'", ".", "format", "(", "service_name", ")", ")", "click", ".", "echo", "(", "'It might take a while!'", ")", "messag...
https://github.com/fandoghpaas/fandogh-cli/blob/8bb3e4e49ebcfea3a3defb1db1b1831e27ba8af7/fandogh_cli/service_commands.py#L135-L141
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/modular/hecke/module.py
python
HeckeModule_free_module.system_of_eigenvalues
(self, n, name='alpha')
return [self.eigenvalue(m, name=name) for m in range(1, n + 1)]
r""" Assuming that ``self`` is a simple space of modular symbols, return the eigenvalues `[a_1, \ldots, a_nmax]` of the Hecke operators on self. See ``self.eigenvalue(n)`` for more details. INPUT: - ``n`` - number of eigenvalues - ``alpha`` - name of generate for eigenvalue field EXAMPLES: The outputs of the following tests are very unstable. The algorithms are randomized and depend on cached results. A slight change in the sequence of pseudo-random numbers or a modification in caching is likely to modify the results. We reset the random number generator and clear some caches for reproducibility:: sage: set_random_seed(0) sage: ModularSymbols_clear_cache() We compute eigenvalues for newforms of level 62:: sage: M = ModularSymbols(62,2,sign=-1) sage: S = M.cuspidal_submodule().new_submodule() sage: [[o.minpoly() for o in A.system_of_eigenvalues(3)] for A in S.decomposition()] [[x - 1, x - 1, x], [x - 1, x + 1, x^2 - 2*x - 2]] Next we define a function that does the above:: sage: def b(N,k=2): ....: t=cputime() ....: S = ModularSymbols(N,k,sign=-1).cuspidal_submodule().new_submodule() ....: for A in S.decomposition(): ....: print("{} {}".format(N, A.system_of_eigenvalues(5))) :: sage: b(63) 63 [1, 1, 0, -1, 2] 63 [1, alpha, 0, 1, -2*alpha] This example illustrates finding field over which the eigenvalues are defined:: sage: M = ModularSymbols(23,2,sign=1).cuspidal_submodule().new_submodule() sage: v = M.system_of_eigenvalues(10); v [1, alpha, -2*alpha - 1, -alpha - 1, 2*alpha, alpha - 2, 2*alpha + 2, -2*alpha - 1, 2, -2*alpha + 2] sage: v[0].parent() Number Field in alpha with defining polynomial x^2 + x - 1 This example illustrates setting the print name of the eigenvalue field. :: sage: A = ModularSymbols(125,sign=1).new_subspace()[0] sage: A.system_of_eigenvalues(10) [1, alpha, -alpha - 2, -alpha - 1, 0, -alpha - 1, -3, -2*alpha - 1, 3*alpha + 2, 0] sage: A.system_of_eigenvalues(10,'x') [1, x, -x - 2, -x - 1, 0, -x - 1, -3, -2*x - 1, 3*x + 2, 0]
r""" Assuming that ``self`` is a simple space of modular symbols, return the eigenvalues `[a_1, \ldots, a_nmax]` of the Hecke operators on self. See ``self.eigenvalue(n)`` for more details.
[ "r", "Assuming", "that", "self", "is", "a", "simple", "space", "of", "modular", "symbols", "return", "the", "eigenvalues", "[", "a_1", "\\", "ldots", "a_nmax", "]", "of", "the", "Hecke", "operators", "on", "self", ".", "See", "self", ".", "eigenvalue", "...
def system_of_eigenvalues(self, n, name='alpha'): r""" Assuming that ``self`` is a simple space of modular symbols, return the eigenvalues `[a_1, \ldots, a_nmax]` of the Hecke operators on self. See ``self.eigenvalue(n)`` for more details. INPUT: - ``n`` - number of eigenvalues - ``alpha`` - name of generate for eigenvalue field EXAMPLES: The outputs of the following tests are very unstable. The algorithms are randomized and depend on cached results. A slight change in the sequence of pseudo-random numbers or a modification in caching is likely to modify the results. We reset the random number generator and clear some caches for reproducibility:: sage: set_random_seed(0) sage: ModularSymbols_clear_cache() We compute eigenvalues for newforms of level 62:: sage: M = ModularSymbols(62,2,sign=-1) sage: S = M.cuspidal_submodule().new_submodule() sage: [[o.minpoly() for o in A.system_of_eigenvalues(3)] for A in S.decomposition()] [[x - 1, x - 1, x], [x - 1, x + 1, x^2 - 2*x - 2]] Next we define a function that does the above:: sage: def b(N,k=2): ....: t=cputime() ....: S = ModularSymbols(N,k,sign=-1).cuspidal_submodule().new_submodule() ....: for A in S.decomposition(): ....: print("{} {}".format(N, A.system_of_eigenvalues(5))) :: sage: b(63) 63 [1, 1, 0, -1, 2] 63 [1, alpha, 0, 1, -2*alpha] This example illustrates finding field over which the eigenvalues are defined:: sage: M = ModularSymbols(23,2,sign=1).cuspidal_submodule().new_submodule() sage: v = M.system_of_eigenvalues(10); v [1, alpha, -2*alpha - 1, -alpha - 1, 2*alpha, alpha - 2, 2*alpha + 2, -2*alpha - 1, 2, -2*alpha + 2] sage: v[0].parent() Number Field in alpha with defining polynomial x^2 + x - 1 This example illustrates setting the print name of the eigenvalue field. :: sage: A = ModularSymbols(125,sign=1).new_subspace()[0] sage: A.system_of_eigenvalues(10) [1, alpha, -alpha - 2, -alpha - 1, 0, -alpha - 1, -3, -2*alpha - 1, 3*alpha + 2, 0] sage: A.system_of_eigenvalues(10,'x') [1, x, -x - 2, -x - 1, 0, -x - 1, -3, -2*x - 1, 3*x + 2, 0] """ return [self.eigenvalue(m, name=name) for m in range(1, n + 1)]
[ "def", "system_of_eigenvalues", "(", "self", ",", "n", ",", "name", "=", "'alpha'", ")", ":", "return", "[", "self", ".", "eigenvalue", "(", "m", ",", "name", "=", "name", ")", "for", "m", "in", "range", "(", "1", ",", "n", "+", "1", ")", "]" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/modular/hecke/module.py#L1664-L1729
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/requests/packages/urllib3/connectionpool.py
python
HTTPSConnectionPool._prepare_conn
(self, conn)
return conn
Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket` and establish the tunnel if proxy is used.
Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket` and establish the tunnel if proxy is used.
[ "Prepare", "the", "connection", "for", ":", "meth", ":", "urllib3", ".", "util", ".", "ssl_wrap_socket", "and", "establish", "the", "tunnel", "if", "proxy", "is", "used", "." ]
def _prepare_conn(self, conn): """ Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket` and establish the tunnel if proxy is used. """ if isinstance(conn, VerifiedHTTPSConnection): conn.set_cert(key_file=self.key_file, cert_file=self.cert_file, cert_reqs=self.cert_reqs, ca_certs=self.ca_certs, ca_cert_dir=self.ca_cert_dir, assert_hostname=self.assert_hostname, assert_fingerprint=self.assert_fingerprint) conn.ssl_version = self.ssl_version return conn
[ "def", "_prepare_conn", "(", "self", ",", "conn", ")", ":", "if", "isinstance", "(", "conn", ",", "VerifiedHTTPSConnection", ")", ":", "conn", ".", "set_cert", "(", "key_file", "=", "self", ".", "key_file", ",", "cert_file", "=", "self", ".", "cert_file", ...
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/requests/packages/urllib3/connectionpool.py#L716-L732
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/pip/vcs/__init__.py
python
VersionControl.get_src_requirement
(self, dist, location)
Return a string representing the requirement needed to redownload the files currently present in location, something like: {repository_url}@{revision}#egg={project_name}-{version_identifier}
Return a string representing the requirement needed to redownload the files currently present in location, something like: {repository_url}
[ "Return", "a", "string", "representing", "the", "requirement", "needed", "to", "redownload", "the", "files", "currently", "present", "in", "location", "something", "like", ":", "{", "repository_url", "}" ]
def get_src_requirement(self, dist, location): """ Return a string representing the requirement needed to redownload the files currently present in location, something like: {repository_url}@{revision}#egg={project_name}-{version_identifier} """ raise NotImplementedError
[ "def", "get_src_requirement", "(", "self", ",", "dist", ",", "location", ")", ":", "raise", "NotImplementedError" ]
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pip/vcs/__init__.py#L288-L295
PaddlePaddle/PaddleX
2bab73f81ab54e328204e7871e6ae4a82e719f5d
paddlex/ppdet/data/transform/keypoint_operators.py
python
register_keypointop
(cls)
return serializable(cls)
[]
def register_keypointop(cls): return serializable(cls)
[ "def", "register_keypointop", "(", "cls", ")", ":", "return", "serializable", "(", "cls", ")" ]
https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/paddlex/ppdet/data/transform/keypoint_operators.py#L55-L56
csu/quora-api
59c8bac0016a29cca1236c39410298a036341e02
server.py
python
user_upvotes_route
(user)
return jsonify({'items': Quora.get_activity(user).upvotes})
[]
def user_upvotes_route(user): return jsonify({'items': Quora.get_activity(user).upvotes})
[ "def", "user_upvotes_route", "(", "user", ")", ":", "return", "jsonify", "(", "{", "'items'", ":", "Quora", ".", "get_activity", "(", "user", ")", ".", "upvotes", "}", ")" ]
https://github.com/csu/quora-api/blob/59c8bac0016a29cca1236c39410298a036341e02/server.py#L85-L86
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/polys/densearith.py
python
dmp_rr_div
(f, g, u, K)
return q, r
Multivariate division with remainder over a ring. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_rr_div(x**2 + x*y, 2*x + 2) (0, x**2 + x*y)
Multivariate division with remainder over a ring.
[ "Multivariate", "division", "with", "remainder", "over", "a", "ring", "." ]
def dmp_rr_div(f, g, u, K): """ Multivariate division with remainder over a ring. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> R.dmp_rr_div(x**2 + x*y, 2*x + 2) (0, x**2 + x*y) """ if not u: return dup_rr_div(f, g, K) df = dmp_degree(f, u) dg = dmp_degree(g, u) if dg < 0: raise ZeroDivisionError("polynomial division") q, r, dr = dmp_zero(u), f, df if df < dg: return q, r lc_g, v = dmp_LC(g, K), u - 1 while True: lc_r = dmp_LC(r, K) c, R = dmp_rr_div(lc_r, lc_g, v, K) if not dmp_zero_p(R, v): break j = dr - dg q = dmp_add_term(q, c, j, u, K) h = dmp_mul_term(g, c, j, u, K) r = dmp_sub(r, h, u, K) _dr, dr = dr, dmp_degree(r, u) if dr < dg: break elif not (dr < _dr): raise PolynomialDivisionFailed(f, g, K) return q, r
[ "def", "dmp_rr_div", "(", "f", ",", "g", ",", "u", ",", "K", ")", ":", "if", "not", "u", ":", "return", "dup_rr_div", "(", "f", ",", "g", ",", "K", ")", "df", "=", "dmp_degree", "(", "f", ",", "u", ")", "dg", "=", "dmp_degree", "(", "g", ",...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/polys/densearith.py#L1359-L1409
tensorflow/datasets
2e496976d7d45550508395fb2f35cf958c8a3414
tensorflow_datasets/audio/savee.py
python
Savee._generate_examples
(self, file_names)
Yields examples.
Yields examples.
[ "Yields", "examples", "." ]
def _generate_examples(self, file_names): """Yields examples.""" for fname in file_names: folder, wavname = os.path.split(fname) _, speaker_id = os.path.split(folder) label_abbrev = re.match('^([a-zA-Z]+)', wavname).group(1) # pytype: disable=attribute-error label = LABEL_MAP[label_abbrev] key = '{}_{}'.format(speaker_id, wavname.split('.')[0]) yield key, {'audio': fname, 'label': label, 'speaker_id': speaker_id}
[ "def", "_generate_examples", "(", "self", ",", "file_names", ")", ":", "for", "fname", "in", "file_names", ":", "folder", ",", "wavname", "=", "os", ".", "path", ".", "split", "(", "fname", ")", "_", ",", "speaker_id", "=", "os", ".", "path", ".", "s...
https://github.com/tensorflow/datasets/blob/2e496976d7d45550508395fb2f35cf958c8a3414/tensorflow_datasets/audio/savee.py#L189-L197
gevent/gevent
ae2cb5aeb2aea8987efcb90a4c50ca4e1ee12c31
src/gevent/_waiter.py
python
Waiter.throw
(self, *throw_args)
Switch to the greenlet with the exception. If there's no greenlet, store the exception.
Switch to the greenlet with the exception. If there's no greenlet, store the exception.
[ "Switch", "to", "the", "greenlet", "with", "the", "exception", ".", "If", "there", "s", "no", "greenlet", "store", "the", "exception", "." ]
def throw(self, *throw_args): """Switch to the greenlet with the exception. If there's no greenlet, store the exception.""" greenlet = self.greenlet if greenlet is None: self._exception = throw_args else: if getcurrent() is not self.hub: # pylint:disable=undefined-variable raise AssertionError("Can only use Waiter.switch method from the Hub greenlet") throw = greenlet.throw try: throw(*throw_args) except: # pylint:disable=bare-except self.hub.handle_error(throw, *sys.exc_info())
[ "def", "throw", "(", "self", ",", "*", "throw_args", ")", ":", "greenlet", "=", "self", ".", "greenlet", "if", "greenlet", "is", "None", ":", "self", ".", "_exception", "=", "throw_args", "else", ":", "if", "getcurrent", "(", ")", "is", "not", "self", ...
https://github.com/gevent/gevent/blob/ae2cb5aeb2aea8987efcb90a4c50ca4e1ee12c31/src/gevent/_waiter.py#L129-L141
minio/minio-py
b3ba3bf99fe6b9ff2b28855550d6ab5345c134e3
minio/datatypes.py
python
ListMultipartUploadsResult.key_marker
(self)
return self._key_marker
Get key marker.
Get key marker.
[ "Get", "key", "marker", "." ]
def key_marker(self): """Get key marker.""" return self._key_marker
[ "def", "key_marker", "(", "self", ")", ":", "return", "self", ".", "_key_marker" ]
https://github.com/minio/minio-py/blob/b3ba3bf99fe6b9ff2b28855550d6ab5345c134e3/minio/datatypes.py#L591-L593
tmulc18/Distributed-TensorFlow-Guide
8e7fec757112a3ab5dccff93e848e7617ef7ed3e
DOWNPOUR/DOWNPOUR.py
python
add_global_variables_to_local_collection
()
return r
Adds all variables from the global collection to the local collection. Returns the list of variables added.
Adds all variables from the global collection to the local collection.
[ "Adds", "all", "variables", "from", "the", "global", "collection", "to", "the", "local", "collection", "." ]
def add_global_variables_to_local_collection(): """Adds all variables from the global collection to the local collection. Returns the list of variables added. """ r =[] for var in tf.get_default_graph()._collections[tf.GraphKeys.GLOBAL_VARIABLES]: tf.add_to_collection(tf.GraphKeys.LOCAL_VARIABLES,var) r.append(var) return r
[ "def", "add_global_variables_to_local_collection", "(", ")", ":", "r", "=", "[", "]", "for", "var", "in", "tf", ".", "get_default_graph", "(", ")", ".", "_collections", "[", "tf", ".", "GraphKeys", ".", "GLOBAL_VARIABLES", "]", ":", "tf", ".", "add_to_collec...
https://github.com/tmulc18/Distributed-TensorFlow-Guide/blob/8e7fec757112a3ab5dccff93e848e7617ef7ed3e/DOWNPOUR/DOWNPOUR.py#L216-L226
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/matching/binary.py
python
DisjunctionMaxMatcher.skip_to_quality
(self, minquality)
return skipped
[]
def skip_to_quality(self, minquality): a = self.a b = self.b # Short circuit if one matcher is inactive if not a.is_active(): sk = b.skip_to_quality(minquality) return sk elif not b.is_active(): return a.skip_to_quality(minquality) skipped = 0 aq = a.block_quality() bq = b.block_quality() while a.is_active() and b.is_active() and max(aq, bq) <= minquality: if aq <= minquality: skipped += a.skip_to_quality(minquality) aq = a.block_quality() if bq <= minquality: skipped += b.skip_to_quality(minquality) bq = b.block_quality() return skipped
[ "def", "skip_to_quality", "(", "self", ",", "minquality", ")", ":", "a", "=", "self", ".", "a", "b", "=", "self", ".", "b", "# Short circuit if one matcher is inactive", "if", "not", "a", ".", "is_active", "(", ")", ":", "sk", "=", "b", ".", "skip_to_qua...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/matching/binary.py#L390-L411
tdamdouni/Pythonista
3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad
stash/pep8.py
python
Checker.report_invalid_syntax
(self)
Check if the syntax is valid.
Check if the syntax is valid.
[ "Check", "if", "the", "syntax", "is", "valid", "." ]
def report_invalid_syntax(self): """Check if the syntax is valid.""" (exc_type, exc) = sys.exc_info()[:2] if len(exc.args) > 1: offset = exc.args[1] if len(offset) > 2: offset = offset[1:3] else: offset = (1, 0) self.report_error(offset[0], offset[1] or 0, 'E901 %s: %s' % (exc_type.__name__, exc.args[0]), self.report_invalid_syntax)
[ "def", "report_invalid_syntax", "(", "self", ")", ":", "(", "exc_type", ",", "exc", ")", "=", "sys", ".", "exc_info", "(", ")", "[", ":", "2", "]", "if", "len", "(", "exc", ".", "args", ")", ">", "1", ":", "offset", "=", "exc", ".", "args", "["...
https://github.com/tdamdouni/Pythonista/blob/3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad/stash/pep8.py#L1425-L1436
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/sklearn/decomposition/pca.py
python
PCA.score_samples
(self, X)
return log_like
Return the log-likelihood of each sample. See. "Pattern Recognition and Machine Learning" by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf Parameters ---------- X: array, shape(n_samples, n_features) The data. Returns ------- ll: array, shape (n_samples,) Log-likelihood of each sample under the current model
Return the log-likelihood of each sample.
[ "Return", "the", "log", "-", "likelihood", "of", "each", "sample", "." ]
def score_samples(self, X): """Return the log-likelihood of each sample. See. "Pattern Recognition and Machine Learning" by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf Parameters ---------- X: array, shape(n_samples, n_features) The data. Returns ------- ll: array, shape (n_samples,) Log-likelihood of each sample under the current model """ check_is_fitted(self, 'mean_') X = check_array(X) Xr = X - self.mean_ n_features = X.shape[1] log_like = np.zeros(X.shape[0]) precision = self.get_precision() log_like = -.5 * (Xr * (np.dot(Xr, precision))).sum(axis=1) log_like -= .5 * (n_features * log(2. * np.pi) - fast_logdet(precision)) return log_like
[ "def", "score_samples", "(", "self", ",", "X", ")", ":", "check_is_fitted", "(", "self", ",", "'mean_'", ")", "X", "=", "check_array", "(", "X", ")", "Xr", "=", "X", "-", "self", ".", "mean_", "n_features", "=", "X", ".", "shape", "[", "1", "]", ...
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/sklearn/decomposition/pca.py#L485-L512
NVIDIA/NeMo
5b0c0b4dec12d87d3cd960846de4105309ce938e
nemo/collections/asr/data/audio_to_text_dataset.py
python
get_bpe_dataset
( config: dict, tokenizer: 'TokenizerSpec', augmentor: Optional['AudioAugmentor'] = None )
return dataset
Instantiates a Byte Pair Encoding / Word Piece Encoding based AudioToBPEDataset. Args: config: Config of the AudioToBPEDataset. tokenizer: An instance of a TokenizerSpec object. augmentor: Optional AudioAugmentor object for augmentations on audio data. Returns: An instance of AudioToBPEDataset.
Instantiates a Byte Pair Encoding / Word Piece Encoding based AudioToBPEDataset.
[ "Instantiates", "a", "Byte", "Pair", "Encoding", "/", "Word", "Piece", "Encoding", "based", "AudioToBPEDataset", "." ]
def get_bpe_dataset( config: dict, tokenizer: 'TokenizerSpec', augmentor: Optional['AudioAugmentor'] = None ) -> audio_to_text.AudioToBPEDataset: """ Instantiates a Byte Pair Encoding / Word Piece Encoding based AudioToBPEDataset. Args: config: Config of the AudioToBPEDataset. tokenizer: An instance of a TokenizerSpec object. augmentor: Optional AudioAugmentor object for augmentations on audio data. Returns: An instance of AudioToBPEDataset. """ dataset = audio_to_text.AudioToBPEDataset( manifest_filepath=config['manifest_filepath'], tokenizer=tokenizer, sample_rate=config['sample_rate'], int_values=config.get('int_values', False), augmentor=augmentor, max_duration=config.get('max_duration', None), min_duration=config.get('min_duration', None), max_utts=config.get('max_utts', 0), trim=config.get('trim_silence', False), use_start_end_token=config.get('use_start_end_token', True), return_sample_id=config.get('return_sample_id', False), ) return dataset
[ "def", "get_bpe_dataset", "(", "config", ":", "dict", ",", "tokenizer", ":", "'TokenizerSpec'", ",", "augmentor", ":", "Optional", "[", "'AudioAugmentor'", "]", "=", "None", ")", "->", "audio_to_text", ".", "AudioToBPEDataset", ":", "dataset", "=", "audio_to_tex...
https://github.com/NVIDIA/NeMo/blob/5b0c0b4dec12d87d3cd960846de4105309ce938e/nemo/collections/asr/data/audio_to_text_dataset.py#L104-L131
bendmorris/static-python
2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473
Lib/pydoc.py
python
TextDoc.docdata
(self, object, name=None, mod=None, cl=None)
return self._docdescriptor(name, object, mod)
Produce text documentation for a data descriptor.
Produce text documentation for a data descriptor.
[ "Produce", "text", "documentation", "for", "a", "data", "descriptor", "." ]
def docdata(self, object, name=None, mod=None, cl=None): """Produce text documentation for a data descriptor.""" return self._docdescriptor(name, object, mod)
[ "def", "docdata", "(", "self", ",", "object", ",", "name", "=", "None", ",", "mod", "=", "None", ",", "cl", "=", "None", ")", ":", "return", "self", ".", "_docdescriptor", "(", "name", ",", "object", ",", "mod", ")" ]
https://github.com/bendmorris/static-python/blob/2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473/Lib/pydoc.py#L1354-L1356
twisted/twisted
dee676b040dd38b847ea6fb112a712cb5e119490
src/twisted/protocols/ftp.py
python
DTPFactory.__init__
(self, pi, peerHost=None, reactor=None)
Constructor @param pi: this factory's protocol interpreter @param peerHost: if peerCheck is True, this is the tuple that the generated instance will use to perform security checks
Constructor
[ "Constructor" ]
def __init__(self, pi, peerHost=None, reactor=None): """ Constructor @param pi: this factory's protocol interpreter @param peerHost: if peerCheck is True, this is the tuple that the generated instance will use to perform security checks """ self.pi = pi self.peerHost = peerHost # from FTP.transport.peerHost() # deferred will fire when instance is connected self.deferred = defer.Deferred() self.delayedCall = None if reactor is None: from twisted.internet import reactor self._reactor = reactor
[ "def", "__init__", "(", "self", ",", "pi", ",", "peerHost", "=", "None", ",", "reactor", "=", "None", ")", ":", "self", ".", "pi", "=", "pi", "self", ".", "peerHost", "=", "peerHost", "# from FTP.transport.peerHost()", "# deferred will fire when instance is conn...
https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/protocols/ftp.py#L590-L605
riptideio/pymodbus
c5772b35ae3f29d1947f3ab453d8d00df846459f
pymodbus/client/sync.py
python
BaseModbusClient.debug_enabled
(self)
return self._debug
Returns a boolean indicating if debug is enabled.
Returns a boolean indicating if debug is enabled.
[ "Returns", "a", "boolean", "indicating", "if", "debug", "is", "enabled", "." ]
def debug_enabled(self): """ Returns a boolean indicating if debug is enabled. """ return self._debug
[ "def", "debug_enabled", "(", "self", ")", ":", "return", "self", ".", "_debug" ]
https://github.com/riptideio/pymodbus/blob/c5772b35ae3f29d1947f3ab453d8d00df846459f/pymodbus/client/sync.py#L136-L140
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/src/class/oc_label.py
python
OCLabel.any_label_exists
(self)
return False
return whether any single label already exists
return whether any single label already exists
[ "return", "whether", "any", "single", "label", "already", "exists" ]
def any_label_exists(self): ''' return whether any single label already exists ''' for current_host_labels in self.current_labels: for label in self.labels: if label['key'] in current_host_labels: return True return False
[ "def", "any_label_exists", "(", "self", ")", ":", "for", "current_host_labels", "in", "self", ".", "current_labels", ":", "for", "label", "in", "self", ".", "labels", ":", "if", "label", "[", "'key'", "]", "in", "current_host_labels", ":", "return", "True", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/src/class/oc_label.py#L59-L66
cognitect-labs/transducers-python
11ac3e5c78a5a9dd30719d3aba91bf333c249a94
transducers/transducers.py
python
take
(n)
return _take_xducer
Takes n values from a collection.
Takes n values from a collection.
[ "Takes", "n", "values", "from", "a", "collection", "." ]
def take(n): """Takes n values from a collection.""" def _take_xducer(step): outer_vars = {"counter": n} def _take_step(r=Missing, x=Missing): if r is Missing: return step() if x is Missing: return step(r) n = outer_vars["counter"] outer_vars["counter"] -= 1 r = step(r, x) if n > 0 else r return ensure_reduced(r) if outer_vars["counter"] <= 0 else r return _take_step return _take_xducer
[ "def", "take", "(", "n", ")", ":", "def", "_take_xducer", "(", "step", ")", ":", "outer_vars", "=", "{", "\"counter\"", ":", "n", "}", "def", "_take_step", "(", "r", "=", "Missing", ",", "x", "=", "Missing", ")", ":", "if", "r", "is", "Missing", ...
https://github.com/cognitect-labs/transducers-python/blob/11ac3e5c78a5a9dd30719d3aba91bf333c249a94/transducers/transducers.py#L123-L136
lisa-lab/pylearn2
af81e5c362f0df4df85c3e54e23b2adeec026055
pylearn2/models/dbm/dbm.py
python
DBM.get_weights
(self)
return self.hidden_layers[0].get_weights()
.. todo:: WRITEME
.. todo::
[ "..", "todo", "::" ]
def get_weights(self): """ .. todo:: WRITEME """ return self.hidden_layers[0].get_weights()
[ "def", "get_weights", "(", "self", ")", ":", "return", "self", ".", "hidden_layers", "[", "0", "]", ".", "get_weights", "(", ")" ]
https://github.com/lisa-lab/pylearn2/blob/af81e5c362f0df4df85c3e54e23b2adeec026055/pylearn2/models/dbm/dbm.py#L391-L397
jparkhill/TensorMol
d52104dc7ee46eec8301d332a95d672270ac0bd1
TensorMol/ForceModifiers/Periodic.py
python
PeriodicForce.BindForce
(self, lf_, rng_)
Adds a local force to be computed when the PeriodicForce is called. Args: lf_: a function which takes z,x and returns atom energies, atom forces.
Adds a local force to be computed when the PeriodicForce is called.
[ "Adds", "a", "local", "force", "to", "be", "computed", "when", "the", "PeriodicForce", "is", "called", "." ]
def BindForce(self, lf_, rng_): """ Adds a local force to be computed when the PeriodicForce is called. Args: lf_: a function which takes z,x and returns atom energies, atom forces. """ self.LocalForces.append(LocalForce(lf_,rng_))
[ "def", "BindForce", "(", "self", ",", "lf_", ",", "rng_", ")", ":", "self", ".", "LocalForces", ".", "append", "(", "LocalForce", "(", "lf_", ",", "rng_", ")", ")" ]
https://github.com/jparkhill/TensorMol/blob/d52104dc7ee46eec8301d332a95d672270ac0bd1/TensorMol/ForceModifiers/Periodic.py#L368-L375
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
site-packages/requests/packages/urllib3/fields.py
python
RequestField._render_part
(self, name, value)
return format_header_param(name, value)
Overridable helper function to format a single header parameter. :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as a unicode string.
Overridable helper function to format a single header parameter.
[ "Overridable", "helper", "function", "to", "format", "a", "single", "header", "parameter", "." ]
def _render_part(self, name, value): """ Overridable helper function to format a single header parameter. :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as a unicode string. """ return format_header_param(name, value)
[ "def", "_render_part", "(", "self", ",", "name", ",", "value", ")", ":", "return", "format_header_param", "(", "name", ",", "value", ")" ]
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/site-packages/requests/packages/urllib3/fields.py#L105-L114
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/asyncio/events.py
python
_get_running_loop
()
Return the running event loop or None. This is a low-level function intended to be used by event loops. This function is thread-specific.
Return the running event loop or None.
[ "Return", "the", "running", "event", "loop", "or", "None", "." ]
def _get_running_loop(): """Return the running event loop or None. This is a low-level function intended to be used by event loops. This function is thread-specific. """ # NOTE: this function is implemented in C (see _asynciomodule.c) running_loop, pid = _running_loop.loop_pid if running_loop is not None and pid == os.getpid(): return running_loop
[ "def", "_get_running_loop", "(", ")", ":", "# NOTE: this function is implemented in C (see _asynciomodule.c)", "running_loop", ",", "pid", "=", "_running_loop", ".", "loop_pid", "if", "running_loop", "is", "not", "None", "and", "pid", "==", "os", ".", "getpid", "(", ...
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/asyncio/events.py#L693-L702
roglew/guppy-proxy
01df16be71dd9f23d7de415a315821659c29bc63
guppyproxy/macros.py
python
ActiveMacroWidget.browse_macro
(self)
[]
def browse_macro(self): fname = open_dialog(self, filter_string="Python File (*.py)") if not fname: return self.tableModel.add_macro(fname)
[ "def", "browse_macro", "(", "self", ")", ":", "fname", "=", "open_dialog", "(", "self", ",", "filter_string", "=", "\"Python File (*.py)\"", ")", "if", "not", "fname", ":", "return", "self", ".", "tableModel", ".", "add_macro", "(", "fname", ")" ]
https://github.com/roglew/guppy-proxy/blob/01df16be71dd9f23d7de415a315821659c29bc63/guppyproxy/macros.py#L666-L670
JinpengLI/deep_ocr
450148c0c51b3565a96ac2f3c94ee33022e55307
deep_ocr/ocrolib/common.py
python
RegionExtractor.x1
(self,i)
return self.bbox(i)[3]
Return x0 (column) for the end of the box.
Return x0 (column) for the end of the box.
[ "Return", "x0", "(", "column", ")", "for", "the", "end", "of", "the", "box", "." ]
def x1(self,i): """Return x0 (column) for the end of the box.""" return self.bbox(i)[3]
[ "def", "x1", "(", "self", ",", "i", ")", ":", "return", "self", ".", "bbox", "(", "i", ")", "[", "3", "]" ]
https://github.com/JinpengLI/deep_ocr/blob/450148c0c51b3565a96ac2f3c94ee33022e55307/deep_ocr/ocrolib/common.py#L351-L353
learningequality/ka-lite
571918ea668013dcf022286ea85eff1c5333fb8b
kalite/packages/bundled/django/contrib/comments/moderation.py
python
CommentModerator.moderate
(self, comment, content_object, request)
return False
Determine whether a given comment on a given object should be allowed to show up immediately, or should be marked non-public and await approval. Return ``True`` if the comment should be moderated (marked non-public), ``False`` otherwise.
Determine whether a given comment on a given object should be allowed to show up immediately, or should be marked non-public and await approval.
[ "Determine", "whether", "a", "given", "comment", "on", "a", "given", "object", "should", "be", "allowed", "to", "show", "up", "immediately", "or", "should", "be", "marked", "non", "-", "public", "and", "await", "approval", "." ]
def moderate(self, comment, content_object, request): """ Determine whether a given comment on a given object should be allowed to show up immediately, or should be marked non-public and await approval. Return ``True`` if the comment should be moderated (marked non-public), ``False`` otherwise. """ if self.auto_moderate_field and self.moderate_after is not None: moderate_after_date = getattr(content_object, self.auto_moderate_field) if moderate_after_date is not None and self._get_delta(timezone.now(), moderate_after_date).days >= self.moderate_after: return True return False
[ "def", "moderate", "(", "self", ",", "comment", ",", "content_object", ",", "request", ")", ":", "if", "self", ".", "auto_moderate_field", "and", "self", ".", "moderate_after", "is", "not", "None", ":", "moderate_after_date", "=", "getattr", "(", "content_obje...
https://github.com/learningequality/ka-lite/blob/571918ea668013dcf022286ea85eff1c5333fb8b/kalite/packages/bundled/django/contrib/comments/moderation.py#L215-L229
jadore801120/attention-is-all-you-need-pytorch
132907dd272e2cc92e3c10e6c4e783a87ff8893d
learn_bpe.py
python
replace_pair
(pair, vocab, indices)
return changes
Replace all occurrences of a symbol pair ('A', 'B') with a new symbol 'AB
Replace all occurrences of a symbol pair ('A', 'B') with a new symbol 'AB
[ "Replace", "all", "occurrences", "of", "a", "symbol", "pair", "(", "A", "B", ")", "with", "a", "new", "symbol", "AB" ]
def replace_pair(pair, vocab, indices): """Replace all occurrences of a symbol pair ('A', 'B') with a new symbol 'AB'""" first, second = pair pair_str = ''.join(pair) pair_str = pair_str.replace('\\','\\\\') changes = [] pattern = re.compile(r'(?<!\S)' + re.escape(first + ' ' + second) + r'(?!\S)') if sys.version_info < (3, 0): iterator = indices[pair].iteritems() else: iterator = indices[pair].items() for j, freq in iterator: if freq < 1: continue word, freq = vocab[j] new_word = ' '.join(word) new_word = pattern.sub(pair_str, new_word) new_word = tuple(new_word.split(' ')) vocab[j] = (new_word, freq) changes.append((j, new_word, word, freq)) return changes
[ "def", "replace_pair", "(", "pair", ",", "vocab", ",", "indices", ")", ":", "first", ",", "second", "=", "pair", "pair_str", "=", "''", ".", "join", "(", "pair", ")", "pair_str", "=", "pair_str", ".", "replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ")", ...
https://github.com/jadore801120/attention-is-all-you-need-pytorch/blob/132907dd272e2cc92e3c10e6c4e783a87ff8893d/learn_bpe.py#L125-L147
XuezheMax/flowseq
8cb4ae00c26fbeb3e1459e3b3b90e7e9a84c3d2b
flownmt/data/dataloader.py
python
DataIterator.get_batch
(self, batch_size)
return self.process_batch(batch)
[]
def get_batch(self, batch_size): batch = random.sample(self.data, batch_size) return self.process_batch(batch)
[ "def", "get_batch", "(", "self", ",", "batch_size", ")", ":", "batch", "=", "random", ".", "sample", "(", "self", ".", "data", ",", "batch_size", ")", "return", "self", ".", "process_batch", "(", "batch", ")" ]
https://github.com/XuezheMax/flowseq/blob/8cb4ae00c26fbeb3e1459e3b3b90e7e9a84c3d2b/flownmt/data/dataloader.py#L458-L460
mozilla/MozDef
d7d4dd1cd898bb4eeb59d014bd5bcfe96554a10f
mq/plugins/parse_su.py
python
message.__init__
(self)
takes an incoming su message and parses it to extract data points
takes an incoming su message and parses it to extract data points
[ "takes", "an", "incoming", "su", "message", "and", "parses", "it", "to", "extract", "data", "points" ]
def __init__(self): ''' takes an incoming su message and parses it to extract data points ''' self.registration = ['sshd'] self.priority = 5
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "registration", "=", "[", "'sshd'", "]", "self", ".", "priority", "=", "5" ]
https://github.com/mozilla/MozDef/blob/d7d4dd1cd898bb4eeb59d014bd5bcfe96554a10f/mq/plugins/parse_su.py#L11-L18
landlab/landlab
a5dd80b8ebfd03d1ba87ef6c4368c409485f222c
landlab/graph/graph.py
python
NetworkGraph.angle_of_link
(self)
return get_angle_of_link(self)
Get the angle of each link. Examples -------- >>> import numpy as np >>> from landlab.graph import Graph >>> node_x, node_y = ([0, 1, 2, 0, 1, 2], ... [0, 0, 0, 1, 1, 1]) >>> links = ((0, 1), (1, 2), ... (0, 3), (1, 4), (2, 5), ... (3, 4), (4, 5)) >>> graph = Graph((node_y, node_x), links=links) >>> graph.angle_of_link * 180. / np.pi array([ 0., 0., 90., 90., 90., 0., 0.]) LLCATS: LINF
Get the angle of each link.
[ "Get", "the", "angle", "of", "each", "link", "." ]
def angle_of_link(self): """Get the angle of each link. Examples -------- >>> import numpy as np >>> from landlab.graph import Graph >>> node_x, node_y = ([0, 1, 2, 0, 1, 2], ... [0, 0, 0, 1, 1, 1]) >>> links = ((0, 1), (1, 2), ... (0, 3), (1, 4), (2, 5), ... (3, 4), (4, 5)) >>> graph = Graph((node_y, node_x), links=links) >>> graph.angle_of_link * 180. / np.pi array([ 0., 0., 90., 90., 90., 0., 0.]) LLCATS: LINF """ return get_angle_of_link(self)
[ "def", "angle_of_link", "(", "self", ")", ":", "return", "get_angle_of_link", "(", "self", ")" ]
https://github.com/landlab/landlab/blob/a5dd80b8ebfd03d1ba87ef6c4368c409485f222c/landlab/graph/graph.py#L566-L585
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/polys/domains/old_polynomialring.py
python
GeneralizedPolynomialRing.to_sympy
(self, a)
return (basic_from_dict(a.numer().to_sympy_dict(), *self.gens) / basic_from_dict(a.denom().to_sympy_dict(), *self.gens))
Convert `a` to a SymPy object.
Convert `a` to a SymPy object.
[ "Convert", "a", "to", "a", "SymPy", "object", "." ]
def to_sympy(self, a): """Convert `a` to a SymPy object. """ return (basic_from_dict(a.numer().to_sympy_dict(), *self.gens) / basic_from_dict(a.denom().to_sympy_dict(), *self.gens))
[ "def", "to_sympy", "(", "self", ",", "a", ")", ":", "return", "(", "basic_from_dict", "(", "a", ".", "numer", "(", ")", ".", "to_sympy_dict", "(", ")", ",", "*", "self", ".", "gens", ")", "/", "basic_from_dict", "(", "a", ".", "denom", "(", ")", ...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/polys/domains/old_polynomialring.py#L309-L312
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/pandas/core/categorical.py
python
Categorical.memory_usage
(self, deep=False)
return self._codes.nbytes + self._categories.memory_usage(deep=deep)
Memory usage of my values Parameters ---------- deep : bool Introspect the data deeply, interrogate `object` dtypes for system-level memory consumption Returns ------- bytes used Notes ----- Memory usage does not include memory consumed by elements that are not components of the array if deep=False See Also -------- numpy.ndarray.nbytes
Memory usage of my values
[ "Memory", "usage", "of", "my", "values" ]
def memory_usage(self, deep=False): """ Memory usage of my values Parameters ---------- deep : bool Introspect the data deeply, interrogate `object` dtypes for system-level memory consumption Returns ------- bytes used Notes ----- Memory usage does not include memory consumed by elements that are not components of the array if deep=False See Also -------- numpy.ndarray.nbytes """ return self._codes.nbytes + self._categories.memory_usage(deep=deep)
[ "def", "memory_usage", "(", "self", ",", "deep", "=", "False", ")", ":", "return", "self", ".", "_codes", ".", "nbytes", "+", "self", ".", "_categories", ".", "memory_usage", "(", "deep", "=", "deep", ")" ]
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pandas/core/categorical.py#L1054-L1077
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/client/grr_response_client/client_actions/memory.py
python
UnprivilegedYaraWrapper.Open
(self)
[]
def Open(self) -> None: with contextlib.ExitStack() as stack: file_descriptors = [] for psutil_process in self._psutil_processes: try: process = stack.enter_context( client_utils.OpenProcessForMemoryAccess(psutil_process.pid)) except Exception as e: # pylint: disable=broad-except # OpenProcessForMemoryAccess can raise any exception upon error. self._pid_to_exception[psutil_process.pid] = e continue self._pid_to_serializable_file_descriptor[ psutil_process.pid] = process.serialized_file_descriptor file_descriptors.append( communication.FileDescriptor.FromSerialized( process.serialized_file_descriptor, communication.Mode.READ)) self._server = memory_server.CreateMemoryServer(file_descriptors) self._server.Start() self._client = memory_client.Client(self._server.Connect())
[ "def", "Open", "(", "self", ")", "->", "None", ":", "with", "contextlib", ".", "ExitStack", "(", ")", "as", "stack", ":", "file_descriptors", "=", "[", "]", "for", "psutil_process", "in", "self", ".", "_psutil_processes", ":", "try", ":", "process", "=",...
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/client/grr_response_client/client_actions/memory.py#L220-L238
GRAAL-Research/poutyne
f46e5fe610d175b96a490db24ef2d22b49cc594b
poutyne/framework/model_bundle.py
python
ModelBundle.infer_dataset
(self, dataset, **kwargs)
return self._predict(self.model.predict_dataset, dataset, **kwargs)
Returns the inferred predictions of the network given a dataset, where the tensors are converted into Numpy arrays. Args: dataset (~torch.utils.data.Dataset): Dataset. Must not return ``y``, just ``x``. checkpoint (Union[str, int]): Which model checkpoint weights to load for the prediction. - If 'best', will load the best weights according to ``monitor_metric`` and ``monitor_mode``. - If 'last', will load the last model checkpoint. - If int, will load the checkpoint of the specified epoch. - If a path (str), will load the model pickled state_dict weights (for instance, saved as ``torch.save(a_pytorch_network.state_dict(), "./a_path.p")``). This argument has no effect when logging is disabled. (Default value = 'best') kwargs: Any keyword arguments to pass to :func:`~Model.predict_dataset()`. Returns: Return the predictions in the format outputted by the model.
Returns the inferred predictions of the network given a dataset, where the tensors are converted into Numpy arrays.
[ "Returns", "the", "inferred", "predictions", "of", "the", "network", "given", "a", "dataset", "where", "the", "tensors", "are", "converted", "into", "Numpy", "arrays", "." ]
def infer_dataset(self, dataset, **kwargs) -> Any: """ Returns the inferred predictions of the network given a dataset, where the tensors are converted into Numpy arrays. Args: dataset (~torch.utils.data.Dataset): Dataset. Must not return ``y``, just ``x``. checkpoint (Union[str, int]): Which model checkpoint weights to load for the prediction. - If 'best', will load the best weights according to ``monitor_metric`` and ``monitor_mode``. - If 'last', will load the last model checkpoint. - If int, will load the checkpoint of the specified epoch. - If a path (str), will load the model pickled state_dict weights (for instance, saved as ``torch.save(a_pytorch_network.state_dict(), "./a_path.p")``). This argument has no effect when logging is disabled. (Default value = 'best') kwargs: Any keyword arguments to pass to :func:`~Model.predict_dataset()`. Returns: Return the predictions in the format outputted by the model. """ return self._predict(self.model.predict_dataset, dataset, **kwargs)
[ "def", "infer_dataset", "(", "self", ",", "dataset", ",", "*", "*", "kwargs", ")", "->", "Any", ":", "return", "self", ".", "_predict", "(", "self", ".", "model", ".", "predict_dataset", ",", "dataset", ",", "*", "*", "kwargs", ")" ]
https://github.com/GRAAL-Research/poutyne/blob/f46e5fe610d175b96a490db24ef2d22b49cc594b/poutyne/framework/model_bundle.py#L1122-L1143
postgres/pgadmin4
374c5e952fa594d749fadf1f88076c1cba8c5f64
web/pgadmin/authenticate/__init__.py
python
get_auth_sources
(type)
return auth_source
Get the authenticated source object from the registry
Get the authenticated source object from the registry
[ "Get", "the", "authenticated", "source", "object", "from", "the", "registry" ]
def get_auth_sources(type): """Get the authenticated source object from the registry""" auth_sources = getattr(current_app, '_pgadmin_auth_sources', None) if auth_sources is None or not isinstance(auth_sources, dict): auth_sources = dict() if type in auth_sources: return auth_sources[type] auth_source = AuthSourceRegistry.get(type) if auth_source is not None: auth_sources[type] = auth_source setattr(current_app, '_pgadmin_auth_sources', auth_sources) return auth_source
[ "def", "get_auth_sources", "(", "type", ")", ":", "auth_sources", "=", "getattr", "(", "current_app", ",", "'_pgadmin_auth_sources'", ",", "None", ")", "if", "auth_sources", "is", "None", "or", "not", "isinstance", "(", "auth_sources", ",", "dict", ")", ":", ...
https://github.com/postgres/pgadmin4/blob/374c5e952fa594d749fadf1f88076c1cba8c5f64/web/pgadmin/authenticate/__init__.py#L258-L275
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/PAN-OS/Integrations/Panorama/Panorama.py
python
panorama_create_edl_command
(args: Dict[str, str])
Create an edl object
Create an edl object
[ "Create", "an", "edl", "object" ]
def panorama_create_edl_command(args: Dict[str, str]): """ Create an edl object """ edl_name = args.get('name') url = args.get('url', '').replace(' ', '%20') type_ = args.get('type') recurring = args.get('recurring') certificate_profile = args.get('certificate_profile') description = args.get('description') edl = panorama_create_edl(edl_name, url, type_, recurring, certificate_profile, description) edl_output = { 'Name': edl_name, 'URL': url, 'Type': type_, 'Recurring': recurring } if DEVICE_GROUP: edl_output['DeviceGroup'] = DEVICE_GROUP if description: edl_output['Description'] = description if certificate_profile: edl_output['CertificateProfile'] = certificate_profile return_results({ 'Type': entryTypes['note'], 'ContentsFormat': formats['json'], 'Contents': edl, 'ReadableContentsFormat': formats['text'], 'HumanReadable': 'External Dynamic List was created successfully.', 'EntryContext': { "Panorama.EDL(val.Name == obj.Name)": edl_output } })
[ "def", "panorama_create_edl_command", "(", "args", ":", "Dict", "[", "str", ",", "str", "]", ")", ":", "edl_name", "=", "args", ".", "get", "(", "'name'", ")", "url", "=", "args", ".", "get", "(", "'url'", ",", "''", ")", ".", "replace", "(", "' '"...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/PAN-OS/Integrations/Panorama/Panorama.py#L3579-L3615
lspvic/CopyNet
2cc44dd672115fe88a2d76bd59b76fb2d7389bb4
nmt/nmt/scripts/rouge.py
python
_get_word_ngrams
(n, sentences)
return _get_ngrams(n, words)
Calculates word n-grams for multiple sentences.
Calculates word n-grams for multiple sentences.
[ "Calculates", "word", "n", "-", "grams", "for", "multiple", "sentences", "." ]
def _get_word_ngrams(n, sentences): """Calculates word n-grams for multiple sentences. """ assert len(sentences) > 0 assert n > 0 words = _split_into_words(sentences) return _get_ngrams(n, words)
[ "def", "_get_word_ngrams", "(", "n", ",", "sentences", ")", ":", "assert", "len", "(", "sentences", ")", ">", "0", "assert", "n", ">", "0", "words", "=", "_split_into_words", "(", "sentences", ")", "return", "_get_ngrams", "(", "n", ",", "words", ")" ]
https://github.com/lspvic/CopyNet/blob/2cc44dd672115fe88a2d76bd59b76fb2d7389bb4/nmt/nmt/scripts/rouge.py#L42-L49
Fallen-Breath/MCDReforged
fdb1d2520b35f916123f265dbd94603981bb2b0c
mcdreforged/plugin/plugin_thread.py
python
PluginThread.run
(self)
[]
def run(self): try: while True: try: if self.task is not None: task_data = self.task self.task = None else: task_data = self.thread_pool.task_queue.get(timeout=0.01) # type: TaskData except queue.Empty: pass else: plugin = task_data.plugin # type: AbstractPlugin with plugin.plugin_manager.with_plugin_context(plugin): self.setName('{}@{}'.format(self, plugin.get_id())) self.thread_pool.working_count += 1 try: task_data.callback() except: self.thread_pool.mcdr_server.logger.exception('Exception in thread created by {}'.format(plugin)) finally: self.thread_pool.working_count -= 1 self.setName(self.original_name) finally: if self.flag_interrupt: break finally: with self.thread_pool.threads_write_lock: self.thread_pool.threads.remove(self)
[ "def", "run", "(", "self", ")", ":", "try", ":", "while", "True", ":", "try", ":", "if", "self", ".", "task", "is", "not", "None", ":", "task_data", "=", "self", ".", "task", "self", ".", "task", "=", "None", "else", ":", "task_data", "=", "self"...
https://github.com/Fallen-Breath/MCDReforged/blob/fdb1d2520b35f916123f265dbd94603981bb2b0c/mcdreforged/plugin/plugin_thread.py#L31-L59
riptideio/pymodbus
c5772b35ae3f29d1947f3ab453d8d00df846459f
pymodbus/server/async_io.py
python
StartTlsServer
(context=None, identity=None, address=None, sslctx=None, certfile=None, keyfile=None, allow_reuse_address=False, allow_reuse_port=False, custom_functions=[], defer_start=True, **kwargs)
return server
A factory to start and run a tls modbus server :param context: The ModbusServerContext datastore :param identity: An optional identify structure :param address: An optional (interface, port) to bind to. :param sslctx: The SSLContext to use for TLS (default None and auto create) :param certfile: The cert file path for TLS (used if sslctx is None) :param keyfile: The key file path for TLS (used if sslctx is None) :param allow_reuse_address: Whether the server will allow the reuse of an address. :param allow_reuse_port: Whether the server will allow the reuse of a port. :param custom_functions: An optional list of custom function classes supported by server instance. :param defer_start: if set, a coroutine which can be started and stopped will be returned. Otherwise, the server will be immediately spun up without the ability to shut it off from within the asyncio loop :param ignore_missing_slaves: True to not send errors on a request to a missing slave :return: an initialized but inactive server object coroutine
A factory to start and run a tls modbus server
[ "A", "factory", "to", "start", "and", "run", "a", "tls", "modbus", "server" ]
async def StartTlsServer(context=None, identity=None, address=None, sslctx=None, certfile=None, keyfile=None, allow_reuse_address=False, allow_reuse_port=False, custom_functions=[], defer_start=True, **kwargs): """ A factory to start and run a tls modbus server :param context: The ModbusServerContext datastore :param identity: An optional identify structure :param address: An optional (interface, port) to bind to. :param sslctx: The SSLContext to use for TLS (default None and auto create) :param certfile: The cert file path for TLS (used if sslctx is None) :param keyfile: The key file path for TLS (used if sslctx is None) :param allow_reuse_address: Whether the server will allow the reuse of an address. :param allow_reuse_port: Whether the server will allow the reuse of a port. :param custom_functions: An optional list of custom function classes supported by server instance. :param defer_start: if set, a coroutine which can be started and stopped will be returned. Otherwise, the server will be immediately spun up without the ability to shut it off from within the asyncio loop :param ignore_missing_slaves: True to not send errors on a request to a missing slave :return: an initialized but inactive server object coroutine """ framer = kwargs.pop("framer", ModbusTlsFramer) server = ModbusTlsServer(context, framer, identity, address, sslctx, certfile, keyfile, allow_reuse_address=allow_reuse_address, allow_reuse_port=allow_reuse_port, **kwargs) for f in custom_functions: server.decoder.register(f) # pragma: no cover if not defer_start: await server.serve_forever() return server
[ "async", "def", "StartTlsServer", "(", "context", "=", "None", ",", "identity", "=", "None", ",", "address", "=", "None", ",", "sslctx", "=", "None", ",", "certfile", "=", "None", ",", "keyfile", "=", "None", ",", "allow_reuse_address", "=", "False", ","...
https://github.com/riptideio/pymodbus/blob/c5772b35ae3f29d1947f3ab453d8d00df846459f/pymodbus/server/async_io.py#L851-L890
lisa-lab/pylearn2
af81e5c362f0df4df85c3e54e23b2adeec026055
pylearn2/datasets/utlc.py
python
load_ndarray_dataset
(name, normalize=True, transfer=False, normalize_on_the_fly=False, randomize_valid=False, randomize_test=False)
Load the train,valid,test data for the dataset `name` and return it in ndarray format. We suppose the data was created with ift6266h11/pretraitement/to_npy.py that shuffle the train. So the train should already be shuffled. Parameters ---------- name : 'avicenna', 'harry', 'rita', 'sylvester' or 'ule' Which dataset to load normalize : bool If True, we normalize the train dataset before returning it transfer : bool If True also return the transfer labels normalize_on_the_fly : bool If True, we return a Theano Variable that will give as output the normalized value. If the user only take a subtensor of that variable, Theano optimization should make that we will only have in memory the subtensor portion that is computed in normalized form. We store the original data in shared memory in its original dtype. This is usefull to have the original data in its original dtype in memory to same memory. Especialy usefull to be able to use rita and harry with 1G per jobs. randomize_valid : bool Do we randomize the order of the valid set? We always use the same random order If False, return in the same order as downloaded on the web randomize_test : bool Do we randomize the order of the test set? We always use the same random order If False, return in the same order as downloaded on the web Returns ------- train, valid, test : ndarrays Datasets returned if transfer = False train, valid, test, transfer : ndarrays Datasets returned if transfer = False
Load the train,valid,test data for the dataset `name` and return it in ndarray format.
[ "Load", "the", "train", "valid", "test", "data", "for", "the", "dataset", "name", "and", "return", "it", "in", "ndarray", "format", "." ]
def load_ndarray_dataset(name, normalize=True, transfer=False, normalize_on_the_fly=False, randomize_valid=False, randomize_test=False): """ Load the train,valid,test data for the dataset `name` and return it in ndarray format. We suppose the data was created with ift6266h11/pretraitement/to_npy.py that shuffle the train. So the train should already be shuffled. Parameters ---------- name : 'avicenna', 'harry', 'rita', 'sylvester' or 'ule' Which dataset to load normalize : bool If True, we normalize the train dataset before returning it transfer : bool If True also return the transfer labels normalize_on_the_fly : bool If True, we return a Theano Variable that will give as output the normalized value. If the user only take a subtensor of that variable, Theano optimization should make that we will only have in memory the subtensor portion that is computed in normalized form. We store the original data in shared memory in its original dtype. This is usefull to have the original data in its original dtype in memory to same memory. Especialy usefull to be able to use rita and harry with 1G per jobs. randomize_valid : bool Do we randomize the order of the valid set? We always use the same random order If False, return in the same order as downloaded on the web randomize_test : bool Do we randomize the order of the test set? We always use the same random order If False, return in the same order as downloaded on the web Returns ------- train, valid, test : ndarrays Datasets returned if transfer = False train, valid, test, transfer : ndarrays Datasets returned if transfer = False """ assert not (normalize and normalize_on_the_fly), \ "Can't normalize in 2 way at the same time!" assert name in ['avicenna', 'harry', 'rita', 'sylvester', 'ule'] common = os.path.join( preprocess('${PYLEARN2_DATA_PATH}'), 'UTLC', 'filetensor', name + '_') trname, vname, tename = [ common + subset + '.ft' for subset in ['train', 'valid', 'test']] train = load_filetensor(trname) valid = load_filetensor(vname) test = load_filetensor(tename) if randomize_valid: rng = make_np_rng(None, [1, 2, 3, 4], which_method='permutation') perm = rng.permutation(valid.shape[0]) valid = valid[perm] if randomize_test: rng = make_np_rng(None, [1, 2, 3, 4], which_method='permutation') perm = rng.permutation(test.shape[0]) test = test[perm] if normalize or normalize_on_the_fly: if normalize_on_the_fly: # Shared variables of the original type train = theano.shared(train, borrow=True, name=name + "_train") valid = theano.shared(valid, borrow=True, name=name + "_valid") test = theano.shared(test, borrow=True, name=name + "_test") # Symbolic variables cast into floatX train = theano.tensor.cast(train, theano.config.floatX) valid = theano.tensor.cast(valid, theano.config.floatX) test = theano.tensor.cast(test, theano.config.floatX) else: train = numpy.asarray(train, theano.config.floatX) valid = numpy.asarray(valid, theano.config.floatX) test = numpy.asarray(test, theano.config.floatX) if name == "ule": train /= 255 valid /= 255 test /= 255 elif name in ["avicenna", "sylvester"]: if name == "avicenna": train_mean = 514.62154022835455 train_std = 6.829096494224145 else: train_mean = 403.81889927027686 train_std = 96.43841050784053 train -= train_mean valid -= train_mean test -= train_mean train /= train_std valid /= train_std test /= train_std elif name == "harry": std = 0.69336046033925791 # train.std()slow to compute train /= std valid /= std test /= std elif name == "rita": v = numpy.asarray(230, dtype=theano.config.floatX) train /= v valid /= v test /= v else: raise Exception( "This dataset don't have its normalization defined") if transfer: transfer = load_ndarray_transfer(name) return train, valid, test, transfer else: return train, valid, test
[ "def", "load_ndarray_dataset", "(", "name", ",", "normalize", "=", "True", ",", "transfer", "=", "False", ",", "normalize_on_the_fly", "=", "False", ",", "randomize_valid", "=", "False", ",", "randomize_test", "=", "False", ")", ":", "assert", "not", "(", "n...
https://github.com/lisa-lab/pylearn2/blob/af81e5c362f0df4df85c3e54e23b2adeec026055/pylearn2/datasets/utlc.py#L21-L140
Ericsson/codechecker
c4e43f62dc3acbf71d3109b337db7c97f7852f43
tools/report-converter/codechecker_report_converter/analyzers/spotbugs/analyzer_result.py
python
AnalyzerResult.__event_from_method
(self, element)
return BugPathEvent( message, get_or_create_file(source_path, self.__file_cache), line, col)
Creates event from a Method element.
Creates event from a Method element.
[ "Creates", "event", "from", "a", "Method", "element", "." ]
def __event_from_method(self, element) -> Optional[BugPathEvent]: """ Creates event from a Method element. """ message = element.find('Message').text source_line = element.find('SourceLine') if source_line is None: return None source_path = source_line.attrib.get('sourcepath') source_path = self.__get_abs_path(source_path) if not source_path: return None line = int(source_line.attrib.get('start', 0)) col = 0 return BugPathEvent( message, get_or_create_file(source_path, self.__file_cache), line, col)
[ "def", "__event_from_method", "(", "self", ",", "element", ")", "->", "Optional", "[", "BugPathEvent", "]", ":", "message", "=", "element", ".", "find", "(", "'Message'", ")", ".", "text", "source_line", "=", "element", ".", "find", "(", "'SourceLine'", ")...
https://github.com/Ericsson/codechecker/blob/c4e43f62dc3acbf71d3109b337db7c97f7852f43/tools/report-converter/codechecker_report_converter/analyzers/spotbugs/analyzer_result.py#L168-L188
0vercl0k/stuffz
2ff82f4739d7e215c6140d4987efa8310db39d55
transmissionrpc.py
python
Client.start
(self, ids, bypass_queue=False, timeout=None)
.. WARNING:: Deprecated, please use start_torrent.
[]
def start(self, ids, bypass_queue=False, timeout=None): """ .. WARNING:: Deprecated, please use start_torrent. """ warnings.warn('start has been deprecated, please use start_torrent instead.', DeprecationWarning) self.start_torrent(ids, bypass_queue, timeout)
[ "def", "start", "(", "self", ",", "ids", ",", "bypass_queue", "=", "False", ",", "timeout", "=", "None", ")", ":", "warnings", ".", "warn", "(", "'start has been deprecated, please use start_torrent instead.'", ",", "DeprecationWarning", ")", "self", ".", "start_t...
https://github.com/0vercl0k/stuffz/blob/2ff82f4739d7e215c6140d4987efa8310db39d55/transmissionrpc.py#L1676-L1683
exaile/exaile
a7b58996c5c15b3aa7b9975ac13ee8f784ef4689
xlgui/widgets/playlist.py
python
PlaylistModel._compute_row_params
(self, rowidx)
return pixbuf, sensitive, weight
:returns: pixbuf, sensitive, weight
:returns: pixbuf, sensitive, weight
[ ":", "returns", ":", "pixbuf", "sensitive", "weight" ]
def _compute_row_params(self, rowidx): """ :returns: pixbuf, sensitive, weight """ pixbuf = self.clear_pixbuf.pixbuf weight = Pango.Weight.NORMAL sensitive = True playlist = self.playlist spatpos = playlist.spat_position spat = spatpos == rowidx if spat: pixbuf = self.stop_pixbuf.pixbuf if playlist is self.player.queue.current_playlist: if ( playlist.current_position == rowidx and playlist[rowidx] == self.player.current ): # this row is the current track, set a special icon state = self.player.get_state() weight = Pango.Weight.HEAVY if state == 'playing': if spat: pixbuf = self.play_stop_pixbuf.pixbuf else: pixbuf = self.play_pixbuf.pixbuf elif state == 'paused': if spat: pixbuf = self.pause_stop_pixbuf.pixbuf else: pixbuf = self.pause_pixbuf.pixbuf if spatpos == -1 or spatpos > rowidx: sensitive = True else: sensitive = False return pixbuf, sensitive, weight
[ "def", "_compute_row_params", "(", "self", ",", "rowidx", ")", ":", "pixbuf", "=", "self", ".", "clear_pixbuf", ".", "pixbuf", "weight", "=", "Pango", ".", "Weight", ".", "NORMAL", "sensitive", "=", "True", "playlist", "=", "self", ".", "playlist", "spatpo...
https://github.com/exaile/exaile/blob/a7b58996c5c15b3aa7b9975ac13ee8f784ef4689/xlgui/widgets/playlist.py#L1934-L1979
jiangxinyang227/NLP-Project
b11f67d8962f40e17990b4fc4551b0ea5496881c
multi_label_classifier/data_helpers/train_data.py
python
TrainData.gen_vocab
(self, words, labels)
return word_to_index, label_to_index
生成词汇,标签等映射表 :param words: 训练集所含有的单词 :param labels: 标签 :return:
生成词汇,标签等映射表 :param words: 训练集所含有的单词 :param labels: 标签 :return:
[ "生成词汇,标签等映射表", ":", "param", "words", ":", "训练集所含有的单词", ":", "param", "labels", ":", "标签", ":", "return", ":" ]
def gen_vocab(self, words, labels): """ 生成词汇,标签等映射表 :param words: 训练集所含有的单词 :param labels: 标签 :return: """ # 如果不是第一次处理,则可以直接加载生成好的词汇表和词向量 if os.path.exists(os.path.join(self._output_path, "word_vectors.npy")): print("load word_vectors") self.word_vectors = np.load(os.path.join(self._output_path, "word_vectors.npy")) if os.path.exists(os.path.join(self._output_path, "word_to_index.pkl")) and \ os.path.exists(os.path.join(self._output_path, "label_to_index.pkl")): print("load word_to_index") with open(os.path.join(self._output_path, "word_to_index.pkl"), "rb") as f: word_to_index = pickle.load(f) with open(os.path.join(self._output_path, "label_to_index.pkl"), "rb") as f: label_to_index = pickle.load(f) self.vocab_size = len(word_to_index) return word_to_index, label_to_index words = ["<PAD>", "<UNK>"] + words vocab = words[:self.vocab_size] # 若vocab的长读小于设置的vocab_size,则选择vocab的长度作为真实的vocab_size self.vocab_size = len(vocab) if self._word_vectors_path: word_vectors = self.get_word_vectors(vocab) self.word_vectors = word_vectors # 将本项目的词向量保存起来 np.save(os.path.join(self._output_path, "word_vectors.npy"), self.word_vectors) word_to_index = dict(zip(vocab, list(range(len(vocab))))) # 将词汇-索引映射表保存为pkl数据,之后做inference时直接加载来处理数据 with open(os.path.join(self._output_path, "word_to_index.pkl"), "wb") as f: pickle.dump(word_to_index, f) # 将标签-索引映射表保存为pkl数据 unique_labels = list(set(chain(*labels))) label_to_index = dict(zip(unique_labels, list(range(len(unique_labels))))) with open(os.path.join(self._output_path, "label_to_index.pkl"), "wb") as f: pickle.dump(label_to_index, f) return word_to_index, label_to_index
[ "def", "gen_vocab", "(", "self", ",", "words", ",", "labels", ")", ":", "# 如果不是第一次处理,则可以直接加载生成好的词汇表和词向量", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_output_path", ",", "\"word_vectors.npy\"", ")", ")", ...
https://github.com/jiangxinyang227/NLP-Project/blob/b11f67d8962f40e17990b4fc4551b0ea5496881c/multi_label_classifier/data_helpers/train_data.py#L94-L143
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
linkerd/datadog_checks/linkerd/config_models/defaults.py
python
instance_metrics
(field, value)
return get_default_field_value(field, value)
[]
def instance_metrics(field, value): return get_default_field_value(field, value)
[ "def", "instance_metrics", "(", "field", ",", "value", ")", ":", "return", "get_default_field_value", "(", "field", ",", "value", ")" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/linkerd/datadog_checks/linkerd/config_models/defaults.py#L193-L194
PaddlePaddle/Research
2da0bd6c72d60e9df403aff23a7802779561c4a1
NLP/ACL2019-KTNET/reading_comprehension/src/model/bert.py
python
BertModel.get_pooled_output
(self)
return next_sent_feat
Get the first feature of each sequence for classification
Get the first feature of each sequence for classification
[ "Get", "the", "first", "feature", "of", "each", "sequence", "for", "classification" ]
def get_pooled_output(self): """Get the first feature of each sequence for classification""" next_sent_feat = fluid.layers.slice( input=self._enc_out, axes=[1], starts=[0], ends=[1]) next_sent_feat = fluid.layers.fc( input=next_sent_feat, size=self._emb_size, act="tanh", param_attr=fluid.ParamAttr( name="pooled_fc.w_0", initializer=self._param_initializer), bias_attr="pooled_fc.b_0") return next_sent_feat
[ "def", "get_pooled_output", "(", "self", ")", ":", "next_sent_feat", "=", "fluid", ".", "layers", ".", "slice", "(", "input", "=", "self", ".", "_enc_out", ",", "axes", "=", "[", "1", "]", ",", "starts", "=", "[", "0", "]", ",", "ends", "=", "[", ...
https://github.com/PaddlePaddle/Research/blob/2da0bd6c72d60e9df403aff23a7802779561c4a1/NLP/ACL2019-KTNET/reading_comprehension/src/model/bert.py#L151-L163
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/core/virtual_network_client_composite_operations.py
python
VirtualNetworkClientCompositeOperations.delete_local_peering_gateway_and_wait_for_state
(self, local_peering_gateway_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={})
Calls :py:func:`~oci.core.VirtualNetworkClient.delete_local_peering_gateway` and waits for the :py:class:`~oci.core.models.LocalPeeringGateway` acted upon to enter the given state(s). :param str local_peering_gateway_id: (required) The `OCID`__ of the local peering gateway. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.core.models.LocalPeeringGateway.lifecycle_state` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.core.VirtualNetworkClient.delete_local_peering_gateway` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
Calls :py:func:`~oci.core.VirtualNetworkClient.delete_local_peering_gateway` and waits for the :py:class:`~oci.core.models.LocalPeeringGateway` acted upon to enter the given state(s).
[ "Calls", ":", "py", ":", "func", ":", "~oci", ".", "core", ".", "VirtualNetworkClient", ".", "delete_local_peering_gateway", "and", "waits", "for", "the", ":", "py", ":", "class", ":", "~oci", ".", "core", ".", "models", ".", "LocalPeeringGateway", "acted", ...
def delete_local_peering_gateway_and_wait_for_state(self, local_peering_gateway_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}): """ Calls :py:func:`~oci.core.VirtualNetworkClient.delete_local_peering_gateway` and waits for the :py:class:`~oci.core.models.LocalPeeringGateway` acted upon to enter the given state(s). :param str local_peering_gateway_id: (required) The `OCID`__ of the local peering gateway. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.core.models.LocalPeeringGateway.lifecycle_state` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.core.VirtualNetworkClient.delete_local_peering_gateway` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait """ initial_get_result = self.client.get_local_peering_gateway(local_peering_gateway_id) operation_result = None try: operation_result = self.client.delete_local_peering_gateway(local_peering_gateway_id, **operation_kwargs) except oci.exceptions.ServiceError as e: if e.status == 404: return WAIT_RESOURCE_NOT_FOUND else: raise e if not wait_for_states: return operation_result lowered_wait_for_states = [w.lower() for w in wait_for_states] try: waiter_result = oci.wait_until( self.client, initial_get_result, evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states, succeed_on_not_found=True, **waiter_kwargs ) result_to_return = waiter_result return result_to_return except Exception as e: raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
[ "def", "delete_local_peering_gateway_and_wait_for_state", "(", "self", ",", "local_peering_gateway_id", ",", "wait_for_states", "=", "[", "]", ",", "operation_kwargs", "=", "{", "}", ",", "waiter_kwargs", "=", "{", "}", ")", ":", "initial_get_result", "=", "self", ...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/core/virtual_network_client_composite_operations.py#L1792-L1839
mpatacchiola/dissecting-reinforcement-learning
38660b0a0d5aed077a46acb4bcb2013565304d9c
src/5/genetic_algorithm_policy_estimation.py
python
return_mutated_population
(population, gene_set, mutation_rate, elite=0)
return population
Returns a mutated population It applies the point-mutation mechanism to each value contained in the chromosomes. @param population numpy array containing the chromosomes @param gene_set a numpy array with the value to pick @parma mutation_rate a float repesenting the probaiblity of mutation for each gene (e.g. 0.02=2%) @return the mutated population
Returns a mutated population
[ "Returns", "a", "mutated", "population" ]
def return_mutated_population(population, gene_set, mutation_rate, elite=0): '''Returns a mutated population It applies the point-mutation mechanism to each value contained in the chromosomes. @param population numpy array containing the chromosomes @param gene_set a numpy array with the value to pick @parma mutation_rate a float repesenting the probaiblity of mutation for each gene (e.g. 0.02=2%) @return the mutated population ''' for x in np.nditer(population[elite:,:], op_flags=['readwrite']): if(np.random.uniform(0,1) < mutation_rate): x[...] = np.random.choice(gene_set, 1) return population
[ "def", "return_mutated_population", "(", "population", ",", "gene_set", ",", "mutation_rate", ",", "elite", "=", "0", ")", ":", "for", "x", "in", "np", ".", "nditer", "(", "population", "[", "elite", ":", ",", ":", "]", ",", "op_flags", "=", "[", "'rea...
https://github.com/mpatacchiola/dissecting-reinforcement-learning/blob/38660b0a0d5aed077a46acb4bcb2013565304d9c/src/5/genetic_algorithm_policy_estimation.py#L74-L88
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python3-alpha/python-libs/gdata/apps/emailsettings/data.py
python
EmailSettingsVacationResponder.GetSubject
(self)
return self._GetProperty(VACATION_RESPONDER_SUBJECT)
Get the Subject value of the Vacation Responder object. Returns: The Subject value of this Vacation Responder object as a string or None.
Get the Subject value of the Vacation Responder object.
[ "Get", "the", "Subject", "value", "of", "the", "Vacation", "Responder", "object", "." ]
def GetSubject(self): """Get the Subject value of the Vacation Responder object. Returns: The Subject value of this Vacation Responder object as a string or None. """ return self._GetProperty(VACATION_RESPONDER_SUBJECT)
[ "def", "GetSubject", "(", "self", ")", ":", "return", "self", ".", "_GetProperty", "(", "VACATION_RESPONDER_SUBJECT", ")" ]
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python3-alpha/python-libs/gdata/apps/emailsettings/data.py#L837-L844
filerock/FileRock-Client
37214f701666e76e723595f8f9ed238a42f6eb06
filerockclient/osconfig/PlatformSettingsOSX.py
python
PlatformSettingsOSX._get_launch_agent_content
(self, enable)
return doc.toxml(encoding='utf-8')
Returns XML content of launch agent plist file
Returns XML content of launch agent plist file
[ "Returns", "XML", "content", "of", "launch", "agent", "plist", "file" ]
def _get_launch_agent_content(self, enable): """ Returns XML content of launch agent plist file """ imp = getDOMImplementation() doctype = imp.createDocumentType("plist", "-//Apple//DTD PLIST 1.0//EN", "http://www.apple.com/DTDs/PropertyList-1.0.dtd") doc = imp.createDocument(None,"plist",doctype) doc.documentElement.setAttribute("version","1.0") dict_elem = doc.createElement("dict") label_key_elem = doc.createElement("key") label_key_elem.appendChild(doc.createTextNode("Label")) label_string_elem = doc.createElement("string") label_string_elem.appendChild(doc.createTextNode(self.LAUNCH_AGENT_BUNDLE_ID)) prog_args_key_elem = doc.createElement("key") prog_args_key_elem.appendChild(doc.createTextNode("ProgramArguments")) args_array_elem = doc.createElement("array") for argument in self._filter_cmd_line_args(self.cmdline_args): arg_string_elem = doc.createElement("string") arg_string_elem.appendChild(doc.createTextNode(argument)) args_array_elem.appendChild(arg_string_elem) run_at_load_key = doc.createElement("key") run_at_load_key.appendChild(doc.createTextNode("RunAtLoad")) run_at_load_true = doc.createElement(str(enable).lower()) dict_elem.appendChild(label_key_elem) dict_elem.appendChild(label_string_elem) dict_elem.appendChild(prog_args_key_elem) dict_elem.appendChild(args_array_elem) dict_elem.appendChild(run_at_load_key) dict_elem.appendChild(run_at_load_true) doc.documentElement.appendChild(dict_elem) return doc.toxml(encoding='utf-8')
[ "def", "_get_launch_agent_content", "(", "self", ",", "enable", ")", ":", "imp", "=", "getDOMImplementation", "(", ")", "doctype", "=", "imp", ".", "createDocumentType", "(", "\"plist\"", ",", "\"-//Apple//DTD PLIST 1.0//EN\"", ",", "\"http://www.apple.com/DTDs/Property...
https://github.com/filerock/FileRock-Client/blob/37214f701666e76e723595f8f9ed238a42f6eb06/filerockclient/osconfig/PlatformSettingsOSX.py#L91-L136
CoinAlpha/hummingbot
36f6149c1644c07cd36795b915f38b8f49b798e7
hummingbot/connector/exchange/ndax/ndax_exchange.py
python
NdaxExchange._api_request
(self, method: str, path_url: str, params: Optional[Dict[str, Any]] = None, data: Optional[Dict[str, Any]] = None, is_auth_required: bool = False, limit_id: Optional[str] = None)
return parsed_response
Sends an aiohttp request and waits for a response. :param method: The HTTP method, e.g. get or post :param path_url: The path url or the API end point :param params: The query parameters of the API request :param params: The body parameters of the API request :param is_auth_required: Whether an authentication is required, when True the function will add encrypted signature to the request. :param limit_id: The id used for the API throttler. If not supplied, the `path_url` is used instead. :returns A response in json format.
Sends an aiohttp request and waits for a response. :param method: The HTTP method, e.g. get or post :param path_url: The path url or the API end point :param params: The query parameters of the API request :param params: The body parameters of the API request :param is_auth_required: Whether an authentication is required, when True the function will add encrypted signature to the request. :param limit_id: The id used for the API throttler. If not supplied, the `path_url` is used instead. :returns A response in json format.
[ "Sends", "an", "aiohttp", "request", "and", "waits", "for", "a", "response", ".", ":", "param", "method", ":", "The", "HTTP", "method", "e", ".", "g", ".", "get", "or", "post", ":", "param", "path_url", ":", "The", "path", "url", "or", "the", "API", ...
async def _api_request(self, method: str, path_url: str, params: Optional[Dict[str, Any]] = None, data: Optional[Dict[str, Any]] = None, is_auth_required: bool = False, limit_id: Optional[str] = None) -> Union[Dict[str, Any], List[Any]]: """ Sends an aiohttp request and waits for a response. :param method: The HTTP method, e.g. get or post :param path_url: The path url or the API end point :param params: The query parameters of the API request :param params: The body parameters of the API request :param is_auth_required: Whether an authentication is required, when True the function will add encrypted signature to the request. :param limit_id: The id used for the API throttler. If not supplied, the `path_url` is used instead. :returns A response in json format. """ url = ndax_utils.rest_api_url(self._domain) + path_url try: if is_auth_required: headers = self._auth.get_auth_headers() else: headers = self._auth.get_headers() limit_id = limit_id or path_url if method == "GET": async with self._throttler.execute_task(limit_id): response = await self._shared_client.get(url, headers=headers, params=params) elif method == "POST": async with self._throttler.execute_task(limit_id): response = await self._shared_client.post(url, headers=headers, data=ujson.dumps(data)) else: raise NotImplementedError(f"{method} HTTP Method not implemented. ") data = await response.text() if data == CONSTANTS.API_LIMIT_REACHED_ERROR_MESSAGE: raise Exception(f"The exchange API request limit has been reached (original error '{data}')") parsed_response = await response.json() except ValueError as e: self.logger().error(f"{str(e)}") raise ValueError(f"Error authenticating request {method} {url}. Error: {str(e)}") except Exception as e: raise IOError(f"Error parsing data from {url}. Error: {str(e)}") if response.status != 200 or (isinstance(parsed_response, dict) and not parsed_response.get("result", True)): self.logger().error(f"Error fetching data from {url}. HTTP status is {response.status}. " f"Message: {parsed_response} " f"Params: {params} " f"Data: {data}") raise Exception(f"Error fetching data from {url}. HTTP status is {response.status}. " f"Message: {parsed_response} " f"Params: {params} " f"Data: {data}") return parsed_response
[ "async", "def", "_api_request", "(", "self", ",", "method", ":", "str", ",", "path_url", ":", "str", ",", "params", ":", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", "=", "None", ",", "data", ":", "Optional", "[", "Dict", "[", "str", ...
https://github.com/CoinAlpha/hummingbot/blob/36f6149c1644c07cd36795b915f38b8f49b798e7/hummingbot/connector/exchange/ndax/ndax_exchange.py#L299-L356
syang1993/gst-tacotron
f28635c539d6a3a9ceece7be2acf8aa2fe3477b0
models/gmm_attention_wrapper.py
python
GMMAttentionWrapper._get_params
(self, cell_out, prev_kappa)
return alpha, beta, kappa
Compute window parameters In GMM-based attention, the location parameters kappa are defined as offsets from the previous locations, and that the size of the offset is constrained to be greater than zero. Then we get: alpha: the importance of the window within the mixture. beta: the width of the window. kappa: the location of the window.
Compute window parameters In GMM-based attention, the location parameters kappa are defined as offsets from the previous locations, and that the size of the offset is constrained to be greater than zero. Then we get:
[ "Compute", "window", "parameters", "In", "GMM", "-", "based", "attention", "the", "location", "parameters", "kappa", "are", "defined", "as", "offsets", "from", "the", "previous", "locations", "and", "that", "the", "size", "of", "the", "offset", "is", "constrai...
def _get_params(self, cell_out, prev_kappa): """Compute window parameters In GMM-based attention, the location parameters kappa are defined as offsets from the previous locations, and that the size of the offset is constrained to be greater than zero. Then we get: alpha: the importance of the window within the mixture. beta: the width of the window. kappa: the location of the window. """ window_params = tf.layers.dense(cell_out, units=3*self._num_attn_mixture) alpha, beta, kappa = tf.split(tf.exp(window_params), 3, axis=1) kappa = kappa + prev_kappa return alpha, beta, kappa
[ "def", "_get_params", "(", "self", ",", "cell_out", ",", "prev_kappa", ")", ":", "window_params", "=", "tf", ".", "layers", ".", "dense", "(", "cell_out", ",", "units", "=", "3", "*", "self", ".", "_num_attn_mixture", ")", "alpha", ",", "beta", ",", "k...
https://github.com/syang1993/gst-tacotron/blob/f28635c539d6a3a9ceece7be2acf8aa2fe3477b0/models/gmm_attention_wrapper.py#L71-L85
openstack/tempest
fe0ac89a5a1c43fa908a76759cd99eea3b1f9853
tempest/lib/services/compute/servers_client.py
python
ServersClient.create_server
(self, **kwargs)
return rest_client.ResponseBody(resp, body)
Create server. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#create-server :param name: Server name :param imageRef: Image reference (UUID) :param flavorRef: Flavor reference (UUID or full URL) Most parameters except the following are passed to the API without any changes. :param disk_config: The name is changed to OS-DCF:diskConfig :param scheduler_hints: The name is changed to os:scheduler_hints and the parameter is set in the same level as the parameter 'server'.
Create server.
[ "Create", "server", "." ]
def create_server(self, **kwargs): """Create server. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/compute/#create-server :param name: Server name :param imageRef: Image reference (UUID) :param flavorRef: Flavor reference (UUID or full URL) Most parameters except the following are passed to the API without any changes. :param disk_config: The name is changed to OS-DCF:diskConfig :param scheduler_hints: The name is changed to os:scheduler_hints and the parameter is set in the same level as the parameter 'server'. """ body = copy.deepcopy(kwargs) if body.get('disk_config'): body['OS-DCF:diskConfig'] = body.pop('disk_config') hints = None if body.get('scheduler_hints'): hints = {'os:scheduler_hints': body.pop('scheduler_hints')} post_body = {'server': body} if hints: post_body.update(hints) post_body = json.dumps(post_body) resp, body = self.post('servers', post_body) body = json.loads(body) # NOTE(maurosr): this deals with the case of multiple server create # with return reservation id set True if 'reservation_id' in body: return rest_client.ResponseBody(resp, body) if self.enable_instance_password: create_schema = schema.create_server_with_admin_pass else: create_schema = schema.create_server self.validate_response(create_schema, resp, body) return rest_client.ResponseBody(resp, body)
[ "def", "create_server", "(", "self", ",", "*", "*", "kwargs", ")", ":", "body", "=", "copy", ".", "deepcopy", "(", "kwargs", ")", "if", "body", ".", "get", "(", "'disk_config'", ")", ":", "body", "[", "'OS-DCF:diskConfig'", "]", "=", "body", ".", "po...
https://github.com/openstack/tempest/blob/fe0ac89a5a1c43fa908a76759cd99eea3b1f9853/tempest/lib/services/compute/servers_client.py#L80-L123
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/core/boxing.py
python
unbox_pyobject
(typ, obj, c)
return NativeValue(obj)
[]
def unbox_pyobject(typ, obj, c): return NativeValue(obj)
[ "def", "unbox_pyobject", "(", "typ", ",", "obj", ",", "c", ")", ":", "return", "NativeValue", "(", "obj", ")" ]
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/core/boxing.py#L1009-L1010
CLUEbenchmark/CLUE
5bd39732734afecb490cf18a5212e692dbf2c007
baselines/models/albert/modeling.py
python
gelu
(x)
return x * cdf
Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: x: float Tensor to perform activation. Returns: `x` with the GELU activation applied.
Gaussian Error Linear Unit.
[ "Gaussian", "Error", "Linear", "Unit", "." ]
def gelu(x): """Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: x: float Tensor to perform activation. Returns: `x` with the GELU activation applied. """ cdf = 0.5 * (1.0 + tf.tanh( (np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3))))) return x * cdf
[ "def", "gelu", "(", "x", ")", ":", "cdf", "=", "0.5", "*", "(", "1.0", "+", "tf", ".", "tanh", "(", "(", "np", ".", "sqrt", "(", "2", "/", "np", ".", "pi", ")", "*", "(", "x", "+", "0.044715", "*", "tf", ".", "pow", "(", "x", ",", "3", ...
https://github.com/CLUEbenchmark/CLUE/blob/5bd39732734afecb490cf18a5212e692dbf2c007/baselines/models/albert/modeling.py#L286-L299
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/zj/v20190121/models.py
python
DescribeSmsSignListRequest.__init__
(self)
r""" :param License: 商户证书 :type License: str :param SignIdSet: 签名ID数组 :type SignIdSet: list of int non-negative :param International: 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 :type International: int
r""" :param License: 商户证书 :type License: str :param SignIdSet: 签名ID数组 :type SignIdSet: list of int non-negative :param International: 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 :type International: int
[ "r", ":", "param", "License", ":", "商户证书", ":", "type", "License", ":", "str", ":", "param", "SignIdSet", ":", "签名ID数组", ":", "type", "SignIdSet", ":", "list", "of", "int", "non", "-", "negative", ":", "param", "International", ":", "是否国际", "/", "港澳台短信...
def __init__(self): r""" :param License: 商户证书 :type License: str :param SignIdSet: 签名ID数组 :type SignIdSet: list of int non-negative :param International: 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 :type International: int """ self.License = None self.SignIdSet = None self.International = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "License", "=", "None", "self", ".", "SignIdSet", "=", "None", "self", ".", "International", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/zj/v20190121/models.py#L975-L988
stoq/stoq
c26991644d1affcf96bc2e0a0434796cabdf8448
stoqlib/domain/workorder.py
python
WorkOrderPackageItem.send
(self, user: LoginUser)
Send the item to the :attr:`WorkOrderPackage.destination_branch` This will mark the package as sent. Note that it's only possible to call this on the same branch as :attr:`.source_branch`. When calling this, the work orders' :attr:`WorkOrder.current_branch` will be ``None``, since they are on a package and not on any branch.
Send the item to the :attr:`WorkOrderPackage.destination_branch`
[ "Send", "the", "item", "to", "the", ":", "attr", ":", "WorkOrderPackage", ".", "destination_branch" ]
def send(self, user: LoginUser): """Send the item to the :attr:`WorkOrderPackage.destination_branch` This will mark the package as sent. Note that it's only possible to call this on the same branch as :attr:`.source_branch`. When calling this, the work orders' :attr:`WorkOrder.current_branch` will be ``None``, since they are on a package and not on any branch. """ if self.package.destination_branch != self.order.branch: old_execution_branch = self.order.execution_branch self.order.execution_branch = self.package.destination_branch WorkOrderHistory.add_entry( self.store, self.order, _(u"Execution branch"), user=user, old_value=(old_execution_branch and old_execution_branch.get_description()), new_value=self.package.destination_branch.get_description())
[ "def", "send", "(", "self", ",", "user", ":", "LoginUser", ")", ":", "if", "self", ".", "package", ".", "destination_branch", "!=", "self", ".", "order", ".", "branch", ":", "old_execution_branch", "=", "self", ".", "order", ".", "execution_branch", "self"...
https://github.com/stoq/stoq/blob/c26991644d1affcf96bc2e0a0434796cabdf8448/stoqlib/domain/workorder.py#L103-L119
jupyter/nbformat
dee3e4f0e97084009f8a8abc34104ad45b9b9896
nbformat/_struct.py
python
Struct.__isub__
(self, other)
return self
Inplace remove keys from self that are in other. Examples -------- >>> s1 = Struct(a=10,b=30) >>> s2 = Struct(a=40) >>> s1 -= s2 >>> s1 {'b': 30}
Inplace remove keys from self that are in other.
[ "Inplace", "remove", "keys", "from", "self", "that", "are", "in", "other", "." ]
def __isub__(self, other): """Inplace remove keys from self that are in other. Examples -------- >>> s1 = Struct(a=10,b=30) >>> s2 = Struct(a=40) >>> s1 -= s2 >>> s1 {'b': 30} """ for k in other.keys(): if k in self: del self[k] return self
[ "def", "__isub__", "(", "self", ",", "other", ")", ":", "for", "k", "in", "other", ".", "keys", "(", ")", ":", "if", "k", "in", "self", ":", "del", "self", "[", "k", "]", "return", "self" ]
https://github.com/jupyter/nbformat/blob/dee3e4f0e97084009f8a8abc34104ad45b9b9896/nbformat/_struct.py#L189-L204
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/pickle.py
python
_Unpickler.load_long4
(self)
[]
def load_long4(self): n, = unpack('<i', self.read(4)) if n < 0: # Corrupt or hostile pickle -- we never write one like this raise UnpicklingError("LONG pickle has negative byte count") data = self.read(n) self.append(decode_long(data))
[ "def", "load_long4", "(", "self", ")", ":", "n", ",", "=", "unpack", "(", "'<i'", ",", "self", ".", "read", "(", "4", ")", ")", "if", "n", "<", "0", ":", "# Corrupt or hostile pickle -- we never write one like this", "raise", "UnpicklingError", "(", "\"LONG ...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/pickle.py#L1135-L1141
mongodb/mongo-python-driver
c760f900f2e4109a247c2ffc8ad3549362007772
gridfs/grid_file.py
python
GridOut.__exit__
(self, exc_type, exc_val, exc_tb)
return False
Makes it possible to use :class:`GridOut` files with the context manager protocol.
Makes it possible to use :class:`GridOut` files with the context manager protocol.
[ "Makes", "it", "possible", "to", "use", ":", "class", ":", "GridOut", "files", "with", "the", "context", "manager", "protocol", "." ]
def __exit__(self, exc_type, exc_val, exc_tb): """Makes it possible to use :class:`GridOut` files with the context manager protocol. """ self.close() return False
[ "def", "__exit__", "(", "self", ",", "exc_type", ",", "exc_val", ",", "exc_tb", ")", ":", "self", ".", "close", "(", ")", "return", "False" ]
https://github.com/mongodb/mongo-python-driver/blob/c760f900f2e4109a247c2ffc8ad3549362007772/gridfs/grid_file.py#L694-L699
meduza-corp/interstellar
40a801ccd7856491726f5a126621d9318cabe2e1
gsutil/third_party/httplib2/python2/httplib2/__init__.py
python
safename
(filename)
return ",".join((filename, filemd5))
Return a filename suitable for the cache. Strips dangerous and common characters to create a filename we can use to store the cache in.
Return a filename suitable for the cache.
[ "Return", "a", "filename", "suitable", "for", "the", "cache", "." ]
def safename(filename): """Return a filename suitable for the cache. Strips dangerous and common characters to create a filename we can use to store the cache in. """ try: if re_url_scheme.match(filename): if isinstance(filename,str): filename = filename.decode('utf-8') filename = filename.encode('idna') else: filename = filename.encode('idna') except UnicodeError: pass if isinstance(filename,unicode): filename=filename.encode('utf-8') filemd5 = _md5(filename).hexdigest() filename = re_url_scheme.sub("", filename) filename = re_slash.sub(",", filename) # limit length of filename if len(filename)>200: filename=filename[:200] return ",".join((filename, filemd5))
[ "def", "safename", "(", "filename", ")", ":", "try", ":", "if", "re_url_scheme", ".", "match", "(", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "str", ")", ":", "filename", "=", "filename", ".", "decode", "(", "'utf-8'", ")", "filen...
https://github.com/meduza-corp/interstellar/blob/40a801ccd7856491726f5a126621d9318cabe2e1/gsutil/third_party/httplib2/python2/httplib2/__init__.py#L235-L260
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/asyncio/base_events.py
python
BaseEventLoop.run_forever
(self)
Run until stop() is called.
Run until stop() is called.
[ "Run", "until", "stop", "()", "is", "called", "." ]
def run_forever(self): """Run until stop() is called.""" self._check_closed() self._check_running() self._set_coroutine_origin_tracking(self._debug) self._thread_id = threading.get_ident() old_agen_hooks = sys.get_asyncgen_hooks() sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook, finalizer=self._asyncgen_finalizer_hook) try: events._set_running_loop(self) while True: self._run_once() if self._stopping: break finally: self._stopping = False self._thread_id = None events._set_running_loop(None) self._set_coroutine_origin_tracking(False) sys.set_asyncgen_hooks(*old_agen_hooks)
[ "def", "run_forever", "(", "self", ")", ":", "self", ".", "_check_closed", "(", ")", "self", ".", "_check_running", "(", ")", "self", ".", "_set_coroutine_origin_tracking", "(", "self", ".", "_debug", ")", "self", ".", "_thread_id", "=", "threading", ".", ...
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/asyncio/base_events.py#L557-L578
uber/causalml
ebf265156f23bba4939a7db0f635c35408324708
causalml/optimize/utils.py
python
get_actual_value
(treatment, observed_outcome, conversion_value, conditions, conversion_cost, impression_cost)
return actual_value
Set the conversion and impression costs based on a dict of parameters. Calculate the actual value of targeting a user with the actual treatment group using the above parameters. Params ------ treatment : array, shape = (num_samples, ) Treatment array. observed_outcome : array, shape = (num_samples, ) Observed outcome array, aka y. conversion_value : array, shape = (num_samples, ) The value of converting a given user. conditions : list, len = len(set(treatment)) List of treatment conditions. conversion_cost : array, shape = (num_samples, num_treatment) Array of conversion costs for each unit in each treatment. impression_cost : array, shape = (num_samples, num_treatment) Array of impression costs for each unit in each treatment. Returns ------- actual_value : array, shape = (num_samples, ) Array of actual values of havng a user in their actual treatment group. conversion_value : array, shape = (num_samples, ) Array of payoffs from converting a user.
Set the conversion and impression costs based on a dict of parameters.
[ "Set", "the", "conversion", "and", "impression", "costs", "based", "on", "a", "dict", "of", "parameters", "." ]
def get_actual_value(treatment, observed_outcome, conversion_value, conditions, conversion_cost, impression_cost): ''' Set the conversion and impression costs based on a dict of parameters. Calculate the actual value of targeting a user with the actual treatment group using the above parameters. Params ------ treatment : array, shape = (num_samples, ) Treatment array. observed_outcome : array, shape = (num_samples, ) Observed outcome array, aka y. conversion_value : array, shape = (num_samples, ) The value of converting a given user. conditions : list, len = len(set(treatment)) List of treatment conditions. conversion_cost : array, shape = (num_samples, num_treatment) Array of conversion costs for each unit in each treatment. impression_cost : array, shape = (num_samples, num_treatment) Array of impression costs for each unit in each treatment. Returns ------- actual_value : array, shape = (num_samples, ) Array of actual values of havng a user in their actual treatment group. conversion_value : array, shape = (num_samples, ) Array of payoffs from converting a user. ''' cost_filter = [actual_group == possible_group for actual_group in treatment for possible_group in conditions] conversion_cost_flat = conversion_cost.flatten() actual_cc = conversion_cost_flat[cost_filter] impression_cost_flat = impression_cost.flatten() actual_ic = impression_cost_flat[cost_filter] # Calculate the actual value of having a user in their actual treatment actual_value = (conversion_value - actual_cc) * \ observed_outcome - actual_ic return actual_value
[ "def", "get_actual_value", "(", "treatment", ",", "observed_outcome", ",", "conversion_value", ",", "conditions", ",", "conversion_cost", ",", "impression_cost", ")", ":", "cost_filter", "=", "[", "actual_group", "==", "possible_group", "for", "actual_group", "in", ...
https://github.com/uber/causalml/blob/ebf265156f23bba4939a7db0f635c35408324708/causalml/optimize/utils.py#L56-L106