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
gluon/AbletonLive9_RemoteScripts
0c0db5e2e29bbed88c82bf327f54d4968d36937e
Push/pad_sensitivity.py
python
pad_parameter_sender
(global_control, pad_control)
return do_send
Sends the sensitivity parameters for a given pad, or all pads (pad == None) over the given ValueControl.
Sends the sensitivity parameters for a given pad, or all pads (pad == None) over the given ValueControl.
[ "Sends", "the", "sensitivity", "parameters", "for", "a", "given", "pad", "or", "all", "pads", "(", "pad", "==", "None", ")", "over", "the", "given", "ValueControl", "." ]
def pad_parameter_sender(global_control, pad_control): """ Sends the sensitivity parameters for a given pad, or all pads (pad == None) over the given ValueControl. """ def do_send(parameters, pad = None): if pad != None: pad_control.send_value((pad,) + parameters.sysex_bytes) else: global_control.send_value(parameters.sysex_bytes) return do_send
[ "def", "pad_parameter_sender", "(", "global_control", ",", "pad_control", ")", ":", "def", "do_send", "(", "parameters", ",", "pad", "=", "None", ")", ":", "if", "pad", "!=", "None", ":", "pad_control", ".", "send_value", "(", "(", "pad", ",", ")", "+", ...
https://github.com/gluon/AbletonLive9_RemoteScripts/blob/0c0db5e2e29bbed88c82bf327f54d4968d36937e/Push/pad_sensitivity.py#L27-L39
Esri/ArcREST
ab240fde2b0200f61d4a5f6df033516e53f2f416
src/arcrest/manageorg/_content.py
python
Item.updateMetadata
(self, metadataFile)
return res
updates or adds the current item's metadata metadataFile is the path to the XML file to upload. Output: dictionary
updates or adds the current item's metadata metadataFile is the path to the XML file to upload. Output: dictionary
[ "updates", "or", "adds", "the", "current", "item", "s", "metadata", "metadataFile", "is", "the", "path", "to", "the", "XML", "file", "to", "upload", ".", "Output", ":", "dictionary" ]
def updateMetadata(self, metadataFile): """ updates or adds the current item's metadata metadataFile is the path to the XML file to upload. Output: dictionary """ ip = ItemParameter() ip.metadata = metadataFile res = self.userItem.updateItem(itemParameters=ip, metadata=metadataFile) del ip return res
[ "def", "updateMetadata", "(", "self", ",", "metadataFile", ")", ":", "ip", "=", "ItemParameter", "(", ")", "ip", ".", "metadata", "=", "metadataFile", "res", "=", "self", ".", "userItem", ".", "updateItem", "(", "itemParameters", "=", "ip", ",", "metadata"...
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/_content.py#L1033-L1045
coderholic/pyradio
cd3ee2d6b369fedfd009371a59aca23ab39b020f
pyradio/config.py
python
PyRadioStations.integrate_playlists
(self)
[]
def integrate_playlists(self): '''''' ''' get user station urls ''' self.added_stations = 0 urls = [] for n in self.stations: urls.append(n[1]) if logger.isEnabledFor(logging.DEBUG): logger.debug('----==== Stations integration ====----') for a_pkg_station in self._package_stations(): if a_pkg_station[1] not in urls: self.stations.append(a_pkg_station) self.added_stations += 1 if logger.isEnabledFor(logging.DEBUG): logger.debug('Added: {0} - {1}'.format(self.added_stations, a_pkg_station))
[ "def", "integrate_playlists", "(", "self", ")", ":", "''' get user station urls '''", "self", ".", "added_stations", "=", "0", "urls", "=", "[", "]", "for", "n", "in", "self", ".", "stations", ":", "urls", ".", "append", "(", "n", "[", "1", "]", ")", "...
https://github.com/coderholic/pyradio/blob/cd3ee2d6b369fedfd009371a59aca23ab39b020f/pyradio/config.py#L459-L474
QCoDeS/Qcodes
3cda2cef44812e2aa4672781f2423bf5f816f9f9
qcodes/logger/logger.py
python
get_formatter_for_telemetry
()
return logging.Formatter(format_string)
Returns :class:`logging.Formatter` with only name, function name and message keywords from FORMAT_STRING_DICT
Returns :class:`logging.Formatter` with only name, function name and message keywords from FORMAT_STRING_DICT
[ "Returns", ":", "class", ":", "logging", ".", "Formatter", "with", "only", "name", "function", "name", "and", "message", "keywords", "from", "FORMAT_STRING_DICT" ]
def get_formatter_for_telemetry() -> logging.Formatter: """ Returns :class:`logging.Formatter` with only name, function name and message keywords from FORMAT_STRING_DICT """ format_string_items = [f'%({name}){fmt}' for name, fmt in FORMAT_STRING_DICT.items() if name in ['message', 'name', 'funcName']] format_string = LOGGING_SEPARATOR.join(format_string_items) return logging.Formatter(format_string)
[ "def", "get_formatter_for_telemetry", "(", ")", "->", "logging", ".", "Formatter", ":", "format_string_items", "=", "[", "f'%({name}){fmt}'", "for", "name", ",", "fmt", "in", "FORMAT_STRING_DICT", ".", "items", "(", ")", "if", "name", "in", "[", "'message'", "...
https://github.com/QCoDeS/Qcodes/blob/3cda2cef44812e2aa4672781f2423bf5f816f9f9/qcodes/logger/logger.py#L88-L97
mmjang/mdict-query
dba760be6a30daff37037c895a0355684e16f83f
readmdict.py
python
MDict._decode_key_block
(self, key_block_compressed, key_block_info_list)
return key_list
[]
def _decode_key_block(self, key_block_compressed, key_block_info_list): key_list = [] i = 0 for compressed_size, decompressed_size in key_block_info_list: start = i end = i + compressed_size # 4 bytes : compression type key_block_type = key_block_compressed[start:start + 4] # 4 bytes : adler checksum of decompressed key block adler32 = unpack('>I', key_block_compressed[start + 4:start + 8])[0] if key_block_type == b'\x00\x00\x00\x00': key_block = key_block_compressed[start + 8:end] elif key_block_type == b'\x01\x00\x00\x00': if lzo is None: print("LZO compression is not supported") break # decompress key block header = b'\xf0' + pack('>I', decompressed_size) key_block = lzo.decompress(key_block_compressed[start + 8:end], initSize = decompressed_size, blockSize=1308672) elif key_block_type == b'\x02\x00\x00\x00': # decompress key block key_block = zlib.decompress(key_block_compressed[start + 8:end]) # extract one single key block into a key list key_list += self._split_key_block(key_block) # notice that adler32 returns signed value assert(adler32 == zlib.adler32(key_block) & 0xffffffff) i += compressed_size return key_list
[ "def", "_decode_key_block", "(", "self", ",", "key_block_compressed", ",", "key_block_info_list", ")", ":", "key_list", "=", "[", "]", "i", "=", "0", "for", "compressed_size", ",", "decompressed_size", "in", "key_block_info_list", ":", "start", "=", "i", "end", ...
https://github.com/mmjang/mdict-query/blob/dba760be6a30daff37037c895a0355684e16f83f/readmdict.py#L192-L220
devbisme/skidl
458709a10b28a864d25ae2c2b44c6103d4ddb291
skidl/arrange.py
python
Arranger.arrange_kl
(self)
Optimally arrange the parts across regions using Kernighan-Lin.
Optimally arrange the parts across regions using Kernighan-Lin.
[ "Optimally", "arrange", "the", "parts", "across", "regions", "using", "Kernighan", "-", "Lin", "." ]
def arrange_kl(self): """Optimally arrange the parts across regions using Kernighan-Lin.""" class Move: # Class for storing the move of a part to a region. def __init__(self, part, region, cost): self.part = part # Part being moved. self.region = region # Region being moved to. self.cost = cost # Cost after the move. def kl_iteration(): # Kernighan-Lin algorithm to optimize symbol placement: # A. Compute cost of moving each part to each region while # keeping all the other parts fixed. # B. Select the part and region that has the lowest cost # and move that part to that region. # C. Repeat the A & B for the remaining parts until no # parts remain. # D. Find the point in the sequence of moves where the # cost reaches its lowest value. Reverse all moves # after that point. def find_best_move(parts): # Find the best of all possible movements of parts to regions. # This stores the best move found across all parts & regions. best_move = Move(None, None, float("inf")) # Move each part to each region, looking for the best cost improvement. for part in parts: # Don't move a part that is fixed to a particular region. if hasattr(part, "fix"): continue # Save the region of the current part and remove the # part from that region. saved_region = part.region saved_region.rmv(part) assert part.region == None assert part not in saved_region.parts # Move the current part to each region and store the move if cost goes down. for x in range(part.move_box.min.x, part.move_box.max.x + 1): for y in range(part.move_box.min.y, part.move_box.max.y + 1): # Don't move a part to the region it's already in. if self.regions[x][y] is part.region: continue # Move part to region. self.regions[x][y].add(part) # Get cost when part is in that region. cost = self.cost() # Record move if it's the best seen so far. if cost < best_move.cost: best_move = Move(part, part.region, cost) # Remove part from the region. self.regions[x][y].rmv(part) assert part.region == None # Return the part to its original region. assert part.region == None saved_region.add(part) assert part in saved_region.parts assert part.region == saved_region # Return the move with the lowest cost. return best_move # Store the beginning arrangement of parts. beginning_arrangement = {part: part.region for part in self.parts} beginning_cost = self.cost() # Get the list of parts that can be moved. movable = [part for part in self.parts if not hasattr(part, "fix")] # Process all the movable parts until every one has been moved. moves = [] while movable: # Find and save the best move of all the movable parts. best_move = find_best_move(movable) moves.append(best_move) # Move the selected part from the region where it was to its new region. best_move.part.region.rmv(best_move.part) best_move.region.add(best_move.part) # Remove the part from the list of removable parts once it has been moved. movable.remove(best_move.part) # Find where the cost was lowest across the sequence of moves. low_pt = min(moves, key=lambda mv: mv.cost) low_pt_idx = moves.index(low_pt) if low_pt.cost >= beginning_cost: # No improvement in cost, so put everything back the way it was. low_pt_idx = -1 low_pt.cost = beginning_cost # Reverse all the part moves after the lowest point to their original regions. for move in moves[low_pt_idx + 1 :]: part = move.part new_region = move.region original_region = beginning_arrangement[part] new_region.rmv(part) original_region.add(part) # Recompute the cost. cost = self.cost() assert math.isclose(low_pt.cost, cost, rel_tol=0.0001) return cost # Iteratively apply KL until cost doesn't go down anymore. cost = self.cost() best_cost = cost + 1 # Make it higher so the following loop will run. while cost < best_cost: best_cost = cost cost = kl_iteration() assert math.isclose(best_cost, self.cost(), rel_tol=0.0001)
[ "def", "arrange_kl", "(", "self", ")", ":", "class", "Move", ":", "# Class for storing the move of a part to a region.", "def", "__init__", "(", "self", ",", "part", ",", "region", ",", "cost", ")", ":", "self", ".", "part", "=", "part", "# Part being moved.", ...
https://github.com/devbisme/skidl/blob/458709a10b28a864d25ae2c2b44c6103d4ddb291/skidl/arrange.py#L194-L317
fofix/fofix
7730d1503c66562b901f62b33a5bd46c3d5e5c34
fofix/game/guitarscene/Rockmeter.py
python
Replace.fixScale
(self)
Fix the scale after the rect is changed.
Fix the scale after the rect is changed.
[ "Fix", "the", "scale", "after", "the", "rect", "is", "changed", "." ]
def fixScale(self): """ Fix the scale after the rect is changed. """ w, h, = self.engine.view.geometry[2:4] rect = self.layer.rect scale = [eval(self.xscaleexpr), eval(self.yscaleexpr)] scale[0] *= (rect[1] - rect[0]) scale[1] *= (rect[3] - rect[2]) # this allows you to scale images in relation to pixels instead # of percentage of the size of the image. if "xscale" in self.layer.inPixels: scale[0] /= self.layer.drawing.pixelSize[0] if "yscale" in self.layer.inPixels: scale[1] /= self.layer.drawing.pixelSize[1] scale[1] = -scale[1] scale[0] *= w / vpc[0] scale[1] *= h / vpc[1] self.layer.scale = scale
[ "def", "fixScale", "(", "self", ")", ":", "w", ",", "h", ",", "=", "self", ".", "engine", ".", "view", ".", "geometry", "[", "2", ":", "4", "]", "rect", "=", "self", ".", "layer", ".", "rect", "scale", "=", "[", "eval", "(", "self", ".", "xsc...
https://github.com/fofix/fofix/blob/7730d1503c66562b901f62b33a5bd46c3d5e5c34/fofix/game/guitarscene/Rockmeter.py#L795-L814
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/gdata/src/gdata/youtube/service.py
python
YouTubeService.AddSubscriptionToChannel
(self, username_to_subscribe_to, my_username = 'default')
return self.Post(subscription_entry, post_uri, converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
Add a new channel subscription to the currently authenticated users account. Needs authentication. Args: username_to_subscribe_to: A string representing the username of the channel to which we want to subscribe to. my_username: An optional string representing the name of the user which we want to subscribe. Defaults to currently authenticated user. Returns: A new YouTubeSubscriptionEntry if successfully posted.
Add a new channel subscription to the currently authenticated users account.
[ "Add", "a", "new", "channel", "subscription", "to", "the", "currently", "authenticated", "users", "account", "." ]
def AddSubscriptionToChannel(self, username_to_subscribe_to, my_username = 'default'): """Add a new channel subscription to the currently authenticated users account. Needs authentication. Args: username_to_subscribe_to: A string representing the username of the channel to which we want to subscribe to. my_username: An optional string representing the name of the user which we want to subscribe. Defaults to currently authenticated user. Returns: A new YouTubeSubscriptionEntry if successfully posted. """ subscription_category = atom.Category( scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME, term='channel') subscription_username = gdata.youtube.Username( text=username_to_subscribe_to) subscription_entry = gdata.youtube.YouTubeSubscriptionEntry( category=subscription_category, username=subscription_username) post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username, 'subscriptions') return self.Post(subscription_entry, post_uri, converter=gdata.youtube.YouTubeSubscriptionEntryFromString)
[ "def", "AddSubscriptionToChannel", "(", "self", ",", "username_to_subscribe_to", ",", "my_username", "=", "'default'", ")", ":", "subscription_category", "=", "atom", ".", "Category", "(", "scheme", "=", "YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME", ",", "term", "=", "'chan...
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/gdata/src/gdata/youtube/service.py#L1063-L1093
auth0/auth0-python
511b016ac9853c7f4ee66769be7ad315c5585735
auth0/v3/management/tickets.py
python
Tickets.create_email_verification
(self, body)
return self.client.post(self._url('email-verification'), data=body)
Create an email verification ticket. Args: body (dict): attributes to set on the email verification request. See: https://auth0.com/docs/api/v2#!/Tickets/post_email_verification
Create an email verification ticket.
[ "Create", "an", "email", "verification", "ticket", "." ]
def create_email_verification(self, body): """Create an email verification ticket. Args: body (dict): attributes to set on the email verification request. See: https://auth0.com/docs/api/v2#!/Tickets/post_email_verification """ return self.client.post(self._url('email-verification'), data=body)
[ "def", "create_email_verification", "(", "self", ",", "body", ")", ":", "return", "self", ".", "client", ".", "post", "(", "self", ".", "_url", "(", "'email-verification'", ")", ",", "data", "=", "body", ")" ]
https://github.com/auth0/auth0-python/blob/511b016ac9853c7f4ee66769be7ad315c5585735/auth0/v3/management/tickets.py#L34-L42
PyFilesystem/pyfilesystem
7dfe14ae6c3b9c53543c1c3890232d9f37579f34
fs/utils.py
python
copydir
(fs1, fs2, create_destination=True, ignore_errors=False, chunk_size=64*1024)
Copies contents of a directory from one filesystem to another. :param fs1: Source filesystem, or a tuple of (<filesystem>, <directory path>) :param fs2: Destination filesystem, or a tuple of (<filesystem>, <directory path>) :param create_destination: If True, the destination will be created if it doesn't exist :param ignore_errors: If True, exceptions from file moves are ignored :param chunk_size: Size of chunks to move if a simple copy is used
Copies contents of a directory from one filesystem to another.
[ "Copies", "contents", "of", "a", "directory", "from", "one", "filesystem", "to", "another", "." ]
def copydir(fs1, fs2, create_destination=True, ignore_errors=False, chunk_size=64*1024): """Copies contents of a directory from one filesystem to another. :param fs1: Source filesystem, or a tuple of (<filesystem>, <directory path>) :param fs2: Destination filesystem, or a tuple of (<filesystem>, <directory path>) :param create_destination: If True, the destination will be created if it doesn't exist :param ignore_errors: If True, exceptions from file moves are ignored :param chunk_size: Size of chunks to move if a simple copy is used """ if isinstance(fs1, tuple): fs1, dir1 = fs1 fs1 = fs1.opendir(dir1) if isinstance(fs2, tuple): fs2, dir2 = fs2 if create_destination: fs2.makedir(dir2, allow_recreate=True, recursive=True) fs2 = fs2.opendir(dir2) mount_fs = MountFS(auto_close=False) mount_fs.mount('src', fs1) mount_fs.mount('dst', fs2) mount_fs.copydir('src', 'dst', overwrite=True, ignore_errors=ignore_errors, chunk_size=chunk_size)
[ "def", "copydir", "(", "fs1", ",", "fs2", ",", "create_destination", "=", "True", ",", "ignore_errors", "=", "False", ",", "chunk_size", "=", "64", "*", "1024", ")", ":", "if", "isinstance", "(", "fs1", ",", "tuple", ")", ":", "fs1", ",", "dir1", "="...
https://github.com/PyFilesystem/pyfilesystem/blob/7dfe14ae6c3b9c53543c1c3890232d9f37579f34/fs/utils.py#L236-L261
twisted/twisted
dee676b040dd38b847ea6fb112a712cb5e119490
src/twisted/internet/inotify.py
python
INotify.watch
( self, path, mask=IN_WATCH_MASK, autoAdd=False, callbacks=None, recursive=False )
Watch the 'mask' events in given path. Can raise C{INotifyError} when there's a problem while adding a directory. @param path: The path needing monitoring @type path: L{FilePath} @param mask: The events that should be watched @type mask: L{int} @param autoAdd: if True automatically add newly created subdirectories @type autoAdd: L{bool} @param callbacks: A list of callbacks that should be called when an event happens in the given path. The callback should accept 3 arguments: (ignored, filepath, mask) @type callbacks: L{list} of callables @param recursive: Also add all the subdirectories in this path @type recursive: L{bool}
Watch the 'mask' events in given path. Can raise C{INotifyError} when there's a problem while adding a directory.
[ "Watch", "the", "mask", "events", "in", "given", "path", ".", "Can", "raise", "C", "{", "INotifyError", "}", "when", "there", "s", "a", "problem", "while", "adding", "a", "directory", "." ]
def watch( self, path, mask=IN_WATCH_MASK, autoAdd=False, callbacks=None, recursive=False ): """ Watch the 'mask' events in given path. Can raise C{INotifyError} when there's a problem while adding a directory. @param path: The path needing monitoring @type path: L{FilePath} @param mask: The events that should be watched @type mask: L{int} @param autoAdd: if True automatically add newly created subdirectories @type autoAdd: L{bool} @param callbacks: A list of callbacks that should be called when an event happens in the given path. The callback should accept 3 arguments: (ignored, filepath, mask) @type callbacks: L{list} of callables @param recursive: Also add all the subdirectories in this path @type recursive: L{bool} """ if recursive: # This behavior is needed to be compatible with the windows # interface for filesystem changes: # http://msdn.microsoft.com/en-us/library/aa365465(VS.85).aspx # ReadDirectoryChangesW can do bWatchSubtree so it doesn't # make sense to implement this at a higher abstraction # level when other platforms support it already for child in path.walk(): if child.isdir(): self.watch(child, mask, autoAdd, callbacks, recursive=False) else: wd = self._isWatched(path) if wd: return wd mask = mask | IN_DELETE_SELF # need this to remove the watch return self._addWatch(path, mask, autoAdd, callbacks)
[ "def", "watch", "(", "self", ",", "path", ",", "mask", "=", "IN_WATCH_MASK", ",", "autoAdd", "=", "False", ",", "callbacks", "=", "None", ",", "recursive", "=", "False", ")", ":", "if", "recursive", ":", "# This behavior is needed to be compatible with the windo...
https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/internet/inotify.py#L326-L369
frescobaldi/frescobaldi
301cc977fc4ba7caa3df9e4bf905212ad5d06912
frescobaldi_app/userguide/read.py
python
Parser.probably_translate
(self, s)
return s
Translates the string if it is a sensible translatable message. The string is not translated if it does not contain any letters or if it is is a Python format string without any text outside the variable names.
Translates the string if it is a sensible translatable message.
[ "Translates", "the", "string", "if", "it", "is", "a", "sensible", "translatable", "message", "." ]
def probably_translate(self, s): """Translates the string if it is a sensible translatable message. The string is not translated if it does not contain any letters or if it is is a Python format string without any text outside the variable names. """ pos = 0 for m in _variable_re.finditer(s): if m.start() > pos and any(c.isalpha() for c in s[pos:m.start()]): return self.translate(s) pos = m.end() if pos < len(s) and any(c.isalpha() for c in s[pos:]): return self.translate(s) return s
[ "def", "probably_translate", "(", "self", ",", "s", ")", ":", "pos", "=", "0", "for", "m", "in", "_variable_re", ".", "finditer", "(", "s", ")", ":", "if", "m", ".", "start", "(", ")", ">", "pos", "and", "any", "(", "c", ".", "isalpha", "(", ")...
https://github.com/frescobaldi/frescobaldi/blob/301cc977fc4ba7caa3df9e4bf905212ad5d06912/frescobaldi_app/userguide/read.py#L78-L93
Azure/blobxfer
c6c6c143e8ee413d09a1110abafdb92e9e8afc39
blobxfer/util.py
python
normalize_azure_path
(path)
return '/'.join(re.split('/|\\\\', _path))
Normalize remote path (strip slashes and use forward slashes) :param str path: path to normalize :rtype: str :return: normalized path
Normalize remote path (strip slashes and use forward slashes) :param str path: path to normalize :rtype: str :return: normalized path
[ "Normalize", "remote", "path", "(", "strip", "slashes", "and", "use", "forward", "slashes", ")", ":", "param", "str", "path", ":", "path", "to", "normalize", ":", "rtype", ":", "str", ":", "return", ":", "normalized", "path" ]
def normalize_azure_path(path): # type: (str) -> str """Normalize remote path (strip slashes and use forward slashes) :param str path: path to normalize :rtype: str :return: normalized path """ if is_none_or_empty(path): raise ValueError('provided path is invalid') _path = path.strip('/').strip('\\') return '/'.join(re.split('/|\\\\', _path))
[ "def", "normalize_azure_path", "(", "path", ")", ":", "# type: (str) -> str", "if", "is_none_or_empty", "(", "path", ")", ":", "raise", "ValueError", "(", "'provided path is invalid'", ")", "_path", "=", "path", ".", "strip", "(", "'/'", ")", ".", "strip", "("...
https://github.com/Azure/blobxfer/blob/c6c6c143e8ee413d09a1110abafdb92e9e8afc39/blobxfer/util.py#L246-L256
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_openshift_3.2/build/src/oc_serviceaccount.py
python
OCServiceAccount.delete
(self)
return self._delete(self.kind, self.config.name)
delete the object
delete the object
[ "delete", "the", "object" ]
def delete(self): '''delete the object''' return self._delete(self.kind, self.config.name)
[ "def", "delete", "(", "self", ")", ":", "return", "self", ".", "_delete", "(", "self", ".", "kind", ",", "self", ".", "config", ".", "name", ")" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_openshift_3.2/build/src/oc_serviceaccount.py#L49-L51
docker/docker-py
a48a5a9647761406d66e8271f19fab7fa0c5f582
docker/models/volumes.py
python
VolumeCollection.get
(self, volume_id)
return self.prepare_model(self.client.api.inspect_volume(volume_id))
Get a volume. Args: volume_id (str): Volume name. Returns: (:py:class:`Volume`): The volume. Raises: :py:class:`docker.errors.NotFound` If the volume does not exist. :py:class:`docker.errors.APIError` If the server returns an error.
Get a volume.
[ "Get", "a", "volume", "." ]
def get(self, volume_id): """ Get a volume. Args: volume_id (str): Volume name. Returns: (:py:class:`Volume`): The volume. Raises: :py:class:`docker.errors.NotFound` If the volume does not exist. :py:class:`docker.errors.APIError` If the server returns an error. """ return self.prepare_model(self.client.api.inspect_volume(volume_id))
[ "def", "get", "(", "self", ",", "volume_id", ")", ":", "return", "self", ".", "prepare_model", "(", "self", ".", "client", ".", "api", ".", "inspect_volume", "(", "volume_id", ")", ")" ]
https://github.com/docker/docker-py/blob/a48a5a9647761406d66e8271f19fab7fa0c5f582/docker/models/volumes.py#L60-L76
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
dist/lib/python2.7/email/message.py
python
Message.set_type
(self, type, header='Content-Type', requote=True)
Set the main type and subtype for the Content-Type header. type must be a string in the form "maintype/subtype", otherwise a ValueError is raised. This method replaces the Content-Type header, keeping all the parameters in place. If requote is False, this leaves the existing header's quoting as is. Otherwise, the parameters will be quoted (the default). An alternative header can be specified in the header argument. When the Content-Type header is set, we'll always also add a MIME-Version header.
Set the main type and subtype for the Content-Type header.
[ "Set", "the", "main", "type", "and", "subtype", "for", "the", "Content", "-", "Type", "header", "." ]
def set_type(self, type, header='Content-Type', requote=True): """Set the main type and subtype for the Content-Type header. type must be a string in the form "maintype/subtype", otherwise a ValueError is raised. This method replaces the Content-Type header, keeping all the parameters in place. If requote is False, this leaves the existing header's quoting as is. Otherwise, the parameters will be quoted (the default). An alternative header can be specified in the header argument. When the Content-Type header is set, we'll always also add a MIME-Version header. """ # BAW: should we be strict? if not type.count('/') == 1: raise ValueError # Set the Content-Type, you get a MIME-Version if header.lower() == 'content-type': del self['mime-version'] self['MIME-Version'] = '1.0' if header not in self: self[header] = type return params = self.get_params(header=header, unquote=requote) del self[header] self[header] = type # Skip the first param; it's the old type. for p, v in params[1:]: self.set_param(p, v, header, requote)
[ "def", "set_type", "(", "self", ",", "type", ",", "header", "=", "'Content-Type'", ",", "requote", "=", "True", ")", ":", "# BAW: should we be strict?", "if", "not", "type", ".", "count", "(", "'/'", ")", "==", "1", ":", "raise", "ValueError", "# Set the C...
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/dist/lib/python2.7/email/message.py#L641-L671
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/gettext.py
python
GNUTranslations.ngettext
(self, msgid1, msgid2, n)
return tmsg
[]
def ngettext(self, msgid1, msgid2, n): try: tmsg = self._catalog[(msgid1, self.plural(n))] except KeyError: if self._fallback: return self._fallback.ngettext(msgid1, msgid2, n) if n == 1: tmsg = msgid1 else: tmsg = msgid2 return tmsg
[ "def", "ngettext", "(", "self", ",", "msgid1", ",", "msgid2", ",", "n", ")", ":", "try", ":", "tmsg", "=", "self", ".", "_catalog", "[", "(", "msgid1", ",", "self", ".", "plural", "(", "n", ")", ")", "]", "except", "KeyError", ":", "if", "self", ...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/gettext.py#L339-L349
NVIDIA/DeepLearningExamples
589604d49e016cd9ef4525f7abcc9c7b826cfc5e
PyTorch/Recommendation/DLRM/dlrm/scripts/utils.py
python
roc_auc_score
(y_true, y_score)
return area
ROC AUC score in PyTorch Args: y_true (Tensor): y_score (Tensor):
ROC AUC score in PyTorch
[ "ROC", "AUC", "score", "in", "PyTorch" ]
def roc_auc_score(y_true, y_score): """ROC AUC score in PyTorch Args: y_true (Tensor): y_score (Tensor): """ device = y_true.device y_true.squeeze_() y_score.squeeze_() if y_true.shape != y_score.shape: raise TypeError(f"Shape of y_true and y_score must match. Got {y_true.shape()} and {y_score.shape()}.") desc_score_indices = torch.argsort(y_score, descending=True) y_score = y_score[desc_score_indices] y_true = y_true[desc_score_indices] distinct_value_indices = torch.nonzero(y_score[1:] - y_score[:-1], as_tuple=False).squeeze() threshold_idxs = torch.cat([distinct_value_indices, torch.tensor([y_true.numel() - 1], device=device)]) tps = torch.cumsum(y_true, dim=0)[threshold_idxs] fps = 1 + threshold_idxs - tps tps = torch.cat([torch.zeros(1, device=device), tps]) fps = torch.cat([torch.zeros(1, device=device), fps]) fpr = fps / fps[-1] tpr = tps / tps[-1] area = torch.trapz(tpr, fpr).item() return area
[ "def", "roc_auc_score", "(", "y_true", ",", "y_score", ")", ":", "device", "=", "y_true", ".", "device", "y_true", ".", "squeeze_", "(", ")", "y_score", ".", "squeeze_", "(", ")", "if", "y_true", ".", "shape", "!=", "y_score", ".", "shape", ":", "raise...
https://github.com/NVIDIA/DeepLearningExamples/blob/589604d49e016cd9ef4525f7abcc9c7b826cfc5e/PyTorch/Recommendation/DLRM/dlrm/scripts/utils.py#L275-L306
Jenyay/outwiker
50530cf7b3f71480bb075b2829bc0669773b835b
plugins/snippets/snippets/libs/jinja2/filters.py
python
environmentfilter
(f)
return f
Decorator for marking environment dependent filters. The current :class:`Environment` is passed to the filter as first argument.
Decorator for marking environment dependent filters. The current :class:`Environment` is passed to the filter as first argument.
[ "Decorator", "for", "marking", "environment", "dependent", "filters", ".", "The", "current", ":", "class", ":", "Environment", "is", "passed", "to", "the", "filter", "as", "first", "argument", "." ]
def environmentfilter(f): """Decorator for marking environment dependent filters. The current :class:`Environment` is passed to the filter as first argument. """ f.environmentfilter = True return f
[ "def", "environmentfilter", "(", "f", ")", ":", "f", ".", "environmentfilter", "=", "True", "return", "f" ]
https://github.com/Jenyay/outwiker/blob/50530cf7b3f71480bb075b2829bc0669773b835b/plugins/snippets/snippets/libs/jinja2/filters.py#L48-L53
beancount/beancount
cb3526a1af95b3b5be70347470c381b5a86055fe
beancount/ops/basicops.py
python
filter_tag
(tag, entries)
Yield all the entries which have the given tag. Args: tag: A string, the tag we are interested in. Yields: Every entry in 'entries' that tags to 'tag.
Yield all the entries which have the given tag.
[ "Yield", "all", "the", "entries", "which", "have", "the", "given", "tag", "." ]
def filter_tag(tag, entries): """Yield all the entries which have the given tag. Args: tag: A string, the tag we are interested in. Yields: Every entry in 'entries' that tags to 'tag. """ for entry in entries: if (isinstance(entry, data.Transaction) and entry.tags and tag in entry.tags): yield entry
[ "def", "filter_tag", "(", "tag", ",", "entries", ")", ":", "for", "entry", "in", "entries", ":", "if", "(", "isinstance", "(", "entry", ",", "data", ".", "Transaction", ")", "and", "entry", ".", "tags", "and", "tag", "in", "entry", ".", "tags", ")", ...
https://github.com/beancount/beancount/blob/cb3526a1af95b3b5be70347470c381b5a86055fe/beancount/ops/basicops.py#L14-L26
sailthru/stolos
7b74da527033b2da7f3ccd6d19ed6fb0245ea0fc
stolos/plugins/pyspark_context.py
python
receive_kwargs_as_dict
(func)
return _partial
A decorator that recieves a dict and passes the kwargs to wrapped func. It's very useful to use for spark functions: @receive_kwargs_as_dict def myfunc(a, b): return a > 1 print myfunc({'a': 4, 'b': 6}) sc.parallelize([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]).filter(myfunc)
A decorator that recieves a dict and passes the kwargs to wrapped func. It's very useful to use for spark functions:
[ "A", "decorator", "that", "recieves", "a", "dict", "and", "passes", "the", "kwargs", "to", "wrapped", "func", ".", "It", "s", "very", "useful", "to", "use", "for", "spark", "functions", ":" ]
def receive_kwargs_as_dict(func): """A decorator that recieves a dict and passes the kwargs to wrapped func. It's very useful to use for spark functions: @receive_kwargs_as_dict def myfunc(a, b): return a > 1 print myfunc({'a': 4, 'b': 6}) sc.parallelize([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]).filter(myfunc) """ @functools.wraps(func) def _partial(kwargs_dct, **kwargs): kwargs.update(kwargs_dct) return func(**kwargs) return _partial
[ "def", "receive_kwargs_as_dict", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "_partial", "(", "kwargs_dct", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "kwargs_dct", ")", "return", "func", "(", "...
https://github.com/sailthru/stolos/blob/7b74da527033b2da7f3ccd6d19ed6fb0245ea0fc/stolos/plugins/pyspark_context.py#L12-L27
CacheBrowser/cachebrowser
4bf1d58e5c82a0dbaa878f7725c830d472f5326e
cachebrowser/api/core.py
python
BaseAPIManager.handle_api_request
(self, context, request)
[]
def handle_api_request(self, context, request): self.handlers[request.route](context, request)
[ "def", "handle_api_request", "(", "self", ",", "context", ",", "request", ")", ":", "self", ".", "handlers", "[", "request", ".", "route", "]", "(", "context", ",", "request", ")" ]
https://github.com/CacheBrowser/cachebrowser/blob/4bf1d58e5c82a0dbaa878f7725c830d472f5326e/cachebrowser/api/core.py#L20-L21
NiaOrg/NiaPy
08f24ffc79fe324bc9c66ee7186ef98633026005
niapy/problems/step.py
python
Step.__init__
(self, dimension=4, lower=-100.0, upper=100.0, *args, **kwargs)
r"""Initialize Step problem.. Args: dimension (Optional[int]): Dimension of the problem. lower (Optional[Union[float, Iterable[float]]]): Lower bounds of the problem. upper (Optional[Union[float, Iterable[float]]]): Upper bounds of the problem. See Also: :func:`niapy.problems.Problem.__init__`
r"""Initialize Step problem..
[ "r", "Initialize", "Step", "problem", ".." ]
def __init__(self, dimension=4, lower=-100.0, upper=100.0, *args, **kwargs): r"""Initialize Step problem.. Args: dimension (Optional[int]): Dimension of the problem. lower (Optional[Union[float, Iterable[float]]]): Lower bounds of the problem. upper (Optional[Union[float, Iterable[float]]]): Upper bounds of the problem. See Also: :func:`niapy.problems.Problem.__init__` """ super().__init__(dimension, lower, upper, *args, **kwargs)
[ "def", "__init__", "(", "self", ",", "dimension", "=", "4", ",", "lower", "=", "-", "100.0", ",", "upper", "=", "100.0", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "__init__", "(", "dimension", ",", "lower", ",",...
https://github.com/NiaOrg/NiaPy/blob/08f24ffc79fe324bc9c66ee7186ef98633026005/niapy/problems/step.py#L51-L63
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/pygments/filters/__init__.py
python
get_all_filters
()
Return a generator of all filter names.
Return a generator of all filter names.
[ "Return", "a", "generator", "of", "all", "filter", "names", "." ]
def get_all_filters(): """ Return a generator of all filter names. """ for name in FILTERS: yield name for name, _ in find_plugin_filters(): yield name
[ "def", "get_all_filters", "(", ")", ":", "for", "name", "in", "FILTERS", ":", "yield", "name", "for", "name", ",", "_", "in", "find_plugin_filters", "(", ")", ":", "yield", "name" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/pygments/filters/__init__.py#L47-L54
deepmind/dm_control
806a10e896e7c887635328bfa8352604ad0fedae
dm_control/mjcf/element.py
python
_ActuatorElement._children_to_xml
(self, xml_element, prefix_root, debug_context=None)
[]
def _children_to_xml(self, xml_element, prefix_root, debug_context=None): second_order = [] third_order = [] debug_comments = {} for child in self.all_children(): child_xml = child.to_xml(prefix_root, debug_context) if (child_xml.attrib or len(child_xml) # pylint: disable=g-explicit-length-test or child.spec.repeated or child.spec.on_demand): if self._is_third_order_actuator(child): third_order.append(child_xml) else: second_order.append(child_xml) if debugging.debug_mode() and debug_context: debug_comment = debug_context.register_element_for_debugging(child) debug_comments[child_xml] = debug_comment if len(child_xml) > 0: # pylint: disable=g-explicit-length-test child_xml.insert(0, copy.deepcopy(debug_comment)) # Ensure that all second-order actuators come before third-order actuators # in the XML. for child_xml in second_order + third_order: xml_element.append(child_xml) if debugging.debug_mode() and debug_context: xml_element.append(debug_comments[child_xml])
[ "def", "_children_to_xml", "(", "self", ",", "xml_element", ",", "prefix_root", ",", "debug_context", "=", "None", ")", ":", "second_order", "=", "[", "]", "third_order", "=", "[", "]", "debug_comments", "=", "{", "}", "for", "child", "in", "self", ".", ...
https://github.com/deepmind/dm_control/blob/806a10e896e7c887635328bfa8352604ad0fedae/dm_control/mjcf/element.py#L1085-L1107
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v1_limit_range_item.py
python
V1LimitRangeItem.max
(self)
return self._max
Gets the max of this V1LimitRangeItem. # noqa: E501 Max usage constraints on this kind by resource name. # noqa: E501 :return: The max of this V1LimitRangeItem. # noqa: E501 :rtype: dict(str, str)
Gets the max of this V1LimitRangeItem. # noqa: E501
[ "Gets", "the", "max", "of", "this", "V1LimitRangeItem", ".", "#", "noqa", ":", "E501" ]
def max(self): """Gets the max of this V1LimitRangeItem. # noqa: E501 Max usage constraints on this kind by resource name. # noqa: E501 :return: The max of this V1LimitRangeItem. # noqa: E501 :rtype: dict(str, str) """ return self._max
[ "def", "max", "(", "self", ")", ":", "return", "self", ".", "_max" ]
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1_limit_range_item.py#L126-L134
djblets/djblets
0496e1ec49e43d43d776768c9fc5b6f8af56ec2c
djblets/extensions/settings.py
python
ExtensionSettings.save
(self)
Save all current settings to the database.
Save all current settings to the database.
[ "Save", "all", "current", "settings", "to", "the", "database", "." ]
def save(self): """Save all current settings to the database.""" registration = self.extension.registration registration.settings = dict(self) registration.save() settings_saved.send(sender=self.extension) # Make sure others are aware that the configuration changed. self.extension.extension_manager._bump_sync_gen()
[ "def", "save", "(", "self", ")", ":", "registration", "=", "self", ".", "extension", ".", "registration", "registration", ".", "settings", "=", "dict", "(", "self", ")", "registration", ".", "save", "(", ")", "settings_saved", ".", "send", "(", "sender", ...
https://github.com/djblets/djblets/blob/0496e1ec49e43d43d776768c9fc5b6f8af56ec2c/djblets/extensions/settings.py#L161-L170
AutodeskRoboticsLab/Mimic
85447f0d346be66988303a6a054473d92f1ed6f4
mimic/scripts/extern/pyqtgraph_0_11_0_dev0/pyqtgraph/flowchart/library/Filters.py
python
RemoveBaseline.disconnectFromPlot
(self, plot)
Define what happens when the node is disconnected from a plot
Define what happens when the node is disconnected from a plot
[ "Define", "what", "happens", "when", "the", "node", "is", "disconnected", "from", "a", "plot" ]
def disconnectFromPlot(self, plot): """Define what happens when the node is disconnected from a plot""" plot.removeItem(self.line)
[ "def", "disconnectFromPlot", "(", "self", ",", "plot", ")", ":", "plot", ".", "removeItem", "(", "self", ".", "line", ")" ]
https://github.com/AutodeskRoboticsLab/Mimic/blob/85447f0d346be66988303a6a054473d92f1ed6f4/mimic/scripts/extern/pyqtgraph_0_11_0_dev0/pyqtgraph/flowchart/library/Filters.py#L227-L229
linsomniac/python-memcached
bad41222379102e3f18f6f2f7be3ee608de6fbff
memcache.py
python
Client.cas
(self, key, val, time=0, min_compress_len=0, noreply=False)
return self._set("cas", key, val, time, min_compress_len, noreply)
Check and set (CAS) Sets a key to a given value in the memcache if it hasn't been altered since last fetched. (See L{gets}). The C{key} can optionally be an tuple, with the first element being the server hash value and the second being the key. If you want to avoid making this module calculate a hash value. You may prefer, for example, to keep all of a given user's objects on the same memcache server, so you could use the user's unique id as the hash value. @return: Nonzero on success. @rtype: int @param time: Tells memcached the time which this value should expire, either as a delta number of seconds, or an absolute unix time-since-the-epoch value. See the memcached protocol docs section "Storage Commands" for more info on <exptime>. We default to 0 == cache forever. @param min_compress_len: The threshold length to kick in auto-compression of the value using the compressor routine. If the value being cached is a string, then the length of the string is measured, else if the value is an object, then the length of the pickle result is measured. If the resulting attempt at compression yields a larger string than the input, then it is discarded. For backwards compatibility, this parameter defaults to 0, indicating don't ever try to compress. @param noreply: optional parameter instructs the server to not send the reply.
Check and set (CAS)
[ "Check", "and", "set", "(", "CAS", ")" ]
def cas(self, key, val, time=0, min_compress_len=0, noreply=False): '''Check and set (CAS) Sets a key to a given value in the memcache if it hasn't been altered since last fetched. (See L{gets}). The C{key} can optionally be an tuple, with the first element being the server hash value and the second being the key. If you want to avoid making this module calculate a hash value. You may prefer, for example, to keep all of a given user's objects on the same memcache server, so you could use the user's unique id as the hash value. @return: Nonzero on success. @rtype: int @param time: Tells memcached the time which this value should expire, either as a delta number of seconds, or an absolute unix time-since-the-epoch value. See the memcached protocol docs section "Storage Commands" for more info on <exptime>. We default to 0 == cache forever. @param min_compress_len: The threshold length to kick in auto-compression of the value using the compressor routine. If the value being cached is a string, then the length of the string is measured, else if the value is an object, then the length of the pickle result is measured. If the resulting attempt at compression yields a larger string than the input, then it is discarded. For backwards compatibility, this parameter defaults to 0, indicating don't ever try to compress. @param noreply: optional parameter instructs the server to not send the reply. ''' return self._set("cas", key, val, time, min_compress_len, noreply)
[ "def", "cas", "(", "self", ",", "key", ",", "val", ",", "time", "=", "0", ",", "min_compress_len", "=", "0", ",", "noreply", "=", "False", ")", ":", "return", "self", ".", "_set", "(", "\"cas\"", ",", "key", ",", "val", ",", "time", ",", "min_com...
https://github.com/linsomniac/python-memcached/blob/bad41222379102e3f18f6f2f7be3ee608de6fbff/memcache.py#L729-L764
bbrodriges/pholcidae
71c83571ad3ab7c60d44b912bd17dcbdd3903a10
pholcidae2/__init__.py
python
Pholcidae.start
(self)
Prepares everything and starts
Prepares everything and starts
[ "Prepares", "everything", "and", "starts" ]
def start(self): """ Prepares everything and starts """ self.__prepare() # trying to call precrawl function precrawl = self._settings['precrawl'] getattr(self, precrawl)() if precrawl else None self.__fetch_pages() # trying to call postcrawl function postcrawl = self._settings['postcrawl'] getattr(self, postcrawl)() if postcrawl else None
[ "def", "start", "(", "self", ")", ":", "self", ".", "__prepare", "(", ")", "# trying to call precrawl function", "precrawl", "=", "self", ".", "_settings", "[", "'precrawl'", "]", "getattr", "(", "self", ",", "precrawl", ")", "(", ")", "if", "precrawl", "e...
https://github.com/bbrodriges/pholcidae/blob/71c83571ad3ab7c60d44b912bd17dcbdd3903a10/pholcidae2/__init__.py#L57-L73
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/dump_reload/sql/load.py
python
DefaultDictWithKey.__missing__
(self, key)
return value
[]
def __missing__(self, key): self[key] = value = self.default_factory(key) return value
[ "def", "__missing__", "(", "self", ",", "key", ")", ":", "self", "[", "key", "]", "=", "value", "=", "self", ".", "default_factory", "(", "key", ")", "return", "value" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/dump_reload/sql/load.py#L238-L240
mikedh/trimesh
6b1e05616b44e6dd708d9bc748b211656ebb27ec
trimesh/grouping.py
python
unique_value_in_row
(data, unique=None)
return result
For a 2D array of integers find the position of a value in each row which only occurs once. If there are more than one value per row which occur once, the last one is returned. Parameters ---------- data : (n, d) int Data to check values unique : (m,) int List of unique values contained in data. Generated from np.unique if not passed Returns --------- result : (n, d) bool With one or zero True values per row. Examples ------------------------------------- In [0]: r = np.array([[-1, 1, 1], [-1, 1, -1], [-1, 1, 1], [-1, 1, -1], [-1, 1, -1]], dtype=np.int8) In [1]: unique_value_in_row(r) Out[1]: array([[ True, False, False], [False, True, False], [ True, False, False], [False, True, False], [False, True, False]], dtype=bool) In [2]: unique_value_in_row(r).sum(axis=1) Out[2]: array([1, 1, 1, 1, 1]) In [3]: r[unique_value_in_row(r)] Out[3]: array([-1, 1, -1, 1, 1], dtype=int8)
For a 2D array of integers find the position of a value in each row which only occurs once.
[ "For", "a", "2D", "array", "of", "integers", "find", "the", "position", "of", "a", "value", "in", "each", "row", "which", "only", "occurs", "once", "." ]
def unique_value_in_row(data, unique=None): """ For a 2D array of integers find the position of a value in each row which only occurs once. If there are more than one value per row which occur once, the last one is returned. Parameters ---------- data : (n, d) int Data to check values unique : (m,) int List of unique values contained in data. Generated from np.unique if not passed Returns --------- result : (n, d) bool With one or zero True values per row. Examples ------------------------------------- In [0]: r = np.array([[-1, 1, 1], [-1, 1, -1], [-1, 1, 1], [-1, 1, -1], [-1, 1, -1]], dtype=np.int8) In [1]: unique_value_in_row(r) Out[1]: array([[ True, False, False], [False, True, False], [ True, False, False], [False, True, False], [False, True, False]], dtype=bool) In [2]: unique_value_in_row(r).sum(axis=1) Out[2]: array([1, 1, 1, 1, 1]) In [3]: r[unique_value_in_row(r)] Out[3]: array([-1, 1, -1, 1, 1], dtype=int8) """ if unique is None: unique = np.unique(data) data = np.asanyarray(data) result = np.zeros_like(data, dtype=bool, subok=False) for value in unique: test = np.equal(data, value) test_ok = test.sum(axis=1) == 1 result[test_ok] = test[test_ok] return result
[ "def", "unique_value_in_row", "(", "data", ",", "unique", "=", "None", ")", ":", "if", "unique", "is", "None", ":", "unique", "=", "np", ".", "unique", "(", "data", ")", "data", "=", "np", ".", "asanyarray", "(", "data", ")", "result", "=", "np", "...
https://github.com/mikedh/trimesh/blob/6b1e05616b44e6dd708d9bc748b211656ebb27ec/trimesh/grouping.py#L435-L487
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/api/resources/v0_5.py
python
DomainUsernames.obj_get_list
(self, bundle, **kwargs)
return results
[]
def obj_get_list(self, bundle, **kwargs): domain = kwargs['domain'] user_ids_username_pairs = get_all_user_id_username_pairs_by_domain(domain) results = [UserInfo(user_id=user_pair[0], user_name=raw_username(user_pair[1])) for user_pair in user_ids_username_pairs] return results
[ "def", "obj_get_list", "(", "self", ",", "bundle", ",", "*", "*", "kwargs", ")", ":", "domain", "=", "kwargs", "[", "'domain'", "]", "user_ids_username_pairs", "=", "get_all_user_id_username_pairs_by_domain", "(", "domain", ")", "results", "=", "[", "UserInfo", ...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/api/resources/v0_5.py#L898-L903
biocore/scikit-bio
ecdfc7941d8c21eb2559ff1ab313d6e9348781da
skbio/diversity/alpha/_gini.py
python
gini_index
(data, method='rectangles')
return 1 - 2 * B
r"""Calculate the Gini index. The Gini index is defined as .. math:: G=\frac{A}{A+B} where :math:`A` is the area between :math:`y=x` and the Lorenz curve and :math:`B` is the area under the Lorenz curve. Simplifies to :math:`1-2B` since :math:`A+B=0.5`. Parameters ---------- data : 1-D array_like Vector of counts, abundances, proportions, etc. All entries must be non-negative. method : {'rectangles', 'trapezoids'} Method for calculating the area under the Lorenz curve. If ``'rectangles'``, connects the Lorenz curve points by lines parallel to the x axis. This is the correct method (in our opinion) though ``'trapezoids'`` might be desirable in some circumstances. If ``'trapezoids'``, connects the Lorenz curve points by linear segments between them. Basically assumes that the given sampling is accurate and that more features of given data would fall on linear gradients between the values of this data. Returns ------- double Gini index. Raises ------ ValueError If `method` isn't one of the supported methods for calculating the area under the curve. Notes ----- The Gini index was introduced in [1]_. The formula for ``method='rectangles'`` is .. math:: dx\sum_{i=1}^n h_i The formula for ``method='trapezoids'`` is .. math:: dx(\frac{h_0+h_n}{2}+\sum_{i=1}^{n-1} h_i) References ---------- .. [1] Gini, C. (1912). "Variability and Mutability", C. Cuppini, Bologna, 156 pages. Reprinted in Memorie di metodologica statistica (Ed. Pizetti E, Salvemini, T). Rome: Libreria Eredi Virgilio Veschi (1955).
r"""Calculate the Gini index.
[ "r", "Calculate", "the", "Gini", "index", "." ]
def gini_index(data, method='rectangles'): r"""Calculate the Gini index. The Gini index is defined as .. math:: G=\frac{A}{A+B} where :math:`A` is the area between :math:`y=x` and the Lorenz curve and :math:`B` is the area under the Lorenz curve. Simplifies to :math:`1-2B` since :math:`A+B=0.5`. Parameters ---------- data : 1-D array_like Vector of counts, abundances, proportions, etc. All entries must be non-negative. method : {'rectangles', 'trapezoids'} Method for calculating the area under the Lorenz curve. If ``'rectangles'``, connects the Lorenz curve points by lines parallel to the x axis. This is the correct method (in our opinion) though ``'trapezoids'`` might be desirable in some circumstances. If ``'trapezoids'``, connects the Lorenz curve points by linear segments between them. Basically assumes that the given sampling is accurate and that more features of given data would fall on linear gradients between the values of this data. Returns ------- double Gini index. Raises ------ ValueError If `method` isn't one of the supported methods for calculating the area under the curve. Notes ----- The Gini index was introduced in [1]_. The formula for ``method='rectangles'`` is .. math:: dx\sum_{i=1}^n h_i The formula for ``method='trapezoids'`` is .. math:: dx(\frac{h_0+h_n}{2}+\sum_{i=1}^{n-1} h_i) References ---------- .. [1] Gini, C. (1912). "Variability and Mutability", C. Cuppini, Bologna, 156 pages. Reprinted in Memorie di metodologica statistica (Ed. Pizetti E, Salvemini, T). Rome: Libreria Eredi Virgilio Veschi (1955). """ # Suppress cast to int because this method supports ints and floats. data = _validate_counts_vector(data, suppress_cast=True) lorenz_points = _lorenz_curve(data) B = _lorenz_curve_integrator(lorenz_points, method) return 1 - 2 * B
[ "def", "gini_index", "(", "data", ",", "method", "=", "'rectangles'", ")", ":", "# Suppress cast to int because this method supports ints and floats.", "data", "=", "_validate_counts_vector", "(", "data", ",", "suppress_cast", "=", "True", ")", "lorenz_points", "=", "_l...
https://github.com/biocore/scikit-bio/blob/ecdfc7941d8c21eb2559ff1ab313d6e9348781da/skbio/diversity/alpha/_gini.py#L16-L81
Komodo/KomodoEdit
61edab75dce2bdb03943b387b0608ea36f548e8e
contrib/html5lib/html5lib/serializer/htmlserializer.py
python
SerializeError
(Exception)
Error in serialized tree
Error in serialized tree
[ "Error", "in", "serialized", "tree" ]
def SerializeError(Exception): """Error in serialized tree""" pass
[ "def", "SerializeError", "(", "Exception", ")", ":", "pass" ]
https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/contrib/html5lib/html5lib/serializer/htmlserializer.py#L319-L321
enthought/traitsui
b7c38c7a47bf6ae7971f9ddab70c8a358647dd25
traitsui/instance_choice.py
python
InstanceChoice.get_name
(self, object=None)
return user_name_for(self.object.__class__.__name__)
Returns the name of the item.
Returns the name of the item.
[ "Returns", "the", "name", "of", "the", "item", "." ]
def get_name(self, object=None): """Returns the name of the item.""" if self.name != "": return self.name name = getattr(self.object, self.name_trait, None) if isinstance(name, str): return name return user_name_for(self.object.__class__.__name__)
[ "def", "get_name", "(", "self", ",", "object", "=", "None", ")", ":", "if", "self", ".", "name", "!=", "\"\"", ":", "return", "self", ".", "name", "name", "=", "getattr", "(", "self", ".", "object", ",", "self", ".", "name_trait", ",", "None", ")",...
https://github.com/enthought/traitsui/blob/b7c38c7a47bf6ae7971f9ddab70c8a358647dd25/traitsui/instance_choice.py#L86-L95
CarterBain/AlephNull
796edec7e106cd76a5a69cb6e67a1a96c7a22cf6
alephnull/transforms/ta.py
python
make_transform
(talib_fn, name)
return TALibTransform
A factory for BatchTransforms based on TALIB abstract functions.
A factory for BatchTransforms based on TALIB abstract functions.
[ "A", "factory", "for", "BatchTransforms", "based", "on", "TALIB", "abstract", "functions", "." ]
def make_transform(talib_fn, name): """ A factory for BatchTransforms based on TALIB abstract functions. """ # make class docstring header = '\n#---- TA-Lib docs\n\n' talib_docs = getattr(talib, talib_fn.info['name']).__doc__ divider1 = '\n#---- Default mapping (TA-Lib : Zipline)\n\n' mappings = '\n'.join(' {0} : {1}'.format(k, v) for k, v in talib_fn.input_names.items()) divider2 = '\n\n#---- Zipline docs\n' help_str = (header + talib_docs + divider1 + mappings + divider2) class TALibTransform(BatchTransform): __doc__ = help_str + """ TA-Lib keyword arguments must be passed at initialization. For example, to construct a moving average with timeperiod of 5, pass "timeperiod=5" during initialization. All abstract TA-Lib functions accept a data dictionary containing 'open', 'high', 'low', 'close', and 'volume' keys, even if they do not require those keys to run. For example, talib.MA (moving average) is always computed using the data under the 'close' key. By default, Zipline constructs this data dictionary with the appropriate sid data, but users may overwrite this by passing mappings as keyword arguments. For example, to compute the moving average of the sid's high, provide "close = 'high'" and Zipline's 'high' data will be used as TA-Lib's 'close' data. Similarly, if a user had a data column named 'Oil', they could compute its moving average by passing "close='Oil'". **Example** A moving average of a data column called 'Oil' with timeperiod 5, talib.transforms.ta.MA(close='Oil', timeperiod=5) The user could find the default arguments and mappings by calling: help(zipline.transforms.ta.MA) **Arguments** open : string, default 'open' high : string, default 'high' low : string, default 'low' close : string, default 'price' volume : string, default 'volume' refresh_period : int, default 0 The refresh_period of the BatchTransform determines the number of iterations that pass before the BatchTransform updates its internal data. \*\*kwargs : any arguments to be passed to the TA-Lib function. """ def __init__(self, close='price', open='open', high='high', low='low', volume='volume', refresh_period=0, bars='daily', **kwargs): key_map = {'high': high, 'low': low, 'open': open, 'volume': volume, 'close': close} self.call_kwargs = kwargs # Make deepcopy of talib abstract function. # This is necessary because talib abstract functions remember # state, including parameters, and we need to set the parameters # in order to compute the lookback period that will determine the # BatchTransform window_length. TALIB has no way to restore default # parameters, so the deepcopy lets us change this function's # parameters without affecting other TALibTransforms of the same # function. self.talib_fn = copy.deepcopy(talib_fn) # set the parameters for param in self.talib_fn.get_parameters().keys(): if param in kwargs: self.talib_fn.set_parameters({param: kwargs[param]}) # get the lookback self.lookback = self.talib_fn.lookback self.bars = bars if bars == 'daily': lookback = self.lookback + 1 elif bars == 'minute': lookback = int(math.ceil(self.lookback / (6.5 * 60))) # Ensure that window_length is at least 1 day's worth of data. window_length = max(lookback, 1) transform_func = functools.partial( zipline_wrapper, self.talib_fn, key_map) super(TALibTransform, self).__init__( func=transform_func, refresh_period=refresh_period, window_length=window_length, compute_only_full=False, bars=bars) def __repr__(self): return 'Zipline BatchTransform: {0}'.format( self.talib_fn.info['name']) TALibTransform.__name__ = name # return class return TALibTransform
[ "def", "make_transform", "(", "talib_fn", ",", "name", ")", ":", "# make class docstring", "header", "=", "'\\n#---- TA-Lib docs\\n\\n'", "talib_docs", "=", "getattr", "(", "talib", ",", "talib_fn", ".", "info", "[", "'name'", "]", ")", ".", "__doc__", "divider1...
https://github.com/CarterBain/AlephNull/blob/796edec7e106cd76a5a69cb6e67a1a96c7a22cf6/alephnull/transforms/ta.py#L84-L203
fastnlp/fastNLP
fb645d370f4cc1b00c7dbb16c1ff4542327c46e5
fastNLP/io/loader/conll.py
python
CTBLoader.download
(self)
r""" 由于版权限制,不能提供自动下载功能。可参考 https://catalog.ldc.upenn.edu/LDC2013T21 :return:
r""" 由于版权限制,不能提供自动下载功能。可参考
[ "r", "由于版权限制,不能提供自动下载功能。可参考" ]
def download(self): r""" 由于版权限制,不能提供自动下载功能。可参考 https://catalog.ldc.upenn.edu/LDC2013T21 :return: """ raise RuntimeError("CTB cannot be downloaded automatically.")
[ "def", "download", "(", "self", ")", ":", "raise", "RuntimeError", "(", "\"CTB cannot be downloaded automatically.\"", ")" ]
https://github.com/fastnlp/fastNLP/blob/fb645d370f4cc1b00c7dbb16c1ff4542327c46e5/fastNLP/io/loader/conll.py#L332-L340
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/server/grr_response_server/flows/general/administrative.py
python
UpdateClient.Start
(self)
Start.
Start.
[ "Start", "." ]
def Start(self): """Start.""" if not self.args.binary_path: raise flow_base.FlowError("Installer binary path is not specified.") self.state.write_path = "%d_%s" % (int( time.time()), os.path.basename(self.args.binary_path)) self.StartBlobsUpload(self._binary_id, self.Interrogate.__name__)
[ "def", "Start", "(", "self", ")", ":", "if", "not", "self", ".", "args", ".", "binary_path", ":", "raise", "flow_base", ".", "FlowError", "(", "\"Installer binary path is not specified.\"", ")", "self", ".", "state", ".", "write_path", "=", "\"%d_%s\"", "%", ...
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/server/grr_response_server/flows/general/administrative.py#L609-L617
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/mako/parsetree.py
python
Node.accept_visitor
(self, visitor)
[]
def accept_visitor(self, visitor): def traverse(node): for n in node.get_children(): n.accept_visitor(visitor) method = getattr(visitor, "visit" + self.__class__.__name__, traverse) method(self)
[ "def", "accept_visitor", "(", "self", ",", "visitor", ")", ":", "def", "traverse", "(", "node", ")", ":", "for", "n", "in", "node", ".", "get_children", "(", ")", ":", "n", ".", "accept_visitor", "(", "visitor", ")", "method", "=", "getattr", "(", "v...
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/mako/parsetree.py#L29-L35
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/plecost/xgoogle/BeautifulSoup.py
python
BeautifulStoneSoup.handle_decl
(self, data)
Handle DOCTYPEs and the like as Declaration objects.
Handle DOCTYPEs and the like as Declaration objects.
[ "Handle", "DOCTYPEs", "and", "the", "like", "as", "Declaration", "objects", "." ]
def handle_decl(self, data): "Handle DOCTYPEs and the like as Declaration objects." self._toStringSubclass(data, Declaration)
[ "def", "handle_decl", "(", "self", ",", "data", ")", ":", "self", ".", "_toStringSubclass", "(", "data", ",", "Declaration", ")" ]
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/plecost/xgoogle/BeautifulSoup.py#L1372-L1374
windelbouwman/ppci
915c069e0667042c085ec42c78e9e3c9a5295324
ppci/binutils/archive.py
python
get_archive
(filename)
return Archive.load(filename)
Load an archive from file.
Load an archive from file.
[ "Load", "an", "archive", "from", "file", "." ]
def get_archive(filename): """ Load an archive from file. """ if isinstance(filename, Archive): return filename return Archive.load(filename)
[ "def", "get_archive", "(", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "Archive", ")", ":", "return", "filename", "return", "Archive", ".", "load", "(", "filename", ")" ]
https://github.com/windelbouwman/ppci/blob/915c069e0667042c085ec42c78e9e3c9a5295324/ppci/binutils/archive.py#L14-L19
CGATOxford/cgat
326aad4694bdfae8ddc194171bb5d73911243947
CGAT/Genomics.py
python
CalculateCAIWeightsFromCounts
(counts, pseudo_counts=0)
return weights
calculate CAI weights from codon counts. pseudo_counts are added if desired.
calculate CAI weights from codon counts. pseudo_counts are added if desired.
[ "calculate", "CAI", "weights", "from", "codon", "counts", ".", "pseudo_counts", "are", "added", "if", "desired", "." ]
def CalculateCAIWeightsFromCounts(counts, pseudo_counts=0): """calculate CAI weights from codon counts. pseudo_counts are added if desired. """ map_aa2codons = GetMapAA2Codons() weights = {} for aa, codons in list(map_aa2codons.items()): max_counts = max(counts[x] for x in codons) + pseudo_counts for x in codons: weights[x] = float(counts[x] + pseudo_counts) / float(max_counts) for codon in StopCodons: weights[codon] = 0.0 return weights
[ "def", "CalculateCAIWeightsFromCounts", "(", "counts", ",", "pseudo_counts", "=", "0", ")", ":", "map_aa2codons", "=", "GetMapAA2Codons", "(", ")", "weights", "=", "{", "}", "for", "aa", ",", "codons", "in", "list", "(", "map_aa2codons", ".", "items", "(", ...
https://github.com/CGATOxford/cgat/blob/326aad4694bdfae8ddc194171bb5d73911243947/CGAT/Genomics.py#L1668-L1685
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/scipy/spatial/kdtree.py
python
minkowski_distance_p
(x, y, p=2)
Compute the p-th power of the L**p distance between two arrays. For efficiency, this function computes the L**p distance but does not extract the pth root. If `p` is 1 or infinity, this is equal to the actual L**p distance. Parameters ---------- x : (M, K) array_like Input array. y : (N, K) array_like Input array. p : float, 1 <= p <= infinity Which Minkowski p-norm to use. Examples -------- >>> from scipy.spatial import minkowski_distance_p >>> minkowski_distance_p([[0,0],[0,0]], [[1,1],[0,1]]) array([2, 1])
Compute the p-th power of the L**p distance between two arrays.
[ "Compute", "the", "p", "-", "th", "power", "of", "the", "L", "**", "p", "distance", "between", "two", "arrays", "." ]
def minkowski_distance_p(x, y, p=2): """ Compute the p-th power of the L**p distance between two arrays. For efficiency, this function computes the L**p distance but does not extract the pth root. If `p` is 1 or infinity, this is equal to the actual L**p distance. Parameters ---------- x : (M, K) array_like Input array. y : (N, K) array_like Input array. p : float, 1 <= p <= infinity Which Minkowski p-norm to use. Examples -------- >>> from scipy.spatial import minkowski_distance_p >>> minkowski_distance_p([[0,0],[0,0]], [[1,1],[0,1]]) array([2, 1]) """ x = np.asarray(x) y = np.asarray(y) if p == np.inf: return np.amax(np.abs(y-x), axis=-1) elif p == 1: return np.sum(np.abs(y-x), axis=-1) else: return np.sum(np.abs(y-x)**p, axis=-1)
[ "def", "minkowski_distance_p", "(", "x", ",", "y", ",", "p", "=", "2", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "y", "=", "np", ".", "asarray", "(", "y", ")", "if", "p", "==", "np", ".", "inf", ":", "return", "np", ".", "ama...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/scipy/spatial/kdtree.py#L15-L46
zh-plus/video-to-pose3D
c1e14af8d184f08d510826852da5a06c57d4a4ec
joints_detectors/hrnet/lib/nms/nms.py
python
nms
(dets, thresh)
return keep
greedily select boxes with high confidence and overlap with current maximum <= thresh rule out overlap >= thresh :param dets: [[x1, y1, x2, y2 score]] :param thresh: retain overlap < thresh :return: indexes to keep
greedily select boxes with high confidence and overlap with current maximum <= thresh rule out overlap >= thresh :param dets: [[x1, y1, x2, y2 score]] :param thresh: retain overlap < thresh :return: indexes to keep
[ "greedily", "select", "boxes", "with", "high", "confidence", "and", "overlap", "with", "current", "maximum", "<", "=", "thresh", "rule", "out", "overlap", ">", "=", "thresh", ":", "param", "dets", ":", "[[", "x1", "y1", "x2", "y2", "score", "]]", ":", ...
def nms(dets, thresh): """ greedily select boxes with high confidence and overlap with current maximum <= thresh rule out overlap >= thresh :param dets: [[x1, y1, x2, y2 score]] :param thresh: retain overlap < thresh :return: indexes to keep """ if dets.shape[0] == 0: return [] x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = scores.argsort()[::-1] keep = [] while order.size > 0: i = order[0] keep.append(i) xx1 = np.maximum(x1[i], x1[order[1:]]) yy1 = np.maximum(y1[i], y1[order[1:]]) xx2 = np.minimum(x2[i], x2[order[1:]]) yy2 = np.minimum(y2[i], y2[order[1:]]) w = np.maximum(0.0, xx2 - xx1 + 1) h = np.maximum(0.0, yy2 - yy1 + 1) inter = w * h ovr = inter / (areas[i] + areas[order[1:]] - inter) inds = np.where(ovr <= thresh)[0] order = order[inds + 1] return keep
[ "def", "nms", "(", "dets", ",", "thresh", ")", ":", "if", "dets", ".", "shape", "[", "0", "]", "==", "0", ":", "return", "[", "]", "x1", "=", "dets", "[", ":", ",", "0", "]", "y1", "=", "dets", "[", ":", ",", "1", "]", "x2", "=", "dets", ...
https://github.com/zh-plus/video-to-pose3D/blob/c1e14af8d184f08d510826852da5a06c57d4a4ec/joints_detectors/hrnet/lib/nms/nms.py#L38-L75
los-cocos/cocos
3b47281f95d6ee52bb2a357a767f213e670bd601
tools/uniform_snippet.py
python
get_endplus_line
(iter_enumerated_lines)
return last_no_blank + 1
Advances the iterator until a nonblank line with zero indentation is found. Returns the line number of the last non whitespace line with indentation greater than zero.
Advances the iterator until a nonblank line with zero indentation is found. Returns the line number of the last non whitespace line with indentation greater than zero.
[ "Advances", "the", "iterator", "until", "a", "nonblank", "line", "with", "zero", "indentation", "is", "found", ".", "Returns", "the", "line", "number", "of", "the", "last", "non", "whitespace", "line", "with", "indentation", "greater", "than", "zero", "." ]
def get_endplus_line(iter_enumerated_lines): """ Advances the iterator until a nonblank line with zero indentation is found. Returns the line number of the last non whitespace line with indentation greater than zero. """ # seek end of object code as the next line with zero indentation # will broke with comments at 0 indent amidst the object code # class / func definition should be in lines[start_line : endplus_line] # trailing whitespace lines are not included last_no_blank = None while 1: try: lineno, line = six.next(iter_enumerated_lines) except StopIteration: # EOF break if len(line)>0 and not line[0].isspace(): # a line with indentation zero, the object code should # have ended at most one line above if last_no_blank is None: last_no_blank = lineno-1 break if len(line)>0 and not line.isspace(): last_no_blank = lineno return last_no_blank + 1
[ "def", "get_endplus_line", "(", "iter_enumerated_lines", ")", ":", "# seek end of object code as the next line with zero indentation", "# will broke with comments at 0 indent amidst the object code", "# class / func definition should be in lines[start_line : endplus_line]", "# trailing whitespace ...
https://github.com/los-cocos/cocos/blob/3b47281f95d6ee52bb2a357a767f213e670bd601/tools/uniform_snippet.py#L173-L198
dmlc/gluon-cv
709bc139919c02f7454cb411311048be188cde64
gluoncv/torch/data/transforms/instance_transforms/transform.py
python
Transform.apply_polygons
(self, polygons: list)
return [self.apply_coords(p) for p in polygons]
Apply the transform on a list of polygons, each represented by a Nx2 array. By default will just transform all the points. Args: polygon (list[ndarray]): each is a Nx2 floating point array of (x, y) format in absolute coordinates. Returns: list[ndarray]: polygon after apply the transformation. Note: The coordinates are not pixel indices. Coordinates on an image of shape (H, W) are in range [0, W] or [0, H].
Apply the transform on a list of polygons, each represented by a Nx2 array. By default will just transform all the points.
[ "Apply", "the", "transform", "on", "a", "list", "of", "polygons", "each", "represented", "by", "a", "Nx2", "array", ".", "By", "default", "will", "just", "transform", "all", "the", "points", "." ]
def apply_polygons(self, polygons: list) -> list: """ Apply the transform on a list of polygons, each represented by a Nx2 array. By default will just transform all the points. Args: polygon (list[ndarray]): each is a Nx2 floating point array of (x, y) format in absolute coordinates. Returns: list[ndarray]: polygon after apply the transformation. Note: The coordinates are not pixel indices. Coordinates on an image of shape (H, W) are in range [0, W] or [0, H]. """ return [self.apply_coords(p) for p in polygons]
[ "def", "apply_polygons", "(", "self", ",", "polygons", ":", "list", ")", "->", "list", ":", "return", "[", "self", ".", "apply_coords", "(", "p", ")", "for", "p", "in", "polygons", "]" ]
https://github.com/dmlc/gluon-cv/blob/709bc139919c02f7454cb411311048be188cde64/gluoncv/torch/data/transforms/instance_transforms/transform.py#L147-L162
goace/personal-file-sharing-center
4a5b903b003f2db1306e77c5e51b6660fc5dbc6a
web/template.py
python
Parser.__init__
(self)
[]
def __init__(self): self.statement_nodes = STATEMENT_NODES self.keywords = KEYWORDS
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "statement_nodes", "=", "STATEMENT_NODES", "self", ".", "keywords", "=", "KEYWORDS" ]
https://github.com/goace/personal-file-sharing-center/blob/4a5b903b003f2db1306e77c5e51b6660fc5dbc6a/web/template.py#L70-L72
ninja-ide/ninja-ide
87d91131bd19fdc3dcfd91eb97ad1e41c49c60c0
ninja_ide/core/template_registry/ntemplate_registry.py
python
BaseProjectType.from_dict
(cls, results)
Create an instance from this project type using the wizard result
Create an instance from this project type using the wizard result
[ "Create", "an", "instance", "from", "this", "project", "type", "using", "the", "wizard", "result" ]
def from_dict(cls, results): """Create an instance from this project type using the wizard result""" raise NotImplementedError("%s lacks from_dict" % cls.__name__)
[ "def", "from_dict", "(", "cls", ",", "results", ")", ":", "raise", "NotImplementedError", "(", "\"%s lacks from_dict\"", "%", "cls", ".", "__name__", ")" ]
https://github.com/ninja-ide/ninja-ide/blob/87d91131bd19fdc3dcfd91eb97ad1e41c49c60c0/ninja_ide/core/template_registry/ntemplate_registry.py#L140-L143
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/utils/network.py
python
_netbsd_remotes_on
(port, which_end)
return remotes
Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506
Returns set of ipv4 host addresses of remote established connections on local tcp port port.
[ "Returns", "set", "of", "ipv4", "host", "addresses", "of", "remote", "established", "connections", "on", "local", "tcp", "port", "port", "." ]
def _netbsd_remotes_on(port, which_end): """ Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1456 29 tcp *.4505 *.* root python2.7 1445 17 tcp *.4506 *.* root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505 root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 $ sudo sockstat -4 -c -n -p 4506 USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506 """ port = int(port) remotes = set() try: cmd = salt.utils.args.shlex_split("sockstat -4 -c -n -p {}".format(port)) data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version except subprocess.CalledProcessError as ex: log.error('Failed "sockstat" with returncode = %s', ex.returncode) raise lines = salt.utils.stringutils.to_str(data).split("\n") for line in lines: chunks = line.split() if not chunks: continue # ['root', 'python2.7', '1456', '37', 'tcp', # '127.0.0.1.4505-', '127.0.0.1.55703'] # print chunks if "COMMAND" in chunks[1]: continue # ignore header if len(chunks) < 2: continue local = chunks[5].split(".") lport = local.pop() lhost = ".".join(local) remote = chunks[6].split(".") rport = remote.pop() rhost = ".".join(remote) if which_end == "local" and int(lport) != port: # ignore if local port not port continue if ( which_end == "remote" and int(rport) != port ): # ignore if remote port not port continue remotes.add(rhost) return remotes
[ "def", "_netbsd_remotes_on", "(", "port", ",", "which_end", ")", ":", "port", "=", "int", "(", "port", ")", "remotes", "=", "set", "(", ")", "try", ":", "cmd", "=", "salt", ".", "utils", ".", "args", ".", "shlex_split", "(", "\"sockstat -4 -c -n -p {}\""...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/utils/network.py#L1833-L1891
OpenMDAO/OpenMDAO-Framework
f2e37b7de3edeaaeb2d251b375917adec059db9b
openmdao.lib/src/openmdao/lib/components/metamodel.py
python
MetaModel._default_surrogate_changed
(self, old_obj, new_obj)
Callback whenever the default_surrogate model is changed.
Callback whenever the default_surrogate model is changed.
[ "Callback", "whenever", "the", "default_surrogate", "model", "is", "changed", "." ]
def _default_surrogate_changed(self, old_obj, new_obj): """Callback whenever the default_surrogate model is changed.""" if old_obj: old_obj.on_trait_change(self._def_surrogate_trait_modified, remove=True) if new_obj: new_obj.on_trait_change(self._def_surrogate_trait_modified) # due to the way "add" works, container will always remove the # old before it adds the new one. So you actually get this method # called twice on a replace. You only do this update when the new # one gets set for name in self._surrogate_output_names: if name not in self._surrogate_overrides: surrogate = deepcopy(self.default_surrogate) self._default_surrogate_copies[name] = surrogate self._update_var_for_surrogate(surrogate, name) self.config_changed() self._train = True
[ "def", "_default_surrogate_changed", "(", "self", ",", "old_obj", ",", "new_obj", ")", ":", "if", "old_obj", ":", "old_obj", ".", "on_trait_change", "(", "self", ".", "_def_surrogate_trait_modified", ",", "remove", "=", "True", ")", "if", "new_obj", ":", "new_...
https://github.com/OpenMDAO/OpenMDAO-Framework/blob/f2e37b7de3edeaaeb2d251b375917adec059db9b/openmdao.lib/src/openmdao/lib/components/metamodel.py#L198-L219
pm4py/pm4py-core
7807b09a088b02199cd0149d724d0e28793971bf
pm4py/algo/simulation/playout/petri_net/variants/stochastic_playout.py
python
apply
(net: PetriNet, initial_marking: Marking, final_marking: Marking = None, parameters: Optional[Dict[Union[str, Parameters], Any]] = None)
return apply_playout(net, initial_marking, max_trace_length=max_trace_length, no_traces=no_traces, case_id_key=case_id_key, activity_key=activity_key, timestamp_key=timestamp_key, final_marking=final_marking, smap=smap, log=log, return_visited_elements=return_visited_elements, semantics=semantics, parameters=None)
Do the playout of a Petrinet generating a log Parameters ----------- net Petri net to play-out initial_marking Initial marking of the Petri net final_marking If provided, the final marking of the Petri net parameters Parameters of the algorithm: Parameters.NO_TRACES -> Number of traces of the log to generate Parameters.MAX_TRACE_LENGTH -> Maximum trace length Parameters.PETRI_SEMANTICS -> Petri net semantics to be used (default: petri_nets.semantics.ClassicSemantics())
Do the playout of a Petrinet generating a log
[ "Do", "the", "playout", "of", "a", "Petrinet", "generating", "a", "log" ]
def apply(net: PetriNet, initial_marking: Marking, final_marking: Marking = None, parameters: Optional[Dict[Union[str, Parameters], Any]] = None) -> EventLog: """ Do the playout of a Petrinet generating a log Parameters ----------- net Petri net to play-out initial_marking Initial marking of the Petri net final_marking If provided, the final marking of the Petri net parameters Parameters of the algorithm: Parameters.NO_TRACES -> Number of traces of the log to generate Parameters.MAX_TRACE_LENGTH -> Maximum trace length Parameters.PETRI_SEMANTICS -> Petri net semantics to be used (default: petri_nets.semantics.ClassicSemantics()) """ if parameters is None: parameters = {} case_id_key = exec_utils.get_param_value(Parameters.CASE_ID_KEY, parameters, xes_constants.DEFAULT_TRACEID_KEY) activity_key = exec_utils.get_param_value(Parameters.ACTIVITY_KEY, parameters, xes_constants.DEFAULT_NAME_KEY) timestamp_key = exec_utils.get_param_value(Parameters.TIMESTAMP_KEY, parameters, xes_constants.DEFAULT_TIMESTAMP_KEY) no_traces = exec_utils.get_param_value(Parameters.NO_TRACES, parameters, 1000) max_trace_length = exec_utils.get_param_value(Parameters.MAX_TRACE_LENGTH, parameters, 1000) smap = exec_utils.get_param_value(Parameters.STOCHASTIC_MAP, parameters, None) log = exec_utils.get_param_value(Parameters.LOG, parameters, None) return_visited_elements = exec_utils.get_param_value(Parameters.RETURN_VISITED_ELEMENTS, parameters, False) semantics = exec_utils.get_param_value(Parameters.PETRI_SEMANTICS, parameters, petri_net.semantics.ClassicSemantics()) return apply_playout(net, initial_marking, max_trace_length=max_trace_length, no_traces=no_traces, case_id_key=case_id_key, activity_key=activity_key, timestamp_key=timestamp_key, final_marking=final_marking, smap=smap, log=log, return_visited_elements=return_visited_elements, semantics=semantics, parameters=None)
[ "def", "apply", "(", "net", ":", "PetriNet", ",", "initial_marking", ":", "Marking", ",", "final_marking", ":", "Marking", "=", "None", ",", "parameters", ":", "Optional", "[", "Dict", "[", "Union", "[", "str", ",", "Parameters", "]", ",", "Any", "]", ...
https://github.com/pm4py/pm4py-core/blob/7807b09a088b02199cd0149d724d0e28793971bf/pm4py/algo/simulation/playout/petri_net/variants/stochastic_playout.py#L147-L183
Robot-Will/Stino
a94831cd1bf40a59587a7b6cc2e9b5c4306b1bf2
StinoCommands.py
python
StinoBuildCommand.is_enabled
(self)
return state
.
.
[ "." ]
def is_enabled(self): """.""" state = False if stino.arduino_info['init_done']: build_enabled = stino.arduino_info['settings'].get('build_enabled') if build_enabled: file_path = self.view.file_name() if file_path: if stino.c_file.is_cpp_file(file_path): get_info = stino.selected.get_sel_board_info info = get_info(stino.arduino_info) if info: state = True return state
[ "def", "is_enabled", "(", "self", ")", ":", "state", "=", "False", "if", "stino", ".", "arduino_info", "[", "'init_done'", "]", ":", "build_enabled", "=", "stino", ".", "arduino_info", "[", "'settings'", "]", ".", "get", "(", "'build_enabled'", ")", "if", ...
https://github.com/Robot-Will/Stino/blob/a94831cd1bf40a59587a7b6cc2e9b5c4306b1bf2/StinoCommands.py#L637-L650
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/pyparsing/core.py
python
StringEnd.__init__
(self)
[]
def __init__(self): super().__init__() self.errmsg = "Expected end of text"
[ "def", "__init__", "(", "self", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "errmsg", "=", "\"Expected end of text\"" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/pyparsing/core.py#L3499-L3501
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/rachio/switch.py
python
RachioZone.__str__
(self)
return f'Rachio Zone "{self.name}" on {str(self._controller)}'
Display the zone as a string.
Display the zone as a string.
[ "Display", "the", "zone", "as", "a", "string", "." ]
def __str__(self): """Display the zone as a string.""" return f'Rachio Zone "{self.name}" on {str(self._controller)}'
[ "def", "__str__", "(", "self", ")", ":", "return", "f'Rachio Zone \"{self.name}\" on {str(self._controller)}'" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/rachio/switch.py#L363-L365
sqlmapproject/sqlmap
3b07b70864624dff4c29dcaa8a61c78e7f9189f7
thirdparty/clientform/clientform.py
python
HTMLForm.click_request_data
(self, name=None, type=None, id=None, nr=0, coord=(1,1), request_class=_urllib.request.Request, label=None)
return self._click(name, type, id, label, nr, coord, "request_data", self._request_class)
As for click method, but return a tuple (url, data, headers). You can use this data to send a request to the server. This is useful if you're using httplib or urllib rather than urllib2. Otherwise, use the click method. # Untested. Have to subclass to add headers, I think -- so use urllib2 # instead! import urllib url, data, hdrs = form.click_request_data() r = _urllib.request.urlopen(url, data) # Untested. I don't know of any reason to use httplib -- you can get # just as much control with urllib2. import httplib, urlparse url, data, hdrs = form.click_request_data() tup = urlparse(url) host, path = tup[1], _urllib.parse.urlunparse((None, None)+tup[2:]) conn = httplib.HTTPConnection(host) if data: httplib.request("POST", path, data, hdrs) else: httplib.request("GET", path, headers=hdrs) r = conn.getresponse()
As for click method, but return a tuple (url, data, headers).
[ "As", "for", "click", "method", "but", "return", "a", "tuple", "(", "url", "data", "headers", ")", "." ]
def click_request_data(self, name=None, type=None, id=None, nr=0, coord=(1,1), request_class=_urllib.request.Request, label=None): """As for click method, but return a tuple (url, data, headers). You can use this data to send a request to the server. This is useful if you're using httplib or urllib rather than urllib2. Otherwise, use the click method. # Untested. Have to subclass to add headers, I think -- so use urllib2 # instead! import urllib url, data, hdrs = form.click_request_data() r = _urllib.request.urlopen(url, data) # Untested. I don't know of any reason to use httplib -- you can get # just as much control with urllib2. import httplib, urlparse url, data, hdrs = form.click_request_data() tup = urlparse(url) host, path = tup[1], _urllib.parse.urlunparse((None, None)+tup[2:]) conn = httplib.HTTPConnection(host) if data: httplib.request("POST", path, data, hdrs) else: httplib.request("GET", path, headers=hdrs) r = conn.getresponse() """ return self._click(name, type, id, label, nr, coord, "request_data", self._request_class)
[ "def", "click_request_data", "(", "self", ",", "name", "=", "None", ",", "type", "=", "None", ",", "id", "=", "None", ",", "nr", "=", "0", ",", "coord", "=", "(", "1", ",", "1", ")", ",", "request_class", "=", "_urllib", ".", "request", ".", "Req...
https://github.com/sqlmapproject/sqlmap/blob/3b07b70864624dff4c29dcaa8a61c78e7f9189f7/thirdparty/clientform/clientform.py#L3129-L3161
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/vendor/pythonfinder/_vendor/pep514tools/_registry.py
python
PythonWrappedDict._attr_to_key
(attr)
return ''.join(c.capitalize() for c in attr.split('_'))
[]
def _attr_to_key(attr): if not attr: return '' if not _VALID_ATTR.match(attr): return attr return ''.join(c.capitalize() for c in attr.split('_'))
[ "def", "_attr_to_key", "(", "attr", ")", ":", "if", "not", "attr", ":", "return", "''", "if", "not", "_VALID_ATTR", ".", "match", "(", "attr", ")", ":", "return", "attr", "return", "''", ".", "join", "(", "c", ".", "capitalize", "(", ")", "for", "c...
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/pythonfinder/_vendor/pep514tools/_registry.py#L43-L48
MycroftAI/mycroft-core
3d963cee402e232174850f36918313e87313fb13
mycroft/skills/common_play_skill.py
python
CommonPlaySkill.__calc_confidence
(self, match, phrase, level)
Translate confidence level and match to a 0-1 value. "play pandora" "play pandora is my girlfriend" "play tom waits on pandora" Assume the more of the words that get consumed, the better the match Args: match (str): Matching string phrase (str): original input phrase level (CPSMatchLevel): match level
Translate confidence level and match to a 0-1 value.
[ "Translate", "confidence", "level", "and", "match", "to", "a", "0", "-", "1", "value", "." ]
def __calc_confidence(self, match, phrase, level): """Translate confidence level and match to a 0-1 value. "play pandora" "play pandora is my girlfriend" "play tom waits on pandora" Assume the more of the words that get consumed, the better the match Args: match (str): Matching string phrase (str): original input phrase level (CPSMatchLevel): match level """ consumed_pct = len(match.split()) / len(phrase.split()) if consumed_pct > 1.0: consumed_pct = 1.0 / consumed_pct # deal with over/under-matching # We'll use this to modify the level, but don't want it to allow a # match to jump to the next match level. So bonus is 0 - 0.05 (1/20) bonus = consumed_pct / 20.0 if level == CPSMatchLevel.EXACT: return 1.0 elif level == CPSMatchLevel.MULTI_KEY: return 0.9 + bonus elif level == CPSMatchLevel.TITLE: return 0.8 + bonus elif level == CPSMatchLevel.ARTIST: return 0.7 + bonus elif level == CPSMatchLevel.CATEGORY: return 0.6 + bonus elif level == CPSMatchLevel.GENERIC: return 0.5 + bonus else: return 0.0
[ "def", "__calc_confidence", "(", "self", ",", "match", ",", "phrase", ",", "level", ")", ":", "consumed_pct", "=", "len", "(", "match", ".", "split", "(", ")", ")", "/", "len", "(", "phrase", ".", "split", "(", ")", ")", "if", "consumed_pct", ">", ...
https://github.com/MycroftAI/mycroft-core/blob/3d963cee402e232174850f36918313e87313fb13/mycroft/skills/common_play_skill.py#L115-L150
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py
python
WorkingSet.subscribe
(self, callback, existing=True)
Invoke `callback` for all distributions If `existing=True` (default), call on all existing ones, as well.
Invoke `callback` for all distributions
[ "Invoke", "callback", "for", "all", "distributions" ]
def subscribe(self, callback, existing=True): """Invoke `callback` for all distributions If `existing=True` (default), call on all existing ones, as well. """ if callback in self.callbacks: return self.callbacks.append(callback) if not existing: return for dist in self: callback(dist)
[ "def", "subscribe", "(", "self", ",", "callback", ",", "existing", "=", "True", ")", ":", "if", "callback", "in", "self", ".", "callbacks", ":", "return", "self", ".", "callbacks", ".", "append", "(", "callback", ")", "if", "not", "existing", ":", "ret...
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L907-L919
hzlzh/AlfredWorkflow.com
7055f14f6922c80ea5943839eb0caff11ae57255
Sources/Workflows/Toggl-Time-Tracking/alp/request/requests/models.py
python
Response.raise_for_status
(self, allow_redirects=True)
Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred.
Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred.
[ "Raises", "stored", ":", "class", ":", "HTTPError", "or", ":", "class", ":", "URLError", "if", "one", "occurred", "." ]
def raise_for_status(self, allow_redirects=True): """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred.""" if self.error: raise self.error http_error_msg = '' if 300 <= self.status_code < 400 and not allow_redirects: http_error_msg = '%s Redirection: %s' % (self.status_code, self.reason) elif 400 <= self.status_code < 500: http_error_msg = '%s Client Error: %s' % (self.status_code, self.reason) elif 500 <= self.status_code < 600: http_error_msg = '%s Server Error: %s' % (self.status_code, self.reason) if http_error_msg: http_error = HTTPError(http_error_msg) http_error.response = self raise http_error
[ "def", "raise_for_status", "(", "self", ",", "allow_redirects", "=", "True", ")", ":", "if", "self", ".", "error", ":", "raise", "self", ".", "error", "http_error_msg", "=", "''", "if", "300", "<=", "self", ".", "status_code", "<", "400", "and", "not", ...
https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/Toggl-Time-Tracking/alp/request/requests/models.py#L888-L907
PaddlePaddle/models
511e2e282960ed4c7440c3f1d1e62017acb90e11
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/transforms.py
python
Grayscale.__init__
(self, num_output_channels=1)
[]
def __init__(self, num_output_channels=1): super().__init__() self.num_output_channels = num_output_channels
[ "def", "__init__", "(", "self", ",", "num_output_channels", "=", "1", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "num_output_channels", "=", "num_output_channels" ]
https://github.com/PaddlePaddle/models/blob/511e2e282960ed4c7440c3f1d1e62017acb90e11/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/transforms.py#L1602-L1604
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/lib-tk/Tkinter.py
python
Image.configure
(self, **kw)
Configure the image.
Configure the image.
[ "Configure", "the", "image", "." ]
def configure(self, **kw): """Configure the image.""" res = () for k, v in _cnfmerge(kw).items(): if v is not None: if k[-1] == '_': k = k[:-1] if hasattr(v, '__call__'): v = self._register(v) res = res + ('-'+k, v) self.tk.call((self.name, 'config') + res)
[ "def", "configure", "(", "self", ",", "*", "*", "kw", ")", ":", "res", "=", "(", ")", "for", "k", ",", "v", "in", "_cnfmerge", "(", "kw", ")", ".", "items", "(", ")", ":", "if", "v", "is", "not", "None", ":", "if", "k", "[", "-", "1", "]"...
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/lib-tk/Tkinter.py#L3214-L3223
volatilityfoundation/volatility3
168b0d0b053ab97a7cb096ef2048795cc54d885f
volatility3/framework/plugins/windows/driverscan.py
python
DriverScan.scan_drivers
(cls, context: interfaces.context.ContextInterface, layer_name: str, symbol_table: str)
Scans for drivers using the poolscanner module and constraints. Args: context: The context to retrieve required elements (layers, symbol tables) from layer_name: The name of the layer on which to operate symbol_table: The name of the table containing the kernel symbols Returns: A list of Driver objects as found from the `layer_name` layer based on Driver pool signatures
Scans for drivers using the poolscanner module and constraints.
[ "Scans", "for", "drivers", "using", "the", "poolscanner", "module", "and", "constraints", "." ]
def scan_drivers(cls, context: interfaces.context.ContextInterface, layer_name: str, symbol_table: str) -> \ Iterable[interfaces.objects.ObjectInterface]: """Scans for drivers using the poolscanner module and constraints. Args: context: The context to retrieve required elements (layers, symbol tables) from layer_name: The name of the layer on which to operate symbol_table: The name of the table containing the kernel symbols Returns: A list of Driver objects as found from the `layer_name` layer based on Driver pool signatures """ constraints = poolscanner.PoolScanner.builtin_constraints(symbol_table, [b'Dri\xf6', b'Driv']) for result in poolscanner.PoolScanner.generate_pool_scan(context, layer_name, symbol_table, constraints): _constraint, mem_object, _header = result yield mem_object
[ "def", "scan_drivers", "(", "cls", ",", "context", ":", "interfaces", ".", "context", ".", "ContextInterface", ",", "layer_name", ":", "str", ",", "symbol_table", ":", "str", ")", "->", "Iterable", "[", "interfaces", ".", "objects", ".", "ObjectInterface", "...
https://github.com/volatilityfoundation/volatility3/blob/168b0d0b053ab97a7cb096ef2048795cc54d885f/volatility3/framework/plugins/windows/driverscan.py#L28-L49
yahoo/TensorFlowOnSpark
c2790b797b57acc540414c94909f4f6ec7e3895c
examples/segmentation/segmentation.py
python
normalize
(input_image, input_mask)
return input_image, input_mask
[]
def normalize(input_image, input_mask): input_image = tf.cast(input_image, tf.float32)/128.0 - 1 input_mask -= 1 return input_image, input_mask
[ "def", "normalize", "(", "input_image", ",", "input_mask", ")", ":", "input_image", "=", "tf", ".", "cast", "(", "input_image", ",", "tf", ".", "float32", ")", "/", "128.0", "-", "1", "input_mask", "-=", "1", "return", "input_image", ",", "input_mask" ]
https://github.com/yahoo/TensorFlowOnSpark/blob/c2790b797b57acc540414c94909f4f6ec7e3895c/examples/segmentation/segmentation.py#L25-L28
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/s3/s3gis.py
python
MAP.__init__
(self, **opts)
:param **opts: options to pass to the Map for server-side processing
:param **opts: options to pass to the Map for server-side processing
[ ":", "param", "**", "opts", ":", "options", "to", "pass", "to", "the", "Map", "for", "server", "-", "side", "processing" ]
def __init__(self, **opts): """ :param **opts: options to pass to the Map for server-side processing """ # We haven't yet run _setup() self.setup = False self.callback = None self.error_message = None self.components = [] # Options for server-side processing self.opts = opts opts_get = opts.get self.id = map_id = opts_get("id", "default_map") # Options for client-side processing self.options = {} # Adapt CSS to size of Map _class = "map_wrapper" if opts_get("window"): _class = "%s fullscreen" % _class if opts_get("print_mode"): _class = "%s print" % _class self.attributes = {"_class": _class, "_id": map_id, } self.parent = None # Show Color Picker? if opts_get("color_picker"): # Can't be done in _setup() as usually run from xml() and hence we've already passed this part of the layout.html s3 = current.response.s3 if s3.debug: style = "plugins/spectrum.css" else: style = "plugins/spectrum.min.css" if style not in s3.stylesheets: s3.stylesheets.append(style)
[ "def", "__init__", "(", "self", ",", "*", "*", "opts", ")", ":", "# We haven't yet run _setup()", "self", ".", "setup", "=", "False", "self", ".", "callback", "=", "None", "self", ".", "error_message", "=", "None", "self", ".", "components", "=", "[", "]...
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3/s3gis.py#L6614-L6653
leancloud/satori
701caccbd4fe45765001ca60435c0cb499477c03
satori-rules/plugin/libs/urllib3/packages/rfc3986/api.py
python
urlparse
(uri, encoding='utf-8')
return ParseResult.from_string(uri, encoding, strict=False)
Parse a given URI and return a ParseResult. This is a partial replacement of the standard library's urlparse function. :param str uri: The URI to be parsed. :param str encoding: The encoding of the string provided. :returns: A parsed URI :rtype: :class:`~rfc3986.parseresult.ParseResult`
Parse a given URI and return a ParseResult.
[ "Parse", "a", "given", "URI", "and", "return", "a", "ParseResult", "." ]
def urlparse(uri, encoding='utf-8'): """Parse a given URI and return a ParseResult. This is a partial replacement of the standard library's urlparse function. :param str uri: The URI to be parsed. :param str encoding: The encoding of the string provided. :returns: A parsed URI :rtype: :class:`~rfc3986.parseresult.ParseResult` """ return ParseResult.from_string(uri, encoding, strict=False)
[ "def", "urlparse", "(", "uri", ",", "encoding", "=", "'utf-8'", ")", ":", "return", "ParseResult", ".", "from_string", "(", "uri", ",", "encoding", ",", "strict", "=", "False", ")" ]
https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/urllib3/packages/rfc3986/api.py#L96-L106
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/site-packages/pkg_resources/__init__.py
python
Distribution.load_entry_point
(self, group, name)
return ep.load()
Return the `name` entry point of `group` or raise ImportError
Return the `name` entry point of `group` or raise ImportError
[ "Return", "the", "name", "entry", "point", "of", "group", "or", "raise", "ImportError" ]
def load_entry_point(self, group, name): """Return the `name` entry point of `group` or raise ImportError""" ep = self.get_entry_info(group, name) if ep is None: raise ImportError("Entry point %r not found" % ((group, name),)) return ep.load()
[ "def", "load_entry_point", "(", "self", ",", "group", ",", "name", ")", ":", "ep", "=", "self", ".", "get_entry_info", "(", "group", ",", "name", ")", "if", "ep", "is", "None", ":", "raise", "ImportError", "(", "\"Entry point %r not found\"", "%", "(", "...
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/site-packages/pkg_resources/__init__.py#L2847-L2852
taizilongxu/douban.fm
d65126d3bd3e12d8a7109137caff8da0efc22b2f
doubanfm/views/base_view.py
python
Cli.display
(self)
显示输出信息
显示输出信息
[ "显示输出信息" ]
def display(self): """ 显示输出信息 """ pass
[ "def", "display", "(", "self", ")", ":", "pass" ]
https://github.com/taizilongxu/douban.fm/blob/d65126d3bd3e12d8a7109137caff8da0efc22b2f/doubanfm/views/base_view.py#L127-L131
spesmilo/electrum
bdbd59300fbd35b01605e66145458e5f396108e8
electrum/slip39.py
python
process_mnemonics
(mnemonics: List[str])
return None, status
[]
def process_mnemonics(mnemonics: List[str]) -> Tuple[bool, str]: # Collect valid shares. shares = [] for i, mnemonic in enumerate(mnemonics): try: share = decode_mnemonic(mnemonic) share.index = i + 1 shares.append(share) except Slip39Error: pass if not shares: return None, _('No valid shares.') # Sort shares into groups. groups: Dict[int, Set[Share]] = defaultdict(set) # group idx : shares common_params = shares[0].common_parameters() for share in shares: if share.common_parameters() != common_params: error_text = _("Share") + ' #%d ' % share.index + _("is not part of the current set.") return None, _ERROR_STYLE % error_text for other in groups[share.group_index]: if share.member_index == other.member_index: error_text = _("Share") + ' #%d ' % share.index + _("is a duplicate of share") + ' #%d.' % other.index return None, _ERROR_STYLE % error_text groups[share.group_index].add(share) # Compile information about groups. groups_completed = 0 for i, group in groups.items(): if group: member_threshold = next(iter(group)).member_threshold if len(group) >= member_threshold: groups_completed += 1 identifier = shares[0].identifier iteration_exponent = shares[0].iteration_exponent group_threshold = shares[0].group_threshold group_count = shares[0].group_count status = '' if group_count > 1: status += _('Completed') + ' <b>%d</b> ' % groups_completed + _('of') + ' <b>%d</b> ' % group_threshold + _('groups needed:<br/>') for group_index in range(group_count): group_prefix = _make_group_prefix(identifier, iteration_exponent, group_index, group_threshold, group_count) status += _group_status(groups[group_index], group_prefix) if groups_completed >= group_threshold: if len(mnemonics) > len(shares): status += _ERROR_STYLE % _('Some shares are invalid.') else: try: encrypted_seed = recover_ems(mnemonics) status += '<b>' + _('The set is complete!') + '</b>' except Slip39Error as e: encrypted_seed = None status = _ERROR_STYLE % str(e) return encrypted_seed, status return None, status
[ "def", "process_mnemonics", "(", "mnemonics", ":", "List", "[", "str", "]", ")", "->", "Tuple", "[", "bool", ",", "str", "]", ":", "# Collect valid shares.", "shares", "=", "[", "]", "for", "i", ",", "mnemonic", "in", "enumerate", "(", "mnemonics", ")", ...
https://github.com/spesmilo/electrum/blob/bdbd59300fbd35b01605e66145458e5f396108e8/electrum/slip39.py#L281-L340
datitran/object_detector_app
44e8eddeb931cced5d8cf1e283383c720a5706bf
object_detection/anchor_generators/multiple_grid_anchor_generator.py
python
MultipleGridAnchorGenerator.name_scope
(self)
return 'MultipleGridAnchorGenerator'
[]
def name_scope(self): return 'MultipleGridAnchorGenerator'
[ "def", "name_scope", "(", "self", ")", ":", "return", "'MultipleGridAnchorGenerator'" ]
https://github.com/datitran/object_detector_app/blob/44e8eddeb931cced5d8cf1e283383c720a5706bf/object_detection/anchor_generators/multiple_grid_anchor_generator.py#L93-L94
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/functions/elementary/miscellaneous.py
python
root
(arg, n)
return C.Pow(arg, 1/n)
The n-th root function (a shortcut for ``arg**(1/n)``) root(x, n) -> Returns the principal n-th root of x. Examples ======== >>> from sympy import root, Rational >>> from sympy.abc import x, n >>> root(x, 2) sqrt(x) >>> root(x, 3) x**(1/3) >>> root(x, n) x**(1/n) >>> root(x, -Rational(2, 3)) x**(-3/2) To get all n n-th roots you can use the RootOf function. The following examples show the roots of unity for n equal 2, 3 and 4: >>> from sympy import RootOf, I >>> [ RootOf(x**2-1,i) for i in (0,1) ] [-1, 1] >>> [ RootOf(x**3-1,i) for i in (0,1,2) ] [1, -1/2 - sqrt(3)*I/2, -1/2 + sqrt(3)*I/2] >>> [ RootOf(x**4-1,i) for i in (0,1,2,3) ] [-1, 1, -I, I] SymPy, like other symbolic algebra systems, returns the complex root of negative numbers. This is the principal root and differs from the text-book result that one might be expecting. For example, the cube root of -8 does not come back as -2: >>> root(-8, 3) 2*(-1)**(1/3) The real_root function can be used to either make such a result real or simply return the real root in the first place: >>> from sympy import real_root >>> real_root(_) -2 >>> real_root(-32, 5) -2 See Also ======== sympy.polys.rootoftools.RootOf sympy.core.power.integer_nthroot sqrt, real_root References ========== * http://en.wikipedia.org/wiki/Square_root * http://en.wikipedia.org/wiki/real_root * http://en.wikipedia.org/wiki/Root_of_unity * http://en.wikipedia.org/wiki/Principal_value * http://mathworld.wolfram.com/CubeRoot.html
The n-th root function (a shortcut for ``arg**(1/n)``)
[ "The", "n", "-", "th", "root", "function", "(", "a", "shortcut", "for", "arg", "**", "(", "1", "/", "n", ")", ")" ]
def root(arg, n): """The n-th root function (a shortcut for ``arg**(1/n)``) root(x, n) -> Returns the principal n-th root of x. Examples ======== >>> from sympy import root, Rational >>> from sympy.abc import x, n >>> root(x, 2) sqrt(x) >>> root(x, 3) x**(1/3) >>> root(x, n) x**(1/n) >>> root(x, -Rational(2, 3)) x**(-3/2) To get all n n-th roots you can use the RootOf function. The following examples show the roots of unity for n equal 2, 3 and 4: >>> from sympy import RootOf, I >>> [ RootOf(x**2-1,i) for i in (0,1) ] [-1, 1] >>> [ RootOf(x**3-1,i) for i in (0,1,2) ] [1, -1/2 - sqrt(3)*I/2, -1/2 + sqrt(3)*I/2] >>> [ RootOf(x**4-1,i) for i in (0,1,2,3) ] [-1, 1, -I, I] SymPy, like other symbolic algebra systems, returns the complex root of negative numbers. This is the principal root and differs from the text-book result that one might be expecting. For example, the cube root of -8 does not come back as -2: >>> root(-8, 3) 2*(-1)**(1/3) The real_root function can be used to either make such a result real or simply return the real root in the first place: >>> from sympy import real_root >>> real_root(_) -2 >>> real_root(-32, 5) -2 See Also ======== sympy.polys.rootoftools.RootOf sympy.core.power.integer_nthroot sqrt, real_root References ========== * http://en.wikipedia.org/wiki/Square_root * http://en.wikipedia.org/wiki/real_root * http://en.wikipedia.org/wiki/Root_of_unity * http://en.wikipedia.org/wiki/Principal_value * http://mathworld.wolfram.com/CubeRoot.html """ n = sympify(n) return C.Pow(arg, 1/n)
[ "def", "root", "(", "arg", ",", "n", ")", ":", "n", "=", "sympify", "(", "n", ")", "return", "C", ".", "Pow", "(", "arg", ",", "1", "/", "n", ")" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/functions/elementary/miscellaneous.py#L164-L240
autotest/autotest
4614ae5f550cc888267b9a419e4b90deb54f8fae
client/tools/boottool.py
python
OptionParser.opts_has_action
(self, opts)
return has_action
Checks if (parsed) opts has a first class action
Checks if (parsed) opts has a first class action
[ "Checks", "if", "(", "parsed", ")", "opts", "has", "a", "first", "class", "action" ]
def opts_has_action(self, opts): ''' Checks if (parsed) opts has a first class action ''' global ACTIONS_OPT_METHOD_NAME has_action = False for action in ACTIONS_OPT_METHOD_NAME: value = getattr(opts, action) if value is not None: has_action = True return has_action
[ "def", "opts_has_action", "(", "self", ",", "opts", ")", ":", "global", "ACTIONS_OPT_METHOD_NAME", "has_action", "=", "False", "for", "action", "in", "ACTIONS_OPT_METHOD_NAME", ":", "value", "=", "getattr", "(", "opts", ",", "action", ")", "if", "value", "is",...
https://github.com/autotest/autotest/blob/4614ae5f550cc888267b9a419e4b90deb54f8fae/client/tools/boottool.py#L1907-L1917
fabric-bolt/fabric-bolt
0f434783026f1b9ce16a416fa496d76921fe49ca
fabric_bolt/core/mixins/tables.py
python
PaginateTable.paginate
(self, klass=Paginator, per_page=None, page=1, *args, **kwargs)
Paginates the table using a paginator and creates a ``page`` property containing information for the current page. :type klass: Paginator class :param klass: a paginator class to paginate the results :type per_page: `int` :param per_page: how many records are displayed on each page :type page: `int` :param page: which page should be displayed. Extra arguments are passed to the paginator. Pagination exceptions (`~django.core.paginator.EmptyPage` and `~django.core.paginator.PageNotAnInteger`) may be raised from this method and should be handled by the caller.
Paginates the table using a paginator and creates a ``page`` property containing information for the current page.
[ "Paginates", "the", "table", "using", "a", "paginator", "and", "creates", "a", "page", "property", "containing", "information", "for", "the", "current", "page", "." ]
def paginate(self, klass=Paginator, per_page=None, page=1, *args, **kwargs): """ Paginates the table using a paginator and creates a ``page`` property containing information for the current page. :type klass: Paginator class :param klass: a paginator class to paginate the results :type per_page: `int` :param per_page: how many records are displayed on each page :type page: `int` :param page: which page should be displayed. Extra arguments are passed to the paginator. Pagination exceptions (`~django.core.paginator.EmptyPage` and `~django.core.paginator.PageNotAnInteger`) may be raised from this method and should be handled by the caller. """ self.per_page_options = [25, 50, 100, 200] # This should probably be a passed in option self.per_page = per_page = per_page or self._meta.per_page self.paginator = klass(self.rows, per_page, *args, **kwargs) self.page = self.paginator.page(page) # Calc variables for use in displaying first, adjacent, and last page links adjacent_pages = 1 # This should probably be a passed in option # Starting page (first page between the ellipsis) start_page = max(self.page.number - adjacent_pages, 1) if start_page <= 3: start_page = 1 # Ending page (last page between the ellipsis) end_page = self.page.number + adjacent_pages + 1 if end_page >= self.paginator.num_pages - 1: end_page = self.paginator.num_pages + 1 # Paging vars used in template self.page_numbers = [n for n in range(start_page, end_page) if 0 < n <= self.paginator.num_pages] self.show_first = 1 not in self.page_numbers self.show_last = self.paginator.num_pages not in self.page_numbers
[ "def", "paginate", "(", "self", ",", "klass", "=", "Paginator", ",", "per_page", "=", "None", ",", "page", "=", "1", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "per_page_options", "=", "[", "25", ",", "50", ",", "100", ",",...
https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/core/mixins/tables.py#L79-L121
odlgroup/odl
0b088df8dc4621c68b9414c3deff9127f4c4f11d
odl/solvers/functional/default_functionals.py
python
IndicatorSimplex._call
(self, x)
Return ``self(x)``.
Return ``self(x)``.
[ "Return", "self", "(", "x", ")", "." ]
def _call(self, x): """Return ``self(x)``.""" sum_constr = abs(x.ufuncs.sum() / self.diameter - 1) <= self.sum_rtol nonneq_constr = x.ufuncs.greater_equal(0).asarray().all() if sum_constr and nonneq_constr: return 0 else: return np.inf
[ "def", "_call", "(", "self", ",", "x", ")", ":", "sum_constr", "=", "abs", "(", "x", ".", "ufuncs", ".", "sum", "(", ")", "/", "self", ".", "diameter", "-", "1", ")", "<=", "self", ".", "sum_rtol", "nonneq_constr", "=", "x", ".", "ufuncs", ".", ...
https://github.com/odlgroup/odl/blob/0b088df8dc4621c68b9414c3deff9127f4c4f11d/odl/solvers/functional/default_functionals.py#L2279-L2289
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idc.py
python
SelStart
()
Get start address of the selected area returns BADADDR - the user has not selected an area
Get start address of the selected area returns BADADDR - the user has not selected an area
[ "Get", "start", "address", "of", "the", "selected", "area", "returns", "BADADDR", "-", "the", "user", "has", "not", "selected", "an", "area" ]
def SelStart(): """ Get start address of the selected area returns BADADDR - the user has not selected an area """ selection, startaddr, endaddr = idaapi.read_selection() if selection == 1: return startaddr else: return BADADDR
[ "def", "SelStart", "(", ")", ":", "selection", ",", "startaddr", ",", "endaddr", "=", "idaapi", ".", "read_selection", "(", ")", "if", "selection", "==", "1", ":", "return", "startaddr", "else", ":", "return", "BADADDR" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idc.py#L1970-L1980
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
mapr/datadog_checks/mapr/config_models/defaults.py
python
instance_disable_legacy_cluster_tag
(field, value)
return False
[]
def instance_disable_legacy_cluster_tag(field, value): return False
[ "def", "instance_disable_legacy_cluster_tag", "(", "field", ",", "value", ")", ":", "return", "False" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/mapr/datadog_checks/mapr/config_models/defaults.py#L21-L22
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/set/src/core/scapy.py
python
IPField.i2m
(self, pkt, x)
return inet_aton(x)
[]
def i2m(self, pkt, x): return inet_aton(x)
[ "def", "i2m", "(", "self", ",", "pkt", ",", "x", ")", ":", "return", "inet_aton", "(", "x", ")" ]
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/set/src/core/scapy.py#L3639-L3640
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-04-research-and-development/preprocessors_bonus.py
python
MeanImputer.transform
(self, X)
return X
[]
def transform(self, X): X = X.copy() for feature in self.variables: X[feature].fillna(self.imputer_dict_[feature], inplace=True) return X
[ "def", "transform", "(", "self", ",", "X", ")", ":", "X", "=", "X", ".", "copy", "(", ")", "for", "feature", "in", "self", ".", "variables", ":", "X", "[", "feature", "]", ".", "fillna", "(", "self", ".", "imputer_dict_", "[", "feature", "]", ","...
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-04-research-and-development/preprocessors_bonus.py#L19-L24
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/sqlalchemy/sql/type_api.py
python
TypeDecorator.__init__
(self, *args, **kwargs)
Construct a :class:`.TypeDecorator`. Arguments sent here are passed to the constructor of the class assigned to the ``impl`` class level attribute, assuming the ``impl`` is a callable, and the resulting object is assigned to the ``self.impl`` instance attribute (thus overriding the class attribute of the same name). If the class level ``impl`` is not a callable (the unusual case), it will be assigned to the same instance attribute 'as-is', ignoring those arguments passed to the constructor. Subclasses can override this to customize the generation of ``self.impl`` entirely.
Construct a :class:`.TypeDecorator`.
[ "Construct", "a", ":", "class", ":", ".", "TypeDecorator", "." ]
def __init__(self, *args, **kwargs): """Construct a :class:`.TypeDecorator`. Arguments sent here are passed to the constructor of the class assigned to the ``impl`` class level attribute, assuming the ``impl`` is a callable, and the resulting object is assigned to the ``self.impl`` instance attribute (thus overriding the class attribute of the same name). If the class level ``impl`` is not a callable (the unusual case), it will be assigned to the same instance attribute 'as-is', ignoring those arguments passed to the constructor. Subclasses can override this to customize the generation of ``self.impl`` entirely. """ if not hasattr(self.__class__, 'impl'): raise AssertionError("TypeDecorator implementations " "require a class-level variable " "'impl' which refers to the class of " "type being decorated") self.impl = to_instance(self.__class__.impl, *args, **kwargs)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "hasattr", "(", "self", ".", "__class__", ",", "'impl'", ")", ":", "raise", "AssertionError", "(", "\"TypeDecorator implementations \"", "\"require a class-level ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/sql/type_api.py#L845-L868
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/asw/v20200722/models.py
python
StopExecutionRequest.__init__
(self)
r""" :param ExecutionQrn: 执行名称 :type ExecutionQrn: str
r""" :param ExecutionQrn: 执行名称 :type ExecutionQrn: str
[ "r", ":", "param", "ExecutionQrn", ":", "执行名称", ":", "type", "ExecutionQrn", ":", "str" ]
def __init__(self): r""" :param ExecutionQrn: 执行名称 :type ExecutionQrn: str """ self.ExecutionQrn = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "ExecutionQrn", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/asw/v20200722/models.py#L741-L746
joxeankoret/diaphora
dcb5a25ac9fe23a285b657e5389cf770de7ac928
pygments/filters/__init__.py
python
NameHighlightFilter.__init__
(self, **options)
[]
def __init__(self, **options): Filter.__init__(self, **options) self.names = set(get_list_opt(options, 'names', [])) tokentype = options.get('tokentype') if tokentype: self.tokentype = string_to_tokentype(tokentype) else: self.tokentype = Name.Function
[ "def", "__init__", "(", "self", ",", "*", "*", "options", ")", ":", "Filter", ".", "__init__", "(", "self", ",", "*", "*", "options", ")", "self", ".", "names", "=", "set", "(", "get_list_opt", "(", "options", ",", "'names'", ",", "[", "]", ")", ...
https://github.com/joxeankoret/diaphora/blob/dcb5a25ac9fe23a285b657e5389cf770de7ac928/pygments/filters/__init__.py#L150-L157
geekori/pyqt5
49b2538fa5afe43b3b2bdadaa0560d0d6ef4924c
src/windows/WindowPattern.py
python
WindowPattern.__init__
(self)
[]
def __init__(self): super().__init__() self.resize(500,260) self.setWindowTitle('设置窗口的样式') self.setWindowFlags(Qt.WindowMaximizeButtonHint | Qt.WindowStaysOnTopHint ) self.setObjectName("MainWindow") self.setStyleSheet("#MainWindow{border-image:url(images/python.jpg);}")
[ "def", "__init__", "(", "self", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "resize", "(", "500", ",", "260", ")", "self", ".", "setWindowTitle", "(", "'设置窗口的样式')", "", "self", ".", "setWindowFlags", "(", "Qt", ".", "WindowMa...
https://github.com/geekori/pyqt5/blob/49b2538fa5afe43b3b2bdadaa0560d0d6ef4924c/src/windows/WindowPattern.py#L12-L19
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/sanitizer.py
python
Filter.allowed_token
(self, token)
return token
[]
def allowed_token(self, token): if "data" in token: attrs = token["data"] attr_names = set(attrs.keys()) # Remove forbidden attributes for to_remove in (attr_names - self.allowed_attributes): del token["data"][to_remove] attr_names.remove(to_remove) # Remove attributes with disallowed URL values for attr in (attr_names & self.attr_val_is_uri): assert attr in attrs # I don't have a clue where this regexp comes from or why it matches those # characters, nor why we call unescape. I just know it's always been here. # Should you be worried by this comment in a sanitizer? Yes. On the other hand, all # this will do is remove *more* than it otherwise would. val_unescaped = re.sub("[`\x00-\x20\x7f-\xa0\\s]+", '', unescape(attrs[attr])).lower() # remove replacement characters from unescaped characters val_unescaped = val_unescaped.replace("\ufffd", "") try: uri = urlparse.urlparse(val_unescaped) except ValueError: uri = None del attrs[attr] if uri and uri.scheme: if uri.scheme not in self.allowed_protocols: del attrs[attr] if uri.scheme == 'data': m = data_content_type.match(uri.path) if not m: del attrs[attr] elif m.group('content_type') not in self.allowed_content_types: del attrs[attr] for attr in self.svg_attr_val_allows_ref: if attr in attrs: attrs[attr] = re.sub(r'url\s*\(\s*[^#\s][^)]+?\)', ' ', unescape(attrs[attr])) if (token["name"] in self.svg_allow_local_href and (namespaces['xlink'], 'href') in attrs and re.search(r'^\s*[^#\s].*', attrs[(namespaces['xlink'], 'href')])): del attrs[(namespaces['xlink'], 'href')] if (None, 'style') in attrs: attrs[(None, 'style')] = self.sanitize_css(attrs[(None, 'style')]) token["data"] = attrs return token
[ "def", "allowed_token", "(", "self", ",", "token", ")", ":", "if", "\"data\"", "in", "token", ":", "attrs", "=", "token", "[", "\"data\"", "]", "attr_names", "=", "set", "(", "attrs", ".", "keys", "(", ")", ")", "# Remove forbidden attributes", "for", "t...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/sanitizer.py#L799-L847
OpenNMT/OpenNMT-tf
59a4dfdb911d0570ba1096b7a0a7b9fc5c7844bf
opennmt/decoders/decoder.py
python
Decoder._get_state_reorder_flags
(self)
return None
Returns a structure that marks states that should be reordered during beam search. By default all states are reordered. Returns: The same structure as the decoder state with tensors replaced by booleans.
Returns a structure that marks states that should be reordered during beam search. By default all states are reordered.
[ "Returns", "a", "structure", "that", "marks", "states", "that", "should", "be", "reordered", "during", "beam", "search", ".", "By", "default", "all", "states", "are", "reordered", "." ]
def _get_state_reorder_flags(self): """Returns a structure that marks states that should be reordered during beam search. By default all states are reordered. Returns: The same structure as the decoder state with tensors replaced by booleans. """ return None
[ "def", "_get_state_reorder_flags", "(", "self", ")", ":", "return", "None" ]
https://github.com/OpenNMT/OpenNMT-tf/blob/59a4dfdb911d0570ba1096b7a0a7b9fc5c7844bf/opennmt/decoders/decoder.py#L470-L477
BlueBrain/BluePyOpt
6d4185479bc6dddb3daad84fa27e0b8457d69652
bluepyopt/ephys/parameters.py
python
MetaParameter.__str__
(self)
return '%s: %s.%s = %s' % (self.name, self.obj.name, self.attr_name, self.value)
String representation
String representation
[ "String", "representation" ]
def __str__(self): """String representation""" return '%s: %s.%s = %s' % (self.name, self.obj.name, self.attr_name, self.value)
[ "def", "__str__", "(", "self", ")", ":", "return", "'%s: %s.%s = %s'", "%", "(", "self", ".", "name", ",", "self", ".", "obj", ".", "name", ",", "self", ".", "attr_name", ",", "self", ".", "value", ")" ]
https://github.com/BlueBrain/BluePyOpt/blob/6d4185479bc6dddb3daad84fa27e0b8457d69652/bluepyopt/ephys/parameters.py#L93-L98
facebookresearch/higher
15a247ac06cac0d22601322677daff0dcfff062e
higher/patch.py
python
_patched_parameters
( self, recurse: bool = True, time: _typing.Optional[int] = None )
return iter(self._fast_params[time])
r"""Returns an iterator over monkey patched module fast parameters. Args: recurse (bool): if True, then yields fast parameters of this module and all submodules. Otherwise, this *still* yields parameters of this module and all submodules, and raises a warning. This keyword exists only to satisfy API compatibility with ``torch.nn.Module.parameters``. time (int or None): if None, the most recent fast parameters are provided. The int provided stands for the number of steps since the module was created. *Note* that the step counter is incremented every time parameters are updated, so this may not align with number of training or evaluations steps. Yields: Parameter: module fast weights.
r"""Returns an iterator over monkey patched module fast parameters.
[ "r", "Returns", "an", "iterator", "over", "monkey", "patched", "module", "fast", "parameters", "." ]
def _patched_parameters( self, recurse: bool = True, time: _typing.Optional[int] = None ) -> _typing.Iterable[_torch.Tensor]: r"""Returns an iterator over monkey patched module fast parameters. Args: recurse (bool): if True, then yields fast parameters of this module and all submodules. Otherwise, this *still* yields parameters of this module and all submodules, and raises a warning. This keyword exists only to satisfy API compatibility with ``torch.nn.Module.parameters``. time (int or None): if None, the most recent fast parameters are provided. The int provided stands for the number of steps since the module was created. *Note* that the step counter is incremented every time parameters are updated, so this may not align with number of training or evaluations steps. Yields: Parameter: module fast weights. """ if getattr(self, "_fast_params", None) is None: raise Exception( "Tried to get fast weights of a monkey patched module which does " "not encapsulate fast weights." ) if not recurse: _warnings.warn( "Calling parameters with recurse=False on a monkey patched module " "still returns all the fast weights of of nested patched modules." ) time = -1 if time is None else time if not self.track_higher_grads and time not in (-1, 0): raise ValueError( "The patched model is not tracking higher gradients. Only the " "latest parameters are available." ) return iter(self._fast_params[time])
[ "def", "_patched_parameters", "(", "self", ",", "recurse", ":", "bool", "=", "True", ",", "time", ":", "_typing", ".", "Optional", "[", "int", "]", "=", "None", ")", "->", "_typing", ".", "Iterable", "[", "_torch", ".", "Tensor", "]", ":", "if", "get...
https://github.com/facebookresearch/higher/blob/15a247ac06cac0d22601322677daff0dcfff062e/higher/patch.py#L48-L88
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
lib-python/2.7/rfc822.py
python
Message.__init__
(self, fp, seekable = 1)
Initialize the class instance and read the headers.
Initialize the class instance and read the headers.
[ "Initialize", "the", "class", "instance", "and", "read", "the", "headers", "." ]
def __init__(self, fp, seekable = 1): """Initialize the class instance and read the headers.""" if seekable == 1: # Exercise tell() to make sure it works # (and then assume seek() works, too) try: fp.tell() except (AttributeError, IOError): seekable = 0 self.fp = fp self.seekable = seekable self.startofheaders = None self.startofbody = None # if self.seekable: try: self.startofheaders = self.fp.tell() except IOError: self.seekable = 0 # self.readheaders() # if self.seekable: try: self.startofbody = self.fp.tell() except IOError: self.seekable = 0
[ "def", "__init__", "(", "self", ",", "fp", ",", "seekable", "=", "1", ")", ":", "if", "seekable", "==", "1", ":", "# Exercise tell() to make sure it works", "# (and then assume seek() works, too)", "try", ":", "fp", ".", "tell", "(", ")", "except", "(", "Attri...
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/lib-python/2.7/rfc822.py#L88-L114
gabrieleangeletti/Deep-Learning-TensorFlow
ddeb1f2848da7b7bee166ad2152b4afc46bb2086
yadlt/models/convolutional/conv_net.py
python
ConvolutionalNetwork._create_layers
(self, n_classes)
Create the layers of the model from self.layers. :param n_classes: number of classes :return: self
Create the layers of the model from self.layers.
[ "Create", "the", "layers", "of", "the", "model", "from", "self", ".", "layers", "." ]
def _create_layers(self, n_classes): """Create the layers of the model from self.layers. :param n_classes: number of classes :return: self """ next_layer_feed = tf.reshape(self.input_data, [-1, self.original_shape[0], self.original_shape[1], self.original_shape[2]]) prev_output_dim = self.original_shape[2] # this flags indicates whether we are building the first dense layer first_full = True self.W_vars = [] self.B_vars = [] for i, l in enumerate(self.layers.split(',')): node = l.split('-') node_type = node[0] if node_type == 'conv2d': # ################### # # Convolutional Layer # # ################### # # fx, fy = shape of the convolutional filter # feature_maps = number of output dimensions fx, fy, feature_maps, stride = int(node[1]),\ int(node[2]), int(node[3]), int(node[4]) print('Building Convolutional layer with %d input channels\ and %d %dx%d filters with stride %d' % (prev_output_dim, feature_maps, fx, fy, stride)) # Create weights and biases W_conv = self.weight_variable( [fx, fy, prev_output_dim, feature_maps]) b_conv = self.bias_variable([feature_maps]) self.W_vars.append(W_conv) self.B_vars.append(b_conv) # Convolution and Activation function h_conv = tf.nn.relu( self.conv2d(next_layer_feed, W_conv, stride) + b_conv) # keep track of the number of output dims of the previous layer prev_output_dim = feature_maps # output node of the last layer next_layer_feed = h_conv elif node_type == 'maxpool': # ################# # # Max Pooling Layer # # ################# # ksize = int(node[1]) print('Building Max Pooling layer with size %d' % ksize) next_layer_feed = self.max_pool(next_layer_feed, ksize) elif node_type == 'full': # ####################### # # Densely Connected Layer # # ####################### # if first_full: # first fully connected layer dim = int(node[1]) shp = next_layer_feed.get_shape() tmpx = shp[1].value tmpy = shp[2].value fanin = tmpx * tmpy * prev_output_dim print('Building fully connected layer with %d in units\ and %d out units' % (fanin, dim)) W_fc = self.weight_variable([fanin, dim]) b_fc = self.bias_variable([dim]) self.W_vars.append(W_fc) self.B_vars.append(b_fc) h_pool_flat = tf.reshape(next_layer_feed, [-1, fanin]) h_fc = tf.nn.relu(tf.add( tf.matmul(h_pool_flat, W_fc), b_fc)) h_fc_drop = tf.nn.dropout(h_fc, self.keep_prob) prev_output_dim = dim next_layer_feed = h_fc_drop first_full = False else: # not first fully connected layer dim = int(node[1]) W_fc = self.weight_variable([prev_output_dim, dim]) b_fc = self.bias_variable([dim]) self.W_vars.append(W_fc) self.B_vars.append(b_fc) h_fc = tf.nn.relu(tf.add( tf.matmul(next_layer_feed, W_fc), b_fc)) h_fc_drop = tf.nn.dropout(h_fc, self.keep_prob) prev_output_dim = dim next_layer_feed = h_fc_drop elif node_type == 'softmax': # ############# # # Softmax Layer # # ############# # print('Building softmax layer with %d in units and\ %d out units' % (prev_output_dim, n_classes)) W_sm = self.weight_variable([prev_output_dim, n_classes]) b_sm = self.bias_variable([n_classes]) self.W_vars.append(W_sm) self.B_vars.append(b_sm) self.mod_y = tf.add(tf.matmul(next_layer_feed, W_sm), b_sm)
[ "def", "_create_layers", "(", "self", ",", "n_classes", ")", ":", "next_layer_feed", "=", "tf", ".", "reshape", "(", "self", ".", "input_data", ",", "[", "-", "1", ",", "self", ".", "original_shape", "[", "0", "]", ",", "self", ".", "original_shape", "...
https://github.com/gabrieleangeletti/Deep-Learning-TensorFlow/blob/ddeb1f2848da7b7bee166ad2152b4afc46bb2086/yadlt/models/convolutional/conv_net.py#L131-L258
inkandswitch/livebook
93c8d467734787366ad084fc3566bf5cbe249c51
public/pypyjs/modules/numpy/ma/core.py
python
array
(data, dtype=None, copy=False, order=False, mask=nomask, fill_value=None, keep_mask=True, hard_mask=False, shrink=True, subok=True, ndmin=0, )
return MaskedArray(data, mask=mask, dtype=dtype, copy=copy, subok=subok, keep_mask=keep_mask, hard_mask=hard_mask, fill_value=fill_value, ndmin=ndmin, shrink=shrink)
Shortcut to MaskedArray. The options are in a different order for convenience and backwards compatibility.
Shortcut to MaskedArray.
[ "Shortcut", "to", "MaskedArray", "." ]
def array(data, dtype=None, copy=False, order=False, mask=nomask, fill_value=None, keep_mask=True, hard_mask=False, shrink=True, subok=True, ndmin=0, ): """ Shortcut to MaskedArray. The options are in a different order for convenience and backwards compatibility. """ # we should try to put 'order' somewhere return MaskedArray(data, mask=mask, dtype=dtype, copy=copy, subok=subok, keep_mask=keep_mask, hard_mask=hard_mask, fill_value=fill_value, ndmin=ndmin, shrink=shrink)
[ "def", "array", "(", "data", ",", "dtype", "=", "None", ",", "copy", "=", "False", ",", "order", "=", "False", ",", "mask", "=", "nomask", ",", "fill_value", "=", "None", ",", "keep_mask", "=", "True", ",", "hard_mask", "=", "False", ",", "shrink", ...
https://github.com/inkandswitch/livebook/blob/93c8d467734787366ad084fc3566bf5cbe249c51/public/pypyjs/modules/numpy/ma/core.py#L6045-L6059
nate-parrott/Flashlight
c3a7c7278a1cccf8918e7543faffc68e863ff5ab
flashlightplugins/bs4/element.py
python
Tag.__call__
(self, *args, **kwargs)
return self.find_all(*args, **kwargs)
Calling a tag like a function is the same as calling its find_all() method. Eg. tag('a') returns a list of all the A tags found within this tag.
Calling a tag like a function is the same as calling its find_all() method. Eg. tag('a') returns a list of all the A tags found within this tag.
[ "Calling", "a", "tag", "like", "a", "function", "is", "the", "same", "as", "calling", "its", "find_all", "()", "method", ".", "Eg", ".", "tag", "(", "a", ")", "returns", "a", "list", "of", "all", "the", "A", "tags", "found", "within", "this", "tag", ...
def __call__(self, *args, **kwargs): """Calling a tag like a function is the same as calling its find_all() method. Eg. tag('a') returns a list of all the A tags found within this tag.""" return self.find_all(*args, **kwargs)
[ "def", "__call__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "find_all", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/nate-parrott/Flashlight/blob/c3a7c7278a1cccf8918e7543faffc68e863ff5ab/flashlightplugins/bs4/element.py#L905-L909
playframework/play1
0ecac3bc2421ae2dbec27a368bf671eda1c9cba5
python/Lib/logging/__init__.py
python
addLevelName
(level, levelName)
Associate 'levelName' with 'level'. This is used when converting levels to text during message formatting.
Associate 'levelName' with 'level'.
[ "Associate", "levelName", "with", "level", "." ]
def addLevelName(level, levelName): """ Associate 'levelName' with 'level'. This is used when converting levels to text during message formatting. """ _acquireLock() try: #unlikely to cause an exception, but you never know... _levelNames[level] = levelName _levelNames[levelName] = level finally: _releaseLock()
[ "def", "addLevelName", "(", "level", ",", "levelName", ")", ":", "_acquireLock", "(", ")", "try", ":", "#unlikely to cause an exception, but you never know...", "_levelNames", "[", "level", "]", "=", "levelName", "_levelNames", "[", "levelName", "]", "=", "level", ...
https://github.com/playframework/play1/blob/0ecac3bc2421ae2dbec27a368bf671eda1c9cba5/python/Lib/logging/__init__.py#L164-L175
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_downward_api_volume_file.py
python
V1DownwardAPIVolumeFile.resource_field_ref
(self)
return self._resource_field_ref
Gets the resource_field_ref of this V1DownwardAPIVolumeFile. # noqa: E501 :return: The resource_field_ref of this V1DownwardAPIVolumeFile. # noqa: E501 :rtype: V1ResourceFieldSelector
Gets the resource_field_ref of this V1DownwardAPIVolumeFile. # noqa: E501
[ "Gets", "the", "resource_field_ref", "of", "this", "V1DownwardAPIVolumeFile", ".", "#", "noqa", ":", "E501" ]
def resource_field_ref(self): """Gets the resource_field_ref of this V1DownwardAPIVolumeFile. # noqa: E501 :return: The resource_field_ref of this V1DownwardAPIVolumeFile. # noqa: E501 :rtype: V1ResourceFieldSelector """ return self._resource_field_ref
[ "def", "resource_field_ref", "(", "self", ")", ":", "return", "self", ".", "_resource_field_ref" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_downward_api_volume_file.py#L139-L146
cgre-aachen/gempy
6ad16c46fc6616c9f452fba85d31ce32decd8b10
gempy/utils/geogrid.py
python
GeoGrid.adjust_gridshape
(self)
Reshape numpy array to reflect model dimensions
Reshape numpy array to reflect model dimensions
[ "Reshape", "numpy", "array", "to", "reflect", "model", "dimensions" ]
def adjust_gridshape(self): """Reshape numpy array to reflect model dimensions""" self.grid = np.reshape(self.grid, (self.nz, self.ny, self.nx)) self.grid = np.swapaxes(self.grid, 0, 2)
[ "def", "adjust_gridshape", "(", "self", ")", ":", "self", ".", "grid", "=", "np", ".", "reshape", "(", "self", ".", "grid", ",", "(", "self", ".", "nz", ",", "self", ".", "ny", ",", "self", ".", "nx", ")", ")", "self", ".", "grid", "=", "np", ...
https://github.com/cgre-aachen/gempy/blob/6ad16c46fc6616c9f452fba85d31ce32decd8b10/gempy/utils/geogrid.py#L218-L221
kamalgill/flask-appengine-template
11760f83faccbb0d0afe416fc58e67ecfb4643c2
src/lib/flask_wtf/file.py
python
FileField.has_file
(self)
return bool(self.data)
Return ``True`` if ``self.data`` is a :class:`~werkzeug.datastructures.FileStorage` object. .. deprecated:: 0.14.1 ``data`` is no longer set if the input is not a non-empty ``FileStorage``. Check ``form.data is not None`` instead.
Return ``True`` if ``self.data`` is a :class:`~werkzeug.datastructures.FileStorage` object.
[ "Return", "True", "if", "self", ".", "data", "is", "a", ":", "class", ":", "~werkzeug", ".", "datastructures", ".", "FileStorage", "object", "." ]
def has_file(self): """Return ``True`` if ``self.data`` is a :class:`~werkzeug.datastructures.FileStorage` object. .. deprecated:: 0.14.1 ``data`` is no longer set if the input is not a non-empty ``FileStorage``. Check ``form.data is not None`` instead. """ warnings.warn(FlaskWTFDeprecationWarning( '"has_file" is deprecated and will be removed in 1.0. The data is ' 'checked during processing instead.' )) return bool(self.data)
[ "def", "has_file", "(", "self", ")", ":", "warnings", ".", "warn", "(", "FlaskWTFDeprecationWarning", "(", "'\"has_file\" is deprecated and will be removed in 1.0. The data is '", "'checked during processing instead.'", ")", ")", "return", "bool", "(", "self", ".", "data", ...
https://github.com/kamalgill/flask-appengine-template/blob/11760f83faccbb0d0afe416fc58e67ecfb4643c2/src/lib/flask_wtf/file.py#L23-L36
researchmm/tasn
5dba8ccc096cedc63913730eeea14a9647911129
tasn-mxnet/ci/build.py
python
default_ccache_dir
()
return os.path.join(tempfile.gettempdir(), "ci_ccache")
:return: ccache directory for the current platform
:return: ccache directory for the current platform
[ ":", "return", ":", "ccache", "directory", "for", "the", "current", "platform" ]
def default_ccache_dir() -> str: """:return: ccache directory for the current platform""" # Share ccache across containers if 'CCACHE_DIR' in os.environ: ccache_dir = os.path.realpath(os.environ['CCACHE_DIR']) try: os.makedirs(ccache_dir, exist_ok=True) return ccache_dir except PermissionError: logging.info('Unable to make dirs at %s, falling back to local temp dir', ccache_dir) # In osx tmpdir is not mountable by default import platform if platform.system() == 'Darwin': ccache_dir = "/tmp/_mxnet_ccache" os.makedirs(ccache_dir, exist_ok=True) return ccache_dir return os.path.join(tempfile.gettempdir(), "ci_ccache")
[ "def", "default_ccache_dir", "(", ")", "->", "str", ":", "# Share ccache across containers", "if", "'CCACHE_DIR'", "in", "os", ".", "environ", ":", "ccache_dir", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "environ", "[", "'CCACHE_DIR'", "]", ")...
https://github.com/researchmm/tasn/blob/5dba8ccc096cedc63913730eeea14a9647911129/tasn-mxnet/ci/build.py#L187-L203
Tencent/GAutomator
0ac9f849d1ca2c59760a91c5c94d3db375a380cd
GAutomatorIos/ga2/device/iOS/wda/__init__.py
python
Session.activate
(self, duration)
return self.http.post('/wda/activateApp', dict(duration=duration))
Put app into background and than put it back Args: - duration (float): deactivate time, seconds
Put app into background and than put it back Args: - duration (float): deactivate time, seconds
[ "Put", "app", "into", "background", "and", "than", "put", "it", "back", "Args", ":", "-", "duration", "(", "float", ")", ":", "deactivate", "time", "seconds" ]
def activate(self, duration): """Put app into background and than put it back Args: - duration (float): deactivate time, seconds """ return self.http.post('/wda/activateApp', dict(duration=duration))
[ "def", "activate", "(", "self", ",", "duration", ")", ":", "return", "self", ".", "http", ".", "post", "(", "'/wda/activateApp'", ",", "dict", "(", "duration", "=", "duration", ")", ")" ]
https://github.com/Tencent/GAutomator/blob/0ac9f849d1ca2c59760a91c5c94d3db375a380cd/GAutomatorIos/ga2/device/iOS/wda/__init__.py#L421-L426
rizar/attention-lvcsr
1ae52cafdd8419874846f9544a299eef9c758f3b
libs/fuel/fuel/utils/__init__.py
python
Subset.__add__
(self, other)
return self.__class__( self.get_list_representation() + other.get_list_representation(), self.original_num_examples)
Merges two subsets together. Parameters ---------- other : Subset Subset to merge with this subset.
Merges two subsets together.
[ "Merges", "two", "subsets", "together", "." ]
def __add__(self, other): """Merges two subsets together. Parameters ---------- other : Subset Subset to merge with this subset. """ # Adding two subsets only works if they're subsets of the same dataset, # wich can't possibly be the case if their original number of examples # differ. if self.original_num_examples != other.original_num_examples: raise ValueError("trying to add two Subset instances with " "different numbers of original examples, they " "can't possibly belong to the same dataset") # An empty subset is a neutral element in subset algebra if self.is_empty: return other # Merging list-based and slice-based subsets results in a list # conversion if self.is_list != other.is_list: return self.__class__( self.get_list_representation() + other.get_list_representation(), self.original_num_examples) # List-based subsets are merged by concatenating their indices. if self.is_list: return self.__class__(self.list_or_slice + other.list_or_slice, self.original_num_examples) # Slice-based subsets are merged into a slice-based subset if they # overlap, otherwise they're converted to a list-based subset. self_sss = self.slice_to_numerical_args( self.list_or_slice, self.original_num_examples) self_start, self_stop, self_step = self_sss other_sss = self.slice_to_numerical_args( other.list_or_slice, other.original_num_examples) other_start, other_stop, other_step = other_sss # In case of overlap, the solution is to choose the smallest start # value and largest stop value. if not (self_stop < other_start or self_start > other_stop): return self.__class__(slice(min(self_start, other_start), max(self_stop, other_stop), self_step), self.original_num_examples) # Everything else is transformed into lists before merging. return self.__class__( self.get_list_representation() + other.get_list_representation(), self.original_num_examples)
[ "def", "__add__", "(", "self", ",", "other", ")", ":", "# Adding two subsets only works if they're subsets of the same dataset,", "# wich can't possibly be the case if their original number of examples", "# differ.", "if", "self", ".", "original_num_examples", "!=", "other", ".", ...
https://github.com/rizar/attention-lvcsr/blob/1ae52cafdd8419874846f9544a299eef9c758f3b/libs/fuel/fuel/utils/__init__.py#L49-L97
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/apis/core_v1_api.py
python
CoreV1Api.proxy_head_namespaced_pod_with_path
(self, name, namespace, path, **kwargs)
proxy HEAD requests to Pod This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.proxy_head_namespaced_pod_with_path(name, namespace, path, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str name: name of the Pod (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str path: path to the resource (required) :return: str If the method is called asynchronously, returns the request thread.
proxy HEAD requests to Pod This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.proxy_head_namespaced_pod_with_path(name, namespace, path, callback=callback_function)
[ "proxy", "HEAD", "requests", "to", "Pod", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "be", "invoked", "...
def proxy_head_namespaced_pod_with_path(self, name, namespace, path, **kwargs): """ proxy HEAD requests to Pod This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.proxy_head_namespaced_pod_with_path(name, namespace, path, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str name: name of the Pod (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str path: path to the resource (required) :return: str If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.proxy_head_namespaced_pod_with_path_with_http_info(name, namespace, path, **kwargs) else: (data) = self.proxy_head_namespaced_pod_with_path_with_http_info(name, namespace, path, **kwargs) return data
[ "def", "proxy_head_namespaced_pod_with_path", "(", "self", ",", "name", ",", "namespace", ",", "path", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", ...
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/apis/core_v1_api.py#L19602-L19627
cnvogelg/amitools
b8aaff735cc64cdb95c4616b0c9a9683e2a0b753
amitools/vamos/loader/segload.py
python
SegmentLoader.load_ami_seglist
(self, ami_bin_file, lock=None)
load seglist, register it, and return seglist baddr or 0
load seglist, register it, and return seglist baddr or 0
[ "load", "seglist", "register", "it", "and", "return", "seglist", "baddr", "or", "0" ]
def load_ami_seglist(self, ami_bin_file, lock=None): """load seglist, register it, and return seglist baddr or 0""" info = self.int_load_ami_seglist(ami_bin_file, lock) if info: baddr = info.seglist.get_baddr() self.infos[baddr] = info log_segload.info("loaded ami seglist: %s", info) return baddr else: log_segload.info("can't load ami seglist: %s", ami_bin_file) return 0
[ "def", "load_ami_seglist", "(", "self", ",", "ami_bin_file", ",", "lock", "=", "None", ")", ":", "info", "=", "self", ".", "int_load_ami_seglist", "(", "ami_bin_file", ",", "lock", ")", "if", "info", ":", "baddr", "=", "info", ".", "seglist", ".", "get_b...
https://github.com/cnvogelg/amitools/blob/b8aaff735cc64cdb95c4616b0c9a9683e2a0b753/amitools/vamos/loader/segload.py#L45-L55
SCons/scons
309f0234d1d9cc76955818be47c5c722f577dac6
SCons/Variables/ListVariable.py
python
ListVariable
(key, help, default, names, map={})
return (key, help, default, None, lambda val: _converter(val, names, map))
Return a tuple describing a list SCons Variable. The input parameters describe a 'list' option. Returns a tuple including the correct converter and validator. The result is usable for input to :meth:`Add`. *help* will have text appended indicating the legal values (not including any extra names from *map*). *map* can be used to map alternative names to the ones in *names* - that is, a form of alias. A 'list' option may either be 'all', 'none' or a list of names (separated by commas).
Return a tuple describing a list SCons Variable.
[ "Return", "a", "tuple", "describing", "a", "list", "SCons", "Variable", "." ]
def ListVariable(key, help, default, names, map={}) -> Tuple[str, str, str, None, Callable]: """Return a tuple describing a list SCons Variable. The input parameters describe a 'list' option. Returns a tuple including the correct converter and validator. The result is usable for input to :meth:`Add`. *help* will have text appended indicating the legal values (not including any extra names from *map*). *map* can be used to map alternative names to the ones in *names* - that is, a form of alias. A 'list' option may either be 'all', 'none' or a list of names (separated by commas). """ names_str = 'allowed names: %s' % ' '.join(names) if SCons.Util.is_List(default): default = ','.join(default) help = '\n '.join( (help, '(all|none|comma-separated list of names)', names_str)) return (key, help, default, None, lambda val: _converter(val, names, map))
[ "def", "ListVariable", "(", "key", ",", "help", ",", "default", ",", "names", ",", "map", "=", "{", "}", ")", "->", "Tuple", "[", "str", ",", "str", ",", "str", ",", "None", ",", "Callable", "]", ":", "names_str", "=", "'allowed names: %s'", "%", "...
https://github.com/SCons/scons/blob/309f0234d1d9cc76955818be47c5c722f577dac6/SCons/Variables/ListVariable.py#L125-L146