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
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gui/widgets/styledtexteditor.py
python
StyledTextEditor._create_spell_menu
(self)
return menu
Create a menu with all the installed spellchecks. It is called each time the popup menu is opened. Each spellcheck forms a radio menu item, and the selected spellcheck is set as active. :returns: menu containing all the installed spellchecks. :rtype: Gtk.Menu
Create a menu with all the installed spellchecks.
[ "Create", "a", "menu", "with", "all", "the", "installed", "spellchecks", "." ]
def _create_spell_menu(self): """ Create a menu with all the installed spellchecks. It is called each time the popup menu is opened. Each spellcheck forms a radio menu item, and the selected spellcheck is set as active. :returns: menu containing all the installed spellchecks. :rtype: Gtk.Menu """ active_spellcheck = self.spellcheck.get_active_spellcheck() menu = Gtk.Menu() group = None for lang in self.spellcheck.get_all_spellchecks(): menuitem = Gtk.RadioMenuItem(label=lang) menuitem.set_active(lang == active_spellcheck) menuitem.connect('activate', self._spell_change_cb, lang) menu.append(menuitem) if group is None: group = menuitem return menu
[ "def", "_create_spell_menu", "(", "self", ")", ":", "active_spellcheck", "=", "self", ".", "spellcheck", ".", "get_active_spellcheck", "(", ")", "menu", "=", "Gtk", ".", "Menu", "(", ")", "group", "=", "None", "for", "lang", "in", "self", ".", "spellcheck"...
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gui/widgets/styledtexteditor.py#L613-L636
spectacles/CodeComplice
8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62
libs/codeintel2/parser_data.py
python
Node.dump_collection
(self, label, attr, indent_level)
[]
def dump_collection(self, label, attr, indent_level): if hasattr(self, attr): collection = getattr(self, attr) if len(collection) > 0: print("%s %s: " % (" " * indent_level, label)) for name, varInfo in list(collection.items()): line, type = varInfo.line_num, varInfo.type if type: typeString = " [" + type + "]" else: typeString = "" print("%s %s - line %s%s" % (" " * (indent_level + 2), name, line, typeString))
[ "def", "dump_collection", "(", "self", ",", "label", ",", "attr", ",", "indent_level", ")", ":", "if", "hasattr", "(", "self", ",", "attr", ")", ":", "collection", "=", "getattr", "(", "self", ",", "attr", ")", "if", "len", "(", "collection", ")", ">...
https://github.com/spectacles/CodeComplice/blob/8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62/libs/codeintel2/parser_data.py#L119-L130
clovaai/tunit
49e633179c5670228a2319d2c99054322616b516
models/inception.py
python
InceptionV3.__init__
(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True, normalize_input=True, requires_grad=False, use_fid_inception=True)
Build pretrained InceptionV3 Parameters ---------- output_blocks : list of int Indices of blocks to return features of. Possible values are: - 0: corresponds to output of first max pooling - 1: corresponds to output of second max pooling - 2: corresponds to output which is fed to aux classifier - 3: corresponds to output of final average pooling resize_input : bool If true, bilinearly resizes input to width and height 299 before feeding input to model. As the network without fully connected layers is fully convolutional, it should be able to handle inputs of arbitrary size, so resizing might not be strictly needed normalize_input : bool If true, scales the input from range (0, 1) to the range the pretrained Inception network expects, namely (-1, 1) requires_grad : bool If true, parameters of the model require gradients. Possibly useful for finetuning the network use_fid_inception : bool If true, uses the pretrained Inception model used in Tensorflow's FID implementation. If false, uses the pretrained Inception model available in torchvision. The FID Inception model has different weights and a slightly different structure from torchvision's Inception model. If you want to compute FID scores, you are strongly advised to set this parameter to true to get comparable results.
Build pretrained InceptionV3
[ "Build", "pretrained", "InceptionV3" ]
def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True, normalize_input=True, requires_grad=False, use_fid_inception=True): """Build pretrained InceptionV3 Parameters ---------- output_blocks : list of int Indices of blocks to return features of. Possible values are: - 0: corresponds to output of first max pooling - 1: corresponds to output of second max pooling - 2: corresponds to output which is fed to aux classifier - 3: corresponds to output of final average pooling resize_input : bool If true, bilinearly resizes input to width and height 299 before feeding input to model. As the network without fully connected layers is fully convolutional, it should be able to handle inputs of arbitrary size, so resizing might not be strictly needed normalize_input : bool If true, scales the input from range (0, 1) to the range the pretrained Inception network expects, namely (-1, 1) requires_grad : bool If true, parameters of the model require gradients. Possibly useful for finetuning the network use_fid_inception : bool If true, uses the pretrained Inception model used in Tensorflow's FID implementation. If false, uses the pretrained Inception model available in torchvision. The FID Inception model has different weights and a slightly different structure from torchvision's Inception model. If you want to compute FID scores, you are strongly advised to set this parameter to true to get comparable results. """ super(InceptionV3, self).__init__() self.resize_input = resize_input self.normalize_input = normalize_input self.output_blocks = sorted(output_blocks) self.last_needed_block = max(output_blocks) assert self.last_needed_block <= 3, \ 'Last possible output block index is 3' self.blocks = nn.ModuleList() if use_fid_inception: inception = fid_inception_v3() else: inception = models.inception_v3(pretrained=True) # Block 0: input to maxpool1 block0 = [ inception.Conv2d_1a_3x3, inception.Conv2d_2a_3x3, inception.Conv2d_2b_3x3, nn.MaxPool2d(kernel_size=3, stride=2) ] self.blocks.append(nn.Sequential(*block0)) # Block 1: maxpool1 to maxpool2 if self.last_needed_block >= 1: block1 = [ inception.Conv2d_3b_1x1, inception.Conv2d_4a_3x3, nn.MaxPool2d(kernel_size=3, stride=2) ] self.blocks.append(nn.Sequential(*block1)) # Block 2: maxpool2 to aux classifier if self.last_needed_block >= 2: block2 = [ inception.Mixed_5b, inception.Mixed_5c, inception.Mixed_5d, inception.Mixed_6a, inception.Mixed_6b, inception.Mixed_6c, inception.Mixed_6d, inception.Mixed_6e, ] self.blocks.append(nn.Sequential(*block2)) # Block 3: aux classifier to final avgpool if self.last_needed_block >= 3: block3 = [ inception.Mixed_7a, inception.Mixed_7b, inception.Mixed_7c, nn.AdaptiveAvgPool2d(output_size=(1, 1)) ] self.blocks.append(nn.Sequential(*block3)) for param in self.parameters(): param.requires_grad = requires_grad
[ "def", "__init__", "(", "self", ",", "output_blocks", "=", "[", "DEFAULT_BLOCK_INDEX", "]", ",", "resize_input", "=", "True", ",", "normalize_input", "=", "True", ",", "requires_grad", "=", "False", ",", "use_fid_inception", "=", "True", ")", ":", "super", "...
https://github.com/clovaai/tunit/blob/49e633179c5670228a2319d2c99054322616b516/models/inception.py#L36-L132
fonttools/fonttools
892322aaff6a89bea5927379ec06bc0da3dfb7df
Lib/fontTools/cffLib/__init__.py
python
TopDict.__init__
(self, strings=None, file=None, offset=None, GlobalSubrs=None, cff2GetGlyphOrder=None, isCFF2=None)
[]
def __init__(self, strings=None, file=None, offset=None, GlobalSubrs=None, cff2GetGlyphOrder=None, isCFF2=None): super(TopDict, self).__init__(strings, file, offset, isCFF2=isCFF2) self.cff2GetGlyphOrder = cff2GetGlyphOrder self.GlobalSubrs = GlobalSubrs if isCFF2: self.defaults = buildDefaults(topDictOperators2) self.charset = cff2GetGlyphOrder() self.order = buildOrder(topDictOperators2) else: self.defaults = buildDefaults(topDictOperators) self.order = buildOrder(topDictOperators)
[ "def", "__init__", "(", "self", ",", "strings", "=", "None", ",", "file", "=", "None", ",", "offset", "=", "None", ",", "GlobalSubrs", "=", "None", ",", "cff2GetGlyphOrder", "=", "None", ",", "isCFF2", "=", "None", ")", ":", "super", "(", "TopDict", ...
https://github.com/fonttools/fonttools/blob/892322aaff6a89bea5927379ec06bc0da3dfb7df/Lib/fontTools/cffLib/__init__.py#L2655-L2666
nortikin/sverchok
7b460f01317c15f2681bfa3e337c5e7346f3711b
utils/meshes.py
python
PyMesh.cast
(self, mesh_type: Type[Mesh])
Convert itself into other mesh types
Convert itself into other mesh types
[ "Convert", "itself", "into", "other", "mesh", "types" ]
def cast(self, mesh_type: Type[Mesh]) -> Mesh: """Convert itself into other mesh types""" if mesh_type == PyMesh: return self elif mesh_type == NpMesh: cast_mesh = NpMesh(self.vertices.data, self.edges.data, self.polygons.data) cast_mesh.vertices.copy_attributes(self.vertices) cast_mesh.edges.copy_attributes(self.edges) cast_mesh.polygons.copy_attributes(self.polygons) return cast_mesh else: raise TypeError(f'"{type(self).__name__}" type can not be converted to {mesh_type.__name__}')
[ "def", "cast", "(", "self", ",", "mesh_type", ":", "Type", "[", "Mesh", "]", ")", "->", "Mesh", ":", "if", "mesh_type", "==", "PyMesh", ":", "return", "self", "elif", "mesh_type", "==", "NpMesh", ":", "cast_mesh", "=", "NpMesh", "(", "self", ".", "ve...
https://github.com/nortikin/sverchok/blob/7b460f01317c15f2681bfa3e337c5e7346f3711b/utils/meshes.py#L156-L167
robhagemans/pcbasic
c3a043b46af66623a801e18a38175be077251ada
pcbasic/interface/sdl2.py
python
get_dll_file
()
return dll.libfile
Gets the file name of the loaded SDL2 library.
Gets the file name of the loaded SDL2 library.
[ "Gets", "the", "file", "name", "of", "the", "loaded", "SDL2", "library", "." ]
def get_dll_file(): """Gets the file name of the loaded SDL2 library.""" return dll.libfile
[ "def", "get_dll_file", "(", ")", ":", "return", "dll", ".", "libfile" ]
https://github.com/robhagemans/pcbasic/blob/c3a043b46af66623a801e18a38175be077251ada/pcbasic/interface/sdl2.py#L216-L218
cbrgm/telegram-robot-rss
58fe98de427121fdc152c8df0721f1891174e6c9
venv/lib/python2.7/site-packages/pip/exceptions.py
python
HashError._requirement_name
(self)
return str(self.req) if self.req else 'unknown package'
Return a description of the requirement that triggered me. This default implementation returns long description of the req, with line numbers
Return a description of the requirement that triggered me.
[ "Return", "a", "description", "of", "the", "requirement", "that", "triggered", "me", "." ]
def _requirement_name(self): """Return a description of the requirement that triggered me. This default implementation returns long description of the req, with line numbers """ return str(self.req) if self.req else 'unknown package'
[ "def", "_requirement_name", "(", "self", ")", ":", "return", "str", "(", "self", ".", "req", ")", "if", "self", ".", "req", "else", "'unknown package'" ]
https://github.com/cbrgm/telegram-robot-rss/blob/58fe98de427121fdc152c8df0721f1891174e6c9/venv/lib/python2.7/site-packages/pip/exceptions.py#L113-L120
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/wagtail/wagtailcore/fields.py
python
StreamField.contribute_to_class
(self, cls, name, **kwargs)
[]
def contribute_to_class(self, cls, name, **kwargs): super(StreamField, self).contribute_to_class(cls, name, **kwargs) # Add Creator descriptor to allow the field to be set from a list or a # JSON string. setattr(cls, self.name, Creator(self))
[ "def", "contribute_to_class", "(", "self", ",", "cls", ",", "name", ",", "*", "*", "kwargs", ")", ":", "super", "(", "StreamField", ",", "self", ")", ".", "contribute_to_class", "(", "cls", ",", "name", ",", "*", "*", "kwargs", ")", "# Add Creator descri...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/wagtail/wagtailcore/fields.py#L135-L140
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/setuptools-0.6c11/setuptools/dist.py
python
Distribution.fetch_build_eggs
(self, requires)
Resolve pre-setup requirements
Resolve pre-setup requirements
[ "Resolve", "pre", "-", "setup", "requirements" ]
def fetch_build_eggs(self, requires): """Resolve pre-setup requirements""" from pkg_resources import working_set, parse_requirements for dist in working_set.resolve( parse_requirements(requires), installer=self.fetch_build_egg ): working_set.add(dist)
[ "def", "fetch_build_eggs", "(", "self", ",", "requires", ")", ":", "from", "pkg_resources", "import", "working_set", ",", "parse_requirements", "for", "dist", "in", "working_set", ".", "resolve", "(", "parse_requirements", "(", "requires", ")", ",", "installer", ...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/setuptools-0.6c11/setuptools/dist.py#L280-L286
pysathq/pysat
07bf3a5a4428d40eca804e7ebdf4f496aadf4213
examples/rc2.py
python
RC2.minimize_core
(self)
Reduce a previously extracted core and compute an over-approximation of an MUS. This is done using the simple deletion-based MUS extraction algorithm. The idea is to try to deactivate soft clauses of the unsatisfiable core one by one while checking if the remaining soft clauses together with the hard part of the formula are unsatisfiable. Clauses that are necessary for preserving unsatisfiability comprise an MUS of the input formula (it is contained in the given unsatisfiable core) and are reported as a result of the procedure. During this core minimization procedure, all SAT calls are dropped after obtaining 1000 conflicts.
Reduce a previously extracted core and compute an over-approximation of an MUS. This is done using the simple deletion-based MUS extraction algorithm.
[ "Reduce", "a", "previously", "extracted", "core", "and", "compute", "an", "over", "-", "approximation", "of", "an", "MUS", ".", "This", "is", "done", "using", "the", "simple", "deletion", "-", "based", "MUS", "extraction", "algorithm", "." ]
def minimize_core(self): """ Reduce a previously extracted core and compute an over-approximation of an MUS. This is done using the simple deletion-based MUS extraction algorithm. The idea is to try to deactivate soft clauses of the unsatisfiable core one by one while checking if the remaining soft clauses together with the hard part of the formula are unsatisfiable. Clauses that are necessary for preserving unsatisfiability comprise an MUS of the input formula (it is contained in the given unsatisfiable core) and are reported as a result of the procedure. During this core minimization procedure, all SAT calls are dropped after obtaining 1000 conflicts. """ if self.minz and len(self.core) > 1: self.core = sorted(self.core, key=lambda l: self.wght[l]) self.oracle.conf_budget(1000) i = 0 while i < len(self.core): to_test = self.core[:i] + self.core[(i + 1):] if self.oracle.solve_limited(assumptions=to_test) == False: self.core = to_test else: i += 1
[ "def", "minimize_core", "(", "self", ")", ":", "if", "self", ".", "minz", "and", "len", "(", "self", ".", "core", ")", ">", "1", ":", "self", ".", "core", "=", "sorted", "(", "self", ".", "core", ",", "key", "=", "lambda", "l", ":", "self", "."...
https://github.com/pysathq/pysat/blob/07bf3a5a4428d40eca804e7ebdf4f496aadf4213/examples/rc2.py#L861-L890
miguelgrinberg/flasky-first-edition
923336f757c5665c56a2bbd21fe4e3b2d280b735
app/auth/views.py
python
password_reset_request
()
return render_template('auth/reset_password.html', form=form)
[]
def password_reset_request(): if not current_user.is_anonymous: return redirect(url_for('main.index')) form = PasswordResetRequestForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user: token = user.generate_reset_token() send_email(user.email, 'Reset Your Password', 'auth/email/reset_password', user=user, token=token, next=request.args.get('next')) flash('An email with instructions to reset your password has been ' 'sent to you.') return redirect(url_for('auth.login')) return render_template('auth/reset_password.html', form=form)
[ "def", "password_reset_request", "(", ")", ":", "if", "not", "current_user", ".", "is_anonymous", ":", "return", "redirect", "(", "url_for", "(", "'main.index'", ")", ")", "form", "=", "PasswordResetRequestForm", "(", ")", "if", "form", ".", "validate_on_submit"...
https://github.com/miguelgrinberg/flasky-first-edition/blob/923336f757c5665c56a2bbd21fe4e3b2d280b735/app/auth/views.py#L105-L120
fitnr/SublimeDataConverter
d659d3b3615aade9e27b0fb6c5797947f7406518
DataConverter.py
python
DataConverterCommand.markdown
(self, data)
return self._spaced_text(data, '|', decorate, between=True)
markdown table format
markdown table format
[ "markdown", "table", "format" ]
def markdown(self, data): """markdown table format""" self.set_syntax('Text', 'Markdown') def decorate(lengths): fields = '|'.join(' ' + ('-' * v) + ' ' for v in lengths) return '|' + fields + '|' return self._spaced_text(data, '|', decorate, between=True)
[ "def", "markdown", "(", "self", ",", "data", ")", ":", "self", ".", "set_syntax", "(", "'Text'", ",", "'Markdown'", ")", "def", "decorate", "(", "lengths", ")", ":", "fields", "=", "'|'", ".", "join", "(", "' '", "+", "(", "'-'", "*", "v", ")", "...
https://github.com/fitnr/SublimeDataConverter/blob/d659d3b3615aade9e27b0fb6c5797947f7406518/DataConverter.py#L649-L657
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
src/templates/java_lexer.py
python
t_comment_cpp
(lexer,tok)
r' //.*\n?
r' //.*\n?
[ "r", "//", ".", "*", "\\", "n?" ]
def t_comment_cpp(lexer,tok): # \n? correct ? r' //.*\n?' pos = lexer.pos lineno = lexer.lineno col = pos-lexer.line_start_pos tok.start = lineno # == tok.lineno tok.col = col tok.end = lineno if tok.value[-1] == '\n': lexer.lineno += 1 lexer.line_start_pos = pos + len(tok.value) tok.value = tok.value[:-1]
[ "def", "t_comment_cpp", "(", "lexer", ",", "tok", ")", ":", "# \\n? correct ?", "pos", "=", "lexer", ".", "pos", "lineno", "=", "lexer", ".", "lineno", "col", "=", "pos", "-", "lexer", ".", "line_start_pos", "tok", ".", "start", "=", "lineno", "# == tok....
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/src/templates/java_lexer.py#L269-L284
heynemann/motorengine
5e1fea7cc15060f768a697fe4c3593d20f23c4ed
motorengine/document.py
python
BaseDocument.find_list_field
(self, document, results, field_name, field)
[]
def find_list_field(self, document, results, field_name, field): from motorengine.fields.reference_field import ReferenceField if self.is_list_field(field): values = document._values.get(field_name) if values: document_type = values[0].__class__ if isinstance(field._base_field, ReferenceField): document_type = field._base_field.reference_type load_function = self._get_load_function( document, field_name, document_type ) for value in values: results.append([ load_function, value, document._values, field_name, self.fill_list_values_collection ]) document._values[field_name] = [] else: self.find_references(document=document_type, results=results)
[ "def", "find_list_field", "(", "self", ",", "document", ",", "results", ",", "field_name", ",", "field", ")", ":", "from", "motorengine", ".", "fields", ".", "reference_field", "import", "ReferenceField", "if", "self", ".", "is_list_field", "(", "field", ")", ...
https://github.com/heynemann/motorengine/blob/5e1fea7cc15060f768a697fe4c3593d20f23c4ed/motorengine/document.py#L257-L278
ondyari/FaceForensics
b952e41cba017eb37593c39e12bd884a934791e1
dataset/DeepFakes/faceswap-master/lib/gui/display_analysis.py
python
Options.add_buttons
(self)
Add the option buttons
Add the option buttons
[ "Add", "the", "option", "buttons" ]
def add_buttons(self): """ Add the option buttons """ for btntype in ("reset", "clear", "save", "load"): cmd = getattr(self.parent, "{}_session".format(btntype)) btn = ttk.Button(self.optsframe, image=Images().icons[btntype], command=cmd) btn.pack(padx=2, side=tk.RIGHT) hlp = self.set_help(btntype) Tooltip(btn, text=hlp, wraplength=200)
[ "def", "add_buttons", "(", "self", ")", ":", "for", "btntype", "in", "(", "\"reset\"", ",", "\"clear\"", ",", "\"save\"", ",", "\"load\"", ")", ":", "cmd", "=", "getattr", "(", "self", ".", "parent", ",", "\"{}_session\"", ".", "format", "(", "btntype", ...
https://github.com/ondyari/FaceForensics/blob/b952e41cba017eb37593c39e12bd884a934791e1/dataset/DeepFakes/faceswap-master/lib/gui/display_analysis.py#L120-L129
qiucheng025/zao-
3a5edf3607b3a523f95746bc69b688090c76d89a
tools/lib_alignments/media.py
python
ExtractedFaces.get_faces_in_frame
(self, frame, update=False)
return self.faces
Return the faces for the selected frame
Return the faces for the selected frame
[ "Return", "the", "faces", "for", "the", "selected", "frame" ]
def get_faces_in_frame(self, frame, update=False): """ Return the faces for the selected frame """ logger.trace("frame: '%s', update: %s", frame, update) if self.current_frame != frame or update: self.get_faces(frame) return self.faces
[ "def", "get_faces_in_frame", "(", "self", ",", "frame", ",", "update", "=", "False", ")", ":", "logger", ".", "trace", "(", "\"frame: '%s', update: %s\"", ",", "frame", ",", "update", ")", "if", "self", ".", "current_frame", "!=", "frame", "or", "update", ...
https://github.com/qiucheng025/zao-/blob/3a5edf3607b3a523f95746bc69b688090c76d89a/tools/lib_alignments/media.py#L330-L335
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/importlib/_bootstrap.py
python
_load
(spec)
Return a new module object, loaded by the spec's loader. The module is not added to its parent. If a module is already in sys.modules, that existing module gets clobbered.
Return a new module object, loaded by the spec's loader.
[ "Return", "a", "new", "module", "object", "loaded", "by", "the", "spec", "s", "loader", "." ]
def _load(spec): """Return a new module object, loaded by the spec's loader. The module is not added to its parent. If a module is already in sys.modules, that existing module gets clobbered. """ with _ModuleLockManager(spec.name): return _load_unlocked(spec)
[ "def", "_load", "(", "spec", ")", ":", "with", "_ModuleLockManager", "(", "spec", ".", "name", ")", ":", "return", "_load_unlocked", "(", "spec", ")" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/importlib/_bootstrap.py#L674-L684
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/werkzeug/contrib/iterio.py
python
IterI.writelines
(self, list)
[]
def writelines(self, list): for item in list: self.write(item)
[ "def", "writelines", "(", "self", ",", "list", ")", ":", "for", "item", "in", "list", ":", "self", ".", "write", "(", "item", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/werkzeug/contrib/iterio.py#L200-L202
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/min/_pyio.py
python
BufferedRWPair.__init__
(self, reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)
Constructor. The arguments are two RawIO instances.
Constructor.
[ "Constructor", "." ]
def __init__(self, reader, writer, buffer_size=DEFAULT_BUFFER_SIZE): """Constructor. The arguments are two RawIO instances. """ if not reader.readable(): raise OSError('"reader" argument must be readable.') if not writer.writable(): raise OSError('"writer" argument must be writable.') self.reader = BufferedReader(reader, buffer_size) self.writer = BufferedWriter(writer, buffer_size)
[ "def", "__init__", "(", "self", ",", "reader", ",", "writer", ",", "buffer_size", "=", "DEFAULT_BUFFER_SIZE", ")", ":", "if", "not", "reader", ".", "readable", "(", ")", ":", "raise", "OSError", "(", "'\"reader\" argument must be readable.'", ")", "if", "not",...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/_pyio.py#L1369-L1381
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
web2py-rest/gluon/compileapp.py
python
run_models_in
(environment)
Runs all models (in the app specified by the current folder) It tries pre-compiled models first before compiling them.
Runs all models (in the app specified by the current folder) It tries pre-compiled models first before compiling them.
[ "Runs", "all", "models", "(", "in", "the", "app", "specified", "by", "the", "current", "folder", ")", "It", "tries", "pre", "-", "compiled", "models", "first", "before", "compiling", "them", "." ]
def run_models_in(environment): """ Runs all models (in the app specified by the current folder) It tries pre-compiled models first before compiling them. """ request = current.request folder = request.folder c = request.controller #f = environment['request'].function response = current.response path = pjoin(folder, 'models') cpath = pjoin(folder, 'compiled') compiled = os.path.exists(cpath) if compiled: models = sorted(listdir(cpath, '^models[_.][\w.]+\.pyc$', 0), model_cmp) else: models = sorted(listdir(path, '^\w+\.py$', 0, sort=False), model_cmp_sep) models_to_run = None for model in models: if response.models_to_run != models_to_run: regex = models_to_run = response.models_to_run[:] if isinstance(regex, list): regex = re_compile('|'.join(regex)) if models_to_run: if compiled: n = len(cpath)+8 fname = model[n:-4].replace('.','/')+'.py' else: n = len(path)+1 fname = model[n:].replace(os.path.sep,'/') if not regex.search(fname) and c != 'appadmin': continue elif compiled: code = read_pyc(model) elif is_gae: code = getcfs(model, model, lambda: compile2(read_file(model), model)) else: code = getcfs(model, model, None) restricted(code, environment, layer=model)
[ "def", "run_models_in", "(", "environment", ")", ":", "request", "=", "current", ".", "request", "folder", "=", "request", ".", "folder", "c", "=", "request", ".", "controller", "#f = environment['request'].function", "response", "=", "current", ".", "response", ...
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py-rest/gluon/compileapp.py#L535-L576
ktbyers/netmiko
4c3732346eea1a4a608abd9e09d65eeb2f577810
netmiko/huawei/huawei.py
python
HuaweiBase.exit_config_mode
(self, exit_config: str = "return", pattern: str = r">")
return super().exit_config_mode(exit_config=exit_config, pattern=pattern)
Exit configuration mode.
Exit configuration mode.
[ "Exit", "configuration", "mode", "." ]
def exit_config_mode(self, exit_config: str = "return", pattern: str = r">") -> str: """Exit configuration mode.""" return super().exit_config_mode(exit_config=exit_config, pattern=pattern)
[ "def", "exit_config_mode", "(", "self", ",", "exit_config", ":", "str", "=", "\"return\"", ",", "pattern", ":", "str", "=", "r\">\"", ")", "->", "str", ":", "return", "super", "(", ")", ".", "exit_config_mode", "(", "exit_config", "=", "exit_config", ",", ...
https://github.com/ktbyers/netmiko/blob/4c3732346eea1a4a608abd9e09d65eeb2f577810/netmiko/huawei/huawei.py#L45-L47
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/ecdsa/numbertheory.py
python
gcd2
(a, b)
return b
Greatest common divisor using Euclid's algorithm.
Greatest common divisor using Euclid's algorithm.
[ "Greatest", "common", "divisor", "using", "Euclid", "s", "algorithm", "." ]
def gcd2(a, b): """Greatest common divisor using Euclid's algorithm.""" while a: a, b = b%a, a return b
[ "def", "gcd2", "(", "a", ",", "b", ")", ":", "while", "a", ":", "a", ",", "b", "=", "b", "%", "a", ",", "a", "return", "b" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/ecdsa/numbertheory.py#L206-L210
hyde/hyde
7f415402cc3e007a746eb2b5bc102281fdb415bd
hyde/ext/templates/jinja.py
python
Markdown._render_markdown
(self, caller=None)
return markdown(self.environment, output)
Calls the markdown filter to transform the output.
Calls the markdown filter to transform the output.
[ "Calls", "the", "markdown", "filter", "to", "transform", "the", "output", "." ]
def _render_markdown(self, caller=None): """ Calls the markdown filter to transform the output. """ if not caller: return '' output = caller().strip() return markdown(self.environment, output)
[ "def", "_render_markdown", "(", "self", ",", "caller", "=", "None", ")", ":", "if", "not", "caller", ":", "return", "''", "output", "=", "caller", "(", ")", ".", "strip", "(", ")", "return", "markdown", "(", "self", ".", "environment", ",", "output", ...
https://github.com/hyde/hyde/blob/7f415402cc3e007a746eb2b5bc102281fdb415bd/hyde/ext/templates/jinja.py#L309-L316
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/unifi/controller.py
python
UniFiController.async_heartbeat
( self, unique_id: str, heartbeat_expire_time: datetime | None = None )
Signal when a device has fresh home state.
Signal when a device has fresh home state.
[ "Signal", "when", "a", "device", "has", "fresh", "home", "state", "." ]
def async_heartbeat( self, unique_id: str, heartbeat_expire_time: datetime | None = None ) -> None: """Signal when a device has fresh home state.""" if heartbeat_expire_time is not None: self._heartbeat_time[unique_id] = heartbeat_expire_time return if unique_id in self._heartbeat_time: del self._heartbeat_time[unique_id]
[ "def", "async_heartbeat", "(", "self", ",", "unique_id", ":", "str", ",", "heartbeat_expire_time", ":", "datetime", "|", "None", "=", "None", ")", "->", "None", ":", "if", "heartbeat_expire_time", "is", "not", "None", ":", "self", ".", "_heartbeat_time", "["...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/unifi/controller.py#L372-L381
kbandla/ImmunityDebugger
2abc03fb15c8f3ed0914e1175c4d8933977c73e3
1.84/Libs/x86smt/sequenceanalyzer.py
python
SequenceAnalyzer.__init__
(self, imm, r_model=None, f_model=None, m_model=False, analysis_mods=[], simplifyState=True, queryTimeout=0, prettysolver=False)
@type r_model: Dict @param r_model: A dictionary mapping registers to concrete values. Any registers not described in this dict will be described as undefined to the solver which effectively implies they are entirely user controlled and can therefore be assigned any value by the solver when looking for a satisfying assignment @type f_model: Dict @param f_model: A dictionary mapping flags to concrete values. Any flags not described in this dict will be described as undefined to the solver which effectively implies they are entirely user controlled and can therefore be assigned any value by the solver when looking for a satisfying assignment @type m_model: Bool @param m_model: If this is set to True then the solver will use the current memory state of the process as the model for any memory references it encounters during analysis. If it is False then values read from memory will be undefined initially.
@type r_model: Dict @param r_model: A dictionary mapping registers to concrete values. Any registers not described in this dict will be described as undefined to the solver which effectively implies they are entirely user controlled and can therefore be assigned any value by the solver when looking for a satisfying assignment
[ "@type", "r_model", ":", "Dict", "@param", "r_model", ":", "A", "dictionary", "mapping", "registers", "to", "concrete", "values", ".", "Any", "registers", "not", "described", "in", "this", "dict", "will", "be", "described", "as", "undefined", "to", "the", "s...
def __init__(self, imm, r_model=None, f_model=None, m_model=False, analysis_mods=[], simplifyState=True, queryTimeout=0, prettysolver=False): """ @type r_model: Dict @param r_model: A dictionary mapping registers to concrete values. Any registers not described in this dict will be described as undefined to the solver which effectively implies they are entirely user controlled and can therefore be assigned any value by the solver when looking for a satisfying assignment @type f_model: Dict @param f_model: A dictionary mapping flags to concrete values. Any flags not described in this dict will be described as undefined to the solver which effectively implies they are entirely user controlled and can therefore be assigned any value by the solver when looking for a satisfying assignment @type m_model: Bool @param m_model: If this is set to True then the solver will use the current memory state of the process as the model for any memory references it encounters during analysis. If it is False then values read from memory will be undefined initially. """ self.imm = imm self._debug = False self._traceback = False self.continue_on_error = False self.ignoredExceptions = [] self.errors = [] self.stack = [] self.REPtooLongCounter=0x20 #a REP with a counter bigger than this is going to raise a "TooBigRepeatCounterException" exception self.useCurrentMemory = m_model sol = Solver(manualInitialization=True) sol.flags = sol.createFlags() sol.setIntFlag(sol.flags, "stimeout", queryTimeout) #set a query timeout to avoid lockouts #0 means unlimited sol.createValidityChecker(sol.flags) if prettysolver: sol = PrettySolver(sol) self.state = StateMachine(r_model, f_model, sol) #we do lazy updates for flags self.state.flags.updatecallback = self.updateFlagsReal # Analysis functions. Should support a check_ins function # that takes a SequenceAnalyzer object as its first argument and # an opCode object representing the current instruction as its # second argument. If it has anything to report it should return # an AnalysisResult object or None otherwise self.analysis_mods = analysis_mods # The analyzeNext function will call each analysis module on # each instruction *before* updating the state with the SMT # semantics of that instruction. self.analysis_mod_results = {} for f in self.analysis_mods: self.analysis_mod_results[f] = [] self.visitedAddresses = [] self.initialAddress=None self.depth=None self.stopInstruction=None self.stopEIP=None self.lastAddress=None self.lastCmd=None self.simplifyState=simplifyState
[ "def", "__init__", "(", "self", ",", "imm", ",", "r_model", "=", "None", ",", "f_model", "=", "None", ",", "m_model", "=", "False", ",", "analysis_mods", "=", "[", "]", ",", "simplifyState", "=", "True", ",", "queryTimeout", "=", "0", ",", "prettysolve...
https://github.com/kbandla/ImmunityDebugger/blob/2abc03fb15c8f3ed0914e1175c4d8933977c73e3/1.84/Libs/x86smt/sequenceanalyzer.py#L791-L865
nanoporetech/tombo
afdb4d87249806d3a171d009f948f5b8558d35a0
tombo/_filter_reads.py
python
filter_reads_for_signal_matching
(fast5s_dir, corr_grp, sig_match_thresh)
return
Filter reads based on observed to expected signal matching score
Filter reads based on observed to expected signal matching score
[ "Filter", "reads", "based", "on", "observed", "to", "expected", "signal", "matching", "score" ]
def filter_reads_for_signal_matching(fast5s_dir, corr_grp, sig_match_thresh): """Filter reads based on observed to expected signal matching score """ def read_fails_matching_score(fast5_fn, corr_group): try: with h5py.File(fast5_fn, 'r') as fast5_data: return fast5_data['/Analyses/' + corr_group].attrs.get( 'signal_match_score') > sig_match_thresh except: return True reads_index = th.TomboReads([fast5s_dir,], corr_grp, remove_filtered=False) th.status_message('Filtering reads above a signal matching score threshold.') filt_reads_index = dict((cs, []) for cs in reads_index.get_all_cs()) num_filt_reads, prev_unfilt_reads, total_reads = 0, 0, 0 for chrm_strand, cs_reads in reads_index: for rd in cs_reads: total_reads += 1 if rd.filtered: filt_reads_index[chrm_strand].append(rd) continue prev_unfilt_reads += 1 if rd.sig_match_score is None: filter_read = read_fails_matching_score(rd.fn, rd.corr_group) else: filter_read = rd.sig_match_score > sig_match_thresh if filter_read: num_filt_reads += 1 rd = rd._replace(filtered=True) filt_reads_index[chrm_strand].append(rd) print_filter_mess(num_filt_reads, prev_unfilt_reads, total_reads, fast5s_dir, 'signal matching') reads_index.replace_index(filt_reads_index) reads_index.write_index_file() return
[ "def", "filter_reads_for_signal_matching", "(", "fast5s_dir", ",", "corr_grp", ",", "sig_match_thresh", ")", ":", "def", "read_fails_matching_score", "(", "fast5_fn", ",", "corr_group", ")", ":", "try", ":", "with", "h5py", ".", "File", "(", "fast5_fn", ",", "'r...
https://github.com/nanoporetech/tombo/blob/afdb4d87249806d3a171d009f948f5b8558d35a0/tombo/_filter_reads.py#L196-L235
openstack/barbican
a9d2b133c8dc3307974f119f9a2b23a4ba82e8ce
barbican/common/validators.py
python
ValidatorBase.validate
(self, json_data, parent_schema=None)
Validate the input JSON. :param json_data: JSON to validate against this class' internal schema. :param parent_schema: Name of the parent schema to this schema. :returns: dict -- JSON content, post-validation and : normalization/defaulting. :raises: schema.ValidationError on schema violations.
Validate the input JSON.
[ "Validate", "the", "input", "JSON", "." ]
def validate(self, json_data, parent_schema=None): """Validate the input JSON. :param json_data: JSON to validate against this class' internal schema. :param parent_schema: Name of the parent schema to this schema. :returns: dict -- JSON content, post-validation and : normalization/defaulting. :raises: schema.ValidationError on schema violations. """
[ "def", "validate", "(", "self", ",", "json_data", ",", "parent_schema", "=", "None", ")", ":" ]
https://github.com/openstack/barbican/blob/a9d2b133c8dc3307974f119f9a2b23a4ba82e8ce/barbican/common/validators.py#L95-L104
grnet/synnefo
d06ec8c7871092131cdaabf6b03ed0b504c93e43
snf-cyclades-app/synnefo/db/migrations/old/0037_network_migration.py
python
Migration.backwards
(self, orm)
Write your backwards methods here.
Write your backwards methods here.
[ "Write", "your", "backwards", "methods", "here", "." ]
def backwards(self, orm): "Write your backwards methods here." pass
[ "def", "backwards", "(", "self", ",", "orm", ")", ":", "pass" ]
https://github.com/grnet/synnefo/blob/d06ec8c7871092131cdaabf6b03ed0b504c93e43/snf-cyclades-app/synnefo/db/migrations/old/0037_network_migration.py#L52-L54
ospalh/anki-addons
4ece13423bd541e29d9b40ebe26ca0999a6962b1
downloadaudio/download.py
python
do_download
(note, field_data_list, language, hide_text=False)
Download audio data. Go through the list of words and list of sites and download each word from each site. Then call a function that asks the user what to do.
Download audio data.
[ "Download", "audio", "data", "." ]
def do_download(note, field_data_list, language, hide_text=False): """ Download audio data. Go through the list of words and list of sites and download each word from each site. Then call a function that asks the user what to do. """ retrieved_entries = [] for field_data in field_data_list: if field_data.empty: continue for dloader in downloaders: # Use a public variable to set the language. dloader.language = language try: # Make it easer inside the downloader. If anything # goes wrong, don't catch, or raise whatever you want. dloader.download_files(field_data) except: # # Uncomment this raise while testing a new # # downloaders. Also use the “For testing” # # downloaders list with your downloader in # # downloaders.__init__ # raise continue retrieved_entries += dloader.downloads_list # Significantly changed the logic. Put all entries in one # list, do stuff with that list of DownloadEntries. for entry in retrieved_entries: # Do the processing before the reviewing now. entry.process() try: retrieved_entries = review_entries(note, retrieved_entries, hide_text) # Now just the dialog, which sets the fields in the entries except ValueError as ve: tooltip(str(ve)) except RuntimeError as rte: if 'cancel' in str(rte): for entry in retrieved_entries: entry.action = Action.Delete else: raise for entry in retrieved_entries: entry.dispatch(note) if any(entry.action == Action.Add for entry in retrieved_entries): note.flush() # We have to do different things here, for download during # review, we should reload the card and replay. When we are in # the add dialog, we do a field update there. rnote = None try: rnote = mw.reviewer.card.note() except AttributeError: # Could not get the note of the reviewer's card. Probably # not reviewing at all. return if note == rnote: # The note we have is the one we were reviewing, so, # reload and replay mw.reviewer.card.load() mw.reviewer.replayAudio()
[ "def", "do_download", "(", "note", ",", "field_data_list", ",", "language", ",", "hide_text", "=", "False", ")", ":", "retrieved_entries", "=", "[", "]", "for", "field_data", "in", "field_data_list", ":", "if", "field_data", ".", "empty", ":", "continue", "f...
https://github.com/ospalh/anki-addons/blob/4ece13423bd541e29d9b40ebe26ca0999a6962b1/downloadaudio/download.py#L62-L123
beeware/ouroboros
a29123c6fab6a807caffbb7587cf548e0c370296
ouroboros/idlelib/SearchEngine.py
python
search_reverse
(prog, chars, col)
return found
Search backwards and return an re match object or None. This is done by searching forwards until there is no match. Prog: compiled re object with a search method returning a match. Chars: line of text, without \\n. Col: stop index for the search; the limit for match.end().
Search backwards and return an re match object or None.
[ "Search", "backwards", "and", "return", "an", "re", "match", "object", "or", "None", "." ]
def search_reverse(prog, chars, col): '''Search backwards and return an re match object or None. This is done by searching forwards until there is no match. Prog: compiled re object with a search method returning a match. Chars: line of text, without \\n. Col: stop index for the search; the limit for match.end(). ''' m = prog.search(chars) if not m: return None found = None i, j = m.span() # m.start(), m.end() == match slice indexes while i < col and j <= col: found = m if i == j: j = j+1 m = prog.search(chars, j) if not m: break i, j = m.span() return found
[ "def", "search_reverse", "(", "prog", ",", "chars", ",", "col", ")", ":", "m", "=", "prog", ".", "search", "(", "chars", ")", "if", "not", "m", ":", "return", "None", "found", "=", "None", "i", ",", "j", "=", "m", ".", "span", "(", ")", "# m.st...
https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/idlelib/SearchEngine.py#L189-L210
cduck/drawSvg
c9aaa230f54091774ba033b7aa57b791c0b0232a
drawSvg/animation.py
python
animate_video
(out_file, draw_func=None, jupyter=False, **video_args)
return AnimationContext(draw_func=draw_func, out_file=out_file, jupyter=jupyter, video_args=video_args)
Returns a context manager that stores frames and saves a video when the context exits. Example: ``` with animate_video('video.mp4') as anim: while True: ... anim.draw_frame(...) ```
Returns a context manager that stores frames and saves a video when the context exits.
[ "Returns", "a", "context", "manager", "that", "stores", "frames", "and", "saves", "a", "video", "when", "the", "context", "exits", "." ]
def animate_video(out_file, draw_func=None, jupyter=False, **video_args): ''' Returns a context manager that stores frames and saves a video when the context exits. Example: ``` with animate_video('video.mp4') as anim: while True: ... anim.draw_frame(...) ``` ''' return AnimationContext(draw_func=draw_func, out_file=out_file, jupyter=jupyter, video_args=video_args)
[ "def", "animate_video", "(", "out_file", ",", "draw_func", "=", "None", ",", "jupyter", "=", "False", ",", "*", "*", "video_args", ")", ":", "return", "AnimationContext", "(", "draw_func", "=", "draw_func", ",", "out_file", "=", "out_file", ",", "jupyter", ...
https://github.com/cduck/drawSvg/blob/c9aaa230f54091774ba033b7aa57b791c0b0232a/drawSvg/animation.py#L73-L87
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/flask/blueprints.py
python
Blueprint.app_context_processor
(self, f)
return f
Like :meth:`Flask.context_processor` but for a blueprint. Such a function is executed each request, even if outside of the blueprint.
Like :meth:`Flask.context_processor` but for a blueprint. Such a function is executed each request, even if outside of the blueprint.
[ "Like", ":", "meth", ":", "Flask", ".", "context_processor", "but", "for", "a", "blueprint", ".", "Such", "a", "function", "is", "executed", "each", "request", "even", "if", "outside", "of", "the", "blueprint", "." ]
def app_context_processor(self, f): """Like :meth:`Flask.context_processor` but for a blueprint. Such a function is executed each request, even if outside of the blueprint. """ self.record_once(lambda s: s.app.template_context_processors .setdefault(None, []).append(f)) return f
[ "def", "app_context_processor", "(", "self", ",", "f", ")", ":", "self", ".", "record_once", "(", "lambda", "s", ":", "s", ".", "app", ".", "template_context_processors", ".", "setdefault", "(", "None", ",", "[", "]", ")", ".", "append", "(", "f", ")",...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/flask/blueprints.py#L373-L379
davidmcclure/open-syllabus-project
078cfd4c5a257fbfb0901d43bfbc6350824eed4e
osp/www/utils/facets.py
python
bootstrap_facets
()
return dict( corpus = corpus_facets(), subfield = subfield_facets(), field = field_facets(), state = state_facets(), country = country_facets(), )
Bootstrap all facets for the front-end.
Bootstrap all facets for the front-end.
[ "Bootstrap", "all", "facets", "for", "the", "front", "-", "end", "." ]
def bootstrap_facets(): """ Bootstrap all facets for the front-end. """ return dict( corpus = corpus_facets(), subfield = subfield_facets(), field = field_facets(), state = state_facets(), country = country_facets(), )
[ "def", "bootstrap_facets", "(", ")", ":", "return", "dict", "(", "corpus", "=", "corpus_facets", "(", ")", ",", "subfield", "=", "subfield_facets", "(", ")", ",", "field", "=", "field_facets", "(", ")", ",", "state", "=", "state_facets", "(", ")", ",", ...
https://github.com/davidmcclure/open-syllabus-project/blob/078cfd4c5a257fbfb0901d43bfbc6350824eed4e/osp/www/utils/facets.py#L101-L113
ThilinaRajapakse/simpletransformers
9323c0398baea0157044e080617b2c4be59de7a9
simpletransformers/question_answering/question_answering_utils.py
python
write_predictions
( all_examples, all_features, all_results, n_best_size, max_answer_length, do_lower_case, output_prediction_file, output_nbest_file, output_null_log_odds_file, verbose_logging, version_2_with_negative, null_score_diff_threshold, )
return all_predictions, all_nbest_json, scores_diff_json
Write final predictions to the json file and log-odds of null if needed.
Write final predictions to the json file and log-odds of null if needed.
[ "Write", "final", "predictions", "to", "the", "json", "file", "and", "log", "-", "odds", "of", "null", "if", "needed", "." ]
def write_predictions( all_examples, all_features, all_results, n_best_size, max_answer_length, do_lower_case, output_prediction_file, output_nbest_file, output_null_log_odds_file, verbose_logging, version_2_with_negative, null_score_diff_threshold, ): """Write final predictions to the json file and log-odds of null if needed.""" # logger.info("Writing predictions to: %s" % (output_prediction_file)) # logger.info("Writing nbest to: %s" % (output_nbest_file)) example_index_to_features = collections.defaultdict(list) for feature in all_features: example_index_to_features[feature.example_index].append(feature) unique_id_to_result = {} for result in all_results: unique_id_to_result[result.unique_id] = result _PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name "PrelimPrediction", ["feature_index", "start_index", "end_index", "start_logit", "end_logit"], ) all_predictions = collections.OrderedDict() all_nbest_json = collections.OrderedDict() scores_diff_json = collections.OrderedDict() for (example_index, example) in enumerate(all_examples): features = example_index_to_features[example_index] prelim_predictions = [] # keep track of the minimum score of null start+end of position 0 score_null = 1000000 # large and positive min_null_feature_index = 0 # the paragraph slice with min null score null_start_logit = 0 # the start logit at the slice with min null score null_end_logit = 0 # the end logit at the slice with min null score for (feature_index, feature) in enumerate(features): result = unique_id_to_result[feature.unique_id] start_indexes = _get_best_indexes(result.start_logits, n_best_size) end_indexes = _get_best_indexes(result.end_logits, n_best_size) # if we could have irrelevant answers, get the min score of irrelevant if version_2_with_negative: feature_null_score = result.start_logits[0] + result.end_logits[0] if feature_null_score < score_null: score_null = feature_null_score min_null_feature_index = feature_index null_start_logit = result.start_logits[0] null_end_logit = result.end_logits[0] for start_index in start_indexes: for end_index in end_indexes: # We could hypothetically create invalid predictions, e.g., predict # that the start of the span is in the question. We throw out all # invalid predictions. if start_index >= len(feature.tokens): continue if end_index >= len(feature.tokens): continue if start_index not in feature.token_to_orig_map: continue if end_index not in feature.token_to_orig_map: continue if not feature.token_is_max_context.get(start_index, False): continue if end_index < start_index: continue length = end_index - start_index + 1 if length > max_answer_length: continue prelim_predictions.append( _PrelimPrediction( feature_index=feature_index, start_index=start_index, end_index=end_index, start_logit=result.start_logits[start_index], end_logit=result.end_logits[end_index], ) ) if version_2_with_negative: prelim_predictions.append( _PrelimPrediction( feature_index=min_null_feature_index, start_index=0, end_index=0, start_logit=null_start_logit, end_logit=null_end_logit, ) ) prelim_predictions = sorted( prelim_predictions, key=lambda x: (x.start_logit + x.end_logit), reverse=True, ) _NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name "NbestPrediction", ["text", "start_logit", "end_logit"] ) seen_predictions = {} nbest = [] for pred in prelim_predictions: if len(nbest) >= n_best_size: break if pred.start_index > 0: # this is a non-null prediction feature = features[pred.feature_index] tok_tokens = feature.tokens[pred.start_index : (pred.end_index + 1)] orig_doc_start = feature.token_to_orig_map[pred.start_index] orig_doc_end = feature.token_to_orig_map[pred.end_index] orig_tokens = example.doc_tokens[orig_doc_start : (orig_doc_end + 1)] tok_text = " ".join(tok_tokens) # De-tokenize WordPieces that have been split off. tok_text = tok_text.replace(" ##", "") tok_text = tok_text.replace("##", "") # Clean whitespace tok_text = tok_text.strip() tok_text = " ".join(tok_text.split()) orig_text = " ".join(orig_tokens) final_text = get_final_text( tok_text, orig_text, do_lower_case, verbose_logging ) if final_text in seen_predictions: continue seen_predictions[final_text] = True else: final_text = "" seen_predictions[final_text] = True nbest.append( _NbestPrediction( text=final_text, start_logit=pred.start_logit, end_logit=pred.end_logit, ) ) # if we didn't include the empty option in the n-best, include it if version_2_with_negative: if "" not in seen_predictions: nbest.append( _NbestPrediction( text="", start_logit=null_start_logit, end_logit=null_end_logit ) ) # In very rare edge cases we could only have single null prediction. # So we just create a nonce prediction in this case to avoid failure. if len(nbest) == 1: nbest.insert( 0, _NbestPrediction(text="empty", start_logit=0.0, end_logit=0.0) ) # In very rare edge cases we could have no valid predictions. So we # just create a nonce prediction in this case to avoid failure. if not nbest: nbest.append(_NbestPrediction(text="empty", start_logit=0.0, end_logit=0.0)) assert len(nbest) >= 1 total_scores = [] best_non_null_entry = None for entry in nbest: total_scores.append(entry.start_logit + entry.end_logit) if not best_non_null_entry: if entry.text: best_non_null_entry = entry probs = _compute_softmax(total_scores) nbest_json = [] for (i, entry) in enumerate(nbest): output = collections.OrderedDict() output["text"] = entry.text output["probability"] = probs[i] output["start_logit"] = entry.start_logit output["end_logit"] = entry.end_logit nbest_json.append(output) assert len(nbest_json) >= 1 if not version_2_with_negative: all_predictions[example.qas_id] = nbest_json[0]["text"] else: # predict "" iff the null score - the score of best non-null > threshold score_diff = ( score_null - best_non_null_entry.start_logit - (best_non_null_entry.end_logit) ) scores_diff_json[example.qas_id] = score_diff if score_diff > null_score_diff_threshold: all_predictions[example.qas_id] = "" else: all_predictions[example.qas_id] = best_non_null_entry.text all_nbest_json[example.qas_id] = nbest_json with open(output_prediction_file, "w") as writer: writer.write(json.dumps(all_predictions, indent=4) + "\n") with open(output_nbest_file, "w") as writer: writer.write(json.dumps(all_nbest_json, indent=4) + "\n") if version_2_with_negative: with open(output_null_log_odds_file, "w") as writer: writer.write(json.dumps(scores_diff_json, indent=4) + "\n") return all_predictions, all_nbest_json, scores_diff_json
[ "def", "write_predictions", "(", "all_examples", ",", "all_features", ",", "all_results", ",", "n_best_size", ",", "max_answer_length", ",", "do_lower_case", ",", "output_prediction_file", ",", "output_nbest_file", ",", "output_null_log_odds_file", ",", "verbose_logging", ...
https://github.com/ThilinaRajapakse/simpletransformers/blob/9323c0398baea0157044e080617b2c4be59de7a9/simpletransformers/question_answering/question_answering_utils.py#L915-L1130
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/tione/v20191022/models.py
python
VpcConfig.__init__
(self)
r""" :param SecurityGroupIds: 安全组id 注意:此字段可能返回 null,表示取不到有效值。 :type SecurityGroupIds: list of str :param SubnetId: 子网id 注意:此字段可能返回 null,表示取不到有效值。 :type SubnetId: str
r""" :param SecurityGroupIds: 安全组id 注意:此字段可能返回 null,表示取不到有效值。 :type SecurityGroupIds: list of str :param SubnetId: 子网id 注意:此字段可能返回 null,表示取不到有效值。 :type SubnetId: str
[ "r", ":", "param", "SecurityGroupIds", ":", "安全组id", "注意:此字段可能返回", "null,表示取不到有效值。", ":", "type", "SecurityGroupIds", ":", "list", "of", "str", ":", "param", "SubnetId", ":", "子网id", "注意:此字段可能返回", "null,表示取不到有效值。", ":", "type", "SubnetId", ":", "str" ]
def __init__(self): r""" :param SecurityGroupIds: 安全组id 注意:此字段可能返回 null,表示取不到有效值。 :type SecurityGroupIds: list of str :param SubnetId: 子网id 注意:此字段可能返回 null,表示取不到有效值。 :type SubnetId: str """ self.SecurityGroupIds = None self.SubnetId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "SecurityGroupIds", "=", "None", "self", ".", "SubnetId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/tione/v20191022/models.py#L2462-L2472
PyHDI/Pyverilog
2a42539bebd1b4587ee577d491ff002d0cc7295d
pyverilog/vparser/parser.py
python
VerilogParser.p_expression_minus
(self, p)
expression : expression MINUS expression
expression : expression MINUS expression
[ "expression", ":", "expression", "MINUS", "expression" ]
def p_expression_minus(self, p): 'expression : expression MINUS expression' p[0] = Minus(p[1], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_expression_minus", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "Minus", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", "0", ...
https://github.com/PyHDI/Pyverilog/blob/2a42539bebd1b4587ee577d491ff002d0cc7295d/pyverilog/vparser/parser.py#L1028-L1031
HunterMcGushion/hyperparameter_hunter
28b1d48e01a993818510811b82a677e0a7a232b2
hyperparameter_hunter/space/space_core.py
python
Space.rvs
(self, n_samples=1, random_state=None)
return rows
Draw random samples. Samples are in the original (untransformed) space. They must be transformed before being passed to a model or minimizer via :meth:`transform` Parameters ---------- n_samples: Int, default=1 Number of samples to be drawn from the space random_state: Int, RandomState, or None, default=None Set random state to something other than None for reproducible results Returns ------- List Randomly drawn samples from the original space. Will be a list of lists, of shape (`n_samples`, :attr:`n_dims`)
Draw random samples. Samples are in the original (untransformed) space. They must be transformed before being passed to a model or minimizer via :meth:`transform`
[ "Draw", "random", "samples", ".", "Samples", "are", "in", "the", "original", "(", "untransformed", ")", "space", ".", "They", "must", "be", "transformed", "before", "being", "passed", "to", "a", "model", "or", "minimizer", "via", ":", "meth", ":", "transfo...
def rvs(self, n_samples=1, random_state=None): """Draw random samples. Samples are in the original (untransformed) space. They must be transformed before being passed to a model or minimizer via :meth:`transform` Parameters ---------- n_samples: Int, default=1 Number of samples to be drawn from the space random_state: Int, RandomState, or None, default=None Set random state to something other than None for reproducible results Returns ------- List Randomly drawn samples from the original space. Will be a list of lists, of shape (`n_samples`, :attr:`n_dims`)""" rng = check_random_state(random_state) #################### Draw #################### columns = [] for dim in self.dimensions: new_val = None try: if sp_version < (0, 16): new_val = dim.rvs(n_samples=n_samples) else: new_val = dim.rvs(n_samples=n_samples, random_state=rng) except TypeError: # `'<' not supported between instances of 'Version' and 'str'` new_val = dim.rvs(n_samples=n_samples, random_state=rng) finally: columns.append(new_val) #################### Transpose #################### rows = [] # TODO: Use `np.transpose`? Might that screw up the dimension types (mostly `Categorical`) for i in range(n_samples): r = [] for j in range(self.n_dims): r.append(columns[j][i]) rows.append(r) return rows
[ "def", "rvs", "(", "self", ",", "n_samples", "=", "1", ",", "random_state", "=", "None", ")", ":", "rng", "=", "check_random_state", "(", "random_state", ")", "#################### Draw ####################", "columns", "=", "[", "]", "for", "dim", "in", "self...
https://github.com/HunterMcGushion/hyperparameter_hunter/blob/28b1d48e01a993818510811b82a677e0a7a232b2/hyperparameter_hunter/space/space_core.py#L178-L221
mylar3/mylar3
fce4771c5b627f8de6868dd4ab6bc53f7b22d303
lib/transmissionrpc/torrent.py
python
Torrent._get_seed_idle_limit
(self)
return self._fields['seedIdleLimit'].value
Get the seed idle limit in minutes.
Get the seed idle limit in minutes.
[ "Get", "the", "seed", "idle", "limit", "in", "minutes", "." ]
def _get_seed_idle_limit(self): """ Get the seed idle limit in minutes. """ return self._fields['seedIdleLimit'].value
[ "def", "_get_seed_idle_limit", "(", "self", ")", ":", "return", "self", ".", "_fields", "[", "'seedIdleLimit'", "]", ".", "value" ]
https://github.com/mylar3/mylar3/blob/fce4771c5b627f8de6868dd4ab6bc53f7b22d303/lib/transmissionrpc/torrent.py#L312-L316
epiception/CalibNet
a4ae349867d6bbf13a4add671b1cb2636eb29e6f
code/utils/pointnet_util.py
python
sample_and_group
(npoint, radius, nsample, xyz, points, tnet_spec=None, knn=False, use_xyz=True)
return new_xyz, new_points, idx, grouped_xyz
Input: npoint: int32 radius: float32 nsample: int32 xyz: (batch_size, ndataset, 3) TF tensor points: (batch_size, ndataset, channel) TF tensor, if None will just use xyz as points tnet_spec: dict (keys: mlp, mlp2, is_training, bn_decay), if None do not apply tnet knn: bool, if True use kNN instead of radius search use_xyz: bool, if True concat XYZ with local point features, otherwise just use point features Output: new_xyz: (batch_size, npoint, 3) TF tensor new_points: (batch_size, npoint, nsample, 3+channel) TF tensor idx: (batch_size, npoint, nsample) TF tensor, indices of local points as in ndataset points grouped_xyz: (batch_size, npoint, nsample, 3) TF tensor, normalized point XYZs (subtracted by seed point XYZ) in local regions
Input: npoint: int32 radius: float32 nsample: int32 xyz: (batch_size, ndataset, 3) TF tensor points: (batch_size, ndataset, channel) TF tensor, if None will just use xyz as points tnet_spec: dict (keys: mlp, mlp2, is_training, bn_decay), if None do not apply tnet knn: bool, if True use kNN instead of radius search use_xyz: bool, if True concat XYZ with local point features, otherwise just use point features Output: new_xyz: (batch_size, npoint, 3) TF tensor new_points: (batch_size, npoint, nsample, 3+channel) TF tensor idx: (batch_size, npoint, nsample) TF tensor, indices of local points as in ndataset points grouped_xyz: (batch_size, npoint, nsample, 3) TF tensor, normalized point XYZs (subtracted by seed point XYZ) in local regions
[ "Input", ":", "npoint", ":", "int32", "radius", ":", "float32", "nsample", ":", "int32", "xyz", ":", "(", "batch_size", "ndataset", "3", ")", "TF", "tensor", "points", ":", "(", "batch_size", "ndataset", "channel", ")", "TF", "tensor", "if", "None", "wil...
def sample_and_group(npoint, radius, nsample, xyz, points, tnet_spec=None, knn=False, use_xyz=True): ''' Input: npoint: int32 radius: float32 nsample: int32 xyz: (batch_size, ndataset, 3) TF tensor points: (batch_size, ndataset, channel) TF tensor, if None will just use xyz as points tnet_spec: dict (keys: mlp, mlp2, is_training, bn_decay), if None do not apply tnet knn: bool, if True use kNN instead of radius search use_xyz: bool, if True concat XYZ with local point features, otherwise just use point features Output: new_xyz: (batch_size, npoint, 3) TF tensor new_points: (batch_size, npoint, nsample, 3+channel) TF tensor idx: (batch_size, npoint, nsample) TF tensor, indices of local points as in ndataset points grouped_xyz: (batch_size, npoint, nsample, 3) TF tensor, normalized point XYZs (subtracted by seed point XYZ) in local regions ''' new_xyz = gather_point(xyz, farthest_point_sample(npoint, xyz)) # (batch_size, npoint, 3) if knn: _,idx = knn_point(nsample, xyz, new_xyz) else: if np.isscalar(radius): idx, pts_cnt = query_ball_point(radius, nsample, xyz, new_xyz) else: idx_list = [] for radius_one, xyz_one, new_xyz_one in zip(tf.unstack(radius,axis=0), tf.unstack(xyz, axis=0),tf.unstack(new_xyz, axis=0)): idx_one, _ = query_ball_point(radius_one, nsample, tf.expand_dims(xyz_one, axis=0), tf.expand_dims(new_xyz_one, axis=0)) idx_list.append(idx_one) idx = tf.stack(idx_list, axis=0) idx = tf.squeeze(idx, axis=1) grouped_xyz = group_point(xyz, idx) # (batch_size, npoint, nsample, 3) grouped_xyz -= tf.tile(tf.expand_dims(new_xyz, 2), [1,1,nsample,1]) # translation normalization if tnet_spec is not None: grouped_xyz = tnet(grouped_xyz, tnet_spec) if points is not None: grouped_points = group_point(points, idx) # (batch_size, npoint, nsample, channel) if use_xyz: # new_points = tf.concat([grouped_xyz, tf.tile(tf.expand_dims(new_xyz, 2), [1,1,nsample,1]),grouped_points], axis=-1) # (batch_size, npoint, nample, 3+channel) new_points = tf.concat([grouped_xyz, grouped_points],axis=-1) # (batch_size, npoint, nample, 3+channel) else: new_points = grouped_points else: # new_points = tf.concat([grouped_xyz, tf.tile(tf.expand_dims(new_xyz, 2), [1,1,nsample,1])], axis=-1) new_points = grouped_xyz return new_xyz, new_points, idx, grouped_xyz
[ "def", "sample_and_group", "(", "npoint", ",", "radius", ",", "nsample", ",", "xyz", ",", "points", ",", "tnet_spec", "=", "None", ",", "knn", "=", "False", ",", "use_xyz", "=", "True", ")", ":", "new_xyz", "=", "gather_point", "(", "xyz", ",", "farthe...
https://github.com/epiception/CalibNet/blob/a4ae349867d6bbf13a4add671b1cb2636eb29e6f/code/utils/pointnet_util.py#L16-L64
d2l-ai/d2l-en
39a7d4174534740b2387b0dc5eb22f409b82ee10
d2l/torch.py
python
masked_softmax
(X, valid_lens)
Perform softmax operation by masking elements on the last axis. Defined in :numref:`sec_attention-scoring-functions`
Perform softmax operation by masking elements on the last axis.
[ "Perform", "softmax", "operation", "by", "masking", "elements", "on", "the", "last", "axis", "." ]
def masked_softmax(X, valid_lens): """Perform softmax operation by masking elements on the last axis. Defined in :numref:`sec_attention-scoring-functions`""" # `X`: 3D tensor, `valid_lens`: 1D or 2D tensor if valid_lens is None: return nn.functional.softmax(X, dim=-1) else: shape = X.shape if valid_lens.dim() == 1: valid_lens = torch.repeat_interleave(valid_lens, shape[1]) else: valid_lens = valid_lens.reshape(-1) # On the last axis, replace masked elements with a very large negative # value, whose exponentiation outputs 0 X = d2l.sequence_mask(X.reshape(-1, shape[-1]), valid_lens, value=-1e6) return nn.functional.softmax(X.reshape(shape), dim=-1)
[ "def", "masked_softmax", "(", "X", ",", "valid_lens", ")", ":", "# `X`: 3D tensor, `valid_lens`: 1D or 2D tensor", "if", "valid_lens", "is", "None", ":", "return", "nn", ".", "functional", ".", "softmax", "(", "X", ",", "dim", "=", "-", "1", ")", "else", ":"...
https://github.com/d2l-ai/d2l-en/blob/39a7d4174534740b2387b0dc5eb22f409b82ee10/d2l/torch.py#L957-L974
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
lib-python/3.5.1/logging/__init__.py
python
Logger.findCaller
(self, stack_info=False)
return rv
Find the stack frame of the caller so that we can note the source file name, line number and function name.
Find the stack frame of the caller so that we can note the source file name, line number and function name.
[ "Find", "the", "stack", "frame", "of", "the", "caller", "so", "that", "we", "can", "note", "the", "source", "file", "name", "line", "number", "and", "function", "name", "." ]
def findCaller(self, stack_info=False): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ f = currentframe() #On some versions of IronPython, currentframe() returns None if #IronPython isn't run with -X:Frames. if f is not None: f = f.f_back rv = "(unknown file)", 0, "(unknown function)", None while hasattr(f, "f_code"): co = f.f_code filename = os.path.normcase(co.co_filename) if filename == _srcfile: f = f.f_back continue sinfo = None if stack_info: sio = io.StringIO() sio.write('Stack (most recent call last):\n') traceback.print_stack(f, file=sio) sinfo = sio.getvalue() if sinfo[-1] == '\n': sinfo = sinfo[:-1] sio.close() rv = (co.co_filename, f.f_lineno, co.co_name, sinfo) break return rv
[ "def", "findCaller", "(", "self", ",", "stack_info", "=", "False", ")", ":", "f", "=", "currentframe", "(", ")", "#On some versions of IronPython, currentframe() returns None if", "#IronPython isn't run with -X:Frames.", "if", "f", "is", "not", "None", ":", "f", "=", ...
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/logging/__init__.py#L1347-L1375
choasup/SIN
4851efb7b1c64180026e51ab8abcd95265c0602c
lib/datasets/kitti_tracking.py
python
kitti_tracking._get_default_path
(self)
return os.path.join(datasets.ROOT_DIR, 'data', 'KITTI_Tracking')
Return the default path where kitti_tracking is expected to be installed.
Return the default path where kitti_tracking is expected to be installed.
[ "Return", "the", "default", "path", "where", "kitti_tracking", "is", "expected", "to", "be", "installed", "." ]
def _get_default_path(self): """ Return the default path where kitti_tracking is expected to be installed. """ return os.path.join(datasets.ROOT_DIR, 'data', 'KITTI_Tracking')
[ "def", "_get_default_path", "(", "self", ")", ":", "return", "os", ".", "path", ".", "join", "(", "datasets", ".", "ROOT_DIR", ",", "'data'", ",", "'KITTI_Tracking'", ")" ]
https://github.com/choasup/SIN/blob/4851efb7b1c64180026e51ab8abcd95265c0602c/lib/datasets/kitti_tracking.py#L126-L130
n1nj4sec/pupy
a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39
pupy/packages/linux/all/usniper.py
python
start
(path, addr, reg='ax', ret=False, cast=None, argtype='chr', event_id=None)
return pupy.manager.create( USniper, path, addr, reg, ret, cast, argtype, event_id=event_id ) is not None
[]
def start(path, addr, reg='ax', ret=False, cast=None, argtype='chr', event_id=None): try: if pupy.manager.active(USniper): return False except: try: pupy.manager.stop(USniper) except: pass if argtype and hasattr(builtins, argtype): argtype = getattr(builtins, argtype) else: argtype = None return pupy.manager.create( USniper, path, addr, reg, ret, cast, argtype, event_id=event_id ) is not None
[ "def", "start", "(", "path", ",", "addr", ",", "reg", "=", "'ax'", ",", "ret", "=", "False", ",", "cast", "=", "None", ",", "argtype", "=", "'chr'", ",", "event_id", "=", "None", ")", ":", "try", ":", "if", "pupy", ".", "manager", ".", "active", ...
https://github.com/n1nj4sec/pupy/blob/a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39/pupy/packages/linux/all/usniper.py#L189-L207
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/compilers/mixins/arm.py
python
ArmclangCompiler.compute_parameters_with_absolute_paths
(self, parameter_list: T.List[str], build_dir: str)
return parameter_list
[]
def compute_parameters_with_absolute_paths(self, parameter_list: T.List[str], build_dir: str) -> T.List[str]: for idx, i in enumerate(parameter_list): if i[:2] == '-I' or i[:2] == '-L': parameter_list[idx] = i[:2] + os.path.normpath(os.path.join(build_dir, i[2:])) return parameter_list
[ "def", "compute_parameters_with_absolute_paths", "(", "self", ",", "parameter_list", ":", "T", ".", "List", "[", "str", "]", ",", "build_dir", ":", "str", ")", "->", "T", ".", "List", "[", "str", "]", ":", "for", "idx", ",", "i", "in", "enumerate", "("...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/compilers/mixins/arm.py#L185-L190
xflr6/graphviz
b764c3a3a62fc3b514ce4866a179819b377bad90
graphviz/_tools.py
python
mkdirs
(filename, *, mode: int = 0o777)
Recursively create directories up to the path of ``filename`` as needed.
Recursively create directories up to the path of ``filename`` as needed.
[ "Recursively", "create", "directories", "up", "to", "the", "path", "of", "filename", "as", "needed", "." ]
def mkdirs(filename, *, mode: int = 0o777) -> None: """Recursively create directories up to the path of ``filename`` as needed.""" dirname = os.path.dirname(filename) if not dirname: return log.debug('os.makedirs(%r)', dirname) os.makedirs(dirname, mode=mode, exist_ok=True)
[ "def", "mkdirs", "(", "filename", ",", "*", ",", "mode", ":", "int", "=", "0o777", ")", "->", "None", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "if", "not", "dirname", ":", "return", "log", ".", "debug", "(", "...
https://github.com/xflr6/graphviz/blob/b764c3a3a62fc3b514ce4866a179819b377bad90/graphviz/_tools.py#L42-L49
CCExtractor/vardbg
8baabb93d2e8afccc5ee837bd8301a5f765635c2
vardbg/output/video_writer/text_format.py
python
_irepr_dict
(painter, dct, highlight_key=None, *args, **kwargs)
return elem_pos
[]
def _irepr_dict(painter, dct, highlight_key=None, *args, **kwargs): # Initialize state painter.write("{") elem_pos = None for idx, (key, elem) in enumerate(dct.items()): # Add comma separator if this isn't the first element if idx > 0: painter.write(", ") # Add key first (no need to record this) painter.write(repr(key) + ": ") # If this is our candidate element, if key == highlight_key: # Record the position and pass highlight flags elem_pos = painter.write(repr(elem), *args, **kwargs) else: painter.write(repr(elem)) # Finalize string last_pos = painter.write("}") # Mark end as highlighted target if not found if elem_pos is None: elem_pos = last_pos # Return indices return elem_pos
[ "def", "_irepr_dict", "(", "painter", ",", "dct", ",", "highlight_key", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Initialize state", "painter", ".", "write", "(", "\"{\"", ")", "elem_pos", "=", "None", "for", "idx", ",", "(",...
https://github.com/CCExtractor/vardbg/blob/8baabb93d2e8afccc5ee837bd8301a5f765635c2/vardbg/output/video_writer/text_format.py#L32-L60
django/django
0a17666045de6739ae1c2ac695041823d5f827f7
django/views/decorators/debug.py
python
sensitive_post_parameters
(*parameters)
return decorator
Indicate which POST parameters used in the decorated view are sensitive, so that those parameters can later be treated in a special way, for example by hiding them when logging unhandled exceptions. Accept two forms: * with specified parameters: @sensitive_post_parameters('password', 'credit_card') def my_view(request): pw = request.POST['password'] cc = request.POST['credit_card'] ... * without any specified parameters, in which case consider all variables are sensitive: @sensitive_post_parameters() def my_view(request) ...
Indicate which POST parameters used in the decorated view are sensitive, so that those parameters can later be treated in a special way, for example by hiding them when logging unhandled exceptions.
[ "Indicate", "which", "POST", "parameters", "used", "in", "the", "decorated", "view", "are", "sensitive", "so", "that", "those", "parameters", "can", "later", "be", "treated", "in", "a", "special", "way", "for", "example", "by", "hiding", "them", "when", "log...
def sensitive_post_parameters(*parameters): """ Indicate which POST parameters used in the decorated view are sensitive, so that those parameters can later be treated in a special way, for example by hiding them when logging unhandled exceptions. Accept two forms: * with specified parameters: @sensitive_post_parameters('password', 'credit_card') def my_view(request): pw = request.POST['password'] cc = request.POST['credit_card'] ... * without any specified parameters, in which case consider all variables are sensitive: @sensitive_post_parameters() def my_view(request) ... """ if len(parameters) == 1 and callable(parameters[0]): raise TypeError( 'sensitive_post_parameters() must be called to use it as a ' 'decorator, e.g., use @sensitive_post_parameters(), not ' '@sensitive_post_parameters.' ) def decorator(view): @functools.wraps(view) def sensitive_post_parameters_wrapper(request, *args, **kwargs): if not isinstance(request, HttpRequest): raise TypeError( "sensitive_post_parameters didn't receive an HttpRequest " "object. If you are decorating a classmethod, make sure " "to use @method_decorator." ) if parameters: request.sensitive_post_parameters = parameters else: request.sensitive_post_parameters = '__ALL__' return view(request, *args, **kwargs) return sensitive_post_parameters_wrapper return decorator
[ "def", "sensitive_post_parameters", "(", "*", "parameters", ")", ":", "if", "len", "(", "parameters", ")", "==", "1", "and", "callable", "(", "parameters", "[", "0", "]", ")", ":", "raise", "TypeError", "(", "'sensitive_post_parameters() must be called to use it a...
https://github.com/django/django/blob/0a17666045de6739ae1c2ac695041823d5f827f7/django/views/decorators/debug.py#L47-L92
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/programy/clients/config.py
python
ClientConfigurationData.storage
(self)
return self._storage
[]
def storage(self): return self._storage
[ "def", "storage", "(", "self", ")", ":", "return", "self", ".", "_storage" ]
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/clients/config.py#L68-L69
horstjens/ThePythonGameBook
e9be46cb519c65379c0d2c59d6434f2fa61b1232
en/pygame/003_static_blit_pretty_template_005.py
python
FlyingObject.wallcheck
(self)
check if Sprite is touching screen edge
check if Sprite is touching screen edge
[ "check", "if", "Sprite", "is", "touching", "screen", "edge" ]
def wallcheck(self): """check if Sprite is touching screen edge""" if self.kill_on_edge: if self.pos[0] - self.width // 2 < 0 or self.pos[1] - self.height // 2 < 0 or self.pos[0] + self.width //2 > PygView.width or self.pos[1] + self.height // 2 > PygView.height: self.kill() elif self.bounce_on_edge: h = pygame.math.Vector2(1,0) # ... horizontal vector v = pygame.math.Vector2(0,1) # ... vertical vector if self.pos[0] - self.width // 2 < 0: self.reflect(h) elif self.pos[0] + self.width // 2 > PygView.width: self.reflect(h) if self.pos[1] + self.height // 2 > 0: self.reflect(v) elif self.pos[1] - self.height // 2 < -PygView.height: self.reflect(v)
[ "def", "wallcheck", "(", "self", ")", ":", "if", "self", ".", "kill_on_edge", ":", "if", "self", ".", "pos", "[", "0", "]", "-", "self", ".", "width", "//", "2", "<", "0", "or", "self", ".", "pos", "[", "1", "]", "-", "self", ".", "height", "...
https://github.com/horstjens/ThePythonGameBook/blob/e9be46cb519c65379c0d2c59d6434f2fa61b1232/en/pygame/003_static_blit_pretty_template_005.py#L134-L149
shiyanlou/louplus-python
4c61697259e286e3d9116c3299f170d019ba3767
Python 进阶挑战(旧)/05-income-tax-calculator-use-modules/calculator.py
python
Config.social_insurance_baseline_low
(self)
return self._get_config('JiShuL')
获取社保基数下限
获取社保基数下限
[ "获取社保基数下限" ]
def social_insurance_baseline_low(self): """ 获取社保基数下限 """ return self._get_config('JiShuL')
[ "def", "social_insurance_baseline_low", "(", "self", ")", ":", "return", "self", ".", "_get_config", "(", "'JiShuL'", ")" ]
https://github.com/shiyanlou/louplus-python/blob/4c61697259e286e3d9116c3299f170d019ba3767/Python 进阶挑战(旧)/05-income-tax-calculator-use-modules/calculator.py#L147-L152
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/plugins/view/citationtreeview.py
python
CitationTreeView.get_default_gramplets
(self)
return (("Citation Filter",), ("Citation Gallery", "Citation Notes", "Citation Backlinks"))
Define the default gramplets for the sidebar and bottombar.
Define the default gramplets for the sidebar and bottombar.
[ "Define", "the", "default", "gramplets", "for", "the", "sidebar", "and", "bottombar", "." ]
def get_default_gramplets(self): """ Define the default gramplets for the sidebar and bottombar. """ return (("Citation Filter",), ("Citation Gallery", "Citation Notes", "Citation Backlinks"))
[ "def", "get_default_gramplets", "(", "self", ")", ":", "return", "(", "(", "\"Citation Filter\"", ",", ")", ",", "(", "\"Citation Gallery\"", ",", "\"Citation Notes\"", ",", "\"Citation Backlinks\"", ")", ")" ]
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/plugins/view/citationtreeview.py#L757-L764
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/plat-unixware7/IN.py
python
GET_TIME
(timep)
return
[]
def GET_TIME(timep): return
[ "def", "GET_TIME", "(", "timep", ")", ":", "return" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/plat-unixware7/IN.py#L426-L426
michaelliao/sinaweibopy
eb5298ad84ea774bf2006f28b6158a9a05d723e5
weibo.py
python
_Executable.__call__
(self, **kw)
return _http_call('%s%s.json' % (self._client.api_url, self._path), method, self._client.access_token, **kw)
[]
def __call__(self, **kw): method = _METHOD_MAP[self._method] if method == _HTTP_POST and 'pic' in kw: method = _HTTP_UPLOAD return _http_call('%s%s.json' % (self._client.api_url, self._path), method, self._client.access_token, **kw)
[ "def", "__call__", "(", "self", ",", "*", "*", "kw", ")", ":", "method", "=", "_METHOD_MAP", "[", "self", ".", "_method", "]", "if", "method", "==", "_HTTP_POST", "and", "'pic'", "in", "kw", ":", "method", "=", "_HTTP_UPLOAD", "return", "_http_call", "...
https://github.com/michaelliao/sinaweibopy/blob/eb5298ad84ea774bf2006f28b6158a9a05d723e5/weibo.py#L323-L327
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/interpreter/dependencyfallbacks.py
python
DependencyFallbacksHolder._get_cached_dep
(self, name: str, kwargs: TYPE_nkwargs)
return None
[]
def _get_cached_dep(self, name: str, kwargs: TYPE_nkwargs) -> T.Optional[Dependency]: # Unlike other methods, this one returns not-found dependency instead # of None in the case the dependency is cached as not-found, or if cached # version does not match. In that case we don't want to continue with # other candidates. for_machine = self.interpreter.machine_from_native_kwarg(kwargs) identifier = dependencies.get_dep_identifier(name, kwargs) wanted_vers = stringlistify(kwargs.get('version', [])) override = self.build.dependency_overrides[for_machine].get(identifier) if override: info = [mlog.blue('(overridden)' if override.explicit else '(cached)')] cached_dep = override.dep # We don't implicitly override not-found dependencies, but user could # have explicitly called meson.override_dependency() with a not-found # dep. if not cached_dep.found(): mlog.log('Dependency', mlog.bold(self.display_name), 'found:', mlog.red('NO'), *info) return cached_dep else: info = [mlog.blue('(cached)')] cached_dep = self.coredata.deps[for_machine].get(identifier) if cached_dep: found_vers = cached_dep.get_version() if not self._check_version(wanted_vers, found_vers): if not override: # We cached this dependency on disk from a previous run, # but it could got updated on the system in the meantime. return None mlog.log('Dependency', mlog.bold(name), 'found:', mlog.red('NO'), 'found', mlog.normal_cyan(found_vers), 'but need:', mlog.bold(', '.join([f"'{e}'" for e in wanted_vers])), *info) return self._notfound_dependency() if found_vers: info = [mlog.normal_cyan(found_vers), *info] mlog.log('Dependency', mlog.bold(self.display_name), 'found:', mlog.green('YES'), *info) return cached_dep return None
[ "def", "_get_cached_dep", "(", "self", ",", "name", ":", "str", ",", "kwargs", ":", "TYPE_nkwargs", ")", "->", "T", ".", "Optional", "[", "Dependency", "]", ":", "# Unlike other methods, this one returns not-found dependency instead", "# of None in the case the dependency...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/interpreter/dependencyfallbacks.py#L195-L237
hupili/snsapi
129529b89f38cbee253a23e5ed31dae2a0ea4254
snsapi/third/twitter.py
python
User.NewFromJsonDict
(data)
return User(id=data.get('id', None), name=data.get('name', None), screen_name=data.get('screen_name', None), location=data.get('location', None), description=data.get('description', None), statuses_count=data.get('statuses_count', None), followers_count=data.get('followers_count', None), favourites_count=data.get('favourites_count', None), friends_count=data.get('friends_count', None), profile_image_url=data.get('profile_image_url_https', data.get('profile_image_url', None)), profile_background_tile = data.get('profile_background_tile', None), profile_background_image_url = data.get('profile_background_image_url', None), profile_sidebar_fill_color = data.get('profile_sidebar_fill_color', None), profile_background_color = data.get('profile_background_color', None), profile_link_color = data.get('profile_link_color', None), profile_text_color = data.get('profile_text_color', None), protected = data.get('protected', None), utc_offset = data.get('utc_offset', None), time_zone = data.get('time_zone', None), url=data.get('url', None), status=status, geo_enabled=data.get('geo_enabled', None), verified=data.get('verified', None), lang=data.get('lang', None), notifications=data.get('notifications', None), contributors_enabled=data.get('contributors_enabled', None), created_at=data.get('created_at', None), listed_count=data.get('listed_count', None))
Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.User instance
Create a new instance based on a JSON dict.
[ "Create", "a", "new", "instance", "based", "on", "a", "JSON", "dict", "." ]
def NewFromJsonDict(data): '''Create a new instance based on a JSON dict. Args: data: A JSON dict, as converted from the JSON in the twitter API Returns: A twitter.User instance ''' if 'status' in data: status = Status.NewFromJsonDict(data['status']) else: status = None return User(id=data.get('id', None), name=data.get('name', None), screen_name=data.get('screen_name', None), location=data.get('location', None), description=data.get('description', None), statuses_count=data.get('statuses_count', None), followers_count=data.get('followers_count', None), favourites_count=data.get('favourites_count', None), friends_count=data.get('friends_count', None), profile_image_url=data.get('profile_image_url_https', data.get('profile_image_url', None)), profile_background_tile = data.get('profile_background_tile', None), profile_background_image_url = data.get('profile_background_image_url', None), profile_sidebar_fill_color = data.get('profile_sidebar_fill_color', None), profile_background_color = data.get('profile_background_color', None), profile_link_color = data.get('profile_link_color', None), profile_text_color = data.get('profile_text_color', None), protected = data.get('protected', None), utc_offset = data.get('utc_offset', None), time_zone = data.get('time_zone', None), url=data.get('url', None), status=status, geo_enabled=data.get('geo_enabled', None), verified=data.get('verified', None), lang=data.get('lang', None), notifications=data.get('notifications', None), contributors_enabled=data.get('contributors_enabled', None), created_at=data.get('created_at', None), listed_count=data.get('listed_count', None))
[ "def", "NewFromJsonDict", "(", "data", ")", ":", "if", "'status'", "in", "data", ":", "status", "=", "Status", ".", "NewFromJsonDict", "(", "data", "[", "'status'", "]", ")", "else", ":", "status", "=", "None", "return", "User", "(", "id", "=", "data",...
https://github.com/hupili/snsapi/blob/129529b89f38cbee253a23e5ed31dae2a0ea4254/snsapi/third/twitter.py#L1468-L1509
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/pandas-0.17.0-py3.3-win-amd64.egg/pandas/tseries/period.py
python
PeriodIndex.dtype_str
(self)
return self.inferred_type
return the dtype str of the underlying data
return the dtype str of the underlying data
[ "return", "the", "dtype", "str", "of", "the", "underlying", "data" ]
def dtype_str(self): """ return the dtype str of the underlying data """ return self.inferred_type
[ "def", "dtype_str", "(", "self", ")", ":", "return", "self", ".", "inferred_type" ]
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/pandas-0.17.0-py3.3-win-amd64.egg/pandas/tseries/period.py#L586-L588
MozillaSecurity/grizzly
1c41478e32f323189a2c322ec041c3e0902a158a
grizzly/target/assets.py
python
AssetManager.__exit__
(self, *exc)
[]
def __exit__(self, *exc): self.cleanup()
[ "def", "__exit__", "(", "self", ",", "*", "exc", ")", ":", "self", ".", "cleanup", "(", ")" ]
https://github.com/MozillaSecurity/grizzly/blob/1c41478e32f323189a2c322ec041c3e0902a158a/grizzly/target/assets.py#L33-L34
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/multiprocessing/managers.py
python
Server.accepter
(self)
[]
def accepter(self): while True: try: c = self.listener.accept() except OSError: continue t = threading.Thread(target=self.handle_request, args=(c,)) t.daemon = True t.start()
[ "def", "accepter", "(", "self", ")", ":", "while", "True", ":", "try", ":", "c", "=", "self", ".", "listener", ".", "accept", "(", ")", "except", "OSError", ":", "continue", "t", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "ha...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/multiprocessing/managers.py#L169-L177
gammapy/gammapy
735b25cd5bbed35e2004d633621896dcd5295e8b
gammapy/maps/hpx/utils.py
python
parse_hpxregion
(region)
Parse the ``HPX_REG`` header keyword into a list of tokens.
Parse the ``HPX_REG`` header keyword into a list of tokens.
[ "Parse", "the", "HPX_REG", "header", "keyword", "into", "a", "list", "of", "tokens", "." ]
def parse_hpxregion(region): """Parse the ``HPX_REG`` header keyword into a list of tokens.""" m = re.match(r"([A-Za-z\_]*?)\((.*?)\)", region) if m is None: raise ValueError(f"Failed to parse hpx region string: {region!r}") if not m.group(1): return re.split(",", m.group(2)) else: return [m.group(1)] + re.split(",", m.group(2))
[ "def", "parse_hpxregion", "(", "region", ")", ":", "m", "=", "re", ".", "match", "(", "r\"([A-Za-z\\_]*?)\\((.*?)\\)\"", ",", "region", ")", "if", "m", "is", "None", ":", "raise", "ValueError", "(", "f\"Failed to parse hpx region string: {region!r}\"", ")", "if", ...
https://github.com/gammapy/gammapy/blob/735b25cd5bbed35e2004d633621896dcd5295e8b/gammapy/maps/hpx/utils.py#L128-L138
cylc/cylc-flow
5ec221143476c7c616c156b74158edfbcd83794a
cylc/flow/exceptions.py
python
HostSelectException.__str__
(self)
return ret
[]
def __str__(self): ret = 'Could not select host from:' for host, data in sorted(self.data.items()): ret += f'\n {host}:' for key, value in data.items(): ret += f'\n {key}: {value}' return ret
[ "def", "__str__", "(", "self", ")", ":", "ret", "=", "'Could not select host from:'", "for", "host", ",", "data", "in", "sorted", "(", "self", ".", "data", ".", "items", "(", ")", ")", ":", "ret", "+=", "f'\\n {host}:'", "for", "key", ",", "value", ...
https://github.com/cylc/cylc-flow/blob/5ec221143476c7c616c156b74158edfbcd83794a/cylc/flow/exceptions.py#L314-L320
gkrizek/bash-lambda-layer
703b0ade8174022d44779d823172ab7ac33a5505
bin/docutils/statemachine.py
python
_exception_data
()
return (type.__name__, value, code.co_filename, traceback.tb_lineno, code.co_name)
Return exception information: - the exception's class name; - the exception object; - the name of the file containing the offending code; - the line number of the offending code; - the function name of the offending code.
Return exception information:
[ "Return", "exception", "information", ":" ]
def _exception_data(): """ Return exception information: - the exception's class name; - the exception object; - the name of the file containing the offending code; - the line number of the offending code; - the function name of the offending code. """ type, value, traceback = sys.exc_info() while traceback.tb_next: traceback = traceback.tb_next code = traceback.tb_frame.f_code return (type.__name__, value, code.co_filename, traceback.tb_lineno, code.co_name)
[ "def", "_exception_data", "(", ")", ":", "type", ",", "value", ",", "traceback", "=", "sys", ".", "exc_info", "(", ")", "while", "traceback", ".", "tb_next", ":", "traceback", "=", "traceback", ".", "tb_next", "code", "=", "traceback", ".", "tb_frame", "...
https://github.com/gkrizek/bash-lambda-layer/blob/703b0ade8174022d44779d823172ab7ac33a5505/bin/docutils/statemachine.py#L1523-L1538
bashtage/arch
05fcc86500603352fb3e6035230a83d99e07fdc1
arch/univariate/distribution.py
python
Distribution.parameter_names
(self)
Names of distribution shape parameters Returns ------- names : list (str) Parameter names
Names of distribution shape parameters
[ "Names", "of", "distribution", "shape", "parameters" ]
def parameter_names(self) -> List[str]: """ Names of distribution shape parameters Returns ------- names : list (str) Parameter names """
[ "def", "parameter_names", "(", "self", ")", "->", "List", "[", "str", "]", ":" ]
https://github.com/bashtage/arch/blob/05fcc86500603352fb3e6035230a83d99e07fdc1/arch/univariate/distribution.py#L253-L261
conda/conda-build
2a19925f2b2ca188f80ffa625cd783e7d403793f
conda_build/jinja_context.py
python
compiler
(language, config, permit_undefined_jinja=False)
return compiler
Support configuration of compilers. This is somewhat platform specific. Native compilers never list their host - it is always implied. Generally, they are metapackages, pointing at a package that does specify the host. These in turn may be metapackages, pointing at a package where the host is the same as the target (both being the native architecture).
Support configuration of compilers. This is somewhat platform specific.
[ "Support", "configuration", "of", "compilers", ".", "This", "is", "somewhat", "platform", "specific", "." ]
def compiler(language, config, permit_undefined_jinja=False): """Support configuration of compilers. This is somewhat platform specific. Native compilers never list their host - it is always implied. Generally, they are metapackages, pointing at a package that does specify the host. These in turn may be metapackages, pointing at a package where the host is the same as the target (both being the native architecture). """ compiler = native_compiler(language, config) version = None if config.variant: target_platform = config.variant.get('target_platform', config.subdir) language_compiler_key = f'{language}_compiler' # fall back to native if language-compiler is not explicitly set in variant compiler = config.variant.get(language_compiler_key, compiler) version = config.variant.get(language_compiler_key + '_version') else: target_platform = config.subdir # support cross compilers. A cross-compiler package will have a name such as # gcc_target # gcc_linux-cos6-64 compiler = '_'.join([compiler, target_platform]) if version: compiler = ' '.join((compiler, version)) compiler = ensure_valid_spec(compiler, warn=False) return compiler
[ "def", "compiler", "(", "language", ",", "config", ",", "permit_undefined_jinja", "=", "False", ")", ":", "compiler", "=", "native_compiler", "(", "language", ",", "config", ")", "version", "=", "None", "if", "config", ".", "variant", ":", "target_platform", ...
https://github.com/conda/conda-build/blob/2a19925f2b2ca188f80ffa625cd783e7d403793f/conda_build/jinja_context.py#L349-L376
lululxvi/deepxde
730c97282636e86c845ce2ba3253482f2178469e
deepxde/data/sampler.py
python
BatchSampler.epochs_completed
(self)
return self._epochs_completed
[]
def epochs_completed(self): return self._epochs_completed
[ "def", "epochs_completed", "(", "self", ")", ":", "return", "self", ".", "_epochs_completed" ]
https://github.com/lululxvi/deepxde/blob/730c97282636e86c845ce2ba3253482f2178469e/deepxde/data/sampler.py#L39-L40
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/spx/sphinxapi.py
python
SphinxClient._GetResponse
(self, sock, client_ver)
return response
INTERNAL METHOD, DO NOT CALL. Gets and checks response packet from searchd server.
INTERNAL METHOD, DO NOT CALL. Gets and checks response packet from searchd server.
[ "INTERNAL", "METHOD", "DO", "NOT", "CALL", ".", "Gets", "and", "checks", "response", "packet", "from", "searchd", "server", "." ]
def _GetResponse (self, sock, client_ver): """ INTERNAL METHOD, DO NOT CALL. Gets and checks response packet from searchd server. """ (status, ver, length) = unpack('>2HL', sock.recv(8)) response = '' left = length while left>0: chunk = sock.recv(left) if chunk: response += chunk left -= len(chunk) else: break if not self._socket: sock.close() # check response read = len(response) if not response or read!=length: if length: self._error = 'failed to read searchd response (status=%s, ver=%s, len=%s, read=%s)' \ % (status, ver, length, read) else: self._error = 'received zero-sized searchd response' return None # check status if status==SEARCHD_WARNING: wend = 4 + unpack ( '>L', response[0:4] )[0] self._warning = response[4:wend] return response[wend:] if status==SEARCHD_ERROR: self._error = 'searchd error: '+response[4:] return None if status==SEARCHD_RETRY: self._error = 'temporary searchd error: '+response[4:] return None if status!=SEARCHD_OK: self._error = 'unknown status code %d' % status return None # check version if ver<client_ver: self._warning = 'searchd command v.%d.%d older than client\'s v.%d.%d, some options might not work' \ % (ver>>8, ver&0xff, client_ver>>8, client_ver&0xff) return response
[ "def", "_GetResponse", "(", "self", ",", "sock", ",", "client_ver", ")", ":", "(", "status", ",", "ver", ",", "length", ")", "=", "unpack", "(", "'>2HL'", ",", "sock", ".", "recv", "(", "8", ")", ")", "response", "=", "''", "left", "=", "length", ...
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/spx/sphinxapi.py#L216-L267
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/Traps/Integrations/PaloAltoNetworks_Traps/PaloAltoNetworks_Traps.py
python
extract_and_validate_http_response
(response, operation_err_message, test=False)
Args: response: raw response operation_err_message: error message to present in case of error test: boolean value, true if test Returns: Error if response is faulty.
[]
def extract_and_validate_http_response(response, operation_err_message, test=False): """ Args: response: raw response operation_err_message: error message to present in case of error test: boolean value, true if test Returns: Error if response is faulty. """ try: response.raise_for_status() return response.json() if not test else response.content except requests.exceptions.HTTPError: try: err_message = response.json().get('message') except Exception: try: err_obj = json.loads(xml2json(response.text)) err_message = demisto.get(err_obj, 'Error.Message') except Exception: err_message = 'Could not parse error' return_error(f'{operation_err_message}: \n{err_message}')
[ "def", "extract_and_validate_http_response", "(", "response", ",", "operation_err_message", ",", "test", "=", "False", ")", ":", "try", ":", "response", ".", "raise_for_status", "(", ")", "return", "response", ".", "json", "(", ")", "if", "not", "test", "else"...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/Traps/Integrations/PaloAltoNetworks_Traps/PaloAltoNetworks_Traps.py#L88-L111
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/ip_messaging/v2/service/channel/webhook.py
python
WebhookInstance.sid
(self)
return self._properties['sid']
:returns: The sid :rtype: unicode
:returns: The sid :rtype: unicode
[ ":", "returns", ":", "The", "sid", ":", "rtype", ":", "unicode" ]
def sid(self): """ :returns: The sid :rtype: unicode """ return self._properties['sid']
[ "def", "sid", "(", "self", ")", ":", "return", "self", ".", "_properties", "[", "'sid'", "]" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/ip_messaging/v2/service/channel/webhook.py#L395-L400
iGio90/Dwarf
bb3011cdffd209c7e3f5febe558053bf649ca69c
dwarf_debugger/ui/widgets/hex_edit.py
python
HexEditor.is_highlighted
(self, address)
return False
Checks if given pos is already colored returns False or highlighttype
Checks if given pos is already colored returns False or highlighttype
[ "Checks", "if", "given", "pos", "is", "already", "colored", "returns", "False", "or", "highlighttype" ]
def is_highlighted(self, address): """ Checks if given pos is already colored returns False or highlighttype """ is_highlight = [ x for x in self._highlights if x.offset <= address <= x.offset + x.length - 1 ] if is_highlight: if is_highlight[0]: return is_highlight[0].what return False
[ "def", "is_highlighted", "(", "self", ",", "address", ")", ":", "is_highlight", "=", "[", "x", "for", "x", "in", "self", ".", "_highlights", "if", "x", ".", "offset", "<=", "address", "<=", "x", ".", "offset", "+", "x", ".", "length", "-", "1", "]"...
https://github.com/iGio90/Dwarf/blob/bb3011cdffd209c7e3f5febe558053bf649ca69c/dwarf_debugger/ui/widgets/hex_edit.py#L706-L718
hvac/hvac
ec048ded30d21c13c21cfa950d148c8bfc1467b0
hvac/api/secrets_engines/transform.py
python
Transform.decode
( self, role_name, value=None, transformation=None, tweak=None, batch_input=None, mount_point=DEFAULT_MOUNT_POINT, )
return self._adapter.post( url=api_path, json=params, )
Decode the provided value using a named role. Supported methods: POST: /{mount_point}/decode/:role_name. :param role_name: the role name to use for this operation. This is specified as part of the URL. :type role_name: str | unicode :param value: the value to be decoded. :type value: str | unicode :param transformation: the transformation within the role that should be used for this decode operation. If a single transformation exists for role, this parameter may be skipped and will be inferred. If multiple transformations exist, one must be specified. :type transformation: str | unicode :param tweak: the tweak source. :type tweak: str | unicode :param batch_input: a list of items to be decoded in a single batch. When this parameter is set, the 'value', 'transformation' and 'tweak' parameters are ignored. Instead, the aforementioned parameters should be provided within each object in the list. :type batch_input: array<object> :param mount_point: The "path" the secrets engine was mounted on. :type mount_point: str | unicode :return: The response of the decode request. :rtype: requests.Response
Decode the provided value using a named role.
[ "Decode", "the", "provided", "value", "using", "a", "named", "role", "." ]
def decode( self, role_name, value=None, transformation=None, tweak=None, batch_input=None, mount_point=DEFAULT_MOUNT_POINT, ): """Decode the provided value using a named role. Supported methods: POST: /{mount_point}/decode/:role_name. :param role_name: the role name to use for this operation. This is specified as part of the URL. :type role_name: str | unicode :param value: the value to be decoded. :type value: str | unicode :param transformation: the transformation within the role that should be used for this decode operation. If a single transformation exists for role, this parameter may be skipped and will be inferred. If multiple transformations exist, one must be specified. :type transformation: str | unicode :param tweak: the tweak source. :type tweak: str | unicode :param batch_input: a list of items to be decoded in a single batch. When this parameter is set, the 'value', 'transformation' and 'tweak' parameters are ignored. Instead, the aforementioned parameters should be provided within each object in the list. :type batch_input: array<object> :param mount_point: The "path" the secrets engine was mounted on. :type mount_point: str | unicode :return: The response of the decode request. :rtype: requests.Response """ params = utils.remove_nones( { "value": value, "transformation": transformation, "tweak": tweak, "batch_input": batch_input, } ) api_path = "/v1/{mount_point}/decode/{role_name}".format( mount_point=mount_point, role_name=role_name, ) return self._adapter.post( url=api_path, json=params, )
[ "def", "decode", "(", "self", ",", "role_name", ",", "value", "=", "None", ",", "transformation", "=", "None", ",", "tweak", "=", "None", ",", "batch_input", "=", "None", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ",", ")", ":", "params", "=", "util...
https://github.com/hvac/hvac/blob/ec048ded30d21c13c21cfa950d148c8bfc1467b0/hvac/api/secrets_engines/transform.py#L716-L767
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/scipy/stats/_multivariate.py
python
invwishart_gen.var
(self, df, scale)
return _squeeze_output(out) if out is not None else out
Variance of the inverse Wishart distribution Only valid if the degrees of freedom are greater than the dimension of the scale matrix plus three. Parameters ---------- %(_doc_default_callparams)s Returns ------- var : float The variance of the distribution
Variance of the inverse Wishart distribution
[ "Variance", "of", "the", "inverse", "Wishart", "distribution" ]
def var(self, df, scale): """ Variance of the inverse Wishart distribution Only valid if the degrees of freedom are greater than the dimension of the scale matrix plus three. Parameters ---------- %(_doc_default_callparams)s Returns ------- var : float The variance of the distribution """ dim, df, scale = self._process_parameters(df, scale) out = self._var(dim, df, scale) return _squeeze_output(out) if out is not None else out
[ "def", "var", "(", "self", ",", "df", ",", "scale", ")", ":", "dim", ",", "df", ",", "scale", "=", "self", ".", "_process_parameters", "(", "df", ",", "scale", ")", "out", "=", "self", ".", "_var", "(", "dim", ",", "df", ",", "scale", ")", "ret...
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/scipy/stats/_multivariate.py#L2465-L2483
ethereum/trinity
6383280c5044feb06695ac2f7bc1100b7bcf4fe0
trinity/chains/light_eventbus.py
python
EventBusLightPeerChain.coro_get_account
(self, block_hash: Hash32, address: Address)
return pass_or_raise( await self.event_bus.request(event, TO_NETWORKING_BROADCAST_CONFIG) ).account
[]
async def coro_get_account(self, block_hash: Hash32, address: Address) -> Account: event = GetAccountRequest(block_hash, address) return pass_or_raise( await self.event_bus.request(event, TO_NETWORKING_BROADCAST_CONFIG) ).account
[ "async", "def", "coro_get_account", "(", "self", ",", "block_hash", ":", "Hash32", ",", "address", ":", "Address", ")", "->", "Account", ":", "event", "=", "GetAccountRequest", "(", "block_hash", ",", "address", ")", "return", "pass_or_raise", "(", "await", ...
https://github.com/ethereum/trinity/blob/6383280c5044feb06695ac2f7bc1100b7bcf4fe0/trinity/chains/light_eventbus.py#L69-L73
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
txdav/common/datastore/sql_notification.py
python
NotificationCollection.notificationObjectRecords
(self)
return NotificationObjectRecord.querysimple(self._txn, notificationHomeResourceID=self.id())
[]
def notificationObjectRecords(self): return NotificationObjectRecord.querysimple(self._txn, notificationHomeResourceID=self.id())
[ "def", "notificationObjectRecords", "(", "self", ")", ":", "return", "NotificationObjectRecord", ".", "querysimple", "(", "self", ".", "_txn", ",", "notificationHomeResourceID", "=", "self", ".", "id", "(", ")", ")" ]
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txdav/common/datastore/sql_notification.py#L347-L348
frappe/erpnext
9d36e30ef7043b391b5ed2523b8288bf46c45d18
erpnext/buying/doctype/supplier_scorecard_variable/supplier_scorecard_variable.py
python
get_rfq_total_items
(scorecard)
return data
Gets the total number of RFQ items sent to supplier
Gets the total number of RFQ items sent to supplier
[ "Gets", "the", "total", "number", "of", "RFQ", "items", "sent", "to", "supplier" ]
def get_rfq_total_items(scorecard): """ Gets the total number of RFQ items sent to supplier""" supplier = frappe.get_doc('Supplier', scorecard.supplier) # Look up all PO Items with delivery dates between our dates data = frappe.db.sql(""" SELECT COUNT(rfq_item.name) as total_rfqs FROM `tabRequest for Quotation Item` rfq_item, `tabRequest for Quotation Supplier` rfq_sup, `tabRequest for Quotation` rfq WHERE rfq_sup.supplier = %(supplier)s AND rfq.transaction_date BETWEEN %(start_date)s AND %(end_date)s AND rfq_item.docstatus = 1 AND rfq_item.parent = rfq.name AND rfq_sup.parent = rfq.name""", {"supplier": supplier.name, "start_date": scorecard.start_date, "end_date": scorecard.end_date}, as_dict=0)[0][0] if not data: data = 0 return data
[ "def", "get_rfq_total_items", "(", "scorecard", ")", ":", "supplier", "=", "frappe", ".", "get_doc", "(", "'Supplier'", ",", "scorecard", ".", "supplier", ")", "# Look up all PO Items with delivery dates between our dates", "data", "=", "frappe", ".", "db", ".", "sq...
https://github.com/frappe/erpnext/blob/9d36e30ef7043b391b5ed2523b8288bf46c45d18/erpnext/buying/doctype/supplier_scorecard_variable/supplier_scorecard_variable.py#L390-L411
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/pkgutil.py
python
get_data
(package, resource)
return loader.get_data(resource_name)
Get a resource from a package. This is a wrapper round the PEP 302 loader get_data API. The package argument should be the name of a package, in standard module format (foo.bar). The resource argument should be in the form of a relative filename, using '/' as the path separator. The parent directory name '..' is not allowed, and nor is a rooted name (starting with a '/'). The function returns a binary string, which is the contents of the specified resource. For packages located in the filesystem, which have already been imported, this is the rough equivalent of d = os.path.dirname(sys.modules[package].__file__) data = open(os.path.join(d, resource), 'rb').read() If the package cannot be located or loaded, or it uses a PEP 302 loader which does not support get_data(), then None is returned.
Get a resource from a package.
[ "Get", "a", "resource", "from", "a", "package", "." ]
def get_data(package, resource): """Get a resource from a package. This is a wrapper round the PEP 302 loader get_data API. The package argument should be the name of a package, in standard module format (foo.bar). The resource argument should be in the form of a relative filename, using '/' as the path separator. The parent directory name '..' is not allowed, and nor is a rooted name (starting with a '/'). The function returns a binary string, which is the contents of the specified resource. For packages located in the filesystem, which have already been imported, this is the rough equivalent of d = os.path.dirname(sys.modules[package].__file__) data = open(os.path.join(d, resource), 'rb').read() If the package cannot be located or loaded, or it uses a PEP 302 loader which does not support get_data(), then None is returned. """ loader = get_loader(package) if loader is None or not hasattr(loader, 'get_data'): return None mod = sys.modules.get(package) or loader.load_module(package) if mod is None or not hasattr(mod, '__file__'): return None # Modify the resource name to be compatible with the loader.get_data # signature - an os.path format "filename" starting with the dirname of # the package's __file__ parts = resource.split('/') parts.insert(0, os.path.dirname(mod.__file__)) resource_name = os.path.join(*parts) return loader.get_data(resource_name)
[ "def", "get_data", "(", "package", ",", "resource", ")", ":", "loader", "=", "get_loader", "(", "package", ")", "if", "loader", "is", "None", "or", "not", "hasattr", "(", "loader", ",", "'get_data'", ")", ":", "return", "None", "mod", "=", "sys", ".", ...
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/pkgutil.py#L548-L583
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py
python
Command.is_local_storage
(self)
return isinstance(self.storage, FileSystemStorage)
[]
def is_local_storage(self): return isinstance(self.storage, FileSystemStorage)
[ "def", "is_local_storage", "(", "self", ")", ":", "return", "isinstance", "(", "self", ".", "storage", ",", "FileSystemStorage", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py#L220-L221
NVIDIA/DeepLearningExamples
589604d49e016cd9ef4525f7abcc9c7b826cfc5e
TensorFlow2/LanguageModeling/BERT/official/nlp/transformer/beam_search_v1.py
python
_expand_to_beam_size
(tensor, beam_size)
return tf.tile(tensor, tile_dims)
Tiles a given tensor by beam_size. Args: tensor: tensor to tile [batch_size, ...] beam_size: How much to tile the tensor by. Returns: Tiled tensor [batch_size, beam_size, ...]
Tiles a given tensor by beam_size.
[ "Tiles", "a", "given", "tensor", "by", "beam_size", "." ]
def _expand_to_beam_size(tensor, beam_size): """Tiles a given tensor by beam_size. Args: tensor: tensor to tile [batch_size, ...] beam_size: How much to tile the tensor by. Returns: Tiled tensor [batch_size, beam_size, ...] """ tensor = tf.expand_dims(tensor, axis=1) tile_dims = [1] * tensor.shape.ndims tile_dims[1] = beam_size return tf.tile(tensor, tile_dims)
[ "def", "_expand_to_beam_size", "(", "tensor", ",", "beam_size", ")", ":", "tensor", "=", "tf", ".", "expand_dims", "(", "tensor", ",", "axis", "=", "1", ")", "tile_dims", "=", "[", "1", "]", "*", "tensor", ".", "shape", ".", "ndims", "tile_dims", "[", ...
https://github.com/NVIDIA/DeepLearningExamples/blob/589604d49e016cd9ef4525f7abcc9c7b826cfc5e/TensorFlow2/LanguageModeling/BERT/official/nlp/transformer/beam_search_v1.py#L557-L571
desbma/sacad
ee7a3da67cb45b3d1f9dda5405dcfed5dccdca47
sacad/sources/base.py
python
CoverSource.unaccentuate
(s)
return "".join(c for c in unicodedata.normalize("NFKD", s) if not unicodedata.combining(c))
Replace accentuated chars in string by their non accentuated equivalent.
Replace accentuated chars in string by their non accentuated equivalent.
[ "Replace", "accentuated", "chars", "in", "string", "by", "their", "non", "accentuated", "equivalent", "." ]
def unaccentuate(s): """ Replace accentuated chars in string by their non accentuated equivalent. """ return "".join(c for c in unicodedata.normalize("NFKD", s) if not unicodedata.combining(c))
[ "def", "unaccentuate", "(", "s", ")", ":", "return", "\"\"", ".", "join", "(", "c", "for", "c", "in", "unicodedata", ".", "normalize", "(", "\"NFKD\"", ",", "s", ")", "if", "not", "unicodedata", ".", "combining", "(", "c", ")", ")" ]
https://github.com/desbma/sacad/blob/ee7a3da67cb45b3d1f9dda5405dcfed5dccdca47/sacad/sources/base.py#L199-L201
clinton-hall/nzbToMedia
27669389216902d1085660167e7bda0bd8527ecf
libs/common/requests/cookies.py
python
RequestsCookieJar.list_paths
(self)
return paths
Utility method to list all the paths in the jar.
Utility method to list all the paths in the jar.
[ "Utility", "method", "to", "list", "all", "the", "paths", "in", "the", "jar", "." ]
def list_paths(self): """Utility method to list all the paths in the jar.""" paths = [] for cookie in iter(self): if cookie.path not in paths: paths.append(cookie.path) return paths
[ "def", "list_paths", "(", "self", ")", ":", "paths", "=", "[", "]", "for", "cookie", "in", "iter", "(", "self", ")", ":", "if", "cookie", ".", "path", "not", "in", "paths", ":", "paths", ".", "append", "(", "cookie", ".", "path", ")", "return", "...
https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/requests/cookies.py#L278-L284
datacenter/acitoolkit
629b84887dd0f0183b81efc8adb16817f985541a
acitoolkit/aciphysobject.py
python
Node._add_vpc_info
(self, working_data)
This method only runs for leaf switches. If the leaf has a VPC peer, the VPC information will be populated and the node.vpc_present flag will be set. check for vpcDom sub-object and if it exists, then create the entry as a dictionary of values. Will first check vpc_inst to see if it is enabled then get vpcDom under vpcInst peer_present is true if vpcDom exists From vpcDom get : domain_id system_mac local_mac monitoring_policy peer_ip peer_system_mac peer_version peer_state vtep_ip vtep_mac oper_role
This method only runs for leaf switches. If the leaf has a VPC peer, the VPC information will be populated and the node.vpc_present flag will be set.
[ "This", "method", "only", "runs", "for", "leaf", "switches", ".", "If", "the", "leaf", "has", "a", "VPC", "peer", "the", "VPC", "information", "will", "be", "populated", "and", "the", "node", ".", "vpc_present", "flag", "will", "be", "set", "." ]
def _add_vpc_info(self, working_data): """ This method only runs for leaf switches. If the leaf has a VPC peer, the VPC information will be populated and the node.vpc_present flag will be set. check for vpcDom sub-object and if it exists, then create the entry as a dictionary of values. Will first check vpc_inst to see if it is enabled then get vpcDom under vpcInst peer_present is true if vpcDom exists From vpcDom get : domain_id system_mac local_mac monitoring_policy peer_ip peer_system_mac peer_version peer_state vtep_ip vtep_mac oper_role """ partial_dn = 'topology/pod-{0}/node-{1}/sys/vpc/inst'.format(self.pod, self.node) vpc_admin_state = 'disabled' data = working_data.get_object(partial_dn) if data: if 'vpcInst' in data: vpc_admin_state = data['vpcInst']['attributes']['adminSt'] result = {'admin_state': vpc_admin_state} if vpc_admin_state == 'enabled': result['oper_state'] = 'inactive' data = working_data.get_subtree('vpcDom', partial_dn) if data: if 'vpcDom' in data[0]: result['oper_state'] = 'active' vpc_dom = data[0]['vpcDom']['attributes'] result['domain_id'] = vpc_dom['id'] result['system_mac'] = vpc_dom['sysMac'] result['local_mac'] = vpc_dom['localMAC'] result['monitoring_policy'] = vpc_dom['monPolDn'] result['peer_ip'] = vpc_dom['peerIp'] result['peer_mac'] = vpc_dom['peerMAC'] result['peer_version'] = vpc_dom['peerVersion'] result['peer_state'] = vpc_dom['peerSt'] result['vtep_ip'] = vpc_dom['virtualIp'] result['vtep_mac'] = vpc_dom['vpcMAC'] result['oper_role'] = vpc_dom['operRole'] else: result['oper_state'] = 'inactive' self.vpc_info = result
[ "def", "_add_vpc_info", "(", "self", ",", "working_data", ")", ":", "partial_dn", "=", "'topology/pod-{0}/node-{1}/sys/vpc/inst'", ".", "format", "(", "self", ".", "pod", ",", "self", ".", "node", ")", "vpc_admin_state", "=", "'disabled'", "data", "=", "working_...
https://github.com/datacenter/acitoolkit/blob/629b84887dd0f0183b81efc8adb16817f985541a/acitoolkit/aciphysobject.py#L1532-L1589
awslabs/aws-ec2rescue-linux
8ecf40e7ea0d2563dac057235803fca2221029d2
lib/s3transfer/download.py
python
IOWriteTask._main
(self, fileobj, data, offset)
Pulls off an io queue to write contents to a file :param f: The file handle to write content to :param data: The data to write :param offset: The offset to write the data to.
Pulls off an io queue to write contents to a file
[ "Pulls", "off", "an", "io", "queue", "to", "write", "contents", "to", "a", "file" ]
def _main(self, fileobj, data, offset): """Pulls off an io queue to write contents to a file :param f: The file handle to write content to :param data: The data to write :param offset: The offset to write the data to. """ fileobj.seek(offset) fileobj.write(data)
[ "def", "_main", "(", "self", ",", "fileobj", ",", "data", ",", "offset", ")", ":", "fileobj", ".", "seek", "(", "offset", ")", "fileobj", ".", "write", "(", "data", ")" ]
https://github.com/awslabs/aws-ec2rescue-linux/blob/8ecf40e7ea0d2563dac057235803fca2221029d2/lib/s3transfer/download.py#L561-L569
asciidisco/plugin.video.netflix
ceb2638a9676f5839250dadfd079b9e4e4bdd759
resources/lib/NetflixHttpSubRessourceHandler.py
python
NetflixHttpSubRessourceHandler.fetch_metadata
(self, params)
return self.netflix_session.fetch_metadata(id=video_id)
Metadata proxy function Parameters ---------- params : :obj:`dict` of :obj:`str` Request params Returns ------- :obj:`Requests.Response` Response of the remote call
Metadata proxy function
[ "Metadata", "proxy", "function" ]
def fetch_metadata(self, params): """Metadata proxy function Parameters ---------- params : :obj:`dict` of :obj:`str` Request params Returns ------- :obj:`Requests.Response` Response of the remote call """ video_id = params.get('video_id', [''])[0] return self.netflix_session.fetch_metadata(id=video_id)
[ "def", "fetch_metadata", "(", "self", ",", "params", ")", ":", "video_id", "=", "params", ".", "get", "(", "'video_id'", ",", "[", "''", "]", ")", "[", "0", "]", "return", "self", ".", "netflix_session", ".", "fetch_metadata", "(", "id", "=", "video_id...
https://github.com/asciidisco/plugin.video.netflix/blob/ceb2638a9676f5839250dadfd079b9e4e4bdd759/resources/lib/NetflixHttpSubRessourceHandler.py#L295-L309
SickChill/SickChill
01020f3636d01535f60b83464d8127ea0efabfc7
sickchill/providers/metadata/mediabrowser.py
python
MediaBrowserMetadata.get_episode_thumb_path
(ep_obj)
return tbn_file_path
Returns a full show dir/metadata/episode.jpg path for MediaBrowser episode thumbs. ep_obj: a TVEpisode object to get the path from
Returns a full show dir/metadata/episode.jpg path for MediaBrowser episode thumbs.
[ "Returns", "a", "full", "show", "dir", "/", "metadata", "/", "episode", ".", "jpg", "path", "for", "MediaBrowser", "episode", "thumbs", "." ]
def get_episode_thumb_path(ep_obj): """ Returns a full show dir/metadata/episode.jpg path for MediaBrowser episode thumbs. ep_obj: a TVEpisode object to get the path from """ if os.path.isfile(ep_obj.location): tbn_filename = replace_extension(os.path.basename(ep_obj.location), "jpg") metadata_dir_name = os.path.join(os.path.dirname(ep_obj.location), "metadata") tbn_file_path = os.path.join(metadata_dir_name, tbn_filename) else: return None return tbn_file_path
[ "def", "get_episode_thumb_path", "(", "ep_obj", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "ep_obj", ".", "location", ")", ":", "tbn_filename", "=", "replace_extension", "(", "os", ".", "path", ".", "basename", "(", "ep_obj", ".", "location", ...
https://github.com/SickChill/SickChill/blob/01020f3636d01535f60b83464d8127ea0efabfc7/sickchill/providers/metadata/mediabrowser.py#L97-L112
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/site-packages/pip/_vendor/distlib/index.py
python
PackageIndex.send_request
(self, req)
return opener.open(req)
Send a standard library :class:`Request` to PyPI and return its response. :param req: The request to send. :return: The HTTP response from PyPI (a standard library HTTPResponse).
Send a standard library :class:`Request` to PyPI and return its response.
[ "Send", "a", "standard", "library", ":", "class", ":", "Request", "to", "PyPI", "and", "return", "its", "response", "." ]
def send_request(self, req): """ Send a standard library :class:`Request` to PyPI and return its response. :param req: The request to send. :return: The HTTP response from PyPI (a standard library HTTPResponse). """ handlers = [] if self.password_handler: handlers.append(self.password_handler) if self.ssl_verifier: handlers.append(self.ssl_verifier) opener = build_opener(*handlers) return opener.open(req)
[ "def", "send_request", "(", "self", ",", "req", ")", ":", "handlers", "=", "[", "]", "if", "self", ".", "password_handler", ":", "handlers", ".", "append", "(", "self", ".", "password_handler", ")", "if", "self", ".", "ssl_verifier", ":", "handlers", "."...
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/site-packages/pip/_vendor/distlib/index.py#L450-L464
foremast/foremast
e8eb9bd24e975772532d90efa8a9ba1850e968cc
src/foremast/consts.py
python
_remove_empty_entries
(entries)
return sorted(valid_entries)
Remove empty entries in a list
Remove empty entries in a list
[ "Remove", "empty", "entries", "in", "a", "list" ]
def _remove_empty_entries(entries): """Remove empty entries in a list""" valid_entries = [] for entry in set(entries): if entry: valid_entries.append(entry) return sorted(valid_entries)
[ "def", "_remove_empty_entries", "(", "entries", ")", ":", "valid_entries", "=", "[", "]", "for", "entry", "in", "set", "(", "entries", ")", ":", "if", "entry", ":", "valid_entries", ".", "append", "(", "entry", ")", "return", "sorted", "(", "valid_entries"...
https://github.com/foremast/foremast/blob/e8eb9bd24e975772532d90efa8a9ba1850e968cc/src/foremast/consts.py#L148-L154
jython/frozen-mirror
b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99
Lib/platform.py
python
_uname
()
return _uname_cache2
Fairly portable uname interface. Returns a tuple of strings (system,node,release,version,machine,processor) identifying the underlying platform. Note that unlike the os.uname function this also returns possible processor information as an additional tuple entry. Entries which cannot be determined are set to ''. Jython-note: _uname resembles CPython behavior for debugging purposes etc.
Fairly portable uname interface. Returns a tuple of strings (system,node,release,version,machine,processor) identifying the underlying platform.
[ "Fairly", "portable", "uname", "interface", ".", "Returns", "a", "tuple", "of", "strings", "(", "system", "node", "release", "version", "machine", "processor", ")", "identifying", "the", "underlying", "platform", "." ]
def _uname(): """ Fairly portable uname interface. Returns a tuple of strings (system,node,release,version,machine,processor) identifying the underlying platform. Note that unlike the os.uname function this also returns possible processor information as an additional tuple entry. Entries which cannot be determined are set to ''. Jython-note: _uname resembles CPython behavior for debugging purposes etc. """ global _uname_cache2 no_os_uname = 0 if _uname_cache2 is not None: return _uname_cache2 processor = '' # Get some infos from the builtin os.uname API... try: system,node,release,version,machine = os.uname() except AttributeError: no_os_uname = 1 if no_os_uname or not filter(None, (system, node, release, version, machine)): # Hmm, no there is either no uname or uname has returned #'unknowns'... we'll have to poke around the system then. if no_os_uname: system = sys.platform release = '' version = '' node = _node() machine = '' use_syscmd_ver = 1 # Try win32_ver() on win32 platforms if system == 'win32': release,version,csd,ptype = win32_ver() if release and version: use_syscmd_ver = 0 # Try to use the PROCESSOR_* environment variables # available on Win XP and later; see # http://support.microsoft.com/kb/888731 and # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM if not machine: # WOW64 processes mask the native architecture if "PROCESSOR_ARCHITEW6432" in os.environ: machine = os.environ.get("PROCESSOR_ARCHITEW6432", '') else: machine = os.environ.get('PROCESSOR_ARCHITECTURE', '') if not processor: processor = os.environ.get('PROCESSOR_IDENTIFIER', machine) # Try the 'ver' system command available on some # platforms if use_syscmd_ver: system,release,version = _syscmd_ver(system) # Normalize system to what win32_ver() normally returns # (_syscmd_ver() tends to return the vendor name as well) if system == 'Microsoft Windows': system = 'Windows' elif system == 'Microsoft' and release == 'Windows': # Under Windows Vista and Windows Server 2008, # Microsoft changed the output of the ver command. The # release is no longer printed. This causes the # system and release to be misidentified. system = 'Windows' if '6.0' == version[:3]: release = 'Vista' else: release = '' # In case we still don't know anything useful, we'll try to # help ourselves if system in ('win32','win16'): if not version: if system == 'win32': version = '32bit' else: version = '16bit' system = 'Windows' elif system[:4] == 'java': release,vendor,vminfo,osinfo = java_ver() system = 'Java' version = string.join(vminfo,', ') if not version: version = vendor # System specific extensions if system == 'OpenVMS': # OpenVMS seems to have release and version mixed up if not release or release == '0': release = version version = '' # Get processor information try: import vms_lib except ImportError: pass else: csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0) if (cpu_number >= 128): processor = 'Alpha' else: processor = 'VAX' if not processor: # Get processor information from the uname system command processor = _syscmd_uname('-p','') #If any unknowns still exist, replace them with ''s, which are more portable if system == 'unknown': system = '' if node == 'unknown': node = '' if release == 'unknown': release = '' if version == 'unknown': version = '' if machine == 'unknown': machine = '' if processor == 'unknown': processor = '' # normalize name if system == 'Microsoft' and release == 'Windows': system = 'Windows' release = 'Vista' if system == 'Windows' and processor == '': processor = _java_getenv('PROCESSOR_IDENTIFIER',processor) _uname_cache2 = system,node,release,version,machine,processor return _uname_cache2
[ "def", "_uname", "(", ")", ":", "global", "_uname_cache2", "no_os_uname", "=", "0", "if", "_uname_cache2", "is", "not", "None", ":", "return", "_uname_cache2", "processor", "=", "''", "# Get some infos from the builtin os.uname API...", "try", ":", "system", ",", ...
https://github.com/jython/frozen-mirror/blob/b8d7aa4cee50c0c0fe2f4b235dd62922dd0f3f99/Lib/platform.py#L1247-L1385
PyCQA/pylint
3fc855f9d0fa8e6410be5a23cf954ffd5471b4eb
pylint/graph.py
python
DotBackend.generate
( self, outputfile: Optional[str] = None, mapfile: Optional[str] = None )
return outputfile
Generates a graph file. :param str outputfile: filename and path [defaults to graphname.png] :param str mapfile: filename and path :rtype: str :return: a path to the generated file :raises RuntimeError: if the executable for rendering was not found
Generates a graph file.
[ "Generates", "a", "graph", "file", "." ]
def generate( self, outputfile: Optional[str] = None, mapfile: Optional[str] = None ) -> str: """Generates a graph file. :param str outputfile: filename and path [defaults to graphname.png] :param str mapfile: filename and path :rtype: str :return: a path to the generated file :raises RuntimeError: if the executable for rendering was not found """ graphviz_extensions = ("dot", "gv") name = self.graphname if outputfile is None: target = "png" pdot, dot_sourcepath = tempfile.mkstemp(".gv", name) ppng, outputfile = tempfile.mkstemp(".png", name) os.close(pdot) os.close(ppng) else: _, _, target = target_info_from_filename(outputfile) if not target: target = "png" outputfile = outputfile + "." + target if target not in graphviz_extensions: pdot, dot_sourcepath = tempfile.mkstemp(".gv", name) os.close(pdot) else: dot_sourcepath = outputfile with codecs.open(dot_sourcepath, "w", encoding="utf8") as file: file.write(self.source) if target not in graphviz_extensions: if shutil.which(self.renderer) is None: raise RuntimeError( f"Cannot generate `{outputfile}` because '{self.renderer}' " "executable not found. Install graphviz, or specify a `.gv` " "outputfile to produce the DOT source code." ) use_shell = sys.platform == "win32" if mapfile: subprocess.call( [ self.renderer, "-Tcmapx", "-o", mapfile, "-T", target, dot_sourcepath, "-o", outputfile, ], shell=use_shell, ) else: subprocess.call( [self.renderer, "-T", target, dot_sourcepath, "-o", outputfile], shell=use_shell, ) os.unlink(dot_sourcepath) return outputfile
[ "def", "generate", "(", "self", ",", "outputfile", ":", "Optional", "[", "str", "]", "=", "None", ",", "mapfile", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "str", ":", "graphviz_extensions", "=", "(", "\"dot\"", ",", "\"gv\"", ")", "n...
https://github.com/PyCQA/pylint/blob/3fc855f9d0fa8e6410be5a23cf954ffd5471b4eb/pylint/graph.py#L86-L147
MurtyShikhar/Question-Answering
86bc5952b5d8df683e10285d7607ed12d2a3462e
qa_model.py
python
QASystem.get_feed_dict
(self, questions, contexts, answers, dropout_val)
return feed
-arg questions: A list of list of ids representing the question sentence -arg contexts: A list of list of ids representing the context paragraph -arg dropout_val: A float representing the keep probability for dropout :return: dict {placeholders: value}
-arg questions: A list of list of ids representing the question sentence -arg contexts: A list of list of ids representing the context paragraph -arg dropout_val: A float representing the keep probability for dropout
[ "-", "arg", "questions", ":", "A", "list", "of", "list", "of", "ids", "representing", "the", "question", "sentence", "-", "arg", "contexts", ":", "A", "list", "of", "list", "of", "ids", "representing", "the", "context", "paragraph", "-", "arg", "dropout_va...
def get_feed_dict(self, questions, contexts, answers, dropout_val): """ -arg questions: A list of list of ids representing the question sentence -arg contexts: A list of list of ids representing the context paragraph -arg dropout_val: A float representing the keep probability for dropout :return: dict {placeholders: value} """ padded_questions, question_lengths = pad_sequences(questions, 0) padded_contexts, passage_lengths = pad_sequences(contexts, 0) feed = { self.question_ids : padded_questions, self.passage_ids : padded_contexts, self.question_lengths : question_lengths, self.passage_lengths : passage_lengths, self.labels : answers, self.dropout : dropout_val } return feed
[ "def", "get_feed_dict", "(", "self", ",", "questions", ",", "contexts", ",", "answers", ",", "dropout_val", ")", ":", "padded_questions", ",", "question_lengths", "=", "pad_sequences", "(", "questions", ",", "0", ")", "padded_contexts", ",", "passage_lengths", "...
https://github.com/MurtyShikhar/Question-Answering/blob/86bc5952b5d8df683e10285d7607ed12d2a3462e/qa_model.py#L281-L303
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/dateutil/tz/tz.py
python
tzrange._dst_base_offset
(self)
return self._dst_base_offset_
[]
def _dst_base_offset(self): return self._dst_base_offset_
[ "def", "_dst_base_offset", "(", "self", ")", ":", "return", "self", ".", "_dst_base_offset_" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/dateutil/tz/tz.py#L1032-L1033
rotki/rotki
aafa446815cdd5e9477436d1b02bee7d01b398c8
tools/profiling/graph.py
python
memory_subplot
(output, data_list)
Plots all data in separated axes, a simple way to look at distinct executions, keep in mind that the time-axis will be skewed, since each plot has a differente running time but the same plotting area.
Plots all data in separated axes, a simple way to look at distinct executions, keep in mind that the time-axis will be skewed, since each plot has a differente running time but the same plotting area.
[ "Plots", "all", "data", "in", "separated", "axes", "a", "simple", "way", "to", "look", "at", "distinct", "executions", "keep", "in", "mind", "that", "the", "time", "-", "axis", "will", "be", "skewed", "since", "each", "plot", "has", "a", "differente", "r...
def memory_subplot(output, data_list): """Plots all data in separated axes, a simple way to look at distinct executions, keep in mind that the time-axis will be skewed, since each plot has a differente running time but the same plotting area.""" import matplotlib.pyplot as plt from matplotlib import dates number_plots = len(data_list) fig, all_memory_axes = plt.subplots(1, number_plots, sharey="row") if number_plots == 1: all_memory_axes = [all_memory_axes] memory_max = 0.0 for line in chain(*data_list): memory_max = max(memory_max, line[MEMORY]) # give room for the lines and axes memory_max *= 1.1 hour_fmt = dates.DateFormatter("%H:%M") for count, (data, memory_axes) in enumerate(zip(data_list, all_memory_axes)): timestamp = [line[TIMESTAMP] for line in data] memory = [line[MEMORY] for line in data] dt_start_time = timestamp[0] hours = timestamp[-1] - dt_start_time label = "{start_date:%Y-%m-%d}\n{runtime}".format(start_date=dt_start_time, runtime=hours) memory_axes.plot(timestamp, memory, color="b") memory_axes.set_ylim(0, memory_max) memory_axes.xaxis.set_major_formatter(hour_fmt) memory_axes.set_xlabel(label) if len(data_list) == 1 or count == 0: memory_axes.set_ylabel("Memory (MB)") else: memory_axes.get_yaxis().set_visible(False) fig.autofmt_xdate() plot_configure(fig) plt.savefig(output)
[ "def", "memory_subplot", "(", "output", ",", "data_list", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "from", "matplotlib", "import", "dates", "number_plots", "=", "len", "(", "data_list", ")", "fig", ",", "all_memory_axes", "=", "plt", "."...
https://github.com/rotki/rotki/blob/aafa446815cdd5e9477436d1b02bee7d01b398c8/tools/profiling/graph.py#L192-L233
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
openedx/core/djangoapps/header_control/__init__.py
python
force_header_for_response
(response, header, value)
Forces the given header for the given response using the header_control middleware.
Forces the given header for the given response using the header_control middleware.
[ "Forces", "the", "given", "header", "for", "the", "given", "response", "using", "the", "header_control", "middleware", "." ]
def force_header_for_response(response, header, value): """Forces the given header for the given response using the header_control middleware.""" force_headers = {} if hasattr(response, 'force_headers'): force_headers = response.force_headers force_headers[header] = value response.force_headers = force_headers
[ "def", "force_header_for_response", "(", "response", ",", "header", ",", "value", ")", ":", "force_headers", "=", "{", "}", "if", "hasattr", "(", "response", ",", "'force_headers'", ")", ":", "force_headers", "=", "response", ".", "force_headers", "force_headers...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/openedx/core/djangoapps/header_control/__init__.py#L15-L22
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_vendor/pyparsing.py
python
ParseResults._asStringList
( self, sep='' )
return out
[]
def _asStringList( self, sep='' ): out = [] for item in self.__toklist: if out and sep: out.append(sep) if isinstance( item, ParseResults ): out += item._asStringList() else: out.append( _ustr(item) ) return out
[ "def", "_asStringList", "(", "self", ",", "sep", "=", "''", ")", ":", "out", "=", "[", "]", "for", "item", "in", "self", ".", "__toklist", ":", "if", "out", "and", "sep", ":", "out", ".", "append", "(", "sep", ")", "if", "isinstance", "(", "item"...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_vendor/pyparsing.py#L670-L679
scanny/python-pptx
71d1ca0b2b3b9178d64cdab565e8503a25a54e0b
pptx/chart/xlsx.py
python
CategoryWorkbookWriter._column_reference
(column_number)
return col_ref
Return str Excel column reference like 'BQ' for *column_number*. *column_number* is an int in the range 1-16384 inclusive, where 1 maps to column 'A'.
Return str Excel column reference like 'BQ' for *column_number*.
[ "Return", "str", "Excel", "column", "reference", "like", "BQ", "for", "*", "column_number", "*", "." ]
def _column_reference(column_number): """Return str Excel column reference like 'BQ' for *column_number*. *column_number* is an int in the range 1-16384 inclusive, where 1 maps to column 'A'. """ if column_number < 1 or column_number > 16384: raise ValueError("column_number must be in range 1-16384") # ---Work right-to-left, one order of magnitude at a time. Note there # is no zero representation in Excel address scheme, so this is # not just a conversion to base-26--- col_ref = "" while column_number: remainder = column_number % 26 if remainder == 0: remainder = 26 col_letter = chr(ord("A") + remainder - 1) col_ref = col_letter + col_ref # ---Advance to next order of magnitude or terminate loop. The # minus-one in this expression reflects the fact the next lower # order of magnitude has a minumum value of 1 (not zero). This is # essentially the complement to the "if it's 0 make it 26' step # above.--- column_number = (column_number - 1) // 26 return col_ref
[ "def", "_column_reference", "(", "column_number", ")", ":", "if", "column_number", "<", "1", "or", "column_number", ">", "16384", ":", "raise", "ValueError", "(", "\"column_number must be in range 1-16384\"", ")", "# ---Work right-to-left, one order of magnitude at a time. No...
https://github.com/scanny/python-pptx/blob/71d1ca0b2b3b9178d64cdab565e8503a25a54e0b/pptx/chart/xlsx.py#L89-L118
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.4/django/contrib/staticfiles/finders.py
python
_get_finder
(import_path)
return Finder()
Imports the staticfiles finder class described by import_path, where import_path is the full Python path to the class.
Imports the staticfiles finder class described by import_path, where import_path is the full Python path to the class.
[ "Imports", "the", "staticfiles", "finder", "class", "described", "by", "import_path", "where", "import_path", "is", "the", "full", "Python", "path", "to", "the", "class", "." ]
def _get_finder(import_path): """ Imports the staticfiles finder class described by import_path, where import_path is the full Python path to the class. """ module, attr = import_path.rsplit('.', 1) try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error importing module %s: "%s"' % (module, e)) try: Finder = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a "%s" ' 'class.' % (module, attr)) if not issubclass(Finder, BaseFinder): raise ImproperlyConfigured('Finder "%s" is not a subclass of "%s"' % (Finder, BaseFinder)) return Finder()
[ "def", "_get_finder", "(", "import_path", ")", ":", "module", ",", "attr", "=", "import_path", ".", "rsplit", "(", "'.'", ",", "1", ")", "try", ":", "mod", "=", "import_module", "(", "module", ")", "except", "ImportError", ",", "e", ":", "raise", "Impr...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.4/django/contrib/staticfiles/finders.py#L255-L274
cltk/cltk
1a8c2f5ef72389e2579dfce1fa5af8e59ebc9ec1
src/cltk/tag/ner.py
python
NamedEntityReplacer.tag_ner_fr
(self, input_text, output_type=list)
return ner_tuple_list
[]
def tag_ner_fr(self, input_text, output_type=list): entities = self.entities for entity in entities: (name, kind) = entity word_tokenizer = PunktWordTokenizer() tokenized_text = word_tokenizer.tokenize(input_text) ner_tuple_list = [] match = False for word in tokenized_text: for name, kind in entities: if word == name: named_things = [(name, "entity", kind)] ner_tuple_list.append(named_things) match = True break else: ner_tuple_list.append((word,)) return ner_tuple_list
[ "def", "tag_ner_fr", "(", "self", ",", "input_text", ",", "output_type", "=", "list", ")", ":", "entities", "=", "self", ".", "entities", "for", "entity", "in", "entities", ":", "(", "name", ",", "kind", ")", "=", "entity", "word_tokenizer", "=", "PunktW...
https://github.com/cltk/cltk/blob/1a8c2f5ef72389e2579dfce1fa5af8e59ebc9ec1/src/cltk/tag/ner.py#L45-L66
python/mypy
17850b3bd77ae9efb5d21f656c4e4e05ac48d894
mypy/plugins/enums.py
python
enum_name_callback
(ctx: 'mypy.plugin.AttributeContext')
This plugin refines the 'name' attribute in enums to act as if they were declared to be final. For example, the expression 'MyEnum.FOO.name' normally is inferred to be of type 'str'. This plugin will instead make the inferred type be a 'str' where the last known value is 'Literal["FOO"]'. This means it would be legal to use 'MyEnum.FOO.name' in contexts that expect a Literal type, just like any other Final variable or attribute. This plugin assumes that the provided context is an attribute access matching one of the strings found in 'ENUM_NAME_ACCESS'.
This plugin refines the 'name' attribute in enums to act as if they were declared to be final.
[ "This", "plugin", "refines", "the", "name", "attribute", "in", "enums", "to", "act", "as", "if", "they", "were", "declared", "to", "be", "final", "." ]
def enum_name_callback(ctx: 'mypy.plugin.AttributeContext') -> Type: """This plugin refines the 'name' attribute in enums to act as if they were declared to be final. For example, the expression 'MyEnum.FOO.name' normally is inferred to be of type 'str'. This plugin will instead make the inferred type be a 'str' where the last known value is 'Literal["FOO"]'. This means it would be legal to use 'MyEnum.FOO.name' in contexts that expect a Literal type, just like any other Final variable or attribute. This plugin assumes that the provided context is an attribute access matching one of the strings found in 'ENUM_NAME_ACCESS'. """ enum_field_name = _extract_underlying_field_name(ctx.type) if enum_field_name is None: return ctx.default_attr_type else: str_type = ctx.api.named_generic_type('builtins.str', []) literal_type = LiteralType(enum_field_name, fallback=str_type) return str_type.copy_modified(last_known_value=literal_type)
[ "def", "enum_name_callback", "(", "ctx", ":", "'mypy.plugin.AttributeContext'", ")", "->", "Type", ":", "enum_field_name", "=", "_extract_underlying_field_name", "(", "ctx", ".", "type", ")", "if", "enum_field_name", "is", "None", ":", "return", "ctx", ".", "defau...
https://github.com/python/mypy/blob/17850b3bd77ae9efb5d21f656c4e4e05ac48d894/mypy/plugins/enums.py#L31-L52
trakt/Plex-Trakt-Scrobbler
aeb0bfbe62fad4b06c164f1b95581da7f35dce0b
Trakttv.bundle/Contents/Libraries/FreeBSD/i386/ucs4/cryptography/x509/base.py
python
CertificateBuilder.issuer_name
(self, name)
return CertificateBuilder( name, self._subject_name, self._public_key, self._serial_number, self._not_valid_before, self._not_valid_after, self._extensions )
Sets the CA's distinguished name.
Sets the CA's distinguished name.
[ "Sets", "the", "CA", "s", "distinguished", "name", "." ]
def issuer_name(self, name): """ Sets the CA's distinguished name. """ if not isinstance(name, Name): raise TypeError('Expecting x509.Name object.') if self._issuer_name is not None: raise ValueError('The issuer name may only be set once.') return CertificateBuilder( name, self._subject_name, self._public_key, self._serial_number, self._not_valid_before, self._not_valid_after, self._extensions )
[ "def", "issuer_name", "(", "self", ",", "name", ")", ":", "if", "not", "isinstance", "(", "name", ",", "Name", ")", ":", "raise", "TypeError", "(", "'Expecting x509.Name object.'", ")", "if", "self", ".", "_issuer_name", "is", "not", "None", ":", "raise", ...
https://github.com/trakt/Plex-Trakt-Scrobbler/blob/aeb0bfbe62fad4b06c164f1b95581da7f35dce0b/Trakttv.bundle/Contents/Libraries/FreeBSD/i386/ucs4/cryptography/x509/base.py#L390-L402
themix-project/oomox
1bb0f3033736c56652e25c7d7b47c7fc499bfeb1
oomox_gui/main.py
python
OomoxGtkApplication.do_startup
(self)
[]
def do_startup(self): # pylint: disable=arguments-differ Gtk.Application.do_startup(self) quit_action = Gio.SimpleAction.new( AppActions.quit, None ) quit_action.connect("activate", self._on_quit) self.add_action(quit_action) _shortcuts = {} def set_accels_for_action(action, accels, action_id=None): action_id = action_id or action.get_id() for accel in accels: if accel in _shortcuts: raise Exception(f'Shortcut "{accel}" is already set.') _shortcuts[accel] = action_id self.set_accels_for_action(action_id, accels) set_accels_for_action(AppActions.quit, ["<Primary>Q"]) set_accels_for_action(WindowActions.import_menu, ["<Primary>M"]) set_accels_for_action(WindowActions.clone, ["<Shift><Primary>S"]) set_accels_for_action(WindowActions.save, ["<Primary>S"]) set_accels_for_action(WindowActions.rename, ["F2"]) set_accels_for_action(WindowActions.remove, ["<Primary>Delete"]) set_accels_for_action(WindowActions.export_theme, ["<Primary>E"]) set_accels_for_action(WindowActions.export_icons, ["<Primary>I"]) set_accels_for_action(WindowActions.export_menu, ["<Primary>O"]) set_accels_for_action(WindowActions.menu, ["F10"]) set_accels_for_action(WindowActions.show_help, ["<Primary>question"]) _plugin_shortcuts = {} for plugin_list, plugin_action_template in ( (PluginLoader.get_import_plugins(), "import_plugin_{}"), (PluginLoader.get_export_plugins(), "export_plugin_{}"), ): for plugin_name, plugin in plugin_list.items(): if not plugin.shortcut: continue if plugin.shortcut in _shortcuts: _is_plugin_shortcut = plugin.shortcut in _plugin_shortcuts error_dialog = Gtk.MessageDialog( text=translate('Error while loading plugin "{plugin_name}"').format( plugin_name=plugin_name ), secondary_text='\n'.join(( translate('Shortcut "{shortcut}" already assigned to {action_type} "{name}".').format( # noqa # pylint: disable=line-too-long shortcut=plugin.shortcut, action_type=translate('plugin') if _is_plugin_shortcut else translate('action'), name=( _plugin_shortcuts[plugin.shortcut] if _is_plugin_shortcut else _shortcuts[plugin.shortcut] ) ), translate('Shortcut will be disabled for "{plugin_name}" plugin.').format( plugin_name=plugin_name ) )), buttons=Gtk.ButtonsType.CLOSE ) error_dialog.run() error_dialog.destroy() continue action_name = plugin_action_template.format(plugin_name) set_accels_for_action( action_name, [plugin.shortcut], f"win.{action_name}" ) _plugin_shortcuts[plugin.shortcut] = plugin_name
[ "def", "do_startup", "(", "self", ")", ":", "# pylint: disable=arguments-differ", "Gtk", ".", "Application", ".", "do_startup", "(", "self", ")", "quit_action", "=", "Gio", ".", "SimpleAction", ".", "new", "(", "AppActions", ".", "quit", ",", "None", ")", "q...
https://github.com/themix-project/oomox/blob/1bb0f3033736c56652e25c7d7b47c7fc499bfeb1/oomox_gui/main.py#L793-L864
PyTorchLightning/pytorch-lightning
5914fb748fb53d826ab337fc2484feab9883a104
pytorch_lightning/profiler/pytorch.py
python
PyTorchProfiler.__init__
( self, dirpath: Optional[Union[str, Path]] = None, filename: Optional[str] = None, group_by_input_shapes: bool = False, emit_nvtx: bool = False, export_to_chrome: bool = True, row_limit: int = 20, sort_by_key: Optional[str] = None, record_functions: Set[str] = None, record_module_names: bool = True, **profiler_kwargs: Any, )
This profiler uses PyTorch's Autograd Profiler and lets you inspect the cost of. different operators inside your model - both on the CPU and GPU Args: dirpath: Directory path for the ``filename``. If ``dirpath`` is ``None`` but ``filename`` is present, the ``trainer.log_dir`` (from :class:`~pytorch_lightning.loggers.tensorboard.TensorBoardLogger`) will be used. filename: If present, filename where the profiler results will be saved instead of printing to stdout. The ``.txt`` extension will be used automatically. group_by_input_shapes: Include operator input shapes and group calls by shape. emit_nvtx: Context manager that makes every autograd operation emit an NVTX range Run:: nvprof --profile-from-start off -o trace_name.prof -- <regular command here> To visualize, you can either use:: nvvp trace_name.prof torch.autograd.profiler.load_nvprof(path) export_to_chrome: Whether to export the sequence of profiled operators for Chrome. It will generate a ``.json`` file which can be read by Chrome. row_limit: Limit the number of rows in a table, ``-1`` is a special value that removes the limit completely. sort_by_key: Attribute used to sort entries. By default they are printed in the same order as they were registered. Valid keys include: ``cpu_time``, ``cuda_time``, ``cpu_time_total``, ``cuda_time_total``, ``cpu_memory_usage``, ``cuda_memory_usage``, ``self_cpu_memory_usage``, ``self_cuda_memory_usage``, ``count``. record_functions: Set of profiled functions which will create a context manager on. Any other will be pass through. record_module_names: Whether to add module names while recording autograd operation. profiler_kwargs: Keyword arguments for the PyTorch profiler. This depends on your PyTorch version Raises: MisconfigurationException: If arg ``sort_by_key`` is not present in ``AVAILABLE_SORT_KEYS``. If arg ``schedule`` is not a ``Callable``. If arg ``schedule`` does not return a ``torch.profiler.ProfilerAction``.
This profiler uses PyTorch's Autograd Profiler and lets you inspect the cost of.
[ "This", "profiler", "uses", "PyTorch", "s", "Autograd", "Profiler", "and", "lets", "you", "inspect", "the", "cost", "of", "." ]
def __init__( self, dirpath: Optional[Union[str, Path]] = None, filename: Optional[str] = None, group_by_input_shapes: bool = False, emit_nvtx: bool = False, export_to_chrome: bool = True, row_limit: int = 20, sort_by_key: Optional[str] = None, record_functions: Set[str] = None, record_module_names: bool = True, **profiler_kwargs: Any, ) -> None: """This profiler uses PyTorch's Autograd Profiler and lets you inspect the cost of. different operators inside your model - both on the CPU and GPU Args: dirpath: Directory path for the ``filename``. If ``dirpath`` is ``None`` but ``filename`` is present, the ``trainer.log_dir`` (from :class:`~pytorch_lightning.loggers.tensorboard.TensorBoardLogger`) will be used. filename: If present, filename where the profiler results will be saved instead of printing to stdout. The ``.txt`` extension will be used automatically. group_by_input_shapes: Include operator input shapes and group calls by shape. emit_nvtx: Context manager that makes every autograd operation emit an NVTX range Run:: nvprof --profile-from-start off -o trace_name.prof -- <regular command here> To visualize, you can either use:: nvvp trace_name.prof torch.autograd.profiler.load_nvprof(path) export_to_chrome: Whether to export the sequence of profiled operators for Chrome. It will generate a ``.json`` file which can be read by Chrome. row_limit: Limit the number of rows in a table, ``-1`` is a special value that removes the limit completely. sort_by_key: Attribute used to sort entries. By default they are printed in the same order as they were registered. Valid keys include: ``cpu_time``, ``cuda_time``, ``cpu_time_total``, ``cuda_time_total``, ``cpu_memory_usage``, ``cuda_memory_usage``, ``self_cpu_memory_usage``, ``self_cuda_memory_usage``, ``count``. record_functions: Set of profiled functions which will create a context manager on. Any other will be pass through. record_module_names: Whether to add module names while recording autograd operation. profiler_kwargs: Keyword arguments for the PyTorch profiler. This depends on your PyTorch version Raises: MisconfigurationException: If arg ``sort_by_key`` is not present in ``AVAILABLE_SORT_KEYS``. If arg ``schedule`` is not a ``Callable``. If arg ``schedule`` does not return a ``torch.profiler.ProfilerAction``. """ super().__init__(dirpath=dirpath, filename=filename) self._group_by_input_shapes = group_by_input_shapes and profiler_kwargs.get("record_shapes", False) self._emit_nvtx = emit_nvtx self._export_to_chrome = export_to_chrome self._row_limit = row_limit self._sort_by_key = sort_by_key or f"{'cuda' if profiler_kwargs.get('use_cuda', False) else 'cpu'}_time_total" self._user_record_functions = record_functions or set() self._record_functions_start = self._user_record_functions | self.START_RECORD_FUNCTIONS self._record_functions = self._user_record_functions | self.RECORD_FUNCTIONS self._record_module_names = record_module_names self._profiler_kwargs = profiler_kwargs self.profiler: Optional[_PROFILER] = None self.function_events: Optional["EventList"] = None self._lightning_module: Optional["LightningModule"] = None # set by ProfilerConnector self._register: Optional[RegisterRecordFunction] = None self._parent_profiler: Optional[_PROFILER] = None self._recording_map: Dict[str, record_function] = {} self._start_action_name: Optional[str] = None self._schedule: Optional[ScheduleWrapper] = None if _KINETO_AVAILABLE: self._init_kineto(profiler_kwargs) if self._sort_by_key not in self.AVAILABLE_SORT_KEYS: raise MisconfigurationException( f"Found sort_by_key: {self._sort_by_key}. Should be within {self.AVAILABLE_SORT_KEYS}. " )
[ "def", "__init__", "(", "self", ",", "dirpath", ":", "Optional", "[", "Union", "[", "str", ",", "Path", "]", "]", "=", "None", ",", "filename", ":", "Optional", "[", "str", "]", "=", "None", ",", "group_by_input_shapes", ":", "bool", "=", "False", ",...
https://github.com/PyTorchLightning/pytorch-lightning/blob/5914fb748fb53d826ab337fc2484feab9883a104/pytorch_lightning/profiler/pytorch.py#L220-L310
bcbio/bcbio-nextgen
c80f9b6b1be3267d1f981b7035e3b72441d258f2
bcbio/ngsalign/rtg.py
python
calculate_splits
(sdf_file, split_size)
return splits
Retrieve
Retrieve
[ "Retrieve" ]
def calculate_splits(sdf_file, split_size): """Retrieve """ counts = _sdfstats(sdf_file)["counts"] splits = [] cur = 0 for i in range(counts // split_size + (0 if counts % split_size == 0 else 1)): splits.append("%s-%s" % (cur, min(counts, cur + split_size))) cur += split_size return splits
[ "def", "calculate_splits", "(", "sdf_file", ",", "split_size", ")", ":", "counts", "=", "_sdfstats", "(", "sdf_file", ")", "[", "\"counts\"", "]", "splits", "=", "[", "]", "cur", "=", "0", "for", "i", "in", "range", "(", "counts", "//", "split_size", "...
https://github.com/bcbio/bcbio-nextgen/blob/c80f9b6b1be3267d1f981b7035e3b72441d258f2/bcbio/ngsalign/rtg.py#L45-L54
biocore/scikit-bio
ecdfc7941d8c21eb2559ff1ab313d6e9348781da
skbio/sequence/_dna.py
python
DNA.transcribe
(self)
return skbio.RNA(seq, metadata=metadata, positional_metadata=positional_metadata, interval_metadata=interval_metadata, validate=False)
Transcribe DNA into RNA. DNA sequence is assumed to be the coding strand. Thymine (T) is replaced with uracil (U) in the transcribed sequence. Returns ------- RNA Transcribed sequence. See Also -------- translate translate_six_frames Notes ----- DNA sequence's metadata, positional, and interval metadata are included in the transcribed RNA sequence. Examples -------- Transcribe DNA into RNA: >>> from skbio import DNA >>> dna = DNA('TAACGTTA') >>> dna DNA -------------------------- Stats: length: 8 has gaps: False has degenerates: False has definites: True GC-content: 25.00% -------------------------- 0 TAACGTTA >>> dna.transcribe() RNA -------------------------- Stats: length: 8 has gaps: False has degenerates: False has definites: True GC-content: 25.00% -------------------------- 0 UAACGUUA
Transcribe DNA into RNA.
[ "Transcribe", "DNA", "into", "RNA", "." ]
def transcribe(self): """Transcribe DNA into RNA. DNA sequence is assumed to be the coding strand. Thymine (T) is replaced with uracil (U) in the transcribed sequence. Returns ------- RNA Transcribed sequence. See Also -------- translate translate_six_frames Notes ----- DNA sequence's metadata, positional, and interval metadata are included in the transcribed RNA sequence. Examples -------- Transcribe DNA into RNA: >>> from skbio import DNA >>> dna = DNA('TAACGTTA') >>> dna DNA -------------------------- Stats: length: 8 has gaps: False has degenerates: False has definites: True GC-content: 25.00% -------------------------- 0 TAACGTTA >>> dna.transcribe() RNA -------------------------- Stats: length: 8 has gaps: False has degenerates: False has definites: True GC-content: 25.00% -------------------------- 0 UAACGUUA """ seq = self._string.replace(b'T', b'U') metadata = None if self.has_metadata(): metadata = self.metadata positional_metadata = None if self.has_positional_metadata(): positional_metadata = self.positional_metadata interval_metadata = None if self.has_interval_metadata(): interval_metadata = self.interval_metadata # turn off validation because `seq` is guaranteed to be valid return skbio.RNA(seq, metadata=metadata, positional_metadata=positional_metadata, interval_metadata=interval_metadata, validate=False)
[ "def", "transcribe", "(", "self", ")", ":", "seq", "=", "self", ".", "_string", ".", "replace", "(", "b'T'", ",", "b'U'", ")", "metadata", "=", "None", "if", "self", ".", "has_metadata", "(", ")", ":", "metadata", "=", "self", ".", "metadata", "posit...
https://github.com/biocore/scikit-bio/blob/ecdfc7941d8c21eb2559ff1ab313d6e9348781da/skbio/sequence/_dna.py#L145-L214