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
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/min/smtpd.py
python
PureProxy.__init__
(self, *args, **kwargs)
[]
def __init__(self, *args, **kwargs): if 'enable_SMTPUTF8' in kwargs and kwargs['enable_SMTPUTF8']: raise ValueError("PureProxy does not support SMTPUTF8.") super(PureProxy, self).__init__(*args, **kwargs)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'enable_SMTPUTF8'", "in", "kwargs", "and", "kwargs", "[", "'enable_SMTPUTF8'", "]", ":", "raise", "ValueError", "(", "\"PureProxy does not support SMTPUTF8.\"", ")", "s...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/smtpd.py#L747-L750
atlassian-api/atlassian-python-api
6d8545a790c3aae10b75bdc225fb5c3a0aee44db
atlassian/confluence.py
python
Confluence.delete_page_property
(self, page_id, page_property)
return response
Delete the page (content) property e.g. delete key of hash :param page_id: content_id format :param page_property: key of property :return:
Delete the page (content) property e.g. delete key of hash :param page_id: content_id format :param page_property: key of property :return:
[ "Delete", "the", "page", "(", "content", ")", "property", "e", ".", "g", ".", "delete", "key", "of", "hash", ":", "param", "page_id", ":", "content_id", "format", ":", "param", "page_property", ":", "key", "of", "property", ":", "return", ":" ]
def delete_page_property(self, page_id, page_property): """ Delete the page (content) property e.g. delete key of hash :param page_id: content_id format :param page_property: key of property :return: """ url = "rest/api/content/{page_id}/property/{page_property}".format( page_id=page_id, page_property=str(page_property) ) try: response = self.delete(path=url) except HTTPError as e: if e.response.status_code == 404: # Raise ApiError as the documented reason is ambiguous raise ApiError( "There is no content with the given id, " "or the calling user does not have permission to view the content", reason=e, ) raise return response
[ "def", "delete_page_property", "(", "self", ",", "page_id", ",", "page_property", ")", ":", "url", "=", "\"rest/api/content/{page_id}/property/{page_property}\"", ".", "format", "(", "page_id", "=", "page_id", ",", "page_property", "=", "str", "(", "page_property", ...
https://github.com/atlassian-api/atlassian-python-api/blob/6d8545a790c3aae10b75bdc225fb5c3a0aee44db/atlassian/confluence.py#L1770-L1793
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/bdf/bdf_interface/get_card.py
python
GetCard.get_mklist
(self)
return mkarray
gets the MKLIST vector from MKAERO1/MKAERO2
gets the MKLIST vector from MKAERO1/MKAERO2
[ "gets", "the", "MKLIST", "vector", "from", "MKAERO1", "/", "MKAERO2" ]
def get_mklist(self) -> np.ndarray: """gets the MKLIST vector from MKAERO1/MKAERO2""" mklist = [] mkarray = np.array([]) for mkaero in self.mkaeros: mklist += mkaero.mklist() if mklist: mkarray = np.hstack([mklist]) #new_array = [tuple(row) for row in mkarray] #unique_pairs = np.lib.arraysetops.unique(new_array, axis=0).tolist() return mkarray
[ "def", "get_mklist", "(", "self", ")", "->", "np", ".", "ndarray", ":", "mklist", "=", "[", "]", "mkarray", "=", "np", ".", "array", "(", "[", "]", ")", "for", "mkaero", "in", "self", ".", "mkaeros", ":", "mklist", "+=", "mkaero", ".", "mklist", ...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/bdf/bdf_interface/get_card.py#L1685-L1695
zetaops/ulakbus
bcc05abf17bbd6dbeec93809e4ad30885e94e83e
ulakbus/views/bap/bap_firma_basvuru_degerlendirme.py
python
BapFirmaBasvuruDegerlendirme.islem_mesaji_olustur
(self)
İşlem bitiminde, işlem mesajı oluşturulur ve gösterilir.
İşlem bitiminde, işlem mesajı oluşturulur ve gösterilir.
[ "İşlem", "bitiminde", "işlem", "mesajı", "oluşturulur", "ve", "gösterilir", "." ]
def islem_mesaji_olustur(self): """ İşlem bitiminde, işlem mesajı oluşturulur ve gösterilir. """ self.ilgili_daveti_sil() self.current.output['msgbox'] = {"type": "info", "title": _(u"Firma Başvuru Kaydı Değerlendirme"), "msg": _(u"""%s adlı firmanın kayıt başvurusu hakkındaki kararınız firma yetkilisine başarıyla iletilmiştir. """ % self.current.task_data["firma_ad"])}
[ "def", "islem_mesaji_olustur", "(", "self", ")", ":", "self", ".", "ilgili_daveti_sil", "(", ")", "self", ".", "current", ".", "output", "[", "'msgbox'", "]", "=", "{", "\"type\"", ":", "\"info\"", ",", "\"title\"", ":", "_", "(", "u\"Firma Başvuru Kaydı Değ...
https://github.com/zetaops/ulakbus/blob/bcc05abf17bbd6dbeec93809e4ad30885e94e83e/ulakbus/views/bap/bap_firma_basvuru_degerlendirme.py#L223-L233
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/plugins/attack/db/sqlmap/plugins/dbms/sybase/enumeration.py
python
Enumeration.getDbs
(self)
return kb.data.cachedDbs
[]
def getDbs(self): if len(kb.data.cachedDbs) > 0: return kb.data.cachedDbs infoMsg = "fetching database names" logger.info(infoMsg) rootQuery = queries[DBMS.SYBASE].dbs randStr = randomStr() query = rootQuery.inband.query if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct: blinds = [False, True] else: blinds = [True] for blind in blinds: retVal = pivotDumpTable("(%s) AS %s" % (query, randStr), ['%s.name' % randStr], blind=blind) if retVal: kb.data.cachedDbs = retVal[0].values()[0] break if kb.data.cachedDbs: kb.data.cachedDbs.sort() return kb.data.cachedDbs
[ "def", "getDbs", "(", "self", ")", ":", "if", "len", "(", "kb", ".", "data", ".", "cachedDbs", ")", ">", "0", ":", "return", "kb", ".", "data", ".", "cachedDbs", "infoMsg", "=", "\"fetching database names\"", "logger", ".", "info", "(", "infoMsg", ")",...
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/plugins/attack/db/sqlmap/plugins/dbms/sybase/enumeration.py#L89-L115
facebookresearch/CrypTen
90bf38b4f80726c808f322efb0ce430dcdf5e5ec
crypten/cuda/cuda_tensor.py
python
CUDALongTensor.clone
(self)
return result
Create a deep copy of the input tensor.
Create a deep copy of the input tensor.
[ "Create", "a", "deep", "copy", "of", "the", "input", "tensor", "." ]
def clone(self): """Create a deep copy of the input tensor.""" # TODO: Rename this to __deepcopy__()? result = CUDALongTensor() result._tensor = self._tensor.clone() return result
[ "def", "clone", "(", "self", ")", ":", "# TODO: Rename this to __deepcopy__()?", "result", "=", "CUDALongTensor", "(", ")", "result", ".", "_tensor", "=", "self", ".", "_tensor", ".", "clone", "(", ")", "return", "result" ]
https://github.com/facebookresearch/CrypTen/blob/90bf38b4f80726c808f322efb0ce430dcdf5e5ec/crypten/cuda/cuda_tensor.py#L149-L154
phoenix2/phoenix
2c83ee6e7c509d2a9378bcd15634a3740adf7666
phoenix2/backend/ClientBase.py
python
ClientBase._deactivateCallbacks
(self)
Shut down the runCallback function. Typically used post-disconnect.
Shut down the runCallback function. Typically used post-disconnect.
[ "Shut", "down", "the", "runCallback", "function", ".", "Typically", "used", "post", "-", "disconnect", "." ]
def _deactivateCallbacks(self): """Shut down the runCallback function. Typically used post-disconnect. """ self.callbacksActive = False
[ "def", "_deactivateCallbacks", "(", "self", ")", ":", "self", ".", "callbacksActive", "=", "False" ]
https://github.com/phoenix2/phoenix/blob/2c83ee6e7c509d2a9378bcd15634a3740adf7666/phoenix2/backend/ClientBase.py#L38-L41
CloudBotIRC/CloudBot
6c5a88f9961b6cd66a8f489a38feb2e8227ac9ea
cloudbot/clients/irc.py
python
IrcClient.__init__
(self, bot, name, nick, *, channels=None, config=None, server, port=6667, use_ssl=False, ignore_cert_errors=True, timeout=300, local_bind=False)
:type bot: cloudbot.bot.CloudBot :type name: str :type nick: str :type channels: list[str] :type config: dict[str, unknown] :type server: str :type port: int :type use_ssl: bool :type ignore_cert_errors: bool :type timeout: int
:type bot: cloudbot.bot.CloudBot :type name: str :type nick: str :type channels: list[str] :type config: dict[str, unknown] :type server: str :type port: int :type use_ssl: bool :type ignore_cert_errors: bool :type timeout: int
[ ":", "type", "bot", ":", "cloudbot", ".", "bot", ".", "CloudBot", ":", "type", "name", ":", "str", ":", "type", "nick", ":", "str", ":", "type", "channels", ":", "list", "[", "str", "]", ":", "type", "config", ":", "dict", "[", "str", "unknown", ...
def __init__(self, bot, name, nick, *, channels=None, config=None, server, port=6667, use_ssl=False, ignore_cert_errors=True, timeout=300, local_bind=False): """ :type bot: cloudbot.bot.CloudBot :type name: str :type nick: str :type channels: list[str] :type config: dict[str, unknown] :type server: str :type port: int :type use_ssl: bool :type ignore_cert_errors: bool :type timeout: int """ super().__init__(bot, name, nick, channels=channels, config=config) self.use_ssl = use_ssl self._ignore_cert_errors = ignore_cert_errors self._timeout = timeout self.server = server self.port = port self.local_bind = local_bind # create SSL context if self.use_ssl: self.ssl_context = SSLContext(PROTOCOL_SSLv23) if self._ignore_cert_errors: self.ssl_context.verify_mode = ssl.CERT_NONE else: self.ssl_context.verify_mode = ssl.CERT_REQUIRED else: self.ssl_context = None # if we're connected self._connected = False # if we've quit self._quit = False # transport and protocol self._transport = None self._protocol = None self.capabilities = set(self.config.get('capabilities', []))
[ "def", "__init__", "(", "self", ",", "bot", ",", "name", ",", "nick", ",", "*", ",", "channels", "=", "None", ",", "config", "=", "None", ",", "server", ",", "port", "=", "6667", ",", "use_ssl", "=", "False", ",", "ignore_cert_errors", "=", "True", ...
https://github.com/CloudBotIRC/CloudBot/blob/6c5a88f9961b6cd66a8f489a38feb2e8227ac9ea/cloudbot/clients/irc.py#L56-L97
jazzband/django-hosts
b3fb2ab26adc725f09aceea042d3394ea47999c5
django_hosts/managers.py
python
HostSiteManager.by_id
(self, site_id=None)
return self.get_queryset(site_id)
Returns a queryset matching the given site id. If not given this falls back to the ``SITE_ID`` setting. :param site_id: the ID of the site :rtype: :class:`~django.db.models.query.QuerySet`
Returns a queryset matching the given site id. If not given this falls back to the ``SITE_ID`` setting.
[ "Returns", "a", "queryset", "matching", "the", "given", "site", "id", ".", "If", "not", "given", "this", "falls", "back", "to", "the", "SITE_ID", "setting", "." ]
def by_id(self, site_id=None): """ Returns a queryset matching the given site id. If not given this falls back to the ``SITE_ID`` setting. :param site_id: the ID of the site :rtype: :class:`~django.db.models.query.QuerySet` """ return self.get_queryset(site_id)
[ "def", "by_id", "(", "self", ",", "site_id", "=", "None", ")", ":", "return", "self", ".", "get_queryset", "(", "site_id", ")" ]
https://github.com/jazzband/django-hosts/blob/b3fb2ab26adc725f09aceea042d3394ea47999c5/django_hosts/managers.py#L87-L95
scikit-learn-contrib/DESlib
64260ae7c6dd745ef0003cc6322c9f829c807708
deslib/dcs/base.py
python
BaseDCS.estimate_competence
(self, competence_region, distances=None, predictions=None)
Estimate the competence of each base classifier for the classification of the query sample. Parameters ---------- competence_region : array of shape (n_samples, n_neighbors) Indices of the k nearest neighbors. distances : array of shape (n_samples, n_neighbors) Distances from the k nearest neighbors to the query. predictions : array of shape (n_samples, n_classifiers) Predictions of the base classifiers for the test examples. Returns ------- competences : array of shape (n_samples, n_classifiers) Competence level estimated for each base classifier and test example.
Estimate the competence of each base classifier for the classification of the query sample.
[ "Estimate", "the", "competence", "of", "each", "base", "classifier", "for", "the", "classification", "of", "the", "query", "sample", "." ]
def estimate_competence(self, competence_region, distances=None, predictions=None): """Estimate the competence of each base classifier for the classification of the query sample. Parameters ---------- competence_region : array of shape (n_samples, n_neighbors) Indices of the k nearest neighbors. distances : array of shape (n_samples, n_neighbors) Distances from the k nearest neighbors to the query. predictions : array of shape (n_samples, n_classifiers) Predictions of the base classifiers for the test examples. Returns ------- competences : array of shape (n_samples, n_classifiers) Competence level estimated for each base classifier and test example. """ pass
[ "def", "estimate_competence", "(", "self", ",", "competence_region", ",", "distances", "=", "None", ",", "predictions", "=", "None", ")", ":", "pass" ]
https://github.com/scikit-learn-contrib/DESlib/blob/64260ae7c6dd745ef0003cc6322c9f829c807708/deslib/dcs/base.py#L39-L61
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/logging/handlers.py
python
TimedRotatingFileHandler.computeRollover
(self, currentTime)
return result
Work out the rollover time based on the specified time.
Work out the rollover time based on the specified time.
[ "Work", "out", "the", "rollover", "time", "based", "on", "the", "specified", "time", "." ]
def computeRollover(self, currentTime): """ Work out the rollover time based on the specified time. """ result = currentTime + self.interval # If we are rolling over at midnight or weekly, then the interval is already known. # What we need to figure out is WHEN the next interval is. In other words, # if you are rolling over at midnight, then your base interval is 1 day, # but you want to start that one day clock at midnight, not now. So, we # have to fudge the rolloverAt value in order to trigger the first rollover # at the right time. After that, the regular interval will take care of # the rest. Note that this code doesn't care about leap seconds. :) if self.when == 'MIDNIGHT' or self.when.startswith('W'): # This could be done with less code, but I wanted it to be clear if self.utc: t = time.gmtime(currentTime) else: t = time.localtime(currentTime) currentHour = t[3] currentMinute = t[4] currentSecond = t[5] # r is the number of seconds left between now and midnight r = _MIDNIGHT - ((currentHour * 60 + currentMinute) * 60 + currentSecond) result = currentTime + r # If we are rolling over on a certain day, add in the number of days until # the next rollover, but offset by 1 since we just calculated the time # until the next day starts. There are three cases: # Case 1) The day to rollover is today; in this case, do nothing # Case 2) The day to rollover is further in the interval (i.e., today is # day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to # next rollover is simply 6 - 2 - 1, or 3. # Case 3) The day to rollover is behind us in the interval (i.e., today # is day 5 (Saturday) and rollover is on day 3 (Thursday). # Days to rollover is 6 - 5 + 3, or 4. In this case, it's the # number of days left in the current week (1) plus the number # of days in the next week until the rollover day (3). # The calculations described in 2) and 3) above need to have a day added. # This is because the above time calculation takes us to midnight on this # day, i.e. the start of the next day. if self.when.startswith('W'): day = t[6] # 0 is Monday if day != self.dayOfWeek: if day < self.dayOfWeek: daysToWait = self.dayOfWeek - day else: daysToWait = 6 - day + self.dayOfWeek + 1 newRolloverAt = result + (daysToWait * (60 * 60 * 24)) if not self.utc: dstNow = t[-1] dstAtRollover = time.localtime(newRolloverAt)[-1] if dstNow != dstAtRollover: if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour addend = -3600 else: # DST bows out before next rollover, so we need to add an hour addend = 3600 newRolloverAt += addend result = newRolloverAt return result
[ "def", "computeRollover", "(", "self", ",", "currentTime", ")", ":", "result", "=", "currentTime", "+", "self", ".", "interval", "# If we are rolling over at midnight or weekly, then the interval is already known.", "# What we need to figure out is WHEN the next interval is. In othe...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/logging/handlers.py#L257-L315
leancloud/satori
701caccbd4fe45765001ca60435c0cb499477c03
satori-rules/plugin/libs/pymysql/connections.py
python
OKPacketWrapper.__init__
(self, from_packet)
[]
def __init__(self, from_packet): if not from_packet.is_ok_packet(): raise ValueError('Cannot create ' + str(self.__class__.__name__) + ' object from invalid packet type') self.packet = from_packet self.packet.advance(1) self.affected_rows = self.packet.read_length_encoded_integer() self.insert_id = self.packet.read_length_encoded_integer() self.server_status, self.warning_count = self.read_struct('<HH') self.message = self.packet.read_all() self.has_next = self.server_status & SERVER_STATUS.SERVER_MORE_RESULTS_EXISTS
[ "def", "__init__", "(", "self", ",", "from_packet", ")", ":", "if", "not", "from_packet", ".", "is_ok_packet", "(", ")", ":", "raise", "ValueError", "(", "'Cannot create '", "+", "str", "(", "self", ".", "__class__", ".", "__name__", ")", "+", "' object fr...
https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/pymysql/connections.py#L456-L468
ihabunek/toot
1387d045eb10560444a4343e40ae9a16229ceed6
toot/tui/app.py
python
TUI.async_load_timeline
(self, is_initial, timeline_name=None, local=None)
return self.run_in_thread(_load_statuses, done_callback=_done_initial if is_initial else _done_next)
Asynchronously load a list of statuses.
Asynchronously load a list of statuses.
[ "Asynchronously", "load", "a", "list", "of", "statuses", "." ]
def async_load_timeline(self, is_initial, timeline_name=None, local=None): """Asynchronously load a list of statuses.""" def _load_statuses(): self.footer.set_message("Loading statuses...") try: data = next(self.timeline_generator) except StopIteration: return [] finally: self.footer.clear_message() return [self.make_status(s) for s in data] def _done_initial(statuses): """Process initial batch of statuses, construct a Timeline.""" self.timeline = self.build_timeline(timeline_name, statuses, local) self.timeline.refresh_status_details() # Draw first status self.refresh_footer(self.timeline) self.body = self.timeline def _done_next(statuses): """Process sequential batch of statuses, adds statuses to the existing timeline.""" self.timeline.append_statuses(statuses) return self.run_in_thread(_load_statuses, done_callback=_done_initial if is_initial else _done_next)
[ "def", "async_load_timeline", "(", "self", ",", "is_initial", ",", "timeline_name", "=", "None", ",", "local", "=", "None", ")", ":", "def", "_load_statuses", "(", ")", ":", "self", ".", "footer", ".", "set_message", "(", "\"Loading statuses...\"", ")", "try...
https://github.com/ihabunek/toot/blob/1387d045eb10560444a4343e40ae9a16229ceed6/toot/tui/app.py#L268-L295
dsoprea/GDriveFS
d307b043ebc235d6444c8c1ae2e0bbb860e788a0
gdrivefs/gdfuse.py
python
_GdfsMixin.release
(self, filepath, fh)
Close a file.
Close a file.
[ "Close", "a", "file", "." ]
def release(self, filepath, fh): """Close a file.""" om = gdrivefs.opened_file.get_om() try: om.remove_by_fh(fh) except: _logger.exception("Could not remove OpenedFile for handle with " "ID (%d) (release).", fh) raise FuseOSError(EIO)
[ "def", "release", "(", "self", ",", "filepath", ",", "fh", ")", ":", "om", "=", "gdrivefs", ".", "opened_file", ".", "get_om", "(", ")", "try", ":", "om", ".", "remove_by_fh", "(", "fh", ")", "except", ":", "_logger", ".", "exception", "(", "\"Could ...
https://github.com/dsoprea/GDriveFS/blob/d307b043ebc235d6444c8c1ae2e0bbb860e788a0/gdrivefs/gdfuse.py#L449-L460
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/pycryptodomex-3.9.7/lib/Cryptodome/Protocol/KDF.py
python
bcrypt_check
(password, bcrypt_hash)
Verify if the provided password matches the given bcrypt hash. Args: password (byte string or string): The secret password or pass phrase to test. It must be at most 72 bytes long. It must not contain the zero byte. Unicode strings will be encoded as UTF-8. bcrypt_hash (byte string, bytearray): The reference bcrypt hash the password needs to be checked against. Raises: ValueError: if the password does not match
Verify if the provided password matches the given bcrypt hash.
[ "Verify", "if", "the", "provided", "password", "matches", "the", "given", "bcrypt", "hash", "." ]
def bcrypt_check(password, bcrypt_hash): """Verify if the provided password matches the given bcrypt hash. Args: password (byte string or string): The secret password or pass phrase to test. It must be at most 72 bytes long. It must not contain the zero byte. Unicode strings will be encoded as UTF-8. bcrypt_hash (byte string, bytearray): The reference bcrypt hash the password needs to be checked against. Raises: ValueError: if the password does not match """ bcrypt_hash = tobytes(bcrypt_hash) if len(bcrypt_hash) != 60: raise ValueError("Incorrect length of the bcrypt hash: %d bytes instead of 60" % len(bcrypt_hash)) if bcrypt_hash[:4] != b'$2a$': raise ValueError("Unsupported prefix") p = re.compile(br'\$2a\$([0-9][0-9])\$([A-Za-z0-9./]{22,22})([A-Za-z0-9./]{31,31})') r = p.match(bcrypt_hash) if not r: raise ValueError("Incorrect bcrypt hash format") cost = int(r.group(1)) if not (4 <= cost <= 31): raise ValueError("Incorrect cost") salt = _bcrypt_decode(r.group(2)) bcrypt_hash2 = bcrypt(password, cost, salt) secret = get_random_bytes(16) mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=bcrypt_hash).digest() mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=bcrypt_hash2).digest() if mac1 != mac2: raise ValueError("Incorrect bcrypt hash")
[ "def", "bcrypt_check", "(", "password", ",", "bcrypt_hash", ")", ":", "bcrypt_hash", "=", "tobytes", "(", "bcrypt_hash", ")", "if", "len", "(", "bcrypt_hash", ")", "!=", "60", ":", "raise", "ValueError", "(", "\"Incorrect length of the bcrypt hash: %d bytes instead ...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/pycryptodomex-3.9.7/lib/Cryptodome/Protocol/KDF.py#L532-L574
cool-RR/python_toolbox
cb9ef64b48f1d03275484d707dc5079b6701ad0c
python_toolbox/combi/perming/perm_space.py
python
PermSpace.short_length_string
(self)
Short string describing size of space, e.g. "12!"
Short string describing size of space, e.g. "12!"
[ "Short", "string", "describing", "size", "of", "space", "e", ".", "g", ".", "12!" ]
def short_length_string(self): '''Short string describing size of space, e.g. "12!"''' if not self.is_recurrent and not self.is_partial and \ not self.is_combination and not self.is_fixed and \ not self.is_sliced: assert self.length == math_tools.factorial(self.sequence_length) return misc.get_short_factorial_string(self.sequence_length) else: return str(self.length)
[ "def", "short_length_string", "(", "self", ")", ":", "if", "not", "self", ".", "is_recurrent", "and", "not", "self", ".", "is_partial", "and", "not", "self", ".", "is_combination", "and", "not", "self", ".", "is_fixed", "and", "not", "self", ".", "is_slice...
https://github.com/cool-RR/python_toolbox/blob/cb9ef64b48f1d03275484d707dc5079b6701ad0c/python_toolbox/combi/perming/perm_space.py#L919-L927
tianzhi0549/FCOS
0eb8ee0b7114a3ca42ad96cd89e0ac63a205461e
fcos_core/utils/env.py
python
setup_environment
()
Perform environment setup work. The default setup is a no-op, but this function allows the user to specify a Python source file that performs custom setup work that may be necessary to their computing environment.
Perform environment setup work. The default setup is a no-op, but this function allows the user to specify a Python source file that performs custom setup work that may be necessary to their computing environment.
[ "Perform", "environment", "setup", "work", ".", "The", "default", "setup", "is", "a", "no", "-", "op", "but", "this", "function", "allows", "the", "user", "to", "specify", "a", "Python", "source", "file", "that", "performs", "custom", "setup", "work", "tha...
def setup_environment(): """Perform environment setup work. The default setup is a no-op, but this function allows the user to specify a Python source file that performs custom setup work that may be necessary to their computing environment. """ custom_module_path = os.environ.get("TORCH_DETECTRON_ENV_MODULE") if custom_module_path: setup_custom_environment(custom_module_path) else: # The default setup is a no-op pass
[ "def", "setup_environment", "(", ")", ":", "custom_module_path", "=", "os", ".", "environ", ".", "get", "(", "\"TORCH_DETECTRON_ENV_MODULE\"", ")", "if", "custom_module_path", ":", "setup_custom_environment", "(", "custom_module_path", ")", "else", ":", "# The default...
https://github.com/tianzhi0549/FCOS/blob/0eb8ee0b7114a3ca42ad96cd89e0ac63a205461e/fcos_core/utils/env.py#L7-L17
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/helpers/device_registry.py
python
DeviceRegistry.async_schedule_save
(self)
Schedule saving the device registry.
Schedule saving the device registry.
[ "Schedule", "saving", "the", "device", "registry", "." ]
def async_schedule_save(self) -> None: """Schedule saving the device registry.""" self._store.async_delay_save(self._data_to_save, SAVE_DELAY)
[ "def", "async_schedule_save", "(", "self", ")", "->", "None", ":", "self", ".", "_store", ".", "async_delay_save", "(", "self", ".", "_data_to_save", ",", "SAVE_DELAY", ")" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/helpers/device_registry.py#L588-L590
hvac/hvac
ec048ded30d21c13c21cfa950d148c8bfc1467b0
hvac/api/system_backend/key.py
python
Key.cancel_rekey_verify
(self)
return self._adapter.delete( url=api_path, )
Cancel any in-progress rekey verification. This clears any progress made and resets the nonce. Unlike cancel_rekey, this only resets the current verification operation, not the entire rekey atttempt. The return value is the same as GET along with the new nonce. Supported methods: DELETE: /sys/rekey/verify. Produces: 204 (empty body) :return: The response of the request. :rtype: requests.Response
Cancel any in-progress rekey verification. This clears any progress made and resets the nonce. Unlike cancel_rekey, this only resets the current verification operation, not the entire rekey atttempt. The return value is the same as GET along with the new nonce.
[ "Cancel", "any", "in", "-", "progress", "rekey", "verification", ".", "This", "clears", "any", "progress", "made", "and", "resets", "the", "nonce", ".", "Unlike", "cancel_rekey", "this", "only", "resets", "the", "current", "verification", "operation", "not", "...
def cancel_rekey_verify(self): """Cancel any in-progress rekey verification. This clears any progress made and resets the nonce. Unlike cancel_rekey, this only resets the current verification operation, not the entire rekey atttempt. The return value is the same as GET along with the new nonce. Supported methods: DELETE: /sys/rekey/verify. Produces: 204 (empty body) :return: The response of the request. :rtype: requests.Response """ api_path = "/v1/sys/rekey/verify" return self._adapter.delete( url=api_path, )
[ "def", "cancel_rekey_verify", "(", "self", ")", ":", "api_path", "=", "\"/v1/sys/rekey/verify\"", "return", "self", ".", "_adapter", ".", "delete", "(", "url", "=", "api_path", ",", ")" ]
https://github.com/hvac/hvac/blob/ec048ded30d21c13c21cfa950d148c8bfc1467b0/hvac/api/system_backend/key.py#L323-L338
foxmask/django-th
29aa84f8d4aa945dbef6cf580593b435cc708e31
th_evernote/my_evernote.py
python
ServiceEvernote.auth
(self, request)
return client.get_authorize_url(request_token)
let's auth the user to the Service
let's auth the user to the Service
[ "let", "s", "auth", "the", "user", "to", "the", "Service" ]
def auth(self, request): """ let's auth the user to the Service """ client = self.get_evernote_client() request_token = client.get_request_token(self.callback_url(request)) # Save the request token information for later request.session['oauth_token'] = request_token['oauth_token'] request.session['oauth_token_secret'] = request_token['oauth_token_secret'] # Redirect the user to the Evernote authorization URL # return the URL string which will be used by redirect() # from the calling func return client.get_authorize_url(request_token)
[ "def", "auth", "(", "self", ",", "request", ")", ":", "client", "=", "self", ".", "get_evernote_client", "(", ")", "request_token", "=", "client", ".", "get_request_token", "(", "self", ".", "callback_url", "(", "request", ")", ")", "# Save the request token i...
https://github.com/foxmask/django-th/blob/29aa84f8d4aa945dbef6cf580593b435cc708e31/th_evernote/my_evernote.py#L275-L287
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/pip/_vendor/idna/uts46data.py
python
_seg_73
()
return [ (0x2F822, 'M', u'割'), (0x2F823, 'M', u'剷'), (0x2F824, 'M', u'㔕'), (0x2F825, 'M', u'勇'), (0x2F826, 'M', u'勉'), (0x2F827, 'M', u'勤'), (0x2F828, 'M', u'勺'), (0x2F829, 'M', u'包'), (0x2F82A, 'M', u'匆'), (0x2F82B, 'M', u'北'), (0x2F82C, 'M', u'卉'), (0x2F82D, 'M', u'卑'), (0x2F82E, 'M', u'博'), (0x2F82F, 'M', u'即'), (0x2F830, 'M', u'卽'), (0x2F831, 'M', u'卿'), (0x2F834, 'M', u'𠨬'), (0x2F835, 'M', u'灰'), (0x2F836, 'M', u'及'), (0x2F837, 'M', u'叟'), (0x2F838, 'M', u'𠭣'), (0x2F839, 'M', u'叫'), (0x2F83A, 'M', u'叱'), (0x2F83B, 'M', u'吆'), (0x2F83C, 'M', u'咞'), (0x2F83D, 'M', u'吸'), (0x2F83E, 'M', u'呈'), (0x2F83F, 'M', u'周'), (0x2F840, 'M', u'咢'), (0x2F841, 'M', u'哶'), (0x2F842, 'M', u'唐'), (0x2F843, 'M', u'啓'), (0x2F844, 'M', u'啣'), (0x2F845, 'M', u'善'), (0x2F847, 'M', u'喙'), (0x2F848, 'M', u'喫'), (0x2F849, 'M', u'喳'), (0x2F84A, 'M', u'嗂'), (0x2F84B, 'M', u'圖'), (0x2F84C, 'M', u'嘆'), (0x2F84D, 'M', u'圗'), (0x2F84E, 'M', u'噑'), (0x2F84F, 'M', u'噴'), (0x2F850, 'M', u'切'), (0x2F851, 'M', u'壮'), (0x2F852, 'M', u'城'), (0x2F853, 'M', u'埴'), (0x2F854, 'M', u'堍'), (0x2F855, 'M', u'型'), (0x2F856, 'M', u'堲'), (0x2F857, 'M', u'報'), (0x2F858, 'M', u'墬'), (0x2F859, 'M', u'𡓤'), (0x2F85A, 'M', u'売'), (0x2F85B, 'M', u'壷'), (0x2F85C, 'M', u'夆'), (0x2F85D, 'M', u'多'), (0x2F85E, 'M', u'夢'), (0x2F85F, 'M', u'奢'), (0x2F860, 'M', u'𡚨'), (0x2F861, 'M', u'𡛪'), (0x2F862, 'M', u'姬'), (0x2F863, 'M', u'娛'), (0x2F864, 'M', u'娧'), (0x2F865, 'M', u'姘'), (0x2F866, 'M', u'婦'), (0x2F867, 'M', u'㛮'), (0x2F868, 'X'), (0x2F869, 'M', u'嬈'), (0x2F86A, 'M', u'嬾'), (0x2F86C, 'M', u'𡧈'), (0x2F86D, 'M', u'寃'), (0x2F86E, 'M', u'寘'), (0x2F86F, 'M', u'寧'), (0x2F870, 'M', u'寳'), (0x2F871, 'M', u'𡬘'), (0x2F872, 'M', u'寿'), (0x2F873, 'M', u'将'), (0x2F874, 'X'), (0x2F875, 'M', u'尢'), (0x2F876, 'M', u'㞁'), (0x2F877, 'M', u'屠'), (0x2F878, 'M', u'屮'), (0x2F879, 'M', u'峀'), (0x2F87A, 'M', u'岍'), (0x2F87B, 'M', u'𡷤'), (0x2F87C, 'M', u'嵃'), (0x2F87D, 'M', u'𡷦'), (0x2F87E, 'M', u'嵮'), (0x2F87F, 'M', u'嵫'), (0x2F880, 'M', u'嵼'), (0x2F881, 'M', u'巡'), (0x2F882, 'M', u'巢'), (0x2F883, 'M', u'㠯'), (0x2F884, 'M', u'巽'), (0x2F885, 'M', u'帨'), (0x2F886, 'M', u'帽'), (0x2F887, 'M', u'幩'), (0x2F888, 'M', u'㡢'), (0x2F889, 'M', u'𢆃'), ]
[]
def _seg_73(): return [ (0x2F822, 'M', u'割'), (0x2F823, 'M', u'剷'), (0x2F824, 'M', u'㔕'), (0x2F825, 'M', u'勇'), (0x2F826, 'M', u'勉'), (0x2F827, 'M', u'勤'), (0x2F828, 'M', u'勺'), (0x2F829, 'M', u'包'), (0x2F82A, 'M', u'匆'), (0x2F82B, 'M', u'北'), (0x2F82C, 'M', u'卉'), (0x2F82D, 'M', u'卑'), (0x2F82E, 'M', u'博'), (0x2F82F, 'M', u'即'), (0x2F830, 'M', u'卽'), (0x2F831, 'M', u'卿'), (0x2F834, 'M', u'𠨬'), (0x2F835, 'M', u'灰'), (0x2F836, 'M', u'及'), (0x2F837, 'M', u'叟'), (0x2F838, 'M', u'𠭣'), (0x2F839, 'M', u'叫'), (0x2F83A, 'M', u'叱'), (0x2F83B, 'M', u'吆'), (0x2F83C, 'M', u'咞'), (0x2F83D, 'M', u'吸'), (0x2F83E, 'M', u'呈'), (0x2F83F, 'M', u'周'), (0x2F840, 'M', u'咢'), (0x2F841, 'M', u'哶'), (0x2F842, 'M', u'唐'), (0x2F843, 'M', u'啓'), (0x2F844, 'M', u'啣'), (0x2F845, 'M', u'善'), (0x2F847, 'M', u'喙'), (0x2F848, 'M', u'喫'), (0x2F849, 'M', u'喳'), (0x2F84A, 'M', u'嗂'), (0x2F84B, 'M', u'圖'), (0x2F84C, 'M', u'嘆'), (0x2F84D, 'M', u'圗'), (0x2F84E, 'M', u'噑'), (0x2F84F, 'M', u'噴'), (0x2F850, 'M', u'切'), (0x2F851, 'M', u'壮'), (0x2F852, 'M', u'城'), (0x2F853, 'M', u'埴'), (0x2F854, 'M', u'堍'), (0x2F855, 'M', u'型'), (0x2F856, 'M', u'堲'), (0x2F857, 'M', u'報'), (0x2F858, 'M', u'墬'), (0x2F859, 'M', u'𡓤'), (0x2F85A, 'M', u'売'), (0x2F85B, 'M', u'壷'), (0x2F85C, 'M', u'夆'), (0x2F85D, 'M', u'多'), (0x2F85E, 'M', u'夢'), (0x2F85F, 'M', u'奢'), (0x2F860, 'M', u'𡚨'), (0x2F861, 'M', u'𡛪'), (0x2F862, 'M', u'姬'), (0x2F863, 'M', u'娛'), (0x2F864, 'M', u'娧'), (0x2F865, 'M', u'姘'), (0x2F866, 'M', u'婦'), (0x2F867, 'M', u'㛮'), (0x2F868, 'X'), (0x2F869, 'M', u'嬈'), (0x2F86A, 'M', u'嬾'), (0x2F86C, 'M', u'𡧈'), (0x2F86D, 'M', u'寃'), (0x2F86E, 'M', u'寘'), (0x2F86F, 'M', u'寧'), (0x2F870, 'M', u'寳'), (0x2F871, 'M', u'𡬘'), (0x2F872, 'M', u'寿'), (0x2F873, 'M', u'将'), (0x2F874, 'X'), (0x2F875, 'M', u'尢'), (0x2F876, 'M', u'㞁'), (0x2F877, 'M', u'屠'), (0x2F878, 'M', u'屮'), (0x2F879, 'M', u'峀'), (0x2F87A, 'M', u'岍'), (0x2F87B, 'M', u'𡷤'), (0x2F87C, 'M', u'嵃'), (0x2F87D, 'M', u'𡷦'), (0x2F87E, 'M', u'嵮'), (0x2F87F, 'M', u'嵫'), (0x2F880, 'M', u'嵼'), (0x2F881, 'M', u'巡'), (0x2F882, 'M', u'巢'), (0x2F883, 'M', u'㠯'), (0x2F884, 'M', u'巽'), (0x2F885, 'M', u'帨'), (0x2F886, 'M', u'帽'), (0x2F887, 'M', u'幩'), (0x2F888, 'M', u'㡢'), (0x2F889, 'M', u'𢆃'), ]
[ "def", "_seg_73", "(", ")", ":", "return", "[", "(", "0x2F822", ",", "'M'", ",", "u'割'),", "", "", "(", "0x2F823", ",", "'M'", ",", "u'剷'),", "", "", "(", "0x2F824", ",", "'M'", ",", "u'㔕'),", "", "", "(", "0x2F825", ",", "'M'", ",", "u'勇'),", ...
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pip/_vendor/idna/uts46data.py#L7600-L7702
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/Django/django/contrib/gis/utils/ogrinspect.py
python
ogrinspect
(*args, **kwargs)
return '\n'.join(s for s in _ogrinspect(*args, **kwargs))
Given a data source (either a string or a DataSource object) and a string model name this function will generate a GeoDjango model. Usage: >>> from django.contrib.gis.utils import ogrinspect >>> ogrinspect('/path/to/shapefile.shp','NewModel') ...will print model definition to stout or put this in a python script and use to redirect the output to a new model like: $ python generate_model.py > myapp/models.py # generate_model.py from django.contrib.gis.utils import ogrinspect shp_file = 'data/mapping_hacks/world_borders.shp' model_name = 'WorldBorders' print(ogrinspect(shp_file, model_name, multi_geom=True, srid=4326, geom_name='shapes', blank=True)) Required Arguments `datasource` => string or DataSource object to file pointer `model name` => string of name of new model class to create Optional Keyword Arguments `geom_name` => For specifying the model name for the Geometry Field. Otherwise will default to `geom` `layer_key` => The key for specifying which layer in the DataSource to use; defaults to 0 (the first layer). May be an integer index or a string identifier for the layer. `srid` => The SRID to use for the Geometry Field. If it can be determined, the SRID of the datasource is used. `multi_geom` => Boolean (default: False) - specify as multigeometry. `name_field` => String - specifies a field name to return for the `__unicode__` function (which will be generated if specified). `imports` => Boolean (default: True) - set to False to omit the `from django.contrib.gis.db import models` code from the autogenerated models thus avoiding duplicated imports when building more than one model by batching ogrinspect() `decimal` => Boolean or sequence (default: False). When set to True all generated model fields corresponding to the `OFTReal` type will be `DecimalField` instead of `FloatField`. A sequence of specific field names to generate as `DecimalField` may also be used. `blank` => Boolean or sequence (default: False). When set to True all generated model fields will have `blank=True`. If the user wants to give specific fields to have blank, then a list/tuple of OGR field names may be used. `null` => Boolean (default: False) - When set to True all generated model fields will have `null=True`. If the user wants to specify give specific fields to have null, then a list/tuple of OGR field names may be used. Note: This routine calls the _ogrinspect() helper to do the heavy lifting.
Given a data source (either a string or a DataSource object) and a string model name this function will generate a GeoDjango model.
[ "Given", "a", "data", "source", "(", "either", "a", "string", "or", "a", "DataSource", "object", ")", "and", "a", "string", "model", "name", "this", "function", "will", "generate", "a", "GeoDjango", "model", "." ]
def ogrinspect(*args, **kwargs): """ Given a data source (either a string or a DataSource object) and a string model name this function will generate a GeoDjango model. Usage: >>> from django.contrib.gis.utils import ogrinspect >>> ogrinspect('/path/to/shapefile.shp','NewModel') ...will print model definition to stout or put this in a python script and use to redirect the output to a new model like: $ python generate_model.py > myapp/models.py # generate_model.py from django.contrib.gis.utils import ogrinspect shp_file = 'data/mapping_hacks/world_borders.shp' model_name = 'WorldBorders' print(ogrinspect(shp_file, model_name, multi_geom=True, srid=4326, geom_name='shapes', blank=True)) Required Arguments `datasource` => string or DataSource object to file pointer `model name` => string of name of new model class to create Optional Keyword Arguments `geom_name` => For specifying the model name for the Geometry Field. Otherwise will default to `geom` `layer_key` => The key for specifying which layer in the DataSource to use; defaults to 0 (the first layer). May be an integer index or a string identifier for the layer. `srid` => The SRID to use for the Geometry Field. If it can be determined, the SRID of the datasource is used. `multi_geom` => Boolean (default: False) - specify as multigeometry. `name_field` => String - specifies a field name to return for the `__unicode__` function (which will be generated if specified). `imports` => Boolean (default: True) - set to False to omit the `from django.contrib.gis.db import models` code from the autogenerated models thus avoiding duplicated imports when building more than one model by batching ogrinspect() `decimal` => Boolean or sequence (default: False). When set to True all generated model fields corresponding to the `OFTReal` type will be `DecimalField` instead of `FloatField`. A sequence of specific field names to generate as `DecimalField` may also be used. `blank` => Boolean or sequence (default: False). When set to True all generated model fields will have `blank=True`. If the user wants to give specific fields to have blank, then a list/tuple of OGR field names may be used. `null` => Boolean (default: False) - When set to True all generated model fields will have `null=True`. If the user wants to specify give specific fields to have null, then a list/tuple of OGR field names may be used. Note: This routine calls the _ogrinspect() helper to do the heavy lifting. """ return '\n'.join(s for s in _ogrinspect(*args, **kwargs))
[ "def", "ogrinspect", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "'\\n'", ".", "join", "(", "s", "for", "s", "in", "_ogrinspect", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/Django/django/contrib/gis/utils/ogrinspect.py#L48-L116
toastdriven/restless
ce18b02886cce6d182d60661cb5c2eeeac215cf6
restless/resources.py
python
Resource.request_method
(self)
return self.request.method.upper()
Returns the HTTP method for the current request. If you're integrating with a new web framework, you might need to override this method within your subclass. :returns: The HTTP method in uppercase :rtype: string
Returns the HTTP method for the current request.
[ "Returns", "the", "HTTP", "method", "for", "the", "current", "request", "." ]
def request_method(self): """ Returns the HTTP method for the current request. If you're integrating with a new web framework, you might need to override this method within your subclass. :returns: The HTTP method in uppercase :rtype: string """ # By default, Django-esque. return self.request.method.upper()
[ "def", "request_method", "(", "self", ")", ":", "# By default, Django-esque.", "return", "self", ".", "request", ".", "method", ".", "upper", "(", ")" ]
https://github.com/toastdriven/restless/blob/ce18b02886cce6d182d60661cb5c2eeeac215cf6/restless/resources.py#L146-L157
themix-project/oomox
1bb0f3033736c56652e25c7d7b47c7fc499bfeb1
plugins/icons_numix/oomox_plugin.py
python
NumixIconsExportDialog.do_export
(self)
[]
def do_export(self): self.command = [ "bash", os.path.join(PLUGIN_DIR, "change_color.sh"), "-o", self.theme_name, self.temp_theme_path, ] super().do_export()
[ "def", "do_export", "(", "self", ")", ":", "self", ".", "command", "=", "[", "\"bash\"", ",", "os", ".", "path", ".", "join", "(", "PLUGIN_DIR", ",", "\"change_color.sh\"", ")", ",", "\"-o\"", ",", "self", ".", "theme_name", ",", "self", ".", "temp_the...
https://github.com/themix-project/oomox/blob/1bb0f3033736c56652e25c7d7b47c7fc499bfeb1/plugins/icons_numix/oomox_plugin.py#L15-L22
snapcore/snapcraft
b81550376df7f2d0dfe65f7bfb006a3107252450
snapcraft/internal/cache/_file.py
python
FileCache.__init__
(self, *, namespace: str = "files")
Create a FileCache under namespace. :param str namespace: set the namespace for the cache (default: "files").
Create a FileCache under namespace.
[ "Create", "a", "FileCache", "under", "namespace", "." ]
def __init__(self, *, namespace: str = "files") -> None: """Create a FileCache under namespace. :param str namespace: set the namespace for the cache (default: "files"). """ super().__init__() self.file_cache = os.path.join(self.cache_root, namespace)
[ "def", "__init__", "(", "self", ",", "*", ",", "namespace", ":", "str", "=", "\"files\"", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "file_cache", "=", "os", ".", "path", ".", "join", "(", "self", ".", "cac...
https://github.com/snapcore/snapcraft/blob/b81550376df7f2d0dfe65f7bfb006a3107252450/snapcraft/internal/cache/_file.py#L31-L38
spartan-array/spartan
fdcf059ce7e48688648d793d632dc5961f4e72b5
spartan/expr/operator/checkpoint.py
python
checkpoint
(x, mode='disk')
return CheckpointExpr(src=lazify(x), path=FLAGS.checkpoint_path, mode=mode, ready=False)
Make a checkpoint for x :param x: `numpy.ndarray` or `Expr` :param mode: 'disk' or 'replica' :rtype: `Expr`
Make a checkpoint for x
[ "Make", "a", "checkpoint", "for", "x" ]
def checkpoint(x, mode='disk'): ''' Make a checkpoint for x :param x: `numpy.ndarray` or `Expr` :param mode: 'disk' or 'replica' :rtype: `Expr` ''' return CheckpointExpr(src=lazify(x), path=FLAGS.checkpoint_path, mode=mode, ready=False)
[ "def", "checkpoint", "(", "x", ",", "mode", "=", "'disk'", ")", ":", "return", "CheckpointExpr", "(", "src", "=", "lazify", "(", "x", ")", ",", "path", "=", "FLAGS", ".", "checkpoint_path", ",", "mode", "=", "mode", ",", "ready", "=", "False", ")" ]
https://github.com/spartan-array/spartan/blob/fdcf059ce7e48688648d793d632dc5961f4e72b5/spartan/expr/operator/checkpoint.py#L51-L59
bit-team/backintime
e1ae23ddc0b4229053e3e9c6c61adcb7f3d8e9b3
common/tools.py
python
pidsWithName
(name)
return [x for x in pids() if processName(x) == name[:15]]
Get all processes currently running with name ``name``. Args: name (str): name of a process like 'python3' or 'backintime' Returns: list: PIDs as int
Get all processes currently running with name ``name``.
[ "Get", "all", "processes", "currently", "running", "with", "name", "name", "." ]
def pidsWithName(name): """ Get all processes currently running with name ``name``. Args: name (str): name of a process like 'python3' or 'backintime' Returns: list: PIDs as int """ # /proc/###/stat stores just the first 16 chars of the process name return [x for x in pids() if processName(x) == name[:15]]
[ "def", "pidsWithName", "(", "name", ")", ":", "# /proc/###/stat stores just the first 16 chars of the process name", "return", "[", "x", "for", "x", "in", "pids", "(", ")", "if", "processName", "(", "x", ")", "==", "name", "[", ":", "15", "]", "]" ]
https://github.com/bit-team/backintime/blob/e1ae23ddc0b4229053e3e9c6c61adcb7f3d8e9b3/common/tools.py#L391-L402
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
pypy/module/cpyext/floatobject.py
python
PyFloat_AS_DOUBLE
(space, w_float)
return space.float_w(w_float)
Return a C double representation of the contents of w_float, but without error checking.
Return a C double representation of the contents of w_float, but without error checking.
[ "Return", "a", "C", "double", "representation", "of", "the", "contents", "of", "w_float", "but", "without", "error", "checking", "." ]
def PyFloat_AS_DOUBLE(space, w_float): """Return a C double representation of the contents of w_float, but without error checking.""" return space.float_w(w_float)
[ "def", "PyFloat_AS_DOUBLE", "(", "space", ",", "w_float", ")", ":", "return", "space", ".", "float_w", "(", "w_float", ")" ]
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/pypy/module/cpyext/floatobject.py#L50-L53
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/celery/backends/redis.py
python
RedisBackend.on_chord_part_return
(self, request, state, result, propagate=None, **kwargs)
[]
def on_chord_part_return(self, request, state, result, propagate=None, **kwargs): app = self.app tid, gid = request.id, request.group if not gid or not tid: return client = self.client jkey = self.get_key_for_group(gid, '.j') tkey = self.get_key_for_group(gid, '.t') result = self.encode_result(result, state) with client.pipeline() as pipe: _, readycount, totaldiff, _, _ = pipe \ .rpush(jkey, self.encode([1, tid, state, result])) \ .llen(jkey) \ .get(tkey) \ .expire(jkey, self.expires) \ .expire(tkey, self.expires) \ .execute() totaldiff = int(totaldiff or 0) try: callback = maybe_signature(request.chord, app=app) total = callback['chord_size'] + totaldiff if readycount == total: decode, unpack = self.decode, self._unpack_chord_result with client.pipeline() as pipe: resl, _, _ = pipe \ .lrange(jkey, 0, total) \ .delete(jkey) \ .delete(tkey) \ .execute() try: callback.delay([unpack(tup, decode) for tup in resl]) except Exception as exc: # pylint: disable=broad-except logger.exception( 'Chord callback for %r raised: %r', request.group, exc) return self.chord_error_from_stack( callback, ChordError('Callback error: {0!r}'.format(exc)), ) except ChordError as exc: logger.exception('Chord %r raised: %r', request.group, exc) return self.chord_error_from_stack(callback, exc) except Exception as exc: # pylint: disable=broad-except logger.exception('Chord %r raised: %r', request.group, exc) return self.chord_error_from_stack( callback, ChordError('Join error: {0!r}'.format(exc)), )
[ "def", "on_chord_part_return", "(", "self", ",", "request", ",", "state", ",", "result", ",", "propagate", "=", "None", ",", "*", "*", "kwargs", ")", ":", "app", "=", "self", ".", "app", "tid", ",", "gid", "=", "request", ".", "id", ",", "request", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/celery/backends/redis.py#L247-L297
NVIDIA/DeepLearningExamples
589604d49e016cd9ef4525f7abcc9c7b826cfc5e
TensorFlow2/LanguageModeling/ELECTRA/modeling.py
python
TFElectraMainLayer._prune_heads
(self, heads_to_prune)
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base class PreTrainedModel
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base class PreTrainedModel
[ "Prunes", "heads", "of", "the", "model", ".", "heads_to_prune", ":", "dict", "of", "{", "layer_num", ":", "list", "of", "heads", "to", "prune", "in", "this", "layer", "}", "See", "base", "class", "PreTrainedModel" ]
def _prune_heads(self, heads_to_prune): """ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base class PreTrainedModel """ raise NotImplementedError
[ "def", "_prune_heads", "(", "self", ",", "heads_to_prune", ")", ":", "raise", "NotImplementedError" ]
https://github.com/NVIDIA/DeepLearningExamples/blob/589604d49e016cd9ef4525f7abcc9c7b826cfc5e/TensorFlow2/LanguageModeling/ELECTRA/modeling.py#L243-L248
maas/maas
db2f89970c640758a51247c59bf1ec6f60cf4ab5
src/provisioningserver/dns/commands/edit_named_options.py
python
parse_file
(config_path, options_file)
return config_dict
Read the named.conf.options file and parse it. Then insert the include statement that we need.
Read the named.conf.options file and parse it.
[ "Read", "the", "named", ".", "conf", ".", "options", "file", "and", "parse", "it", "." ]
def parse_file(config_path, options_file): """Read the named.conf.options file and parse it. Then insert the include statement that we need. """ try: config_dict = parse_isc_string(options_file) except ISCParseException as e: raise ValueError( "Failed to parse %s: %s" % (config_path, str(e)) ) from e options_block = config_dict.get("options", None) if options_block is None: # Something is horribly wrong with the file; bail out rather # than doing anything drastic. raise ValueError( "Can't find options {} block in %s, bailing out without " "doing anything." % config_path ) return config_dict
[ "def", "parse_file", "(", "config_path", ",", "options_file", ")", ":", "try", ":", "config_dict", "=", "parse_isc_string", "(", "options_file", ")", "except", "ISCParseException", "as", "e", ":", "raise", "ValueError", "(", "\"Failed to parse %s: %s\"", "%", "(",...
https://github.com/maas/maas/blob/db2f89970c640758a51247c59bf1ec6f60cf4ab5/src/provisioningserver/dns/commands/edit_named_options.py#L75-L94
bigaidream-projects/drmad
a4bb6010595d956f29c5a42a095bab76a60b29eb
gpu_ver/refcode/models/layers/conv_layers.py
python
pool_layer.__init__
(self, rstream, index, x, params, useRglrz, bnPhase, poolShape, inFilters, outFilters, stride, ignore_border = False, b=None, a=None, normParam=None, normParam2=None, rglrzParam=None)
Pooling layer + BN + noise
Pooling layer + BN + noise
[ "Pooling", "layer", "+", "BN", "+", "noise" ]
def __init__(self, rstream, index, x, params, useRglrz, bnPhase, poolShape, inFilters, outFilters, stride, ignore_border = False, b=None, a=None, normParam=None, normParam2=None, rglrzParam=None): ''' Pooling layer + BN + noise ''' # batch normalization if params.batchNorm and params.convLayers[index].bn: _, b, a = t1_shared(params=params, rng=0, index=index, nIn=0, nOut=0, outFilters=inFilters, filterShape=0, defineW=0) self.b = b; self.a = a if params.batchNorm and not params.aFix: self.paramsT1 = [b, a] else: self.paramsT1 = [b] if normParam is None: normParam, paramsBN = bn_shared(params, inFilters, index) self.normParam = normParam self.paramsBN = paramsBN x, updateBN = bn_layer(x, self.a, self.b, self.normParam, params, bnPhase) self.updateBN = updateBN # additive noise self.paramsT2 = [] if 'addNoise' in params.rglrz and params.convLayers[index].noise: if rglrzParam is None: self.rglrzParam = {} tempValue = params.rglrzInitial['addNoise'][index] tempParam = np.asarray(tempValue, dtype=theano.config.floatX) noizParam = theano.shared(value=tempParam, name='%s_%d' % ('addNoise', index), borrow=True) self.rglrzParam['addNoise']=noizParam if params.useT2 and 'addNoise' in params.rglrzTrain: self.paramsT2 = [noizParam] x = noiseup(x, useRglrz, noizParam, params.noiseT1, params, index, rstream) # dropout if dropout_conditions(params, index, 'type0') and params.convLayers[index].noise: if ('dropOut' in params.rglrz): drop = self.rglrzInitial['dropOut'][index] elif 'dropOutB' in rglrzParam.keys(): drop = self.rglrzInitial['dropOutB'][index] x = dropout(x, useRglrz, drop, params, inFilters, rstream) # pooling if cudasConv: self.output = cudnn.dnn_pool(x, poolShape, stride = stride, mode = 'max')#, ignore_border = ignore_border) else: self.output = pool.pool_2d(x, ds = poolShape, st = stride, ignore_border = ignore_border, mode = 'max') # batch normalization if params.batchNorm and params.convLayers[index].bn and params.poolBNafter: _, b, a = t1_shared(params=params, rng=0, index=index+20, nIn=0, nOut=0, outFilters=outFilters, filterShape=0, defineW=0) self.b = b; self.a = a if params.batchNorm and not params.aFix: self.paramsT1 = [b, a] else: self.paramsT1 = [b] if normParam2 is None: normParam2, paramsBN2 = bn_shared(params, outFilters, index+20) self.normParam2 = normParam2 self.paramsBN += paramsBN2 self.output, updateBN2 = bn_layer(self.output, self.a, self.b, self.normParam2, params, bnPhase) self.updateBN += updateBN2
[ "def", "__init__", "(", "self", ",", "rstream", ",", "index", ",", "x", ",", "params", ",", "useRglrz", ",", "bnPhase", ",", "poolShape", ",", "inFilters", ",", "outFilters", ",", "stride", ",", "ignore_border", "=", "False", ",", "b", "=", "None", ","...
https://github.com/bigaidream-projects/drmad/blob/a4bb6010595d956f29c5a42a095bab76a60b29eb/gpu_ver/refcode/models/layers/conv_layers.py#L121-L194
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/pillows/application.py
python
transform_app_for_es
(doc_dict)
return doc.to_json()
[]
def transform_app_for_es(doc_dict): # perform any lazy migrations doc = get_correct_app_class(doc_dict).wrap(doc_dict) doc['@indexed_on'] = json_format_datetime(datetime.utcnow()) return doc.to_json()
[ "def", "transform_app_for_es", "(", "doc_dict", ")", ":", "# perform any lazy migrations", "doc", "=", "get_correct_app_class", "(", "doc_dict", ")", ".", "wrap", "(", "doc_dict", ")", "doc", "[", "'@indexed_on'", "]", "=", "json_format_datetime", "(", "datetime", ...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/pillows/application.py#L16-L20
piergiaj/representation-flow-cvpr19
b9dcb0a7750732210bccf84dbe6044cc33b48c17
baseline_2d_resnets.py
python
resnet34
(pretrained=False, mode='rgb', **kwargs)
return model
Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
[ "Constructs", "a", "ResNet", "-", "34", "model", ".", "Args", ":", "pretrained", "(", "bool", ")", ":", "If", "True", "returns", "a", "model", "pre", "-", "trained", "on", "ImageNet" ]
def resnet34(pretrained=False, mode='rgb', **kwargs): """Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ if mode == 'flow': model = ResNet(BasicBlock, [3, 4, 6, 3], inp=20, **kwargs) else: model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet34'])) return model
[ "def", "resnet34", "(", "pretrained", "=", "False", ",", "mode", "=", "'rgb'", ",", "*", "*", "kwargs", ")", ":", "if", "mode", "==", "'flow'", ":", "model", "=", "ResNet", "(", "BasicBlock", ",", "[", "3", ",", "4", ",", "6", ",", "3", "]", ",...
https://github.com/piergiaj/representation-flow-cvpr19/blob/b9dcb0a7750732210bccf84dbe6044cc33b48c17/baseline_2d_resnets.py#L215-L227
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/s3/s3navigation.py
python
S3NavigationItem.__setitem__
(self, i, item)
Overwrite the component item at position i with item Args: i: the index within the component list item: the item
Overwrite the component item at position i with item
[ "Overwrite", "the", "component", "item", "at", "position", "i", "with", "item" ]
def __setitem__(self, i, item): """ Overwrite the component item at position i with item Args: i: the index within the component list item: the item """ self.components.__setitem__(i, item)
[ "def", "__setitem__", "(", "self", ",", "i", ",", "item", ")", ":", "self", ".", "components", ".", "__setitem__", "(", "i", ",", "item", ")" ]
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3/s3navigation.py#L1130-L1139
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/pyparsing.py
python
ParseResults.__setitem__
( self, k, v, isinstance=isinstance )
[]
def __setitem__( self, k, v, isinstance=isinstance ): if isinstance(v,_ParseResultsWithOffset): self.__tokdict[k] = self.__tokdict.get(k,list()) + [v] sub = v[0] elif isinstance(k,(int,slice)): self.__toklist[k] = v sub = v else: self.__tokdict[k] = self.__tokdict.get(k,list()) + [_ParseResultsWithOffset(v,0)] sub = v if isinstance(sub,ParseResults): sub.__parent = wkref(self)
[ "def", "__setitem__", "(", "self", ",", "k", ",", "v", ",", "isinstance", "=", "isinstance", ")", ":", "if", "isinstance", "(", "v", ",", "_ParseResultsWithOffset", ")", ":", "self", ".", "__tokdict", "[", "k", "]", "=", "self", ".", "__tokdict", ".", ...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/pyparsing.py#L397-L408
web2py/web2py
095905c4e010a1426c729483d912e270a51b7ba8
gluon/contrib/login_methods/motp_auth.py
python
motp_auth
(db=DAL('sqlite://storage.sqlite'), time_offset=60)
return motp_auth_aux
motp allows you to login with a one time password(OTP) generated on a motp client, motp clients are available for practically all platforms. to know more about OTP visit http://en.wikipedia.org/wiki/One-time_password to know more visit http://motp.sourceforge.net Written by Madhukar R Pai (madspai@gmail.com) License : MIT or GPL v2 thanks and credits to the web2py community to use motp_auth: motp_auth.py has to be located in gluon/contrib/login_methods/ folder first auth_user has to have 2 extra fields - motp_secret and motp_pin for that define auth like shown below: ## after auth = Auth(db) db.define_table( auth.settings.table_user_name, Field('first_name', length=128, default=''), Field('last_name', length=128, default=''), Field('email', length=128, default='', unique=True), # required Field('password', 'password', length=512, # required readable=False, label='Password'), Field('motp_secret',length=512,default='', label='MOTP Seceret'), Field('motp_pin',length=128,default='', label='MOTP PIN'), Field('registration_key', length=512, # required writable=False, readable=False, default=''), Field('reset_password_key', length=512, # required writable=False, readable=False, default=''), Field('registration_id', length=512, # required writable=False, readable=False, default='')) ##validators custom_auth_table = db[auth.settings.table_user_name] # get the custom_auth_table custom_auth_table.first_name.requires = \ IS_NOT_EMPTY(error_message=auth.messages.is_empty) custom_auth_table.last_name.requires = \ IS_NOT_EMPTY(error_message=auth.messages.is_empty) custom_auth_table.password.requires = CRYPT() custom_auth_table.email.requires = [ IS_EMAIL(error_message=auth.messages.invalid_email), IS_NOT_IN_DB(db, custom_auth_table.email)] auth.settings.table_user = custom_auth_table # tell auth to use custom_auth_table ## before auth.define_tables() ##after that: from gluon.contrib.login_methods.motp_auth import motp_auth auth.settings.login_methods.append(motp_auth(db=db)) ##Instructions for using MOTP - after configuring motp for web2py, Install a MOTP client on your phone (android,IOS, java, windows phone, etc) - initialize the motp client (to reset a motp secret type in #**#), During user creation enter the secret generated during initialization into the motp_secret field in auth_user and similarly enter a pre-decided pin into the motp_pin - done.. to login, just generate a fresh OTP by typing in the pin and use the OTP as password ###To Dos### - both motp_secret and pin are stored in plain text! need to have some way of encrypting - web2py stores the password in db on successful login (should not happen) - maybe some utility or page to check the otp would be useful - as of now user field is hardcoded to email. Some way of selecting user table and user field.
motp allows you to login with a one time password(OTP) generated on a motp client, motp clients are available for practically all platforms. to know more about OTP visit http://en.wikipedia.org/wiki/One-time_password to know more visit http://motp.sourceforge.net
[ "motp", "allows", "you", "to", "login", "with", "a", "one", "time", "password", "(", "OTP", ")", "generated", "on", "a", "motp", "client", "motp", "clients", "are", "available", "for", "practically", "all", "platforms", ".", "to", "know", "more", "about", ...
def motp_auth(db=DAL('sqlite://storage.sqlite'), time_offset=60): """ motp allows you to login with a one time password(OTP) generated on a motp client, motp clients are available for practically all platforms. to know more about OTP visit http://en.wikipedia.org/wiki/One-time_password to know more visit http://motp.sourceforge.net Written by Madhukar R Pai (madspai@gmail.com) License : MIT or GPL v2 thanks and credits to the web2py community to use motp_auth: motp_auth.py has to be located in gluon/contrib/login_methods/ folder first auth_user has to have 2 extra fields - motp_secret and motp_pin for that define auth like shown below: ## after auth = Auth(db) db.define_table( auth.settings.table_user_name, Field('first_name', length=128, default=''), Field('last_name', length=128, default=''), Field('email', length=128, default='', unique=True), # required Field('password', 'password', length=512, # required readable=False, label='Password'), Field('motp_secret',length=512,default='', label='MOTP Seceret'), Field('motp_pin',length=128,default='', label='MOTP PIN'), Field('registration_key', length=512, # required writable=False, readable=False, default=''), Field('reset_password_key', length=512, # required writable=False, readable=False, default=''), Field('registration_id', length=512, # required writable=False, readable=False, default='')) ##validators custom_auth_table = db[auth.settings.table_user_name] # get the custom_auth_table custom_auth_table.first_name.requires = \ IS_NOT_EMPTY(error_message=auth.messages.is_empty) custom_auth_table.last_name.requires = \ IS_NOT_EMPTY(error_message=auth.messages.is_empty) custom_auth_table.password.requires = CRYPT() custom_auth_table.email.requires = [ IS_EMAIL(error_message=auth.messages.invalid_email), IS_NOT_IN_DB(db, custom_auth_table.email)] auth.settings.table_user = custom_auth_table # tell auth to use custom_auth_table ## before auth.define_tables() ##after that: from gluon.contrib.login_methods.motp_auth import motp_auth auth.settings.login_methods.append(motp_auth(db=db)) ##Instructions for using MOTP - after configuring motp for web2py, Install a MOTP client on your phone (android,IOS, java, windows phone, etc) - initialize the motp client (to reset a motp secret type in #**#), During user creation enter the secret generated during initialization into the motp_secret field in auth_user and similarly enter a pre-decided pin into the motp_pin - done.. to login, just generate a fresh OTP by typing in the pin and use the OTP as password ###To Dos### - both motp_secret and pin are stored in plain text! need to have some way of encrypting - web2py stores the password in db on successful login (should not happen) - maybe some utility or page to check the otp would be useful - as of now user field is hardcoded to email. Some way of selecting user table and user field. """ def verify_otp(otp, pin, secret, offset=60): epoch_time = int(time.time()) time_start = int(str(epoch_time - offset)[:-1]) time_end = int(str(epoch_time + offset)[:-1]) for t in range(time_start - 1, time_end + 1): to_hash = str(t) + secret + pin hash = md5(to_hash).hexdigest()[:6] if otp == hash: return True return False def motp_auth_aux(email, password, db=db, offset=time_offset): if db: user_data = db(db.auth_user.email == email).select().first() if user_data: if user_data['motp_secret'] and user_data['motp_pin']: motp_secret = user_data['motp_secret'] motp_pin = user_data['motp_pin'] otp_check = verify_otp( password, motp_pin, motp_secret, offset=offset) if otp_check: return True else: return False else: return False return False return motp_auth_aux
[ "def", "motp_auth", "(", "db", "=", "DAL", "(", "'sqlite://storage.sqlite'", ")", ",", "time_offset", "=", "60", ")", ":", "def", "verify_otp", "(", "otp", ",", "pin", ",", "secret", ",", "offset", "=", "60", ")", ":", "epoch_time", "=", "int", "(", ...
https://github.com/web2py/web2py/blob/095905c4e010a1426c729483d912e270a51b7ba8/gluon/contrib/login_methods/motp_auth.py#L8-L111
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/27/Doc/jinja2/environment.py
python
Environment.handle_exception
(self, exc_info=None, rendered=False, source_hint=None)
Exception handling helper. This is used internally to either raise rewritten exceptions or return a rendered traceback for the template.
Exception handling helper. This is used internally to either raise rewritten exceptions or return a rendered traceback for the template.
[ "Exception", "handling", "helper", ".", "This", "is", "used", "internally", "to", "either", "raise", "rewritten", "exceptions", "or", "return", "a", "rendered", "traceback", "for", "the", "template", "." ]
def handle_exception(self, exc_info=None, rendered=False, source_hint=None): """Exception handling helper. This is used internally to either raise rewritten exceptions or return a rendered traceback for the template. """ global _make_traceback if exc_info is None: exc_info = sys.exc_info() # the debugging module is imported when it's used for the first time. # we're doing a lot of stuff there and for applications that do not # get any exceptions in template rendering there is no need to load # all of that. if _make_traceback is None: from jinja2.debug import make_traceback as _make_traceback traceback = _make_traceback(exc_info, source_hint) if rendered and self.exception_formatter is not None: return self.exception_formatter(traceback) if self.exception_handler is not None: self.exception_handler(traceback) exc_type, exc_value, tb = traceback.standard_exc_info raise exc_type, exc_value, tb
[ "def", "handle_exception", "(", "self", ",", "exc_info", "=", "None", ",", "rendered", "=", "False", ",", "source_hint", "=", "None", ")", ":", "global", "_make_traceback", "if", "exc_info", "is", "None", ":", "exc_info", "=", "sys", ".", "exc_info", "(", ...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Doc/jinja2/environment.py#L494-L514
ialbert/biostar-central
2dc7bd30691a50b2da9c2833ba354056bc686afa
biostar/recipes/forms.py
python
clean_file
(fobj, user, project, check_name=True)
return fobj
[]
def clean_file(fobj, user, project, check_name=True): if not fobj: return fobj check_size(fobj=fobj, maxsize=settings.MAX_FILE_SIZE_MB) check_upload_limit(file=fobj, user=user) # Check if this name already exists. if check_name and Data.objects.filter(name=fobj.name, project=project).exists(): msg = "Name already exists. Upload another file or rename existing data." raise forms.ValidationError(msg) return fobj
[ "def", "clean_file", "(", "fobj", ",", "user", ",", "project", ",", "check_name", "=", "True", ")", ":", "if", "not", "fobj", ":", "return", "fobj", "check_size", "(", "fobj", "=", "fobj", ",", "maxsize", "=", "settings", ".", "MAX_FILE_SIZE_MB", ")", ...
https://github.com/ialbert/biostar-central/blob/2dc7bd30691a50b2da9c2833ba354056bc686afa/biostar/recipes/forms.py#L92-L105
ChineseGLUE/ChineseGLUE
1591b85cf5427c2ff60f718d359ecb71d2b44879
baselines/models/xlnet/run_classifier_thucnews.py
python
LCQMCProcessor.get_test_examples
(self, data_dir)
return self._create_examples( self._read_tsv(os.path.join(data_dir, "test.txt")), "test")
See base class.
See base class.
[ "See", "base", "class", "." ]
def get_test_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "test.txt")), "test")
[ "def", "get_test_examples", "(", "self", ",", "data_dir", ")", ":", "return", "self", ".", "_create_examples", "(", "self", ".", "_read_tsv", "(", "os", ".", "path", ".", "join", "(", "data_dir", ",", "\"test.txt\"", ")", ")", ",", "\"test\"", ")" ]
https://github.com/ChineseGLUE/ChineseGLUE/blob/1591b85cf5427c2ff60f718d359ecb71d2b44879/baselines/models/xlnet/run_classifier_thucnews.py#L498-L501
Qidian213/deep_sort_yolov3
df913275777ecaee19b4a99ea1889ac6063c0a4b
convert.py
python
unique_config_sections
(config_file)
return output_stream
Convert all config sections to have unique names. Adds unique suffixes to config sections for compability with configparser.
Convert all config sections to have unique names.
[ "Convert", "all", "config", "sections", "to", "have", "unique", "names", "." ]
def unique_config_sections(config_file): """Convert all config sections to have unique names. Adds unique suffixes to config sections for compability with configparser. """ section_counters = defaultdict(int) output_stream = io.StringIO() with open(config_file) as fin: for line in fin: if line.startswith('['): section = line.strip().strip('[]') _section = section + '_' + str(section_counters[section]) section_counters[section] += 1 line = line.replace(section, _section) output_stream.write(line) output_stream.seek(0) return output_stream
[ "def", "unique_config_sections", "(", "config_file", ")", ":", "section_counters", "=", "defaultdict", "(", "int", ")", "output_stream", "=", "io", ".", "StringIO", "(", ")", "with", "open", "(", "config_file", ")", "as", "fin", ":", "for", "line", "in", "...
https://github.com/Qidian213/deep_sort_yolov3/blob/df913275777ecaee19b4a99ea1889ac6063c0a4b/convert.py#L34-L50
Qiskit/qiskit-terra
b66030e3b9192efdd3eb95cf25c6545fe0a13da4
qiskit/quantum_info/synthesis/clifford_decompose.py
python
_from_pair_paulis_to_type
(pauli_x, pauli_z, qubit)
return [type_x, type_z]
Converts a pair of Paulis pauli_x and pauli_z into a type
Converts a pair of Paulis pauli_x and pauli_z into a type
[ "Converts", "a", "pair", "of", "Paulis", "pauli_x", "and", "pauli_z", "into", "a", "type" ]
def _from_pair_paulis_to_type(pauli_x, pauli_z, qubit): """Converts a pair of Paulis pauli_x and pauli_z into a type""" type_x = [pauli_x.z[qubit], pauli_x.x[qubit]] type_z = [pauli_z.z[qubit], pauli_z.x[qubit]] return [type_x, type_z]
[ "def", "_from_pair_paulis_to_type", "(", "pauli_x", ",", "pauli_z", ",", "qubit", ")", ":", "type_x", "=", "[", "pauli_x", ".", "z", "[", "qubit", "]", ",", "pauli_x", ".", "x", "[", "qubit", "]", "]", "type_z", "=", "[", "pauli_z", ".", "z", "[", ...
https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/quantum_info/synthesis/clifford_decompose.py#L577-L582
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/scatterpolar/marker/_line.py
python
Line.colorscale
(self)
return self["colorscale"]
Sets the colorscale. Has an effect only if in `marker.line.color`is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,Cividis,Earth,Electric, Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,RdBu,Reds,Viridis, YlGnBu,YlOrRd. The 'colorscale' property is a colorscale and may be specified as: - A list of colors that will be spaced evenly to create the colorscale. Many predefined colorscale lists are included in the sequential, diverging, and cyclical modules in the plotly.colors package. - A list of 2-element lists where the first element is the normalized color level value (starting at 0 and ending at 1), and the second item is a valid color string. (e.g. [[0, 'green'], [0.5, 'red'], [1.0, 'rgb(0, 0, 255)']]) - One of the following named colorscales: ['aggrnyl', 'agsunset', 'algae', 'amp', 'armyrose', 'balance', 'blackbody', 'bluered', 'blues', 'blugrn', 'bluyl', 'brbg', 'brwnyl', 'bugn', 'bupu', 'burg', 'burgyl', 'cividis', 'curl', 'darkmint', 'deep', 'delta', 'dense', 'earth', 'edge', 'electric', 'emrld', 'fall', 'geyser', 'gnbu', 'gray', 'greens', 'greys', 'haline', 'hot', 'hsv', 'ice', 'icefire', 'inferno', 'jet', 'magenta', 'magma', 'matter', 'mint', 'mrybm', 'mygbm', 'oranges', 'orrd', 'oryel', 'oxy', 'peach', 'phase', 'picnic', 'pinkyl', 'piyg', 'plasma', 'plotly3', 'portland', 'prgn', 'pubu', 'pubugn', 'puor', 'purd', 'purp', 'purples', 'purpor', 'rainbow', 'rdbu', 'rdgy', 'rdpu', 'rdylbu', 'rdylgn', 'redor', 'reds', 'solar', 'spectral', 'speed', 'sunset', 'sunsetdark', 'teal', 'tealgrn', 'tealrose', 'tempo', 'temps', 'thermal', 'tropic', 'turbid', 'turbo', 'twilight', 'viridis', 'ylgn', 'ylgnbu', 'ylorbr', 'ylorrd']. Appending '_r' to a named colorscale reverses it. Returns ------- str
Sets the colorscale. Has an effect only if in `marker.line.color`is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,Cividis,Earth,Electric, Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,RdBu,Reds,Viridis, YlGnBu,YlOrRd. The 'colorscale' property is a colorscale and may be specified as: - A list of colors that will be spaced evenly to create the colorscale. Many predefined colorscale lists are included in the sequential, diverging, and cyclical modules in the plotly.colors package. - A list of 2-element lists where the first element is the normalized color level value (starting at 0 and ending at 1), and the second item is a valid color string. (e.g. [[0, 'green'], [0.5, 'red'], [1.0, 'rgb(0, 0, 255)']]) - One of the following named colorscales: ['aggrnyl', 'agsunset', 'algae', 'amp', 'armyrose', 'balance', 'blackbody', 'bluered', 'blues', 'blugrn', 'bluyl', 'brbg', 'brwnyl', 'bugn', 'bupu', 'burg', 'burgyl', 'cividis', 'curl', 'darkmint', 'deep', 'delta', 'dense', 'earth', 'edge', 'electric', 'emrld', 'fall', 'geyser', 'gnbu', 'gray', 'greens', 'greys', 'haline', 'hot', 'hsv', 'ice', 'icefire', 'inferno', 'jet', 'magenta', 'magma', 'matter', 'mint', 'mrybm', 'mygbm', 'oranges', 'orrd', 'oryel', 'oxy', 'peach', 'phase', 'picnic', 'pinkyl', 'piyg', 'plasma', 'plotly3', 'portland', 'prgn', 'pubu', 'pubugn', 'puor', 'purd', 'purp', 'purples', 'purpor', 'rainbow', 'rdbu', 'rdgy', 'rdpu', 'rdylbu', 'rdylgn', 'redor', 'reds', 'solar', 'spectral', 'speed', 'sunset', 'sunsetdark', 'teal', 'tealgrn', 'tealrose', 'tempo', 'temps', 'thermal', 'tropic', 'turbid', 'turbo', 'twilight', 'viridis', 'ylgn', 'ylgnbu', 'ylorbr', 'ylorrd']. Appending '_r' to a named colorscale reverses it.
[ "Sets", "the", "colorscale", ".", "Has", "an", "effect", "only", "if", "in", "marker", ".", "line", ".", "color", "is", "set", "to", "a", "numerical", "array", ".", "The", "colorscale", "must", "be", "an", "array", "containing", "arrays", "mapping", "a",...
def colorscale(self): """ Sets the colorscale. Has an effect only if in `marker.line.color`is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,Cividis,Earth,Electric, Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,RdBu,Reds,Viridis, YlGnBu,YlOrRd. The 'colorscale' property is a colorscale and may be specified as: - A list of colors that will be spaced evenly to create the colorscale. Many predefined colorscale lists are included in the sequential, diverging, and cyclical modules in the plotly.colors package. - A list of 2-element lists where the first element is the normalized color level value (starting at 0 and ending at 1), and the second item is a valid color string. (e.g. [[0, 'green'], [0.5, 'red'], [1.0, 'rgb(0, 0, 255)']]) - One of the following named colorscales: ['aggrnyl', 'agsunset', 'algae', 'amp', 'armyrose', 'balance', 'blackbody', 'bluered', 'blues', 'blugrn', 'bluyl', 'brbg', 'brwnyl', 'bugn', 'bupu', 'burg', 'burgyl', 'cividis', 'curl', 'darkmint', 'deep', 'delta', 'dense', 'earth', 'edge', 'electric', 'emrld', 'fall', 'geyser', 'gnbu', 'gray', 'greens', 'greys', 'haline', 'hot', 'hsv', 'ice', 'icefire', 'inferno', 'jet', 'magenta', 'magma', 'matter', 'mint', 'mrybm', 'mygbm', 'oranges', 'orrd', 'oryel', 'oxy', 'peach', 'phase', 'picnic', 'pinkyl', 'piyg', 'plasma', 'plotly3', 'portland', 'prgn', 'pubu', 'pubugn', 'puor', 'purd', 'purp', 'purples', 'purpor', 'rainbow', 'rdbu', 'rdgy', 'rdpu', 'rdylbu', 'rdylgn', 'redor', 'reds', 'solar', 'spectral', 'speed', 'sunset', 'sunsetdark', 'teal', 'tealgrn', 'tealrose', 'tempo', 'temps', 'thermal', 'tropic', 'turbid', 'turbo', 'twilight', 'viridis', 'ylgn', 'ylgnbu', 'ylorbr', 'ylorrd']. Appending '_r' to a named colorscale reverses it. Returns ------- str """ return self["colorscale"]
[ "def", "colorscale", "(", "self", ")", ":", "return", "self", "[", "\"colorscale\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/scatterpolar/marker/_line.py#L243-L289
django/channels
6af1bc3ab45f55e3f47d0d1d059d5db0a18a9581
channels/generic/websocket.py
python
WebsocketConsumer.receive
(self, text_data=None, bytes_data=None)
Called with a decoded WebSocket frame.
Called with a decoded WebSocket frame.
[ "Called", "with", "a", "decoded", "WebSocket", "frame", "." ]
def receive(self, text_data=None, bytes_data=None): """ Called with a decoded WebSocket frame. """ pass
[ "def", "receive", "(", "self", ",", "text_data", "=", "None", ",", "bytes_data", "=", "None", ")", ":", "pass" ]
https://github.com/django/channels/blob/6af1bc3ab45f55e3f47d0d1d059d5db0a18a9581/channels/generic/websocket.py#L63-L67
SublimeText-Markdown/MarkdownEditing
ec66bbee7396a3fec10a29cfc0fa30ec073a4e91
plugins/folding.py
python
urls_to_fold
(view)
return [url for url in url_regions(view) if not any(url.contains(sel) for sel in view.sel())]
Returns a list of url regions to fold. Returns all url regions but those a caret is placed within or which are partly selected. :param view: The view :param region: The region urls to return for. :returns: A list of regions
Returns a list of url regions to fold.
[ "Returns", "a", "list", "of", "url", "regions", "to", "fold", "." ]
def urls_to_fold(view): """ Returns a list of url regions to fold. Returns all url regions but those a caret is placed within or which are partly selected. :param view: The view :param region: The region urls to return for. :returns: A list of regions """ if not view.settings().get("mde.auto_fold_link.enabled", True): return [] return [url for url in url_regions(view) if not any(url.contains(sel) for sel in view.sel())]
[ "def", "urls_to_fold", "(", "view", ")", ":", "if", "not", "view", ".", "settings", "(", ")", ".", "get", "(", "\"mde.auto_fold_link.enabled\"", ",", "True", ")", ":", "return", "[", "]", "return", "[", "url", "for", "url", "in", "url_regions", "(", "v...
https://github.com/SublimeText-Markdown/MarkdownEditing/blob/ec66bbee7396a3fec10a29cfc0fa30ec073a4e91/plugins/folding.py#L154-L168
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/tools/sqli/thirdparty/chardet/mbcharsetprober.py
python
MultiByteCharSetProber.feed
(self, aBuf)
return self.get_state()
[]
def feed(self, aBuf): aLen = len(aBuf) for i in xrange(0, aLen): codingState = self._mCodingSM.next_state(aBuf[i]) if codingState == eError: if constants._debug: sys.stderr.write(self.get_charset_name() + ' prober hit error at byte ' + str(i) + '\n') self._mState = constants.eNotMe break elif codingState == eItsMe: self._mState = constants.eFoundIt break elif codingState == eStart: charLen = self._mCodingSM.get_current_charlen() if i == 0: self._mLastChar[1] = aBuf[0] self._mDistributionAnalyzer.feed(self._mLastChar, charLen) else: self._mDistributionAnalyzer.feed(aBuf[i-1:i+1], charLen) self._mLastChar[0] = aBuf[aLen - 1] if self.get_state() == constants.eDetecting: if self._mDistributionAnalyzer.got_enough_data() and \ (self.get_confidence() > constants.SHORTCUT_THRESHOLD): self._mState = constants.eFoundIt return self.get_state()
[ "def", "feed", "(", "self", ",", "aBuf", ")", ":", "aLen", "=", "len", "(", "aBuf", ")", "for", "i", "in", "xrange", "(", "0", ",", "aLen", ")", ":", "codingState", "=", "self", ".", "_mCodingSM", ".", "next_state", "(", "aBuf", "[", "i", "]", ...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/sqli/thirdparty/chardet/mbcharsetprober.py#L52-L79
materialsproject/pymatgen
8128f3062a334a2edd240e4062b5b9bdd1ae6f58
pymatgen/io/vasp/sets.py
python
MPNonSCFSet.override_from_prev_calc
(self, prev_calc_dir=".")
return self
Update the input set to include settings from a previous calculation. Args: prev_calc_dir (str): The path to the previous calculation directory. Returns: The input set with the settings (structure, k-points, incar, etc) updated using the previous VASP run.
Update the input set to include settings from a previous calculation.
[ "Update", "the", "input", "set", "to", "include", "settings", "from", "a", "previous", "calculation", "." ]
def override_from_prev_calc(self, prev_calc_dir="."): """ Update the input set to include settings from a previous calculation. Args: prev_calc_dir (str): The path to the previous calculation directory. Returns: The input set with the settings (structure, k-points, incar, etc) updated using the previous VASP run. """ vasprun, outcar = get_vasprun_outcar(prev_calc_dir) self.prev_incar = vasprun.incar # Get a Magmom-decorated structure self._structure = get_structure_from_prev_run(vasprun, outcar) if self.standardize: warnings.warn( "Use of standardize=True with from_prev_run is not " "recommended as there is no guarantee the copied " "files will be appropriate for the standardized" " structure. copy_chgcar is enforced to be false." ) self.copy_chgcar = False # Turn off spin when magmom for every site is smaller than 0.02. if outcar and outcar.magnetization: site_magmom = np.array([i["tot"] for i in outcar.magnetization]) ispin = 2 if np.any(site_magmom[np.abs(site_magmom) > 0.02]) else 1 elif vasprun.is_spin: ispin = 2 else: ispin = 1 nbands = int(np.ceil(vasprun.parameters["NBANDS"] * self.nbands_factor)) self.prev_incar.update({"ISPIN": ispin, "NBANDS": nbands}) files_to_transfer = {} if self.copy_chgcar: chgcars = sorted(glob.glob(str(Path(prev_calc_dir) / "CHGCAR*"))) if chgcars: files_to_transfer["CHGCAR"] = str(chgcars[-1]) self.files_to_transfer.update(files_to_transfer) # multiply the reciprocal density if needed: if self.small_gap_multiply: gap = vasprun.eigenvalue_band_properties[0] if gap <= self.small_gap_multiply[0]: self.reciprocal_density = self.reciprocal_density * self.small_gap_multiply[1] self.kpoints_line_density = self.kpoints_line_density * self.small_gap_multiply[1] # automatic setting of nedos using the energy range and the energy step dedos if self.nedos == 0: emax = max(eigs.max() for eigs in vasprun.eigenvalues.values()) emin = min(eigs.min() for eigs in vasprun.eigenvalues.values()) self.nedos = int((emax - emin) / self.dedos) return self
[ "def", "override_from_prev_calc", "(", "self", ",", "prev_calc_dir", "=", "\".\"", ")", ":", "vasprun", ",", "outcar", "=", "get_vasprun_outcar", "(", "prev_calc_dir", ")", "self", ".", "prev_incar", "=", "vasprun", ".", "incar", "# Get a Magmom-decorated structure"...
https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/io/vasp/sets.py#L1694-L1757
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/_pyio.py
python
BytesIO.getvalue
(self)
return bytes(self._buffer)
Return the bytes value (contents) of the buffer
Return the bytes value (contents) of the buffer
[ "Return", "the", "bytes", "value", "(", "contents", ")", "of", "the", "buffer" ]
def getvalue(self): """Return the bytes value (contents) of the buffer """ if self.closed: raise ValueError("getvalue on closed file") return bytes(self._buffer)
[ "def", "getvalue", "(", "self", ")", ":", "if", "self", ".", "closed", ":", "raise", "ValueError", "(", "\"getvalue on closed file\"", ")", "return", "bytes", "(", "self", ".", "_buffer", ")" ]
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/_pyio.py#L858-L863
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/numpy/lib/nanfunctions.py
python
nansum
(a, axis=None, dtype=None, out=None, keepdims=np._NoValue)
return np.sum(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero. In NumPy versions <= 1.8.0 Nan is returned for slices that are all-NaN or empty. In later versions zero is returned. Parameters ---------- a : array_like Array containing numbers whose sum is desired. If `a` is not an array, a conversion is attempted. axis : int, optional Axis along which the sum is computed. The default is to compute the sum of the flattened array. dtype : data-type, optional The type of the returned array and of the accumulator in which the elements are summed. By default, the dtype of `a` is used. An exception is when `a` has an integer type with less precision than the platform (u)intp. In that case, the default will be either (u)int32 or (u)int64 depending on whether the platform is 32 or 64 bits. For inexact inputs, dtype must be inexact. .. versionadded:: 1.8.0 out : ndarray, optional Alternate output array in which to place the result. The default is ``None``. If provided, it must have the same shape as the expected output, but the type will be cast if necessary. See `doc.ufuncs` for details. The casting of NaN to integer can yield unexpected results. .. versionadded:: 1.8.0 keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `a`. If the value is anything but the default, then `keepdims` will be passed through to the `mean` or `sum` methods of sub-classes of `ndarray`. If the sub-classes methods does not implement `keepdims` any exceptions will be raised. .. versionadded:: 1.8.0 Returns ------- nansum : ndarray. A new array holding the result is returned unless `out` is specified, in which it is returned. The result has the same size as `a`, and the same shape as `a` if `axis` is not None or `a` is a 1-d array. See Also -------- numpy.sum : Sum across array propagating NaNs. isnan : Show which elements are NaN. isfinite: Show which elements are not NaN or +/-inf. Notes ----- If both positive and negative infinity are present, the sum will be Not A Number (NaN). Examples -------- >>> np.nansum(1) 1 >>> np.nansum([1]) 1 >>> np.nansum([1, np.nan]) 1.0 >>> a = np.array([[1, 1], [1, np.nan]]) >>> np.nansum(a) 3.0 >>> np.nansum(a, axis=0) array([ 2., 1.]) >>> np.nansum([1, np.nan, np.inf]) inf >>> np.nansum([1, np.nan, np.NINF]) -inf >>> np.nansum([1, np.nan, np.inf, -np.inf]) # both +/- infinity present nan
Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.
[ "Return", "the", "sum", "of", "array", "elements", "over", "a", "given", "axis", "treating", "Not", "a", "Numbers", "(", "NaNs", ")", "as", "zero", "." ]
def nansum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue): """ Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero. In NumPy versions <= 1.8.0 Nan is returned for slices that are all-NaN or empty. In later versions zero is returned. Parameters ---------- a : array_like Array containing numbers whose sum is desired. If `a` is not an array, a conversion is attempted. axis : int, optional Axis along which the sum is computed. The default is to compute the sum of the flattened array. dtype : data-type, optional The type of the returned array and of the accumulator in which the elements are summed. By default, the dtype of `a` is used. An exception is when `a` has an integer type with less precision than the platform (u)intp. In that case, the default will be either (u)int32 or (u)int64 depending on whether the platform is 32 or 64 bits. For inexact inputs, dtype must be inexact. .. versionadded:: 1.8.0 out : ndarray, optional Alternate output array in which to place the result. The default is ``None``. If provided, it must have the same shape as the expected output, but the type will be cast if necessary. See `doc.ufuncs` for details. The casting of NaN to integer can yield unexpected results. .. versionadded:: 1.8.0 keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `a`. If the value is anything but the default, then `keepdims` will be passed through to the `mean` or `sum` methods of sub-classes of `ndarray`. If the sub-classes methods does not implement `keepdims` any exceptions will be raised. .. versionadded:: 1.8.0 Returns ------- nansum : ndarray. A new array holding the result is returned unless `out` is specified, in which it is returned. The result has the same size as `a`, and the same shape as `a` if `axis` is not None or `a` is a 1-d array. See Also -------- numpy.sum : Sum across array propagating NaNs. isnan : Show which elements are NaN. isfinite: Show which elements are not NaN or +/-inf. Notes ----- If both positive and negative infinity are present, the sum will be Not A Number (NaN). Examples -------- >>> np.nansum(1) 1 >>> np.nansum([1]) 1 >>> np.nansum([1, np.nan]) 1.0 >>> a = np.array([[1, 1], [1, np.nan]]) >>> np.nansum(a) 3.0 >>> np.nansum(a, axis=0) array([ 2., 1.]) >>> np.nansum([1, np.nan, np.inf]) inf >>> np.nansum([1, np.nan, np.NINF]) -inf >>> np.nansum([1, np.nan, np.inf, -np.inf]) # both +/- infinity present nan """ a, mask = _replace_nan(a, 0) return np.sum(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
[ "def", "nansum", "(", "a", ",", "axis", "=", "None", ",", "dtype", "=", "None", ",", "out", "=", "None", ",", "keepdims", "=", "np", ".", "_NoValue", ")", ":", "a", ",", "mask", "=", "_replace_nan", "(", "a", ",", "0", ")", "return", "np", ".",...
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/numpy/lib/nanfunctions.py#L451-L538
aws/aws-sam-cli
2aa7bf01b2e0b0864ef63b1898a8b30577443acc
samcli/lib/utils/sam_logging.py
python
SamCliLogger.configure_logger
(logger, formatter, level)
Configure a Logger with the level provided and also the first handler's formatter. If there is no handler in the logger, a new StreamHandler will be added. Parameters ---------- logger logging.getLogger Logger to configure formatter logging.formatter Formatter for the logger
Configure a Logger with the level provided and also the first handler's formatter. If there is no handler in the logger, a new StreamHandler will be added.
[ "Configure", "a", "Logger", "with", "the", "level", "provided", "and", "also", "the", "first", "handler", "s", "formatter", ".", "If", "there", "is", "no", "handler", "in", "the", "logger", "a", "new", "StreamHandler", "will", "be", "added", "." ]
def configure_logger(logger, formatter, level): """ Configure a Logger with the level provided and also the first handler's formatter. If there is no handler in the logger, a new StreamHandler will be added. Parameters ---------- logger logging.getLogger Logger to configure formatter logging.formatter Formatter for the logger """ handlers = logger.handlers if handlers: log_stream_handler = handlers[0] else: log_stream_handler = logging.StreamHandler() logger.addHandler(log_stream_handler) log_stream_handler.setLevel(logging.DEBUG) log_stream_handler.setFormatter(formatter) logger.setLevel(level) logger.propagate = False
[ "def", "configure_logger", "(", "logger", ",", "formatter", ",", "level", ")", ":", "handlers", "=", "logger", ".", "handlers", "if", "handlers", ":", "log_stream_handler", "=", "handlers", "[", "0", "]", "else", ":", "log_stream_handler", "=", "logging", "....
https://github.com/aws/aws-sam-cli/blob/2aa7bf01b2e0b0864ef63b1898a8b30577443acc/samcli/lib/utils/sam_logging.py#L16-L39
cylc/cylc-flow
5ec221143476c7c616c156b74158edfbcd83794a
cylc/flow/terminal.py
python
get_width
(default=80)
Return the terminal width or `default` if it is not determinable.
Return the terminal width or `default` if it is not determinable.
[ "Return", "the", "terminal", "width", "or", "default", "if", "it", "is", "not", "determinable", "." ]
def get_width(default=80): """Return the terminal width or `default` if it is not determinable.""" # stty can have different install locs so don't use absolute path proc = Popen(['stty', 'size'], stdout=PIPE, stderr=PIPE) # nosec if proc.wait(): return default try: return int(proc.communicate()[0].split()[1]) or default except (IndexError, ValueError): return default
[ "def", "get_width", "(", "default", "=", "80", ")", ":", "# stty can have different install locs so don't use absolute path", "proc", "=", "Popen", "(", "[", "'stty'", ",", "'size'", "]", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "# nosec", ...
https://github.com/cylc/cylc-flow/blob/5ec221143476c7c616c156b74158edfbcd83794a/cylc/flow/terminal.py#L56-L65
frerich/clcache
cae73d8255d78db8ba11e23c51fd2c9a89e7475b
clcache/__main__.py
python
CacheFileStrategy.__init__
(self, cacheDirectory=None)
[]
def __init__(self, cacheDirectory=None): self.dir = cacheDirectory if not self.dir: try: self.dir = os.environ["CLCACHE_DIR"] except KeyError: self.dir = os.path.join(os.path.expanduser("~"), "clcache") manifestsRootDir = os.path.join(self.dir, "manifests") ensureDirectoryExists(manifestsRootDir) self.manifestRepository = ManifestRepository(manifestsRootDir) compilerArtifactsRootDir = os.path.join(self.dir, "objects") ensureDirectoryExists(compilerArtifactsRootDir) self.compilerArtifactsRepository = CompilerArtifactsRepository(compilerArtifactsRootDir) self.configuration = Configuration(os.path.join(self.dir, "config.txt")) self.statistics = Statistics(os.path.join(self.dir, "stats.txt"))
[ "def", "__init__", "(", "self", ",", "cacheDirectory", "=", "None", ")", ":", "self", ".", "dir", "=", "cacheDirectory", "if", "not", "self", ".", "dir", ":", "try", ":", "self", ".", "dir", "=", "os", ".", "environ", "[", "\"CLCACHE_DIR\"", "]", "ex...
https://github.com/frerich/clcache/blob/cae73d8255d78db8ba11e23c51fd2c9a89e7475b/clcache/__main__.py#L502-L519
sdaps/sdaps
51d1072185223f5e48512661e2c1e8399d63e876
sdaps/script.py
python
add_project_argument
(parser)
[]
def add_project_argument(parser): parser.add_argument('project', type=str, help=_("project directory|The SDAPS project."))
[ "def", "add_project_argument", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'project'", ",", "type", "=", "str", ",", "help", "=", "_", "(", "\"project directory|The SDAPS project.\"", ")", ")" ]
https://github.com/sdaps/sdaps/blob/51d1072185223f5e48512661e2c1e8399d63e876/sdaps/script.py#L60-L61
lutris/lutris
66675a4d5537f6b2a2ba2b6df0b3cdf8924c823a
lutris/util/wine/wine.py
python
is_gstreamer_build
(wine_path)
return system.path_exists(os.path.join(base_path, "lib64/gstreamer-1.0"))
Returns whether a wine build ships with gstreamer libraries. This allows to set GST_PLUGIN_SYSTEM_PATH_1_0 for the builds that support it.
Returns whether a wine build ships with gstreamer libraries. This allows to set GST_PLUGIN_SYSTEM_PATH_1_0 for the builds that support it.
[ "Returns", "whether", "a", "wine", "build", "ships", "with", "gstreamer", "libraries", ".", "This", "allows", "to", "set", "GST_PLUGIN_SYSTEM_PATH_1_0", "for", "the", "builds", "that", "support", "it", "." ]
def is_gstreamer_build(wine_path): """Returns whether a wine build ships with gstreamer libraries. This allows to set GST_PLUGIN_SYSTEM_PATH_1_0 for the builds that support it. """ base_path = os.path.dirname(os.path.dirname(wine_path)) return system.path_exists(os.path.join(base_path, "lib64/gstreamer-1.0"))
[ "def", "is_gstreamer_build", "(", "wine_path", ")", ":", "base_path", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "wine_path", ")", ")", "return", "system", ".", "path_exists", "(", "os", ".", "path", ".", "join...
https://github.com/lutris/lutris/blob/66675a4d5537f6b2a2ba2b6df0b3cdf8924c823a/lutris/util/wine/wine.py#L131-L136
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/sqlalchemy/sql/elements.py
python
_only_column_elements_or_none
(element, name)
[]
def _only_column_elements_or_none(element, name): if element is None: return None else: return _only_column_elements(element, name)
[ "def", "_only_column_elements_or_none", "(", "element", ",", "name", ")", ":", "if", "element", "is", "None", ":", "return", "None", "else", ":", "return", "_only_column_elements", "(", "element", ",", "name", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/sql/elements.py#L4296-L4300
menpo/menpofit
5f2f45bab26df206d43292fd32d19cd8f62f0443
menpofit/lk/residual.py
python
Residual.steepest_descent_update
(self, sdi, image, template)
r""" Calculates the steepest descent parameter updates. These are defined, for the forward additive algorithm, as: .. math:: \sum_x [ \nabla I \frac{\partial W}{\partial p} ]^T [ T(x) - I(W(x;p)) ] Parameters ---------- J : ``(N, n_params)`` `ndarray` The steepest descent images. image : `menpo.image.Image` Either the warped image or the template (depending on the framework) template : `menpo.image.Image` Either the warped image or the template (depending on the framework) Returns ------- sd_delta_p : ``(n_params,)`` `ndarray` The steepest descent parameter updates.
r""" Calculates the steepest descent parameter updates.
[ "r", "Calculates", "the", "steepest", "descent", "parameter", "updates", "." ]
def steepest_descent_update(self, sdi, image, template): r""" Calculates the steepest descent parameter updates. These are defined, for the forward additive algorithm, as: .. math:: \sum_x [ \nabla I \frac{\partial W}{\partial p} ]^T [ T(x) - I(W(x;p)) ] Parameters ---------- J : ``(N, n_params)`` `ndarray` The steepest descent images. image : `menpo.image.Image` Either the warped image or the template (depending on the framework) template : `menpo.image.Image` Either the warped image or the template (depending on the framework) Returns ------- sd_delta_p : ``(n_params,)`` `ndarray` The steepest descent parameter updates. """ pass
[ "def", "steepest_descent_update", "(", "self", ",", "sdi", ",", "image", ",", "template", ")", ":", "pass" ]
https://github.com/menpo/menpofit/blob/5f2f45bab26df206d43292fd32d19cd8f62f0443/menpofit/lk/residual.py#L109-L132
user-cont/conu
0d8962560f6f7f17fe1be0d434a4809e2a0ea51d
conu/backend/docker/image.py
python
DockerImage.save_to
(self, image)
Save this image to another DockerImage :param image: DockerImage :return:
Save this image to another DockerImage
[ "Save", "this", "image", "to", "another", "DockerImage" ]
def save_to(self, image): """ Save this image to another DockerImage :param image: DockerImage :return: """ if not isinstance(image, self.__class__): raise ConuException("Invalid target image type", type(image)) self.copy(image.name, image.tag, target_transport=image.transport, target_path=image.path, logs=False)
[ "def", "save_to", "(", "self", ",", "image", ")", ":", "if", "not", "isinstance", "(", "image", ",", "self", ".", "__class__", ")", ":", "raise", "ConuException", "(", "\"Invalid target image type\"", ",", "type", "(", "image", ")", ")", "self", ".", "co...
https://github.com/user-cont/conu/blob/0d8962560f6f7f17fe1be0d434a4809e2a0ea51d/conu/backend/docker/image.py#L256-L266
nipreps/mriqc
ad8813035136acc1a80c96ac1fbbdde1d82b14ee
mriqc/workflows/utils.py
python
fwhm_dict
(fwhm)
return { "fwhm_x": fwhm[0], "fwhm_y": fwhm[1], "fwhm_z": fwhm[2], "fwhm_avg": fwhm[3], }
Convert a list of FWHM into a dictionary
Convert a list of FWHM into a dictionary
[ "Convert", "a", "list", "of", "FWHM", "into", "a", "dictionary" ]
def fwhm_dict(fwhm): """Convert a list of FWHM into a dictionary""" fwhm = [float(f) for f in fwhm] return { "fwhm_x": fwhm[0], "fwhm_y": fwhm[1], "fwhm_z": fwhm[2], "fwhm_avg": fwhm[3], }
[ "def", "fwhm_dict", "(", "fwhm", ")", ":", "fwhm", "=", "[", "float", "(", "f", ")", "for", "f", "in", "fwhm", "]", "return", "{", "\"fwhm_x\"", ":", "fwhm", "[", "0", "]", ",", "\"fwhm_y\"", ":", "fwhm", "[", "1", "]", ",", "\"fwhm_z\"", ":", ...
https://github.com/nipreps/mriqc/blob/ad8813035136acc1a80c96ac1fbbdde1d82b14ee/mriqc/workflows/utils.py#L56-L64
sabnzbd/sabnzbd
52d21e94d3cc6e30764a833fe2a256783d1a8931
sabnzbd/filesystem.py
python
sanitize_filename
(name: str)
return name + ext
Return filename with illegal chars converted to legal ones and with the par2 extension always in lowercase
Return filename with illegal chars converted to legal ones and with the par2 extension always in lowercase
[ "Return", "filename", "with", "illegal", "chars", "converted", "to", "legal", "ones", "and", "with", "the", "par2", "extension", "always", "in", "lowercase" ]
def sanitize_filename(name: str) -> str: """Return filename with illegal chars converted to legal ones and with the par2 extension always in lowercase """ if not name: return name illegal = CH_ILLEGAL legal = CH_LEGAL if sabnzbd.WIN32 or sabnzbd.cfg.sanitize_safe(): # Remove all bad Windows chars too illegal += CH_ILLEGAL_WIN legal += CH_LEGAL_WIN if ":" in name and sabnzbd.DARWIN: # Compensate for the foolish way par2 on macOS handles a colon character name = name[name.rfind(":") + 1 :] lst = [] for ch in name.strip(): if ch in illegal: ch = legal[illegal.find(ch)] lst.append(ch) name = "".join(lst) if sabnzbd.WIN32 or sabnzbd.cfg.sanitize_safe(): name = replace_win_devices(name) if not name: name = "unknown" # now split name into name, ext name, ext = os.path.splitext(name) # If filename is too long (more than DEF_FILE_MAX bytes), brute-force truncate it, # preserving the extension (max ext length 20) # Note: some filesystem can handle up to 255 UTF chars (which is more than 255 bytes) in the filename, # but we stay on the safe side: max DEF_FILE_MAX bytes if len(utob(name)) + len(utob(ext)) > DEF_FILE_MAX: logging.debug("Filename %s is too long, so truncating", name + ext) # Too long filenames are often caused by incorrect non-ascii chars, # so brute-force remove those non-ascii chars name = ubtou(name.encode("ascii", "ignore")) # Now it's plain ASCII, so no need for len(str.encode()) anymore; plain len() is enough if len(name) + len(ext) > DEF_FILE_MAX: # still too long, limit the extension maxextlength = 20 # max length of an extension if len(ext) > maxextlength: # allow first <maxextlength> chars, including the starting dot ext = ext[:maxextlength] if len(name) + len(ext) > DEF_FILE_MAX: # Still too long, limit the basename name = name[: DEF_FILE_MAX - len(ext)] lowext = ext.lower() if lowext == ".par2" and lowext != ext: ext = lowext return name + ext
[ "def", "sanitize_filename", "(", "name", ":", "str", ")", "->", "str", ":", "if", "not", "name", ":", "return", "name", "illegal", "=", "CH_ILLEGAL", "legal", "=", "CH_LEGAL", "if", "sabnzbd", ".", "WIN32", "or", "sabnzbd", ".", "cfg", ".", "sanitize_saf...
https://github.com/sabnzbd/sabnzbd/blob/52d21e94d3cc6e30764a833fe2a256783d1a8931/sabnzbd/filesystem.py#L185-L243
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
lib-python/2.7/random.py
python
Random.gauss
(self, mu, sigma)
return mu + z*sigma
Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function. Not thread-safe without a lock around calls.
Gaussian distribution.
[ "Gaussian", "distribution", "." ]
def gauss(self, mu, sigma): """Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function. Not thread-safe without a lock around calls. """ # When x and y are two variables from [0, 1), uniformly # distributed, then # # cos(2*pi*x)*sqrt(-2*log(1-y)) # sin(2*pi*x)*sqrt(-2*log(1-y)) # # are two *independent* variables with normal distribution # (mu = 0, sigma = 1). # (Lambert Meertens) # (corrected version; bug discovered by Mike Miller, fixed by LM) # Multithreading note: When two threads call this function # simultaneously, it is possible that they will receive the # same return value. The window is very small though. To # avoid this, you have to use a lock around all calls. (I # didn't want to slow this down in the serial case by using a # lock here.) random = self.random z = self.gauss_next self.gauss_next = None if z is None: x2pi = random() * TWOPI g2rad = _sqrt(-2.0 * _log(1.0 - random())) z = _cos(x2pi) * g2rad self.gauss_next = _sin(x2pi) * g2rad return mu + z*sigma
[ "def", "gauss", "(", "self", ",", "mu", ",", "sigma", ")", ":", "# When x and y are two variables from [0, 1), uniformly", "# distributed, then", "#", "# cos(2*pi*x)*sqrt(-2*log(1-y))", "# sin(2*pi*x)*sqrt(-2*log(1-y))", "#", "# are two *independent* variables with normal distr...
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/random.py#L563-L600
uqfoundation/mystic
154e6302d1f2f94e8f13e88ecc5f24241cc28ac7
models/storn.py
python
Corana.function
(self,coeffs)
return r
r"""evaluates a 4-D Corana's parabola function for a list of coeffs f(x) = \sum_(i=0)^(3) f_0(x) Where for \abs(x_i - z_i) < 0.05: f_0(x) = 0.15*(z_i - 0.05*\sign(z_i))^(2) * d_i and otherwise: f_0(x) = d_i * x_(i)^(2), with z_i = \floor(\abs(x_i/0.2)+0.49999)*\sign(x_i)*0.2 and d_i = 1,1000,10,100. For len(x) == 1, x = x_0,0,0,0; for len(x) == 2, x = x_0,0,x_1,0; for len(x) == 3, x = x_0,0,x_1,x_2; for len(x) >= 4, x = x_0,x_1,x_2,x_3. Inspect with mystic_model_plotter using:: mystic.models.corana -b "-1:1:.01, -1:1:.01" -d -x 1 The minimum is f(x)=0 for \abs(x_i) < 0.05 for all i.
r"""evaluates a 4-D Corana's parabola function for a list of coeffs
[ "r", "evaluates", "a", "4", "-", "D", "Corana", "s", "parabola", "function", "for", "a", "list", "of", "coeffs" ]
def function(self,coeffs): r"""evaluates a 4-D Corana's parabola function for a list of coeffs f(x) = \sum_(i=0)^(3) f_0(x) Where for \abs(x_i - z_i) < 0.05: f_0(x) = 0.15*(z_i - 0.05*\sign(z_i))^(2) * d_i and otherwise: f_0(x) = d_i * x_(i)^(2), with z_i = \floor(\abs(x_i/0.2)+0.49999)*\sign(x_i)*0.2 and d_i = 1,1000,10,100. For len(x) == 1, x = x_0,0,0,0; for len(x) == 2, x = x_0,0,x_1,0; for len(x) == 3, x = x_0,0,x_1,x_2; for len(x) >= 4, x = x_0,x_1,x_2,x_3. Inspect with mystic_model_plotter using:: mystic.models.corana -b "-1:1:.01, -1:1:.01" -d -x 1 The minimum is f(x)=0 for \abs(x_i) < 0.05 for all i.""" d = [1., 1000., 10., 100.] _d = [0, 3, 1, 2] # ordering for lower dimensions #x = asarray(coeffs) #XXX: converting to numpy.array slows by 10x x = [0.]*4 # ensure that there are 4 coefficients if len(coeffs) < 4: _x = x[:] _x[:len(coeffs)]=coeffs for i in range(4): x[_d.index(i)] = _x[i] else: x = coeffs r = 0 for j in range(4): zj = floor( abs(x[j]/0.2) + 0.49999 ) * sign(x[j]) * 0.2 if abs(x[j]-zj) < 0.05: r += 0.15 * pow(zj - 0.05*sign(zj), 2) * d[j] else: r += d[j] * x[j] * x[j] return r
[ "def", "function", "(", "self", ",", "coeffs", ")", ":", "d", "=", "[", "1.", ",", "1000.", ",", "10.", ",", "100.", "]", "_d", "=", "[", "0", ",", "3", ",", "1", ",", "2", "]", "# ordering for lower dimensions", "#x = asarray(coeffs) #XXX: converting to...
https://github.com/uqfoundation/mystic/blob/154e6302d1f2f94e8f13e88ecc5f24241cc28ac7/models/storn.py#L54-L93
pypa/setuptools
9f37366aab9cd8f6baa23e6a77cfdb8daf97757e
setuptools/_vendor/packaging/version.py
python
LegacyVersion.epoch
(self)
return -1
[]
def epoch(self) -> int: return -1
[ "def", "epoch", "(", "self", ")", "->", "int", ":", "return", "-", "1" ]
https://github.com/pypa/setuptools/blob/9f37366aab9cd8f6baa23e6a77cfdb8daf97757e/setuptools/_vendor/packaging/version.py#L132-L133
lfz/Guided-Denoise
8881ab768d16eaf87342da4ff7dc8271e183e205
Attackset/fgsm_ensv3_resv2_inresv2_random/nets/mobilenet_v1.py
python
mobilenet_v1
(inputs, num_classes=1000, dropout_keep_prob=0.999, is_training=True, min_depth=8, depth_multiplier=1.0, conv_defs=None, prediction_fn=tf.contrib.layers.softmax, spatial_squeeze=True, reuse=None, scope='MobilenetV1')
return logits, end_points
Mobilenet v1 model for classification. Args: inputs: a tensor of shape [batch_size, height, width, channels]. num_classes: number of predicted classes. dropout_keep_prob: the percentage of activation values that are retained. is_training: whether is training or not. min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. conv_defs: A list of ConvDef namedtuples specifying the net architecture. prediction_fn: a function to get predictions out of logits. spatial_squeeze: if True, logits is of shape is [B, C], if false logits is of shape [B, 1, 1, C], where B is batch_size and C is number of classes. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. Returns: logits: the pre-softmax activations, a tensor of size [batch_size, num_classes] end_points: a dictionary from components of the network to the corresponding activation. Raises: ValueError: Input rank is invalid.
Mobilenet v1 model for classification.
[ "Mobilenet", "v1", "model", "for", "classification", "." ]
def mobilenet_v1(inputs, num_classes=1000, dropout_keep_prob=0.999, is_training=True, min_depth=8, depth_multiplier=1.0, conv_defs=None, prediction_fn=tf.contrib.layers.softmax, spatial_squeeze=True, reuse=None, scope='MobilenetV1'): """Mobilenet v1 model for classification. Args: inputs: a tensor of shape [batch_size, height, width, channels]. num_classes: number of predicted classes. dropout_keep_prob: the percentage of activation values that are retained. is_training: whether is training or not. min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. conv_defs: A list of ConvDef namedtuples specifying the net architecture. prediction_fn: a function to get predictions out of logits. spatial_squeeze: if True, logits is of shape is [B, C], if false logits is of shape [B, 1, 1, C], where B is batch_size and C is number of classes. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. Returns: logits: the pre-softmax activations, a tensor of size [batch_size, num_classes] end_points: a dictionary from components of the network to the corresponding activation. Raises: ValueError: Input rank is invalid. """ input_shape = inputs.get_shape().as_list() if len(input_shape) != 4: raise ValueError('Invalid input tensor rank, expected 4, was: %d' % len(input_shape)) with tf.variable_scope(scope, 'MobilenetV1', [inputs, num_classes], reuse=reuse) as scope: with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training): net, end_points = mobilenet_v1_base(inputs, scope=scope, min_depth=min_depth, depth_multiplier=depth_multiplier, conv_defs=conv_defs) with tf.variable_scope('Logits'): kernel_size = _reduced_kernel_size_for_small_input(net, [7, 7]) net = slim.avg_pool2d(net, kernel_size, padding='VALID', scope='AvgPool_1a') end_points['AvgPool_1a'] = net # 1 x 1 x 1024 net = slim.dropout(net, keep_prob=dropout_keep_prob, scope='Dropout_1b') logits = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, scope='Conv2d_1c_1x1') if spatial_squeeze: logits = tf.squeeze(logits, [1, 2], name='SpatialSqueeze') end_points['Logits'] = logits if prediction_fn: end_points['Predictions'] = prediction_fn(logits, scope='Predictions') return logits, end_points
[ "def", "mobilenet_v1", "(", "inputs", ",", "num_classes", "=", "1000", ",", "dropout_keep_prob", "=", "0.999", ",", "is_training", "=", "True", ",", "min_depth", "=", "8", ",", "depth_multiplier", "=", "1.0", ",", "conv_defs", "=", "None", ",", "prediction_f...
https://github.com/lfz/Guided-Denoise/blob/8881ab768d16eaf87342da4ff7dc8271e183e205/Attackset/fgsm_ensv3_resv2_inresv2_random/nets/mobilenet_v1.py#L269-L338
MartinThoma/algorithms
6199cfa3446e1056c7b4d75ca6e306e9e56fd95b
finite-groups/finiteGroupChecks.py
python
generate_empty_conjunction
(nr_of_elements)
return conjunction
Generate a conjunction which maps everything to 0. Parameters ---------- nr_of_elements : int Returns ------- list
Generate a conjunction which maps everything to 0.
[ "Generate", "a", "conjunction", "which", "maps", "everything", "to", "0", "." ]
def generate_empty_conjunction(nr_of_elements): """ Generate a conjunction which maps everything to 0. Parameters ---------- nr_of_elements : int Returns ------- list """ conjunction = [] for i in range(nr_of_elements): line = [] for j in range(nr_of_elements): line.append(0) conjunction.append(line) return conjunction
[ "def", "generate_empty_conjunction", "(", "nr_of_elements", ")", ":", "conjunction", "=", "[", "]", "for", "i", "in", "range", "(", "nr_of_elements", ")", ":", "line", "=", "[", "]", "for", "j", "in", "range", "(", "nr_of_elements", ")", ":", "line", "."...
https://github.com/MartinThoma/algorithms/blob/6199cfa3446e1056c7b4d75ca6e306e9e56fd95b/finite-groups/finiteGroupChecks.py#L163-L181
pyansys/pymapdl
c07291fc062b359abf0e92b95a92d753a95ef3d7
ansys/mapdl/core/_commands/preproc/booleans.py
python
Booleans.lsba
(self, nl="", na="", sepo="", keepl="", keepa="", **kwargs)
return self.run(command, **kwargs)
Subtracts areas from lines. APDL Command: LSBA Parameters ---------- nl Line (or lines, if picking is used) to be subtracted from. If ALL, use all selected lines. If NL = P, graphical picking is enabled and all remaining command fields are ignored (valid only in the GUI). A component name may also be substituted for NL. na Area (or areas, if picking is used) to be subtracted. If ALL, use all selected areas. A component name may also be substituted for NA. sepo Behavior if the intersection of the lines and the areas is a keypoint or keypoints: (blank) - The resulting lines will share keypoint(s) where they touch. SEPO - The resulting lines will have separate, but coincident keypoint(s) where they touch. keepl Specifies whether NL lines are to be deleted: (blank) - Use the setting of KEEP on the BOPTN command. DELETE - Delete NL lines after LSBA operation (override BOPTN command settings). KEEP - Keep NL lines after LSBA operation (override BOPTN command settings). keepa Specifies whether NA areas are to be deleted: (blank) - Use the setting of KEEP on the BOPTN command. DELETE - Delete areas after LSBA operation (override BOPTN command settings). KEEP - Keep areas after LSBA operation (override BOPTN command settings). Notes ----- Generates new lines by subtracting the regions common to both NL lines and NA areas (the intersection) from the NL lines. The intersection can be a line(s) or keypoint(s). If the intersection is a keypoint and SEPO is blank, the NL line is divided at the keypoint and the resulting lines will be connected, sharing a common keypoint where they touch. If SEPO is set to SEPO, NL is divided into two unconnected lines with separate keypoints where they touch. See the Modeling and Meshing Guide for an illustration. See the BOPTN command for an explanation of the options available to Boolean operations. Element attributes and solid model boundary conditions assigned to the original entities will not be transferred to the new entities generated.
Subtracts areas from lines.
[ "Subtracts", "areas", "from", "lines", "." ]
def lsba(self, nl="", na="", sepo="", keepl="", keepa="", **kwargs): """Subtracts areas from lines. APDL Command: LSBA Parameters ---------- nl Line (or lines, if picking is used) to be subtracted from. If ALL, use all selected lines. If NL = P, graphical picking is enabled and all remaining command fields are ignored (valid only in the GUI). A component name may also be substituted for NL. na Area (or areas, if picking is used) to be subtracted. If ALL, use all selected areas. A component name may also be substituted for NA. sepo Behavior if the intersection of the lines and the areas is a keypoint or keypoints: (blank) - The resulting lines will share keypoint(s) where they touch. SEPO - The resulting lines will have separate, but coincident keypoint(s) where they touch. keepl Specifies whether NL lines are to be deleted: (blank) - Use the setting of KEEP on the BOPTN command. DELETE - Delete NL lines after LSBA operation (override BOPTN command settings). KEEP - Keep NL lines after LSBA operation (override BOPTN command settings). keepa Specifies whether NA areas are to be deleted: (blank) - Use the setting of KEEP on the BOPTN command. DELETE - Delete areas after LSBA operation (override BOPTN command settings). KEEP - Keep areas after LSBA operation (override BOPTN command settings). Notes ----- Generates new lines by subtracting the regions common to both NL lines and NA areas (the intersection) from the NL lines. The intersection can be a line(s) or keypoint(s). If the intersection is a keypoint and SEPO is blank, the NL line is divided at the keypoint and the resulting lines will be connected, sharing a common keypoint where they touch. If SEPO is set to SEPO, NL is divided into two unconnected lines with separate keypoints where they touch. See the Modeling and Meshing Guide for an illustration. See the BOPTN command for an explanation of the options available to Boolean operations. Element attributes and solid model boundary conditions assigned to the original entities will not be transferred to the new entities generated. """ command = f"LSBA,{nl},{na},{sepo},{keepl},{keepa}" return self.run(command, **kwargs)
[ "def", "lsba", "(", "self", ",", "nl", "=", "\"\"", ",", "na", "=", "\"\"", ",", "sepo", "=", "\"\"", ",", "keepl", "=", "\"\"", ",", "keepa", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "command", "=", "f\"LSBA,{nl},{na},{sepo},{keepl},{keepa}\"",...
https://github.com/pyansys/pymapdl/blob/c07291fc062b359abf0e92b95a92d753a95ef3d7/ansys/mapdl/core/_commands/preproc/booleans.py#L915-L975
stefankoegl/kdtree
587edc7056d7735177ad56a84ad5abccdea91693
kdtree.py
python
KDNode.is_valid
(self)
return all(c.is_valid() for c, _ in self.children) or self.is_leaf
Checks recursively if the tree is valid It is valid if each node splits correctly
Checks recursively if the tree is valid
[ "Checks", "recursively", "if", "the", "tree", "is", "valid" ]
def is_valid(self): """ Checks recursively if the tree is valid It is valid if each node splits correctly """ if not self: return True if self.left and self.data[self.axis] < self.left.data[self.axis]: return False if self.right and self.data[self.axis] > self.right.data[self.axis]: return False return all(c.is_valid() for c, _ in self.children) or self.is_leaf
[ "def", "is_valid", "(", "self", ")", ":", "if", "not", "self", ":", "return", "True", "if", "self", ".", "left", "and", "self", ".", "data", "[", "self", ".", "axis", "]", "<", "self", ".", "left", ".", "data", "[", "self", ".", "axis", "]", ":...
https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L534-L548
paulwinex/pw_MultiScriptEditor
e447e99f87cb07e238baf693b7e124e50efdbc51
multi_script_editor/managers/nuke/main.py
python
NodeConstructor.__new__
(self,S, )
T.__new__(S, ...) -> a new object with type S, a subtype of T
T.__new__(S, ...) -> a new object with type S, a subtype of T
[ "T", ".", "__new__", "(", "S", "...", ")", "-", ">", "a", "new", "object", "with", "type", "S", "a", "subtype", "of", "T" ]
def __new__(self,S, ): """T.__new__(S, ...) -> a new object with type S, a subtype of T""" pass
[ "def", "__new__", "(", "self", ",", "S", ",", ")", ":", "pass" ]
https://github.com/paulwinex/pw_MultiScriptEditor/blob/e447e99f87cb07e238baf693b7e124e50efdbc51/multi_script_editor/managers/nuke/main.py#L2209-L2211
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/rings/padics/lattice_precision.py
python
pRational.unit_part
(self)
return self.__class__(p, x, 0, valuation=0)
r""" Return the unit part of this element, that is the part ``u`` in the writing ``u * p^v`` with ``u`` coprime to `p`. TESTS:: sage: from sage.rings.padics.lattice_precision import pRational sage: x = pRational(2, 123456, 7); x 2^7 * 123456 sage: x.unit_part() 1929
r""" Return the unit part of this element, that is the part ``u`` in the writing ``u * p^v`` with ``u`` coprime to `p`.
[ "r", "Return", "the", "unit", "part", "of", "this", "element", "that", "is", "the", "part", "u", "in", "the", "writing", "u", "*", "p^v", "with", "u", "coprime", "to", "p", "." ]
def unit_part(self): r""" Return the unit part of this element, that is the part ``u`` in the writing ``u * p^v`` with ``u`` coprime to `p`. TESTS:: sage: from sage.rings.padics.lattice_precision import pRational sage: x = pRational(2, 123456, 7); x 2^7 * 123456 sage: x.unit_part() 1929 """ if self.is_zero(): raise ValueError("the unit part of zero is not defined") p = self.p val = self.valuation() x = self.x / (p ** (val-self.exponent)) return self.__class__(p, x, 0, valuation=0)
[ "def", "unit_part", "(", "self", ")", ":", "if", "self", ".", "is_zero", "(", ")", ":", "raise", "ValueError", "(", "\"the unit part of zero is not defined\"", ")", "p", "=", "self", ".", "p", "val", "=", "self", ".", "valuation", "(", ")", "x", "=", "...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/padics/lattice_precision.py#L484-L502
Miserlou/Zappa
5a11c17f5ecf0568bdb73b4baf6fb08ff0184f39
zappa/cli.py
python
ZappaCLI.check_for_update
(self)
Print a warning if there's a new Zappa version available.
Print a warning if there's a new Zappa version available.
[ "Print", "a", "warning", "if", "there", "s", "a", "new", "Zappa", "version", "available", "." ]
def check_for_update(self): """ Print a warning if there's a new Zappa version available. """ try: version = pkg_resources.require("zappa")[0].version updateable = check_new_version_available(version) if updateable: click.echo(click.style("Important!", fg="yellow", bold=True) + " A new version of " + click.style("Zappa", bold=True) + " is available!") click.echo("Upgrade with: " + click.style("pip install zappa --upgrade", bold=True)) click.echo("Visit the project page on GitHub to see the latest changes: " + click.style("https://github.com/Miserlou/Zappa", bold=True)) except Exception as e: # pragma: no cover print(e) return
[ "def", "check_for_update", "(", "self", ")", ":", "try", ":", "version", "=", "pkg_resources", ".", "require", "(", "\"zappa\"", ")", "[", "0", "]", ".", "version", "updateable", "=", "check_new_version_available", "(", "version", ")", "if", "updateable", ":...
https://github.com/Miserlou/Zappa/blob/5a11c17f5ecf0568bdb73b4baf6fb08ff0184f39/zappa/cli.py#L1988-L2003
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
thirdparty_libs/django/core/mail/backends/locmem.py
python
EmailBackend.send_messages
(self, messages)
return len(messages)
Redirect messages to the dummy outbox
Redirect messages to the dummy outbox
[ "Redirect", "messages", "to", "the", "dummy", "outbox" ]
def send_messages(self, messages): """Redirect messages to the dummy outbox""" for message in messages: # .message() triggers header validation message.message() mail.outbox.extend(messages) return len(messages)
[ "def", "send_messages", "(", "self", ",", "messages", ")", ":", "for", "message", "in", "messages", ":", "# .message() triggers header validation", "message", ".", "message", "(", ")", "mail", ".", "outbox", ".", "extend", "(", "messages", ")", "return", "len"...
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/thirdparty_libs/django/core/mail/backends/locmem.py#L21-L26
stellargraph/stellargraph
3c2c8c18ab4c5c16660f350d8e23d7dc39e738de
scripts/notebook_text_checker.py
python
no_leading_block_quotes
(cells)
A block quote at the start of a cell doesn't recieve the necessary separating comment in rST A rST quote is just indented text, which can merge with earlier directives unless there's a separating comment. Within a single cell, nbsphinx/nbconvert handles this correctly, but it doesn't when the quote is at the start of the cell. See: - https://github.com/spatialaudio/nbsphinx/issues/450 - https://github.com/stellargraph/stellargraph/pull/1398
A block quote at the start of a cell doesn't recieve the necessary separating comment in rST
[ "A", "block", "quote", "at", "the", "start", "of", "a", "cell", "doesn", "t", "recieve", "the", "necessary", "separating", "comment", "in", "rST" ]
def no_leading_block_quotes(cells): """ A block quote at the start of a cell doesn't recieve the necessary separating comment in rST A rST quote is just indented text, which can merge with earlier directives unless there's a separating comment. Within a single cell, nbsphinx/nbconvert handles this correctly, but it doesn't when the quote is at the start of the cell. See: - https://github.com/spatialaudio/nbsphinx/issues/450 - https://github.com/stellargraph/stellargraph/pull/1398 """ errors = [] for cell in cells: if not isinstance(cell, MarkdownCell): continue # unfortunately, the cloud runner cells break this rule (and there doesn't seem to be a good # way to avoid it), so skip them, and we just have to be careful that they get formatted # correctly. if "CloudRunner" in cell.metadata.get("tags", []): continue first = cell.ast.first_child if is_block_quote(first): errors.append( message_with_line( cell, f"Found a block quote (like `> ...`) as the first element of a cell; this must be avoided because it may cause problems during the reStructuredText conversion (https://github.com/spatialaudio/nbsphinx/issues/450). Consider: moving the block quote", sourcepos=first.sourcepos, ) ) if errors: raise FormattingError(errors)
[ "def", "no_leading_block_quotes", "(", "cells", ")", ":", "errors", "=", "[", "]", "for", "cell", "in", "cells", ":", "if", "not", "isinstance", "(", "cell", ",", "MarkdownCell", ")", ":", "continue", "# unfortunately, the cloud runner cells break this rule (and the...
https://github.com/stellargraph/stellargraph/blob/3c2c8c18ab4c5c16660f350d8e23d7dc39e738de/scripts/notebook_text_checker.py#L395-L428
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/xdrlib.py
python
Packer.reset
(self)
[]
def reset(self): self.__buf = _StringIO()
[ "def", "reset", "(", "self", ")", ":", "self", ".", "__buf", "=", "_StringIO", "(", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/xdrlib.py#L56-L57
DataDog/dd-trace-py
13f9c6c1a8b4820365b299ab204f2bb5189d2a49
ddtrace/vendor/psutil/_pslinux.py
python
virtual_memory
()
return svmem(total, avail, percent, used, free, active, inactive, buffers, cached, shared, slab)
Report virtual memory stats. This implementation matches "free" and "vmstat -s" cmdline utility values and procps-ng-3.3.12 source was used as a reference (2016-09-18): https://gitlab.com/procps-ng/procps/blob/ 24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c For reference, procps-ng-3.3.10 is the version available on Ubuntu 16.04. Note about "available" memory: up until psutil 4.3 it was calculated as "avail = (free + buffers + cached)". Now "MemAvailable:" column (kernel 3.14) from /proc/meminfo is used as it's more accurate. That matches "available" column in newer versions of "free".
Report virtual memory stats. This implementation matches "free" and "vmstat -s" cmdline utility values and procps-ng-3.3.12 source was used as a reference (2016-09-18): https://gitlab.com/procps-ng/procps/blob/ 24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c For reference, procps-ng-3.3.10 is the version available on Ubuntu 16.04.
[ "Report", "virtual", "memory", "stats", ".", "This", "implementation", "matches", "free", "and", "vmstat", "-", "s", "cmdline", "utility", "values", "and", "procps", "-", "ng", "-", "3", ".", "3", ".", "12", "source", "was", "used", "as", "a", "reference...
def virtual_memory(): """Report virtual memory stats. This implementation matches "free" and "vmstat -s" cmdline utility values and procps-ng-3.3.12 source was used as a reference (2016-09-18): https://gitlab.com/procps-ng/procps/blob/ 24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c For reference, procps-ng-3.3.10 is the version available on Ubuntu 16.04. Note about "available" memory: up until psutil 4.3 it was calculated as "avail = (free + buffers + cached)". Now "MemAvailable:" column (kernel 3.14) from /proc/meminfo is used as it's more accurate. That matches "available" column in newer versions of "free". """ missing_fields = [] mems = {} with open_binary('%s/meminfo' % get_procfs_path()) as f: for line in f: fields = line.split() mems[fields[0]] = int(fields[1]) * 1024 # /proc doc states that the available fields in /proc/meminfo vary # by architecture and compile options, but these 3 values are also # returned by sysinfo(2); as such we assume they are always there. total = mems[b'MemTotal:'] free = mems[b'MemFree:'] try: buffers = mems[b'Buffers:'] except KeyError: # https://github.com/giampaolo/psutil/issues/1010 buffers = 0 missing_fields.append('buffers') try: cached = mems[b"Cached:"] except KeyError: cached = 0 missing_fields.append('cached') else: # "free" cmdline utility sums reclaimable to cached. # Older versions of procps used to add slab memory instead. # This got changed in: # https://gitlab.com/procps-ng/procps/commit/ # 05d751c4f076a2f0118b914c5e51cfbb4762ad8e cached += mems.get(b"SReclaimable:", 0) # since kernel 2.6.19 try: shared = mems[b'Shmem:'] # since kernel 2.6.32 except KeyError: try: shared = mems[b'MemShared:'] # kernels 2.4 except KeyError: shared = 0 missing_fields.append('shared') try: active = mems[b"Active:"] except KeyError: active = 0 missing_fields.append('active') try: inactive = mems[b"Inactive:"] except KeyError: try: inactive = \ mems[b"Inact_dirty:"] + \ mems[b"Inact_clean:"] + \ mems[b"Inact_laundry:"] except KeyError: inactive = 0 missing_fields.append('inactive') try: slab = mems[b"Slab:"] except KeyError: slab = 0 used = total - free - cached - buffers if used < 0: # May be symptomatic of running within a LCX container where such # values will be dramatically distorted over those of the host. used = total - free # - starting from 4.4.0 we match free's "available" column. # Before 4.4.0 we calculated it as (free + buffers + cached) # which matched htop. # - free and htop available memory differs as per: # http://askubuntu.com/a/369589 # http://unix.stackexchange.com/a/65852/168884 # - MemAvailable has been introduced in kernel 3.14 try: avail = mems[b'MemAvailable:'] except KeyError: avail = calculate_avail_vmem(mems) if avail < 0: avail = 0 missing_fields.append('available') # If avail is greater than total or our calculation overflows, # that's symptomatic of running within a LCX container where such # values will be dramatically distorted over those of the host. # https://gitlab.com/procps-ng/procps/blob/ # 24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c#L764 if avail > total: avail = free percent = usage_percent((total - avail), total, round_=1) # Warn about missing metrics which are set to 0. if missing_fields: msg = "%s memory stats couldn't be determined and %s set to 0" % ( ", ".join(missing_fields), "was" if len(missing_fields) == 1 else "were") warnings.warn(msg, RuntimeWarning) return svmem(total, avail, percent, used, free, active, inactive, buffers, cached, shared, slab)
[ "def", "virtual_memory", "(", ")", ":", "missing_fields", "=", "[", "]", "mems", "=", "{", "}", "with", "open_binary", "(", "'%s/meminfo'", "%", "get_procfs_path", "(", ")", ")", "as", "f", ":", "for", "line", "in", "f", ":", "fields", "=", "line", "...
https://github.com/DataDog/dd-trace-py/blob/13f9c6c1a8b4820365b299ab204f2bb5189d2a49/ddtrace/vendor/psutil/_pslinux.py#L377-L496
pydoit/doit
cf7edfbe73fafebd1b2a6f1d3be8b69fde41383d
doit/tools.py
python
set_trace
()
start debugger, make sure stdout shows pdb output. output is not restored.
start debugger, make sure stdout shows pdb output. output is not restored.
[ "start", "debugger", "make", "sure", "stdout", "shows", "pdb", "output", ".", "output", "is", "not", "restored", "." ]
def set_trace(): # pragma: no cover """start debugger, make sure stdout shows pdb output. output is not restored. """ import pdb import sys debugger = pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__) debugger.set_trace(sys._getframe().f_back)
[ "def", "set_trace", "(", ")", ":", "# pragma: no cover", "import", "pdb", "import", "sys", "debugger", "=", "pdb", ".", "Pdb", "(", "stdin", "=", "sys", ".", "__stdin__", ",", "stdout", "=", "sys", ".", "__stdout__", ")", "debugger", ".", "set_trace", "(...
https://github.com/pydoit/doit/blob/cf7edfbe73fafebd1b2a6f1d3be8b69fde41383d/doit/tools.py#L230-L237
NervanaSystems/neon
8c3fb8a93b4a89303467b25817c60536542d08bd
examples/faster-rcnn/proposal_layer.py
python
ProposalLayer._sample_fg_bg
(self, max_overlaps)
return keep_inds, int(fg_rois_per_this_image)
Return sample of at most fg_fraction * num_rois foreground indicies, padding the remaining num_rois with background indicies. Foreground and background labels are determined based on max_overlaps and the thresholds fg_thresh, bg_thresh_hi, bg_thresh_lo. Returns: keep_inds (array): (num_rois,) sampled indicies of bboxes. fg_rois_per_this_image (int): number of fg rois sampled from the image.
Return sample of at most fg_fraction * num_rois foreground indicies, padding the remaining num_rois with background indicies. Foreground and background labels are determined based on max_overlaps and the thresholds fg_thresh, bg_thresh_hi, bg_thresh_lo. Returns: keep_inds (array): (num_rois,) sampled indicies of bboxes. fg_rois_per_this_image (int): number of fg rois sampled from the image.
[ "Return", "sample", "of", "at", "most", "fg_fraction", "*", "num_rois", "foreground", "indicies", "padding", "the", "remaining", "num_rois", "with", "background", "indicies", ".", "Foreground", "and", "background", "labels", "are", "determined", "based", "on", "ma...
def _sample_fg_bg(self, max_overlaps): """Return sample of at most fg_fraction * num_rois foreground indicies, padding the remaining num_rois with background indicies. Foreground and background labels are determined based on max_overlaps and the thresholds fg_thresh, bg_thresh_hi, bg_thresh_lo. Returns: keep_inds (array): (num_rois,) sampled indicies of bboxes. fg_rois_per_this_image (int): number of fg rois sampled from the image. """ # Split proposals into foreground and background based on overlap fg_inds = np.where(max_overlaps >= self.fg_thresh)[0] fg_rois_per_image = np.round(self.fg_fraction * self.num_rois) # Guard against the case when an image has fewer than fg_rois_per_image foreground RoIs fg_rois_per_this_image = min(fg_rois_per_image, fg_inds.size) # Sample foreground regions without replacement if fg_inds.size > 0 and not self.deterministic: fg_inds = self.be.rng.choice(fg_inds, size=int(fg_rois_per_this_image), replace=False) elif fg_inds.size > 0: fg_inds = fg_inds[:fg_rois_per_this_image] # Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI) bg_inds = np.where((max_overlaps < self.bg_thresh_hi) & (max_overlaps >= self.bg_thresh_lo))[0] # Compute number of background RoIs to take from this image (guarding # against there being fewer than desired) bg_rois_per_this_image = self.num_rois - fg_rois_per_this_image bg_rois_per_this_image = min(bg_rois_per_this_image, bg_inds.size) # Sample background regions without replacement if bg_inds.size > 0 and not self.deterministic: bg_inds = self.be.rng.choice(bg_inds, size=int(bg_rois_per_this_image), replace=False) elif bg_inds.size > 0: bg_inds = bg_inds[:bg_rois_per_this_image] # The indices that we're selecting (both fg and bg) keep_inds = np.append(fg_inds, bg_inds) return keep_inds, int(fg_rois_per_this_image)
[ "def", "_sample_fg_bg", "(", "self", ",", "max_overlaps", ")", ":", "# Split proposals into foreground and background based on overlap", "fg_inds", "=", "np", ".", "where", "(", "max_overlaps", ">=", "self", ".", "fg_thresh", ")", "[", "0", "]", "fg_rois_per_image", ...
https://github.com/NervanaSystems/neon/blob/8c3fb8a93b4a89303467b25817c60536542d08bd/examples/faster-rcnn/proposal_layer.py#L397-L436
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/venv/lib/python2.7/site-packages/pip/_vendor/requests/utils.py
python
get_netrc_auth
(url)
Returns the Requests tuple auth for a given url from netrc.
Returns the Requests tuple auth for a given url from netrc.
[ "Returns", "the", "Requests", "tuple", "auth", "for", "a", "given", "url", "from", "netrc", "." ]
def get_netrc_auth(url): """Returns the Requests tuple auth for a given url from netrc.""" try: from netrc import netrc, NetrcParseError netrc_path = None for f in NETRC_FILES: try: loc = os.path.expanduser('~/{0}'.format(f)) except KeyError: # os.path.expanduser can fail when $HOME is undefined and # getpwuid fails. See http://bugs.python.org/issue20164 & # https://github.com/kennethreitz/requests/issues/1846 return if os.path.exists(loc): netrc_path = loc break # Abort early if there isn't one. if netrc_path is None: return ri = urlparse(url) # Strip port numbers from netloc host = ri.netloc.split(':')[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = (0 if _netrc[0] else 1) return (_netrc[login_i], _netrc[2]) except (NetrcParseError, IOError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth pass # AppEngine hackiness. except (ImportError, AttributeError): pass
[ "def", "get_netrc_auth", "(", "url", ")", ":", "try", ":", "from", "netrc", "import", "netrc", ",", "NetrcParseError", "netrc_path", "=", "None", "for", "f", "in", "NETRC_FILES", ":", "try", ":", "loc", "=", "os", ".", "path", ".", "expanduser", "(", "...
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/venv/lib/python2.7/site-packages/pip/_vendor/requests/utils.py#L69-L112
atomistic-machine-learning/schnetpack
dacf6076d43509dfd8b6694a846ac8453ae39b5e
src/schnetpack/md/parsers/md_setup.py
python
SetupCalculator._setup
(self, md_initializer)
Main routine for loading the model, preparing it for the calculator and setting up the main :obj:`schnetpack.md.calculator`. Args: md_initializer (schnetpack.md.parser.MDSimulation): Parent MDSimulation class.
Main routine for loading the model, preparing it for the calculator and setting up the main :obj:`schnetpack.md.calculator`.
[ "Main", "routine", "for", "loading", "the", "model", "preparing", "it", "for", "the", "calculator", "and", "setting", "up", "the", "main", ":", "obj", ":", "schnetpack", ".", "md", ".", "calculator", "." ]
def _setup(self, md_initializer): """ Main routine for loading the model, preparing it for the calculator and setting up the main :obj:`schnetpack.md.calculator`. Args: md_initializer (schnetpack.md.parser.MDSimulation): Parent MDSimulation class. """ calculator = self.target_config_block calculator_dict = {} # Load model, else get options for key in calculator: # TODO Figure out conventions for ensemble if key == "model_file" or key == "model_files": if calculator[CalculatorInit.kind] in self.basic_models: model = self._load_model_schnetpack( calculator["model_file"], md_initializer.device ).to(md_initializer.device) calculator_dict["model"] = model elif calculator[CalculatorInit.kind] in self.ensemble_models: models = [ self._load_model_schnetpack(model, md_initializer.device).to( md_initializer.device ) for model in calculator["model_files"] ] calculator_dict["models"] = models elif calculator[CalculatorInit.kind] == "sgdml": model = self._load_model_sgdml(calculator["model_file"]).to( md_initializer.device ) calculator_dict["model"] = model else: raise ValueError( f"Unrecognized ML calculator {calculator[CalculatorInit.kind]}" ) elif key == "neighbor_list": # Check for neighbor list calculator_dict[key] = self.neighbor_list[calculator[key]] else: calculator_dict[key] = calculator[key] calculator = CalculatorInit(calculator_dict).initialized md_initializer.calculator = calculator
[ "def", "_setup", "(", "self", ",", "md_initializer", ")", ":", "calculator", "=", "self", ".", "target_config_block", "calculator_dict", "=", "{", "}", "# Load model, else get options", "for", "key", "in", "calculator", ":", "# TODO Figure out conventions for ensemble",...
https://github.com/atomistic-machine-learning/schnetpack/blob/dacf6076d43509dfd8b6694a846ac8453ae39b5e/src/schnetpack/md/parsers/md_setup.py#L338-L383
kylebebak/Requester
4a9f9f051fa5fc951a8f7ad098a328261ca2db97
deps/urllib3/packages/ordered_dict.py
python
OrderedDict.__reversed__
(self)
od.__reversed__() <==> reversed(od)
od.__reversed__() <==> reversed(od)
[ "od", ".", "__reversed__", "()", "<", "==", ">", "reversed", "(", "od", ")" ]
def __reversed__(self): 'od.__reversed__() <==> reversed(od)' root = self.__root curr = root[0] while curr is not root: yield curr[2] curr = curr[0]
[ "def", "__reversed__", "(", "self", ")", ":", "root", "=", "self", ".", "__root", "curr", "=", "root", "[", "0", "]", "while", "curr", "is", "not", "root", ":", "yield", "curr", "[", "2", "]", "curr", "=", "curr", "[", "0", "]" ]
https://github.com/kylebebak/Requester/blob/4a9f9f051fa5fc951a8f7ad098a328261ca2db97/deps/urllib3/packages/ordered_dict.py#L71-L77
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/min/pydoc.py
python
Helper.listkeywords
(self)
[]
def listkeywords(self): self.output.write(''' Here is a list of the Python keywords. Enter any keyword to get more help. ''') self.list(self.keywords.keys())
[ "def", "listkeywords", "(", "self", ")", ":", "self", ".", "output", ".", "write", "(", "'''\nHere is a list of the Python keywords. Enter any keyword to get more help.\n\n'''", ")", "self", ".", "list", "(", "self", ".", "keywords", ".", "keys", "(", ")", ")" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/pydoc.py#L2094-L2099
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/lib/type_check.py
python
mintypecode
(typechars,typeset='GDFgdf',default='d')
return l[0][1]
Return the character for the minimum-size type to which given types can be safely cast. The returned type character must represent the smallest size dtype such that an array of the returned type can handle the data from an array of all types in `typechars` (or if `typechars` is an array, then its dtype.char). Parameters ---------- typechars : list of str or array_like If a list of strings, each string should represent a dtype. If array_like, the character representation of the array dtype is used. typeset : str or list of str, optional The set of characters that the returned character is chosen from. The default set is 'GDFgdf'. default : str, optional The default character, this is returned if none of the characters in `typechars` matches a character in `typeset`. Returns ------- typechar : str The character representing the minimum-size type that was found. See Also -------- dtype, sctype2char, maximum_sctype Examples -------- >>> np.mintypecode(['d', 'f', 'S']) 'd' >>> x = np.array([1.1, 2-3.j]) >>> np.mintypecode(x) 'D' >>> np.mintypecode('abceh', default='G') 'G'
Return the character for the minimum-size type to which given types can be safely cast.
[ "Return", "the", "character", "for", "the", "minimum", "-", "size", "type", "to", "which", "given", "types", "can", "be", "safely", "cast", "." ]
def mintypecode(typechars,typeset='GDFgdf',default='d'): """ Return the character for the minimum-size type to which given types can be safely cast. The returned type character must represent the smallest size dtype such that an array of the returned type can handle the data from an array of all types in `typechars` (or if `typechars` is an array, then its dtype.char). Parameters ---------- typechars : list of str or array_like If a list of strings, each string should represent a dtype. If array_like, the character representation of the array dtype is used. typeset : str or list of str, optional The set of characters that the returned character is chosen from. The default set is 'GDFgdf'. default : str, optional The default character, this is returned if none of the characters in `typechars` matches a character in `typeset`. Returns ------- typechar : str The character representing the minimum-size type that was found. See Also -------- dtype, sctype2char, maximum_sctype Examples -------- >>> np.mintypecode(['d', 'f', 'S']) 'd' >>> x = np.array([1.1, 2-3.j]) >>> np.mintypecode(x) 'D' >>> np.mintypecode('abceh', default='G') 'G' """ typecodes = [(isinstance(t, str) and t) or asarray(t).dtype.char for t in typechars] intersection = [t for t in typecodes if t in typeset] if not intersection: return default if 'F' in intersection and 'd' in intersection: return 'D' l = [] for t in intersection: i = _typecodes_by_elsize.index(t) l.append((i, t)) l.sort() return l[0][1]
[ "def", "mintypecode", "(", "typechars", ",", "typeset", "=", "'GDFgdf'", ",", "default", "=", "'d'", ")", ":", "typecodes", "=", "[", "(", "isinstance", "(", "t", ",", "str", ")", "and", "t", ")", "or", "asarray", "(", "t", ")", ".", "dtype", ".", ...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/lib/type_check.py#L18-L73
donnemartin/data-science-ipython-notebooks
5b3c00d462c6e9200315afe46d0093948621eb95
scikit-learn/fig_code/svm_gui.py
python
View.plot_support_vectors
(self, support_vectors)
Plot the support vectors by placing circles over the corresponding data points and adds the circle collection to the contours list.
Plot the support vectors by placing circles over the corresponding data points and adds the circle collection to the contours list.
[ "Plot", "the", "support", "vectors", "by", "placing", "circles", "over", "the", "corresponding", "data", "points", "and", "adds", "the", "circle", "collection", "to", "the", "contours", "list", "." ]
def plot_support_vectors(self, support_vectors): """Plot the support vectors by placing circles over the corresponding data points and adds the circle collection to the contours list.""" cs = self.ax.scatter(support_vectors[:, 0], support_vectors[:, 1], s=80, edgecolors="k", facecolors="none") self.contours.append(cs)
[ "def", "plot_support_vectors", "(", "self", ",", "support_vectors", ")", ":", "cs", "=", "self", ".", "ax", ".", "scatter", "(", "support_vectors", "[", ":", ",", "0", "]", ",", "support_vectors", "[", ":", ",", "1", "]", ",", "s", "=", "80", ",", ...
https://github.com/donnemartin/data-science-ipython-notebooks/blob/5b3c00d462c6e9200315afe46d0093948621eb95/scikit-learn/fig_code/svm_gui.py#L229-L235
fsspec/filesystem_spec
76da18cf5a9697f480e5a0f6d1013d71676af131
fsspec/utils.py
python
stringify_path
(filepath)
Attempt to convert a path-like object to a string. Parameters ---------- filepath: object to be converted Returns ------- filepath_str: maybe a string version of the object Notes ----- Objects supporting the fspath protocol (Python 3.6+) are coerced according to its __fspath__ method. For backwards compatibility with older Python version, pathlib.Path objects are specially coerced. Any other object is passed through unchanged, which includes bytes, strings, buffers, or anything else that's not even path-like.
Attempt to convert a path-like object to a string.
[ "Attempt", "to", "convert", "a", "path", "-", "like", "object", "to", "a", "string", "." ]
def stringify_path(filepath): """Attempt to convert a path-like object to a string. Parameters ---------- filepath: object to be converted Returns ------- filepath_str: maybe a string version of the object Notes ----- Objects supporting the fspath protocol (Python 3.6+) are coerced according to its __fspath__ method. For backwards compatibility with older Python version, pathlib.Path objects are specially coerced. Any other object is passed through unchanged, which includes bytes, strings, buffers, or anything else that's not even path-like. """ if isinstance(filepath, str): return filepath elif hasattr(filepath, "__fspath__"): return filepath.__fspath__() elif isinstance(filepath, pathlib.Path): return str(filepath) elif hasattr(filepath, "path"): return filepath.path else: return filepath
[ "def", "stringify_path", "(", "filepath", ")", ":", "if", "isinstance", "(", "filepath", ",", "str", ")", ":", "return", "filepath", "elif", "hasattr", "(", "filepath", ",", "\"__fspath__\"", ")", ":", "return", "filepath", ".", "__fspath__", "(", ")", "el...
https://github.com/fsspec/filesystem_spec/blob/76da18cf5a9697f480e5a0f6d1013d71676af131/fsspec/utils.py#L291-L322
rwth-i6/returnn
f2d718a197a280b0d5f0fd91a7fcb8658560dddb
tools/bliss-collect-seq-lens.py
python
main
()
Main entry.
Main entry.
[ "Main", "entry", "." ]
def main(): """ Main entry. """ arg_parser = ArgumentParser() arg_parser.add_argument("bliss_filename", nargs="+") arg_parser.add_argument("--output", default="/dev/stdout") args = arg_parser.parse_args() if args.output.endswith(".gz"): out = gzip.GzipFile(args.output, mode="wb") else: out = open(args.output, "wb") out.write(b"{\n") for bliss_item in itertools.chain(*[iter_bliss(fn) for fn in args.bliss_filename]): assert isinstance(bliss_item, BlissItem) seq_len = round(bliss_item.delta_time * 100.) # assume 10ms frames, round out.write(b"%r: %i,\n" % (bliss_item.segment_name, seq_len)) out.write(b"}\n") out.close()
[ "def", "main", "(", ")", ":", "arg_parser", "=", "ArgumentParser", "(", ")", "arg_parser", ".", "add_argument", "(", "\"bliss_filename\"", ",", "nargs", "=", "\"+\"", ")", "arg_parser", ".", "add_argument", "(", "\"--output\"", ",", "default", "=", "\"/dev/std...
https://github.com/rwth-i6/returnn/blob/f2d718a197a280b0d5f0fd91a7fcb8658560dddb/tools/bliss-collect-seq-lens.py#L95-L113
johnroper100/CrowdMaster
dfd72c424c8cc8d1877830ff9dd2e00226f518c3
cm_channels/cm_formationChannels.py
python
Formation.registerOld
(self, agent, formID, val)
Adds an object that is a formation target
Adds an object that is a formation target
[ "Adds", "an", "object", "that", "is", "a", "formation", "target" ]
def registerOld(self, agent, formID, val): """Adds an object that is a formation target""" if formID in dir(self): logger.info("""Formation ID must not be an attribute of this python object""") else: if formID not in self.formations: ch = Channel(formID, self.sim) self.formations[formID] = ch self.formations[formID].register(agent.id, val)
[ "def", "registerOld", "(", "self", ",", "agent", ",", "formID", ",", "val", ")", ":", "if", "formID", "in", "dir", "(", "self", ")", ":", "logger", ".", "info", "(", "\"\"\"Formation ID must not be an attribute of this\n python object\"\"\"", ")", ...
https://github.com/johnroper100/CrowdMaster/blob/dfd72c424c8cc8d1877830ff9dd2e00226f518c3/cm_channels/cm_formationChannels.py#L49-L58
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v7/services/services/managed_placement_view_service/client.py
python
ManagedPlacementViewServiceClient.common_location_path
(project: str, location: str,)
return "projects/{project}/locations/{location}".format( project=project, location=location, )
Return a fully-qualified location string.
Return a fully-qualified location string.
[ "Return", "a", "fully", "-", "qualified", "location", "string", "." ]
def common_location_path(project: str, location: str,) -> str: """Return a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, )
[ "def", "common_location_path", "(", "project", ":", "str", ",", "location", ":", "str", ",", ")", "->", "str", ":", "return", "\"projects/{project}/locations/{location}\"", ".", "format", "(", "project", "=", "project", ",", "location", "=", "location", ",", "...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v7/services/services/managed_placement_view_service/client.py#L232-L236
Patrowl/PatrowlEngines
61dce987b662177396fa2f914ae07fd651179daf
engines/shhgit/engine-shhgit.py
python
clean_scan
(scan_id)
return engine.clean_scan(scan_id)
Clean scan identified by id.
Clean scan identified by id.
[ "Clean", "scan", "identified", "by", "id", "." ]
def clean_scan(scan_id): """Clean scan identified by id.""" return engine.clean_scan(scan_id)
[ "def", "clean_scan", "(", "scan_id", ")", ":", "return", "engine", ".", "clean_scan", "(", "scan_id", ")" ]
https://github.com/Patrowl/PatrowlEngines/blob/61dce987b662177396fa2f914ae07fd651179daf/engines/shhgit/engine-shhgit.py#L115-L117
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/core/leoNodes.py
python
Position.is_at_ignore
(self)
return g.match_word(p.h, 0, '@ignore')
Return True if p is an @ignore node.
Return True if p is an
[ "Return", "True", "if", "p", "is", "an" ]
def is_at_ignore(self): """Return True if p is an @ignore node.""" p = self return g.match_word(p.h, 0, '@ignore')
[ "def", "is_at_ignore", "(", "self", ")", ":", "p", "=", "self", "return", "g", ".", "match_word", "(", "p", ".", "h", ",", "0", ",", "'@ignore'", ")" ]
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/core/leoNodes.py#L1911-L1914
frol/flask-restplus-server-example
fa5a2cdbc1d78ac60fa822208bbf656b71e38c58
tasks/app/env.py
python
enter
(context, install_dependencies=True, upgrade_db=True)
Enter into IPython notebook shell with an initialized app.
Enter into IPython notebook shell with an initialized app.
[ "Enter", "into", "IPython", "notebook", "shell", "with", "an", "initialized", "app", "." ]
def enter(context, install_dependencies=True, upgrade_db=True): """ Enter into IPython notebook shell with an initialized app. """ if install_dependencies: context.invoke_execute(context, 'app.dependencies.install') if upgrade_db: context.invoke_execute(context, 'app.db.upgrade') context.invoke_execute( context, 'app.db.init_development_data', upgrade_db=False, skip_on_failure=True ) import pprint from werkzeug import script import flask import app flask_app = app.create_app() def shell_context(): context = dict(pprint=pprint.pprint) context.update(vars(flask)) context.update(vars(app)) return context with flask_app.app_context(): script.make_shell(shell_context, use_ipython=True)()
[ "def", "enter", "(", "context", ",", "install_dependencies", "=", "True", ",", "upgrade_db", "=", "True", ")", ":", "if", "install_dependencies", ":", "context", ".", "invoke_execute", "(", "context", ",", "'app.dependencies.install'", ")", "if", "upgrade_db", "...
https://github.com/frol/flask-restplus-server-example/blob/fa5a2cdbc1d78ac60fa822208bbf656b71e38c58/tasks/app/env.py#L13-L44
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/vendor/wheel/cli/pack.py
python
pack
(directory, dest_dir, build_number)
Repack a previously unpacked wheel directory into a new wheel file. The .dist-info/WHEEL file must contain one or more tags so that the target wheel file name can be determined. :param directory: The unpacked wheel directory :param dest_dir: Destination directory (defaults to the current directory)
Repack a previously unpacked wheel directory into a new wheel file.
[ "Repack", "a", "previously", "unpacked", "wheel", "directory", "into", "a", "new", "wheel", "file", "." ]
def pack(directory, dest_dir, build_number): """Repack a previously unpacked wheel directory into a new wheel file. The .dist-info/WHEEL file must contain one or more tags so that the target wheel file name can be determined. :param directory: The unpacked wheel directory :param dest_dir: Destination directory (defaults to the current directory) """ # Find the .dist-info directory dist_info_dirs = [fn for fn in os.listdir(directory) if os.path.isdir(os.path.join(directory, fn)) and DIST_INFO_RE.match(fn)] if len(dist_info_dirs) > 1: raise WheelError('Multiple .dist-info directories found in {}'.format(directory)) elif not dist_info_dirs: raise WheelError('No .dist-info directories found in {}'.format(directory)) # Determine the target wheel filename dist_info_dir = dist_info_dirs[0] name_version = DIST_INFO_RE.match(dist_info_dir).group('namever') # Read the tags and the existing build number from .dist-info/WHEEL existing_build_number = None wheel_file_path = os.path.join(directory, dist_info_dir, 'WHEEL') with open(wheel_file_path) as f: tags = [] for line in f: if line.startswith('Tag: '): tags.append(line.split(' ')[1].rstrip()) elif line.startswith('Build: '): existing_build_number = line.split(' ')[1].rstrip() if not tags: raise WheelError('No tags present in {}/WHEEL; cannot determine target wheel filename' .format(dist_info_dir)) # Set the wheel file name and add/replace/remove the Build tag in .dist-info/WHEEL build_number = build_number if build_number is not None else existing_build_number if build_number is not None: if build_number: name_version += '-' + build_number if build_number != existing_build_number: replacement = ('Build: %s\r\n' % build_number).encode('ascii') if build_number else b'' with open(wheel_file_path, 'rb+') as f: wheel_file_content = f.read() if not BUILD_NUM_RE.subn(replacement, wheel_file_content)[1]: wheel_file_content += replacement f.truncate() f.write(wheel_file_content) # Reassemble the tags for the wheel file impls = sorted({tag.split('-')[0] for tag in tags}) abivers = sorted({tag.split('-')[1] for tag in tags}) platforms = sorted({tag.split('-')[2] for tag in tags}) tagline = '-'.join(['.'.join(impls), '.'.join(abivers), '.'.join(platforms)]) # Repack the wheel wheel_path = os.path.join(dest_dir, '{}-{}.whl'.format(name_version, tagline)) with WheelFile(wheel_path, 'w') as wf: print("Repacking wheel as {}...".format(wheel_path), end='') sys.stdout.flush() wf.write_files(directory) print('OK')
[ "def", "pack", "(", "directory", ",", "dest_dir", ",", "build_number", ")", ":", "# Find the .dist-info directory", "dist_info_dirs", "=", "[", "fn", "for", "fn", "in", "os", ".", "listdir", "(", "directory", ")", "if", "os", ".", "path", ".", "isdir", "("...
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/wheel/cli/pack.py#L14-L79
microsoft/azure-devops-python-api
451cade4c475482792cbe9e522c1fee32393139e
azure-devops/azure/devops/v6_0/notification/notification_client.py
python
NotificationClient.update_subscriber
(self, update_parameters, subscriber_id)
return self._deserialize('NotificationSubscriber', response)
UpdateSubscriber. [Preview API] Update delivery preferences of a notifications subscriber. :param :class:`<NotificationSubscriberUpdateParameters> <azure.devops.v6_0.notification.models.NotificationSubscriberUpdateParameters>` update_parameters: :param str subscriber_id: ID of the user or group. :rtype: :class:`<NotificationSubscriber> <azure.devops.v6_0.notification.models.NotificationSubscriber>`
UpdateSubscriber. [Preview API] Update delivery preferences of a notifications subscriber. :param :class:`<NotificationSubscriberUpdateParameters> <azure.devops.v6_0.notification.models.NotificationSubscriberUpdateParameters>` update_parameters: :param str subscriber_id: ID of the user or group. :rtype: :class:`<NotificationSubscriber> <azure.devops.v6_0.notification.models.NotificationSubscriber>`
[ "UpdateSubscriber", ".", "[", "Preview", "API", "]", "Update", "delivery", "preferences", "of", "a", "notifications", "subscriber", ".", ":", "param", ":", "class", ":", "<NotificationSubscriberUpdateParameters", ">", "<azure", ".", "devops", ".", "v6_0", ".", "...
def update_subscriber(self, update_parameters, subscriber_id): """UpdateSubscriber. [Preview API] Update delivery preferences of a notifications subscriber. :param :class:`<NotificationSubscriberUpdateParameters> <azure.devops.v6_0.notification.models.NotificationSubscriberUpdateParameters>` update_parameters: :param str subscriber_id: ID of the user or group. :rtype: :class:`<NotificationSubscriber> <azure.devops.v6_0.notification.models.NotificationSubscriber>` """ route_values = {} if subscriber_id is not None: route_values['subscriberId'] = self._serialize.url('subscriber_id', subscriber_id, 'str') content = self._serialize.body(update_parameters, 'NotificationSubscriberUpdateParameters') response = self._send(http_method='PATCH', location_id='4d5caff1-25ba-430b-b808-7a1f352cc197', version='6.0-preview.1', route_values=route_values, content=content) return self._deserialize('NotificationSubscriber', response)
[ "def", "update_subscriber", "(", "self", ",", "update_parameters", ",", "subscriber_id", ")", ":", "route_values", "=", "{", "}", "if", "subscriber_id", "is", "not", "None", ":", "route_values", "[", "'subscriberId'", "]", "=", "self", ".", "_serialize", ".", ...
https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/v6_0/notification/notification_client.py#L155-L171
aleju/imgaug
0101108d4fed06bc5056c4a03e2bcb0216dac326
imgaug/augmenters/blend.py
python
BlendAlphaElementwise.factor
(self)
return self.mask_generator.parameter
[]
def factor(self): return self.mask_generator.parameter
[ "def", "factor", "(", "self", ")", ":", "return", "self", ".", "mask_generator", ".", "parameter" ]
https://github.com/aleju/imgaug/blob/0101108d4fed06bc5056c4a03e2bcb0216dac326/imgaug/augmenters/blend.py#L1163-L1164
and3rson/clay
c271cecf6b6ea6465abcdd2444171b1a565a60a3
clay/vlc.py
python
libvlc_audio_equalizer_get_preset_name
(u_index)
return f(u_index)
Get the name of a particular equalizer preset. This name can be used, for example, to prepare a preset label or menu in a user interface. @param u_index: index of the preset, counting from zero. @return: preset name, or None if there is no such preset. @version: LibVLC 2.2.0 or later.
Get the name of a particular equalizer preset. This name can be used, for example, to prepare a preset label or menu in a user interface.
[ "Get", "the", "name", "of", "a", "particular", "equalizer", "preset", ".", "This", "name", "can", "be", "used", "for", "example", "to", "prepare", "a", "preset", "label", "or", "menu", "in", "a", "user", "interface", "." ]
def libvlc_audio_equalizer_get_preset_name(u_index): '''Get the name of a particular equalizer preset. This name can be used, for example, to prepare a preset label or menu in a user interface. @param u_index: index of the preset, counting from zero. @return: preset name, or None if there is no such preset. @version: LibVLC 2.2.0 or later. ''' f = _Cfunctions.get('libvlc_audio_equalizer_get_preset_name', None) or \ _Cfunction('libvlc_audio_equalizer_get_preset_name', ((1,),), None, ctypes.c_char_p, ctypes.c_uint) return f(u_index)
[ "def", "libvlc_audio_equalizer_get_preset_name", "(", "u_index", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_audio_equalizer_get_preset_name'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_audio_equalizer_get_preset_name'", ",", "(", "(", "1", ...
https://github.com/and3rson/clay/blob/c271cecf6b6ea6465abcdd2444171b1a565a60a3/clay/vlc.py#L6525-L6536
yihui-he/KL-Loss
66c0ed9e886a2218f4cf88c0efd4f40199bff54a
detectron/utils/keypoints.py
python
get_keypoints
()
return keypoints, keypoint_flip_map
Get the COCO keypoints and their left/right flip coorespondence map.
Get the COCO keypoints and their left/right flip coorespondence map.
[ "Get", "the", "COCO", "keypoints", "and", "their", "left", "/", "right", "flip", "coorespondence", "map", "." ]
def get_keypoints(): """Get the COCO keypoints and their left/right flip coorespondence map.""" # Keypoints are not available in the COCO json for the test split, so we # provide them here. keypoints = [ 'nose', 'left_eye', 'right_eye', 'left_ear', 'right_ear', 'left_shoulder', 'right_shoulder', 'left_elbow', 'right_elbow', 'left_wrist', 'right_wrist', 'left_hip', 'right_hip', 'left_knee', 'right_knee', 'left_ankle', 'right_ankle' ] keypoint_flip_map = { 'left_eye': 'right_eye', 'left_ear': 'right_ear', 'left_shoulder': 'right_shoulder', 'left_elbow': 'right_elbow', 'left_wrist': 'right_wrist', 'left_hip': 'right_hip', 'left_knee': 'right_knee', 'left_ankle': 'right_ankle' } return keypoints, keypoint_flip_map
[ "def", "get_keypoints", "(", ")", ":", "# Keypoints are not available in the COCO json for the test split, so we", "# provide them here.", "keypoints", "=", "[", "'nose'", ",", "'left_eye'", ",", "'right_eye'", ",", "'left_ear'", ",", "'right_ear'", ",", "'left_shoulder'", ...
https://github.com/yihui-he/KL-Loss/blob/66c0ed9e886a2218f4cf88c0efd4f40199bff54a/detectron/utils/keypoints.py#L30-L63
blackfeather-wang/ISDA-for-Deep-Networks
b66a594482557dada126211d65a4e9b6f4328423
Image classification on CIFAR/train.py
python
AverageMeter.update
(self, val, n=1)
[]
def update(self, val, n=1): self.value = val self.sum += val * n self.count += n self.ave = self.sum / self.count
[ "def", "update", "(", "self", ",", "val", ",", "n", "=", "1", ")", ":", "self", ".", "value", "=", "val", "self", ".", "sum", "+=", "val", "*", "n", "self", ".", "count", "+=", "n", "self", ".", "ave", "=", "self", ".", "sum", "/", "self", ...
https://github.com/blackfeather-wang/ISDA-for-Deep-Networks/blob/b66a594482557dada126211d65a4e9b6f4328423/Image classification on CIFAR/train.py#L581-L585
pillone/usntssearch
24b5e5bc4b6af2589d95121c4d523dc58cb34273
NZBmegasearch/werkzeug/routing.py
python
Map.iter_rules
(self, endpoint=None)
return iter(self._rules)
Iterate over all rules or the rules of an endpoint. :param endpoint: if provided only the rules for that endpoint are returned. :return: an iterator
Iterate over all rules or the rules of an endpoint.
[ "Iterate", "over", "all", "rules", "or", "the", "rules", "of", "an", "endpoint", "." ]
def iter_rules(self, endpoint=None): """Iterate over all rules or the rules of an endpoint. :param endpoint: if provided only the rules for that endpoint are returned. :return: an iterator """ self.update() if endpoint is not None: return iter(self._rules_by_endpoint[endpoint]) return iter(self._rules)
[ "def", "iter_rules", "(", "self", ",", "endpoint", "=", "None", ")", ":", "self", ".", "update", "(", ")", "if", "endpoint", "is", "not", "None", ":", "return", "iter", "(", "self", ".", "_rules_by_endpoint", "[", "endpoint", "]", ")", "return", "iter"...
https://github.com/pillone/usntssearch/blob/24b5e5bc4b6af2589d95121c4d523dc58cb34273/NZBmegasearch/werkzeug/routing.py#L1066-L1076
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/plugins/view/noteview.py
python
NoteView.remove_tag
(self, transaction, note_handle, tag_handle)
Remove the given tag from the given note.
Remove the given tag from the given note.
[ "Remove", "the", "given", "tag", "from", "the", "given", "note", "." ]
def remove_tag(self, transaction, note_handle, tag_handle): """ Remove the given tag from the given note. """ note = self.dbstate.db.get_note_from_handle(note_handle) note.remove_tag(tag_handle) self.dbstate.db.commit_note(note, transaction)
[ "def", "remove_tag", "(", "self", ",", "transaction", ",", "note_handle", ",", "tag_handle", ")", ":", "note", "=", "self", ".", "dbstate", ".", "db", ".", "get_note_from_handle", "(", "note_handle", ")", "note", ".", "remove_tag", "(", "tag_handle", ")", ...
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/plugins/view/noteview.py#L385-L391
maas/maas
db2f89970c640758a51247c59bf1ec6f60cf4ab5
src/maasserver/models/domain.py
python
validate_domain_name
(value)
Django validator: `value` must be a valid DNS Zone name.
Django validator: `value` must be a valid DNS Zone name.
[ "Django", "validator", ":", "value", "must", "be", "a", "valid", "DNS", "Zone", "name", "." ]
def validate_domain_name(value): """Django validator: `value` must be a valid DNS Zone name.""" namespec = re.compile("^%s$" % NAMESPEC) if not namespec.search(value) or len(value) > 255: raise ValidationError("Invalid domain name: %s." % value)
[ "def", "validate_domain_name", "(", "value", ")", ":", "namespec", "=", "re", ".", "compile", "(", "\"^%s$\"", "%", "NAMESPEC", ")", "if", "not", "namespec", ".", "search", "(", "value", ")", "or", "len", "(", "value", ")", ">", "255", ":", "raise", ...
https://github.com/maas/maas/blob/db2f89970c640758a51247c59bf1ec6f60cf4ab5/src/maasserver/models/domain.py#L37-L41
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/combinat.py
python
CombinatorialClass.__next_from_iterator
(self, obj)
return None
Default implementation for next which uses iterator. EXAMPLES:: sage: C = CombinatorialClass() sage: C.list = lambda: [1,2,3] sage: C.next(2) # indirect doctest 3
Default implementation for next which uses iterator.
[ "Default", "implementation", "for", "next", "which", "uses", "iterator", "." ]
def __next_from_iterator(self, obj): """ Default implementation for next which uses iterator. EXAMPLES:: sage: C = CombinatorialClass() sage: C.list = lambda: [1,2,3] sage: C.next(2) # indirect doctest 3 """ found = False for i in self: if found: return i if i == obj: found = True return None
[ "def", "__next_from_iterator", "(", "self", ",", "obj", ")", ":", "found", "=", "False", "for", "i", "in", "self", ":", "if", "found", ":", "return", "i", "if", "i", "==", "obj", ":", "found", "=", "True", "return", "None" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/combinat.py#L2031-L2048
conjure-up/conjure-up
d2bf8ab8e71ff01321d0e691a8d3e3833a047678
conjureup/hooklib/writer.py
python
success
(msg)
Returns a successful step
Returns a successful step
[ "Returns", "a", "successful", "step" ]
def success(msg): """ Returns a successful step """ print(msg) sys.exit(0)
[ "def", "success", "(", "msg", ")", ":", "print", "(", "msg", ")", "sys", ".", "exit", "(", "0", ")" ]
https://github.com/conjure-up/conjure-up/blob/d2bf8ab8e71ff01321d0e691a8d3e3833a047678/conjureup/hooklib/writer.py#L17-L21
learningequality/ka-lite
571918ea668013dcf022286ea85eff1c5333fb8b
kalite/packages/bundled/django/contrib/localflavor/pl/forms.py
python
PLPESELField.has_valid_checksum
(self, number)
return result % 10 == 0
Calculates a checksum with the provided algorithm.
Calculates a checksum with the provided algorithm.
[ "Calculates", "a", "checksum", "with", "the", "provided", "algorithm", "." ]
def has_valid_checksum(self, number): """ Calculates a checksum with the provided algorithm. """ multiple_table = (1, 3, 7, 9, 1, 3, 7, 9, 1, 3, 1) result = 0 for i in range(len(number)): result += int(number[i]) * multiple_table[i] return result % 10 == 0
[ "def", "has_valid_checksum", "(", "self", ",", "number", ")", ":", "multiple_table", "=", "(", "1", ",", "3", ",", "7", ",", "9", ",", "1", ",", "3", ",", "7", ",", "9", ",", "1", ",", "3", ",", "1", ")", "result", "=", "0", "for", "i", "in...
https://github.com/learningequality/ka-lite/blob/571918ea668013dcf022286ea85eff1c5333fb8b/kalite/packages/bundled/django/contrib/localflavor/pl/forms.py#L58-L66