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
wtforms/wtforms
efe4e90acdb4a6b5d9b64a25756a33b41719319b
src/wtforms/form.py
python
BaseForm.__delitem__
(self, name)
Remove a field from this form.
Remove a field from this form.
[ "Remove", "a", "field", "from", "this", "form", "." ]
def __delitem__(self, name): """Remove a field from this form.""" del self._fields[name]
[ "def", "__delitem__", "(", "self", ",", "name", ")", ":", "del", "self", ".", "_fields", "[", "name", "]" ]
https://github.com/wtforms/wtforms/blob/efe4e90acdb4a6b5d9b64a25756a33b41719319b/src/wtforms/form.py#L69-L71
ctxis/canape
5f0e03424577296bcc60c2008a60a98ec5307e4b
CANAPE.Scripting/Lib/decimal.py
python
Context.remainder_near
(self, a, b)
return a.remainder_near(b, context=self)
Returns to be "a - b * n", where n is the integer nearest the exact value of "x / b" (if two integers are equally near then the even one is chosen). If the result is equal to 0 then its sign will be the sign of a. This operation will fail under the same conditions as integer division (that is, if integer division on the same two operands would fail, the remainder cannot be calculated). >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) Decimal('-0.9') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) Decimal('-2') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) Decimal('1') >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) Decimal('-1') >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) Decimal('0.2') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) Decimal('0.1') >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) Decimal('-0.3') >>> ExtendedContext.remainder_near(3, 11) Decimal('3') >>> ExtendedContext.remainder_near(Decimal(3), 11) Decimal('3') >>> ExtendedContext.remainder_near(3, Decimal(11)) Decimal('3')
Returns to be "a - b * n", where n is the integer nearest the exact value of "x / b" (if two integers are equally near then the even one is chosen). If the result is equal to 0 then its sign will be the sign of a.
[ "Returns", "to", "be", "a", "-", "b", "*", "n", "where", "n", "is", "the", "integer", "nearest", "the", "exact", "value", "of", "x", "/", "b", "(", "if", "two", "integers", "are", "equally", "near", "then", "the", "even", "one", "is", "chosen", ")"...
def remainder_near(self, a, b): """Returns to be "a - b * n", where n is the integer nearest the exact value of "x / b" (if two integers are equally near then the even one is chosen). If the result is equal to 0 then its sign will be the sign of a. This operation will fail under the same conditions as integer division (that is, if integer division on the same two operands would fail, the remainder cannot be calculated). >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) Decimal('-0.9') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) Decimal('-2') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) Decimal('1') >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) Decimal('-1') >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) Decimal('0.2') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) Decimal('0.1') >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) Decimal('-0.3') >>> ExtendedContext.remainder_near(3, 11) Decimal('3') >>> ExtendedContext.remainder_near(Decimal(3), 11) Decimal('3') >>> ExtendedContext.remainder_near(3, Decimal(11)) Decimal('3') """ a = _convert_other(a, raiseit=True) return a.remainder_near(b, context=self)
[ "def", "remainder_near", "(", "self", ",", "a", ",", "b", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "remainder_near", "(", "b", ",", "context", "=", "self", ")" ]
https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/decimal.py#L5127-L5159
sublimelsp/LSP
19a01aa045de04bcc805e56043923656548050e0
plugin/session_view.py
python
SessionView._register_auto_complete_triggers
(self, registration_id: str, trigger_chars: List[str])
Register trigger characters from a dynamic server registration.
Register trigger characters from a dynamic server registration.
[ "Register", "trigger", "characters", "from", "a", "dynamic", "server", "registration", "." ]
def _register_auto_complete_triggers(self, registration_id: str, trigger_chars: List[str]) -> None: """Register trigger characters from a dynamic server registration.""" self._apply_auto_complete_triggers(self.view.settings(), trigger_chars, registration_id)
[ "def", "_register_auto_complete_triggers", "(", "self", ",", "registration_id", ":", "str", ",", "trigger_chars", ":", "List", "[", "str", "]", ")", "->", "None", ":", "self", ".", "_apply_auto_complete_triggers", "(", "self", ".", "view", ".", "settings", "("...
https://github.com/sublimelsp/LSP/blob/19a01aa045de04bcc805e56043923656548050e0/plugin/session_view.py#L140-L142
lepture/authlib
2284f751a47474da7d127303e0d8f34d9046c310
authlib/oauth2/rfc6749/grants/authorization_code.py
python
AuthorizationCodeGrant.save_authorization_code
(self, code, request)
Save authorization_code for later use. Developers MUST implement it in subclass. Here is an example:: def save_authorization_code(self, code, request): client = request.client item = AuthorizationCode( code=code, client_id=client.client_id, redirect_uri=request.redirect_uri, scope=request.scope, user_id=request.user.id, ) item.save()
Save authorization_code for later use. Developers MUST implement it in subclass. Here is an example::
[ "Save", "authorization_code", "for", "later", "use", ".", "Developers", "MUST", "implement", "it", "in", "subclass", ".", "Here", "is", "an", "example", "::" ]
def save_authorization_code(self, code, request): """Save authorization_code for later use. Developers MUST implement it in subclass. Here is an example:: def save_authorization_code(self, code, request): client = request.client item = AuthorizationCode( code=code, client_id=client.client_id, redirect_uri=request.redirect_uri, scope=request.scope, user_id=request.user.id, ) item.save() """ raise NotImplementedError()
[ "def", "save_authorization_code", "(", "self", ",", "code", ",", "request", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/lepture/authlib/blob/2284f751a47474da7d127303e0d8f34d9046c310/authlib/oauth2/rfc6749/grants/authorization_code.py#L295-L310
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/urllib/request.py
python
Request.get_method
(self)
return getattr(self, 'method', default_method)
Return a string indicating the HTTP request method.
Return a string indicating the HTTP request method.
[ "Return", "a", "string", "indicating", "the", "HTTP", "request", "method", "." ]
def get_method(self): """Return a string indicating the HTTP request method.""" default_method = "POST" if self.data is not None else "GET" return getattr(self, 'method', default_method)
[ "def", "get_method", "(", "self", ")", ":", "default_method", "=", "\"POST\"", "if", "self", ".", "data", "is", "not", "None", "else", "\"GET\"", "return", "getattr", "(", "self", ",", "'method'", ",", "default_method", ")" ]
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/urllib/request.py#L382-L385
getting-things-gnome/gtg
4b02c43744b32a00facb98174f04ec5953bd055d
GTG/core/datastore.py
python
TaskSource.__init__
(self, requester, backend, datastore)
Instantiates a TaskSource object. @param requester: a Requester @param backend: the backend being wrapped @param datastore: a Datastore
Instantiates a TaskSource object.
[ "Instantiates", "a", "TaskSource", "object", "." ]
def __init__(self, requester, backend, datastore): """ Instantiates a TaskSource object. @param requester: a Requester @param backend: the backend being wrapped @param datastore: a Datastore """ self.backend = backend self.req = requester self.backend.register_datastore(datastore) self.tasktree = datastore.get_tasks_tree().get_main_view() self.to_set = deque() self.to_remove = deque() self.please_quit = False self.task_filter = self.get_task_filter_for_backend() if log.isEnabledFor(logging.DEBUG): self.timer_timestep = 5 else: self.timer_timestep = 1 self.add_task_handle = None self.set_task_handle = None self.remove_task_handle = None self.to_set_timer = None
[ "def", "__init__", "(", "self", ",", "requester", ",", "backend", ",", "datastore", ")", ":", "self", ".", "backend", "=", "backend", "self", ".", "req", "=", "requester", "self", ".", "backend", ".", "register_datastore", "(", "datastore", ")", "self", ...
https://github.com/getting-things-gnome/gtg/blob/4b02c43744b32a00facb98174f04ec5953bd055d/GTG/core/datastore.py#L666-L689
twisted/twisted
dee676b040dd38b847ea6fb112a712cb5e119490
src/twisted/trial/_dist/workerreporter.py
python
WorkerReporter._getFrames
(self, failure)
return frames
Extract frames from a C{Failure} instance.
Extract frames from a C{Failure} instance.
[ "Extract", "frames", "from", "a", "C", "{", "Failure", "}", "instance", "." ]
def _getFrames(self, failure): """ Extract frames from a C{Failure} instance. """ frames = [] for frame in failure.frames: frames.extend([frame[0], frame[1], str(frame[2])]) return frames
[ "def", "_getFrames", "(", "self", ",", "failure", ")", ":", "frames", "=", "[", "]", "for", "frame", "in", "failure", ".", "frames", ":", "frames", ".", "extend", "(", "[", "frame", "[", "0", "]", ",", "frame", "[", "1", "]", ",", "str", "(", "...
https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/trial/_dist/workerreporter.py#L46-L53
elastic/elasticsearch-py
6ef1adfa3c840a84afda7369cd8e43ae7dc45cdb
elasticsearch/_sync/client/transform.py
python
TransformClient.get_transform
( self, *, transform_id: Optional[Any] = None, allow_no_match: Optional[bool] = None, error_trace: Optional[bool] = None, exclude_generated: Optional[bool] = None, filter_path: Optional[Union[List[str], str]] = None, from_: Optional[int] = None, human: Optional[bool] = None, pretty: Optional[bool] = None, size: Optional[int] = None, )
return self._perform_request("GET", __target, headers=__headers)
Retrieves configuration information for transforms. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/get-transform.html>`_ :param transform_id: Identifier for the transform. It can be a transform identifier or a wildcard expression. You can get information for all transforms by using `_all`, by specifying `*` as the `<transform_id>`, or by omitting the `<transform_id>`. :param allow_no_match: Specifies what to do when the request: 1. Contains wildcard expressions and there are no transforms that match. 2. Contains the _all string or no identifiers and there are no matches. 3. Contains wildcard expressions and there are only partial matches. If this parameter is false, the request returns a 404 status code when there are no matches or only partial matches. :param exclude_generated: Excludes fields that were automatically added when creating the transform. This allows the configuration to be in an acceptable format to be retrieved and then added to another cluster. :param from_: Skips the specified number of transforms. :param size: Specifies the maximum number of transforms to obtain.
Retrieves configuration information for transforms.
[ "Retrieves", "configuration", "information", "for", "transforms", "." ]
def get_transform( self, *, transform_id: Optional[Any] = None, allow_no_match: Optional[bool] = None, error_trace: Optional[bool] = None, exclude_generated: Optional[bool] = None, filter_path: Optional[Union[List[str], str]] = None, from_: Optional[int] = None, human: Optional[bool] = None, pretty: Optional[bool] = None, size: Optional[int] = None, ) -> ObjectApiResponse[Any]: """ Retrieves configuration information for transforms. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/get-transform.html>`_ :param transform_id: Identifier for the transform. It can be a transform identifier or a wildcard expression. You can get information for all transforms by using `_all`, by specifying `*` as the `<transform_id>`, or by omitting the `<transform_id>`. :param allow_no_match: Specifies what to do when the request: 1. Contains wildcard expressions and there are no transforms that match. 2. Contains the _all string or no identifiers and there are no matches. 3. Contains wildcard expressions and there are only partial matches. If this parameter is false, the request returns a 404 status code when there are no matches or only partial matches. :param exclude_generated: Excludes fields that were automatically added when creating the transform. This allows the configuration to be in an acceptable format to be retrieved and then added to another cluster. :param from_: Skips the specified number of transforms. :param size: Specifies the maximum number of transforms to obtain. """ if transform_id not in SKIP_IN_PATH: __path = f"/_transform/{_quote(transform_id)}" else: __path = "/_transform" __query: Dict[str, Any] = {} if allow_no_match is not None: __query["allow_no_match"] = allow_no_match if error_trace is not None: __query["error_trace"] = error_trace if exclude_generated is not None: __query["exclude_generated"] = exclude_generated if filter_path is not None: __query["filter_path"] = filter_path if from_ is not None: __query["from"] = from_ if human is not None: __query["human"] = human if pretty is not None: __query["pretty"] = pretty if size is not None: __query["size"] = size if __query: __target = f"{__path}?{_quote_query(__query)}" else: __target = __path __headers = {"accept": "application/json"} return self._perform_request("GET", __target, headers=__headers)
[ "def", "get_transform", "(", "self", ",", "*", ",", "transform_id", ":", "Optional", "[", "Any", "]", "=", "None", ",", "allow_no_match", ":", "Optional", "[", "bool", "]", "=", "None", ",", "error_trace", ":", "Optional", "[", "bool", "]", "=", "None"...
https://github.com/elastic/elasticsearch-py/blob/6ef1adfa3c840a84afda7369cd8e43ae7dc45cdb/elasticsearch/_sync/client/transform.py#L77-L135
SickChill/SickChill
01020f3636d01535f60b83464d8127ea0efabfc7
sickchill/views/api/webapi.py
python
CMDShowGetQuality.run
(self)
return _responds(RESULT_SUCCESS, {"initial": any_qualities, "archive": best_qualities})
Get the quality setting of a show
Get the quality setting of a show
[ "Get", "the", "quality", "setting", "of", "a", "show" ]
def run(self): """Get the quality setting of a show""" show_obj = Show.find(settings.showList, int(self.indexerid)) if not show_obj: return _responds(RESULT_FAILURE, msg="Show not found") any_qualities, best_qualities = _map_quality(show_obj.quality) return _responds(RESULT_SUCCESS, {"initial": any_qualities, "archive": best_qualities})
[ "def", "run", "(", "self", ")", ":", "show_obj", "=", "Show", ".", "find", "(", "settings", ".", "showList", ",", "int", "(", "self", ".", "indexerid", ")", ")", "if", "not", "show_obj", ":", "return", "_responds", "(", "RESULT_FAILURE", ",", "msg", ...
https://github.com/SickChill/SickChill/blob/01020f3636d01535f60b83464d8127ea0efabfc7/sickchill/views/api/webapi.py#L2317-L2325
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/goodfet/GoodFETNRF.py
python
GoodFETNRF.RF_setfreq
(self,frequency)
Set the frequency in Hz.
Set the frequency in Hz.
[ "Set", "the", "frequency", "in", "Hz", "." ]
def RF_setfreq(self,frequency): """Set the frequency in Hz.""" #On the NRF24L01+, register 0x05 is the offset in #MHz above 2400. chan=frequency/1000000-2400; self.poke(0x05,chan);
[ "def", "RF_setfreq", "(", "self", ",", "frequency", ")", ":", "#On the NRF24L01+, register 0x05 is the offset in", "#MHz above 2400.", "chan", "=", "frequency", "/", "1000000", "-", "2400", "self", ".", "poke", "(", "0x05", ",", "chan", ")" ]
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/goodfet/GoodFETNRF.py#L95-L102
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/cherrypy/cherrypy/lib/caching.py
python
Cache.clear
(self)
Reset the cache to its initial, empty state.
Reset the cache to its initial, empty state.
[ "Reset", "the", "cache", "to", "its", "initial", "empty", "state", "." ]
def clear(self): """Reset the cache to its initial, empty state.""" raise NotImplemented
[ "def", "clear", "(", "self", ")", ":", "raise", "NotImplemented" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/cherrypy/cherrypy/lib/caching.py#L60-L62
NYUCCL/psiTurk
bad1e5c70ab2a0b7f04a1a86f166ed2f998b607d
psiturk/amt_services_wrapper.py
python
MTurkServicesWrapper._try_fetch_local_assignment
(self, try_this, with_psiturk_status=None)
Can accept either an assignment_id or the return of a mturk boto grab...
Can accept either an assignment_id or the return of a mturk boto grab...
[ "Can", "accept", "either", "an", "assignment_id", "or", "the", "return", "of", "a", "mturk", "boto", "grab", "..." ]
def _try_fetch_local_assignment(self, try_this, with_psiturk_status=None): """ Can accept either an assignment_id or the return of a mturk boto grab... """ query = Participant.query.order_by(Participant.beginhit.desc()) if with_psiturk_status: query = query.filter(Participant.status == with_psiturk_status) if isinstance(try_this, str): # then assume that it's an assignment_id assignment_id = try_this query = query.filter(Participant.assignmentid == assignment_id) elif isinstance(try_this, dict): # then assume that it's a return from mturk assignment = try_this assignment_id = assignment['assignmentId'] query = query.filter(Participant.workerid == assignment['workerId']) \ .filter(Participant.assignmentid == assignment_id) else: raise PsiturkException('Unrecognized `try_this` value-type: {}'.format(type(try_this))) local_assignment = query.first() if local_assignment: return local_assignment else: return try_this
[ "def", "_try_fetch_local_assignment", "(", "self", ",", "try_this", ",", "with_psiturk_status", "=", "None", ")", ":", "query", "=", "Participant", ".", "query", ".", "order_by", "(", "Participant", ".", "beginhit", ".", "desc", "(", ")", ")", "if", "with_ps...
https://github.com/NYUCCL/psiTurk/blob/bad1e5c70ab2a0b7f04a1a86f166ed2f998b607d/psiturk/amt_services_wrapper.py#L274-L299
wgrathwohl/JEM
3d01161547109b464eee87304f07b2dac8519d03
train_wrn_ebm.py
python
init_random
(args, bs)
return t.FloatTensor(bs, n_ch, im_sz, im_sz).uniform_(-1, 1)
[]
def init_random(args, bs): return t.FloatTensor(bs, n_ch, im_sz, im_sz).uniform_(-1, 1)
[ "def", "init_random", "(", "args", ",", "bs", ")", ":", "return", "t", ".", "FloatTensor", "(", "bs", ",", "n_ch", ",", "im_sz", ",", "im_sz", ")", ".", "uniform_", "(", "-", "1", ",", "1", ")" ]
https://github.com/wgrathwohl/JEM/blob/3d01161547109b464eee87304f07b2dac8519d03/train_wrn_ebm.py#L106-L107
gammapy/gammapy
735b25cd5bbed35e2004d633621896dcd5295e8b
gammapy/estimators/points/core.py
python
FluxPoints.read
( cls, filename, sed_type=None, format="gadf-sed", reference_model=None, **kwargs )
return cls.from_table( table=table, sed_type=sed_type, reference_model=reference_model, format=format, )
Read flux points. Parameters ---------- filename : str Filename sed_type : {"dnde", "flux", "eflux", "e2dnde", "likelihood"} Sed type format : {"gadf-sed", "lightcurve"} Format string. reference_model : `SpectralModel` Reference spectral model **kwargs : dict Keyword arguments passed to `astropy.table.Table.read`. Returns ------- flux_points : `FluxPoints` Flux points
Read flux points.
[ "Read", "flux", "points", "." ]
def read( cls, filename, sed_type=None, format="gadf-sed", reference_model=None, **kwargs ): """Read flux points. Parameters ---------- filename : str Filename sed_type : {"dnde", "flux", "eflux", "e2dnde", "likelihood"} Sed type format : {"gadf-sed", "lightcurve"} Format string. reference_model : `SpectralModel` Reference spectral model **kwargs : dict Keyword arguments passed to `astropy.table.Table.read`. Returns ------- flux_points : `FluxPoints` Flux points """ filename = make_path(filename) try: table = Table.read(filename, **kwargs) except IORegistryError: kwargs.setdefault("format", "ascii.ecsv") table = Table.read(filename, **kwargs) return cls.from_table( table=table, sed_type=sed_type, reference_model=reference_model, format=format, )
[ "def", "read", "(", "cls", ",", "filename", ",", "sed_type", "=", "None", ",", "format", "=", "\"gadf-sed\"", ",", "reference_model", "=", "None", ",", "*", "*", "kwargs", ")", ":", "filename", "=", "make_path", "(", "filename", ")", "try", ":", "table...
https://github.com/gammapy/gammapy/blob/735b25cd5bbed35e2004d633621896dcd5295e8b/gammapy/estimators/points/core.py#L108-L144
audreyfeldroy/complexity
710dc771b11c65fb65820cfb2a519dd749c65419
complexity/utils.py
python
make_sure_path_exists
(path)
return True
Ensures that a directory exists. :param path: A directory path.
Ensures that a directory exists.
[ "Ensures", "that", "a", "directory", "exists", "." ]
def make_sure_path_exists(path): """ Ensures that a directory exists. :param path: A directory path. """ try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: return False return True
[ "def", "make_sure_path_exists", "(", "path", ")", ":", "try", ":", "os", ".", "makedirs", "(", "path", ")", "except", "OSError", "as", "exception", ":", "if", "exception", ".", "errno", "!=", "errno", ".", "EEXIST", ":", "return", "False", "return", "Tru...
https://github.com/audreyfeldroy/complexity/blob/710dc771b11c65fb65820cfb2a519dd749c65419/complexity/utils.py#L23-L34
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
lib-python/3.5.1/_pydecimal.py
python
Decimal.is_canonical
(self)
return True
Return True if self is canonical; otherwise return False. Currently, the encoding of a Decimal instance is always canonical, so this method returns True for any Decimal.
Return True if self is canonical; otherwise return False.
[ "Return", "True", "if", "self", "is", "canonical", ";", "otherwise", "return", "False", "." ]
def is_canonical(self): """Return True if self is canonical; otherwise return False. Currently, the encoding of a Decimal instance is always canonical, so this method returns True for any Decimal. """ return True
[ "def", "is_canonical", "(", "self", ")", ":", "return", "True" ]
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/_pydecimal.py#L3099-L3105
CalebBell/thermo
572a47d1b03d49fe609b8d5f826fa6a7cde00828
thermo/eos_mix.py
python
IGMIX.d3delta_dninjnks
(self)
return self._zeros3d()
r'''Helper method for calculating the third partial mole number derivatives of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial^3 \delta}{\partial n_i \partial n_j \partial n_k } \right)_{T, P, n_{m \ne i,j,k}} = 0 Returns ------- d3delta_dninjnks : list[list[list[float]]] Third mole number derivative of `delta` of each component, [m^3/mol^4]
r'''Helper method for calculating the third partial mole number derivatives of `delta`. Note this is independent of the phase.
[ "r", "Helper", "method", "for", "calculating", "the", "third", "partial", "mole", "number", "derivatives", "of", "delta", ".", "Note", "this", "is", "independent", "of", "the", "phase", "." ]
def d3delta_dninjnks(self): r'''Helper method for calculating the third partial mole number derivatives of `delta`. Note this is independent of the phase. .. math:: \left(\frac{\partial^3 \delta}{\partial n_i \partial n_j \partial n_k } \right)_{T, P, n_{m \ne i,j,k}} = 0 Returns ------- d3delta_dninjnks : list[list[list[float]]] Third mole number derivative of `delta` of each component, [m^3/mol^4] ''' return self._zeros3d()
[ "def", "d3delta_dninjnks", "(", "self", ")", ":", "return", "self", ".", "_zeros3d", "(", ")" ]
https://github.com/CalebBell/thermo/blob/572a47d1b03d49fe609b8d5f826fa6a7cde00828/thermo/eos_mix.py#L6304-L6319
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/messaging/v1/usecase.py
python
UsecaseInstance.usecases
(self)
return self._properties['usecases']
:returns: Human readable Messaging Service Use Case details :rtype: list[dict]
:returns: Human readable Messaging Service Use Case details :rtype: list[dict]
[ ":", "returns", ":", "Human", "readable", "Messaging", "Service", "Use", "Case", "details", ":", "rtype", ":", "list", "[", "dict", "]" ]
def usecases(self): """ :returns: Human readable Messaging Service Use Case details :rtype: list[dict] """ return self._properties['usecases']
[ "def", "usecases", "(", "self", ")", ":", "return", "self", ".", "_properties", "[", "'usecases'", "]" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/messaging/v1/usecase.py#L116-L121
jkehler/awslambda-psycopg2
c7b1b2f6382bbe5893d95c4e7f4b5ffdf05ab3b4
psycopg2-3.8/extras.py
python
register_composite
(name, conn_or_curs, globally=False, factory=None)
return caster
Register a typecaster to convert a composite type into a tuple. :param name: the name of a PostgreSQL composite type, e.g. created using the |CREATE TYPE|_ command :param conn_or_curs: a connection or cursor used to find the type oid and components; the typecaster is registered in a scope limited to this object, unless *globally* is set to `!True` :param globally: if `!False` (default) register the typecaster only on *conn_or_curs*, otherwise register it globally :param factory: if specified it should be a `CompositeCaster` subclass: use it to :ref:`customize how to cast composite types <custom-composite>` :return: the registered `CompositeCaster` or *factory* instance responsible for the conversion
Register a typecaster to convert a composite type into a tuple.
[ "Register", "a", "typecaster", "to", "convert", "a", "composite", "type", "into", "a", "tuple", "." ]
def register_composite(name, conn_or_curs, globally=False, factory=None): """Register a typecaster to convert a composite type into a tuple. :param name: the name of a PostgreSQL composite type, e.g. created using the |CREATE TYPE|_ command :param conn_or_curs: a connection or cursor used to find the type oid and components; the typecaster is registered in a scope limited to this object, unless *globally* is set to `!True` :param globally: if `!False` (default) register the typecaster only on *conn_or_curs*, otherwise register it globally :param factory: if specified it should be a `CompositeCaster` subclass: use it to :ref:`customize how to cast composite types <custom-composite>` :return: the registered `CompositeCaster` or *factory* instance responsible for the conversion """ if factory is None: factory = CompositeCaster caster = factory._from_db(name, conn_or_curs) _ext.register_type(caster.typecaster, not globally and conn_or_curs or None) if caster.array_typecaster is not None: _ext.register_type( caster.array_typecaster, not globally and conn_or_curs or None) return caster
[ "def", "register_composite", "(", "name", ",", "conn_or_curs", ",", "globally", "=", "False", ",", "factory", "=", "None", ")", ":", "if", "factory", "is", "None", ":", "factory", "=", "CompositeCaster", "caster", "=", "factory", ".", "_from_db", "(", "nam...
https://github.com/jkehler/awslambda-psycopg2/blob/c7b1b2f6382bbe5893d95c4e7f4b5ffdf05ab3b4/psycopg2-3.8/extras.py#L1137-L1162
mattupstate/flask-security
674b18103fa8734aca71bbd084ea01e3709817ef
flask_security/datastore.py
python
UserDatastore.find_role
(self, *args, **kwargs)
Returns a role matching the provided name.
Returns a role matching the provided name.
[ "Returns", "a", "role", "matching", "the", "provided", "name", "." ]
def find_role(self, *args, **kwargs): """Returns a role matching the provided name.""" raise NotImplementedError
[ "def", "find_role", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError" ]
https://github.com/mattupstate/flask-security/blob/674b18103fa8734aca71bbd084ea01e3709817ef/flask_security/datastore.py#L144-L146
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/yaml/scanner.py
python
Scanner.scan_to_next_token
(self)
[]
def scan_to_next_token(self): # We ignore spaces, line breaks and comments. # If we find a line break in the block context, we set the flag # `allow_simple_key` on. # The byte order mark is stripped if it's the first character in the # stream. We do not yet support BOM inside the stream as the # specification requires. Any such mark will be considered as a part # of the document. # # TODO: We need to make tab handling rules more sane. A good rule is # Tabs cannot precede tokens # BLOCK-SEQUENCE-START, BLOCK-MAPPING-START, BLOCK-END, # KEY(block), VALUE(block), BLOCK-ENTRY # So the checking code is # if <TAB>: # self.allow_simple_keys = False # We also need to add the check for `allow_simple_keys == True` to # `unwind_indent` before issuing BLOCK-END. # Scanners for block, flow, and plain scalars need to be modified. if self.index == 0 and self.peek() == u'\uFEFF': self.forward() found = False while not found: while self.peek() == u' ': self.forward() if self.peek() == u'#': while self.peek() not in u'\0\r\n\x85\u2028\u2029': self.forward() if self.scan_line_break(): if not self.flow_level: self.allow_simple_key = True else: found = True
[ "def", "scan_to_next_token", "(", "self", ")", ":", "# We ignore spaces, line breaks and comments.", "# If we find a line break in the block context, we set the flag", "# `allow_simple_key` on.", "# The byte order mark is stripped if it's the first character in the", "# stream. We do not yet sup...
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/yaml/scanner.py#L753-L786
PyMVPA/PyMVPA
76c476b3de8264b0bb849bf226da5674d659564e
mvpa2/measures/winner.py
python
feature_loser_measure
()
return WinnerMeasure('features', partial(np.argmin, axis=1), 'lta_')
takes loser over features
takes loser over features
[ "takes", "loser", "over", "features" ]
def feature_loser_measure(): '''takes loser over features''' return WinnerMeasure('features', partial(np.argmin, axis=1), 'lta_')
[ "def", "feature_loser_measure", "(", ")", ":", "return", "WinnerMeasure", "(", "'features'", ",", "partial", "(", "np", ".", "argmin", ",", "axis", "=", "1", ")", ",", "'lta_'", ")" ]
https://github.com/PyMVPA/PyMVPA/blob/76c476b3de8264b0bb849bf226da5674d659564e/mvpa2/measures/winner.py#L135-L137
Antergos/Cnchi
13ac2209da9432d453e0097cf48a107640b563a9
src/pacman/pac.py
python
Pac.initialize_alpm
(self)
Set alpm setup
Set alpm setup
[ "Set", "alpm", "setup" ]
def initialize_alpm(self): """ Set alpm setup """ if self.config is not None: root_dir = self.config.options["RootDir"] db_path = self.config.options["DBPath"] else: root_dir = _DEFAULT_ROOT_DIR db_path = _DEFAULT_DB_PATH self.handle = pyalpm.Handle(root_dir, db_path) logging.debug( "ALPM initialised with root dir %s and db path %s", root_dir, db_path) if self.handle is None: raise pyalpm.error if self.config is not None: self.config.apply(self.handle) # Set callback functions # Callback used for logging self.handle.logcb = self.cb_log # Callback used to report download progress self.handle.dlcb = self.cb_dl # Callback used to report total download size self.handle.totaldlcb = self.cb_totaldl # Callback used for events self.handle.eventcb = self.cb_event # Callback used for questions self.handle.questioncb = self.cb_question # Callback used for operation progress self.handle.progresscb = self.cb_progress # Downloading callback self.handle.fetchcb = None
[ "def", "initialize_alpm", "(", "self", ")", ":", "if", "self", ".", "config", "is", "not", "None", ":", "root_dir", "=", "self", ".", "config", ".", "options", "[", "\"RootDir\"", "]", "db_path", "=", "self", ".", "config", ".", "options", "[", "\"DBPa...
https://github.com/Antergos/Cnchi/blob/13ac2209da9432d453e0097cf48a107640b563a9/src/pacman/pac.py#L122-L156
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/junos.py
python
install_config
(path=None, **kwargs)
Installs the given configuration file into the candidate configuration. Commits the changes if the commit checks or throws an error. path (required) Path where the configuration/template file is present. If the file has a ``.conf`` extension, the content is treated as text format. If the file has a ``.xml`` extension, the content is treated as XML format. If the file has a ``.set`` extension, the content is treated as Junos OS ``set`` commands. mode : exclusive The mode in which the configuration is locked. Can be one of ``private``, ``dynamic``, ``batch``, ``exclusive``, ``ephemeral`` dev_timeout : 30 Set NETCONF RPC timeout. Can be used for commands which take a while to execute. overwrite : False Set to ``True`` if you want this file is to completely replace the configuration file. Sets action to override .. note:: This option cannot be used if **format** is "set". replace : False Specify whether the configuration file uses ``replace:`` statements. If ``True``, only those statements under the ``replace`` tag will be changed. merge : False If set to ``True`` will set the load-config action to merge. the default load-config action is 'replace' for xml/json/text config format Determines the format of the contents update : False Compare a complete loaded configuration against the candidate configuration. For each hierarchy level or configuration object that is different in the two configurations, the version in the loaded configuration replaces the version in the candidate configuration. When the configuration is later committed, only system processes that are affected by the changed configuration elements parse the new configuration. This action is supported from PyEZ 2.1. comment Provide a comment for the commit confirm Provide time in minutes for commit confirmation. If this option is specified, the commit will be rolled back in the specified amount of time unless the commit is confirmed. diffs_file Path to the file where the diff (difference in old configuration and the committed configuration) will be stored. Note that the file will be stored on the proxy minion. To push the files to the master use: py:func:`cp.push <salt.modules.cp.push>`. template_vars Variables to be passed into the template processing engine in addition to those present in pillar, the minion configuration, grains, etc. You may reference these variables in your template like so: .. code-block:: jinja {{ template_vars["var_name"] }} CLI Examples: .. code-block:: bash salt 'device_name' junos.install_config 'salt://production/network/routers/config.set' salt 'device_name' junos.install_config 'salt://templates/replace_config.conf' replace=True comment='Committed via SaltStack' salt 'device_name' junos.install_config 'salt://my_new_configuration.conf' dev_timeout=300 diffs_file='/salt/confs/old_config.conf' overwrite=True salt 'device_name' junos.install_config 'salt://syslog_template.conf' template_vars='{"syslog_host": "10.180.222.7"}'
Installs the given configuration file into the candidate configuration. Commits the changes if the commit checks or throws an error.
[ "Installs", "the", "given", "configuration", "file", "into", "the", "candidate", "configuration", ".", "Commits", "the", "changes", "if", "the", "commit", "checks", "or", "throws", "an", "error", "." ]
def install_config(path=None, **kwargs): """ Installs the given configuration file into the candidate configuration. Commits the changes if the commit checks or throws an error. path (required) Path where the configuration/template file is present. If the file has a ``.conf`` extension, the content is treated as text format. If the file has a ``.xml`` extension, the content is treated as XML format. If the file has a ``.set`` extension, the content is treated as Junos OS ``set`` commands. mode : exclusive The mode in which the configuration is locked. Can be one of ``private``, ``dynamic``, ``batch``, ``exclusive``, ``ephemeral`` dev_timeout : 30 Set NETCONF RPC timeout. Can be used for commands which take a while to execute. overwrite : False Set to ``True`` if you want this file is to completely replace the configuration file. Sets action to override .. note:: This option cannot be used if **format** is "set". replace : False Specify whether the configuration file uses ``replace:`` statements. If ``True``, only those statements under the ``replace`` tag will be changed. merge : False If set to ``True`` will set the load-config action to merge. the default load-config action is 'replace' for xml/json/text config format Determines the format of the contents update : False Compare a complete loaded configuration against the candidate configuration. For each hierarchy level or configuration object that is different in the two configurations, the version in the loaded configuration replaces the version in the candidate configuration. When the configuration is later committed, only system processes that are affected by the changed configuration elements parse the new configuration. This action is supported from PyEZ 2.1. comment Provide a comment for the commit confirm Provide time in minutes for commit confirmation. If this option is specified, the commit will be rolled back in the specified amount of time unless the commit is confirmed. diffs_file Path to the file where the diff (difference in old configuration and the committed configuration) will be stored. Note that the file will be stored on the proxy minion. To push the files to the master use: py:func:`cp.push <salt.modules.cp.push>`. template_vars Variables to be passed into the template processing engine in addition to those present in pillar, the minion configuration, grains, etc. You may reference these variables in your template like so: .. code-block:: jinja {{ template_vars["var_name"] }} CLI Examples: .. code-block:: bash salt 'device_name' junos.install_config 'salt://production/network/routers/config.set' salt 'device_name' junos.install_config 'salt://templates/replace_config.conf' replace=True comment='Committed via SaltStack' salt 'device_name' junos.install_config 'salt://my_new_configuration.conf' dev_timeout=300 diffs_file='/salt/confs/old_config.conf' overwrite=True salt 'device_name' junos.install_config 'salt://syslog_template.conf' template_vars='{"syslog_host": "10.180.222.7"}' """ conn = __proxy__["junos.conn"]() ret = {} ret["out"] = True if path is None: ret[ "message" ] = "Please provide the salt path where the configuration is present" ret["out"] = False return ret op = {} if "__pub_arg" in kwargs: if kwargs["__pub_arg"]: if isinstance(kwargs["__pub_arg"][-1], dict): op.update(kwargs["__pub_arg"][-1]) else: op.update(kwargs) test = op.pop("test", False) kwargs = {} if "template_vars" in op: kwargs.update({"template_vars": op["template_vars"]}) with HandleFileCopy(path, **kwargs) as template_cached_path: if template_cached_path is None: ret["message"] = "Invalid file path." ret["out"] = False return ret if os.path.getsize(template_cached_path) == 0: ret["message"] = "Template failed to render" ret["out"] = False return ret write_diff = "" if "diffs_file" in op and op["diffs_file"] is not None: write_diff = op["diffs_file"] del op["diffs_file"] op["path"] = template_cached_path if "format" not in op: if path.endswith("set"): template_format = "set" elif path.endswith("xml"): template_format = "xml" elif path.endswith("json"): template_format = "json" else: template_format = "text" op["format"] = template_format if "replace" in op and op["replace"]: op["merge"] = False del op["replace"] elif "overwrite" in op and op["overwrite"]: op["overwrite"] = True elif "overwrite" in op and not op["overwrite"]: op["merge"] = True del op["overwrite"] db_mode = op.pop("mode", "exclusive") if write_diff and db_mode in ["dynamic", "ephemeral"]: ret[ "message" ] = "Write diff is not supported with dynamic/ephemeral configuration mode" ret["out"] = False return ret config_params = {} if "ephemeral_instance" in op: config_params["ephemeral_instance"] = op.pop("ephemeral_instance") try: with Config(conn, mode=db_mode, **config_params) as cu: try: cu.load(**op) except Exception as exception: # pylint: disable=broad-except ret[ "message" ] = 'Could not load configuration due to : "{}"'.format(exception) ret["format"] = op["format"] ret["out"] = False _restart_connection() return ret config_diff = None if db_mode in ["dynamic", "ephemeral"]: log.warning("diff is not supported for dynamic and ephemeral") else: config_diff = cu.diff() if config_diff is None: ret["message"] = "Configuration already applied!" ret["out"] = True return ret commit_params = {} if "confirm" in op: commit_params["confirm"] = op["confirm"] if "comment" in op: commit_params["comment"] = op["comment"] # Assume commit_check succeeds and initialize variable check check = True if db_mode in ["dynamic", "ephemeral"]: log.warning("commit check not supported for dynamic and ephemeral") else: try: check = cu.commit_check() except Exception as exception: # pylint: disable=broad-except ret[ "message" ] = 'Commit check threw the following exception: "{}"'.format( exception ) ret["out"] = False _restart_connection() return ret if check and not test: try: cu.commit(**commit_params) ret["message"] = "Successfully loaded and committed!" except Exception as exception: # pylint: disable=broad-except ret[ "message" ] = 'Commit check successful but commit failed with "{}"'.format( exception ) ret["out"] = False _restart_connection() return ret elif not check: try: cu.rollback() ret["message"] = ( "Loaded configuration but commit check failed, hence" " rolling back configuration." ) except Exception as exception: # pylint: disable=broad-except ret["message"] = ( "Loaded configuration but commit check failed, and" ' exception occurred during rolling back configuration "{}"'.format( exception ) ) _restart_connection() ret["out"] = False else: try: cu.rollback() ret["message"] = ( "Commit check passed, but skipping commit for dry-run and" " rolling back configuration." ) ret["out"] = True except Exception as exception: # pylint: disable=broad-except ret["message"] = ( "Commit check passed, but skipping commit for dry-run and" ' while rolling back configuration exception occurred "{}"'.format( exception ) ) ret["out"] = False _restart_connection() try: if write_diff and config_diff is not None: with salt.utils.files.fopen(write_diff, "w") as fp: fp.write(salt.utils.stringutils.to_str(config_diff)) except Exception as exception: # pylint: disable=broad-except ret[ "message" ] = "Could not write into diffs_file due to: '{}'".format(exception) ret["out"] = False except ValueError as ex: message = "install_config failed due to: {}".format(str(ex)) log.error(message) ret["message"] = message ret["out"] = False except LockError as ex: log.error("Configuration database is locked") ret["message"] = ex.message ret["out"] = False except RpcTimeoutError as ex: message = "install_config failed due to timeout error : {}".format(str(ex)) log.error(message) ret["message"] = message ret["out"] = False except Exception as exc: # pylint: disable=broad-except ret["message"] = "install_config failed due to exception: '{}'".format(exc) ret["out"] = False return ret
[ "def", "install_config", "(", "path", "=", "None", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "__proxy__", "[", "\"junos.conn\"", "]", "(", ")", "ret", "=", "{", "}", "ret", "[", "\"out\"", "]", "=", "True", "if", "path", "is", "None", ":", ...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/junos.py#L995-L1273
google/apis-client-generator
f09f0ba855c3845d315b811c6234fd3996f33172
src/googleapis/codegen/php_generator.py
python
PHPApi.ToClassName
(self, s, unused_element, element_type=None)
return utilities.CamelCase(s)
Convert a discovery name to a suitable PHP class name. Overrides the default. Args: s: (string) The wire format name of a class. unused_element: (object) The object we need a class name for. element_type: (string) The kind of object we need a class name for. Returns: A name suitable for use as a class in PHP.
Convert a discovery name to a suitable PHP class name.
[ "Convert", "a", "discovery", "name", "to", "a", "suitable", "PHP", "class", "name", "." ]
def ToClassName(self, s, unused_element, element_type=None): """Convert a discovery name to a suitable PHP class name. Overrides the default. Args: s: (string) The wire format name of a class. unused_element: (object) The object we need a class name for. element_type: (string) The kind of object we need a class name for. Returns: A name suitable for use as a class in PHP. """ if s.lower() in PhpLanguageModel.RESERVED_CLASS_NAMES: # Prepend the service name. return utilities.CamelCase(self.values['name']) + utilities.CamelCase(s) return utilities.CamelCase(s)
[ "def", "ToClassName", "(", "self", ",", "s", ",", "unused_element", ",", "element_type", "=", "None", ")", ":", "if", "s", ".", "lower", "(", ")", "in", "PhpLanguageModel", ".", "RESERVED_CLASS_NAMES", ":", "# Prepend the service name.", "return", "utilities", ...
https://github.com/google/apis-client-generator/blob/f09f0ba855c3845d315b811c6234fd3996f33172/src/googleapis/codegen/php_generator.py#L296-L311
google-research/motion_imitation
d0e7b963c5a301984352d25a3ee0820266fa4218
mpc_controller/foot_stepper.py
python
FootStepper.swing_foot
(self)
[]
def swing_foot(self): self.move_swing_foot = True
[ "def", "swing_foot", "(", "self", ")", ":", "self", ".", "move_swing_foot", "=", "True" ]
https://github.com/google-research/motion_imitation/blob/d0e7b963c5a301984352d25a3ee0820266fa4218/mpc_controller/foot_stepper.py#L78-L79
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/xml/dom/minidom.py
python
Element.setAttribute
(self, attname, value)
[]
def setAttribute(self, attname, value): attr = self.getAttributeNode(attname) if attr is None: attr = Attr(attname) attr.value = value # also sets nodeValue attr.ownerDocument = self.ownerDocument self.setAttributeNode(attr) elif value != attr.value: attr.value = value if attr.isId: _clear_id_cache(self)
[ "def", "setAttribute", "(", "self", ",", "attname", ",", "value", ")", ":", "attr", "=", "self", ".", "getAttributeNode", "(", "attname", ")", "if", "attr", "is", "None", ":", "attr", "=", "Attr", "(", "attname", ")", "attr", ".", "value", "=", "valu...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/xml/dom/minidom.py#L745-L755
lfz/Guided-Denoise
8881ab768d16eaf87342da4ff7dc8271e183e205
Attackset/Iter2_v3_resv2_inresv2_random/nets/alexnet.py
python
alexnet_v2
(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.5, spatial_squeeze=True, scope='alexnet_v2')
AlexNet version 2. Described in: http://arxiv.org/pdf/1404.5997v2.pdf Parameters from: github.com/akrizhevsky/cuda-convnet2/blob/master/layers/ layers-imagenet-1gpu.cfg Note: All the fully_connected layers have been transformed to conv2d layers. To use in classification mode, resize input to 224x224. To use in fully convolutional mode, set spatial_squeeze to false. The LRN layers have been removed and change the initializers from random_normal_initializer to xavier_initializer. Args: inputs: a tensor of size [batch_size, height, width, channels]. num_classes: number of predicted classes. is_training: whether or not the model is being trained. dropout_keep_prob: the probability that activations are kept in the dropout layers during training. spatial_squeeze: whether or not should squeeze the spatial dimensions of the outputs. Useful to remove unnecessary dimensions for classification. scope: Optional scope for the variables. Returns: the last op containing the log predictions and end_points dict.
AlexNet version 2.
[ "AlexNet", "version", "2", "." ]
def alexnet_v2(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.5, spatial_squeeze=True, scope='alexnet_v2'): """AlexNet version 2. Described in: http://arxiv.org/pdf/1404.5997v2.pdf Parameters from: github.com/akrizhevsky/cuda-convnet2/blob/master/layers/ layers-imagenet-1gpu.cfg Note: All the fully_connected layers have been transformed to conv2d layers. To use in classification mode, resize input to 224x224. To use in fully convolutional mode, set spatial_squeeze to false. The LRN layers have been removed and change the initializers from random_normal_initializer to xavier_initializer. Args: inputs: a tensor of size [batch_size, height, width, channels]. num_classes: number of predicted classes. is_training: whether or not the model is being trained. dropout_keep_prob: the probability that activations are kept in the dropout layers during training. spatial_squeeze: whether or not should squeeze the spatial dimensions of the outputs. Useful to remove unnecessary dimensions for classification. scope: Optional scope for the variables. Returns: the last op containing the log predictions and end_points dict. """ with tf.variable_scope(scope, 'alexnet_v2', [inputs]) as sc: end_points_collection = sc.name + '_end_points' # Collect outputs for conv2d, fully_connected and max_pool2d. with slim.arg_scope([slim.conv2d, slim.fully_connected, slim.max_pool2d], outputs_collections=[end_points_collection]): net = slim.conv2d(inputs, 64, [11, 11], 4, padding='VALID', scope='conv1') net = slim.max_pool2d(net, [3, 3], 2, scope='pool1') net = slim.conv2d(net, 192, [5, 5], scope='conv2') net = slim.max_pool2d(net, [3, 3], 2, scope='pool2') net = slim.conv2d(net, 384, [3, 3], scope='conv3') net = slim.conv2d(net, 384, [3, 3], scope='conv4') net = slim.conv2d(net, 256, [3, 3], scope='conv5') net = slim.max_pool2d(net, [3, 3], 2, scope='pool5') # Use conv2d instead of fully_connected layers. with slim.arg_scope([slim.conv2d], weights_initializer=trunc_normal(0.005), biases_initializer=tf.constant_initializer(0.1)): net = slim.conv2d(net, 4096, [5, 5], padding='VALID', scope='fc6') net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='dropout6') net = slim.conv2d(net, 4096, [1, 1], scope='fc7') net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='dropout7') net = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, biases_initializer=tf.zeros_initializer(), scope='fc8') # Convert end_points_collection into a end_point dict. end_points = slim.utils.convert_collection_to_dict(end_points_collection) if spatial_squeeze: net = tf.squeeze(net, [1, 2], name='fc8/squeezed') end_points[sc.name + '/fc8'] = net return net, end_points
[ "def", "alexnet_v2", "(", "inputs", ",", "num_classes", "=", "1000", ",", "is_training", "=", "True", ",", "dropout_keep_prob", "=", "0.5", ",", "spatial_squeeze", "=", "True", ",", "scope", "=", "'alexnet_v2'", ")", ":", "with", "tf", ".", "variable_scope",...
https://github.com/lfz/Guided-Denoise/blob/8881ab768d16eaf87342da4ff7dc8271e183e205/Attackset/Iter2_v3_resv2_inresv2_random/nets/alexnet.py#L55-L124
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/templates/IFRC/menus.py
python
S3MainMenu.menu_modules
(cls)
return [ homepage("gis")( ), homepage("hrm", "org", name=T("Staff"), #vars={"group": "staff"}, check=hrm)( vars={"group": "staff"})( MM("Staff", c="hrm", f="staff", m="summary"), MM("Teams", c="hrm", f="group"), MM("National Societies", c="org", f="organisation", vars = red_cross_filter), MM("Offices", c="org", f="office"), MM("Job Titles", c="hrm", f="job_title"), #MM("Skill List", c="hrm", f="skill"), MM("Training Events", c="hrm", f="training_event"), MM("Training Courses", c="hrm", f="course"), MM("Certificate List", c="hrm", f="certificate", check=use_certs), ), #homepage("vol", name=T("Volunteers"), check=vol)( homepage("vol", name=T("Volunteers"))( MM("Volunteers", c="vol", f="volunteer", m="summary"), MM("Teams", c="vol", f="group", check=vol_teams), MM("Volunteer Roles", c="vol", f="job_title", check=vol_roles), MM("Activities", c="vol", f="activity", check=vol_activities), MM("Programs", c="vol", f="programme", check=vol_programmes), #MM("Skill List", c="vol", f="skill"), MM("Training Events", c="vol", f="training_event"), MM("Training Courses", c="vol", f="course"), MM("Certificate List", c="vol", f="certificate", check=use_certs), ), homepage("member")( MM("Members", c="member", f="membership", m="summary"), ), #homepage("inv", "supply", check=inv)( homepage("inv", "supply")( #MM("Warehouses", c="inv", f="warehouse", m="summary", check=multi_warehouse), MM("Warehouses", c="inv", f="warehouse", m="summary"), #MM(inv_recv_list, c="inv", f="recv", check=multi_warehouse), MM(inv_recv_list, c="inv", f="recv"), #MM("Sent Shipments", c="inv", f="send", check=multi_warehouse), MM("Sent Shipments", c="inv", f="send"), #MM("Items", c="supply", f="item", check=basic_warehouse), MM("Items", c="supply", f="item"), #MM("Catalogs", c="supply", f="catalog", check=basic_warehouse), MM("Catalogs", c="supply", f="catalog"), ##MM("Item Categories", c="supply", f="item_category"), #M("Suppliers", c="inv", f="supplier", check=basic_warehouse)(), M("Suppliers", c="inv", f="supplier")(), #M("Facilities", c="inv", f="facility", check=basic_warehouse)(), M("Facilities", c="inv", f="facility")(), M("Requests", c="inv", f="req")(), ##M("Commitments", c="inv", f="commit")(), ), homepage("asset")( MM("Assets", c="asset", f="asset", m="summary"), MM("Items", c="asset", f="item", m="summary"), ), homepage("survey")( MM("Assessment Templates", c="survey", f="template"), MM("Disaster Assessments", c="survey", f="series"), ), homepage("project")( MM("Projects", c="project", f="project", m="summary"), MM("Communities", c="project", f="location"), MM("Outreach", c="po", f="index", check=outreach), ), homepage("vulnerability")( MM("Map", c="vulnerability", f="index"), ), homepage("event")( MM("Events", c="event", f="event", m="summary"), MM("Incident Reports", c="event", f="incident_report", m="summary"), ), homepage("deploy", name="Surge", f="mission", m="summary", vars={"~.status__belongs": "2"})( MM("InBox", c="deploy", f="email_inbox"), MM("Missions", c="deploy", f="mission", m="summary"), MM("Members", c="deploy", f="human_resource", m="summary"), ), ]
Custom Modules Menu
Custom Modules Menu
[ "Custom", "Modules", "Menu" ]
def menu_modules(cls): """ Custom Modules Menu """ system_roles = current.session.s3.system_roles ADMIN = system_roles.ADMIN T = current.T auth = current.auth has_role = auth.s3_has_role s3db = current.s3db if not has_role(ADMIN): if auth.s3_has_roles(("EVENT_MONITOR", "EVENT_ORGANISER", "EVENT_OFFICE_MANAGER")): # Simplified menu for Bangkok CCST return [homepage("hrm", "org", name=T("Training Events"), f="training_event", #vars={"group": "staff"}, check=hrm)( vars={"group": "staff"})( #MM("Training Events", c="hrm", f="training_event"), #MM("Trainings", c="hrm", f="training"), #MM("Training Courses", c="hrm", f="course"), ), ] elif not has_role("RDRT_ADMIN") and has_role("RDRT_MEMBER"): # Simplified menu for AP RDRT return [] settings = current.deployment_settings root_org = auth.root_org_name() ORG_ADMIN = system_roles.ORG_ADMIN s3db.inv_recv_crud_strings() inv_recv_list = current.response.s3.crud_strings.inv_recv.title_list vol_activities = lambda i: True if root_org == CRMADA else False use_certs = lambda i: settings.get_hrm_use_certificates() vol_programmes = lambda i: settings.get_hrm_vol_experience() in ("programme", "both") #def hrm(item): # return root_org != HNRC or \ # has_role(ORG_ADMIN) #def inv(item): # return root_org != HNRC or \ # has_role("hn_wh_manager") or \ # has_role("hn_national_wh_manager") or \ # has_role(ORG_ADMIN) #def basic_warehouse(i): # if root_org == HNRC and \ # not (has_role("hn_national_wh_manager") or \ # has_role(ORG_ADMIN)): # # Hide menu entries which user shouldn't need access to # return False # else: # return True #def multi_warehouse(i): # if root_org == HNRC and \ # not (has_role("hn_national_wh_manager") or \ # has_role(ORG_ADMIN)): # # Only responsible for 1 warehouse so hide menu entries which should be accessed via Tabs on their warehouse # return False # else: # return True def outreach(item): return root_org == NZRC or \ root_org is None and has_role(ADMIN) #def rdrt_admin(item): # return has_role("RDRT_ADMIN") #def vol(item): # return root_org != HNRC or \ # has_role(ORG_ADMIN) def vol_roles(item): return root_org != IRCS def vol_teams(item): return root_org != IRCS return [ homepage("gis")( ), homepage("hrm", "org", name=T("Staff"), #vars={"group": "staff"}, check=hrm)( vars={"group": "staff"})( MM("Staff", c="hrm", f="staff", m="summary"), MM("Teams", c="hrm", f="group"), MM("National Societies", c="org", f="organisation", vars = red_cross_filter), MM("Offices", c="org", f="office"), MM("Job Titles", c="hrm", f="job_title"), #MM("Skill List", c="hrm", f="skill"), MM("Training Events", c="hrm", f="training_event"), MM("Training Courses", c="hrm", f="course"), MM("Certificate List", c="hrm", f="certificate", check=use_certs), ), #homepage("vol", name=T("Volunteers"), check=vol)( homepage("vol", name=T("Volunteers"))( MM("Volunteers", c="vol", f="volunteer", m="summary"), MM("Teams", c="vol", f="group", check=vol_teams), MM("Volunteer Roles", c="vol", f="job_title", check=vol_roles), MM("Activities", c="vol", f="activity", check=vol_activities), MM("Programs", c="vol", f="programme", check=vol_programmes), #MM("Skill List", c="vol", f="skill"), MM("Training Events", c="vol", f="training_event"), MM("Training Courses", c="vol", f="course"), MM("Certificate List", c="vol", f="certificate", check=use_certs), ), homepage("member")( MM("Members", c="member", f="membership", m="summary"), ), #homepage("inv", "supply", check=inv)( homepage("inv", "supply")( #MM("Warehouses", c="inv", f="warehouse", m="summary", check=multi_warehouse), MM("Warehouses", c="inv", f="warehouse", m="summary"), #MM(inv_recv_list, c="inv", f="recv", check=multi_warehouse), MM(inv_recv_list, c="inv", f="recv"), #MM("Sent Shipments", c="inv", f="send", check=multi_warehouse), MM("Sent Shipments", c="inv", f="send"), #MM("Items", c="supply", f="item", check=basic_warehouse), MM("Items", c="supply", f="item"), #MM("Catalogs", c="supply", f="catalog", check=basic_warehouse), MM("Catalogs", c="supply", f="catalog"), ##MM("Item Categories", c="supply", f="item_category"), #M("Suppliers", c="inv", f="supplier", check=basic_warehouse)(), M("Suppliers", c="inv", f="supplier")(), #M("Facilities", c="inv", f="facility", check=basic_warehouse)(), M("Facilities", c="inv", f="facility")(), M("Requests", c="inv", f="req")(), ##M("Commitments", c="inv", f="commit")(), ), homepage("asset")( MM("Assets", c="asset", f="asset", m="summary"), MM("Items", c="asset", f="item", m="summary"), ), homepage("survey")( MM("Assessment Templates", c="survey", f="template"), MM("Disaster Assessments", c="survey", f="series"), ), homepage("project")( MM("Projects", c="project", f="project", m="summary"), MM("Communities", c="project", f="location"), MM("Outreach", c="po", f="index", check=outreach), ), homepage("vulnerability")( MM("Map", c="vulnerability", f="index"), ), homepage("event")( MM("Events", c="event", f="event", m="summary"), MM("Incident Reports", c="event", f="incident_report", m="summary"), ), homepage("deploy", name="Surge", f="mission", m="summary", vars={"~.status__belongs": "2"})( MM("InBox", c="deploy", f="email_inbox"), MM("Missions", c="deploy", f="mission", m="summary"), MM("Members", c="deploy", f="human_resource", m="summary"), ), ]
[ "def", "menu_modules", "(", "cls", ")", ":", "system_roles", "=", "current", ".", "session", ".", "s3", ".", "system_roles", "ADMIN", "=", "system_roles", ".", "ADMIN", "T", "=", "current", ".", "T", "auth", "=", "current", ".", "auth", "has_role", "=", ...
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/templates/IFRC/menus.py#L43-L206
frescobaldi/frescobaldi
301cc977fc4ba7caa3df9e4bf905212ad5d06912
frescobaldi_app/actioncollectionmanager.py
python
ActionCollectionManager.action
(self, collection_name, action_name)
Returns the named action from the named collection.
Returns the named action from the named collection.
[ "Returns", "the", "named", "action", "from", "the", "named", "collection", "." ]
def action(self, collection_name, action_name): """Returns the named action from the named collection.""" collection = self._actioncollections.get(collection_name) if collection: if isinstance(collection, actioncollection.ShortcutCollection): return collection.realAction(action_name) return getattr(collection, action_name, None)
[ "def", "action", "(", "self", ",", "collection_name", ",", "action_name", ")", ":", "collection", "=", "self", ".", "_actioncollections", ".", "get", "(", "collection_name", ")", "if", "collection", ":", "if", "isinstance", "(", "collection", ",", "actioncolle...
https://github.com/frescobaldi/frescobaldi/blob/301cc977fc4ba7caa3df9e4bf905212ad5d06912/frescobaldi_app/actioncollectionmanager.py#L75-L81
archlinux/archweb
19e5da892ef2af7bf045576f8114c256589e16c4
todolists/utils.py
python
attach_staging
(packages, list_id)
return annotated
Look for any staging version of the packages provided and attach them to the 'staging' attribute on each package if found.
Look for any staging version of the packages provided and attach them to the 'staging' attribute on each package if found.
[ "Look", "for", "any", "staging", "version", "of", "the", "packages", "provided", "and", "attach", "them", "to", "the", "staging", "attribute", "on", "each", "package", "if", "found", "." ]
def attach_staging(packages, list_id): '''Look for any staging version of the packages provided and attach them to the 'staging' attribute on each package if found.''' pkgnames = TodolistPackage.objects.filter( todolist_id=list_id).values('pkgname') staging_pkgs = Package.objects.normal().filter(repo__staging=True, pkgname__in=pkgnames) # now build a lookup dict to attach to the correct package lookup = {(p.pkgname, p.arch): p for p in staging_pkgs} annotated = [] for package in packages: in_staging = lookup.get((package.pkgname, package.arch), None) package.staging = in_staging return annotated
[ "def", "attach_staging", "(", "packages", ",", "list_id", ")", ":", "pkgnames", "=", "TodolistPackage", ".", "objects", ".", "filter", "(", "todolist_id", "=", "list_id", ")", ".", "values", "(", "'pkgname'", ")", "staging_pkgs", "=", "Package", ".", "object...
https://github.com/archlinux/archweb/blob/19e5da892ef2af7bf045576f8114c256589e16c4/todolists/utils.py#L41-L56
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
lms/djangoapps/instructor/views/instructor_dashboard.py
python
is_ecommerce_course
(course_key)
return sku_count > 0
Checks if the given course is an e-commerce course or not, by checking its SKU value from CourseMode records for the course
Checks if the given course is an e-commerce course or not, by checking its SKU value from CourseMode records for the course
[ "Checks", "if", "the", "given", "course", "is", "an", "e", "-", "commerce", "course", "or", "not", "by", "checking", "its", "SKU", "value", "from", "CourseMode", "records", "for", "the", "course" ]
def is_ecommerce_course(course_key): """ Checks if the given course is an e-commerce course or not, by checking its SKU value from CourseMode records for the course """ sku_count = len([mode.sku for mode in CourseMode.modes_for_course(course_key) if mode.sku]) return sku_count > 0
[ "def", "is_ecommerce_course", "(", "course_key", ")", ":", "sku_count", "=", "len", "(", "[", "mode", ".", "sku", "for", "mode", "in", "CourseMode", ".", "modes_for_course", "(", "course_key", ")", "if", "mode", ".", "sku", "]", ")", "return", "sku_count",...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/lms/djangoapps/instructor/views/instructor_dashboard.py#L775-L781
googleads/googleads-python-lib
b3b42a6deedbe6eaa1c9b30183a9eae3f9e9a7ee
examples/adwords/v201809/advanced_operations/add_ad_customizer.py
python
CreateCustomizerFeed
(client, feed_name)
Creates a new AdCustomizerFeed. Args: client: an AdWordsClient instance. feed_name: the name for the new AdCustomizerFeed. Returns: The new AdCustomizerFeed.
Creates a new AdCustomizerFeed.
[ "Creates", "a", "new", "AdCustomizerFeed", "." ]
def CreateCustomizerFeed(client, feed_name): """Creates a new AdCustomizerFeed. Args: client: an AdWordsClient instance. feed_name: the name for the new AdCustomizerFeed. Returns: The new AdCustomizerFeed. """ # Get the AdCustomizerFeedService ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', 'v201809') customizer_feed = { 'feedName': feed_name, 'feedAttributes': [ {'type': 'STRING', 'name': 'Name'}, {'type': 'STRING', 'name': 'Price'}, {'type': 'DATE_TIME', 'name': 'Date'} ] } feed_service_operation = { 'operator': 'ADD', 'operand': customizer_feed } response = ad_customizer_feed_service.mutate([feed_service_operation]) if response and 'value' in response: feed = response['value'][0] feed_data = { 'feedId': feed['feedId'], 'nameId': feed['feedAttributes'][0]['id'], 'priceId': feed['feedAttributes'][1]['id'], 'dateId': feed['feedAttributes'][2]['id'] } print('Feed with name "%s" and ID %s was added with:\n' '\tName attribute ID %s and price attribute ID %s and date attribute' 'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'], feed_data['priceId'], feed_data['dateId']) return feed else: raise errors.GoogleAdsError('No feeds were added')
[ "def", "CreateCustomizerFeed", "(", "client", ",", "feed_name", ")", ":", "# Get the AdCustomizerFeedService", "ad_customizer_feed_service", "=", "client", ".", "GetService", "(", "'AdCustomizerFeedService'", ",", "'v201809'", ")", "customizer_feed", "=", "{", "'feedName'...
https://github.com/googleads/googleads-python-lib/blob/b3b42a6deedbe6eaa1c9b30183a9eae3f9e9a7ee/examples/adwords/v201809/advanced_operations/add_ad_customizer.py#L82-L125
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/pkg_resources/_vendor/packaging/version.py
python
LegacyVersion.local
(self)
return None
[]
def local(self): return None
[ "def", "local", "(", "self", ")", ":", "return", "None" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pkg_resources/_vendor/packaging/version.py#L93-L94
ulfalizer/Kconfiglib
061e71f7d78cb057762d88de088055361863deff
kconfiglib.py
python
Kconfig.unset_values
(self)
Removes any user values from all symbols, as if Kconfig.load_config() or Symbol.set_value() had never been called.
Removes any user values from all symbols, as if Kconfig.load_config() or Symbol.set_value() had never been called.
[ "Removes", "any", "user", "values", "from", "all", "symbols", "as", "if", "Kconfig", ".", "load_config", "()", "or", "Symbol", ".", "set_value", "()", "had", "never", "been", "called", "." ]
def unset_values(self): """ Removes any user values from all symbols, as if Kconfig.load_config() or Symbol.set_value() had never been called. """ self._warn_assign_no_prompt = False try: # set_value() already rejects undefined symbols, and they don't # need to be invalidated (because their value never changes), so we # can just iterate over defined symbols for sym in self.unique_defined_syms: sym.unset_value() for choice in self.unique_choices: choice.unset_value() finally: self._warn_assign_no_prompt = True
[ "def", "unset_values", "(", "self", ")", ":", "self", ".", "_warn_assign_no_prompt", "=", "False", "try", ":", "# set_value() already rejects undefined symbols, and they don't", "# need to be invalidated (because their value never changes), so we", "# can just iterate over defined symb...
https://github.com/ulfalizer/Kconfiglib/blob/061e71f7d78cb057762d88de088055361863deff/kconfiglib.py#L1990-L2006
ucfopen/canvasapi
3f1a71e23c86a49dbaa6e84f6c0e81c297b86e36
canvasapi/user.py
python
User.get_content_export
(self, content_export, **kwargs)
return ContentExport(self._requester, response.json())
Return information about a single content export. :calls: `GET /api/v1/users/:user_id/content_exports/:id\ <https://canvas.instructure.com/doc/api/content_exports.html#method.content_exports_api.show>`_ :param content_export: The object or ID of the content export to show. :type content_export: int or :class:`canvasapi.content_export.ContentExport` :rtype: :class:`canvasapi.content_export.ContentExport`
Return information about a single content export.
[ "Return", "information", "about", "a", "single", "content", "export", "." ]
def get_content_export(self, content_export, **kwargs): """ Return information about a single content export. :calls: `GET /api/v1/users/:user_id/content_exports/:id\ <https://canvas.instructure.com/doc/api/content_exports.html#method.content_exports_api.show>`_ :param content_export: The object or ID of the content export to show. :type content_export: int or :class:`canvasapi.content_export.ContentExport` :rtype: :class:`canvasapi.content_export.ContentExport` """ from canvasapi.content_export import ContentExport export_id = obj_or_id(content_export, "content_export", (ContentExport,)) response = self._requester.request( "GET", "users/{}/content_exports/{}".format(self.id, export_id), _kwargs=combine_kwargs(**kwargs), ) return ContentExport(self._requester, response.json())
[ "def", "get_content_export", "(", "self", ",", "content_export", ",", "*", "*", "kwargs", ")", ":", "from", "canvasapi", ".", "content_export", "import", "ContentExport", "export_id", "=", "obj_or_id", "(", "content_export", ",", "\"content_export\"", ",", "(", ...
https://github.com/ucfopen/canvasapi/blob/3f1a71e23c86a49dbaa6e84f6c0e81c297b86e36/canvasapi/user.py#L339-L361
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/api/v2010/account/usage/record/this_month.py
python
ThisMonthInstance.price
(self)
return self._properties['price']
:returns: The total price of the usage :rtype: unicode
:returns: The total price of the usage :rtype: unicode
[ ":", "returns", ":", "The", "total", "price", "of", "the", "usage", ":", "rtype", ":", "unicode" ]
def price(self): """ :returns: The total price of the usage :rtype: unicode """ return self._properties['price']
[ "def", "price", "(", "self", ")", ":", "return", "self", ".", "_properties", "[", "'price'", "]" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/api/v2010/account/usage/record/this_month.py#L541-L546
Cog-Creators/Red-DiscordBot
b05933274a11fb097873ab0d1b246d37b06aa306
redbot/cogs/downloader/repo_manager.py
python
RepoManager.delete_repo
(self, name: str)
Delete a repository and its folders. Parameters ---------- name : str The name of the repository to delete. Raises ------ .MissingGitRepo If the repo does not exist.
Delete a repository and its folders.
[ "Delete", "a", "repository", "and", "its", "folders", "." ]
async def delete_repo(self, name: str) -> None: """Delete a repository and its folders. Parameters ---------- name : str The name of the repository to delete. Raises ------ .MissingGitRepo If the repo does not exist. """ repo = self.get_repo(name) if repo is None: raise errors.MissingGitRepo(f"There is no repo with the name {name}") safe_delete(repo.folder_path) await self.config.repos.clear_raw(repo.name) try: del self._repos[name] except KeyError: pass
[ "async", "def", "delete_repo", "(", "self", ",", "name", ":", "str", ")", "->", "None", ":", "repo", "=", "self", ".", "get_repo", "(", "name", ")", "if", "repo", "is", "None", ":", "raise", "errors", ".", "MissingGitRepo", "(", "f\"There is no repo with...
https://github.com/Cog-Creators/Red-DiscordBot/blob/b05933274a11fb097873ab0d1b246d37b06aa306/redbot/cogs/downloader/repo_manager.py#L1118-L1142
serge-sans-paille/pythran
f9f73aa5a965adc4ebcb91a439784dbe9ef911fa
pythran/types/type_dependencies.py
python
TypeDependencies.visit_Assign
(self, node)
In case of assignment assign value depend on r-value type dependencies. It is valid for subscript, `a[i] = foo()` means `a` type depend on `foo` return type.
In case of assignment assign value depend on r-value type dependencies.
[ "In", "case", "of", "assignment", "assign", "value", "depend", "on", "r", "-", "value", "type", "dependencies", "." ]
def visit_Assign(self, node): """ In case of assignment assign value depend on r-value type dependencies. It is valid for subscript, `a[i] = foo()` means `a` type depend on `foo` return type. """ value_deps = self.visit(node.value) for target in node.targets: name = get_variable(target) if isinstance(name, ast.Name): self.naming[name.id] = value_deps
[ "def", "visit_Assign", "(", "self", ",", "node", ")", ":", "value_deps", "=", "self", ".", "visit", "(", "node", ".", "value", ")", "for", "target", "in", "node", ".", "targets", ":", "name", "=", "get_variable", "(", "target", ")", "if", "isinstance",...
https://github.com/serge-sans-paille/pythran/blob/f9f73aa5a965adc4ebcb91a439784dbe9ef911fa/pythran/types/type_dependencies.py#L330-L341
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/ipaddress.py
python
_count_righthand_zero_bits
(number, bits)
return min(bits, _compat_bit_length(~number & (number - 1)))
Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number.
Count the number of zero bits on the right hand side.
[ "Count", "the", "number", "of", "zero", "bits", "on", "the", "right", "hand", "side", "." ]
def _count_righthand_zero_bits(number, bits): """Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number. """ if number == 0: return bits return min(bits, _compat_bit_length(~number & (number - 1)))
[ "def", "_count_righthand_zero_bits", "(", "number", ",", "bits", ")", ":", "if", "number", "==", "0", ":", "return", "bits", "return", "min", "(", "bits", ",", "_compat_bit_length", "(", "~", "number", "&", "(", "number", "-", "1", ")", ")", ")" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/ipaddress.py#L306-L319
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/apscheduler/jobstores/base.py
python
BaseJobStore.lookup_job
(self, job_id)
Returns a specific job, or ``None`` if it isn't found.. The job store is responsible for setting the ``scheduler`` and ``jobstore`` attributes of the returned job to point to the scheduler and itself, respectively. :param str|unicode job_id: identifier of the job :rtype: Job
Returns a specific job, or ``None`` if it isn't found..
[ "Returns", "a", "specific", "job", "or", "None", "if", "it", "isn", "t", "found", ".." ]
def lookup_job(self, job_id): """ Returns a specific job, or ``None`` if it isn't found.. The job store is responsible for setting the ``scheduler`` and ``jobstore`` attributes of the returned job to point to the scheduler and itself, respectively. :param str|unicode job_id: identifier of the job :rtype: Job """
[ "def", "lookup_job", "(", "self", ",", "job_id", ")", ":" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/apscheduler/jobstores/base.py#L68-L77
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/api/core_v1_api.py
python
CoreV1Api.create_namespaced_event
(self, namespace, body, **kwargs)
return self.create_namespaced_event_with_http_info(namespace, body, **kwargs)
create_namespaced_event # noqa: E501 create an Event # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_event(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param CoreV1Event body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: CoreV1Event If the method is called asynchronously, returns the request thread.
create_namespaced_event # noqa: E501
[ "create_namespaced_event", "#", "noqa", ":", "E501" ]
def create_namespaced_event(self, namespace, body, **kwargs): # noqa: E501 """create_namespaced_event # noqa: E501 create an Event # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_event(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param CoreV1Event body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: CoreV1Event If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.create_namespaced_event_with_http_info(namespace, body, **kwargs)
[ "def", "create_namespaced_event", "(", "self", ",", "namespace", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "return", "self", ".", "create_namespaced_event_with_http_info", "(", "nam...
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/api/core_v1_api.py#L6879-L6906
google/youtube-8m
e6f6bf682d20bb21904ea9c081c15e070809d914
readers.py
python
YT8MAggregatedFeatureReader.__init__
( # pylint: disable=dangerous-default-value self, num_classes=3862, feature_sizes=[1024, 128], feature_names=["mean_rgb", "mean_audio"])
Construct a YT8MAggregatedFeatureReader. Args: num_classes: a positive integer for the number of classes. feature_sizes: positive integer(s) for the feature dimensions as a list. feature_names: the feature name(s) in the tensorflow record as a list.
Construct a YT8MAggregatedFeatureReader.
[ "Construct", "a", "YT8MAggregatedFeatureReader", "." ]
def __init__( # pylint: disable=dangerous-default-value self, num_classes=3862, feature_sizes=[1024, 128], feature_names=["mean_rgb", "mean_audio"]): """Construct a YT8MAggregatedFeatureReader. Args: num_classes: a positive integer for the number of classes. feature_sizes: positive integer(s) for the feature dimensions as a list. feature_names: the feature name(s) in the tensorflow record as a list. """ assert len(feature_names) == len(feature_sizes), ( "length of feature_names (={}) != length of feature_sizes (={})".format( len(feature_names), len(feature_sizes))) self.num_classes = num_classes self.feature_sizes = feature_sizes self.feature_names = feature_names
[ "def", "__init__", "(", "# pylint: disable=dangerous-default-value", "self", ",", "num_classes", "=", "3862", ",", "feature_sizes", "=", "[", "1024", ",", "128", "]", ",", "feature_names", "=", "[", "\"mean_rgb\"", ",", "\"mean_audio\"", "]", ")", ":", "assert",...
https://github.com/google/youtube-8m/blob/e6f6bf682d20bb21904ea9c081c15e070809d914/readers.py#L74-L93
CGCookie/retopoflow
3d8b3a47d1d661f99ab0aeb21d31370bf15de35e
addon_common/common/maths.py
python
Size2D.get_width_midmaxmin
(self)
return self._min_width
[]
def get_width_midmaxmin(self): if self._width is not None: return self._width if self._max_width is not None: return self._max_width return self._min_width
[ "def", "get_width_midmaxmin", "(", "self", ")", ":", "if", "self", ".", "_width", "is", "not", "None", ":", "return", "self", ".", "_width", "if", "self", ".", "_max_width", "is", "not", "None", ":", "return", "self", ".", "_max_width", "return", "self",...
https://github.com/CGCookie/retopoflow/blob/3d8b3a47d1d661f99ab0aeb21d31370bf15de35e/addon_common/common/maths.py#L1349-L1352
megvii-model/CrowdDetection
446f8e688fde679e04c35bd1aa1d4d491646f2eb
model/emd_refine/inference.py
python
inference
(args)
[]
def inference(args): @jit.trace(symbolic=False) def val_func(): pred_boxes = net(net.inputs) return pred_boxes # model path model_file = args.resume_weights assert os.path.exists(model_file) # load model net = network.Network() net.eval() check_point = mge.load(model_file) net.load_state_dict(check_point['state_dict']) ori_image, image, im_info = get_data(args.img_path) net.inputs["image"].set_value(image.astype(np.float32)) net.inputs["im_info"].set_value(im_info) pred_boxes = val_func().numpy() num_tag = config.num_classes - 1 target_shape = (pred_boxes.shape[0]//num_tag//top_k, top_k) pred_tags = (np.arange(num_tag) + 1).reshape(-1,1) pred_tags = np.tile(pred_tags, target_shape).reshape(-1,1) # nms if if_set_nms: from set_nms_utils import set_cpu_nms n = pred_boxes.shape[0] // top_k idents = np.tile(np.arange(n)[:,None], (1, top_k)).reshape(-1, 1) pred_boxes = np.hstack((pred_boxes, idents)) keep = pred_boxes[:, -2] > args.thresh pred_boxes = pred_boxes[keep] pred_tags = pred_tags[keep] keep = set_cpu_nms(pred_boxes, 0.5) pred_boxes = pred_boxes[keep][:, :-1] pred_tags = pred_tags[keep] else: from set_nms_utils import cpu_nms keep = pred_boxes[:, -1] > args.thresh pred_boxes = pred_boxes[keep] pred_tags = pred_tags[keep] keep = cpu_nms(pred_boxes, 0.5) pred_boxes = pred_boxes[keep] pred_tags = pred_tags[keep] pred_tags = pred_tags.astype(np.int32).flatten() pred_tags_name = np.array(config.class_names)[pred_tags] visual_utils.draw_boxes(ori_image, pred_boxes[:, :-1], pred_boxes[:, -1], pred_tags_name) name = args.img_path.split('/')[-1].split('.')[-2] fpath = 'result.jpg' cv2.imwrite(fpath, ori_image)
[ "def", "inference", "(", "args", ")", ":", "@", "jit", ".", "trace", "(", "symbolic", "=", "False", ")", "def", "val_func", "(", ")", ":", "pred_boxes", "=", "net", "(", "net", ".", "inputs", ")", "return", "pred_boxes", "# model path", "model_file", "...
https://github.com/megvii-model/CrowdDetection/blob/446f8e688fde679e04c35bd1aa1d4d491646f2eb/model/emd_refine/inference.py#L19-L65
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/matplotlib/axes/_base.py
python
_AxesBase.set_prop_cycle
(self, *args, **kwargs)
Set the property cycle of the Axes. The property cycle controls the style properties such as color, marker and linestyle of future plot commands. The style properties of data already added to the Axes are not modified. Call signatures:: set_prop_cycle(cycler) set_prop_cycle(label=values[, label2=values2[, ...]]) set_prop_cycle(label, values) Form 1 sets given `~cycler.Cycler` object. Form 2 creates a `~cycler.Cycler` which cycles over one or more properties simultaneously and set it as the property cycle of the axes. If multiple properties are given, their value lists must have the same length. This is just a shortcut for explicitly creating a cycler and passing it to the function, i.e. it's short for ``set_prop_cycle(cycler(label=values label2=values2, ...))``. Form 3 creates a `~cycler.Cycler` for a single property and set it as the property cycle of the axes. This form exists for compatibility with the original `cycler.cycler` interface. Its use is discouraged in favor of the kwarg form, i.e. ``set_prop_cycle(label=values)``. Parameters ---------- cycler : Cycler Set the given Cycler. *None* resets to the cycle defined by the current style. label : str The property key. Must be a valid `.Artist` property. For example, 'color' or 'linestyle'. Aliases are allowed, such as 'c' for 'color' and 'lw' for 'linewidth'. values : iterable Finite-length iterable of the property values. These values are validated and will raise a ValueError if invalid. Examples -------- Setting the property cycle for a single property: >>> ax.set_prop_cycle(color=['red', 'green', 'blue']) Setting the property cycle for simultaneously cycling over multiple properties (e.g. red circle, green plus, blue cross): >>> ax.set_prop_cycle(color=['red', 'green', 'blue'], ... marker=['o', '+', 'x']) See Also -------- matplotlib.rcsetup.cycler Convenience function for creating validated cyclers for properties. cycler.cycler The original function for creating unvalidated cyclers.
Set the property cycle of the Axes.
[ "Set", "the", "property", "cycle", "of", "the", "Axes", "." ]
def set_prop_cycle(self, *args, **kwargs): """ Set the property cycle of the Axes. The property cycle controls the style properties such as color, marker and linestyle of future plot commands. The style properties of data already added to the Axes are not modified. Call signatures:: set_prop_cycle(cycler) set_prop_cycle(label=values[, label2=values2[, ...]]) set_prop_cycle(label, values) Form 1 sets given `~cycler.Cycler` object. Form 2 creates a `~cycler.Cycler` which cycles over one or more properties simultaneously and set it as the property cycle of the axes. If multiple properties are given, their value lists must have the same length. This is just a shortcut for explicitly creating a cycler and passing it to the function, i.e. it's short for ``set_prop_cycle(cycler(label=values label2=values2, ...))``. Form 3 creates a `~cycler.Cycler` for a single property and set it as the property cycle of the axes. This form exists for compatibility with the original `cycler.cycler` interface. Its use is discouraged in favor of the kwarg form, i.e. ``set_prop_cycle(label=values)``. Parameters ---------- cycler : Cycler Set the given Cycler. *None* resets to the cycle defined by the current style. label : str The property key. Must be a valid `.Artist` property. For example, 'color' or 'linestyle'. Aliases are allowed, such as 'c' for 'color' and 'lw' for 'linewidth'. values : iterable Finite-length iterable of the property values. These values are validated and will raise a ValueError if invalid. Examples -------- Setting the property cycle for a single property: >>> ax.set_prop_cycle(color=['red', 'green', 'blue']) Setting the property cycle for simultaneously cycling over multiple properties (e.g. red circle, green plus, blue cross): >>> ax.set_prop_cycle(color=['red', 'green', 'blue'], ... marker=['o', '+', 'x']) See Also -------- matplotlib.rcsetup.cycler Convenience function for creating validated cyclers for properties. cycler.cycler The original function for creating unvalidated cyclers. """ if args and kwargs: raise TypeError("Cannot supply both positional and keyword " "arguments to this method.") # Can't do `args == (None,)` as that crashes cycler. if len(args) == 1 and args[0] is None: prop_cycle = None else: prop_cycle = cycler(*args, **kwargs) self._get_lines.set_prop_cycle(prop_cycle) self._get_patches_for_fill.set_prop_cycle(prop_cycle)
[ "def", "set_prop_cycle", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "and", "kwargs", ":", "raise", "TypeError", "(", "\"Cannot supply both positional and keyword \"", "\"arguments to this method.\"", ")", "# Can't do `args == (None...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/matplotlib/axes/_base.py#L1150-L1222
evennia/evennia
fa79110ba6b219932f22297838e8ac72ebc0be0e
evennia/web/utils/general_context.py
python
set_webclient_settings
()
As with set_game_name_and_slogan above, this sets global variables pertaining to webclient settings. Notes: Used for unit testing.
As with set_game_name_and_slogan above, this sets global variables pertaining to webclient settings.
[ "As", "with", "set_game_name_and_slogan", "above", "this", "sets", "global", "variables", "pertaining", "to", "webclient", "settings", "." ]
def set_webclient_settings(): """ As with set_game_name_and_slogan above, this sets global variables pertaining to webclient settings. Notes: Used for unit testing. """ global WEBCLIENT_ENABLED, WEBSOCKET_CLIENT_ENABLED, WEBSOCKET_PORT, WEBSOCKET_URL WEBCLIENT_ENABLED = settings.WEBCLIENT_ENABLED WEBSOCKET_CLIENT_ENABLED = settings.WEBSOCKET_CLIENT_ENABLED # if we are working through a proxy or uses docker port-remapping, the webclient port encoded # in the webclient should be different than the one the server expects. Use the environment # variable WEBSOCKET_CLIENT_PROXY_PORT if this is the case. WEBSOCKET_PORT = int( os.environ.get("WEBSOCKET_CLIENT_PROXY_PORT", settings.WEBSOCKET_CLIENT_PORT) ) # this is determined dynamically by the client and is less of an issue WEBSOCKET_URL = settings.WEBSOCKET_CLIENT_URL
[ "def", "set_webclient_settings", "(", ")", ":", "global", "WEBCLIENT_ENABLED", ",", "WEBSOCKET_CLIENT_ENABLED", ",", "WEBSOCKET_PORT", ",", "WEBSOCKET_URL", "WEBCLIENT_ENABLED", "=", "settings", ".", "WEBCLIENT_ENABLED", "WEBSOCKET_CLIENT_ENABLED", "=", "settings", ".", "...
https://github.com/evennia/evennia/blob/fa79110ba6b219932f22297838e8ac72ebc0be0e/evennia/web/utils/general_context.py#L46-L64
misterch0c/shadowbroker
e3a069bea47a2c1009697941ac214adc6f90aa8d
windows/Resources/Python/Core/Lib/compiler/syntax.py
python
SyntaxErrorChecker.__init__
(self, multi=None)
Create new visitor object. If optional argument multi is not None, then print messages for each error rather than raising a SyntaxError for the first.
Create new visitor object. If optional argument multi is not None, then print messages for each error rather than raising a SyntaxError for the first.
[ "Create", "new", "visitor", "object", ".", "If", "optional", "argument", "multi", "is", "not", "None", "then", "print", "messages", "for", "each", "error", "rather", "than", "raising", "a", "SyntaxError", "for", "the", "first", "." ]
def __init__(self, multi=None): """Create new visitor object. If optional argument multi is not None, then print messages for each error rather than raising a SyntaxError for the first. """ self.multi = multi self.errors = 0
[ "def", "__init__", "(", "self", ",", "multi", "=", "None", ")", ":", "self", ".", "multi", "=", "multi", "self", ".", "errors", "=", "0" ]
https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/compiler/syntax.py#L27-L35
WikidPad/WikidPad
558109638807bc76b4672922686e416ab2d5f79c
WikidPad/lib/whoosh/reading.py
python
IndexReader.storage
(self)
return None
Returns the :class:`whoosh.filedb.filestore.Storage` object used by this reader to read its files. If the reader is not atomic, (``reader.is_atomic() == True``), returns None.
Returns the :class:`whoosh.filedb.filestore.Storage` object used by this reader to read its files. If the reader is not atomic, (``reader.is_atomic() == True``), returns None.
[ "Returns", "the", ":", "class", ":", "whoosh", ".", "filedb", ".", "filestore", ".", "Storage", "object", "used", "by", "this", "reader", "to", "read", "its", "files", ".", "If", "the", "reader", "is", "not", "atomic", "(", "reader", ".", "is_atomic", ...
def storage(self): """Returns the :class:`whoosh.filedb.filestore.Storage` object used by this reader to read its files. If the reader is not atomic, (``reader.is_atomic() == True``), returns None. """ return None
[ "def", "storage", "(", "self", ")", ":", "return", "None" ]
https://github.com/WikidPad/WikidPad/blob/558109638807bc76b4672922686e416ab2d5f79c/WikidPad/lib/whoosh/reading.py#L177-L183
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/pandas/io/sql.py
python
to_sql
(frame, name, con, schema=None, if_exists='fail', index=True, index_label=None, chunksize=None, dtype=None, method=None)
Write records stored in a DataFrame to a SQL database. Parameters ---------- frame : DataFrame, Series name : string Name of SQL table. con : SQLAlchemy connectable(engine/connection) or database string URI or sqlite3 DBAPI2 connection Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported. schema : string, default None Name of SQL schema in database to write to (if database flavor supports this). If None, use default schema (default). if_exists : {'fail', 'replace', 'append'}, default 'fail' - fail: If table exists, do nothing. - replace: If table exists, drop it, recreate it, and insert data. - append: If table exists, insert data. Create if does not exist. index : boolean, default True Write DataFrame index as a column. index_label : string or sequence, default None Column label for index column(s). If None is given (default) and `index` is True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex. chunksize : int, default None If not None, then rows will be written in batches of this size at a time. If None, all rows will be written at once. dtype : single SQLtype or dict of column name to SQL type, default None Optional specifying the datatype for columns. The SQL type should be a SQLAlchemy type, or a string for sqlite3 fallback connection. If all columns are of the same type, one single value can be used. method : {None, 'multi', callable}, default None Controls the SQL insertion clause used: - None : Uses standard SQL ``INSERT`` clause (one per row). - 'multi': Pass multiple values in a single ``INSERT`` clause. - callable with signature ``(pd_table, conn, keys, data_iter)``. Details and a sample callable implementation can be found in the section :ref:`insert method <io.sql.method>`. .. versionadded:: 0.24.0
Write records stored in a DataFrame to a SQL database.
[ "Write", "records", "stored", "in", "a", "DataFrame", "to", "a", "SQL", "database", "." ]
def to_sql(frame, name, con, schema=None, if_exists='fail', index=True, index_label=None, chunksize=None, dtype=None, method=None): """ Write records stored in a DataFrame to a SQL database. Parameters ---------- frame : DataFrame, Series name : string Name of SQL table. con : SQLAlchemy connectable(engine/connection) or database string URI or sqlite3 DBAPI2 connection Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported. schema : string, default None Name of SQL schema in database to write to (if database flavor supports this). If None, use default schema (default). if_exists : {'fail', 'replace', 'append'}, default 'fail' - fail: If table exists, do nothing. - replace: If table exists, drop it, recreate it, and insert data. - append: If table exists, insert data. Create if does not exist. index : boolean, default True Write DataFrame index as a column. index_label : string or sequence, default None Column label for index column(s). If None is given (default) and `index` is True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex. chunksize : int, default None If not None, then rows will be written in batches of this size at a time. If None, all rows will be written at once. dtype : single SQLtype or dict of column name to SQL type, default None Optional specifying the datatype for columns. The SQL type should be a SQLAlchemy type, or a string for sqlite3 fallback connection. If all columns are of the same type, one single value can be used. method : {None, 'multi', callable}, default None Controls the SQL insertion clause used: - None : Uses standard SQL ``INSERT`` clause (one per row). - 'multi': Pass multiple values in a single ``INSERT`` clause. - callable with signature ``(pd_table, conn, keys, data_iter)``. Details and a sample callable implementation can be found in the section :ref:`insert method <io.sql.method>`. .. versionadded:: 0.24.0 """ if if_exists not in ('fail', 'replace', 'append'): raise ValueError("'{0}' is not valid for if_exists".format(if_exists)) pandas_sql = pandasSQL_builder(con, schema=schema) if isinstance(frame, Series): frame = frame.to_frame() elif not isinstance(frame, DataFrame): raise NotImplementedError("'frame' argument should be either a " "Series or a DataFrame") pandas_sql.to_sql(frame, name, if_exists=if_exists, index=index, index_label=index_label, schema=schema, chunksize=chunksize, dtype=dtype, method=method)
[ "def", "to_sql", "(", "frame", ",", "name", ",", "con", ",", "schema", "=", "None", ",", "if_exists", "=", "'fail'", ",", "index", "=", "True", ",", "index_label", "=", "None", ",", "chunksize", "=", "None", ",", "dtype", "=", "None", ",", "method", ...
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/pandas/io/sql.py#L400-L460
daoluan/decode-Django
d46a858b45b56de48b0355f50dd9e45402d04cfd
Django-1.5.1/django/utils/timezone.py
python
get_current_timezone
()
return getattr(_active, "value", get_default_timezone())
Returns the currently active time zone as a tzinfo instance.
Returns the currently active time zone as a tzinfo instance.
[ "Returns", "the", "currently", "active", "time", "zone", "as", "a", "tzinfo", "instance", "." ]
def get_current_timezone(): """ Returns the currently active time zone as a tzinfo instance. """ return getattr(_active, "value", get_default_timezone())
[ "def", "get_current_timezone", "(", ")", ":", "return", "getattr", "(", "_active", ",", "\"value\"", ",", "get_default_timezone", "(", ")", ")" ]
https://github.com/daoluan/decode-Django/blob/d46a858b45b56de48b0355f50dd9e45402d04cfd/Django-1.5.1/django/utils/timezone.py#L127-L131
andyzsf/TuShare
92787ad0cd492614bdb6389b71a19c80d1c8c9ae
tushare/datayes/macro.py
python
Macro.GermanyDataFinance
(self, indicID='', indicName='', beginDate='', endDate='', field='')
return _ret_data(code, result)
包含德国财政收支数据,具体指标可参见API文档;历史数据从2004年开始,按月更新。
包含德国财政收支数据,具体指标可参见API文档;历史数据从2004年开始,按月更新。
[ "包含德国财政收支数据,具体指标可参见API文档;历史数据从2004年开始,按月更新。" ]
def GermanyDataFinance(self, indicID='', indicName='', beginDate='', endDate='', field=''): """ 包含德国财政收支数据,具体指标可参见API文档;历史数据从2004年开始,按月更新。 """ code, result = self.client.getData(vs.GERMANYDATAFINANCE%(indicID, indicName, beginDate, endDate, field)) return _ret_data(code, result)
[ "def", "GermanyDataFinance", "(", "self", ",", "indicID", "=", "''", ",", "indicName", "=", "''", ",", "beginDate", "=", "''", ",", "endDate", "=", "''", ",", "field", "=", "''", ")", ":", "code", ",", "result", "=", "self", ".", "client", ".", "ge...
https://github.com/andyzsf/TuShare/blob/92787ad0cd492614bdb6389b71a19c80d1c8c9ae/tushare/datayes/macro.py#L1403-L1408
clinton-hall/nzbToMedia
27669389216902d1085660167e7bda0bd8527ecf
libs/common/setuptools/command/easy_install.py
python
easy_install.check_pth_processing
(self)
return False
Empirically verify whether .pth files are supported in inst. dir
Empirically verify whether .pth files are supported in inst. dir
[ "Empirically", "verify", "whether", ".", "pth", "files", "are", "supported", "in", "inst", ".", "dir" ]
def check_pth_processing(self): """Empirically verify whether .pth files are supported in inst. dir""" instdir = self.install_dir log.info("Checking .pth file support in %s", instdir) pth_file = self.pseudo_tempname() + ".pth" ok_file = pth_file + '.ok' ok_exists = os.path.exists(ok_file) tmpl = _one_liner(""" import os f = open({ok_file!r}, 'w') f.write('OK') f.close() """) + '\n' try: if ok_exists: os.unlink(ok_file) dirname = os.path.dirname(ok_file) pkg_resources.py31compat.makedirs(dirname, exist_ok=True) f = open(pth_file, 'w') except (OSError, IOError): self.cant_write_to_target() else: try: f.write(tmpl.format(**locals())) f.close() f = None executable = sys.executable if os.name == 'nt': dirname, basename = os.path.split(executable) alt = os.path.join(dirname, 'pythonw.exe') use_alt = ( basename.lower() == 'python.exe' and os.path.exists(alt) ) if use_alt: # use pythonw.exe to avoid opening a console window executable = alt from distutils.spawn import spawn spawn([executable, '-E', '-c', 'pass'], 0) if os.path.exists(ok_file): log.info( "TEST PASSED: %s appears to support .pth files", instdir ) return True finally: if f: f.close() if os.path.exists(ok_file): os.unlink(ok_file) if os.path.exists(pth_file): os.unlink(pth_file) if not self.multi_version: log.warn("TEST FAILED: %s does NOT support .pth files", instdir) return False
[ "def", "check_pth_processing", "(", "self", ")", ":", "instdir", "=", "self", ".", "install_dir", "log", ".", "info", "(", "\"Checking .pth file support in %s\"", ",", "instdir", ")", "pth_file", "=", "self", ".", "pseudo_tempname", "(", ")", "+", "\".pth\"", ...
https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/setuptools/command/easy_install.py#L537-L594
NoGameNoLife00/mybolg
afe17ea5bfe405e33766e5682c43a4262232ee12
libs/wtforms/fields/core.py
python
Field.post_validate
(self, form, validation_stopped)
Override if you need to run any field-level validation tasks after normal validation. This shouldn't be needed in most cases. :param form: The form the field belongs to. :param validation_stopped: `True` if any validator raised StopValidation.
Override if you need to run any field-level validation tasks after normal validation. This shouldn't be needed in most cases.
[ "Override", "if", "you", "need", "to", "run", "any", "field", "-", "level", "validation", "tasks", "after", "normal", "validation", ".", "This", "shouldn", "t", "be", "needed", "in", "most", "cases", "." ]
def post_validate(self, form, validation_stopped): """ Override if you need to run any field-level validation tasks after normal validation. This shouldn't be needed in most cases. :param form: The form the field belongs to. :param validation_stopped: `True` if any validator raised StopValidation. """ pass
[ "def", "post_validate", "(", "self", ",", "form", ",", "validation_stopped", ")", ":", "pass" ]
https://github.com/NoGameNoLife00/mybolg/blob/afe17ea5bfe405e33766e5682c43a4262232ee12/libs/wtforms/fields/core.py#L239-L248
rdiff-backup/rdiff-backup
321e0cd6e5e47d4c158a0172e47ab38240a8b653
src/rdiff_backup/SetConnections.py
python
_init_connection_routing
(conn, conn_number, remote_cmd)
Called by _init_connection, establish routing, conn dict
Called by _init_connection, establish routing, conn dict
[ "Called", "by", "_init_connection", "establish", "routing", "conn", "dict" ]
def _init_connection_routing(conn, conn_number, remote_cmd): """Called by _init_connection, establish routing, conn dict""" Globals.connection_dict[conn_number] = conn conn.SetConnections.init_connection_remote(conn_number) for other_remote_conn in Globals.connections[1:]: conn.SetConnections.add_redirected_conn(other_remote_conn.conn_number) other_remote_conn.SetConnections.add_redirected_conn(conn_number) Globals.connections.append(conn) __conn_remote_cmds.append(remote_cmd)
[ "def", "_init_connection_routing", "(", "conn", ",", "conn_number", ",", "remote_cmd", ")", ":", "Globals", ".", "connection_dict", "[", "conn_number", "]", "=", "conn", "conn", ".", "SetConnections", ".", "init_connection_remote", "(", "conn_number", ")", "for", ...
https://github.com/rdiff-backup/rdiff-backup/blob/321e0cd6e5e47d4c158a0172e47ab38240a8b653/src/rdiff_backup/SetConnections.py#L444-L454
softlayer/softlayer-python
cdef7d63c66413197a9a97b0414de9f95887a82a
SoftLayer/CLI/loadbal/layer7_policy_list.py
python
policies
(env, protocol_id)
List policies of the front-end protocol (listener).
List policies of the front-end protocol (listener).
[ "List", "policies", "of", "the", "front", "-", "end", "protocol", "(", "listener", ")", "." ]
def policies(env, protocol_id): """List policies of the front-end protocol (listener).""" mgr = SoftLayer.LoadBalancerManager(env.client) if protocol_id: l7policies = mgr.get_l7policies(protocol_id) table = generate_l7policies_table(l7policies, protocol_id) else: l7policies = mgr.get_all_l7policies() table = l7policies_table(l7policies) env.fout(table)
[ "def", "policies", "(", "env", ",", "protocol_id", ")", ":", "mgr", "=", "SoftLayer", ".", "LoadBalancerManager", "(", "env", ".", "client", ")", "if", "protocol_id", ":", "l7policies", "=", "mgr", ".", "get_l7policies", "(", "protocol_id", ")", "table", "...
https://github.com/softlayer/softlayer-python/blob/cdef7d63c66413197a9a97b0414de9f95887a82a/SoftLayer/CLI/loadbal/layer7_policy_list.py#L15-L25
pymeasure/pymeasure
b4d888e9ead85ef7f7af0031f2dbb44c9ce1825e
pymeasure/adapters/vxi11.py
python
VXI11Adapter.read
(self)
return self.connection.read()
Wrapper function for the read command using the vx11 interface. :return string containing a response from the device.
Wrapper function for the read command using the vx11 interface.
[ "Wrapper", "function", "for", "the", "read", "command", "using", "the", "vx11", "interface", "." ]
def read(self): """ Wrapper function for the read command using the vx11 interface. :return string containing a response from the device. """ return self.connection.read()
[ "def", "read", "(", "self", ")", ":", "return", "self", ".", "connection", ".", "read", "(", ")" ]
https://github.com/pymeasure/pymeasure/blob/b4d888e9ead85ef7f7af0031f2dbb44c9ce1825e/pymeasure/adapters/vxi11.py#L68-L74
postlund/pyatv
4ed1f5539f37d86d80272663d1f2ea34a6c41ec4
pyatv/conf.py
python
AppleTV.deep_sleep
(self)
return self._deep_sleep
If device is in deep sleep.
If device is in deep sleep.
[ "If", "device", "is", "in", "deep", "sleep", "." ]
def deep_sleep(self) -> bool: """If device is in deep sleep.""" return self._deep_sleep
[ "def", "deep_sleep", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_deep_sleep" ]
https://github.com/postlund/pyatv/blob/4ed1f5539f37d86d80272663d1f2ea34a6c41ec4/pyatv/conf.py#L51-L53
yuantiku/fairseq-gec
10aafebc482706346f768e4f18a9813153cb1ecc
fairseq/tasks/fairseq_task.py
python
FairseqTask.setup_task
(cls, args, **kwargs)
return cls(args)
Setup the task (e.g., load dictionaries). Args: args (argparse.Namespace): parsed command-line arguments
Setup the task (e.g., load dictionaries).
[ "Setup", "the", "task", "(", "e", ".", "g", ".", "load", "dictionaries", ")", "." ]
def setup_task(cls, args, **kwargs): """Setup the task (e.g., load dictionaries). Args: args (argparse.Namespace): parsed command-line arguments """ return cls(args)
[ "def", "setup_task", "(", "cls", ",", "args", ",", "*", "*", "kwargs", ")", ":", "return", "cls", "(", "args", ")" ]
https://github.com/yuantiku/fairseq-gec/blob/10aafebc482706346f768e4f18a9813153cb1ecc/fairseq/tasks/fairseq_task.py#L59-L65
ceph/ceph-ansible
583e60af84180f0414d67ee52c3ec7cd64ddb4dd
library/radosgw_zone.py
python
get_zonegroup
(module, container_image=None)
return cmd
Get existing zonegroup
Get existing zonegroup
[ "Get", "existing", "zonegroup" ]
def get_zonegroup(module, container_image=None): ''' Get existing zonegroup ''' cluster = module.params.get('cluster') realm = module.params.get('realm') zonegroup = module.params.get('zonegroup') cmd = pre_generate_radosgw_cmd(container_image=container_image) args = [ '--cluster', cluster, 'zonegroup', 'get', '--rgw-realm=' + realm, '--rgw-zonegroup=' + zonegroup, '--format=json' ] cmd.extend(args) return cmd
[ "def", "get_zonegroup", "(", "module", ",", "container_image", "=", "None", ")", ":", "cluster", "=", "module", ".", "params", ".", "get", "(", "'cluster'", ")", "realm", "=", "module", ".", "params", ".", "get", "(", "'realm'", ")", "zonegroup", "=", ...
https://github.com/ceph/ceph-ansible/blob/583e60af84180f0414d67ee52c3ec7cd64ddb4dd/library/radosgw_zone.py#L310-L333
google/pytype
fa43edc95dd42ade6e3147d6580d63e778c9d506
pytype/metrics.py
python
get_cpu_clock
()
return time.process_time()
Returns CPU clock to keep compatibility with various Python versions.
Returns CPU clock to keep compatibility with various Python versions.
[ "Returns", "CPU", "clock", "to", "keep", "compatibility", "with", "various", "Python", "versions", "." ]
def get_cpu_clock(): """Returns CPU clock to keep compatibility with various Python versions.""" return time.process_time()
[ "def", "get_cpu_clock", "(", ")", ":", "return", "time", ".", "process_time", "(", ")" ]
https://github.com/google/pytype/blob/fa43edc95dd42ade6e3147d6580d63e778c9d506/pytype/metrics.py#L89-L91
tanghaibao/goatools
647e9dd833695f688cd16c2f9ea18f1692e5c6bc
goatools/gosubdag/plot/go_edge.py
python
GoEdge.__init__
(self, gosubdag, optobj)
[]
def __init__(self, gosubdag, optobj): self.gosubdag = gosubdag # GoSubDag self.kws = optobj.get_kws()
[ "def", "__init__", "(", "self", ",", "gosubdag", ",", "optobj", ")", ":", "self", ".", "gosubdag", "=", "gosubdag", "# GoSubDag", "self", ".", "kws", "=", "optobj", ".", "get_kws", "(", ")" ]
https://github.com/tanghaibao/goatools/blob/647e9dd833695f688cd16c2f9ea18f1692e5c6bc/goatools/gosubdag/plot/go_edge.py#L47-L49
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/cherrypy/lib/sessions.py
python
Session.__init__
(self, id=None, **kwargs)
[]
def __init__(self, id=None, **kwargs): self.id_observers = [] self._data = {} for k, v in kwargs.items(): setattr(self, k, v) self.originalid = id self.missing = False if id is None: if self.debug: cherrypy.log('No id given; making a new one', 'TOOLS.SESSIONS') self._regenerate() else: self.id = id if self._exists(): if self.debug: cherrypy.log('Set id to %s.' % id, 'TOOLS.SESSIONS') else: if self.debug: cherrypy.log('Expired or malicious session %r; ' 'making a new one' % id, 'TOOLS.SESSIONS') # Expired or malicious session. Make a new one. # See https://github.com/cherrypy/cherrypy/issues/709. self.id = None self.missing = True self._regenerate()
[ "def", "__init__", "(", "self", ",", "id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "id_observers", "=", "[", "]", "self", ".", "_data", "=", "{", "}", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "se...
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/cherrypy/lib/sessions.py#L177-L203
accel-brain/accel-brain-code
86f489dc9be001a3bae6d053f48d6b57c0bedb95
Generative-Adversarial-Networks/pygan/controllablemodel/_mxnet/gancontroller/cluster_gan_controller.py
python
ClusterGANController.train_clusterer
(self)
return total_g_loss, total_posterior
Train clusterer. Returns: Tuple data. - generative loss. - discriminative posterior.
Train clusterer. Returns: Tuple data. - generative loss. - discriminative posterior.
[ "Train", "clusterer", ".", "Returns", ":", "Tuple", "data", ".", "-", "generative", "loss", ".", "-", "discriminative", "posterior", "." ]
def train_clusterer(self): ''' Train clusterer. Returns: Tuple data. - generative loss. - discriminative posterior. ''' total_g_loss = 0.0 total_posterior = 0.0 for g in range(self.g_step): with autograd.record(): with autograd.predict_mode(): generated_arr, true_soft_assignment_arr = self.__generative_model.draw() generated_arr = generated_arr.reshape(self.__generated_shape) #predictive_model_flag = self.clustering_model.predictive_model_flag #self.clustering_model.predictive_model_flag = True clustered_arr, soft_assignment_arr = self.clustering_model.draw() #self.clustering_model.predictive_model_flag = predictive_model_flag with autograd.predict_mode(): x = (generated_arr, true_soft_assignment_arr) g_feature_arr = None for i in range(len(self.discriminative_model.model_list)): arr = self.discriminative_model.model_list[i](x[i]) if g_feature_arr is None: g_feature_arr = arr else: g_feature_arr = nd.concat(g_feature_arr, arr, dim=1) generated_posterior_arr = self.__discriminative_model.inference(g_feature_arr) if isinstance(self.discriminator_loss, DiscriminatorLoss) is False: if self.__generator_loss is not None: g_loss = self.__generator_loss(generated_posterior_arr) else: g_loss = 0.0 else: g_loss = generated_posterior_arr c_loss = self.__consistency_loss(clustered_arr, generated_arr) loss = g_loss + c_loss loss.backward() self.clustering_model.model.regularize() total_g_loss += loss.mean().asnumpy()[0] total_posterior += generated_posterior_arr.mean().asnumpy()[0] total_g_loss = total_g_loss / self.g_step total_posterior = total_posterior / self.g_step return total_g_loss, total_posterior
[ "def", "train_clusterer", "(", "self", ")", ":", "total_g_loss", "=", "0.0", "total_posterior", "=", "0.0", "for", "g", "in", "range", "(", "self", ".", "g_step", ")", ":", "with", "autograd", ".", "record", "(", ")", ":", "with", "autograd", ".", "pre...
https://github.com/accel-brain/accel-brain-code/blob/86f489dc9be001a3bae6d053f48d6b57c0bedb95/Generative-Adversarial-Networks/pygan/controllablemodel/_mxnet/gancontroller/cluster_gan_controller.py#L367-L422
PyHDI/veriloggen
2382d200deabf59cfcfd741f5eba371010aaf2bb
veriloggen/types/fixed.py
python
_FixedGreaterEq.__init__
(self, left, right)
[]
def __init__(self, left, right): left, right = self.init(left, right) vtypes.GreaterEq.__init__(self, left, right)
[ "def", "__init__", "(", "self", ",", "left", ",", "right", ")", ":", "left", ",", "right", "=", "self", ".", "init", "(", "left", ",", "right", ")", "vtypes", ".", "GreaterEq", ".", "__init__", "(", "self", ",", "left", ",", "right", ")" ]
https://github.com/PyHDI/veriloggen/blob/2382d200deabf59cfcfd741f5eba371010aaf2bb/veriloggen/types/fixed.py#L615-L617
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/matrices/expressions/matexpr.py
python
MatrixExpr.__rmul__
(self, other)
return MatMul(other, self).doit()
[]
def __rmul__(self, other): return MatMul(other, self).doit()
[ "def", "__rmul__", "(", "self", ",", "other", ")", ":", "return", "MatMul", "(", "other", ",", "self", ")", ".", "doit", "(", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/matrices/expressions/matexpr.py#L104-L105
vyos/vyos-1x
6e8a8934a7d4e1b21d7c828e372303683b499b56
python/vyos/configdict.py
python
node_changed
(conf, path, key_mangling=None)
return list(keys)
Check if a leaf node was altered. If it has been altered - values has been changed, or it was added/removed, we will return the old value. If nothing has been changed, None is returned
Check if a leaf node was altered. If it has been altered - values has been changed, or it was added/removed, we will return the old value. If nothing has been changed, None is returned
[ "Check", "if", "a", "leaf", "node", "was", "altered", ".", "If", "it", "has", "been", "altered", "-", "values", "has", "been", "changed", "or", "it", "was", "added", "/", "removed", "we", "will", "return", "the", "old", "value", ".", "If", "nothing", ...
def node_changed(conf, path, key_mangling=None): """ Check if a leaf node was altered. If it has been altered - values has been changed, or it was added/removed, we will return the old value. If nothing has been changed, None is returned """ from vyos.configdiff import get_config_diff, Diff D = get_config_diff(conf, key_mangling) D.set_level(conf.get_level()) # get_child_nodes() will return dict_keys(), mangle this into a list with PEP448 keys = D.get_child_nodes_diff(path, expand_nodes=Diff.DELETE)['delete'].keys() return list(keys)
[ "def", "node_changed", "(", "conf", ",", "path", ",", "key_mangling", "=", "None", ")", ":", "from", "vyos", ".", "configdiff", "import", "get_config_diff", ",", "Diff", "D", "=", "get_config_diff", "(", "conf", ",", "key_mangling", ")", "D", ".", "set_lev...
https://github.com/vyos/vyos-1x/blob/6e8a8934a7d4e1b21d7c828e372303683b499b56/python/vyos/configdict.py#L133-L144
ipfs-shipyard/py-ipfs-http-client
f04ff601556f8429837eb7d4851fe02913f72f63
ipfshttpclient/client/base.py
python
ResponseBase.__iter__
(self)
return iter(self._raw)
[]
def __iter__(self) -> ty.Iterator[str]: return iter(self._raw)
[ "def", "__iter__", "(", "self", ")", "->", "ty", ".", "Iterator", "[", "str", "]", ":", "return", "iter", "(", "self", ".", "_raw", ")" ]
https://github.com/ipfs-shipyard/py-ipfs-http-client/blob/f04ff601556f8429837eb7d4851fe02913f72f63/ipfshttpclient/client/base.py#L96-L97
samoturk/mol2vec
850d944d5f48a58e26ed0264332b5741f72555aa
mol2vec/features.py
python
generate_corpus
(in_file, out_file, r, sentence_type='alt', n_jobs=1)
Generates corpus file from sdf Parameters ---------- in_file : str Input sdf out_file : str Outfile name prefix, suffix is either _r0, _r1, etc. or _alt_r1 (max radius in alt sentence) r : int Radius of morgan fingerprint sentence_type : str Options: 'all' - generates all corpus files for all types of sentences, 'alt' - generates a corpus file with only combined alternating sentence, 'individual' - generates corpus files for each radius n_jobs : int Number of cores to use (only 'alt' sentence type is parallelized) Returns -------
Generates corpus file from sdf Parameters ---------- in_file : str Input sdf out_file : str Outfile name prefix, suffix is either _r0, _r1, etc. or _alt_r1 (max radius in alt sentence) r : int Radius of morgan fingerprint sentence_type : str Options: 'all' - generates all corpus files for all types of sentences, 'alt' - generates a corpus file with only combined alternating sentence, 'individual' - generates corpus files for each radius n_jobs : int Number of cores to use (only 'alt' sentence type is parallelized)
[ "Generates", "corpus", "file", "from", "sdf", "Parameters", "----------", "in_file", ":", "str", "Input", "sdf", "out_file", ":", "str", "Outfile", "name", "prefix", "suffix", "is", "either", "_r0", "_r1", "etc", ".", "or", "_alt_r1", "(", "max", "radius", ...
def generate_corpus(in_file, out_file, r, sentence_type='alt', n_jobs=1): """Generates corpus file from sdf Parameters ---------- in_file : str Input sdf out_file : str Outfile name prefix, suffix is either _r0, _r1, etc. or _alt_r1 (max radius in alt sentence) r : int Radius of morgan fingerprint sentence_type : str Options: 'all' - generates all corpus files for all types of sentences, 'alt' - generates a corpus file with only combined alternating sentence, 'individual' - generates corpus files for each radius n_jobs : int Number of cores to use (only 'alt' sentence type is parallelized) Returns ------- """ # File type detection in_split = in_file.split('.') if in_split[-1].lower() not in ['sdf', 'smi', 'ism', 'gz']: raise ValueError('File extension not supported (sdf, smi, ism, sdf.gz, smi.gz)') gzipped = False if in_split[-1].lower() == 'gz': gzipped = True if in_split[-2].lower() not in ['sdf', 'smi', 'ism']: raise ValueError('File extension not supported (sdf, smi, ism, sdf.gz, smi.gz)') file_handles = [] # write only files which contain corpus if (sentence_type == 'individual') or (sentence_type == 'all'): f1 = open(out_file+'_r0.corpus', "w") f2 = open(out_file+'_r1.corpus', "w") file_handles.append(f1) file_handles.append(f2) if (sentence_type == 'alt') or (sentence_type == 'all'): f3 = open(out_file, "w") file_handles.append(f3) if gzipped: import gzip if in_split[-2].lower() == 'sdf': mols_file = gzip.open(in_file, mode='r') suppl = Chem.ForwardSDMolSupplier(mols_file) else: mols_file = gzip.open(in_file, mode='rt') suppl = _read_smi(mols_file) else: if in_split[-1].lower() == 'sdf': suppl = Chem.ForwardSDMolSupplier(in_file) else: mols_file = open(in_file, mode='rt') suppl = _read_smi(mols_file) if sentence_type == 'alt': # This can run parallelized result = Parallel(n_jobs=n_jobs, verbose=1)(delayed(_parallel_job)(mol, r) for mol in suppl) for i, line in enumerate(result): f3.write(str(line) + '\n') print('% molecules successfully processed.') else: for mol in suppl: if mol is not None: smiles = Chem.MolToSmiles(mol) mol = Chem.MolFromSmiles(smiles) identifier_sentences, alternating_sentence = mol2sentence(mol, r) identifier_sentence_r0 = " ".join(identifier_sentences[0]) identifier_sentence_r1 = " ".join(identifier_sentences[1]) alternating_sentence_r0r1 = " ".join(alternating_sentence) if len(smiles) != 0: if (sentence_type == 'individual') or (sentence_type == 'all'): f1.write(str(identifier_sentence_r0)+'\n') f2.write(str(identifier_sentence_r1)+'\n') if (sentence_type == 'alt') or (sentence_type == 'all'): f3.write(str(alternating_sentence_r0r1)+'\n') for fh in file_handles: fh.close()
[ "def", "generate_corpus", "(", "in_file", ",", "out_file", ",", "r", ",", "sentence_type", "=", "'alt'", ",", "n_jobs", "=", "1", ")", ":", "# File type detection", "in_split", "=", "in_file", ".", "split", "(", "'.'", ")", "if", "in_split", "[", "-", "1...
https://github.com/samoturk/mol2vec/blob/850d944d5f48a58e26ed0264332b5741f72555aa/mol2vec/features.py#L189-L277
chainer/chainercv
7159616642e0be7c5b3ef380b848e16b7e99355b
chainercv/links/model/senet/se_resnet.py
python
SEResNet.__init__
(self, n_layer, n_class=None, pretrained_model=None, mean=None, initialW=None, fc_kwargs={})
[]
def __init__(self, n_layer, n_class=None, pretrained_model=None, mean=None, initialW=None, fc_kwargs={}): blocks = self._blocks[n_layer] param, path = utils.prepare_pretrained_model( {'n_class': n_class, 'mean': mean}, pretrained_model, self._models[n_layer], {'n_class': 1000, 'mean': _imagenet_mean}) self.mean = param['mean'] if initialW is None: initialW = initializers.HeNormal(scale=1., fan_option='fan_out') if 'initialW' not in fc_kwargs: fc_kwargs['initialW'] = initializers.Normal(scale=0.01) if pretrained_model: # As a sampling process is time-consuming, # we employ a zero initializer for faster computation. initialW = initializers.constant.Zero() fc_kwargs['initialW'] = initializers.constant.Zero() kwargs = { 'initialW': initialW, 'stride_first': True, 'add_seblock': True} super(SEResNet, self).__init__() with self.init_scope(): self.conv1 = Conv2DBNActiv(None, 64, 7, 2, 3, nobias=True, initialW=initialW) self.pool1 = lambda x: F.max_pooling_2d(x, ksize=3, stride=2) self.res2 = ResBlock(blocks[0], None, 64, 256, 1, **kwargs) self.res3 = ResBlock(blocks[1], None, 128, 512, 2, **kwargs) self.res4 = ResBlock(blocks[2], None, 256, 1024, 2, **kwargs) self.res5 = ResBlock(blocks[3], None, 512, 2048, 2, **kwargs) self.pool5 = lambda x: F.average(x, axis=(2, 3)) self.fc6 = L.Linear(None, param['n_class'], **fc_kwargs) self.prob = F.softmax if path: chainer.serializers.load_npz(path, self)
[ "def", "__init__", "(", "self", ",", "n_layer", ",", "n_class", "=", "None", ",", "pretrained_model", "=", "None", ",", "mean", "=", "None", ",", "initialW", "=", "None", ",", "fc_kwargs", "=", "{", "}", ")", ":", "blocks", "=", "self", ".", "_blocks...
https://github.com/chainer/chainercv/blob/7159616642e0be7c5b3ef380b848e16b7e99355b/chainercv/links/model/senet/se_resnet.py#L104-L142
gcovr/gcovr
09e89b5287fa5a11408a208cb34aea0efd19d4f5
noxfile.py
python
upload_wheel
(session: nox.Session)
Upload the wheel.
Upload the wheel.
[ "Upload", "the", "wheel", "." ]
def upload_wheel(session: nox.Session) -> None: """Upload the wheel.""" session.install("twine") session.run("twine", "upload", "dist/*", external=True)
[ "def", "upload_wheel", "(", "session", ":", "nox", ".", "Session", ")", "->", "None", ":", "session", ".", "install", "(", "\"twine\"", ")", "session", ".", "run", "(", "\"twine\"", ",", "\"upload\"", ",", "\"dist/*\"", ",", "external", "=", "True", ")" ...
https://github.com/gcovr/gcovr/blob/09e89b5287fa5a11408a208cb34aea0efd19d4f5/noxfile.py#L183-L186
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/setuptools/command/egg_info.py
python
FileList._repair
(self)
Replace self.files with only safe paths Because some owners of FileList manipulate the underlying ``files`` attribute directly, this method must be called to repair those paths.
Replace self.files with only safe paths
[ "Replace", "self", ".", "files", "with", "only", "safe", "paths" ]
def _repair(self): """ Replace self.files with only safe paths Because some owners of FileList manipulate the underlying ``files`` attribute directly, this method must be called to repair those paths. """ self.files = list(filter(self._safe_path, self.files))
[ "def", "_repair", "(", "self", ")", ":", "self", ".", "files", "=", "list", "(", "filter", "(", "self", ".", "_safe_path", ",", "self", ".", "files", ")", ")" ]
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/setuptools/command/egg_info.py#L483-L491
ilastik/ilastik
6acd2c554bc517e9c8ddad3623a7aaa2e6970c28
lazyflow/request/request.py
python
Request.reset_thread_pool
(cls, num_workers=min(multiprocessing.cpu_count(), 8))
Change the number of threads allocated to the request system. :param num_workers: How many threads to create in the threadpool. Note: Beyond a certain point, we don't benefit from extra workers, even on machines with many CPUs. For more details, see: https://github.com/ilastik/ilastik/issues/1458 As a special case, you may set ``num_workers`` to 0. In that case, the normal thread pool is not used at all. Instead, all requests will execute synchronously, from within the submitting thread. Utilities like ``RequestLock``, ``SimpleRequestCondition`` will use alternate implementations based on equivalent classes in the builtin ``threading`` module. .. note:: It is only valid to call this function during startup. Any existing requests will be dropped from the pool!
Change the number of threads allocated to the request system.
[ "Change", "the", "number", "of", "threads", "allocated", "to", "the", "request", "system", "." ]
def reset_thread_pool(cls, num_workers=min(multiprocessing.cpu_count(), 8)): """ Change the number of threads allocated to the request system. :param num_workers: How many threads to create in the threadpool. Note: Beyond a certain point, we don't benefit from extra workers, even on machines with many CPUs. For more details, see: https://github.com/ilastik/ilastik/issues/1458 As a special case, you may set ``num_workers`` to 0. In that case, the normal thread pool is not used at all. Instead, all requests will execute synchronously, from within the submitting thread. Utilities like ``RequestLock``, ``SimpleRequestCondition`` will use alternate implementations based on equivalent classes in the builtin ``threading`` module. .. note:: It is only valid to call this function during startup. Any existing requests will be dropped from the pool! """ with cls.class_lock: active_count = 0 if cls.global_thread_pool is not None: cls.global_thread_pool.stop() cls.global_thread_pool = threadPool.ThreadPool(num_workers)
[ "def", "reset_thread_pool", "(", "cls", ",", "num_workers", "=", "min", "(", "multiprocessing", ".", "cpu_count", "(", ")", ",", "8", ")", ")", ":", "with", "cls", ".", "class_lock", ":", "active_count", "=", "0", "if", "cls", ".", "global_thread_pool", ...
https://github.com/ilastik/ilastik/blob/6acd2c554bc517e9c8ddad3623a7aaa2e6970c28/lazyflow/request/request.py#L121-L145
magenta/magenta
be6558f1a06984faff6d6949234f5fe9ad0ffdb5
magenta/models/image_stylization/image_utils.py
python
load_np_image_uint8
(image_file)
Loads an image as a numpy array. Args: image_file: str. Image file. Returns: A 3-D numpy array of shape [image_size, image_size, 3] and dtype uint8, with values in [0, 255].
Loads an image as a numpy array.
[ "Loads", "an", "image", "as", "a", "numpy", "array", "." ]
def load_np_image_uint8(image_file): """Loads an image as a numpy array. Args: image_file: str. Image file. Returns: A 3-D numpy array of shape [image_size, image_size, 3] and dtype uint8, with values in [0, 255]. """ with tempfile.NamedTemporaryFile() as f: f.write(tf.gfile.GFile(image_file, 'rb').read()) f.flush() image = skimage.io.imread(f.name) # Workaround for black-and-white images if image.ndim == 2: image = np.tile(image[:, :, None], (1, 1, 3)) return image
[ "def", "load_np_image_uint8", "(", "image_file", ")", ":", "with", "tempfile", ".", "NamedTemporaryFile", "(", ")", "as", "f", ":", "f", ".", "write", "(", "tf", ".", "gfile", ".", "GFile", "(", "image_file", ",", "'rb'", ")", ".", "read", "(", ")", ...
https://github.com/magenta/magenta/blob/be6558f1a06984faff6d6949234f5fe9ad0ffdb5/magenta/models/image_stylization/image_utils.py#L385-L402
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/27/Lib/xmlrpclib.py
python
ServerProxy.__call__
(self, attr)
A workaround to get special attributes on the ServerProxy without interfering with the magic __getattr__
A workaround to get special attributes on the ServerProxy without interfering with the magic __getattr__
[ "A", "workaround", "to", "get", "special", "attributes", "on", "the", "ServerProxy", "without", "interfering", "with", "the", "magic", "__getattr__" ]
def __call__(self, attr): """A workaround to get special attributes on the ServerProxy without interfering with the magic __getattr__ """ if attr == "close": return self.__close elif attr == "transport": return self.__transport raise AttributeError("Attribute %r not found" % (attr,))
[ "def", "__call__", "(", "self", ",", "attr", ")", ":", "if", "attr", "==", "\"close\"", ":", "return", "self", ".", "__close", "elif", "attr", "==", "\"transport\"", ":", "return", "self", ".", "__transport", "raise", "AttributeError", "(", "\"Attribute %r n...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/xmlrpclib.py#L1625-L1633
whoosh-community/whoosh
5421f1ab3bb802114105b3181b7ce4f44ad7d0bb
src/whoosh/searching.py
python
Results.__iter__
(self)
Yields a :class:`Hit` object for each result in ranked order.
Yields a :class:`Hit` object for each result in ranked order.
[ "Yields", "a", ":", "class", ":", "Hit", "object", "for", "each", "result", "in", "ranked", "order", "." ]
def __iter__(self): """Yields a :class:`Hit` object for each result in ranked order. """ for i in xrange(len(self.top_n)): yield Hit(self, self.top_n[i][1], i, self.top_n[i][0])
[ "def", "__iter__", "(", "self", ")", ":", "for", "i", "in", "xrange", "(", "len", "(", "self", ".", "top_n", ")", ")", ":", "yield", "Hit", "(", "self", ",", "self", ".", "top_n", "[", "i", "]", "[", "1", "]", ",", "i", ",", "self", ".", "t...
https://github.com/whoosh-community/whoosh/blob/5421f1ab3bb802114105b3181b7ce4f44ad7d0bb/src/whoosh/searching.py#L1000-L1005
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/cnt/commands/EditNanotube/EditNanotube_GraphicsMode.py
python
EditNanotube_GraphicsMode.leftUp
(self, event)
return
Method called during Left up event.
Method called during Left up event.
[ "Method", "called", "during", "Left", "up", "event", "." ]
def leftUp(self, event): """ Method called during Left up event. """ _superclass.leftUp(self, event) self.update_selobj(event) self.update_cursor() self.o.gl_update() #Reset the flag that decides whether to draw the handles. This flag is #set during left dragging, when no handle is 'grabbed'. See the #class definition for more details about this flag. if self.command and self.command.handles: if not self._handleDrawingRequested: self._handleDrawingRequested = True pass pass return
[ "def", "leftUp", "(", "self", ",", "event", ")", ":", "_superclass", ".", "leftUp", "(", "self", ",", "event", ")", "self", ".", "update_selobj", "(", "event", ")", "self", ".", "update_cursor", "(", ")", "self", ".", "o", ".", "gl_update", "(", ")",...
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/cnt/commands/EditNanotube/EditNanotube_GraphicsMode.py#L272-L289
junsukchoe/ADL
dab2e78163bd96970ec9ae41de62835332dbf4fe
tensorpack/train/base.py
python
Trainer.main_loop
(self, steps_per_epoch, starting_epoch, max_epoch)
Run the main training loop. Args: steps_per_epoch, starting_epoch, max_epoch (int):
Run the main training loop.
[ "Run", "the", "main", "training", "loop", "." ]
def main_loop(self, steps_per_epoch, starting_epoch, max_epoch): """ Run the main training loop. Args: steps_per_epoch, starting_epoch, max_epoch (int): """ with self.sess.as_default(): self.loop.config(steps_per_epoch, starting_epoch, max_epoch) self.loop.update_global_step() try: self._callbacks.before_train() # refresh global step (might have changed by callbacks) TODO ugly # what if gs is changed later? self.loop.update_global_step() for self.loop._epoch_num in range( self.loop.starting_epoch, self.loop.max_epoch + 1): logger.info("Start Epoch {} ...".format(self.loop.epoch_num)) self._callbacks.before_epoch() start_time = time.time() for self.loop._local_step in range(self.loop.steps_per_epoch): if self.hooked_sess.should_stop(): return self.run_step() # implemented by subclass self._callbacks.trigger_step() self._callbacks.after_epoch() logger.info("Epoch {} (global_step {}) finished, time:{}.".format( self.loop.epoch_num, self.loop.global_step, humanize_time_delta(time.time() - start_time))) # trigger epoch outside the timing region. self._callbacks.trigger_epoch() logger.info("Training has finished!") except (StopTraining, tf.errors.OutOfRangeError) as e: logger.info("Training was stopped by exception {}.".format(str(e))) except KeyboardInterrupt: logger.info("Detected Ctrl-C and exiting main loop.") raise finally: self._callbacks.after_train() self.hooked_sess.close()
[ "def", "main_loop", "(", "self", ",", "steps_per_epoch", ",", "starting_epoch", ",", "max_epoch", ")", ":", "with", "self", ".", "sess", ".", "as_default", "(", ")", ":", "self", ".", "loop", ".", "config", "(", "steps_per_epoch", ",", "starting_epoch", ",...
https://github.com/junsukchoe/ADL/blob/dab2e78163bd96970ec9ae41de62835332dbf4fe/tensorpack/train/base.py#L256-L295
wakatime/komodo-wakatime
8923c04ded9fa64d7374fadd8cde3a6fadfe053d
components/wakatime/packages/pygments/modeline.py
python
get_filetype_from_buffer
(buf, max_lines=5)
return None
Scan the buffer for modelines and return filetype if one is found.
Scan the buffer for modelines and return filetype if one is found.
[ "Scan", "the", "buffer", "for", "modelines", "and", "return", "filetype", "if", "one", "is", "found", "." ]
def get_filetype_from_buffer(buf, max_lines=5): """ Scan the buffer for modelines and return filetype if one is found. """ lines = buf.splitlines() for l in lines[-1:-max_lines-1:-1]: ret = get_filetype_from_line(l) if ret: return ret for i in range(max_lines, -1, -1): if i < len(lines): ret = get_filetype_from_line(lines[i]) if ret: return ret return None
[ "def", "get_filetype_from_buffer", "(", "buf", ",", "max_lines", "=", "5", ")", ":", "lines", "=", "buf", ".", "splitlines", "(", ")", "for", "l", "in", "lines", "[", "-", "1", ":", "-", "max_lines", "-", "1", ":", "-", "1", "]", ":", "ret", "=",...
https://github.com/wakatime/komodo-wakatime/blob/8923c04ded9fa64d7374fadd8cde3a6fadfe053d/components/wakatime/packages/pygments/modeline.py#L29-L44
eblot/pyftdi
72797e5ae0945d6f771f13102d7fccac255d83d7
pyftdi/misc.py
python
EasyDict.mirror
(self)
return EasyDict({v: k for k, v in self.items()})
Instanciate a mirror EasyDict.
Instanciate a mirror EasyDict.
[ "Instanciate", "a", "mirror", "EasyDict", "." ]
def mirror(self) -> 'EasyDict': """Instanciate a mirror EasyDict.""" return EasyDict({v: k for k, v in self.items()})
[ "def", "mirror", "(", "self", ")", "->", "'EasyDict'", ":", "return", "EasyDict", "(", "{", "v", ":", "k", "for", "k", ",", "v", "in", "self", ".", "items", "(", ")", "}", ")" ]
https://github.com/eblot/pyftdi/blob/72797e5ae0945d6f771f13102d7fccac255d83d7/pyftdi/misc.py#L343-L345
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/case_search/models.py
python
_flatten_multi_value_dict_values
(value)
return {k: _flatten_singleton_list(v) for k, v in value.items()}
[]
def _flatten_multi_value_dict_values(value): return {k: _flatten_singleton_list(v) for k, v in value.items()}
[ "def", "_flatten_multi_value_dict_values", "(", "value", ")", ":", "return", "{", "k", ":", "_flatten_singleton_list", "(", "v", ")", "for", "k", ",", "v", "in", "value", ".", "items", "(", ")", "}" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/case_search/models.py#L40-L41
openassistant/oa-core
5e8151edff872d7810ad4580add4fb8d9fdc1081
oa/modules/mind/__init__.py
python
set_mind
(name, history=True)
return oa.legacy.mind
Activate new mind.
Activate new mind.
[ "Activate", "new", "mind", "." ]
def set_mind(name, history=True): """ Activate new mind. """ _logger.info('Opening Mind: {}'.format(name)) if history: _history.append(name) oa.legacy.mind = oa.legacy.minds[name] return oa.legacy.mind
[ "def", "set_mind", "(", "name", ",", "history", "=", "True", ")", ":", "_logger", ".", "info", "(", "'Opening Mind: {}'", ".", "format", "(", "name", ")", ")", "if", "history", ":", "_history", ".", "append", "(", "name", ")", "oa", ".", "legacy", "....
https://github.com/openassistant/oa-core/blob/5e8151edff872d7810ad4580add4fb8d9fdc1081/oa/modules/mind/__init__.py#L41-L48
biolab/orange2
db40a9449cb45b507d63dcd5739b223f9cffb8e6
Orange/OrangeCanvas/registry/description.py
python
CategoryDescription.from_package
(cls, package)
return CategoryDescription( name=name, qualified_name=qualified_name, description=description, long_description=long_description, help=help, author=author, author_email=author_email, maintainer=maintainer, maintainer_email=maintainer_email, url=url, keywords=keywords, widgets=widgets, priority=priority, icon=icon, background=background, hidden=hidden)
Get the CategoryDescription from a package. Parameters ---------- package : `module` or `str` A package containing the category.
Get the CategoryDescription from a package.
[ "Get", "the", "CategoryDescription", "from", "a", "package", "." ]
def from_package(cls, package): """ Get the CategoryDescription from a package. Parameters ---------- package : `module` or `str` A package containing the category. """ if isinstance(package, basestring): package = __import__(package, fromlist=[""]) package_name = package.__name__ qualified_name = package_name default_name = package_name.rsplit(".", 1)[-1] name = getattr(package, "NAME", default_name) description = getattr(package, "DESCRIPTION", None) long_description = getattr(package, "LONG_DESCRIPTION", None) author = getattr(package, "AUTHOR", None) author_email = getattr(package, "AUTHOR_EMAIL", None) maintainer = getattr(package, "MAINTAINER", None) maintainer_email = getattr(package, "MAINTAINER_MAIL", None) url = getattr(package, "URL", None) help = getattr(package, "HELP", None) keywords = getattr(package, "KEYWORDS", None) widgets = getattr(package, "WIDGETS", None) priority = getattr(package, "PRIORITY", sys.maxint - 1) icon = getattr(package, "ICON", None) background = getattr(package, "BACKGROUND", None) hidden = getattr(package, "HIDDEN", None) if priority == sys.maxint - 1 and name.lower() == "prototypes": priority = sys.maxint return CategoryDescription( name=name, qualified_name=qualified_name, description=description, long_description=long_description, help=help, author=author, author_email=author_email, maintainer=maintainer, maintainer_email=maintainer_email, url=url, keywords=keywords, widgets=widgets, priority=priority, icon=icon, background=background, hidden=hidden)
[ "def", "from_package", "(", "cls", ",", "package", ")", ":", "if", "isinstance", "(", "package", ",", "basestring", ")", ":", "package", "=", "__import__", "(", "package", ",", "fromlist", "=", "[", "\"\"", "]", ")", "package_name", "=", "package", ".", ...
https://github.com/biolab/orange2/blob/db40a9449cb45b507d63dcd5739b223f9cffb8e6/Orange/OrangeCanvas/registry/description.py#L522-L573
criteo/biggraphite
1f647ada6b3f2b2f3fb4e59d326f73a2c891fc30
tools/elasticsearch/import-metrics.py
python
create_metric
(es, row, labels=None)
Create a metric.
Create a metric.
[ "Create", "a", "metric", "." ]
def create_metric(es, row, labels=None): """Create a metric.""" metric, config, created_on, uid, read_on, updated_on = row print(metric, labels) if labels: # Make sure there are no collisions for labelled metrics doc_id = chr((ord(uid[0]) + 1) % 254) + uid[1:] else: doc_id = uid es.create( index=INDEX_PREFIX + "metrics", doc_type="_doc", id=doc_id, body=document(metric, config, created_on, updated_on, read_on, uid, labels), ignore=409, )
[ "def", "create_metric", "(", "es", ",", "row", ",", "labels", "=", "None", ")", ":", "metric", ",", "config", ",", "created_on", ",", "uid", ",", "read_on", ",", "updated_on", "=", "row", "print", "(", "metric", ",", "labels", ")", "if", "labels", ":...
https://github.com/criteo/biggraphite/blob/1f647ada6b3f2b2f3fb4e59d326f73a2c891fc30/tools/elasticsearch/import-metrics.py#L114-L131
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-darwin/x64/cryptography/hazmat/backends/openssl/decode_asn1.py
python
_decode_general_name
(backend, gn)
[]
def _decode_general_name(backend, gn): if gn.type == backend._lib.GEN_DNS: # Convert to bytes and then decode to utf8. We don't use # asn1_string_to_utf8 here because it doesn't properly convert # utf8 from ia5strings. data = _asn1_string_to_bytes(backend, gn.d.dNSName).decode("utf8") # We don't use the constructor for DNSName so we can bypass validation # This allows us to create DNSName objects that have unicode chars # when a certificate (against the RFC) contains them. return x509.DNSName._init_without_validation(data) elif gn.type == backend._lib.GEN_URI: # Convert to bytes and then decode to utf8. We don't use # asn1_string_to_utf8 here because it doesn't properly convert # utf8 from ia5strings. data = _asn1_string_to_bytes( backend, gn.d.uniformResourceIdentifier ).decode("utf8") # We don't use the constructor for URI so we can bypass validation # This allows us to create URI objects that have unicode chars # when a certificate (against the RFC) contains them. return x509.UniformResourceIdentifier._init_without_validation(data) elif gn.type == backend._lib.GEN_RID: oid = _obj2txt(backend, gn.d.registeredID) return x509.RegisteredID(x509.ObjectIdentifier(oid)) elif gn.type == backend._lib.GEN_IPADD: data = _asn1_string_to_bytes(backend, gn.d.iPAddress) data_len = len(data) if data_len == 8 or data_len == 32: # This is an IPv4 or IPv6 Network and not a single IP. This # type of data appears in Name Constraints. Unfortunately, # ipaddress doesn't support packed bytes + netmask. Additionally, # IPv6Network can only handle CIDR rather than the full 16 byte # netmask. To handle this we convert the netmask to integer, then # find the first 0 bit, which will be the prefix. If another 1 # bit is present after that the netmask is invalid. base = ipaddress.ip_address(data[:data_len // 2]) netmask = ipaddress.ip_address(data[data_len // 2:]) bits = bin(int(netmask))[2:] prefix = bits.find('0') # If no 0 bits are found it is a /32 or /128 if prefix == -1: prefix = len(bits) if "1" in bits[prefix:]: raise ValueError("Invalid netmask") ip = ipaddress.ip_network(base.exploded + u"/{0}".format(prefix)) else: ip = ipaddress.ip_address(data) return x509.IPAddress(ip) elif gn.type == backend._lib.GEN_DIRNAME: return x509.DirectoryName( _decode_x509_name(backend, gn.d.directoryName) ) elif gn.type == backend._lib.GEN_EMAIL: # Convert to bytes and then decode to utf8. We don't use # asn1_string_to_utf8 here because it doesn't properly convert # utf8 from ia5strings. data = _asn1_string_to_bytes(backend, gn.d.rfc822Name).decode("utf8") # We don't use the constructor for RFC822Name so we can bypass # validation. This allows us to create RFC822Name objects that have # unicode chars when a certificate (against the RFC) contains them. return x509.RFC822Name._init_without_validation(data) elif gn.type == backend._lib.GEN_OTHERNAME: type_id = _obj2txt(backend, gn.d.otherName.type_id) value = _asn1_to_der(backend, gn.d.otherName.value) return x509.OtherName(x509.ObjectIdentifier(type_id), value) else: # x400Address or ediPartyName raise x509.UnsupportedGeneralNameType( "{0} is not a supported type".format( x509._GENERAL_NAMES.get(gn.type, gn.type) ), gn.type )
[ "def", "_decode_general_name", "(", "backend", ",", "gn", ")", ":", "if", "gn", ".", "type", "==", "backend", ".", "_lib", ".", "GEN_DNS", ":", "# Convert to bytes and then decode to utf8. We don't use", "# asn1_string_to_utf8 here because it doesn't properly convert", "# u...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/cryptography/hazmat/backends/openssl/decode_asn1.py#L89-L164
cogitas3d/OrtogOnBlender
881e93f5beb2263e44c270974dd0e81deca44762
DinamicaMole.py
python
GeraNarizDinamicaMole
()
[]
def GeraNarizDinamicaMole(): foundTrichion = 'Trichion' in bpy.data.objects foundRadix = 'Radix' in bpy.data.objects foundTipofNose = 'Tip of Nose' in bpy.data.objects foundAlarGrooveright = 'Alar Groove right' in bpy.data.objects foundAlarGrooveleft = 'Alar Groove left' in bpy.data.objects foundSubmental = 'Submental' in bpy.data.objects if foundTrichion == True and foundRadix == True and foundTipofNose == True and foundAlarGrooveright == True and foundAlarGrooveleft == True and foundSubmental == True: print("Pontos do nariz presentes!") def InverseMatrix(): context = bpy.context ob = context.object constraints = [(pb, c) for pb in ob.pose.bones for c in pb.constraints if c.type == 'CHILD_OF'] cmd = 'SET' # or 'SET' for pb, c in constraints: if cmd == 'CLEAR': c.inverse_matrix = Matrix.Identity(4) elif cmd == 'SET': if c.target: M = ob.convert_space(pose_bone=pb, matrix=c.target.matrix_world, from_space='WORLD', to_space='POSE') P = Matrix.Identity(4).lerp(M, c.influence) c.inverse_matrix = P.inverted() # toggle a property target = c.target c.target = None c.target = target #pb.constraints.update() # Captura objetos ListaPontos = ['Radix', 'Tip of Nose', 'Alar Groove left', 'Alar Groove right', 'Trichion', 'Submental'] print("LEITURA FEITA!") for i in ListaPontos: # print("HÁ O NOME!", i.name) bpy.ops.object.select_all(action='DESELECT') ObjetoAtual = bpy.data.objects[i] ObjetoAtual.select_set(True) bpy.context.view_layer.objects.active = ObjetoAtual bpy.ops.object.duplicate() NovoNome = str(bpy.data.objects[i].name)+"_COPY_NOSE_DEFORM" bpy.context.object.name = NovoNome bpy.ops.object.parent_clear(type='CLEAR_KEEP_TRANSFORM') bpy.ops.object.select_all(action='DESELECT') EMPNasionSoft = bpy.data.objects["Radix_COPY_NOSE_DEFORM"] EMPPNPoint = bpy.data.objects["Tip of Nose_COPY_NOSE_DEFORM"] EMPAlaL = bpy.data.objects["Alar Groove left_COPY_NOSE_DEFORM"] EMPAlaR = bpy.data.objects["Alar Groove right_COPY_NOSE_DEFORM"] EMPTopHead = bpy.data.objects["Trichion_COPY_NOSE_DEFORM"] EMPBottomHead = bpy.data.objects["Submental_COPY_NOSE_DEFORM"] # Adiciona Empty Sphere bpy.ops.object.select_all(action='DESELECT') bpy.ops.object.empty_add(type='SPHERE', radius=7, view_align=False, location=EMPPNPoint.location) bpy.context.object.name = "EMPNoseUpDown" EMPNoseUpDown = bpy.data.objects["EMPNoseUpDown"] bpy.ops.object.constraint_add(type='TRANSFORM') bpy.context.object.constraints["Transformation"].target = bpy.data.objects["ma"] bpy.context.object.constraints["Transformation"].use_motion_extrapolate = True bpy.context.object.constraints["Transformation"].from_max_y = 10 bpy.context.object.constraints["Transformation"].map_to_x_from = 'Y' bpy.context.object.constraints["Transformation"].map_to_y_from = 'Y' bpy.context.object.constraints["Transformation"].map_to_z_from = 'Y' bpy.context.object.constraints["Transformation"].to_max_z = -5 # O CURSOR TEM QUE ESTAR NA ORIGEM TOTAL #bpy.context.area.spaces[1].pivot_point='CURSOR' # ANTIGO 2.79 bpy.context.scene.tool_settings.transform_pivot_point = 'CURSOR' #bpy.context.area.spaces[1].cursor_location = (0.0, 0.0, 0.0) # ANTIGO 2.79 bpy.context.scene.cursor.location = 0,0,0 # Adiciona Armature em modo de edição bpy.ops.object.armature_add(radius=1, view_align=False, enter_editmode=True) # Desseleciona tudo #bpy.ops.armature.select_all(action='TOGGLE') # Modifica posição dos bones #bpy.context.object.data.edit_bones["Bone"].head = Vector((1.0, 2.0, 3.0)) bpy.context.object.data.edit_bones["Bone"].name = "Nose" bpy.context.object.data.edit_bones["Nose"].head = EMPPNPoint.location bpy.context.object.data.edit_bones["Nose"].tail = EMPNasionSoft.location # Adiciona Asa Esquerda bpy.ops.armature.bone_primitive_add() bpy.context.object.data.edit_bones["Bone"].name = "AlaL" bpy.context.object.data.edit_bones["AlaL"].head = EMPPNPoint.location bpy.context.object.data.edit_bones["AlaL"].tail = EMPAlaL.location # Adiciona Asa Direita bpy.ops.armature.bone_primitive_add() bpy.context.object.data.edit_bones["Bone"].name = "AlaR" bpy.context.object.data.edit_bones["AlaR"].head = EMPPNPoint.location bpy.context.object.data.edit_bones["AlaR"].tail = EMPAlaR.location # Adiciona Nariz bpy.context.scene.tool_settings.transform_pivot_point = 'CURSOR' bpy.context.scene.cursor.location = EMPPNPoint.location bpy.ops.armature.bone_primitive_add() bpy.context.object.data.edit_bones["Bone"].name = "IK_Nose" bpy.context.object.data.edit_bones["IK_Nose"].use_deform = False # Adicionar Top Bottom bpy.ops.armature.bone_primitive_add() bpy.context.object.data.edit_bones["Bone"].name = "TopBottomHead" bpy.context.object.data.edit_bones["TopBottomHead"].head = EMPTopHead.location bpy.context.object.data.edit_bones["TopBottomHead"].tail = EMPBottomHead.location # Parentamento bpy.context.object.data.edit_bones["Nose"].parent = bpy.context.object.data.edit_bones['IK_Nose'] bpy.context.object.data.edit_bones["AlaL"].parent = bpy.context.object.data.edit_bones['IK_Nose'] bpy.context.object.data.edit_bones["AlaR"].parent = bpy.context.object.data.edit_bones['IK_Nose'] # bpy.context.object.data.draw_type = 'ENVELOPE' # ANTIGO 2.78 bpy.context.object.data.display_type = 'ENVELOPE' # Aumenta tamanho envelope bpy.ops.object.mode_set(mode='EDIT') bpy.context.object.data.edit_bones["Nose"].head_radius=8.5 bpy.context.object.data.edit_bones["AlaL"].head_radius=8.5 bpy.context.object.data.edit_bones["AlaR"].head_radius=8.5 bpy.context.object.data.edit_bones["Nose"].tail_radius=3.5 bpy.context.object.data.edit_bones["AlaL"].tail_radius=3.5 bpy.context.object.data.edit_bones["AlaR"].tail_radius=3.5 #bpy.context.object.data.edit_bones["Nose"].select_head=True #bpy.context.object.data.edit_bones["AlaL"].select_head=True #bpy.context.object.data.edit_bones["AlaR"].select_head=True #bpy.ops.transform.transform(mode='BONE_ENVELOPE', value=(85, 0, 0, 0)) # Fazendo o constraint #obj = bpy.data.objects["Armature.002"] bpy.ops.object.mode_set(mode='OBJECT') context = bpy.context obj = context.active_object bpy.ops.object.mode_set(mode='POSE') pbase=obj.pose.bones['IK_Nose'] pbase.bone.select=True bpy.context.object.data.bones.active = bpy.context.object.data.bones['IK_Nose'] # Child Of selected_bone = pbase constraint = selected_bone.constraints ChildOf = constraint.new('CHILD_OF') ChildOf.target = EMPNoseUpDown InverseMatrix() bpy.context.object.pose.bones["IK_Nose"].constraints["Child Of"].influence = 0.5 # Track to pbase=obj.pose.bones['Nose'] pbase.bone.select=True bpy.context.object.data.bones.active = bpy.context.object.data.bones['Nose'] selected_bone = pbase constraint = selected_bone.constraints StretchTo = constraint.new('STRETCH_TO') StretchTo.target = EMPNasionSoft pbase=obj.pose.bones['AlaL'] pbase.bone.select=True bpy.context.object.data.bones.active = bpy.context.object.data.bones['AlaL'] selected_bone = pbase constraint = selected_bone.constraints StretchTo = constraint.new('STRETCH_TO') StretchTo.target = EMPAlaL pbase=obj.pose.bones['AlaR'] pbase.bone.select=True bpy.context.object.data.bones.active = bpy.context.object.data.bones['AlaR'] selected_bone = pbase constraint = selected_bone.constraints StretchTo = constraint.new('STRETCH_TO') StretchTo.target = EMPAlaR bpy.ops.object.mode_set(mode='OBJECT') Armature = context.active_object bpy.ops.object.select_all(action='DESELECT') Armature.select_set(True) # Envelope configurações bpy.ops.object.mode_set(mode='EDIT') bpy.context.object.data.edit_bones["Nose"].envelope_distance = 14 bpy.context.object.data.edit_bones["Nose"].head_radius = 5 bpy.context.object.data.edit_bones["Nose"].tail_radius = 1 bpy.context.object.data.edit_bones["AlaL"].envelope_distance = 9 bpy.context.object.data.edit_bones["AlaL"].head_radius = 9 bpy.context.object.data.edit_bones["AlaL"].tail_radius = 3.5 bpy.context.object.data.edit_bones["AlaR"].envelope_distance = 9 bpy.context.object.data.edit_bones["AlaR"].head_radius = 9 bpy.context.object.data.edit_bones["AlaR"].tail_radius = 3.5 bpy.context.object.data.edit_bones["TopBottomHead"].envelope_distance = 55 bpy.context.object.data.edit_bones["TopBottomHead"].head_radius = 22 bpy.context.object.data.edit_bones["TopBottomHead"].tail_radius = 22 # Deformação bpy.ops.object.mode_set(mode='OBJECT') #bpy.context.object.data.draw_type = 'WIRE' # ANTIGO 2.78 bpy.context.object.data.display_type = 'WIRE' bpy.ops.object.select_all(action='DESELECT') FaceMalha = bpy.data.objects['SoftTissueDynamic'] Armature.select_set(True) FaceMalha.select_set(True) bpy.context.view_layer.objects.active = Armature bpy.ops.object.parent_set(type='ARMATURE_ENVELOPE') bpy.ops.object.select_all(action='DESELECT') FaceMalha.select_set(True) bpy.context.view_layer.objects.active = FaceMalha bpy.ops.object.modifier_move_up(modifier="Armature.001") # Oculta Objetos EMPNoseUpDown.hide_viewport=True Armature.hide_viewport=True EMPNasionSoft.hide_viewport=True EMPPNPoint.hide_viewport=True EMPAlaL.hide_viewport=True EMPAlaR.hide_viewport=True EMPTopHead.hide_viewport=True EMPBottomHead.hide_viewport=True else: print("Falta algum ponto anatômico no processo.")
[ "def", "GeraNarizDinamicaMole", "(", ")", ":", "foundTrichion", "=", "'Trichion'", "in", "bpy", ".", "data", ".", "objects", "foundRadix", "=", "'Radix'", "in", "bpy", ".", "data", ".", "objects", "foundTipofNose", "=", "'Tip of Nose'", "in", "bpy", ".", "da...
https://github.com/cogitas3d/OrtogOnBlender/blob/881e93f5beb2263e44c270974dd0e81deca44762/DinamicaMole.py#L283-L555
CalebBell/thermo
572a47d1b03d49fe609b8d5f826fa6a7cde00828
thermo/chemical.py
python
Chemical.Van_der_Waals_area
(self)
return None
r'''Unnormalized Van der Waals area, in units of [m^2/mol]. Examples -------- >>> Chemical('hexane').Van_der_Waals_area 964000.0
r'''Unnormalized Van der Waals area, in units of [m^2/mol].
[ "r", "Unnormalized", "Van", "der", "Waals", "area", "in", "units", "of", "[", "m^2", "/", "mol", "]", "." ]
def Van_der_Waals_area(self): r'''Unnormalized Van der Waals area, in units of [m^2/mol]. Examples -------- >>> Chemical('hexane').Van_der_Waals_area 964000.0 ''' if self.UNIFAC_Q: return Van_der_Waals_area(self.UNIFAC_Q) return None
[ "def", "Van_der_Waals_area", "(", "self", ")", ":", "if", "self", ".", "UNIFAC_Q", ":", "return", "Van_der_Waals_area", "(", "self", ".", "UNIFAC_Q", ")", "return", "None" ]
https://github.com/CalebBell/thermo/blob/572a47d1b03d49fe609b8d5f826fa6a7cde00828/thermo/chemical.py#L1821-L1831
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/logic/utilities/dimacs.py
python
load
(s)
return And(*clauses)
Loads a boolean expression from a string. Examples ======== >>> from sympy.logic.utilities.dimacs import load >>> load('1') cnf_1 >>> load('1 2') cnf_1 | cnf_2 >>> load('1 \\n 2') cnf_1 & cnf_2 >>> load('1 2 \\n 3') cnf_3 & (cnf_1 | cnf_2)
Loads a boolean expression from a string.
[ "Loads", "a", "boolean", "expression", "from", "a", "string", "." ]
def load(s): """Loads a boolean expression from a string. Examples ======== >>> from sympy.logic.utilities.dimacs import load >>> load('1') cnf_1 >>> load('1 2') cnf_1 | cnf_2 >>> load('1 \\n 2') cnf_1 & cnf_2 >>> load('1 2 \\n 3') cnf_3 & (cnf_1 | cnf_2) """ clauses = [] lines = s.split('\n') pComment = re.compile(r'c.*') pStats = re.compile(r'p\s*cnf\s*(\d*)\s*(\d*)') while len(lines) > 0: line = lines.pop(0) # Only deal with lines that aren't comments if not pComment.match(line): m = pStats.match(line) if not m: nums = line.rstrip('\n').split(' ') list = [] for lit in nums: if lit != '': if int(lit) == 0: continue num = abs(int(lit)) sign = True if int(lit) < 0: sign = False if sign: list.append(Symbol("cnf_%s" % num)) else: list.append(~Symbol("cnf_%s" % num)) if len(list) > 0: clauses.append(Or(*list)) return And(*clauses)
[ "def", "load", "(", "s", ")", ":", "clauses", "=", "[", "]", "lines", "=", "s", ".", "split", "(", "'\\n'", ")", "pComment", "=", "re", ".", "compile", "(", "r'c.*'", ")", "pStats", "=", "re", ".", "compile", "(", "r'p\\s*cnf\\s*(\\d*)\\s*(\\d*)'", "...
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/logic/utilities/dimacs.py#L12-L62
Kolifanes/plugin.video.youtube
834998dfb52a9be71a5de8efe9808ec713bc2e04
resources/lib/kodion/impl/abstract_logger.py
python
AbstractLogger.log
(self, text, log_level=constants.log.NOTICE)
Needs to be implemented by a mock for testing or the real deal. Logging. :param text: :param log_level: :return:
Needs to be implemented by a mock for testing or the real deal. Logging. :param text: :param log_level: :return:
[ "Needs", "to", "be", "implemented", "by", "a", "mock", "for", "testing", "or", "the", "real", "deal", ".", "Logging", ".", ":", "param", "text", ":", ":", "param", "log_level", ":", ":", "return", ":" ]
def log(self, text, log_level=constants.log.NOTICE): """ Needs to be implemented by a mock for testing or the real deal. Logging. :param text: :param log_level: :return: """ raise NotImplementedError()
[ "def", "log", "(", "self", ",", "text", ",", "log_level", "=", "constants", ".", "log", ".", "NOTICE", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/Kolifanes/plugin.video.youtube/blob/834998dfb52a9be71a5de8efe9808ec713bc2e04/resources/lib/kodion/impl/abstract_logger.py#L10-L18
ulif/diceware
5d909b5e2f8efdd8dfe53a4f68c50f7710961dc0
diceware/config.py
python
get_configparser
(path_list=None)
return found, parser
Parse `path_list` for config values. If no list is given we use `valid_locations()`. Return a list of paths read and a config parser instance.
Parse `path_list` for config values.
[ "Parse", "path_list", "for", "config", "values", "." ]
def get_configparser(path_list=None): """Parse `path_list` for config values. If no list is given we use `valid_locations()`. Return a list of paths read and a config parser instance. """ if path_list is None: path_list = valid_locations() parser = SafeParser() found = parser.read(path_list) return found, parser
[ "def", "get_configparser", "(", "path_list", "=", "None", ")", ":", "if", "path_list", "is", "None", ":", "path_list", "=", "valid_locations", "(", ")", "parser", "=", "SafeParser", "(", ")", "found", "=", "parser", ".", "read", "(", "path_list", ")", "r...
https://github.com/ulif/diceware/blob/5d909b5e2f8efdd8dfe53a4f68c50f7710961dc0/diceware/config.py#L56-L67
inducer/loopy
55143b21711a534c07bbb14aaa63ff3879a93433
loopy/kernel/function_interface.py
python
InKernelCallable.get_used_hw_axes
(self, callables_table)
Returns a tuple ``group_axes_used, local_axes_used``, where ``(group|local)_axes_used`` are :class:`frozenset` of hardware axes indices used by the callable.
Returns a tuple ``group_axes_used, local_axes_used``, where ``(group|local)_axes_used`` are :class:`frozenset` of hardware axes indices used by the callable.
[ "Returns", "a", "tuple", "group_axes_used", "local_axes_used", "where", "(", "group|local", ")", "_axes_used", "are", ":", "class", ":", "frozenset", "of", "hardware", "axes", "indices", "used", "by", "the", "callable", "." ]
def get_used_hw_axes(self, callables_table): """ Returns a tuple ``group_axes_used, local_axes_used``, where ``(group|local)_axes_used`` are :class:`frozenset` of hardware axes indices used by the callable. """ raise NotImplementedError
[ "def", "get_used_hw_axes", "(", "self", ",", "callables_table", ")", ":", "raise", "NotImplementedError" ]
https://github.com/inducer/loopy/blob/55143b21711a534c07bbb14aaa63ff3879a93433/loopy/kernel/function_interface.py#L423-L429
mozilla/dxr
ef09324a32930e2769e6ff63eaa8de76fcf79ee3
dxr/plugins/rust/__init__.py
python
TreeToIndex.fixup_sub_mods_impl
(self, table_name, table_ref_name)
NOTE table_name and table_ref_name should not come from user input, otherwise there is potential for SQL injection attacks.
NOTE table_name and table_ref_name should not come from user input, otherwise there is potential for SQL injection attacks.
[ "NOTE", "table_name", "and", "table_ref_name", "should", "not", "come", "from", "user", "input", "otherwise", "there", "is", "potential", "for", "SQL", "injection", "attacks", "." ]
def fixup_sub_mods_impl(self, table_name, table_ref_name): """ NOTE table_name and table_ref_name should not come from user input, otherwise there is potential for SQL injection attacks. """ # First create refids for module refs whose qualnames match the qualname of # the module (i.e., no aliases). table_refs = getattr(self.data, table_ref_name) table_by_name = self.data.index(table_name, 'qualname') for v in table_refs: if v['refid'] > 0: continue if v['qualname'] and v['qualname'] in table_by_name: v['refid'] = table_by_name[v['qualname']][0]['id'] # We do our own scpoing of aliases and it is kinda nasty. We keep a record # of a reflexive, transitive 'inside' relation for scopes in impl. So we # check that the alias is outside the reference to the alias. # XXX This does not take into account overriding/shadowing, so if there is # an alias in a smaller scope which hides an outer alias, it is chance which # you will get. if table_name == 'modules': # Next account for where the path is an aliased modules e.g., alias::c, # where c is already accounted for. module_aliases_by_scope = self.data.index('module_aliases', 'scopeid') module_refs_0 = [item for item in self.data.module_refs if item['refid'] == -1] for mod_ref in module_refs_0: if mod_ref['scopeid'] not in self.scope_inheritance: continue parent_ids = self.scope_inheritance[mod_ref['scopeid']] for parent_id in parent_ids: if parent_id in module_aliases_by_scope: for alias in module_aliases_by_scope[parent_id]: if alias['name'] == mod_ref['qualname']: qualname = str(parent_id) +"$" + alias['name'] mod_ref['qualname'] = qualname mod = None id = alias['refid'] if id in self.data.modules: mod = self.data.modules[id] elif id in self.data.extern_crate_mods: mod = self.data.extern_crate_mods[id] if mod: mod_ref['refid'] = mod['id'] mod_ref['aliasid'] = alias['id']
[ "def", "fixup_sub_mods_impl", "(", "self", ",", "table_name", ",", "table_ref_name", ")", ":", "# First create refids for module refs whose qualnames match the qualname of", "# the module (i.e., no aliases).", "table_refs", "=", "getattr", "(", "self", ".", "data", ",", "tabl...
https://github.com/mozilla/dxr/blob/ef09324a32930e2769e6ff63eaa8de76fcf79ee3/dxr/plugins/rust/__init__.py#L489-L535
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/tools/sqli/thirdparty/bottle/bottle.py
python
BaseRequest.content_type
(self)
return self.environ.get('CONTENT_TYPE', '').lower()
The Content-Type header as a lowercase-string (default: empty).
The Content-Type header as a lowercase-string (default: empty).
[ "The", "Content", "-", "Type", "header", "as", "a", "lowercase", "-", "string", "(", "default", ":", "empty", ")", "." ]
def content_type(self): ''' The Content-Type header as a lowercase-string (default: empty). ''' return self.environ.get('CONTENT_TYPE', '').lower()
[ "def", "content_type", "(", "self", ")", ":", "return", "self", ".", "environ", ".", "get", "(", "'CONTENT_TYPE'", ",", "''", ")", ".", "lower", "(", ")" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/sqli/thirdparty/bottle/bottle.py#L1154-L1156
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/helpers/event.py
python
_TrackStateChangeFiltered.async_update_listeners
(self, new_track_states: TrackStates)
Update the listeners based on the new TrackStates.
Update the listeners based on the new TrackStates.
[ "Update", "the", "listeners", "based", "on", "the", "new", "TrackStates", "." ]
def async_update_listeners(self, new_track_states: TrackStates) -> None: """Update the listeners based on the new TrackStates.""" last_track_states = self._last_track_states self._last_track_states = new_track_states had_all_listener = last_track_states.all_states if new_track_states.all_states: if had_all_listener: return self._cancel_listener(_DOMAINS_LISTENER) self._cancel_listener(_ENTITIES_LISTENER) self._setup_all_listener() return if had_all_listener: self._cancel_listener(_ALL_LISTENER) domains_changed = new_track_states.domains != last_track_states.domains if had_all_listener or domains_changed: domains_changed = True self._cancel_listener(_DOMAINS_LISTENER) self._setup_domains_listener(new_track_states.domains) if ( had_all_listener or domains_changed or new_track_states.entities != last_track_states.entities ): self._cancel_listener(_ENTITIES_LISTENER) self._setup_entities_listener( new_track_states.domains, new_track_states.entities )
[ "def", "async_update_listeners", "(", "self", ",", "new_track_states", ":", "TrackStates", ")", "->", "None", ":", "last_track_states", "=", "self", ".", "_last_track_states", "self", ".", "_last_track_states", "=", "new_track_states", "had_all_listener", "=", "last_t...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/helpers/event.py#L572-L605
aws/aws-sam-cli
2aa7bf01b2e0b0864ef63b1898a8b30577443acc
samcli/lib/warnings/sam_cli_warning.py
python
CodeDeployConditionWarning.check
(self, template_dict)
return (False, "")
Checking if template dictionary have Function with Condition and DeploymentPreferences which will trigger this warning.
Checking if template dictionary have Function with Condition and DeploymentPreferences which will trigger this warning.
[ "Checking", "if", "template", "dictionary", "have", "Function", "with", "Condition", "and", "DeploymentPreferences", "which", "will", "trigger", "this", "warning", "." ]
def check(self, template_dict): """ Checking if template dictionary have Function with Condition and DeploymentPreferences which will trigger this warning. """ functions = [ resource for (_, resource) in template_dict.get("Resources", {}).items() if resource.get("Type", "") == "AWS::Serverless::Function" ] for function in functions: if self._have_condition(function) and self._have_deployment_preferences(function): return (True, self.WARNING_MESSAGE) return (False, "")
[ "def", "check", "(", "self", ",", "template_dict", ")", ":", "functions", "=", "[", "resource", "for", "(", "_", ",", "resource", ")", "in", "template_dict", ".", "get", "(", "\"Resources\"", ",", "{", "}", ")", ".", "items", "(", ")", "if", "resourc...
https://github.com/aws/aws-sam-cli/blob/2aa7bf01b2e0b0864ef63b1898a8b30577443acc/samcli/lib/warnings/sam_cli_warning.py#L104-L117
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/numpy/oldnumeric/ma.py
python
sort
(x, axis = -1, fill_value=None)
return masked_values(s, fill_value, copy=0)
If x does not have a mask, return a masked array formed from the result of numeric.sort(x, axis). Otherwise, fill x with fill_value. Sort it. Set a mask where the result is equal to fill_value. Note that this may have unintended consequences if the data contains the fill value at a non-masked site. If fill_value is not given the default fill value for x's type will be used.
If x does not have a mask, return a masked array formed from the result of numeric.sort(x, axis). Otherwise, fill x with fill_value. Sort it. Set a mask where the result is equal to fill_value. Note that this may have unintended consequences if the data contains the fill value at a non-masked site.
[ "If", "x", "does", "not", "have", "a", "mask", "return", "a", "masked", "array", "formed", "from", "the", "result", "of", "numeric", ".", "sort", "(", "x", "axis", ")", ".", "Otherwise", "fill", "x", "with", "fill_value", ".", "Sort", "it", ".", "Set...
def sort (x, axis = -1, fill_value=None): """If x does not have a mask, return a masked array formed from the result of numeric.sort(x, axis). Otherwise, fill x with fill_value. Sort it. Set a mask where the result is equal to fill_value. Note that this may have unintended consequences if the data contains the fill value at a non-masked site. If fill_value is not given the default fill value for x's type will be used. """ if fill_value is None: fill_value = default_fill_value (x) d = filled(x, fill_value) s = fromnumeric.sort(d, axis) if getmask(x) is nomask: return masked_array(s) return masked_values(s, fill_value, copy=0)
[ "def", "sort", "(", "x", ",", "axis", "=", "-", "1", ",", "fill_value", "=", "None", ")", ":", "if", "fill_value", "is", "None", ":", "fill_value", "=", "default_fill_value", "(", "x", ")", "d", "=", "filled", "(", "x", ",", "fill_value", ")", "s",...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/numpy/oldnumeric/ma.py#L2075-L2092
SanPen/GridCal
d3f4566d2d72c11c7e910c9d162538ef0e60df31
src/GridCal/Gui/Main/GridCalMain.py
python
MainGUI.get_selected_buses
(self)
return lst
Get the selected buses :return:
Get the selected buses :return:
[ "Get", "the", "selected", "buses", ":", "return", ":" ]
def get_selected_buses(self) -> List[Tuple[int, Bus]]: """ Get the selected buses :return: """ lst: List[Tuple[int, Bus]] = list() for k, bus in enumerate(self.circuit.buses): if bus.graphic_obj is not None: if bus.graphic_obj.isSelected(): lst.append((k, bus)) return lst
[ "def", "get_selected_buses", "(", "self", ")", "->", "List", "[", "Tuple", "[", "int", ",", "Bus", "]", "]", ":", "lst", ":", "List", "[", "Tuple", "[", "int", ",", "Bus", "]", "]", "=", "list", "(", ")", "for", "k", ",", "bus", "in", "enumerat...
https://github.com/SanPen/GridCal/blob/d3f4566d2d72c11c7e910c9d162538ef0e60df31/src/GridCal/Gui/Main/GridCalMain.py#L6192-L6202
CouchPotato/CouchPotatoServer
7260c12f72447ddb6f062367c6dfbda03ecd4e9c
libs/apscheduler/scheduler.py
python
Scheduler.start
(self)
Starts the scheduler in a new thread. In threaded mode (the default), this method will return immediately after starting the scheduler thread. In standalone mode, this method will block until there are no more scheduled jobs.
Starts the scheduler in a new thread.
[ "Starts", "the", "scheduler", "in", "a", "new", "thread", "." ]
def start(self): """ Starts the scheduler in a new thread. In threaded mode (the default), this method will return immediately after starting the scheduler thread. In standalone mode, this method will block until there are no more scheduled jobs. """ if self.running: raise SchedulerAlreadyRunningError # Create a RAMJobStore as the default if there is no default job store if not 'default' in self._jobstores: self.add_jobstore(RAMJobStore(), 'default', True) # Schedule all pending jobs for job, jobstore in self._pending_jobs: self._real_add_job(job, jobstore, False) del self._pending_jobs[:] self._stopped = False if self.standalone: self._main_loop() else: self._thread = Thread(target=self._main_loop, name='APScheduler') self._thread.setDaemon(self.daemonic) self._thread.start()
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "running", ":", "raise", "SchedulerAlreadyRunningError", "# Create a RAMJobStore as the default if there is no default job store", "if", "not", "'default'", "in", "self", ".", "_jobstores", ":", "self", ".", "a...
https://github.com/CouchPotato/CouchPotatoServer/blob/7260c12f72447ddb6f062367c6dfbda03ecd4e9c/libs/apscheduler/scheduler.py#L86-L114
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/ip_messaging/v2/service/__init__.py
python
ServiceInstance.bindings
(self)
return self._proxy.bindings
Access the bindings :returns: twilio.rest.ip_messaging.v2.service.binding.BindingList :rtype: twilio.rest.ip_messaging.v2.service.binding.BindingList
Access the bindings
[ "Access", "the", "bindings" ]
def bindings(self): """ Access the bindings :returns: twilio.rest.ip_messaging.v2.service.binding.BindingList :rtype: twilio.rest.ip_messaging.v2.service.binding.BindingList """ return self._proxy.bindings
[ "def", "bindings", "(", "self", ")", ":", "return", "self", ".", "_proxy", ".", "bindings" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/ip_messaging/v2/service/__init__.py#L796-L803
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/wagtail_bak/contrib/wagtailapi/serializers.py
python
PageSerializer.build_relational_field
(self, field_name, relation_info)
return super(PageSerializer, self).build_relational_field(field_name, relation_info)
[]
def build_relational_field(self, field_name, relation_info): # Find all relation fields that point to child class and make them use # the ChildRelationField class. if relation_info.to_many: model = getattr(self.Meta, 'model') child_relations = { child_relation.field.rel.related_name: child_relation.related_model for child_relation in get_all_child_relations(model) } if field_name in child_relations and hasattr(child_relations[field_name], 'api_fields'): return ChildRelationField, {'child_fields': child_relations[field_name].api_fields} return super(PageSerializer, self).build_relational_field(field_name, relation_info)
[ "def", "build_relational_field", "(", "self", ",", "field_name", ",", "relation_info", ")", ":", "# Find all relation fields that point to child class and make them use", "# the ChildRelationField class.", "if", "relation_info", ".", "to_many", ":", "model", "=", "getattr", "...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/wagtail_bak/contrib/wagtailapi/serializers.py#L258-L271