repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
lreis2415/PyGeoC
pygeoc/raster.py
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L586-L631
def raster_erosion(rasterfile): """Erode the raster image. Find the min pixel's value in 8-neighborhood. Then change the compute pixel's value into the min pixel's value. Args: rasterfile: input original raster image, type can be filename(string, like "test1.t...
[ "def", "raster_erosion", "(", "rasterfile", ")", ":", "if", "is_string", "(", "rasterfile", ")", ":", "origin_raster", "=", "RasterUtilClass", ".", "read_raster", "(", "str", "(", "rasterfile", ")", ")", "elif", "isinstance", "(", "rasterfile", ",", "Raster", ...
Erode the raster image. Find the min pixel's value in 8-neighborhood. Then change the compute pixel's value into the min pixel's value. Args: rasterfile: input original raster image, type can be filename(string, like "test1.tif"), rasterfile(class Raster) or numpy.nda...
[ "Erode", "the", "raster", "image", "." ]
python
train
51.934783
anentropic/django-conditional-aggregates
djconnagg/aggregates.py
https://github.com/anentropic/django-conditional-aggregates/blob/20d060c31344267b589b0cff9bdcd341a6b539ab/djconnagg/aggregates.py#L29-L77
def render_q(q, qn, connection): """ Renders the Q object into SQL for the WHEN clause. Uses as much as possible the Django ORM machinery for SQL generation, handling table aliases, field quoting, parameter escaping etc. :param q: Q object representing the filter condition :param qn: db specif...
[ "def", "render_q", "(", "q", ",", "qn", ",", "connection", ")", ":", "joinstr", "=", "u' {} '", ".", "format", "(", "q", ".", "connector", ")", "conditions", "=", "[", "]", "params", "=", "[", "]", "if", "DJANGO_MAJOR", "==", "1", "and", "DJANGO_MINO...
Renders the Q object into SQL for the WHEN clause. Uses as much as possible the Django ORM machinery for SQL generation, handling table aliases, field quoting, parameter escaping etc. :param q: Q object representing the filter condition :param qn: db specific 'quote names' function that was passed int...
[ "Renders", "the", "Q", "object", "into", "SQL", "for", "the", "WHEN", "clause", "." ]
python
train
36.285714
onecodex/onecodex
onecodex/viz/_metadata.py
https://github.com/onecodex/onecodex/blob/326a0a1af140e3a57ccf31c3c9c5e17a5775c13d/onecodex/viz/_metadata.py#L9-L175
def plot_metadata( self, rank="auto", haxis="Label", vaxis="simpson", title=None, xlabel=None, ylabel=None, return_chart=False, plot_type="auto", label=None, ): """Plot an arbitrary metadata field versus an arbitrary quantity as...
[ "def", "plot_metadata", "(", "self", ",", "rank", "=", "\"auto\"", ",", "haxis", "=", "\"Label\"", ",", "vaxis", "=", "\"simpson\"", ",", "title", "=", "None", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ",", "return_chart", "=", "False", "...
Plot an arbitrary metadata field versus an arbitrary quantity as a boxplot or scatter plot. Parameters ---------- rank : {'auto', 'kingdom', 'phylum', 'class', 'order', 'family', 'genus', 'species'}, optional Analysis will be restricted to abundances of taxa at the specified level. ...
[ "Plot", "an", "arbitrary", "metadata", "field", "versus", "an", "arbitrary", "quantity", "as", "a", "boxplot", "or", "scatter", "plot", "." ]
python
train
38.886228
hawkowl/txctools
txctools/reports/hotspot.py
https://github.com/hawkowl/txctools/blob/14cab033ea179211a7bfd88dc202d576fc336ddc/txctools/reports/hotspot.py#L63-L100
def deliverTextResults(self): """ Deliver the results in a pretty text output. @return: Pretty text output! """ output = "=======================\ntxctools Hotspot Report\n"\ "=======================\n\n" fileResults = sorted(self.fileCounts.items(), ...
[ "def", "deliverTextResults", "(", "self", ")", ":", "output", "=", "\"=======================\\ntxctools Hotspot Report\\n\"", "\"=======================\\n\\n\"", "fileResults", "=", "sorted", "(", "self", ".", "fileCounts", ".", "items", "(", ")", ",", "key", "=", "...
Deliver the results in a pretty text output. @return: Pretty text output!
[ "Deliver", "the", "results", "in", "a", "pretty", "text", "output", "." ]
python
train
30.736842
openstack/proliantutils
proliantutils/hpssa/objects.py
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/hpssa/objects.py#L273-L286
def get_logical_drives(self): """Get all the RAID logical drives in the Server. This method returns all the RAID logical drives on the server by examining all the controllers. :returns: a list of LogicalDrive objects. """ logical_drives = [] for controller in se...
[ "def", "get_logical_drives", "(", "self", ")", ":", "logical_drives", "=", "[", "]", "for", "controller", "in", "self", ".", "controllers", ":", "for", "array", "in", "controller", ".", "raid_arrays", ":", "for", "logical_drive", "in", "array", ".", "logical...
Get all the RAID logical drives in the Server. This method returns all the RAID logical drives on the server by examining all the controllers. :returns: a list of LogicalDrive objects.
[ "Get", "all", "the", "RAID", "logical", "drives", "in", "the", "Server", "." ]
python
train
36.928571
openpermissions/perch
perch/model.py
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/model.py#L609-L627
def delete(self, user): """Delete a sub-resource""" if user: can_delete = yield self.can_delete(user) else: can_delete = False if not can_delete: raise exceptions.Unauthorized('User may not delete the resource') try: parent = yiel...
[ "def", "delete", "(", "self", ",", "user", ")", ":", "if", "user", ":", "can_delete", "=", "yield", "self", ".", "can_delete", "(", "user", ")", "else", ":", "can_delete", "=", "False", "if", "not", "can_delete", ":", "raise", "exceptions", ".", "Unaut...
Delete a sub-resource
[ "Delete", "a", "sub", "-", "resource" ]
python
train
30.526316
dcaune/perseus-lib-python-common
exifread/classes.py
https://github.com/dcaune/perseus-lib-python-common/blob/ba48fe0fd9bb4a75b53e7d10c41ada36a72d4496/exifread/classes.py#L474-L495
def _canon_decode_tag(self, value, mn_tags): """ Decode Canon MakerNote tag based on offset within tag. See http://www.burren.cx/david/canon.html by David Burren """ for i in range(1, len(value)): tag = mn_tags.get(i, ('Unknown', )) name = tag[0] ...
[ "def", "_canon_decode_tag", "(", "self", ",", "value", ",", "mn_tags", ")", ":", "for", "i", "in", "range", "(", "1", ",", "len", "(", "value", ")", ")", ":", "tag", "=", "mn_tags", ".", "get", "(", "i", ",", "(", "'Unknown'", ",", ")", ")", "n...
Decode Canon MakerNote tag based on offset within tag. See http://www.burren.cx/david/canon.html by David Burren
[ "Decode", "Canon", "MakerNote", "tag", "based", "on", "offset", "within", "tag", "." ]
python
train
39.409091
bwengals/ccsnmultivar
ccsnmultivar/designmatrix.py
https://github.com/bwengals/ccsnmultivar/blob/dbadf52e728e0ce922cbc147864e693c2c2d305c/ccsnmultivar/designmatrix.py#L58-L85
def make_param_dict_from_file(self,path_to_params): """ make param dict from a file on disk """ # then we were given a path to a parameter file param_list = list(csv.reader(open(path_to_params,"rb"))) # delete empty elements (if any) param_file = [x for x in param...
[ "def", "make_param_dict_from_file", "(", "self", ",", "path_to_params", ")", ":", "# then we were given a path to a parameter file", "param_list", "=", "list", "(", "csv", ".", "reader", "(", "open", "(", "path_to_params", ",", "\"rb\"", ")", ")", ")", "# delete emp...
make param dict from a file on disk
[ "make", "param", "dict", "from", "a", "file", "on", "disk" ]
python
train
46.714286
zetaops/zengine
zengine/messaging/model.py
https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/messaging/model.py#L370-L398
def serialize(self, user=None): """ Serializes message for given user. Note: Should be called before first save(). Otherwise "is_update" will get wrong value. Args: user: User object Returns: Dict. JSON serialization ready dictionary object ...
[ "def", "serialize", "(", "self", ",", "user", "=", "None", ")", ":", "return", "{", "'content'", ":", "self", ".", "body", ",", "'type'", ":", "self", ".", "typ", ",", "'updated_at'", ":", "self", ".", "updated_at", ",", "'timestamp'", ":", "self", "...
Serializes message for given user. Note: Should be called before first save(). Otherwise "is_update" will get wrong value. Args: user: User object Returns: Dict. JSON serialization ready dictionary object
[ "Serializes", "message", "for", "given", "user", "." ]
python
train
32.206897
chaoss/grimoirelab-elk
utils/gh2k.py
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/utils/gh2k.py#L192-L250
def notify_contact(mail, owner, graas_url, repos, first_repo=False): """ Send an email to the contact with the details to access the Kibana dashboard """ footer = """ -- Bitergia Cauldron Team http://bitergia.com """ twitter_txt = "Check Cauldron.io dashboard for %s at %s/dashboards/%s" % (own...
[ "def", "notify_contact", "(", "mail", ",", "owner", ",", "graas_url", ",", "repos", ",", "first_repo", "=", "False", ")", ":", "footer", "=", "\"\"\"\n--\nBitergia Cauldron Team\nhttp://bitergia.com\n \"\"\"", "twitter_txt", "=", "\"Check Cauldron.io dashboard for %s at ...
Send an email to the contact with the details to access the Kibana dashboard
[ "Send", "an", "email", "to", "the", "contact", "with", "the", "details", "to", "access", "the", "Kibana", "dashboard" ]
python
train
28.59322
mabuchilab/QNET
src/qnet/algebra/core/scalar_algebra.py
https://github.com/mabuchilab/QNET/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/algebra/core/scalar_algebra.py#L966-L968
def real(self): """Real part""" return self.__class__.create(self.term.real, *self.ranges)
[ "def", "real", "(", "self", ")", ":", "return", "self", ".", "__class__", ".", "create", "(", "self", ".", "term", ".", "real", ",", "*", "self", ".", "ranges", ")" ]
Real part
[ "Real", "part" ]
python
train
34.666667
rbarrois/mpdlcd
mpdlcd/mpdhooks.py
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/mpdhooks.py#L68-L96
def handle(self, client, subhooks=()): """Handle a new update. Fetches new data from the client, then compares it to the previous lookup. Returns: (bool, new_data): whether changes occurred, and the new value. """ new_data = self.fetch(client) # Hol...
[ "def", "handle", "(", "self", ",", "client", ",", "subhooks", "=", "(", ")", ")", ":", "new_data", "=", "self", ".", "fetch", "(", "client", ")", "# Holds the list of updated fields.", "updated", "=", "{", "}", "if", "not", "subhooks", ":", "# We always wa...
Handle a new update. Fetches new data from the client, then compares it to the previous lookup. Returns: (bool, new_data): whether changes occurred, and the new value.
[ "Handle", "a", "new", "update", "." ]
python
train
30.896552
gagneurlab/concise
concise/utils/splines.py
https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/utils/splines.py#L144-L173
def get_X_spline(x, knots, n_bases=10, spline_order=3, add_intercept=True): """ Returns: np.array of shape [len(x), n_bases + (add_intercept)] # BSpline formula https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.BSpline.html#scipy.interpolate.BSpline Fortran code: h...
[ "def", "get_X_spline", "(", "x", ",", "knots", ",", "n_bases", "=", "10", ",", "spline_order", "=", "3", ",", "add_intercept", "=", "True", ")", ":", "if", "len", "(", "x", ".", "shape", ")", "is", "not", "1", ":", "raise", "ValueError", "(", "\"x ...
Returns: np.array of shape [len(x), n_bases + (add_intercept)] # BSpline formula https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.BSpline.html#scipy.interpolate.BSpline Fortran code: https://github.com/scipy/scipy/blob/v0.19.0/scipy/interpolate/fitpack/splev.f
[ "Returns", ":", "np", ".", "array", "of", "shape", "[", "len", "(", "x", ")", "n_bases", "+", "(", "add_intercept", ")", "]" ]
python
train
27.666667
mwolff44/django-simple-invoice
invoice/pdf_example.py
https://github.com/mwolff44/django-simple-invoice/blob/ab14d905a69f37cd27e137c039750e6630bce4ef/invoice/pdf_example.py#L64-L133
def draw_pdf(buffer, invoice): """ Draws the invoice """ canvas = Canvas(buffer, pagesize=A4) canvas.translate(0, 29.7 * cm) canvas.setFont('Helvetica', 10) canvas.saveState() header_func(canvas) canvas.restoreState() canvas.saveState() footer_func(canvas) canvas.restoreState()...
[ "def", "draw_pdf", "(", "buffer", ",", "invoice", ")", ":", "canvas", "=", "Canvas", "(", "buffer", ",", "pagesize", "=", "A4", ")", "canvas", ".", "translate", "(", "0", ",", "29.7", "*", "cm", ")", "canvas", ".", "setFont", "(", "'Helvetica'", ",",...
Draws the invoice
[ "Draws", "the", "invoice" ]
python
train
34.142857
Kozea/wdb
client/wdb/__init__.py
https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L116-L120
def pop(): """Remove instance from instance list""" pid = os.getpid() thread = threading.current_thread() Wdb._instances.pop((pid, thread))
[ "def", "pop", "(", ")", ":", "pid", "=", "os", ".", "getpid", "(", ")", "thread", "=", "threading", ".", "current_thread", "(", ")", "Wdb", ".", "_instances", ".", "pop", "(", "(", "pid", ",", "thread", ")", ")" ]
Remove instance from instance list
[ "Remove", "instance", "from", "instance", "list" ]
python
train
33.4
googleapis/google-cloud-python
bigquery/google/cloud/bigquery/table.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/table.py#L263-L279
def from_api_repr(cls, resource): """Factory: construct a table reference given its API representation Args: resource (Dict[str, object]): Table reference representation returned from the API Returns: google.cloud.bigquery.table.TableReference: ...
[ "def", "from_api_repr", "(", "cls", ",", "resource", ")", ":", "from", "google", ".", "cloud", ".", "bigquery", ".", "dataset", "import", "DatasetReference", "project", "=", "resource", "[", "\"projectId\"", "]", "dataset_id", "=", "resource", "[", "\"datasetI...
Factory: construct a table reference given its API representation Args: resource (Dict[str, object]): Table reference representation returned from the API Returns: google.cloud.bigquery.table.TableReference: Table reference parsed from ``resourc...
[ "Factory", ":", "construct", "a", "table", "reference", "given", "its", "API", "representation" ]
python
train
36.647059
ktbyers/netmiko
netmiko/ssh_autodetect.py
https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/ssh_autodetect.py#L269-L290
def _send_command_wrapper(self, cmd): """ Send command to the remote device with a caching feature to avoid sending the same command twice based on the SSH_MAPPER_BASE dict cmd key. Parameters ---------- cmd : str The command to send to the remote device afte...
[ "def", "_send_command_wrapper", "(", "self", ",", "cmd", ")", ":", "cached_results", "=", "self", ".", "_results_cache", ".", "get", "(", "cmd", ")", "if", "not", "cached_results", ":", "response", "=", "self", ".", "_send_command", "(", "cmd", ")", "self"...
Send command to the remote device with a caching feature to avoid sending the same command twice based on the SSH_MAPPER_BASE dict cmd key. Parameters ---------- cmd : str The command to send to the remote device after checking cache. Returns ------- ...
[ "Send", "command", "to", "the", "remote", "device", "with", "a", "caching", "feature", "to", "avoid", "sending", "the", "same", "command", "twice", "based", "on", "the", "SSH_MAPPER_BASE", "dict", "cmd", "key", "." ]
python
train
31.318182
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/ietf_netconf_notifications.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/ietf_netconf_notifications.py#L90-L100
def netconf_config_change_edit_operation(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") netconf_config_change = ET.SubElement(config, "netconf-config-change", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-notifications") edit = ET.SubElement(netconf_c...
[ "def", "netconf_config_change_edit_operation", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "netconf_config_change", "=", "ET", ".", "SubElement", "(", "config", ",", "\"netconf-config-change\"", ",...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
47.636364
unbit/sftpclone
sftpclone/sftpclone.py
https://github.com/unbit/sftpclone/blob/1cc89478e680fc4e0d12b1a15b5bafd0390d05da/sftpclone/sftpclone.py#L447-L460
def create_update_symlink(self, link_destination, remote_path): """Create a new link pointing to link_destination in remote_path position.""" try: # if there's anything, delete it self.sftp.remove(remote_path) except IOError: # that's fine, nothing exists there! pass ...
[ "def", "create_update_symlink", "(", "self", ",", "link_destination", ",", "remote_path", ")", ":", "try", ":", "# if there's anything, delete it", "self", ".", "sftp", ".", "remove", "(", "remote_path", ")", "except", "IOError", ":", "# that's fine, nothing exists th...
Create a new link pointing to link_destination in remote_path position.
[ "Create", "a", "new", "link", "pointing", "to", "link_destination", "in", "remote_path", "position", "." ]
python
train
51.642857
BlueBrain/NeuroM
neurom/core/_soma.py
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/core/_soma.py#L188-L191
def center(self): '''Obtain the center from the average of all points''' points = np.array(self._points) return np.mean(points[:, COLS.XYZ], axis=0)
[ "def", "center", "(", "self", ")", ":", "points", "=", "np", ".", "array", "(", "self", ".", "_points", ")", "return", "np", ".", "mean", "(", "points", "[", ":", ",", "COLS", ".", "XYZ", "]", ",", "axis", "=", "0", ")" ]
Obtain the center from the average of all points
[ "Obtain", "the", "center", "from", "the", "average", "of", "all", "points" ]
python
train
42.25
bykof/billomapy
billomapy/billomapy.py
https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L2552-L2567
def send_credit_note_email(self, credit_note_it, email_dict): """ Sends an credit note by email If you want to send your email to more than one persons do: 'recipients': {'to': ['bykof@me.com', 'mbykovski@seibert-media.net']}} :param credit_note_it: the credit note id :p...
[ "def", "send_credit_note_email", "(", "self", ",", "credit_note_it", ",", "email_dict", ")", ":", "return", "self", ".", "_create_post_request", "(", "resource", "=", "CREDIT_NOTES", ",", "billomat_id", "=", "credit_note_it", ",", "send_data", "=", "email_dict", "...
Sends an credit note by email If you want to send your email to more than one persons do: 'recipients': {'to': ['bykof@me.com', 'mbykovski@seibert-media.net']}} :param credit_note_it: the credit note id :param email_dict: the email dict :return dict
[ "Sends", "an", "credit", "note", "by", "email", "If", "you", "want", "to", "send", "your", "email", "to", "more", "than", "one", "persons", "do", ":", "recipients", ":", "{", "to", ":", "[", "bykof@me", ".", "com", "mbykovski@seibert", "-", "media", "....
python
train
34.8125
CalebBell/thermo
thermo/chemical.py
https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/chemical.py#L1314-L1330
def legal_status(self): r'''Dictionary of legal status indicators for the chemical. Examples -------- >>> pprint(Chemical('benzene').legal_status) {'DSL': 'LISTED', 'EINECS': 'LISTED', 'NLP': 'UNLISTED', 'SPIN': 'LISTED', 'TSCA': 'LISTED'} ...
[ "def", "legal_status", "(", "self", ")", ":", "if", "self", ".", "__legal_status", ":", "return", "self", ".", "__legal_status", "else", ":", "self", ".", "__legal_status", "=", "legal_status", "(", "self", ".", "CAS", ",", "Method", "=", "'COMBINED'", ")"...
r'''Dictionary of legal status indicators for the chemical. Examples -------- >>> pprint(Chemical('benzene').legal_status) {'DSL': 'LISTED', 'EINECS': 'LISTED', 'NLP': 'UNLISTED', 'SPIN': 'LISTED', 'TSCA': 'LISTED'}
[ "r", "Dictionary", "of", "legal", "status", "indicators", "for", "the", "chemical", "." ]
python
valid
30.117647
markuskiller/textblob-de
textblob_de/ext/_pattern/text/__init__.py
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/__init__.py#L112-L121
def pprint(string, token=[WORD, POS, CHUNK, PNP], column=4): """ Pretty-prints the output of Parser.parse() as a table with outlined columns. Alternatively, you can supply a tree.Text or tree.Sentence object. """ if isinstance(string, basestring): print("\n\n".join([table(sentence, fill=colu...
[ "def", "pprint", "(", "string", ",", "token", "=", "[", "WORD", ",", "POS", ",", "CHUNK", ",", "PNP", "]", ",", "column", "=", "4", ")", ":", "if", "isinstance", "(", "string", ",", "basestring", ")", ":", "print", "(", "\"\\n\\n\"", ".", "join", ...
Pretty-prints the output of Parser.parse() as a table with outlined columns. Alternatively, you can supply a tree.Text or tree.Sentence object.
[ "Pretty", "-", "prints", "the", "output", "of", "Parser", ".", "parse", "()", "as", "a", "table", "with", "outlined", "columns", ".", "Alternatively", "you", "can", "supply", "a", "tree", ".", "Text", "or", "tree", ".", "Sentence", "object", "." ]
python
train
54.7
django-fluent/django-fluent-utils
fluent_utils/softdeps/comments.py
https://github.com/django-fluent/django-fluent-utils/blob/5f93e5aa20f33a44133ad49fde4df0bfe1bc9f0b/fluent_utils/softdeps/comments.py#L98-L114
def get_comments_are_moderated(instance): """ Check if comments are moderated for the instance """ if not IS_INSTALLED: return False try: # Get the moderator which is installed for this model. mod = moderator._registry[instance.__class__] except KeyError: # No mo...
[ "def", "get_comments_are_moderated", "(", "instance", ")", ":", "if", "not", "IS_INSTALLED", ":", "return", "False", "try", ":", "# Get the moderator which is installed for this model.", "mod", "=", "moderator", ".", "_registry", "[", "instance", ".", "__class__", "]"...
Check if comments are moderated for the instance
[ "Check", "if", "comments", "are", "moderated", "for", "the", "instance" ]
python
train
30.235294
saltstack/salt
salt/modules/boto3_elasticache.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_elasticache.py#L411-L422
def replication_group_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if a replication group exists. Example: .. code-block:: bash salt myminion boto3_elasticache.replication_group_exists myelasticache ''' return bool(describe_replication_groups(name=na...
[ "def", "replication_group_exists", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "return", "bool", "(", "describe_replication_groups", "(", "name", "=", "name", ",", "r...
Check to see if a replication group exists. Example: .. code-block:: bash salt myminion boto3_elasticache.replication_group_exists myelasticache
[ "Check", "to", "see", "if", "a", "replication", "group", "exists", "." ]
python
train
31.916667
guaix-ucm/numina
numina/array/wavecalib/crosscorrelation.py
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/wavecalib/crosscorrelation.py#L105-L147
def convolve_comb_lines(lines_wave, lines_flux, sigma, crpix1, crval1, cdelt1, naxis1): """Convolve a set of lines of known wavelengths and flux. Parameters ---------- lines_wave : array like Input array with wavelengths lines_flux : array like Input array wi...
[ "def", "convolve_comb_lines", "(", "lines_wave", ",", "lines_flux", ",", "sigma", ",", "crpix1", ",", "crval1", ",", "cdelt1", ",", "naxis1", ")", ":", "# generate wavelengths for output spectrum", "xwave", "=", "crval1", "+", "(", "np", ".", "arange", "(", "n...
Convolve a set of lines of known wavelengths and flux. Parameters ---------- lines_wave : array like Input array with wavelengths lines_flux : array like Input array with fluxes sigma : float Sigma of the broadening gaussian to be applied. crpix1 : float CRPIX1 o...
[ "Convolve", "a", "set", "of", "lines", "of", "known", "wavelengths", "and", "flux", "." ]
python
train
29.255814
portfoliome/foil
foil/counting.py
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/counting.py#L5-L16
def count_by(records: Sequence[Dict], field_name: str) -> defaultdict: """ Frequency each value occurs in a record sequence for a given field name. """ counter = defaultdict(int) for record in records: name = record[field_name] counter[name] += 1 return counter
[ "def", "count_by", "(", "records", ":", "Sequence", "[", "Dict", "]", ",", "field_name", ":", "str", ")", "->", "defaultdict", ":", "counter", "=", "defaultdict", "(", "int", ")", "for", "record", "in", "records", ":", "name", "=", "record", "[", "fiel...
Frequency each value occurs in a record sequence for a given field name.
[ "Frequency", "each", "value", "occurs", "in", "a", "record", "sequence", "for", "a", "given", "field", "name", "." ]
python
train
24.416667
limodou/uliweb
uliweb/contrib/secretkey/__init__.py
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/secretkey/__init__.py#L5-L18
def get_cipher(key=None, keyfile=None): """ Get cipher object, and then you can invoke: des = get_cipher() d = des.encrpy('Hello') print des.descrpy(d) """ des_func = import_attr(settings.SECRETKEY.CIPHER_CLS) kwargs = settings.SECRETKEY.CIPHER_ARGS if not key: ...
[ "def", "get_cipher", "(", "key", "=", "None", ",", "keyfile", "=", "None", ")", ":", "des_func", "=", "import_attr", "(", "settings", ".", "SECRETKEY", ".", "CIPHER_CLS", ")", "kwargs", "=", "settings", ".", "SECRETKEY", ".", "CIPHER_ARGS", "if", "not", ...
Get cipher object, and then you can invoke: des = get_cipher() d = des.encrpy('Hello') print des.descrpy(d)
[ "Get", "cipher", "object", "and", "then", "you", "can", "invoke", ":", "des", "=", "get_cipher", "()", "d", "=", "des", ".", "encrpy", "(", "Hello", ")", "print", "des", ".", "descrpy", "(", "d", ")" ]
python
train
28.857143
wavycloud/pyboto3
pyboto3/elasticache.py
https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/elasticache.py#L702-L1009
def create_replication_group(ReplicationGroupId=None, ReplicationGroupDescription=None, PrimaryClusterId=None, AutomaticFailoverEnabled=None, NumCacheClusters=None, PreferredCacheClusterAZs=None, NumNodeGroups=None, ReplicasPerNodeGroup=None, NodeGroupConfiguration=None, CacheNodeType=None, Engine=None, EngineVersion=N...
[ "def", "create_replication_group", "(", "ReplicationGroupId", "=", "None", ",", "ReplicationGroupDescription", "=", "None", ",", "PrimaryClusterId", "=", "None", ",", "AutomaticFailoverEnabled", "=", "None", ",", "NumCacheClusters", "=", "None", ",", "PreferredCacheClus...
Creates a Redis (cluster mode disabled) or a Redis (cluster mode enabled) replication group. A Redis (cluster mode disabled) replication group is a collection of cache clusters, where one of the cache clusters is a read/write primary and the others are read-only replicas. Writes to the primary are asynchronously pr...
[ "Creates", "a", "Redis", "(", "cluster", "mode", "disabled", ")", "or", "a", "Redis", "(", "cluster", "mode", "enabled", ")", "replication", "group", ".", "A", "Redis", "(", "cluster", "mode", "disabled", ")", "replication", "group", "is", "a", "collection...
python
train
58.915584
OpenTreeOfLife/peyotl
peyotl/nexson_proxy.py
https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/nexson_proxy.py#L352-L394
def nexson_tree_preorder_iter(tree_proxy, node_id=None, node=None, edge_id=None, edge=None): """Takes a tree in "By ID" NexSON (v1.2). provides and iterator over: NexsonNodeProxy object where the edge of the object is the edge connectin the node to the parent. The first node will be the root and wi...
[ "def", "nexson_tree_preorder_iter", "(", "tree_proxy", ",", "node_id", "=", "None", ",", "node", "=", "None", ",", "edge_id", "=", "None", ",", "edge", "=", "None", ")", ":", "tree", "=", "tree_proxy", ".", "_nexson_tree", "ebsid", "=", "tree", "[", "'ed...
Takes a tree in "By ID" NexSON (v1.2). provides and iterator over: NexsonNodeProxy object where the edge of the object is the edge connectin the node to the parent. The first node will be the root and will have None as it's edge
[ "Takes", "a", "tree", "in", "By", "ID", "NexSON", "(", "v1", ".", "2", ")", ".", "provides", "and", "iterator", "over", ":", "NexsonNodeProxy", "object", "where", "the", "edge", "of", "the", "object", "is", "the", "edge", "connectin", "the", "node", "t...
python
train
42.511628
reingart/gui2py
gui/component.py
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/component.py#L365-L368
def set_parent(self, new_parent, init=False): "Store the gui/wx object parent for this component" # set init=True if this is called from the constructor self._parent = get(new_parent, init)
[ "def", "set_parent", "(", "self", ",", "new_parent", ",", "init", "=", "False", ")", ":", "# set init=True if this is called from the constructor\r", "self", ".", "_parent", "=", "get", "(", "new_parent", ",", "init", ")" ]
Store the gui/wx object parent for this component
[ "Store", "the", "gui", "/", "wx", "object", "parent", "for", "this", "component" ]
python
test
53.25
aws/sagemaker-containers
src/sagemaker_containers/_worker.py
https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_worker.py#L147-L159
def accept(self): # type: () -> str """The content-type for the response to the client. Returns: (str): The value of the header 'Accept' or the user-supplied SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT environment variable. """ accept = self.headers.get('Accept...
[ "def", "accept", "(", "self", ")", ":", "# type: () -> str", "accept", "=", "self", ".", "headers", ".", "get", "(", "'Accept'", ")", "if", "not", "accept", "or", "accept", "==", "_content_types", ".", "ANY", ":", "return", "self", ".", "_default_accept", ...
The content-type for the response to the client. Returns: (str): The value of the header 'Accept' or the user-supplied SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT environment variable.
[ "The", "content", "-", "type", "for", "the", "response", "to", "the", "client", "." ]
python
train
34.307692
yt-project/unyt
unyt/unit_object.py
https://github.com/yt-project/unyt/blob/7a4eafc229f83784f4c63d639aee554f9a6b1ca0/unyt/unit_object.py#L976-L1042
def define_unit( symbol, value, tex_repr=None, offset=None, prefixable=False, registry=None ): """ Define a new unit and add it to the specified unit registry. Parameters ---------- symbol : string The symbol for the new unit. value : tuple or :class:`unyt.array.unyt_quantity` ...
[ "def", "define_unit", "(", "symbol", ",", "value", ",", "tex_repr", "=", "None", ",", "offset", "=", "None", ",", "prefixable", "=", "False", ",", "registry", "=", "None", ")", ":", "from", "unyt", ".", "array", "import", "unyt_quantity", ",", "_iterable...
Define a new unit and add it to the specified unit registry. Parameters ---------- symbol : string The symbol for the new unit. value : tuple or :class:`unyt.array.unyt_quantity` The definition of the new unit in terms of some other units. For example, one would define a new "mp...
[ "Define", "a", "new", "unit", "and", "add", "it", "to", "the", "specified", "unit", "registry", "." ]
python
train
36.432836
kensho-technologies/graphql-compiler
graphql_compiler/compiler/workarounds/orientdb_query_execution.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/workarounds/orientdb_query_execution.py#L311-L350
def _expose_all_eligible_locations(match_query, location_types, eligible_locations): """Return a MATCH query where all eligible locations are valid as query start locations.""" eligible_location_types = dict() new_match_traversals = [] for current_traversal in match_query.match_traversals: new_...
[ "def", "_expose_all_eligible_locations", "(", "match_query", ",", "location_types", ",", "eligible_locations", ")", ":", "eligible_location_types", "=", "dict", "(", ")", "new_match_traversals", "=", "[", "]", "for", "current_traversal", "in", "match_query", ".", "mat...
Return a MATCH query where all eligible locations are valid as query start locations.
[ "Return", "a", "MATCH", "query", "where", "all", "eligible", "locations", "are", "valid", "as", "query", "start", "locations", "." ]
python
train
60.25
Chyroc/WechatSogou
wechatsogou/structuring.py
https://github.com/Chyroc/WechatSogou/blob/2e0e9886f555fd8bcfc7ae9718ced6ce955cd24a/wechatsogou/structuring.py#L381-L441
def get_gzh_article_by_hot(text): """从 首页热门搜索 提取公众号信息 和 文章列表信息 Parameters ---------- text : str or unicode 首页热门搜索 页 中 某一页 的文本 Returns ------- list[dict] { 'gzh': { 'headimage': str, # 公众号头像 ...
[ "def", "get_gzh_article_by_hot", "(", "text", ")", ":", "page", "=", "etree", ".", "HTML", "(", "text", ")", "lis", "=", "page", ".", "xpath", "(", "'/html/body/li'", ")", "gzh_article_list", "=", "[", "]", "for", "li", "in", "lis", ":", "url", "=", ...
从 首页热门搜索 提取公众号信息 和 文章列表信息 Parameters ---------- text : str or unicode 首页热门搜索 页 中 某一页 的文本 Returns ------- list[dict] { 'gzh': { 'headimage': str, # 公众号头像 'wechat_name': str, # 公众号名称 ...
[ "从", "首页热门搜索", "提取公众号信息", "和", "文章列表信息" ]
python
train
33.672131
mushkevych/scheduler
synergy/mq/flopsy.py
https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/synergy/mq/flopsy.py#L207-L212
def get(self): """ :return valid :mq::flopsy::Publisher instance """ if len(self.publishers) == 0: return Publisher(name=self.name, parent_pool=self) else: return self.publishers.pop()
[ "def", "get", "(", "self", ")", ":", "if", "len", "(", "self", ".", "publishers", ")", "==", "0", ":", "return", "Publisher", "(", "name", "=", "self", ".", "name", ",", "parent_pool", "=", "self", ")", "else", ":", "return", "self", ".", "publishe...
:return valid :mq::flopsy::Publisher instance
[ ":", "return", "valid", ":", "mq", "::", "flopsy", "::", "Publisher", "instance" ]
python
train
37.833333
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_GPSInput.py
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_GPSInput.py#L57-L94
def idle_task(self): '''called in idle time''' try: datagram = self.port.recvfrom(self.BUFFER_SIZE) data = json.loads(datagram[0]) except socket.error as e: if e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK ]: return ...
[ "def", "idle_task", "(", "self", ")", ":", "try", ":", "datagram", "=", "self", ".", "port", ".", "recvfrom", "(", "self", ".", "BUFFER_SIZE", ")", "data", "=", "json", ".", "loads", "(", "datagram", "[", "0", "]", ")", "except", "socket", ".", "er...
called in idle time
[ "called", "in", "idle", "time" ]
python
train
32.026316
PGower/PyCanvas
pycanvas/apis/files.py
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/files.py#L865-L919
def create_folder_courses(self, name, course_id, hidden=None, lock_at=None, locked=None, parent_folder_id=None, parent_folder_path=None, position=None, unlock_at=None): """ Create folder. Creates a folder in the specified context """ path = {} data = {} p...
[ "def", "create_folder_courses", "(", "self", ",", "name", ",", "course_id", ",", "hidden", "=", "None", ",", "lock_at", "=", "None", ",", "locked", "=", "None", ",", "parent_folder_id", "=", "None", ",", "parent_folder_path", "=", "None", ",", "position", ...
Create folder. Creates a folder in the specified context
[ "Create", "folder", ".", "Creates", "a", "folder", "in", "the", "specified", "context" ]
python
train
44.254545
spantaleev/flask-sijax
examples/chat.py
https://github.com/spantaleev/flask-sijax/blob/df9f6d9b8385b3375c119a51aa100491d5445e17/examples/chat.py#L28-L38
def check_csrf_token(): """Checks that token is correct, aborting if not""" if request.method in ("GET",): # not exhaustive list return token = request.form.get("csrf_token") if token is None: app.logger.warning("Expected CSRF Token: not present") abort(400) if not safe_str_c...
[ "def", "check_csrf_token", "(", ")", ":", "if", "request", ".", "method", "in", "(", "\"GET\"", ",", ")", ":", "# not exhaustive list", "return", "token", "=", "request", ".", "form", ".", "get", "(", "\"csrf_token\"", ")", "if", "token", "is", "None", "...
Checks that token is correct, aborting if not
[ "Checks", "that", "token", "is", "correct", "aborting", "if", "not" ]
python
train
36.727273
bitesofcode/projexui
projexui/widgets/xorbtreewidget/xorbtreewidget.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbtreewidget/xorbtreewidget.py#L1183-L1192
def emitRecordMiddleDoubleClicked(self, item): """ Emits the record clicked signal for the given item, provided the signals are not currently blocked. :param item | <QTreeWidgetItem> """ # emit that the record has been double clicked if isins...
[ "def", "emitRecordMiddleDoubleClicked", "(", "self", ",", "item", ")", ":", "# emit that the record has been double clicked\r", "if", "isinstance", "(", "item", ",", "XOrbRecordItem", ")", "and", "not", "self", ".", "signalsBlocked", "(", ")", ":", "self", ".", "r...
Emits the record clicked signal for the given item, provided the signals are not currently blocked. :param item | <QTreeWidgetItem>
[ "Emits", "the", "record", "clicked", "signal", "for", "the", "given", "item", "provided", "the", "signals", "are", "not", "currently", "blocked", ".", ":", "param", "item", "|", "<QTreeWidgetItem", ">" ]
python
train
43.3
abseil/abseil-py
absl/logging/__init__.py
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L1002-L1007
def warn(self, msg, *args, **kwargs): """Logs 'msg % args' with severity 'WARN'.""" if six.PY3: warnings.warn("The 'warn' method is deprecated, use 'warning' instead", DeprecationWarning, 2) self.log(logging.WARN, msg, *args, **kwargs)
[ "def", "warn", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "six", ".", "PY3", ":", "warnings", ".", "warn", "(", "\"The 'warn' method is deprecated, use 'warning' instead\"", ",", "DeprecationWarning", ",", "2", ")", ...
Logs 'msg % args' with severity 'WARN'.
[ "Logs", "msg", "%", "args", "with", "severity", "WARN", "." ]
python
train
44.666667
log2timeline/dfvfs
dfvfs/vfs/tsk_file_entry.py
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_file_entry.py#L784-L811
def GetFileObject(self, data_stream_name=''): """Retrieves the file-like object. Args: data_stream_name (Optional[str]): data stream name, where an empty string represents the default data stream. Returns: TSKFileIO: file-like object or None. """ data_stream_names = [ ...
[ "def", "GetFileObject", "(", "self", ",", "data_stream_name", "=", "''", ")", ":", "data_stream_names", "=", "[", "data_stream", ".", "name", "for", "data_stream", "in", "self", ".", "_GetDataStreams", "(", ")", "]", "if", "data_stream_name", "and", "data_stre...
Retrieves the file-like object. Args: data_stream_name (Optional[str]): data stream name, where an empty string represents the default data stream. Returns: TSKFileIO: file-like object or None.
[ "Retrieves", "the", "file", "-", "like", "object", "." ]
python
train
38.678571
saltstack/salt
salt/daemons/masterapi.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/daemons/masterapi.py#L1108-L1149
def runner(self, load): ''' Send a master control function back to the runner system ''' # All runner opts pass through eauth auth_type, err_name, key = self._prep_auth_info(load) # Authenticate auth_check = self.loadauth.check_authentication(load, auth_type) ...
[ "def", "runner", "(", "self", ",", "load", ")", ":", "# All runner opts pass through eauth", "auth_type", ",", "err_name", ",", "key", "=", "self", ".", "_prep_auth_info", "(", "load", ")", "# Authenticate", "auth_check", "=", "self", ".", "loadauth", ".", "ch...
Send a master control function back to the runner system
[ "Send", "a", "master", "control", "function", "back", "to", "the", "runner", "system" ]
python
train
40.619048
aleju/imgaug
imgaug/imgaug.py
https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L977-L1052
def draw_text(img, y, x, text, color=(0, 255, 0), size=25): """ Draw text on an image. This uses by default DejaVuSans as its font, which is included in this library. dtype support:: * ``uint8``: yes; fully tested * ``uint16``: no * ``uint32``: no * ``uint64``: no ...
[ "def", "draw_text", "(", "img", ",", "y", ",", "x", ",", "text", ",", "color", "=", "(", "0", ",", "255", ",", "0", ")", ",", "size", "=", "25", ")", ":", "do_assert", "(", "img", ".", "dtype", "in", "[", "np", ".", "uint8", ",", "np", ".",...
Draw text on an image. This uses by default DejaVuSans as its font, which is included in this library. dtype support:: * ``uint8``: yes; fully tested * ``uint16``: no * ``uint32``: no * ``uint64``: no * ``int8``: no * ``int16``: no * ``int32``: no ...
[ "Draw", "text", "on", "an", "image", "." ]
python
valid
26.552632
wavefrontHQ/python-client
wavefront_api_client/models/notificant.py
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/notificant.py#L131-L146
def content_type(self, content_type): """Sets the content_type of this Notificant. The value of the Content-Type header of the webhook POST request. # noqa: E501 :param content_type: The content_type of this Notificant. # noqa: E501 :type: str """ allowed_values = ["a...
[ "def", "content_type", "(", "self", ",", "content_type", ")", ":", "allowed_values", "=", "[", "\"application/json\"", ",", "\"text/html\"", ",", "\"text/plain\"", ",", "\"application/x-www-form-urlencoded\"", ",", "\"\"", "]", "# noqa: E501", "if", "content_type", "n...
Sets the content_type of this Notificant. The value of the Content-Type header of the webhook POST request. # noqa: E501 :param content_type: The content_type of this Notificant. # noqa: E501 :type: str
[ "Sets", "the", "content_type", "of", "this", "Notificant", "." ]
python
train
42.6875
phaethon/kamene
kamene/crypto/cert.py
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/crypto/cert.py#L664-L751
def _rsaes_oaep_decrypt(self, C, h=None, mgf=None, L=None): """ Internal method providing RSAES-OAEP-DECRYPT as defined in Sect. 7.1.2 of RFC 3447. Not intended to be used directly. Please, see encrypt() method for type "OAEP". Input: C : ciphertext to be decrypted,...
[ "def", "_rsaes_oaep_decrypt", "(", "self", ",", "C", ",", "h", "=", "None", ",", "mgf", "=", "None", ",", "L", "=", "None", ")", ":", "# The steps below are the one described in Sect. 7.1.2 of RFC 3447.", "# 1) Length Checking", "# 1.a) is not done", "if", "h", "is"...
Internal method providing RSAES-OAEP-DECRYPT as defined in Sect. 7.1.2 of RFC 3447. Not intended to be used directly. Please, see encrypt() method for type "OAEP". Input: C : ciphertext to be decrypted, an octet string of length k, where k = 2*hLen + 2 (k denotes th...
[ "Internal", "method", "providing", "RSAES", "-", "OAEP", "-", "DECRYPT", "as", "defined", "in", "Sect", ".", "7", ".", "1", ".", "2", "of", "RFC", "3447", ".", "Not", "intended", "to", "be", "used", "directly", ".", "Please", "see", "encrypt", "()", ...
python
train
40.556818
smarie/python-parsyfiles
parsyfiles/converting_core.py
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/converting_core.py#L806-L861
def chain(first_converter, second_converter, strict: bool): """ Utility method to chain two converters. If any of them is already a ConversionChain, this method "unpacks" it first. Note: the created conversion chain is created with the provided 'strict' flag, that may be different from t...
[ "def", "chain", "(", "first_converter", ",", "second_converter", ",", "strict", ":", "bool", ")", ":", "if", "isinstance", "(", "first_converter", ",", "ConversionChain", ")", ":", "if", "isinstance", "(", "second_converter", ",", "ConversionChain", ")", ":", ...
Utility method to chain two converters. If any of them is already a ConversionChain, this method "unpacks" it first. Note: the created conversion chain is created with the provided 'strict' flag, that may be different from the ones of the converters (if compliant). For example you may chain a 'strict' c...
[ "Utility", "method", "to", "chain", "two", "converters", ".", "If", "any", "of", "them", "is", "already", "a", "ConversionChain", "this", "method", "unpacks", "it", "first", ".", "Note", ":", "the", "created", "conversion", "chain", "is", "created", "with", ...
python
train
54.035714
eng-tools/sfsimodels
sfsimodels/files.py
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/files.py#L33-L51
def loads_json(p_str, custom=None, meta=False, verbose=0): """ Given a json string it creates a dictionary of sfsi objects :param ffp: str, Full file path to json file :param custom: dict, used to load custom objects, {model type: custom object} :param meta: bool, if true then also return all ecp m...
[ "def", "loads_json", "(", "p_str", ",", "custom", "=", "None", ",", "meta", "=", "False", ",", "verbose", "=", "0", ")", ":", "data", "=", "json", ".", "loads", "(", "p_str", ")", "if", "meta", ":", "md", "=", "{", "}", "for", "item", "in", "da...
Given a json string it creates a dictionary of sfsi objects :param ffp: str, Full file path to json file :param custom: dict, used to load custom objects, {model type: custom object} :param meta: bool, if true then also return all ecp meta data in separate dict :param verbose: int, console output :...
[ "Given", "a", "json", "string", "it", "creates", "a", "dictionary", "of", "sfsi", "objects" ]
python
train
36.526316
myint/language-check
language_check/__init__.py
https://github.com/myint/language-check/blob/58e419833ef28a9193fcaa21193616a8a14504a9/language_check/__init__.py#L493-L508
def correct(text: str, matches: [Match]) -> str: """Automatically apply suggestions to the text.""" ltext = list(text) matches = [match for match in matches if match.replacements] errors = [ltext[match.offset:match.offset + match.errorlength] for match in matches] correct_offset = 0 ...
[ "def", "correct", "(", "text", ":", "str", ",", "matches", ":", "[", "Match", "]", ")", "->", "str", ":", "ltext", "=", "list", "(", "text", ")", "matches", "=", "[", "match", "for", "match", "in", "matches", "if", "match", ".", "replacements", "]"...
Automatically apply suggestions to the text.
[ "Automatically", "apply", "suggestions", "to", "the", "text", "." ]
python
valid
43.8125
portfoliome/foil
foil/filters.py
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/filters.py#L38-L50
def create_key_filter(properties: Dict[str, list]) -> List[Tuple]: """Generate combinations of key, value pairs for each key in properties. Examples -------- properties = {'ent': ['geo_rev', 'supply_chain'], 'own', 'fi'} >> create_key_filter(properties) --> [('ent', 'geo_rev'), ('ent', 'suppl...
[ "def", "create_key_filter", "(", "properties", ":", "Dict", "[", "str", ",", "list", "]", ")", "->", "List", "[", "Tuple", "]", ":", "combinations", "=", "(", "product", "(", "[", "k", "]", ",", "v", ")", "for", "k", ",", "v", "in", "properties", ...
Generate combinations of key, value pairs for each key in properties. Examples -------- properties = {'ent': ['geo_rev', 'supply_chain'], 'own', 'fi'} >> create_key_filter(properties) --> [('ent', 'geo_rev'), ('ent', 'supply_chain'), ('own', 'fi')]
[ "Generate", "combinations", "of", "key", "value", "pairs", "for", "each", "key", "in", "properties", "." ]
python
train
35.076923
dnanexus/dx-toolkit
src/python/dxpy/bindings/dxproject.py
https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/bindings/dxproject.py#L284-L339
def new(self, name, summary=None, description=None, protected=None, restricted=None, download_restricted=None, contains_phi=None, tags=None, properties=None, bill_to=None, **kwargs): """ :param name: The name of the project :type name: string :param summary: If pr...
[ "def", "new", "(", "self", ",", "name", ",", "summary", "=", "None", ",", "description", "=", "None", ",", "protected", "=", "None", ",", "restricted", "=", "None", ",", "download_restricted", "=", "None", ",", "contains_phi", "=", "None", ",", "tags", ...
:param name: The name of the project :type name: string :param summary: If provided, a short summary of what the project contains :type summary: string :param description: If provided, the new project description :type name: string :param protected: If provided, whether t...
[ ":", "param", "name", ":", "The", "name", "of", "the", "project", ":", "type", "name", ":", "string", ":", "param", "summary", ":", "If", "provided", "a", "short", "summary", "of", "what", "the", "project", "contains", ":", "type", "summary", ":", "str...
python
train
49.267857
PmagPy/PmagPy
pmagpy/builder2.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/builder2.py#L247-L266
def add_specimen(self, spec_name, samp_name=None, er_data=None, pmag_data=None): """ Create a Specimen object and add it to self.specimens. If a sample name is provided, add the specimen to sample.specimens as well. """ if samp_name: sample = self.find_by_name(samp_na...
[ "def", "add_specimen", "(", "self", ",", "spec_name", ",", "samp_name", "=", "None", ",", "er_data", "=", "None", ",", "pmag_data", "=", "None", ")", ":", "if", "samp_name", ":", "sample", "=", "self", ".", "find_by_name", "(", "samp_name", ",", "self", ...
Create a Specimen object and add it to self.specimens. If a sample name is provided, add the specimen to sample.specimens as well.
[ "Create", "a", "Specimen", "object", "and", "add", "it", "to", "self", ".", "specimens", ".", "If", "a", "sample", "name", "is", "provided", "add", "the", "specimen", "to", "sample", ".", "specimens", "as", "well", "." ]
python
train
39.3
IdentityPython/pysaml2
src/saml2/__init__.py
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/__init__.py#L80-L97
def create_class_from_xml_string(target_class, xml_string): """Creates an instance of the target class from a string. :param target_class: The class which will be instantiated and populated with the contents of the XML. This class must have a c_tag and a c_namespace class variable. :param x...
[ "def", "create_class_from_xml_string", "(", "target_class", ",", "xml_string", ")", ":", "if", "not", "isinstance", "(", "xml_string", ",", "six", ".", "binary_type", ")", ":", "xml_string", "=", "xml_string", ".", "encode", "(", "'utf-8'", ")", "tree", "=", ...
Creates an instance of the target class from a string. :param target_class: The class which will be instantiated and populated with the contents of the XML. This class must have a c_tag and a c_namespace class variable. :param xml_string: A string which contains valid XML. The root element ...
[ "Creates", "an", "instance", "of", "the", "target", "class", "from", "a", "string", "." ]
python
train
49.388889
Alignak-monitoring/alignak
alignak/objects/host.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/host.py#L1220-L1234
def get_status(self, hosts, services): """Get the status of this host :return: "UP", "DOWN", "UNREACHABLE" or "n/a" based on host state_id or business_rule state :rtype: str """ if self.got_business_rule: mapping = { 0: "UP", 1: "DOWN"...
[ "def", "get_status", "(", "self", ",", "hosts", ",", "services", ")", ":", "if", "self", ".", "got_business_rule", ":", "mapping", "=", "{", "0", ":", "\"UP\"", ",", "1", ":", "\"DOWN\"", ",", "4", ":", "\"UNREACHABLE\"", ",", "}", "return", "mapping",...
Get the status of this host :return: "UP", "DOWN", "UNREACHABLE" or "n/a" based on host state_id or business_rule state :rtype: str
[ "Get", "the", "status", "of", "this", "host" ]
python
train
31.133333
anomaly/vishnu
vishnu/util.py
https://github.com/anomaly/vishnu/blob/5b3a6a69beedc8554cc506ddfab273760d61dc65/vishnu/util.py#L3-L30
def google_app_engine_ndb_delete_expired_sessions(dormant_for=86400, limit=500): """ Deletes expired sessions A session is expired if it expires date is set and has passed or if it has not been accessed for a given period of time. :param dormant_for: seconds since last access to delete sessions, de...
[ "def", "google_app_engine_ndb_delete_expired_sessions", "(", "dormant_for", "=", "86400", ",", "limit", "=", "500", ")", ":", "from", "vishnu", ".", "backend", ".", "client", ".", "google_app_engine_ndb", "import", "VishnuSession", "from", "google", ".", "appengine"...
Deletes expired sessions A session is expired if it expires date is set and has passed or if it has not been accessed for a given period of time. :param dormant_for: seconds since last access to delete sessions, defaults to 24 hours. :type dormant_for: int :param limit: amount to delete in one call...
[ "Deletes", "expired", "sessions", "A", "session", "is", "expired", "if", "it", "expires", "date", "is", "set", "and", "has", "passed", "or", "if", "it", "has", "not", "been", "accessed", "for", "a", "given", "period", "of", "time", "." ]
python
train
37.892857
tsroten/dragonmapper
dragonmapper/transcriptions.py
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L233-L240
def pinyin_syllable_to_ipa(s): """Convert Pinyin syllable *s* to an IPA syllable.""" pinyin_syllable, tone = _parse_pinyin_syllable(s) try: ipa_syllable = _PINYIN_MAP[pinyin_syllable.lower()]['IPA'] except KeyError: raise ValueError('Not a valid syllable: %s' % s) return ipa_syllable...
[ "def", "pinyin_syllable_to_ipa", "(", "s", ")", ":", "pinyin_syllable", ",", "tone", "=", "_parse_pinyin_syllable", "(", "s", ")", "try", ":", "ipa_syllable", "=", "_PINYIN_MAP", "[", "pinyin_syllable", ".", "lower", "(", ")", "]", "[", "'IPA'", "]", "except...
Convert Pinyin syllable *s* to an IPA syllable.
[ "Convert", "Pinyin", "syllable", "*", "s", "*", "to", "an", "IPA", "syllable", "." ]
python
train
41.5
mmp2/megaman
megaman/geometry/geometry.py
https://github.com/mmp2/megaman/blob/faccaf267aad0a8b18ec8a705735fd9dd838ca1e/megaman/geometry/geometry.py#L142-L151
def set_matrix(self, X, input_type): """Set the data matrix given the (string) input_type""" if input_type == 'data': self.set_data_matrix(X) elif input_type == 'adjacency': self.set_adjacency_matrix(X) elif input_type == 'affinity': self.set_affinity_...
[ "def", "set_matrix", "(", "self", ",", "X", ",", "input_type", ")", ":", "if", "input_type", "==", "'data'", ":", "self", ".", "set_data_matrix", "(", "X", ")", "elif", "input_type", "==", "'adjacency'", ":", "self", ".", "set_adjacency_matrix", "(", "X", ...
Set the data matrix given the (string) input_type
[ "Set", "the", "data", "matrix", "given", "the", "(", "string", ")", "input_type" ]
python
train
41.4
deepmipt/DeepPavlov
deeppavlov/metrics/bleu.py
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/metrics/bleu.py#L27-L55
def bleu_advanced(y_true: List[Any], y_predicted: List[Any], weights: Tuple=(1,), smoothing_function=SMOOTH.method1, auto_reweigh=False, penalty=True) -> float: """Calculate BLEU score Parameters: y_true: list of reference tokens y_predicted: list of query to...
[ "def", "bleu_advanced", "(", "y_true", ":", "List", "[", "Any", "]", ",", "y_predicted", ":", "List", "[", "Any", "]", ",", "weights", ":", "Tuple", "=", "(", "1", ",", ")", ",", "smoothing_function", "=", "SMOOTH", ".", "method1", ",", "auto_reweigh",...
Calculate BLEU score Parameters: y_true: list of reference tokens y_predicted: list of query tokens weights: n-gram weights smoothing_function: SmoothingFunction auto_reweigh: Option to re-normalize the weights uniformly penalty: either enable brevity penalty or not ...
[ "Calculate", "BLEU", "score" ]
python
test
31.413793
pybel/pybel-tools
src/pybel_tools/selection/group_nodes.py
https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/selection/group_nodes.py#L22-L33
def group_nodes_by_annotation(graph: BELGraph, annotation: str = 'Subgraph') -> Mapping[str, Set[BaseEntity]]: """Group the nodes occurring in edges by the given annotation.""" result = defaultdict(set) for u, v, d in graph.edges(data=True): if not edge_has_annotation(d, annotation): co...
[ "def", "group_nodes_by_annotation", "(", "graph", ":", "BELGraph", ",", "annotation", ":", "str", "=", "'Subgraph'", ")", "->", "Mapping", "[", "str", ",", "Set", "[", "BaseEntity", "]", "]", ":", "result", "=", "defaultdict", "(", "set", ")", "for", "u"...
Group the nodes occurring in edges by the given annotation.
[ "Group", "the", "nodes", "occurring", "in", "edges", "by", "the", "given", "annotation", "." ]
python
valid
36.75
sorgerlab/indra
indra/tools/incremental_model.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/incremental_model.py#L165-L177
def get_statements(self): """Return a list of all Statements in a single list. Returns ------- stmts : list[indra.statements.Statement] A list of all the INDRA Statements in the model. """ stmt_lists = [v for k, v in self.stmts.items()] stmts = [] ...
[ "def", "get_statements", "(", "self", ")", ":", "stmt_lists", "=", "[", "v", "for", "k", ",", "v", "in", "self", ".", "stmts", ".", "items", "(", ")", "]", "stmts", "=", "[", "]", "for", "s", "in", "stmt_lists", ":", "stmts", "+=", "s", "return",...
Return a list of all Statements in a single list. Returns ------- stmts : list[indra.statements.Statement] A list of all the INDRA Statements in the model.
[ "Return", "a", "list", "of", "all", "Statements", "in", "a", "single", "list", "." ]
python
train
29
Pytwitcher/pytwitcherapi
src/pytwitcherapi/session.py
https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/session.py#L391-L425
def get_streams(self, game=None, channels=None, limit=25, offset=0): """Return a list of streams queried by a number of parameters sorted by number of viewers descending :param game: the game or name of the game :type game: :class:`str` | :class:`models.Game` :param channels: li...
[ "def", "get_streams", "(", "self", ",", "game", "=", "None", ",", "channels", "=", "None", ",", "limit", "=", "25", ",", "offset", "=", "0", ")", ":", "if", "isinstance", "(", "game", ",", "models", ".", "Game", ")", ":", "game", "=", "game", "."...
Return a list of streams queried by a number of parameters sorted by number of viewers descending :param game: the game or name of the game :type game: :class:`str` | :class:`models.Game` :param channels: list of models.Channels or channel names (can be mixed) :type channels: :c...
[ "Return", "a", "list", "of", "streams", "queried", "by", "a", "number", "of", "parameters", "sorted", "by", "number", "of", "viewers", "descending" ]
python
train
36.971429
aichaos/rivescript-python
rivescript/rivescript.py
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L693-L702
def set_uservar(self, user, name, value): """Set a variable for a user. This is like the ``<set>`` tag in RiveScript code. :param str user: The user ID to set a variable for. :param str name: The name of the variable to set. :param str value: The value to set there. """...
[ "def", "set_uservar", "(", "self", ",", "user", ",", "name", ",", "value", ")", ":", "self", ".", "_session", ".", "set", "(", "user", ",", "{", "name", ":", "value", "}", ")" ]
Set a variable for a user. This is like the ``<set>`` tag in RiveScript code. :param str user: The user ID to set a variable for. :param str name: The name of the variable to set. :param str value: The value to set there.
[ "Set", "a", "variable", "for", "a", "user", "." ]
python
train
35.8
AndrewAnnex/SpiceyPy
spiceypy/spiceypy.py
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L4625-L4653
def ekuced(handle, segno, recno, column, nvals, dvals, isnull): """ Update a double precision column entry in a specified EK record. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekuced_c.html :param handle: EK file handle. :type handle: int :param segno: Index of segment containing ...
[ "def", "ekuced", "(", "handle", ",", "segno", ",", "recno", ",", "column", ",", "nvals", ",", "dvals", ",", "isnull", ")", ":", "handle", "=", "ctypes", ".", "c_int", "(", "handle", ")", "segno", "=", "ctypes", ".", "c_int", "(", "segno", ")", "rec...
Update a double precision column entry in a specified EK record. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekuced_c.html :param handle: EK file handle. :type handle: int :param segno: Index of segment containing record. :type segno: int :param recno: Record to which data is to be...
[ "Update", "a", "double", "precision", "column", "entry", "in", "a", "specified", "EK", "record", "." ]
python
train
36.206897
aws/sagemaker-python-sdk
src/sagemaker/session.py
https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/session.py#L1266-L1294
def production_variant(model_name, instance_type, initial_instance_count=1, variant_name='AllTraffic', initial_weight=1, accelerator_type=None): """Create a production variant description suitable for use in a ``ProductionVariant`` list as part of a ``CreateEndpointConfig`` request. ...
[ "def", "production_variant", "(", "model_name", ",", "instance_type", ",", "initial_instance_count", "=", "1", ",", "variant_name", "=", "'AllTraffic'", ",", "initial_weight", "=", "1", ",", "accelerator_type", "=", "None", ")", ":", "production_variant_configuration"...
Create a production variant description suitable for use in a ``ProductionVariant`` list as part of a ``CreateEndpointConfig`` request. Args: model_name (str): The name of the SageMaker model this production variant references. instance_type (str): The EC2 instance type for this production vari...
[ "Create", "a", "production", "variant", "description", "suitable", "for", "use", "in", "a", "ProductionVariant", "list", "as", "part", "of", "a", "CreateEndpointConfig", "request", "." ]
python
train
53.172414
blockstack/blockstack-core
blockstack/lib/scripts.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/scripts.py#L475-L502
def check_subdomain(fqn): """ Verify that the given fqn is a subdomain >>> check_subdomain('a.b.c') True >>> check_subdomain(123) False >>> check_subdomain('a.b.c.d') False >>> check_subdomain('A.b.c') False >>> check_subdomain('abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdab...
[ "def", "check_subdomain", "(", "fqn", ")", ":", "if", "type", "(", "fqn", ")", "not", "in", "[", "str", ",", "unicode", "]", ":", "return", "False", "if", "not", "is_subdomain", "(", "fqn", ")", ":", "return", "False", "return", "True" ]
Verify that the given fqn is a subdomain >>> check_subdomain('a.b.c') True >>> check_subdomain(123) False >>> check_subdomain('a.b.c.d') False >>> check_subdomain('A.b.c') False >>> check_subdomain('abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd.a.b') True >>> check_subdom...
[ "Verify", "that", "the", "given", "fqn", "is", "a", "subdomain" ]
python
train
23.107143
kstaniek/condoor
condoor/drivers/XR.py
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/XR.py#L145-L149
def rollback(self, label, plane): """Rollback config.""" cm_label = 'condoor-{}'.format(int(time.time())) self.device.send(self.rollback_cmd.format(label), timeout=120) return cm_label
[ "def", "rollback", "(", "self", ",", "label", ",", "plane", ")", ":", "cm_label", "=", "'condoor-{}'", ".", "format", "(", "int", "(", "time", ".", "time", "(", ")", ")", ")", "self", ".", "device", ".", "send", "(", "self", ".", "rollback_cmd", "....
Rollback config.
[ "Rollback", "config", "." ]
python
train
42.4
aiortc/aiortc
aiortc/rtcsctptransport.py
https://github.com/aiortc/aiortc/blob/60ed036abf4575bd63985724b4493d569e6da29b/aiortc/rtcsctptransport.py#L850-L971
async def _receive_chunk(self, chunk): """ Handle an incoming chunk. """ self.__log_debug('< %s', chunk) # common if isinstance(chunk, DataChunk): await self._receive_data_chunk(chunk) elif isinstance(chunk, SackChunk): await self._receive...
[ "async", "def", "_receive_chunk", "(", "self", ",", "chunk", ")", ":", "self", ".", "__log_debug", "(", "'< %s'", ",", "chunk", ")", "# common", "if", "isinstance", "(", "chunk", ",", "DataChunk", ")", ":", "await", "self", ".", "_receive_data_chunk", "(",...
Handle an incoming chunk.
[ "Handle", "an", "incoming", "chunk", "." ]
python
train
45.721311
androguard/androguard
generators/axplorer_to_androguard.py
https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/generators/axplorer_to_androguard.py#L56-L74
def convert_name(s): """ Converts a line of axplorer format into androguard method signature + permission :param s: :return: """ m = re.compile(r"^(.*)\.(.*)\((.*)\)(.*) :: (.*)$") res = m.search(s) if res: clname, methodname, all_args, ret, perm = res.groups() args = "...
[ "def", "convert_name", "(", "s", ")", ":", "m", "=", "re", ".", "compile", "(", "r\"^(.*)\\.(.*)\\((.*)\\)(.*) :: (.*)$\"", ")", "res", "=", "m", ".", "search", "(", "s", ")", "if", "res", ":", "clname", ",", "methodname", ",", "all_args", ",", "ret", ...
Converts a line of axplorer format into androguard method signature + permission :param s: :return:
[ "Converts", "a", "line", "of", "axplorer", "format", "into", "androguard", "method", "signature", "+", "permission", ":", "param", "s", ":", ":", "return", ":" ]
python
train
33.368421
bxlab/bx-python
lib/bx_extras/lrucache.py
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/lrucache.py#L203-L211
def mtime(self, key): """Return the last modification time for the cache record with key. May be useful for cache instances where the stored values can get 'stale', such as caching file or network resource contents.""" if key not in self.__dict: raise CacheKeyError(key) ...
[ "def", "mtime", "(", "self", ",", "key", ")", ":", "if", "key", "not", "in", "self", ".", "__dict", ":", "raise", "CacheKeyError", "(", "key", ")", "else", ":", "node", "=", "self", ".", "__dict", "[", "key", "]", "return", "node", ".", "mtime" ]
Return the last modification time for the cache record with key. May be useful for cache instances where the stored values can get 'stale', such as caching file or network resource contents.
[ "Return", "the", "last", "modification", "time", "for", "the", "cache", "record", "with", "key", ".", "May", "be", "useful", "for", "cache", "instances", "where", "the", "stored", "values", "can", "get", "stale", "such", "as", "caching", "file", "or", "net...
python
train
42.888889
StanfordBioinformatics/loom
client/loomengine/playbooks/gce.py
https://github.com/StanfordBioinformatics/loom/blob/db2031a1a87124fee1aeb7414a668c03d774a698/client/loomengine/playbooks/gce.py#L314-L320
def parse_env_zones(self): '''returns a list of comma separated zones parsed from the GCE_ZONE environment variable. If provided, this will be used to filter the results of the grouped_instances call''' import csv reader = csv.reader([os.environ.get('GCE_ZONE',"")], skipinitialspace=True...
[ "def", "parse_env_zones", "(", "self", ")", ":", "import", "csv", "reader", "=", "csv", ".", "reader", "(", "[", "os", ".", "environ", ".", "get", "(", "'GCE_ZONE'", ",", "\"\"", ")", "]", ",", "skipinitialspace", "=", "True", ")", "zones", "=", "[",...
returns a list of comma separated zones parsed from the GCE_ZONE environment variable. If provided, this will be used to filter the results of the grouped_instances call
[ "returns", "a", "list", "of", "comma", "separated", "zones", "parsed", "from", "the", "GCE_ZONE", "environment", "variable", ".", "If", "provided", "this", "will", "be", "used", "to", "filter", "the", "results", "of", "the", "grouped_instances", "call" ]
python
train
55.428571
frictionlessdata/tabulator-py
tabulator/validate.py
https://github.com/frictionlessdata/tabulator-py/blob/06c25845a7139d919326388cc6335f33f909db8c/tabulator/validate.py#L14-L42
def validate(source, scheme=None, format=None): '''Check if tabulator is able to load the source. Args: source (Union[str, IO]): The source path or IO object. scheme (str, optional): The source scheme. Auto-detect by default. format (str, optional): The source file format. Auto-detect b...
[ "def", "validate", "(", "source", ",", "scheme", "=", "None", ",", "format", "=", "None", ")", ":", "# Get scheme and format", "detected_scheme", ",", "detected_format", "=", "helpers", ".", "detect_scheme_and_format", "(", "source", ")", "scheme", "=", "scheme"...
Check if tabulator is able to load the source. Args: source (Union[str, IO]): The source path or IO object. scheme (str, optional): The source scheme. Auto-detect by default. format (str, optional): The source file format. Auto-detect by default. Returns: bool: Whether tabulato...
[ "Check", "if", "tabulator", "is", "able", "to", "load", "the", "source", "." ]
python
train
36.586207
Clinical-Genomics/scout
scout/parse/panel.py
https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/parse/panel.py#L374-L418
def get_omim_panel_genes(genemap2_lines, mim2gene_lines, alias_genes): """Return all genes that should be included in the OMIM-AUTO panel Return the hgnc symbols Genes that have at least one 'established' or 'provisional' phenotype connection are included in the gene panel Args: ge...
[ "def", "get_omim_panel_genes", "(", "genemap2_lines", ",", "mim2gene_lines", ",", "alias_genes", ")", ":", "parsed_genes", "=", "get_mim_genes", "(", "genemap2_lines", ",", "mim2gene_lines", ")", "STATUS_TO_ADD", "=", "set", "(", "[", "'established'", ",", "'provisi...
Return all genes that should be included in the OMIM-AUTO panel Return the hgnc symbols Genes that have at least one 'established' or 'provisional' phenotype connection are included in the gene panel Args: genemap2_lines(iterable) mim2gene_lines(iterable) alias_genes(di...
[ "Return", "all", "genes", "that", "should", "be", "included", "in", "the", "OMIM", "-", "AUTO", "panel", "Return", "the", "hgnc", "symbols", "Genes", "that", "have", "at", "least", "one", "established", "or", "provisional", "phenotype", "connection", "are", ...
python
test
34.733333
pywavefront/PyWavefront
pywavefront/obj.py
https://github.com/pywavefront/PyWavefront/blob/39ee5186cb37750d4654d19ebe43f723ecd01e2f/pywavefront/obj.py#L159-L179
def consume_normals(self): """Consumes all consecutive texture coordinate lines""" # The first iteration processes the current/first vn statement. # The loop continues until there are no more vn-statements or StopIteration is raised by generator while True: yield ( ...
[ "def", "consume_normals", "(", "self", ")", ":", "# The first iteration processes the current/first vn statement.", "# The loop continues until there are no more vn-statements or StopIteration is raised by generator", "while", "True", ":", "yield", "(", "float", "(", "self", ".", "...
Consumes all consecutive texture coordinate lines
[ "Consumes", "all", "consecutive", "texture", "coordinate", "lines" ]
python
train
30.666667
juju/python-libjuju
juju/model.py
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L875-L896
async def _notify_observers(self, delta, old_obj, new_obj): """Call observing callbacks, notifying them of a change in model state :param delta: The raw change from the watcher (:class:`juju.client.overrides.Delta`) :param old_obj: The object in the model that this delta updates. ...
[ "async", "def", "_notify_observers", "(", "self", ",", "delta", ",", "old_obj", ",", "new_obj", ")", ":", "if", "new_obj", "and", "not", "old_obj", ":", "delta", ".", "type", "=", "'add'", "log", ".", "debug", "(", "'Model changed: %s %s %s'", ",", "delta"...
Call observing callbacks, notifying them of a change in model state :param delta: The raw change from the watcher (:class:`juju.client.overrides.Delta`) :param old_obj: The object in the model that this delta updates. May be None. :param new_obj: The object in the model ...
[ "Call", "observing", "callbacks", "notifying", "them", "of", "a", "change", "in", "model", "state" ]
python
train
37.909091
joshspeagle/dynesty
dynesty/bounding.py
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/bounding.py#L253-L263
def unitcube_overlap(self, ndraws=10000, rstate=None): """Using `ndraws` Monte Carlo draws, estimate the fraction of overlap between the ellipsoid and the unit cube.""" if rstate is None: rstate = np.random samples = [self.sample(rstate=rstate) for i in range(ndraws)] ...
[ "def", "unitcube_overlap", "(", "self", ",", "ndraws", "=", "10000", ",", "rstate", "=", "None", ")", ":", "if", "rstate", "is", "None", ":", "rstate", "=", "np", ".", "random", "samples", "=", "[", "self", ".", "sample", "(", "rstate", "=", "rstate"...
Using `ndraws` Monte Carlo draws, estimate the fraction of overlap between the ellipsoid and the unit cube.
[ "Using", "ndraws", "Monte", "Carlo", "draws", "estimate", "the", "fraction", "of", "overlap", "between", "the", "ellipsoid", "and", "the", "unit", "cube", "." ]
python
train
35.363636
tensorflow/tensor2tensor
tensor2tensor/trax/trax.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/trax.py#L280-L304
def _jit_predict_fun(model_predict, num_devices): """Use jit on model_predict if required.""" def predict(x, params=(), rng=None): """Predict function jited and parallelized as requested.""" # On one device, jit and run. if num_devices == 1: return backend.jit(model_predict)(x, params, rng=rng) ...
[ "def", "_jit_predict_fun", "(", "model_predict", ",", "num_devices", ")", ":", "def", "predict", "(", "x", ",", "params", "=", "(", ")", ",", "rng", "=", "None", ")", ":", "\"\"\"Predict function jited and parallelized as requested.\"\"\"", "# On one device, jit and r...
Use jit on model_predict if required.
[ "Use", "jit", "on", "model_predict", "if", "required", "." ]
python
train
40.32
Alignak-monitoring/alignak
alignak/objects/host.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/host.py#L1438-L1464
def explode(self, hostgroups, contactgroups): """Explode hosts with hostgroups, contactgroups:: * Add contact from contactgroups to host contacts * Add host into their hostgroups as hostgroup members :param hostgroups: Hostgroups to explode :type hostgroups: alignak.objects.hos...
[ "def", "explode", "(", "self", ",", "hostgroups", ",", "contactgroups", ")", ":", "for", "template", "in", "list", "(", "self", ".", "templates", ".", "values", "(", ")", ")", ":", "# items::explode_contact_groups_into_contacts", "# take all contacts from our contac...
Explode hosts with hostgroups, contactgroups:: * Add contact from contactgroups to host contacts * Add host into their hostgroups as hostgroup members :param hostgroups: Hostgroups to explode :type hostgroups: alignak.objects.hostgroup.Hostgroups :param contactgroups: Contactgo...
[ "Explode", "hosts", "with", "hostgroups", "contactgroups", "::" ]
python
train
46.777778
pallets/werkzeug
src/werkzeug/wrappers/base_response.py
https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/wrappers/base_response.py#L522-L532
def close(self): """Close the wrapped response if possible. You can also use the object in a with statement which will automatically close it. .. versionadded:: 0.9 Can now be used in a with statement. """ if hasattr(self.response, "close"): self.response...
[ "def", "close", "(", "self", ")", ":", "if", "hasattr", "(", "self", ".", "response", ",", "\"close\"", ")", ":", "self", ".", "response", ".", "close", "(", ")", "for", "func", "in", "self", ".", "_on_close", ":", "func", "(", ")" ]
Close the wrapped response if possible. You can also use the object in a with statement which will automatically close it. .. versionadded:: 0.9 Can now be used in a with statement.
[ "Close", "the", "wrapped", "response", "if", "possible", ".", "You", "can", "also", "use", "the", "object", "in", "a", "with", "statement", "which", "will", "automatically", "close", "it", "." ]
python
train
33.909091
python-rope/rope
rope/refactor/introduce_factory.py
https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/introduce_factory.py#L26-L46
def get_changes(self, factory_name, global_factory=False, resources=None, task_handle=taskhandle.NullTaskHandle()): """Get the changes this refactoring makes `factory_name` indicates the name of the factory function to be added. If `global_factory` is `True` the factory wil...
[ "def", "get_changes", "(", "self", ",", "factory_name", ",", "global_factory", "=", "False", ",", "resources", "=", "None", ",", "task_handle", "=", "taskhandle", ".", "NullTaskHandle", "(", ")", ")", ":", "if", "resources", "is", "None", ":", "resources", ...
Get the changes this refactoring makes `factory_name` indicates the name of the factory function to be added. If `global_factory` is `True` the factory will be global otherwise a static method is added to the class. `resources` can be a list of `rope.base.resource.File`\s that ...
[ "Get", "the", "changes", "this", "refactoring", "makes" ]
python
train
47.095238
awslabs/serverless-application-model
samtranslator/intrinsics/resolver.py
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/intrinsics/resolver.py#L134-L146
def _traverse_dict(self, input_dict, resolution_data, resolver_method): """ Traverse a dictionary to resolve intrinsic functions on every value :param input_dict: Input dictionary to traverse :param resolution_data: Data that the `resolver_method` needs to operate :param resolve...
[ "def", "_traverse_dict", "(", "self", ",", "input_dict", ",", "resolution_data", ",", "resolver_method", ")", ":", "for", "key", ",", "value", "in", "input_dict", ".", "items", "(", ")", ":", "input_dict", "[", "key", "]", "=", "self", ".", "_traverse", ...
Traverse a dictionary to resolve intrinsic functions on every value :param input_dict: Input dictionary to traverse :param resolution_data: Data that the `resolver_method` needs to operate :param resolver_method: Method that can actually resolve an intrinsic function, if it detects one ...
[ "Traverse", "a", "dictionary", "to", "resolve", "intrinsic", "functions", "on", "every", "value" ]
python
train
47.692308
totalgood/twip
twip/plot.py
https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/plot.py#L153-L191
def score_hist(df, columns=None, groupby=None, threshold=0.7, stacked=True, bins=20, percent=True, alpha=0.33, show=True, block=False, save=False): """Plot multiple histograms on one plot, typically of "score" values between 0 and 1 Typically the groupby or columns of the dataframe are the classi...
[ "def", "score_hist", "(", "df", ",", "columns", "=", "None", ",", "groupby", "=", "None", ",", "threshold", "=", "0.7", ",", "stacked", "=", "True", ",", "bins", "=", "20", ",", "percent", "=", "True", ",", "alpha", "=", "0.33", ",", "show", "=", ...
Plot multiple histograms on one plot, typically of "score" values between 0 and 1 Typically the groupby or columns of the dataframe are the classification categories (0, .5, 1) And the values are scores between 0 and 1.
[ "Plot", "multiple", "histograms", "on", "one", "plot", "typically", "of", "score", "values", "between", "0", "and", "1", "Typically", "the", "groupby", "or", "columns", "of", "the", "dataframe", "are", "the", "classification", "categories", "(", "0", ".", "5...
python
train
46.076923
borntyping/python-riemann-client
riemann_client/transport.py
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/transport.py#L130-L147
def send(self, message): """Sends a message to a Riemann server and returns it's response :param message: The message to send to the Riemann server :returns: The response message from Riemann :raises RiemannError: if the server returns an error """ message = message.Seri...
[ "def", "send", "(", "self", ",", "message", ")", ":", "message", "=", "message", ".", "SerializeToString", "(", ")", "self", ".", "socket", ".", "sendall", "(", "struct", ".", "pack", "(", "'!I'", ",", "len", "(", "message", ")", ")", "+", "message",...
Sends a message to a Riemann server and returns it's response :param message: The message to send to the Riemann server :returns: The response message from Riemann :raises RiemannError: if the server returns an error
[ "Sends", "a", "message", "to", "a", "Riemann", "server", "and", "returns", "it", "s", "response" ]
python
train
37.444444
saulpw/visidata
visidata/movement.py
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/movement.py#L64-L107
def searchRegex(vd, sheet, moveCursor=False, reverse=False, **kwargs): 'Set row index if moveCursor, otherwise return list of row indexes.' def findMatchingColumn(sheet, row, columns, func): 'Find column for which func matches the displayed value in this row' for c in columns: ...
[ "def", "searchRegex", "(", "vd", ",", "sheet", ",", "moveCursor", "=", "False", ",", "reverse", "=", "False", ",", "*", "*", "kwargs", ")", ":", "def", "findMatchingColumn", "(", "sheet", ",", "row", ",", "columns", ",", "func", ")", ":", "'Find column...
Set row index if moveCursor, otherwise return list of row indexes.
[ "Set", "row", "index", "if", "moveCursor", "otherwise", "return", "list", "of", "row", "indexes", "." ]
python
train
38
yougov/elastic2-doc-manager
mongo_connector/doc_managers/elastic2_doc_manager.py
https://github.com/yougov/elastic2-doc-manager/blob/ad92138d1fd6656bb2e71cb5cc840f9ba0109c49/mongo_connector/doc_managers/elastic2_doc_manager.py#L620-L627
def get_docs_sources_from_ES(self): """Get document sources using MGET elasticsearch API""" docs = [doc for doc, _, _, get_from_ES in self.doc_to_update if get_from_ES] if docs: documents = self.docman.elastic.mget(body={"docs": docs}, realtime=True) return iter(documents...
[ "def", "get_docs_sources_from_ES", "(", "self", ")", ":", "docs", "=", "[", "doc", "for", "doc", ",", "_", ",", "_", ",", "get_from_ES", "in", "self", ".", "doc_to_update", "if", "get_from_ES", "]", "if", "docs", ":", "documents", "=", "self", ".", "do...
Get document sources using MGET elasticsearch API
[ "Get", "document", "sources", "using", "MGET", "elasticsearch", "API" ]
python
train
45.5
meejah/txtorcon
txtorcon/torconfig.py
https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/torconfig.py#L37-L64
def launch_tor(config, reactor, tor_binary=None, progress_updates=None, connection_creator=None, timeout=None, kill_on_stderr=True, stdout=None, stderr=None): """ Deprecated; use launch() instead. See also controller....
[ "def", "launch_tor", "(", "config", ",", "reactor", ",", "tor_binary", "=", "None", ",", "progress_updates", "=", "None", ",", "connection_creator", "=", "None", ",", "timeout", "=", "None", ",", "kill_on_stderr", "=", "True", ",", "stdout", "=", "None", "...
Deprecated; use launch() instead. See also controller.py
[ "Deprecated", ";", "use", "launch", "()", "instead", "." ]
python
train
31
inspirehep/inspire-schemas
inspire_schemas/builders/literature.py
https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/literature.py#L136-L143
def _sourced_dict(self, source=None, **kwargs): """Like ``dict(**kwargs)``, but where the ``source`` key is special. """ if source: kwargs['source'] = source elif self.source: kwargs['source'] = self.source return kwargs
[ "def", "_sourced_dict", "(", "self", ",", "source", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "source", ":", "kwargs", "[", "'source'", "]", "=", "source", "elif", "self", ".", "source", ":", "kwargs", "[", "'source'", "]", "=", "self", ...
Like ``dict(**kwargs)``, but where the ``source`` key is special.
[ "Like", "dict", "(", "**", "kwargs", ")", "but", "where", "the", "source", "key", "is", "special", "." ]
python
train
34.625
Duke-GCB/DukeDSClient
ddsc/core/pathfilter.py
https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/core/pathfilter.py#L49-L54
def get_unused_paths(self): """ Returns which include_paths or exclude_paths that were not used via include_path method. :return: [str] list of filtering paths that were not used. """ return [path for path in self.filter.paths if path not in self.seen_paths]
[ "def", "get_unused_paths", "(", "self", ")", ":", "return", "[", "path", "for", "path", "in", "self", ".", "filter", ".", "paths", "if", "path", "not", "in", "self", ".", "seen_paths", "]" ]
Returns which include_paths or exclude_paths that were not used via include_path method. :return: [str] list of filtering paths that were not used.
[ "Returns", "which", "include_paths", "or", "exclude_paths", "that", "were", "not", "used", "via", "include_path", "method", ".", ":", "return", ":", "[", "str", "]", "list", "of", "filtering", "paths", "that", "were", "not", "used", "." ]
python
train
48.833333
refinery29/chassis
chassis/services/dependency_injection/__init__.py
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/__init__.py#L223-L237
def _replace_services_in_args(self, args): """ Replace service references in arguments list """ _check_type('args', args, list) new_args = [] for arg in args: if isinstance(arg, list): new_args.append(self._replace_services_in_args(arg)) elif isin...
[ "def", "_replace_services_in_args", "(", "self", ",", "args", ")", ":", "_check_type", "(", "'args'", ",", "args", ",", "list", ")", "new_args", "=", "[", "]", "for", "arg", "in", "args", ":", "if", "isinstance", "(", "arg", ",", "list", ")", ":", "n...
Replace service references in arguments list
[ "Replace", "service", "references", "in", "arguments", "list" ]
python
train
38.8
sirfoga/pyhal
hal/internet/services/github.py
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/internet/services/github.py#L167-L193
def _get_repos(url): """Gets repos in url :param url: Url :return: List of repositories in given url """ current_page = 1 there_is_something_left = True repos_list = [] while there_is_something_left: api_driver = GithubRawApi( ...
[ "def", "_get_repos", "(", "url", ")", ":", "current_page", "=", "1", "there_is_something_left", "=", "True", "repos_list", "=", "[", "]", "while", "there_is_something_left", ":", "api_driver", "=", "GithubRawApi", "(", "url", ",", "url_params", "=", "{", "\"pa...
Gets repos in url :param url: Url :return: List of repositories in given url
[ "Gets", "repos", "in", "url" ]
python
train
30.62963
BrewBlox/brewblox-service
brewblox_service/events.py
https://github.com/BrewBlox/brewblox-service/blob/f2572fcb5ea337c24aa5a28c2b0b19ebcfc076eb/brewblox_service/events.py#L169-L184
def _lazy_listen(self): """ Ensures that the listener task only runs when actually needed. This function is a no-op if any of the preconditions is not met. Preconditions are: * The application is running (self._loop is set) * The task is not already running * The...
[ "def", "_lazy_listen", "(", "self", ")", ":", "if", "all", "(", "[", "self", ".", "_loop", ",", "not", "self", ".", "running", ",", "self", ".", "_subscriptions", "or", "(", "self", ".", "_pending", "and", "not", "self", ".", "_pending", ".", "empty"...
Ensures that the listener task only runs when actually needed. This function is a no-op if any of the preconditions is not met. Preconditions are: * The application is running (self._loop is set) * The task is not already running * There are subscriptions: either pending, or act...
[ "Ensures", "that", "the", "listener", "task", "only", "runs", "when", "actually", "needed", ".", "This", "function", "is", "a", "no", "-", "op", "if", "any", "of", "the", "preconditions", "is", "not", "met", "." ]
python
train
37.0625
pypa/pipenv
pipenv/patched/notpip/_internal/utils/misc.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/misc.py#L219-L225
def is_svn_page(html): # type: (Union[str, Text]) -> Optional[Match[Union[str, Text]]] """ Returns true if the page appears to be the index page of an svn repository """ return (re.search(r'<title>[^<]*Revision \d+:', html) and re.search(r'Powered by (?:<a[^>]*?>)?Subversion', html, re.I...
[ "def", "is_svn_page", "(", "html", ")", ":", "# type: (Union[str, Text]) -> Optional[Match[Union[str, Text]]]", "return", "(", "re", ".", "search", "(", "r'<title>[^<]*Revision \\d+:'", ",", "html", ")", "and", "re", ".", "search", "(", "r'Powered by (?:<a[^>]*?>)?Subvers...
Returns true if the page appears to be the index page of an svn repository
[ "Returns", "true", "if", "the", "page", "appears", "to", "be", "the", "index", "page", "of", "an", "svn", "repository" ]
python
train
45.142857
rene-aguirre/pywinusb
examples/pnp_sample.py
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/examples/pnp_sample.py#L35-L65
def on_hid_pnp(self, hid_event = None): """This function will be called on per class event changes, so we need to test if our device has being connected or is just gone""" # keep old reference for UI updates old_device = self.device if hid_event: print("Hey, a...
[ "def", "on_hid_pnp", "(", "self", ",", "hid_event", "=", "None", ")", ":", "# keep old reference for UI updates\r", "old_device", "=", "self", ".", "device", "if", "hid_event", ":", "print", "(", "\"Hey, a hid device just %s!\"", "%", "hid_event", ")", "if", "hid_...
This function will be called on per class event changes, so we need to test if our device has being connected or is just gone
[ "This", "function", "will", "be", "called", "on", "per", "class", "event", "changes", "so", "we", "need", "to", "test", "if", "our", "device", "has", "being", "connected", "or", "is", "just", "gone" ]
python
train
38.290323
tensorpack/tensorpack
tensorpack/utils/fs.py
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/fs.py#L32-L74
def download(url, dir, filename=None, expect_size=None): """ Download URL to a directory. Will figure out the filename automatically from URL, if not given. """ mkdir_p(dir) if filename is None: filename = url.split('/')[-1] fpath = os.path.join(dir, filename) if os.path.isfile(...
[ "def", "download", "(", "url", ",", "dir", ",", "filename", "=", "None", ",", "expect_size", "=", "None", ")", ":", "mkdir_p", "(", "dir", ")", "if", "filename", "is", "None", ":", "filename", "=", "url", ".", "split", "(", "'/'", ")", "[", "-", ...
Download URL to a directory. Will figure out the filename automatically from URL, if not given.
[ "Download", "URL", "to", "a", "directory", ".", "Will", "figure", "out", "the", "filename", "automatically", "from", "URL", "if", "not", "given", "." ]
python
train
37.348837
spacetelescope/drizzlepac
drizzlepac/runastrodriz.py
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/runastrodriz.py#L609-L613
def _restoreResults(newdir,origdir): """ Move (not copy) all files from newdir back to the original directory """ for fname in glob.glob(os.path.join(newdir,'*')): shutil.move(fname,os.path.join(origdir,os.path.basename(fname)))
[ "def", "_restoreResults", "(", "newdir", ",", "origdir", ")", ":", "for", "fname", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "newdir", ",", "'*'", ")", ")", ":", "shutil", ".", "move", "(", "fname", ",", "os", ".", "pat...
Move (not copy) all files from newdir back to the original directory
[ "Move", "(", "not", "copy", ")", "all", "files", "from", "newdir", "back", "to", "the", "original", "directory" ]
python
train
48.8
kensho-technologies/graphql-compiler
graphql_compiler/compiler/expressions.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/expressions.py#L29-L38
def make_replacement_visitor(find_expression, replace_expression): """Return a visitor function that replaces every instance of one expression with another one.""" def visitor_fn(expression): """Return the replacement if this expression matches the expression we're looking for.""" if expression ...
[ "def", "make_replacement_visitor", "(", "find_expression", ",", "replace_expression", ")", ":", "def", "visitor_fn", "(", "expression", ")", ":", "\"\"\"Return the replacement if this expression matches the expression we're looking for.\"\"\"", "if", "expression", "==", "find_exp...
Return a visitor function that replaces every instance of one expression with another one.
[ "Return", "a", "visitor", "function", "that", "replaces", "every", "instance", "of", "one", "expression", "with", "another", "one", "." ]
python
train
43.5
materialsproject/pymatgen
pymatgen/io/abinit/works.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/works.py#L1273-L1309
def add_becs_from_scf_task(self, scf_task, ddk_tolerance, ph_tolerance): """ Build tasks for the computation of Born effective charges and add them to the work. Args: scf_task: ScfTask object. ddk_tolerance: dict {"varname": value} with the tolerance used in the DDK run....
[ "def", "add_becs_from_scf_task", "(", "self", ",", "scf_task", ",", "ddk_tolerance", ",", "ph_tolerance", ")", ":", "if", "not", "isinstance", "(", "scf_task", ",", "ScfTask", ")", ":", "raise", "TypeError", "(", "\"task `%s` does not inherit from ScfTask\"", "%", ...
Build tasks for the computation of Born effective charges and add them to the work. Args: scf_task: ScfTask object. ddk_tolerance: dict {"varname": value} with the tolerance used in the DDK run. None to use AbiPy default. ph_tolerance: dict {"varname": value}...
[ "Build", "tasks", "for", "the", "computation", "of", "Born", "effective", "charges", "and", "add", "them", "to", "the", "work", "." ]
python
train
40.648649
junzis/pyModeS
pyModeS/decoder/bds/bds60.py
https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds60.py#L75-L101
def hdg60(msg): """Megnetic heading of aircraft Args: msg (String): 28 bytes hexadecimal message (BDS60) string Returns: float: heading in degrees to megnetic north (from 0 to 360) """ d = hex2bin(data(msg)) if d[0] == '0': return None sign = int(d[1]) # 1 -> w...
[ "def", "hdg60", "(", "msg", ")", ":", "d", "=", "hex2bin", "(", "data", "(", "msg", ")", ")", "if", "d", "[", "0", "]", "==", "'0'", ":", "return", "None", "sign", "=", "int", "(", "d", "[", "1", "]", ")", "# 1 -> west", "value", "=", "bin2in...
Megnetic heading of aircraft Args: msg (String): 28 bytes hexadecimal message (BDS60) string Returns: float: heading in degrees to megnetic north (from 0 to 360)
[ "Megnetic", "heading", "of", "aircraft" ]
python
train
19.222222
erichiggins/gaek
gaek/environ.py
https://github.com/erichiggins/gaek/blob/eb6bbc2d2688302834f97fd97891592e8b9659f2/gaek/environ.py#L160-L164
def get_dot_target_name(version=None, module=None): """Returns the current version/module in -dot- notation which is used by `target:` parameters.""" version = version or get_current_version_name() module = module or get_current_module_name() return '-dot-'.join((version, module))
[ "def", "get_dot_target_name", "(", "version", "=", "None", ",", "module", "=", "None", ")", ":", "version", "=", "version", "or", "get_current_version_name", "(", ")", "module", "=", "module", "or", "get_current_module_name", "(", ")", "return", "'-dot-'", "."...
Returns the current version/module in -dot- notation which is used by `target:` parameters.
[ "Returns", "the", "current", "version", "/", "module", "in", "-", "dot", "-", "notation", "which", "is", "used", "by", "target", ":", "parameters", "." ]
python
test
57
kofrasa/migrate
migrate.py
https://github.com/kofrasa/migrate/blob/b53b7168f8ac27e4c557de6e62ad85fe00d99566/migrate.py#L154-L161
def _get_revision(self): """Validate and return the revision to use for current command """ assert self._revisions, "no migration revision exist" revision = self._rev or self._revisions[-1] # revision count must be less or equal since revisions are ordered assert revision...
[ "def", "_get_revision", "(", "self", ")", ":", "assert", "self", ".", "_revisions", ",", "\"no migration revision exist\"", "revision", "=", "self", ".", "_rev", "or", "self", ".", "_revisions", "[", "-", "1", "]", "# revision count must be less or equal since revis...
Validate and return the revision to use for current command
[ "Validate", "and", "return", "the", "revision", "to", "use", "for", "current", "command" ]
python
train
48.25
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1290-L1300
def autoencoder_discrete_cifar(): """Discrete autoencoder model for compressing cifar.""" hparams = autoencoder_ordered_discrete() hparams.bottleneck_noise = 0.0 hparams.bottleneck_bits = 90 hparams.num_hidden_layers = 2 hparams.hidden_size = 256 hparams.num_residual_layers = 4 hparams.batch_size = 32 ...
[ "def", "autoencoder_discrete_cifar", "(", ")", ":", "hparams", "=", "autoencoder_ordered_discrete", "(", ")", "hparams", ".", "bottleneck_noise", "=", "0.0", "hparams", ".", "bottleneck_bits", "=", "90", "hparams", ".", "num_hidden_layers", "=", "2", "hparams", "....
Discrete autoencoder model for compressing cifar.
[ "Discrete", "autoencoder", "model", "for", "compressing", "cifar", "." ]
python
train
33.090909