repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
klahnakoski/pyLibrary | mo_dots/nones.py | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_dots/nones.py#L235-L269 | def _assign_to_null(obj, path, value, force=True):
"""
value IS ASSIGNED TO obj[self.path][key]
path IS AN ARRAY OF PROPERTY NAMES
force=False IF YOU PREFER TO use setDefault()
"""
try:
if obj is Null:
return
if _get(obj, CLASS) is NullType:
d = _get(obj, ... | [
"def",
"_assign_to_null",
"(",
"obj",
",",
"path",
",",
"value",
",",
"force",
"=",
"True",
")",
":",
"try",
":",
"if",
"obj",
"is",
"Null",
":",
"return",
"if",
"_get",
"(",
"obj",
",",
"CLASS",
")",
"is",
"NullType",
":",
"d",
"=",
"_get",
"(",... | value IS ASSIGNED TO obj[self.path][key]
path IS AN ARRAY OF PROPERTY NAMES
force=False IF YOU PREFER TO use setDefault() | [
"value",
"IS",
"ASSIGNED",
"TO",
"obj",
"[",
"self",
".",
"path",
"]",
"[",
"key",
"]",
"path",
"IS",
"AN",
"ARRAY",
"OF",
"PROPERTY",
"NAMES",
"force",
"=",
"False",
"IF",
"YOU",
"PREFER",
"TO",
"use",
"setDefault",
"()"
] | python | train |
santoshphilip/eppy | eppy/EPlusInterfaceFunctions/mylib2.py | https://github.com/santoshphilip/eppy/blob/55410ff7c11722f35bc4331ff5e00a0b86f787e1/eppy/EPlusInterfaceFunctions/mylib2.py#L61-L73 | def tabstr2list(data):
"""tabstr2list"""
alist = data.split(os.linesep)
blist = alist[1].split('\t')
clist = []
for num in range(0, len(alist)):
ilist = alist[num].split('\t')
clist = clist+[ilist]
cclist = clist[:-1]
#the last element is turning out to be empty
#thi... | [
"def",
"tabstr2list",
"(",
"data",
")",
":",
"alist",
"=",
"data",
".",
"split",
"(",
"os",
".",
"linesep",
")",
"blist",
"=",
"alist",
"[",
"1",
"]",
".",
"split",
"(",
"'\\t'",
")",
"clist",
"=",
"[",
"]",
"for",
"num",
"in",
"range",
"(",
"0... | tabstr2list | [
"tabstr2list"
] | python | train |
h2non/pook | pook/engine.py | https://github.com/h2non/pook/blob/e64094e41e4d89d98d2d29af7608ef27dc50cf19/pook/engine.py#L232-L246 | def activate(self):
"""
Activates the registered interceptors in the mocking engine.
This means any HTTP traffic captures by those interceptors will
trigger the HTTP mock matching engine in order to determine if a given
HTTP transaction should be mocked out or not.
"""
... | [
"def",
"activate",
"(",
"self",
")",
":",
"if",
"self",
".",
"active",
":",
"return",
"None",
"# Activate mock engine",
"self",
".",
"mock_engine",
".",
"activate",
"(",
")",
"# Enable engine state",
"self",
".",
"active",
"=",
"True"
] | Activates the registered interceptors in the mocking engine.
This means any HTTP traffic captures by those interceptors will
trigger the HTTP mock matching engine in order to determine if a given
HTTP transaction should be mocked out or not. | [
"Activates",
"the",
"registered",
"interceptors",
"in",
"the",
"mocking",
"engine",
"."
] | python | test |
konstantinstadler/pymrio | pymrio/core/mriosystem.py | https://github.com/konstantinstadler/pymrio/blob/d764aa0dd2150200e867a9713a98ddae203e12d4/pymrio/core/mriosystem.py#L727-L907 | def calc_system(self, x, Y, Y_agg=None, L=None, population=None):
""" Calculates the missing part of the extension plus accounts
This method allows to specify an aggregated Y_agg for the
account calculation (see Y_agg below). However, the full Y needs
to be specified for the calculation... | [
"def",
"calc_system",
"(",
"self",
",",
"x",
",",
"Y",
",",
"Y_agg",
"=",
"None",
",",
"L",
"=",
"None",
",",
"population",
"=",
"None",
")",
":",
"if",
"Y_agg",
"is",
"None",
":",
"try",
":",
"Y_agg",
"=",
"Y",
".",
"sum",
"(",
"level",
"=",
... | Calculates the missing part of the extension plus accounts
This method allows to specify an aggregated Y_agg for the
account calculation (see Y_agg below). However, the full Y needs
to be specified for the calculation of FY or SY.
Calculates:
- for each sector and country:
... | [
"Calculates",
"the",
"missing",
"part",
"of",
"the",
"extension",
"plus",
"accounts"
] | python | train |
PmagPy/PmagPy | SPD/lib/lib_arai_plot_statistics.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_arai_plot_statistics.py#L279-L292 | def get_Zstar(x_segment, y_segment, x_int, y_int, slope, n):
"""
input: x_segment, y_segment, x_int, y_int, slope, n
output: Z* (Arai plot zigzag parameter (alternate))
"""
total = 0
first_time = True
for num, x in enumerate(x_segment):
b_wiggle = get_b_wiggle(x, y_segment[num], y_in... | [
"def",
"get_Zstar",
"(",
"x_segment",
",",
"y_segment",
",",
"x_int",
",",
"y_int",
",",
"slope",
",",
"n",
")",
":",
"total",
"=",
"0",
"first_time",
"=",
"True",
"for",
"num",
",",
"x",
"in",
"enumerate",
"(",
"x_segment",
")",
":",
"b_wiggle",
"="... | input: x_segment, y_segment, x_int, y_int, slope, n
output: Z* (Arai plot zigzag parameter (alternate)) | [
"input",
":",
"x_segment",
"y_segment",
"x_int",
"y_int",
"slope",
"n",
"output",
":",
"Z",
"*",
"(",
"Arai",
"plot",
"zigzag",
"parameter",
"(",
"alternate",
"))"
] | python | train |
foremast/foremast | src/foremast/slacknotify/slack_notification.py | https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/slacknotify/slack_notification.py#L45-L52 | def post_message(self):
"""Send templated message to **#deployments-{env}**.
Primarily for production deployments.
"""
message = get_template(template_file='slack/pipeline-prepare-ran.j2', info=self.info)
channel = '#deployments-prod'
post_slack_message(message=message, ... | [
"def",
"post_message",
"(",
"self",
")",
":",
"message",
"=",
"get_template",
"(",
"template_file",
"=",
"'slack/pipeline-prepare-ran.j2'",
",",
"info",
"=",
"self",
".",
"info",
")",
"channel",
"=",
"'#deployments-prod'",
"post_slack_message",
"(",
"message",
"="... | Send templated message to **#deployments-{env}**.
Primarily for production deployments. | [
"Send",
"templated",
"message",
"to",
"**",
"#deployments",
"-",
"{",
"env",
"}",
"**",
"."
] | python | train |
SheffieldML/GPyOpt | GPyOpt/core/bo.py | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/bo.py#L238-L256 | def _update_model(self, normalization_type='stats'):
"""
Updates the model (when more than one observation is available) and saves the parameters (if available).
"""
if self.num_acquisitions % self.model_update_interval == 0:
# input that goes into the model (is unziped in c... | [
"def",
"_update_model",
"(",
"self",
",",
"normalization_type",
"=",
"'stats'",
")",
":",
"if",
"self",
".",
"num_acquisitions",
"%",
"self",
".",
"model_update_interval",
"==",
"0",
":",
"# input that goes into the model (is unziped in case there are categorical variables)... | Updates the model (when more than one observation is available) and saves the parameters (if available). | [
"Updates",
"the",
"model",
"(",
"when",
"more",
"than",
"one",
"observation",
"is",
"available",
")",
"and",
"saves",
"the",
"parameters",
"(",
"if",
"available",
")",
"."
] | python | train |
pantsbuild/pants | src/python/pants/engine/build_files.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/build_files.py#L44-L62 | def parse_address_family(address_mapper, directory):
"""Given an AddressMapper and a directory, return an AddressFamily.
The AddressFamily may be empty, but it will not be None.
"""
patterns = tuple(join(directory.path, p) for p in address_mapper.build_patterns)
path_globs = PathGlobs(include=patterns,
... | [
"def",
"parse_address_family",
"(",
"address_mapper",
",",
"directory",
")",
":",
"patterns",
"=",
"tuple",
"(",
"join",
"(",
"directory",
".",
"path",
",",
"p",
")",
"for",
"p",
"in",
"address_mapper",
".",
"build_patterns",
")",
"path_globs",
"=",
"PathGlo... | Given an AddressMapper and a directory, return an AddressFamily.
The AddressFamily may be empty, but it will not be None. | [
"Given",
"an",
"AddressMapper",
"and",
"a",
"directory",
"return",
"an",
"AddressFamily",
"."
] | python | train |
googleapis/oauth2client | oauth2client/contrib/appengine.py | https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L730-L742 | def http(self, *args, **kwargs):
"""Returns an authorized http instance.
Must only be called from within an @oauth_required decorated method, or
from within an @oauth_aware decorated method where has_credentials()
returns True.
Args:
*args: Positional arguments pass... | [
"def",
"http",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"credentials",
".",
"authorize",
"(",
"transport",
".",
"get_http_object",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | Returns an authorized http instance.
Must only be called from within an @oauth_required decorated method, or
from within an @oauth_aware decorated method where has_credentials()
returns True.
Args:
*args: Positional arguments passed to httplib2.Http constructor.
... | [
"Returns",
"an",
"authorized",
"http",
"instance",
"."
] | python | valid |
mitsei/dlkit | dlkit/handcar/relationship/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/relationship/sessions.py#L627-L642 | def get_family(self):
"""Gets the ``Family`` associated with this session.
return: (osid.relationship.Family) - the family
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemen... | [
"def",
"get_family",
"(",
"self",
")",
":",
"# Implemented from template for osid.resource.ResourceLookupSession.get_bin",
"from",
".",
".",
"osid",
".",
"osid_errors",
"import",
"OperationFailed",
",",
"PermissionDenied",
"from",
".",
"objects",
"import",
"Family",
"try"... | Gets the ``Family`` associated with this session.
return: (osid.relationship.Family) - the family
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.* | [
"Gets",
"the",
"Family",
"associated",
"with",
"this",
"session",
"."
] | python | train |
vaexio/vaex | packages/vaex-core/vaex/dataframe.py | https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/dataframe.py#L4867-L4967 | def compare(self, other, report_missing=True, report_difference=False, show=10, orderby=None, column_names=None):
"""Compare two DataFrames and report their difference, use with care for large DataFrames"""
if column_names is None:
column_names = self.get_column_names(virtual=False)
... | [
"def",
"compare",
"(",
"self",
",",
"other",
",",
"report_missing",
"=",
"True",
",",
"report_difference",
"=",
"False",
",",
"show",
"=",
"10",
",",
"orderby",
"=",
"None",
",",
"column_names",
"=",
"None",
")",
":",
"if",
"column_names",
"is",
"None",
... | Compare two DataFrames and report their difference, use with care for large DataFrames | [
"Compare",
"two",
"DataFrames",
"and",
"report",
"their",
"difference",
"use",
"with",
"care",
"for",
"large",
"DataFrames"
] | python | test |
rflamary/POT | ot/bregman.py | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L984-L986 | def projC(gamma, q):
"""return the KL projection on the column constrints """
return np.multiply(gamma, q / np.maximum(np.sum(gamma, axis=0), 1e-10)) | [
"def",
"projC",
"(",
"gamma",
",",
"q",
")",
":",
"return",
"np",
".",
"multiply",
"(",
"gamma",
",",
"q",
"/",
"np",
".",
"maximum",
"(",
"np",
".",
"sum",
"(",
"gamma",
",",
"axis",
"=",
"0",
")",
",",
"1e-10",
")",
")"
] | return the KL projection on the column constrints | [
"return",
"the",
"KL",
"projection",
"on",
"the",
"column",
"constrints"
] | python | train |
hyperledger-archives/indy-ledger | ledger/stores/chunked_file_store.py | https://github.com/hyperledger-archives/indy-ledger/blob/7210c3b288e07f940eddad09b1dfc6a56be846df/ledger/stores/chunked_file_store.py#L291-L304 | def numKeys(self) -> int:
"""
This will iterate only over the last chunk since the name of the last
chunk indicates how many lines in total exist in all other chunks
"""
chunks = self._listChunks()
num_chunks = len(chunks)
if num_chunks == 0:
return 0
... | [
"def",
"numKeys",
"(",
"self",
")",
"->",
"int",
":",
"chunks",
"=",
"self",
".",
"_listChunks",
"(",
")",
"num_chunks",
"=",
"len",
"(",
"chunks",
")",
"if",
"num_chunks",
"==",
"0",
":",
"return",
"0",
"count",
"=",
"(",
"num_chunks",
"-",
"1",
"... | This will iterate only over the last chunk since the name of the last
chunk indicates how many lines in total exist in all other chunks | [
"This",
"will",
"iterate",
"only",
"over",
"the",
"last",
"chunk",
"since",
"the",
"name",
"of",
"the",
"last",
"chunk",
"indicates",
"how",
"many",
"lines",
"in",
"total",
"exist",
"in",
"all",
"other",
"chunks"
] | python | train |
kgori/treeCl | treeCl/bootstrap.py | https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/bootstrap.py#L442-L450 | def _make_A_and_part_of_b_adjacent(self, ref_crds):
"""
Make A and part of b. See docstring of this class
for answer to "What are A and b?"
"""
rot = self._rotate_rows(ref_crds)
A = 2*(rot - ref_crds)
partial_b = (rot**2 - ref_crds**2).sum(1)
return A, par... | [
"def",
"_make_A_and_part_of_b_adjacent",
"(",
"self",
",",
"ref_crds",
")",
":",
"rot",
"=",
"self",
".",
"_rotate_rows",
"(",
"ref_crds",
")",
"A",
"=",
"2",
"*",
"(",
"rot",
"-",
"ref_crds",
")",
"partial_b",
"=",
"(",
"rot",
"**",
"2",
"-",
"ref_crd... | Make A and part of b. See docstring of this class
for answer to "What are A and b?" | [
"Make",
"A",
"and",
"part",
"of",
"b",
".",
"See",
"docstring",
"of",
"this",
"class",
"for",
"answer",
"to",
"What",
"are",
"A",
"and",
"b?"
] | python | train |
mk-fg/python-pulse-control | pulsectl/lookup.py | https://github.com/mk-fg/python-pulse-control/blob/902d5e9e5591b89c356e5194a370212e23fb0e93/pulsectl/lookup.py#L23-L93 | def pulse_obj_lookup(pulse, obj_lookup, prop_default=None):
'''Return set of pulse object(s) with proplist values matching lookup-string.
Pattern syntax:
[ { 'sink' | 'source' | 'sink-input' | 'source-output' } [ / ... ] ':' ]
[ proplist-key-name (non-empty) [ / ... ] ':' ] [ ':' (for regexp match) ]
[ pro... | [
"def",
"pulse_obj_lookup",
"(",
"pulse",
",",
"obj_lookup",
",",
"prop_default",
"=",
"None",
")",
":",
"# \\ue000-\\uf8ff - private use area, never assigned to symbols",
"obj_lookup",
"=",
"obj_lookup",
".",
"replace",
"(",
"'\\\\\\\\'",
",",
"'\\ue000'",
")",
".",
"... | Return set of pulse object(s) with proplist values matching lookup-string.
Pattern syntax:
[ { 'sink' | 'source' | 'sink-input' | 'source-output' } [ / ... ] ':' ]
[ proplist-key-name (non-empty) [ / ... ] ':' ] [ ':' (for regexp match) ]
[ proplist-key-value ]
Examples:
- sink:alsa.driver_name:snd_hd... | [
"Return",
"set",
"of",
"pulse",
"object",
"(",
"s",
")",
"with",
"proplist",
"values",
"matching",
"lookup",
"-",
"string",
"."
] | python | train |
kisom/pypcapfile | pcapfile/protocols/linklayer/wifi.py | https://github.com/kisom/pypcapfile/blob/67520cfbb6c2e9ab3e7c181a8012ddc56ec5cad8/pcapfile/protocols/linklayer/wifi.py#L2267-L2280 | def extract_acked_seqs(bitmap, ssc_seq):
"""extracts acknowledged sequences from bitmap and
starting sequence number.
:bitmap: str
:ssc_seq: int
:return: int[]
acknowledged sequence numbers
"""
acked_seqs = []
for idx, val in enumerate(bitmap):... | [
"def",
"extract_acked_seqs",
"(",
"bitmap",
",",
"ssc_seq",
")",
":",
"acked_seqs",
"=",
"[",
"]",
"for",
"idx",
",",
"val",
"in",
"enumerate",
"(",
"bitmap",
")",
":",
"if",
"int",
"(",
"val",
")",
"==",
"1",
":",
"seq",
"=",
"(",
"ssc_seq",
"+",
... | extracts acknowledged sequences from bitmap and
starting sequence number.
:bitmap: str
:ssc_seq: int
:return: int[]
acknowledged sequence numbers | [
"extracts",
"acknowledged",
"sequences",
"from",
"bitmap",
"and",
"starting",
"sequence",
"number",
".",
":",
"bitmap",
":",
"str",
":",
"ssc_seq",
":",
"int",
":",
"return",
":",
"int",
"[]",
"acknowledged",
"sequence",
"numbers"
] | python | valid |
bndr/pipreqs | pipreqs/pipreqs.py | https://github.com/bndr/pipreqs/blob/15208540da03fdacf48fcb0a8b88b26da76b64f3/pipreqs/pipreqs.py#L66-L93 | def _open(filename=None, mode='r'):
"""Open a file or ``sys.stdout`` depending on the provided filename.
Args:
filename (str): The path to the file that should be opened. If
``None`` or ``'-'``, ``sys.stdout`` or ``sys.stdin`` is
returned depending on the desired mode. Defaults ... | [
"def",
"_open",
"(",
"filename",
"=",
"None",
",",
"mode",
"=",
"'r'",
")",
":",
"if",
"not",
"filename",
"or",
"filename",
"==",
"'-'",
":",
"if",
"not",
"mode",
"or",
"'r'",
"in",
"mode",
":",
"file",
"=",
"sys",
".",
"stdin",
"elif",
"'w'",
"i... | Open a file or ``sys.stdout`` depending on the provided filename.
Args:
filename (str): The path to the file that should be opened. If
``None`` or ``'-'``, ``sys.stdout`` or ``sys.stdin`` is
returned depending on the desired mode. Defaults to ``None``.
mode (str): The mode t... | [
"Open",
"a",
"file",
"or",
"sys",
".",
"stdout",
"depending",
"on",
"the",
"provided",
"filename",
"."
] | python | train |
inspirehep/inspire-json-merger | inspire_json_merger/utils.py | https://github.com/inspirehep/inspire-json-merger/blob/6af3140fcf7c3f851141c0928eedfe99fddeeda0/inspire_json_merger/utils.py#L147-L153 | def filter_records(root, head, update, filters=()):
"""Apply the filters to the records."""
root, head, update = freeze(root), freeze(head), freeze(update)
for filter_ in filters:
root, head, update = filter_(root, head, update)
return thaw(root), thaw(head), thaw(update) | [
"def",
"filter_records",
"(",
"root",
",",
"head",
",",
"update",
",",
"filters",
"=",
"(",
")",
")",
":",
"root",
",",
"head",
",",
"update",
"=",
"freeze",
"(",
"root",
")",
",",
"freeze",
"(",
"head",
")",
",",
"freeze",
"(",
"update",
")",
"f... | Apply the filters to the records. | [
"Apply",
"the",
"filters",
"to",
"the",
"records",
"."
] | python | train |
outini/python-pylls | pylls/cachet.py | https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L383-L401 | def create(self, name, suffix, description, default_value, display=None):
"""Create a new Metric
:param str name: Name of metric
:param str suffix: Metric unit
:param str description: Description of what the metric is measuring
:param int default_value: Default value to use when... | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"suffix",
",",
"description",
",",
"default_value",
",",
"display",
"=",
"None",
")",
":",
"data",
"=",
"ApiParams",
"(",
")",
"data",
"[",
"'name'",
"]",
"=",
"name",
"data",
"[",
"'suffix'",
"]",
"=",... | Create a new Metric
:param str name: Name of metric
:param str suffix: Metric unit
:param str description: Description of what the metric is measuring
:param int default_value: Default value to use when a point is added
:param int display: Display the chart on the status page
... | [
"Create",
"a",
"new",
"Metric"
] | python | train |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_0/tfvc/tfvc_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/tfvc/tfvc_client.py#L733-L746 | def get_shelveset_work_items(self, shelveset_id):
"""GetShelvesetWorkItems.
Get work items associated with a shelveset.
:param str shelveset_id: Shelveset's unique ID
:rtype: [AssociatedWorkItem]
"""
query_parameters = {}
if shelveset_id is not None:
q... | [
"def",
"get_shelveset_work_items",
"(",
"self",
",",
"shelveset_id",
")",
":",
"query_parameters",
"=",
"{",
"}",
"if",
"shelveset_id",
"is",
"not",
"None",
":",
"query_parameters",
"[",
"'shelvesetId'",
"]",
"=",
"self",
".",
"_serialize",
".",
"query",
"(",
... | GetShelvesetWorkItems.
Get work items associated with a shelveset.
:param str shelveset_id: Shelveset's unique ID
:rtype: [AssociatedWorkItem] | [
"GetShelvesetWorkItems",
".",
"Get",
"work",
"items",
"associated",
"with",
"a",
"shelveset",
".",
":",
"param",
"str",
"shelveset_id",
":",
"Shelveset",
"s",
"unique",
"ID",
":",
"rtype",
":",
"[",
"AssociatedWorkItem",
"]"
] | python | train |
FactoryBoy/factory_boy | factory/builder.py | https://github.com/FactoryBoy/factory_boy/blob/edaa7c7f5a14065b229927903bd7989cc93cd069/factory/builder.py#L308-L310 | def recurse(self, factory_meta, extras):
"""Recurse into a sub-factory call."""
return self.__class__(factory_meta, extras, strategy=self.strategy) | [
"def",
"recurse",
"(",
"self",
",",
"factory_meta",
",",
"extras",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"factory_meta",
",",
"extras",
",",
"strategy",
"=",
"self",
".",
"strategy",
")"
] | Recurse into a sub-factory call. | [
"Recurse",
"into",
"a",
"sub",
"-",
"factory",
"call",
"."
] | python | train |
googlefonts/fontmake | Lib/fontmake/font_project.py | https://github.com/googlefonts/fontmake/blob/b611baf49929575c2a30fd18662055365219ce2d/Lib/fontmake/font_project.py#L1042-L1074 | def _output_path(
self,
ufo_or_font_name,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
output_dir=None,
suffix=None,
):
"""Generate output path for a font file with given extension."""
if i... | [
"def",
"_output_path",
"(",
"self",
",",
"ufo_or_font_name",
",",
"ext",
",",
"is_instance",
"=",
"False",
",",
"interpolatable",
"=",
"False",
",",
"autohinted",
"=",
"False",
",",
"is_variable",
"=",
"False",
",",
"output_dir",
"=",
"None",
",",
"suffix",
... | Generate output path for a font file with given extension. | [
"Generate",
"output",
"path",
"for",
"a",
"font",
"file",
"with",
"given",
"extension",
"."
] | python | train |
solocompt/plugs-mail | plugs_mail/management/commands/load_email_templates.py | https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L120-L132 | def get_subject(self, text):
"""
Email template subject is the first
line of the email template, we can optionally
add SUBJECT: to make it clearer
"""
first_line = text.splitlines(True)[0]
# TODO second line should be empty
if first_line.startswith('SUBJEC... | [
"def",
"get_subject",
"(",
"self",
",",
"text",
")",
":",
"first_line",
"=",
"text",
".",
"splitlines",
"(",
"True",
")",
"[",
"0",
"]",
"# TODO second line should be empty",
"if",
"first_line",
".",
"startswith",
"(",
"'SUBJECT:'",
")",
":",
"subject",
"=",... | Email template subject is the first
line of the email template, we can optionally
add SUBJECT: to make it clearer | [
"Email",
"template",
"subject",
"is",
"the",
"first",
"line",
"of",
"the",
"email",
"template",
"we",
"can",
"optionally",
"add",
"SUBJECT",
":",
"to",
"make",
"it",
"clearer"
] | python | train |
poldracklab/niworkflows | niworkflows/data/utils.py | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/data/utils.py#L36-L197 | def fetch_file(dataset_name, url, dataset_dir, dataset_prefix=None,
default_paths=None, filetype=None, resume=True, overwrite=False,
md5sum=None, username=None, password=None, retry=0,
verbose=1, temp_downloads=None):
"""Load requested file, downloading it if needed or r... | [
"def",
"fetch_file",
"(",
"dataset_name",
",",
"url",
",",
"dataset_dir",
",",
"dataset_prefix",
"=",
"None",
",",
"default_paths",
"=",
"None",
",",
"filetype",
"=",
"None",
",",
"resume",
"=",
"True",
",",
"overwrite",
"=",
"False",
",",
"md5sum",
"=",
... | Load requested file, downloading it if needed or requested.
:param str url: contains the url of the file to be downloaded.
:param str dataset_dir: path of the data directory. Used for data
storage in the specified location.
:param bool resume: if true, try to resume partially downloaded files
:... | [
"Load",
"requested",
"file",
"downloading",
"it",
"if",
"needed",
"or",
"requested",
"."
] | python | train |
bitly/asyncmongo | asyncmongo/message.py | https://github.com/bitly/asyncmongo/blob/3da47c96d4592ec9e8b3ef5cf1b7d5b439ab3a5b/asyncmongo/message.py#L79-L98 | def update(collection_name, upsert, multi, spec, doc, safe, last_error_args):
"""Get an **update** message.
"""
options = 0
if upsert:
options += 1
if multi:
options += 2
data = __ZERO
data += bson._make_c_string(collection_name)
data += struct.pack("<i", options)
da... | [
"def",
"update",
"(",
"collection_name",
",",
"upsert",
",",
"multi",
",",
"spec",
",",
"doc",
",",
"safe",
",",
"last_error_args",
")",
":",
"options",
"=",
"0",
"if",
"upsert",
":",
"options",
"+=",
"1",
"if",
"multi",
":",
"options",
"+=",
"2",
"d... | Get an **update** message. | [
"Get",
"an",
"**",
"update",
"**",
"message",
"."
] | python | train |
saltstack/salt | salt/modules/marathon.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/marathon.py#L104-L141 | def update_app(id, config):
'''
Update the specified app with the given configuration.
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.update_app my-app '<config yaml>'
'''
if 'id' not in config:
config['id'] = id
config.pop('version', None)
# mirror... | [
"def",
"update_app",
"(",
"id",
",",
"config",
")",
":",
"if",
"'id'",
"not",
"in",
"config",
":",
"config",
"[",
"'id'",
"]",
"=",
"id",
"config",
".",
"pop",
"(",
"'version'",
",",
"None",
")",
"# mirror marathon-ui handling for uris deprecation (see",
"# ... | Update the specified app with the given configuration.
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.update_app my-app '<config yaml>' | [
"Update",
"the",
"specified",
"app",
"with",
"the",
"given",
"configuration",
"."
] | python | train |
vijaykatam/django-cache-manager | django_cache_manager/mixins.py | https://github.com/vijaykatam/django-cache-manager/blob/05142c44eb349d3f24f962592945888d9d367375/django_cache_manager/mixins.py#L23-L39 | def generate_key(self):
"""
Generate cache key for the current query. If a new key is created for the model it is
then shared with other consumers.
"""
sql = self.sql()
key, created = self.get_or_create_model_key()
if created:
db_table = self.model._me... | [
"def",
"generate_key",
"(",
"self",
")",
":",
"sql",
"=",
"self",
".",
"sql",
"(",
")",
"key",
",",
"created",
"=",
"self",
".",
"get_or_create_model_key",
"(",
")",
"if",
"created",
":",
"db_table",
"=",
"self",
".",
"model",
".",
"_meta",
".",
"db_... | Generate cache key for the current query. If a new key is created for the model it is
then shared with other consumers. | [
"Generate",
"cache",
"key",
"for",
"the",
"current",
"query",
".",
"If",
"a",
"new",
"key",
"is",
"created",
"for",
"the",
"model",
"it",
"is",
"then",
"shared",
"with",
"other",
"consumers",
"."
] | python | train |
mdscruggs/ga | ga/examples/irrigation.py | https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/examples/irrigation.py#L160-L181 | def map_sprinkler(self, sx, sy, watered_crop='^', watered_field='_', dry_field=' ', dry_crop='x'):
"""
Return a version of the ASCII map showing reached crop cells.
"""
# convert strings (rows) to lists of characters for easier map editing
maplist = [list(s) for s in self.maplist... | [
"def",
"map_sprinkler",
"(",
"self",
",",
"sx",
",",
"sy",
",",
"watered_crop",
"=",
"'^'",
",",
"watered_field",
"=",
"'_'",
",",
"dry_field",
"=",
"' '",
",",
"dry_crop",
"=",
"'x'",
")",
":",
"# convert strings (rows) to lists of characters for easier map editi... | Return a version of the ASCII map showing reached crop cells. | [
"Return",
"a",
"version",
"of",
"the",
"ASCII",
"map",
"showing",
"reached",
"crop",
"cells",
"."
] | python | train |
dariusbakunas/rawdisk | rawdisk/plugins/filesystems/ntfs/ntfs.py | https://github.com/dariusbakunas/rawdisk/blob/1dc9d0b377fe5da3c406ccec4abc238c54167403/rawdisk/plugins/filesystems/ntfs/ntfs.py#L27-L44 | def detect(self, filename, offset, standalone=False):
"""Verifies NTFS filesystem signature.
Returns:
bool: True if filesystem signature at offset 0x03 \
matches 'NTFS ', False otherwise.
"""
r = RawStruct(
filename=filename,
offset=off... | [
"def",
"detect",
"(",
"self",
",",
"filename",
",",
"offset",
",",
"standalone",
"=",
"False",
")",
":",
"r",
"=",
"RawStruct",
"(",
"filename",
"=",
"filename",
",",
"offset",
"=",
"offset",
"+",
"SIG_OFFSET",
",",
"length",
"=",
"SIG_SIZE",
")",
"oem... | Verifies NTFS filesystem signature.
Returns:
bool: True if filesystem signature at offset 0x03 \
matches 'NTFS ', False otherwise. | [
"Verifies",
"NTFS",
"filesystem",
"signature",
"."
] | python | train |
EVEprosper/ProsperCommon | prosper/common/prosper_config.py | https://github.com/EVEprosper/ProsperCommon/blob/bcada3b25420099e1f204db8d55eb268e7b4dc27/prosper/common/prosper_config.py#L265-L287 | def read_config(
config_filepath,
logger=logging.getLogger('ProsperCommon'),
):
"""fetch and parse config file
Args:
config_filepath (str): path to config file. abspath > relpath
logger (:obj:`logging.Logger`): logger to catch error msgs
"""
config_parser = configparse... | [
"def",
"read_config",
"(",
"config_filepath",
",",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'ProsperCommon'",
")",
",",
")",
":",
"config_parser",
"=",
"configparser",
".",
"ConfigParser",
"(",
"interpolation",
"=",
"ExtendedInterpolation",
"(",
")",
",... | fetch and parse config file
Args:
config_filepath (str): path to config file. abspath > relpath
logger (:obj:`logging.Logger`): logger to catch error msgs | [
"fetch",
"and",
"parse",
"config",
"file"
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1176-L1217 | def attention_image_summary(attn, image_shapes=None):
"""Compute color image summary.
Args:
attn: a Tensor with shape [batch, num_heads, query_length, memory_length]
image_shapes: optional tuple of integer scalars.
If the query positions and memory positions represent the
pixels of flattened im... | [
"def",
"attention_image_summary",
"(",
"attn",
",",
"image_shapes",
"=",
"None",
")",
":",
"attn",
"=",
"tf",
".",
"cast",
"(",
"attn",
",",
"tf",
".",
"float32",
")",
"num_heads",
"=",
"common_layers",
".",
"shape_list",
"(",
"attn",
")",
"[",
"1",
"]... | Compute color image summary.
Args:
attn: a Tensor with shape [batch, num_heads, query_length, memory_length]
image_shapes: optional tuple of integer scalars.
If the query positions and memory positions represent the
pixels of flattened images, then pass in their dimensions:
(query_rows, q... | [
"Compute",
"color",
"image",
"summary",
"."
] | python | train |
aganezov/bg | bg/tree.py | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/tree.py#L181-L201 | def __update_consistent_multicolors(self):
""" Internally used method, that recalculates T-consistent / VT-consistent multicolors for current tree topology
"""
v_t_consistent_multicolors = self.__get_v_tree_consistent_leaf_based_hashable_multicolors()
hashed_vtree_consistent_leaves_mult... | [
"def",
"__update_consistent_multicolors",
"(",
"self",
")",
":",
"v_t_consistent_multicolors",
"=",
"self",
".",
"__get_v_tree_consistent_leaf_based_hashable_multicolors",
"(",
")",
"hashed_vtree_consistent_leaves_multicolors",
"=",
"{",
"mc",
".",
"hashable_representation",
"f... | Internally used method, that recalculates T-consistent / VT-consistent multicolors for current tree topology | [
"Internally",
"used",
"method",
"that",
"recalculates",
"T",
"-",
"consistent",
"/",
"VT",
"-",
"consistent",
"multicolors",
"for",
"current",
"tree",
"topology"
] | python | train |
jwkvam/plotlywrapper | plotlywrapper.py | https://github.com/jwkvam/plotlywrapper/blob/762b42912e824fecb1212c186900f2ebdd0ab12b/plotlywrapper.py#L254-L267 | def ylabelsize(self, size, index=1):
"""Set the size of the label.
Parameters
----------
size : int
Returns
-------
Chart
"""
self.layout['yaxis' + str(index)]['titlefont']['size'] = size
return self | [
"def",
"ylabelsize",
"(",
"self",
",",
"size",
",",
"index",
"=",
"1",
")",
":",
"self",
".",
"layout",
"[",
"'yaxis'",
"+",
"str",
"(",
"index",
")",
"]",
"[",
"'titlefont'",
"]",
"[",
"'size'",
"]",
"=",
"size",
"return",
"self"
] | Set the size of the label.
Parameters
----------
size : int
Returns
-------
Chart | [
"Set",
"the",
"size",
"of",
"the",
"label",
"."
] | python | train |
mattja/sdeint | sdeint/wiener.py | https://github.com/mattja/sdeint/blob/7cf807cdf97b3bb39d29e1c2dc834b519499b601/sdeint/wiener.py#L65-L72 | def _Aterm(N, h, m, k, dW):
"""kth term in the sum of Wiktorsson2001 equation (2.2)"""
sqrt2h = np.sqrt(2.0/h)
Xk = np.random.normal(0.0, 1.0, (N, m, 1))
Yk = np.random.normal(0.0, 1.0, (N, m, 1))
term1 = _dot(Xk, _t(Yk + sqrt2h*dW))
term2 = _dot(Yk + sqrt2h*dW, _t(Xk))
return (term1 - term2... | [
"def",
"_Aterm",
"(",
"N",
",",
"h",
",",
"m",
",",
"k",
",",
"dW",
")",
":",
"sqrt2h",
"=",
"np",
".",
"sqrt",
"(",
"2.0",
"/",
"h",
")",
"Xk",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"0.0",
",",
"1.0",
",",
"(",
"N",
",",
"m",
"... | kth term in the sum of Wiktorsson2001 equation (2.2) | [
"kth",
"term",
"in",
"the",
"sum",
"of",
"Wiktorsson2001",
"equation",
"(",
"2",
".",
"2",
")"
] | python | train |
genialis/resolwe | resolwe/flow/models/utils.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/utils.py#L620-L624 | def fill_with_defaults(process_input, input_schema):
"""Fill empty optional fields in input with default values."""
for field_schema, fields, path in iterate_schema(process_input, input_schema):
if 'default' in field_schema and field_schema['name'] not in fields:
dict_dot(process_input, path... | [
"def",
"fill_with_defaults",
"(",
"process_input",
",",
"input_schema",
")",
":",
"for",
"field_schema",
",",
"fields",
",",
"path",
"in",
"iterate_schema",
"(",
"process_input",
",",
"input_schema",
")",
":",
"if",
"'default'",
"in",
"field_schema",
"and",
"fie... | Fill empty optional fields in input with default values. | [
"Fill",
"empty",
"optional",
"fields",
"in",
"input",
"with",
"default",
"values",
"."
] | python | train |
vaexio/vaex | packages/vaex-astro/vaex/astro/transformations.py | https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-astro/vaex/astro/transformations.py#L243-L250 | def add_virtual_columns_equatorial_to_galactic_cartesian(self, alpha, delta, distance, xname, yname, zname, radians=True, alpha_gp=np.radians(192.85948), delta_gp=np.radians(27.12825), l_omega=np.radians(32.93192)):
"""From http://arxiv.org/pdf/1306.2945v2.pdf"""
if not radians:
alpha = "pi/180.*%s" % a... | [
"def",
"add_virtual_columns_equatorial_to_galactic_cartesian",
"(",
"self",
",",
"alpha",
",",
"delta",
",",
"distance",
",",
"xname",
",",
"yname",
",",
"zname",
",",
"radians",
"=",
"True",
",",
"alpha_gp",
"=",
"np",
".",
"radians",
"(",
"192.85948",
")",
... | From http://arxiv.org/pdf/1306.2945v2.pdf | [
"From",
"http",
":",
"//",
"arxiv",
".",
"org",
"/",
"pdf",
"/",
"1306",
".",
"2945v2",
".",
"pdf"
] | python | test |
tensorlayer/tensorlayer | tensorlayer/nlp.py | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/nlp.py#L873-L932 | def create_vocabulary(
vocabulary_path, data_path, max_vocabulary_size, tokenizer=None, normalize_digits=True,
_DIGIT_RE=re.compile(br"\d"), _START_VOCAB=None
):
r"""Create vocabulary file (if it does not exist yet) from data file.
Data file is assumed to contain one sentence per line. Each sen... | [
"def",
"create_vocabulary",
"(",
"vocabulary_path",
",",
"data_path",
",",
"max_vocabulary_size",
",",
"tokenizer",
"=",
"None",
",",
"normalize_digits",
"=",
"True",
",",
"_DIGIT_RE",
"=",
"re",
".",
"compile",
"(",
"br\"\\d\"",
")",
",",
"_START_VOCAB",
"=",
... | r"""Create vocabulary file (if it does not exist yet) from data file.
Data file is assumed to contain one sentence per line. Each sentence is
tokenized and digits are normalized (if normalize_digits is set).
Vocabulary contains the most-frequent tokens up to max_vocabulary_size.
We write it to vocabula... | [
"r",
"Create",
"vocabulary",
"file",
"(",
"if",
"it",
"does",
"not",
"exist",
"yet",
")",
"from",
"data",
"file",
"."
] | python | valid |
sixty-north/cosmic-ray | src/cosmic_ray/config.py | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/config.py#L11-L26 | def load_config(filename=None):
"""Load a configuration from a file or stdin.
If `filename` is `None` or "-", then configuration gets read from stdin.
Returns: A `ConfigDict`.
Raises: ConfigError: If there is an error loading the config.
"""
try:
with _config_stream(filename) as handl... | [
"def",
"load_config",
"(",
"filename",
"=",
"None",
")",
":",
"try",
":",
"with",
"_config_stream",
"(",
"filename",
")",
"as",
"handle",
":",
"filename",
"=",
"handle",
".",
"name",
"return",
"deserialize_config",
"(",
"handle",
".",
"read",
"(",
")",
"... | Load a configuration from a file or stdin.
If `filename` is `None` or "-", then configuration gets read from stdin.
Returns: A `ConfigDict`.
Raises: ConfigError: If there is an error loading the config. | [
"Load",
"a",
"configuration",
"from",
"a",
"file",
"or",
"stdin",
"."
] | python | train |
tcalmant/python-javaobj | javaobj/core.py | https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1074-L1096 | def _create_hexdump(src, start_offset=0, length=16):
"""
Prepares an hexadecimal dump string
:param src: A string containing binary data
:param start_offset: The start offset of the source
:param length: Length of a dump line
:return: A dump string
"""
FI... | [
"def",
"_create_hexdump",
"(",
"src",
",",
"start_offset",
"=",
"0",
",",
"length",
"=",
"16",
")",
":",
"FILTER",
"=",
"\"\"",
".",
"join",
"(",
"(",
"len",
"(",
"repr",
"(",
"chr",
"(",
"x",
")",
")",
")",
"==",
"3",
")",
"and",
"chr",
"(",
... | Prepares an hexadecimal dump string
:param src: A string containing binary data
:param start_offset: The start offset of the source
:param length: Length of a dump line
:return: A dump string | [
"Prepares",
"an",
"hexadecimal",
"dump",
"string"
] | python | train |
pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L1366-L1378 | def evaluate_marker(text, extra=None):
"""
Evaluate a PEP 508 environment marker.
Return a boolean indicating the marker result in this environment.
Raise SyntaxError if marker is invalid.
This implementation uses the 'pyparsing' module.
"""
try:
marker = packaging.markers.Marker(te... | [
"def",
"evaluate_marker",
"(",
"text",
",",
"extra",
"=",
"None",
")",
":",
"try",
":",
"marker",
"=",
"packaging",
".",
"markers",
".",
"Marker",
"(",
"text",
")",
"return",
"marker",
".",
"evaluate",
"(",
")",
"except",
"packaging",
".",
"markers",
"... | Evaluate a PEP 508 environment marker.
Return a boolean indicating the marker result in this environment.
Raise SyntaxError if marker is invalid.
This implementation uses the 'pyparsing' module. | [
"Evaluate",
"a",
"PEP",
"508",
"environment",
"marker",
".",
"Return",
"a",
"boolean",
"indicating",
"the",
"marker",
"result",
"in",
"this",
"environment",
".",
"Raise",
"SyntaxError",
"if",
"marker",
"is",
"invalid",
"."
] | python | train |
CenturyLinkCloud/clc-python-sdk | src/clc/APIv2/server.py | https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L620-L674 | def Clone(self,network_id,name=None,cpu=None,memory=None,group_id=None,alias=None,password=None,ip_address=None,
storage_type=None,type=None,primary_dns=None,secondary_dns=None,
custom_fields=None,ttl=None,managed_os=False,description=None,
source_server_password=None,cpu_autoscale_policy_id=None,a... | [
"def",
"Clone",
"(",
"self",
",",
"network_id",
",",
"name",
"=",
"None",
",",
"cpu",
"=",
"None",
",",
"memory",
"=",
"None",
",",
"group_id",
"=",
"None",
",",
"alias",
"=",
"None",
",",
"password",
"=",
"None",
",",
"ip_address",
"=",
"None",
",... | Creates one or more clones of existing server.
https://www.centurylinkcloud.com/api-docs/v2/#servers-create-server
Set ttl as number of seconds before server is to be terminated.
* - network_id is currently a required parameter. This will change to optional once APIs are available to
return the network ... | [
"Creates",
"one",
"or",
"more",
"clones",
"of",
"existing",
"server",
"."
] | python | train |
adaptive-learning/proso-apps | proso_models/models.py | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/models.py#L539-L575 | def translate_identifiers(self, identifiers, language):
"""
Translate a list of identifiers to item ids. Identifier is a string of
the following form:
<model_prefix>/<model_identifier>
where <model_prefix> is any suffix of database table of the given model
which uniquel... | [
"def",
"translate_identifiers",
"(",
"self",
",",
"identifiers",
",",
"language",
")",
":",
"result",
"=",
"{",
"}",
"identifiers",
"=",
"set",
"(",
"identifiers",
")",
"item_types",
"=",
"ItemType",
".",
"objects",
".",
"get_all_types",
"(",
")",
"for",
"... | Translate a list of identifiers to item ids. Identifier is a string of
the following form:
<model_prefix>/<model_identifier>
where <model_prefix> is any suffix of database table of the given model
which uniquely specifies the table, and <model_identifier> is
identifier of the o... | [
"Translate",
"a",
"list",
"of",
"identifiers",
"to",
"item",
"ids",
".",
"Identifier",
"is",
"a",
"string",
"of",
"the",
"following",
"form",
":"
] | python | train |
F5Networks/f5-common-python | f5-sdk-dist/scripts/construct_setups.py | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5-sdk-dist/scripts/construct_setups.py#L36-L59 | def construct_cfgs(**kargs):
"""construct_cfgs
Performs actions to construct either the setup.cfg (rpm) or stdeb.cfg (deb)
files as per the operating system specified. This construction is done as
per the setup_requirements.txt file from within the working directory
specified.
This is a very tempermental functio... | [
"def",
"construct_cfgs",
"(",
"*",
"*",
"kargs",
")",
":",
"docker_dir",
"=",
"_check_args",
"(",
"*",
"*",
"kargs",
")",
"if",
"not",
"docker_dir",
"or",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"docker_dir",
")",
":",
"print",
"(",
"\"Unable to d... | construct_cfgs
Performs actions to construct either the setup.cfg (rpm) or stdeb.cfg (deb)
files as per the operating system specified. This construction is done as
per the setup_requirements.txt file from within the working directory
specified.
This is a very tempermental function by design. It intentionally exits... | [
"construct_cfgs"
] | python | train |
PedalPi/Application | application/controller/plugins_controller.py | https://github.com/PedalPi/Application/blob/3fdf6f97cfef97a7f1d90a5881dd04324c229f9d/application/controller/plugins_controller.py#L67-L77 | def by(self, technology):
"""
Get the plugins registered in PedalPi by technology
:param PluginTechnology technology: PluginTechnology identifier
"""
if technology == PluginTechnology.LV2 \
or str(technology).upper() == PluginTechnology.LV2.value.upper():
ret... | [
"def",
"by",
"(",
"self",
",",
"technology",
")",
":",
"if",
"technology",
"==",
"PluginTechnology",
".",
"LV2",
"or",
"str",
"(",
"technology",
")",
".",
"upper",
"(",
")",
"==",
"PluginTechnology",
".",
"LV2",
".",
"value",
".",
"upper",
"(",
")",
... | Get the plugins registered in PedalPi by technology
:param PluginTechnology technology: PluginTechnology identifier | [
"Get",
"the",
"plugins",
"registered",
"in",
"PedalPi",
"by",
"technology"
] | python | train |
llazzaro/analyzerstrategies | analyzerstrategies/zscoreMomentumPortfolioStrategy.py | https://github.com/llazzaro/analyzerstrategies/blob/3c647802f582bf2f06c6793f282bee0d26514cd6/analyzerstrategies/zscoreMomentumPortfolioStrategy.py#L120-L149 | def tickUpdate(self, tick):
''' consume ticks '''
LOG.debug("tickUpdate %s with tick %s, price %s" % (self.__symbol, tick.time, tick.close))
self.__priceZscore(tick.close)
self.__volumeZscore(tick.volume)
# get zscore
priceZscore=self.__priceZscore.getLastValue()
... | [
"def",
"tickUpdate",
"(",
"self",
",",
"tick",
")",
":",
"LOG",
".",
"debug",
"(",
"\"tickUpdate %s with tick %s, price %s\"",
"%",
"(",
"self",
".",
"__symbol",
",",
"tick",
".",
"time",
",",
"tick",
".",
"close",
")",
")",
"self",
".",
"__priceZscore",
... | consume ticks | [
"consume",
"ticks"
] | python | train |
emory-libraries/eulcommon | eulcommon/searchutil/templatetags/search_utils.py | https://github.com/emory-libraries/eulcommon/blob/dc63a9b3b5e38205178235e0d716d1b28158d3a9/eulcommon/searchutil/templatetags/search_utils.py#L6-L40 | def pagination_links(paginator_page, show_pages, url_params=None,
first_page_label=None, last_page_label=None,
page_url=''):
'''Django template tag to display pagination links for a paginated
list of items.
Expects the following variables:
* the current :class... | [
"def",
"pagination_links",
"(",
"paginator_page",
",",
"show_pages",
",",
"url_params",
"=",
"None",
",",
"first_page_label",
"=",
"None",
",",
"last_page_label",
"=",
"None",
",",
"page_url",
"=",
"''",
")",
":",
"return",
"{",
"'items'",
":",
"paginator_page... | Django template tag to display pagination links for a paginated
list of items.
Expects the following variables:
* the current :class:`~django.core.paginator.Page` of a
:class:`~django.core.paginator.Paginator` object
* a dictionary of the pages to be displayed, in the format
generated b... | [
"Django",
"template",
"tag",
"to",
"display",
"pagination",
"links",
"for",
"a",
"paginated",
"list",
"of",
"items",
"."
] | python | train |
Kozea/cairocffi | cairocffi/patterns.py | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/patterns.py#L111-L142 | def set_matrix(self, matrix):
"""Sets the pattern’s transformation matrix to :obj:`matrix`.
This matrix is a transformation from user space to pattern space.
When a pattern is first created
it always has the identity matrix for its transformation matrix,
which means that pattern... | [
"def",
"set_matrix",
"(",
"self",
",",
"matrix",
")",
":",
"cairo",
".",
"cairo_pattern_set_matrix",
"(",
"self",
".",
"_pointer",
",",
"matrix",
".",
"_pointer",
")",
"self",
".",
"_check_status",
"(",
")"
] | Sets the pattern’s transformation matrix to :obj:`matrix`.
This matrix is a transformation from user space to pattern space.
When a pattern is first created
it always has the identity matrix for its transformation matrix,
which means that pattern space is initially identical to user spa... | [
"Sets",
"the",
"pattern’s",
"transformation",
"matrix",
"to",
":",
"obj",
":",
"matrix",
".",
"This",
"matrix",
"is",
"a",
"transformation",
"from",
"user",
"space",
"to",
"pattern",
"space",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/frontend/terminal/interactiveshell.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/terminal/interactiveshell.py#L456-L475 | def mainloop(self, display_banner=None):
"""Start the mainloop.
If an optional banner argument is given, it will override the
internally created default banner.
"""
with nested(self.builtin_trap, self.display_trap):
while 1:
try:
... | [
"def",
"mainloop",
"(",
"self",
",",
"display_banner",
"=",
"None",
")",
":",
"with",
"nested",
"(",
"self",
".",
"builtin_trap",
",",
"self",
".",
"display_trap",
")",
":",
"while",
"1",
":",
"try",
":",
"self",
".",
"interact",
"(",
"display_banner",
... | Start the mainloop.
If an optional banner argument is given, it will override the
internally created default banner. | [
"Start",
"the",
"mainloop",
"."
] | python | test |
riggsd/davies | davies/compass/__init__.py | https://github.com/riggsd/davies/blob/8566c626202a875947ad01c087300108c68d80b5/davies/compass/__init__.py#L339-L346 | def write(self, outfname=None):
"""Write or overwrite a `Survey` to the specified .DAT file"""
outfname = outfname or self.filename
with codecs.open(outfname, 'wb', 'windows-1252') as outf:
for survey in self.surveys:
outf.write('\r\n'.join(survey._serialize()))
... | [
"def",
"write",
"(",
"self",
",",
"outfname",
"=",
"None",
")",
":",
"outfname",
"=",
"outfname",
"or",
"self",
".",
"filename",
"with",
"codecs",
".",
"open",
"(",
"outfname",
",",
"'wb'",
",",
"'windows-1252'",
")",
"as",
"outf",
":",
"for",
"survey"... | Write or overwrite a `Survey` to the specified .DAT file | [
"Write",
"or",
"overwrite",
"a",
"Survey",
"to",
"the",
"specified",
".",
"DAT",
"file"
] | python | train |
GNS3/gns3-server | gns3server/compute/project_manager.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/project_manager.py#L78-L96 | def _check_available_disk_space(self, project):
"""
Sends a warning notification if disk space is getting low.
:param project: project instance
"""
try:
used_disk_space = psutil.disk_usage(project.path).percent
except FileNotFoundError:
log.warni... | [
"def",
"_check_available_disk_space",
"(",
"self",
",",
"project",
")",
":",
"try",
":",
"used_disk_space",
"=",
"psutil",
".",
"disk_usage",
"(",
"project",
".",
"path",
")",
".",
"percent",
"except",
"FileNotFoundError",
":",
"log",
".",
"warning",
"(",
"'... | Sends a warning notification if disk space is getting low.
:param project: project instance | [
"Sends",
"a",
"warning",
"notification",
"if",
"disk",
"space",
"is",
"getting",
"low",
"."
] | python | train |
F5Networks/f5-common-python | f5/bigip/tm/security/firewall.py | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/security/firewall.py#L159-L162 | def update(self, **kwargs):
"""We need to implement the custom exclusive parameter check."""
self._check_exclusive_parameters(**kwargs)
return super(Rule, self)._update(**kwargs) | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_check_exclusive_parameters",
"(",
"*",
"*",
"kwargs",
")",
"return",
"super",
"(",
"Rule",
",",
"self",
")",
".",
"_update",
"(",
"*",
"*",
"kwargs",
")"
] | We need to implement the custom exclusive parameter check. | [
"We",
"need",
"to",
"implement",
"the",
"custom",
"exclusive",
"parameter",
"check",
"."
] | python | train |
google/grr | grr/core/grr_response_core/stats/default_stats_collector.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/stats/default_stats_collector.py#L77-L83 | def Increment(self, delta, fields=None):
"""Increments counter value by a given delta."""
if delta < 0:
raise ValueError(
"Counter increment should not be < 0 (received: %d)" % delta)
self._metric_values[_FieldsToKey(fields)] = self.Get(fields=fields) + delta | [
"def",
"Increment",
"(",
"self",
",",
"delta",
",",
"fields",
"=",
"None",
")",
":",
"if",
"delta",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Counter increment should not be < 0 (received: %d)\"",
"%",
"delta",
")",
"self",
".",
"_metric_values",
"[",
"_Fi... | Increments counter value by a given delta. | [
"Increments",
"counter",
"value",
"by",
"a",
"given",
"delta",
"."
] | python | train |
Autodesk/aomi | aomi/vault.py | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/vault.py#L72-L78 | def approle_token(vault_client, role_id, secret_id):
"""Returns a vault token based on the role and seret id"""
resp = vault_client.auth_approle(role_id, secret_id)
if 'auth' in resp and 'client_token' in resp['auth']:
return resp['auth']['client_token']
else:
raise aomi.exceptions.AomiC... | [
"def",
"approle_token",
"(",
"vault_client",
",",
"role_id",
",",
"secret_id",
")",
":",
"resp",
"=",
"vault_client",
".",
"auth_approle",
"(",
"role_id",
",",
"secret_id",
")",
"if",
"'auth'",
"in",
"resp",
"and",
"'client_token'",
"in",
"resp",
"[",
"'auth... | Returns a vault token based on the role and seret id | [
"Returns",
"a",
"vault",
"token",
"based",
"on",
"the",
"role",
"and",
"seret",
"id"
] | python | train |
maas/python-libmaas | maas/client/flesh/__init__.py | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/__init__.py#L260-L264 | def name(cls):
"""Return the preferred name as which this command will be known."""
name = cls.__name__.replace("_", "-").lower()
name = name[4:] if name.startswith("cmd-") else name
return name | [
"def",
"name",
"(",
"cls",
")",
":",
"name",
"=",
"cls",
".",
"__name__",
".",
"replace",
"(",
"\"_\"",
",",
"\"-\"",
")",
".",
"lower",
"(",
")",
"name",
"=",
"name",
"[",
"4",
":",
"]",
"if",
"name",
".",
"startswith",
"(",
"\"cmd-\"",
")",
"... | Return the preferred name as which this command will be known. | [
"Return",
"the",
"preferred",
"name",
"as",
"which",
"this",
"command",
"will",
"be",
"known",
"."
] | python | train |
rackerlabs/fleece | fleece/log.py | https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/log.py#L93-L116 | def _has_streamhandler(logger, level=None, fmt=LOG_FORMAT,
stream=DEFAULT_STREAM):
"""Check the named logger for an appropriate existing StreamHandler.
This only returns True if a StreamHandler that exaclty matches
our specification is found. If other StreamHandlers are seen,
we ... | [
"def",
"_has_streamhandler",
"(",
"logger",
",",
"level",
"=",
"None",
",",
"fmt",
"=",
"LOG_FORMAT",
",",
"stream",
"=",
"DEFAULT_STREAM",
")",
":",
"# Ensure we are talking the same type of logging levels",
"# if they passed in a string we need to convert it to a number",
"... | Check the named logger for an appropriate existing StreamHandler.
This only returns True if a StreamHandler that exaclty matches
our specification is found. If other StreamHandlers are seen,
we assume they were added for a different purpose. | [
"Check",
"the",
"named",
"logger",
"for",
"an",
"appropriate",
"existing",
"StreamHandler",
"."
] | python | train |
tiany/django-aliyun-storage | aliyunstorage/backends.py | https://github.com/tiany/django-aliyun-storage/blob/582760ea05d333d37ff1a3bebff94437d7965a88/aliyunstorage/backends.py#L18-L32 | def get_aliyun_config(name, default=None):
'''
Get configuration variable from environment variable or
or django settings.py
'''
config = os.environ.get(name, getattr(settings, name, default))
if config is not None:
if isinstance(config, str):
return config.strip()
el... | [
"def",
"get_aliyun_config",
"(",
"name",
",",
"default",
"=",
"None",
")",
":",
"config",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"name",
",",
"getattr",
"(",
"settings",
",",
"name",
",",
"default",
")",
")",
"if",
"config",
"is",
"not",
"None",... | Get configuration variable from environment variable or
or django settings.py | [
"Get",
"configuration",
"variable",
"from",
"environment",
"variable",
"or",
"or",
"django",
"settings",
".",
"py"
] | python | train |
mitodl/django-server-status | server_status/views.py | https://github.com/mitodl/django-server-status/blob/99bd29343138f94a08718fdbd9285e551751777b/server_status/views.py#L156-L182 | def get_certificate_info():
"""
checks app certificate expiry status
"""
if hasattr(settings, 'MIT_WS_CERTIFICATE') and settings.MIT_WS_CERTIFICATE:
mit_ws_certificate = settings.MIT_WS_CERTIFICATE
else:
return {"status": NO_CONFIG}
app_cert = OpenSSL.crypto.load_certificate(
... | [
"def",
"get_certificate_info",
"(",
")",
":",
"if",
"hasattr",
"(",
"settings",
",",
"'MIT_WS_CERTIFICATE'",
")",
"and",
"settings",
".",
"MIT_WS_CERTIFICATE",
":",
"mit_ws_certificate",
"=",
"settings",
".",
"MIT_WS_CERTIFICATE",
"else",
":",
"return",
"{",
"\"st... | checks app certificate expiry status | [
"checks",
"app",
"certificate",
"expiry",
"status"
] | python | train |
cloudendpoints/endpoints-python | endpoints/api_config_manager.py | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L79-L150 | def _get_sorted_methods(self, methods):
"""Get a copy of 'methods' sorted the way they would be on the live server.
Args:
methods: JSON configuration of an API's methods.
Returns:
The same configuration with the methods sorted based on what order
they'll be checked by the server.
"""... | [
"def",
"_get_sorted_methods",
"(",
"self",
",",
"methods",
")",
":",
"if",
"not",
"methods",
":",
"return",
"methods",
"# Comparison function we'll use to sort the methods:",
"def",
"_sorted_methods_comparison",
"(",
"method_info1",
",",
"method_info2",
")",
":",
"\"\"\... | Get a copy of 'methods' sorted the way they would be on the live server.
Args:
methods: JSON configuration of an API's methods.
Returns:
The same configuration with the methods sorted based on what order
they'll be checked by the server. | [
"Get",
"a",
"copy",
"of",
"methods",
"sorted",
"the",
"way",
"they",
"would",
"be",
"on",
"the",
"live",
"server",
"."
] | python | train |
pycontribs/pyrax | pyrax/utils.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/utils.py#L504-L528 | def iso_time_string(val, show_tzinfo=False):
"""
Takes either a date, datetime or a string, and returns the standard ISO
formatted string for that date/time, with any fractional second portion
removed.
"""
if not val:
return ""
if isinstance(val, six.string_types):
dt = _pars... | [
"def",
"iso_time_string",
"(",
"val",
",",
"show_tzinfo",
"=",
"False",
")",
":",
"if",
"not",
"val",
":",
"return",
"\"\"",
"if",
"isinstance",
"(",
"val",
",",
"six",
".",
"string_types",
")",
":",
"dt",
"=",
"_parse_datetime_string",
"(",
"val",
")",
... | Takes either a date, datetime or a string, and returns the standard ISO
formatted string for that date/time, with any fractional second portion
removed. | [
"Takes",
"either",
"a",
"date",
"datetime",
"or",
"a",
"string",
"and",
"returns",
"the",
"standard",
"ISO",
"formatted",
"string",
"for",
"that",
"date",
"/",
"time",
"with",
"any",
"fractional",
"second",
"portion",
"removed",
"."
] | python | train |
heikomuller/sco-datastore | scodata/__init__.py | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/__init__.py#L228-L251 | def experiments_fmri_download(self, experiment_id):
"""Download the fMRI data file associated with given experiment.
Parameters
----------
experiment_id : string
Unique experiment identifier
Returns
-------
FileInfo
Information about fMRI... | [
"def",
"experiments_fmri_download",
"(",
"self",
",",
"experiment_id",
")",
":",
"# Get experiment fMRI to ensure that it exists",
"fmri",
"=",
"self",
".",
"experiments_fmri_get",
"(",
"experiment_id",
")",
"if",
"fmri",
"is",
"None",
":",
"return",
"None",
"# Return... | Download the fMRI data file associated with given experiment.
Parameters
----------
experiment_id : string
Unique experiment identifier
Returns
-------
FileInfo
Information about fMRI file on disk or None if experiment is
unknown or h... | [
"Download",
"the",
"fMRI",
"data",
"file",
"associated",
"with",
"given",
"experiment",
"."
] | python | train |
viewflow/django-fsm | django_fsm/__init__.py | https://github.com/viewflow/django-fsm/blob/c86cd3eb949467626ffc68249ad001746333c38e/django_fsm/__init__.py#L106-L117 | def get_available_FIELD_transitions(instance, field):
"""
List of transitions available in current model state
with all conditions met
"""
curr_state = field.get_state(instance)
transitions = field.transitions[instance.__class__]
for name, transition in transitions.items():
meta = t... | [
"def",
"get_available_FIELD_transitions",
"(",
"instance",
",",
"field",
")",
":",
"curr_state",
"=",
"field",
".",
"get_state",
"(",
"instance",
")",
"transitions",
"=",
"field",
".",
"transitions",
"[",
"instance",
".",
"__class__",
"]",
"for",
"name",
",",
... | List of transitions available in current model state
with all conditions met | [
"List",
"of",
"transitions",
"available",
"in",
"current",
"model",
"state",
"with",
"all",
"conditions",
"met"
] | python | train |
bram85/topydo | topydo/lib/Color.py | https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Color.py#L182-L193 | def as_rgb(self):
"""
Returns a tuple (r, g, b) of the color.
"""
html = self.as_html()
return (
int(html[1:3], 16),
int(html[3:5], 16),
int(html[5:7], 16)
) | [
"def",
"as_rgb",
"(",
"self",
")",
":",
"html",
"=",
"self",
".",
"as_html",
"(",
")",
"return",
"(",
"int",
"(",
"html",
"[",
"1",
":",
"3",
"]",
",",
"16",
")",
",",
"int",
"(",
"html",
"[",
"3",
":",
"5",
"]",
",",
"16",
")",
",",
"int... | Returns a tuple (r, g, b) of the color. | [
"Returns",
"a",
"tuple",
"(",
"r",
"g",
"b",
")",
"of",
"the",
"color",
"."
] | python | train |
krukas/Trionyx | trionyx/trionyx/views/core.py | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/views/core.py#L186-L193 | def get_search(self):
"""Get current search or search from session, reset page if search is changed"""
old_search = self.get_session_value('search', '')
search = self.get_and_save_value('search', '')
if old_search != search:
self.page = 1
self.get_session_value('p... | [
"def",
"get_search",
"(",
"self",
")",
":",
"old_search",
"=",
"self",
".",
"get_session_value",
"(",
"'search'",
",",
"''",
")",
"search",
"=",
"self",
".",
"get_and_save_value",
"(",
"'search'",
",",
"''",
")",
"if",
"old_search",
"!=",
"search",
":",
... | Get current search or search from session, reset page if search is changed | [
"Get",
"current",
"search",
"or",
"search",
"from",
"session",
"reset",
"page",
"if",
"search",
"is",
"changed"
] | python | train |
lvieirajr/mongorest | mongorest/collection.py | https://github.com/lvieirajr/mongorest/blob/00f4487ded33254434bc51ff09d48c7a936bd465/mongorest/collection.py#L367-L372 | def documents(cls, filter=None, **kwargs):
"""
Returns a list of Documents if any document is filtered
"""
documents = [cls(document) for document in cls.find(filter, **kwargs)]
return [document for document in documents if document.document] | [
"def",
"documents",
"(",
"cls",
",",
"filter",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"documents",
"=",
"[",
"cls",
"(",
"document",
")",
"for",
"document",
"in",
"cls",
".",
"find",
"(",
"filter",
",",
"*",
"*",
"kwargs",
")",
"]",
"ret... | Returns a list of Documents if any document is filtered | [
"Returns",
"a",
"list",
"of",
"Documents",
"if",
"any",
"document",
"is",
"filtered"
] | python | train |
justinmayer/django-autoslug | autoslug/utils.py | https://github.com/justinmayer/django-autoslug/blob/b3991daddf5a476a829b48c28afad4ae08a18179/autoslug/utils.py#L48-L89 | def generate_unique_slug(field, instance, slug, manager):
"""
Generates unique slug by adding a number to given value until no model
instance can be found with such slug. If ``unique_with`` (a tuple of field
names) was specified for the field, all these fields are included together
in the query when... | [
"def",
"generate_unique_slug",
"(",
"field",
",",
"instance",
",",
"slug",
",",
"manager",
")",
":",
"original_slug",
"=",
"slug",
"=",
"crop_slug",
"(",
"field",
",",
"slug",
")",
"default_lookups",
"=",
"tuple",
"(",
"get_uniqueness_lookups",
"(",
"field",
... | Generates unique slug by adding a number to given value until no model
instance can be found with such slug. If ``unique_with`` (a tuple of field
names) was specified for the field, all these fields are included together
in the query when looking for a "rival" model instance. | [
"Generates",
"unique",
"slug",
"by",
"adding",
"a",
"number",
"to",
"given",
"value",
"until",
"no",
"model",
"instance",
"can",
"be",
"found",
"with",
"such",
"slug",
".",
"If",
"unique_with",
"(",
"a",
"tuple",
"of",
"field",
"names",
")",
"was",
"spec... | python | train |
Arubacloud/pyArubaCloud | ArubaCloud/PyArubaAPI.py | https://github.com/Arubacloud/pyArubaCloud/blob/ec4aecd8ca342b1e1a4f16b7cc87cb5e697cfcd4/ArubaCloud/PyArubaAPI.py#L184-L216 | def find_template(self, name=None, hv=None):
"""
Return a list of templates that could have one or more elements.
Args:
name: name of the template to find.
hv: the ID of the hypervisor to search the template in
Returns:
A list of templates object. If h... | [
"def",
"find_template",
"(",
"self",
",",
"name",
"=",
"None",
",",
"hv",
"=",
"None",
")",
":",
"if",
"len",
"(",
"self",
".",
"templates",
")",
"<=",
"0",
":",
"self",
".",
"get_hypervisors",
"(",
")",
"if",
"name",
"is",
"not",
"None",
"and",
... | Return a list of templates that could have one or more elements.
Args:
name: name of the template to find.
hv: the ID of the hypervisor to search the template in
Returns:
A list of templates object. If hv is None will return all the
templates matching the ... | [
"Return",
"a",
"list",
"of",
"templates",
"that",
"could",
"have",
"one",
"or",
"more",
"elements",
".",
"Args",
":",
"name",
":",
"name",
"of",
"the",
"template",
"to",
"find",
".",
"hv",
":",
"the",
"ID",
"of",
"the",
"hypervisor",
"to",
"search",
... | python | train |
metacloud/gilt | gilt/git.py | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/git.py#L49-L74 | def extract(repository, destination, version, debug=False):
"""
Extract the specified repository/version into the given directory and
return None.
:param repository: A string containing the path to the repository to be
extracted.
:param destination: A string containing the directory to clone t... | [
"def",
"extract",
"(",
"repository",
",",
"destination",
",",
"version",
",",
"debug",
"=",
"False",
")",
":",
"with",
"util",
".",
"saved_cwd",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"destination",
")",
":",
"shutil",
".",
"rmtre... | Extract the specified repository/version into the given directory and
return None.
:param repository: A string containing the path to the repository to be
extracted.
:param destination: A string containing the directory to clone the
repository into. Relative to the directory ``gilt`` is running
... | [
"Extract",
"the",
"specified",
"repository",
"/",
"version",
"into",
"the",
"given",
"directory",
"and",
"return",
"None",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/io/abinit/works.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/works.py#L61-L70 | def from_node(cls, work):
"""Initialize an instance from a :class:`Work` instance."""
new = super().from_node(work)
# Will put all files found in outdir in GridFs
# Warning: assuming binary files.
d = {os.path.basename(f): f for f in work.outdir.list_filepaths()}
new.reg... | [
"def",
"from_node",
"(",
"cls",
",",
"work",
")",
":",
"new",
"=",
"super",
"(",
")",
".",
"from_node",
"(",
"work",
")",
"# Will put all files found in outdir in GridFs",
"# Warning: assuming binary files.",
"d",
"=",
"{",
"os",
".",
"path",
".",
"basename",
... | Initialize an instance from a :class:`Work` instance. | [
"Initialize",
"an",
"instance",
"from",
"a",
":",
"class",
":",
"Work",
"instance",
"."
] | python | train |
harlowja/failure | failure/failure.py | https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L584-L620 | def _extract_cause(cls, exc_val):
"""Helper routine to extract nested cause (if any)."""
# See: https://www.python.org/dev/peps/pep-3134/ for why/what
# these are...
#
# '__cause__' attribute for explicitly chained exceptions
# '__context__' attribute for implicitly chain... | [
"def",
"_extract_cause",
"(",
"cls",
",",
"exc_val",
")",
":",
"# See: https://www.python.org/dev/peps/pep-3134/ for why/what",
"# these are...",
"#",
"# '__cause__' attribute for explicitly chained exceptions",
"# '__context__' attribute for implicitly chained exceptions",
"# '__traceback... | Helper routine to extract nested cause (if any). | [
"Helper",
"routine",
"to",
"extract",
"nested",
"cause",
"(",
"if",
"any",
")",
"."
] | python | train |
sci-bots/mpm | mpm/api.py | https://github.com/sci-bots/mpm/blob/a69651cda4b37ee6b17df4fe0809249e7f4dc536/mpm/api.py#L464-L539 | def update(*args, **kwargs):
'''
Update installed plugin package(s).
Each plugin package must have a directory (**NOT** a link) containing a
``properties.yml`` file with a ``package_name`` value in the following
directory:
<conda prefix>/share/microdrop/plugins/available/
Parameters
... | [
"def",
"update",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"package_name",
"=",
"kwargs",
".",
"pop",
"(",
"'package_name'",
",",
"None",
")",
"# Only consider **installed** plugins (see `installed_plugins()` docstring).",
"installed_plugins_",
"=",
"instal... | Update installed plugin package(s).
Each plugin package must have a directory (**NOT** a link) containing a
``properties.yml`` file with a ``package_name`` value in the following
directory:
<conda prefix>/share/microdrop/plugins/available/
Parameters
----------
*args
Extra arg... | [
"Update",
"installed",
"plugin",
"package",
"(",
"s",
")",
"."
] | python | train |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L858-L862 | def alloc_seg(self, net_id):
"""Allocates the segmentation ID. """
segmentation_id = self.service_segs.allocate_segmentation_id(
net_id, source=fw_const.FW_CONST)
return segmentation_id | [
"def",
"alloc_seg",
"(",
"self",
",",
"net_id",
")",
":",
"segmentation_id",
"=",
"self",
".",
"service_segs",
".",
"allocate_segmentation_id",
"(",
"net_id",
",",
"source",
"=",
"fw_const",
".",
"FW_CONST",
")",
"return",
"segmentation_id"
] | Allocates the segmentation ID. | [
"Allocates",
"the",
"segmentation",
"ID",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/combinators.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/combinators.py#L134-L145 | def _nested_op(inputs, op): # pylint: disable=invalid-name
"""Helper: sum a list of arrays or nested arrays."""
# First the simple non-nested case.
if not isinstance(inputs[0], (list, tuple)):
return op(inputs)
# In the nested case, sum on each axis separately.
result_list = []
for i in range(len(input... | [
"def",
"_nested_op",
"(",
"inputs",
",",
"op",
")",
":",
"# pylint: disable=invalid-name",
"# First the simple non-nested case.",
"if",
"not",
"isinstance",
"(",
"inputs",
"[",
"0",
"]",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"op",
"(",
"in... | Helper: sum a list of arrays or nested arrays. | [
"Helper",
":",
"sum",
"a",
"list",
"of",
"arrays",
"or",
"nested",
"arrays",
"."
] | python | train |
tensorflow/probability | tensorflow_probability/python/distributions/normal.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/normal.py#L234-L237 | def _inv_z(self, z):
"""Reconstruct input `x` from a its normalized version."""
with tf.name_scope("reconstruct"):
return z * self.scale + self.loc | [
"def",
"_inv_z",
"(",
"self",
",",
"z",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"reconstruct\"",
")",
":",
"return",
"z",
"*",
"self",
".",
"scale",
"+",
"self",
".",
"loc"
] | Reconstruct input `x` from a its normalized version. | [
"Reconstruct",
"input",
"x",
"from",
"a",
"its",
"normalized",
"version",
"."
] | python | test |
gbiggs/rtctree | rtctree/node.py | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/node.py#L220-L233 | def rem_callback(self, event, cb):
'''Remove a callback from this node.
The callback is removed from the specified event.
@param cb The callback function to remove.
'''
if event not in self._cbs:
raise exceptions.NoSuchEventError(self.name, event)
c = [(x[0... | [
"def",
"rem_callback",
"(",
"self",
",",
"event",
",",
"cb",
")",
":",
"if",
"event",
"not",
"in",
"self",
".",
"_cbs",
":",
"raise",
"exceptions",
".",
"NoSuchEventError",
"(",
"self",
".",
"name",
",",
"event",
")",
"c",
"=",
"[",
"(",
"x",
"[",
... | Remove a callback from this node.
The callback is removed from the specified event.
@param cb The callback function to remove. | [
"Remove",
"a",
"callback",
"from",
"this",
"node",
"."
] | python | train |
odlgroup/odl | odl/contrib/tomo/elekta.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/contrib/tomo/elekta.py#L163-L205 | def elekta_icon_fbp(ray_transform,
padding=False, filter_type='Hann', frequency_scaling=0.6,
parker_weighting=True):
"""Approximation of the FDK reconstruction used in the Elekta Icon.
Parameters
----------
ray_transform : `RayTransform`
The ray transform... | [
"def",
"elekta_icon_fbp",
"(",
"ray_transform",
",",
"padding",
"=",
"False",
",",
"filter_type",
"=",
"'Hann'",
",",
"frequency_scaling",
"=",
"0.6",
",",
"parker_weighting",
"=",
"True",
")",
":",
"fbp_op",
"=",
"odl",
".",
"tomo",
".",
"fbp_op",
"(",
"r... | Approximation of the FDK reconstruction used in the Elekta Icon.
Parameters
----------
ray_transform : `RayTransform`
The ray transform to be used, should have an Elekta Icon geometry.
padding : bool, optional
Whether the FBP filter should use padding, increases memory use
signi... | [
"Approximation",
"of",
"the",
"FDK",
"reconstruction",
"used",
"in",
"the",
"Elekta",
"Icon",
"."
] | python | train |
DinoTools/python-flextls | flextls/field.py | https://github.com/DinoTools/python-flextls/blob/c73448f20e79b1969adcc2271b91d8edda517857/flextls/field.py#L157-L171 | def get_value_name(self, pretty=False):
"""
Get the name of the value
:param Boolean pretty: Return the name in a pretty format
:return: The name
:rtype: String
"""
if pretty:
return "%s (%x)" % (
self.enums.get(self._value, "n/a"),
... | [
"def",
"get_value_name",
"(",
"self",
",",
"pretty",
"=",
"False",
")",
":",
"if",
"pretty",
":",
"return",
"\"%s (%x)\"",
"%",
"(",
"self",
".",
"enums",
".",
"get",
"(",
"self",
".",
"_value",
",",
"\"n/a\"",
")",
",",
"self",
".",
"_value",
")",
... | Get the name of the value
:param Boolean pretty: Return the name in a pretty format
:return: The name
:rtype: String | [
"Get",
"the",
"name",
"of",
"the",
"value"
] | python | train |
bukun/TorCMS | torcms/handlers/page_ajax_handler.py | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/page_ajax_handler.py#L61-L66 | def j_count_plus(self, slug):
'''
plus count via ajax.
'''
output = {'status': 1 if MWiki.view_count_plus(slug) else 0}
return json.dump(output, self) | [
"def",
"j_count_plus",
"(",
"self",
",",
"slug",
")",
":",
"output",
"=",
"{",
"'status'",
":",
"1",
"if",
"MWiki",
".",
"view_count_plus",
"(",
"slug",
")",
"else",
"0",
"}",
"return",
"json",
".",
"dump",
"(",
"output",
",",
"self",
")"
] | plus count via ajax. | [
"plus",
"count",
"via",
"ajax",
"."
] | python | train |
msztolcman/versionner | versionner/commands/__init__.py | https://github.com/msztolcman/versionner/blob/78fca02859e3e3eb71c9eb7ea230758944177c54/versionner/commands/__init__.py#L38-L47 | def get(name, *args, **kwargs):
"""Find command class for given command name and return it's instance
:param name: str
:param args: additional arguments for Command
:param kwargs: additional arguments for Command
:return: Command
"""
cmd = COMMAND_MAPPER.get(name)
return cmd(*args, **kw... | [
"def",
"get",
"(",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cmd",
"=",
"COMMAND_MAPPER",
".",
"get",
"(",
"name",
")",
"return",
"cmd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Find command class for given command name and return it's instance
:param name: str
:param args: additional arguments for Command
:param kwargs: additional arguments for Command
:return: Command | [
"Find",
"command",
"class",
"for",
"given",
"command",
"name",
"and",
"return",
"it",
"s",
"instance"
] | python | train |
toumorokoshi/jsonschema-extractor | jsonschema_extractor/typing_extractor.py | https://github.com/toumorokoshi/jsonschema-extractor/blob/e72c608f6ea72cb8bb43912e1177829cff32c13b/jsonschema_extractor/typing_extractor.py#L104-L115 | def _is_sequence(typ):
"""
returns True if the type in question
is a Sequence[] object from the typing module.
"""
# PEP_560 deprecates issubclass for
# List types, for the time being
# we'll support a specific escape hatch.
if PEP_560: # pragma: no cover
return isinstance(typ, ... | [
"def",
"_is_sequence",
"(",
"typ",
")",
":",
"# PEP_560 deprecates issubclass for",
"# List types, for the time being",
"# we'll support a specific escape hatch.",
"if",
"PEP_560",
":",
"# pragma: no cover",
"return",
"isinstance",
"(",
"typ",
",",
"_GenericAlias",
")",
"and"... | returns True if the type in question
is a Sequence[] object from the typing module. | [
"returns",
"True",
"if",
"the",
"type",
"in",
"question",
"is",
"a",
"Sequence",
"[]",
"object",
"from",
"the",
"typing",
"module",
"."
] | python | train |
hugapi/hug | hug/use.py | https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/use.py#L245-L249 | def _dgram_send_and_receive(self, _socket, message, buffer_size=4096, *args):
"""User Datagram Protocol sender and receiver"""
_socket.send(message.encode('utf-8'))
data, address = _socket.recvfrom(buffer_size)
return BytesIO(data) | [
"def",
"_dgram_send_and_receive",
"(",
"self",
",",
"_socket",
",",
"message",
",",
"buffer_size",
"=",
"4096",
",",
"*",
"args",
")",
":",
"_socket",
".",
"send",
"(",
"message",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"data",
",",
"address",
"=",
"_... | User Datagram Protocol sender and receiver | [
"User",
"Datagram",
"Protocol",
"sender",
"and",
"receiver"
] | python | train |
googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/client.py#L342-L354 | def collections(self):
"""List top-level collections of the client's database.
Returns:
Sequence[~.firestore_v1beta1.collection.CollectionReference]:
iterator of subcollections of the current document.
"""
iterator = self._firestore_api.list_collection_ids(
... | [
"def",
"collections",
"(",
"self",
")",
":",
"iterator",
"=",
"self",
".",
"_firestore_api",
".",
"list_collection_ids",
"(",
"self",
".",
"_database_string",
",",
"metadata",
"=",
"self",
".",
"_rpc_metadata",
")",
"iterator",
".",
"client",
"=",
"self",
"i... | List top-level collections of the client's database.
Returns:
Sequence[~.firestore_v1beta1.collection.CollectionReference]:
iterator of subcollections of the current document. | [
"List",
"top",
"-",
"level",
"collections",
"of",
"the",
"client",
"s",
"database",
"."
] | python | train |
pantsbuild/pants | src/python/pants/backend/python/subsystems/pex_build_util.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/python/subsystems/pex_build_util.py#L189-L211 | def extract_single_dist_for_current_platform(self, reqs, dist_key):
"""Resolve a specific distribution from a set of requirements matching the current platform.
:param list reqs: A list of :class:`PythonRequirement` to resolve.
:param str dist_key: The value of `distribution.key` to match for a `distributi... | [
"def",
"extract_single_dist_for_current_platform",
"(",
"self",
",",
"reqs",
",",
"dist_key",
")",
":",
"distributions",
"=",
"self",
".",
"_resolve_distributions_by_platform",
"(",
"reqs",
",",
"platforms",
"=",
"[",
"'current'",
"]",
")",
"try",
":",
"matched_di... | Resolve a specific distribution from a set of requirements matching the current platform.
:param list reqs: A list of :class:`PythonRequirement` to resolve.
:param str dist_key: The value of `distribution.key` to match for a `distribution` from the
resolved requirements.
:return: T... | [
"Resolve",
"a",
"specific",
"distribution",
"from",
"a",
"set",
"of",
"requirements",
"matching",
"the",
"current",
"platform",
"."
] | python | train |
elliterate/capybara.py | capybara/queries/selector_query.py | https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/queries/selector_query.py#L93-L98 | def kwargs(self):
""" Dict[str, Any]: The keyword arguments with which this query was initialized. """
kwargs = {}
kwargs.update(self.options)
kwargs.update(self.filter_options)
return kwargs | [
"def",
"kwargs",
"(",
"self",
")",
":",
"kwargs",
"=",
"{",
"}",
"kwargs",
".",
"update",
"(",
"self",
".",
"options",
")",
"kwargs",
".",
"update",
"(",
"self",
".",
"filter_options",
")",
"return",
"kwargs"
] | Dict[str, Any]: The keyword arguments with which this query was initialized. | [
"Dict",
"[",
"str",
"Any",
"]",
":",
"The",
"keyword",
"arguments",
"with",
"which",
"this",
"query",
"was",
"initialized",
"."
] | python | test |
dstufft/storages | storages/utils.py | https://github.com/dstufft/storages/blob/0d893afc1db32cd83eaf8e2ad4ed51b37933d5f0/storages/utils.py#L48-L70 | def safe_join(base, *paths):
"""
Joins one or more path components to the base path component intelligently.
Returns a normalized, absolute version of the final path.
The final path must be located inside of the base path component (otherwise
a ValueError is raised).
"""
base = base
pat... | [
"def",
"safe_join",
"(",
"base",
",",
"*",
"paths",
")",
":",
"base",
"=",
"base",
"paths",
"=",
"[",
"p",
"for",
"p",
"in",
"paths",
"]",
"final_path",
"=",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"*",
"paths",
")",
"... | Joins one or more path components to the base path component intelligently.
Returns a normalized, absolute version of the final path.
The final path must be located inside of the base path component (otherwise
a ValueError is raised). | [
"Joins",
"one",
"or",
"more",
"path",
"components",
"to",
"the",
"base",
"path",
"component",
"intelligently",
".",
"Returns",
"a",
"normalized",
"absolute",
"version",
"of",
"the",
"final",
"path",
"."
] | python | train |
Erotemic/utool | utool/util_str.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L1327-L1336 | def repr2_json(obj_, **kwargs):
""" hack for json reprs """
import utool as ut
kwargs['trailing_sep'] = False
json_str = ut.repr2(obj_, **kwargs)
json_str = str(json_str.replace('\'', '"'))
json_str = json_str.replace('(', '[')
json_str = json_str.replace(')', ']')
json_str = json_str.re... | [
"def",
"repr2_json",
"(",
"obj_",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"utool",
"as",
"ut",
"kwargs",
"[",
"'trailing_sep'",
"]",
"=",
"False",
"json_str",
"=",
"ut",
".",
"repr2",
"(",
"obj_",
",",
"*",
"*",
"kwargs",
")",
"json_str",
"=",
... | hack for json reprs | [
"hack",
"for",
"json",
"reprs"
] | python | train |
mozilla/Marketplace.Python | marketplace/connection.py | https://github.com/mozilla/Marketplace.Python/blob/88176b12201f766b6b96bccc1e4c3e82f0676283/marketplace/connection.py#L66-L79 | def fetch(self, method, url, data=None, expected_status_code=None):
"""Prepare the headers, encode data, call API and provide
data it returns
"""
kwargs = self.prepare_request(method, url, data)
log.debug(json.dumps(kwargs))
response = getattr(requests, method.lower())(ur... | [
"def",
"fetch",
"(",
"self",
",",
"method",
",",
"url",
",",
"data",
"=",
"None",
",",
"expected_status_code",
"=",
"None",
")",
":",
"kwargs",
"=",
"self",
".",
"prepare_request",
"(",
"method",
",",
"url",
",",
"data",
")",
"log",
".",
"debug",
"("... | Prepare the headers, encode data, call API and provide
data it returns | [
"Prepare",
"the",
"headers",
"encode",
"data",
"call",
"API",
"and",
"provide",
"data",
"it",
"returns"
] | python | train |
pawelad/pymonzo | src/pymonzo/monzo_api.py | https://github.com/pawelad/pymonzo/blob/b5c8d4f46dcb3a2f475797a8b8ef1c15f6493fb9/src/pymonzo/monzo_api.py#L331-L372 | def transactions(self, account_id=None, reverse=True, limit=None):
"""
Returns a list of transactions on the user's account.
Official docs:
https://monzo.com/docs/#list-transactions
:param account_id: Monzo account ID
:type account_id: str
:param reverse: wh... | [
"def",
"transactions",
"(",
"self",
",",
"account_id",
"=",
"None",
",",
"reverse",
"=",
"True",
",",
"limit",
"=",
"None",
")",
":",
"if",
"not",
"account_id",
":",
"if",
"len",
"(",
"self",
".",
"accounts",
"(",
")",
")",
"==",
"1",
":",
"account... | Returns a list of transactions on the user's account.
Official docs:
https://monzo.com/docs/#list-transactions
:param account_id: Monzo account ID
:type account_id: str
:param reverse: whether transactions should be in in descending order
:type reverse: bool
... | [
"Returns",
"a",
"list",
"of",
"transactions",
"on",
"the",
"user",
"s",
"account",
"."
] | python | train |
DarkEnergySurvey/ugali | setup.py | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/setup.py#L250-L258 | def install_isochrones(self):
"""
Call to isochrone install command:
http://stackoverflow.com/a/24353921/4075339
"""
cmd_obj = self.distribution.get_command_obj('isochrones')
cmd_obj.force = self.force
if self.ugali_dir: cmd_obj.ugali_dir = self.ugali_dir
... | [
"def",
"install_isochrones",
"(",
"self",
")",
":",
"cmd_obj",
"=",
"self",
".",
"distribution",
".",
"get_command_obj",
"(",
"'isochrones'",
")",
"cmd_obj",
".",
"force",
"=",
"self",
".",
"force",
"if",
"self",
".",
"ugali_dir",
":",
"cmd_obj",
".",
"uga... | Call to isochrone install command:
http://stackoverflow.com/a/24353921/4075339 | [
"Call",
"to",
"isochrone",
"install",
"command",
":",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"24353921",
"/",
"4075339"
] | python | train |
weijia/djangoautoconf | djangoautoconf/class_based_views/create_view_factory.py | https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/class_based_views/create_view_factory.py#L33-L53 | def create_ajaxable_view_from_model_inherit_parent_class(model_class, parent_class_list, operation="Create"):
"""
:param model_class: the django model class
:param operation: "Create" or "Update"
:param ajax_mixin: user may pass a sub class of AjaxableResponseMixin to put more info in the ajax response
... | [
"def",
"create_ajaxable_view_from_model_inherit_parent_class",
"(",
"model_class",
",",
"parent_class_list",
",",
"operation",
"=",
"\"Create\"",
")",
":",
"generic_module",
"=",
"importlib",
".",
"import_module",
"(",
"\"django.views.generic\"",
")",
"view_class_name",
"="... | :param model_class: the django model class
:param operation: "Create" or "Update"
:param ajax_mixin: user may pass a sub class of AjaxableResponseMixin to put more info in the ajax response
:return: dynamically generated class based view. The instance of the view class has as_view method. | [
":",
"param",
"model_class",
":",
"the",
"django",
"model",
"class",
":",
"param",
"operation",
":",
"Create",
"or",
"Update",
":",
"param",
"ajax_mixin",
":",
"user",
"may",
"pass",
"a",
"sub",
"class",
"of",
"AjaxableResponseMixin",
"to",
"put",
"more",
... | python | train |
genialis/resolwe | resolwe/flow/views/data.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/views/data.py#L187-L213 | def perform_create(self, serializer):
"""Create a resource."""
process = serializer.validated_data.get('process')
if not process.is_active:
raise exceptions.ParseError(
'Process retired (id: {}, slug: {}/{}).'.format(process.id, process.slug, process.version)
... | [
"def",
"perform_create",
"(",
"self",
",",
"serializer",
")",
":",
"process",
"=",
"serializer",
".",
"validated_data",
".",
"get",
"(",
"'process'",
")",
"if",
"not",
"process",
".",
"is_active",
":",
"raise",
"exceptions",
".",
"ParseError",
"(",
"'Process... | Create a resource. | [
"Create",
"a",
"resource",
"."
] | python | train |
juju/charm-helpers | charmhelpers/core/hookenv.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L960-L965 | def action_set(values):
"""Sets the values to be returned after the action finishes"""
cmd = ['action-set']
for k, v in list(values.items()):
cmd.append('{}={}'.format(k, v))
subprocess.check_call(cmd) | [
"def",
"action_set",
"(",
"values",
")",
":",
"cmd",
"=",
"[",
"'action-set'",
"]",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"values",
".",
"items",
"(",
")",
")",
":",
"cmd",
".",
"append",
"(",
"'{}={}'",
".",
"format",
"(",
"k",
",",
"v",
")... | Sets the values to be returned after the action finishes | [
"Sets",
"the",
"values",
"to",
"be",
"returned",
"after",
"the",
"action",
"finishes"
] | python | train |
ethereum/eth-abi | eth_abi/base.py | https://github.com/ethereum/eth-abi/blob/0a5cab0bdeae30b77efa667379427581784f1707/eth_abi/base.py#L15-L77 | def parse_type_str(expected_base=None, with_arrlist=False):
"""
Used by BaseCoder subclasses as a convenience for implementing the
``from_type_str`` method required by ``ABIRegistry``. Useful if normalizing
then parsing a type string with an (optional) expected base is required in
that method.
... | [
"def",
"parse_type_str",
"(",
"expected_base",
"=",
"None",
",",
"with_arrlist",
"=",
"False",
")",
":",
"def",
"decorator",
"(",
"old_from_type_str",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"old_from_type_str",
")",
"def",
"new_from_type_str",
"(",
"cl... | Used by BaseCoder subclasses as a convenience for implementing the
``from_type_str`` method required by ``ABIRegistry``. Useful if normalizing
then parsing a type string with an (optional) expected base is required in
that method. | [
"Used",
"by",
"BaseCoder",
"subclasses",
"as",
"a",
"convenience",
"for",
"implementing",
"the",
"from_type_str",
"method",
"required",
"by",
"ABIRegistry",
".",
"Useful",
"if",
"normalizing",
"then",
"parsing",
"a",
"type",
"string",
"with",
"an",
"(",
"optiona... | python | train |
mitsei/dlkit | dlkit/services/learning.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/learning.py#L990-L998 | def get_objective_bank_form(self, *args, **kwargs):
"""Pass through to provider ObjectiveBankAdminSession.get_objective_bank_form_for_update"""
# Implemented from kitosid template for -
# osid.resource.BinAdminSession.get_bin_form_for_update_template
# This method might be a bit sketchy.... | [
"def",
"get_objective_bank_form",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Implemented from kitosid template for -",
"# osid.resource.BinAdminSession.get_bin_form_for_update_template",
"# This method might be a bit sketchy. Time will tell.",
"if",
"isins... | Pass through to provider ObjectiveBankAdminSession.get_objective_bank_form_for_update | [
"Pass",
"through",
"to",
"provider",
"ObjectiveBankAdminSession",
".",
"get_objective_bank_form_for_update"
] | python | train |
tanghaibao/goatools | goatools/obo_parser.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L601-L633 | def draw_lineage(self, recs, nodecolor="mediumseagreen",
edgecolor="lightslateblue", dpi=96,
lineage_img="GO_lineage.png", engine="pygraphviz",
gml=False, draw_parents=True, draw_children=True):
"""Draw GO DAG subplot."""
assert engine in Gr... | [
"def",
"draw_lineage",
"(",
"self",
",",
"recs",
",",
"nodecolor",
"=",
"\"mediumseagreen\"",
",",
"edgecolor",
"=",
"\"lightslateblue\"",
",",
"dpi",
"=",
"96",
",",
"lineage_img",
"=",
"\"GO_lineage.png\"",
",",
"engine",
"=",
"\"pygraphviz\"",
",",
"gml",
"... | Draw GO DAG subplot. | [
"Draw",
"GO",
"DAG",
"subplot",
"."
] | python | train |
IdentityPython/pyop | src/pyop/authz_state.py | https://github.com/IdentityPython/pyop/blob/7b1385964f079c39752fce5f2dbcf458b8a92e56/src/pyop/authz_state.py#L148-L171 | def exchange_code_for_token(self, authorization_code):
# type: (str) -> se_leg_op.access_token.AccessToken
"""
Exchanges an authorization code for an access token.
"""
if authorization_code not in self.authorization_codes:
raise InvalidAuthorizationCode('{} unknown'.f... | [
"def",
"exchange_code_for_token",
"(",
"self",
",",
"authorization_code",
")",
":",
"# type: (str) -> se_leg_op.access_token.AccessToken",
"if",
"authorization_code",
"not",
"in",
"self",
".",
"authorization_codes",
":",
"raise",
"InvalidAuthorizationCode",
"(",
"'{} unknown'... | Exchanges an authorization code for an access token. | [
"Exchanges",
"an",
"authorization",
"code",
"for",
"an",
"access",
"token",
"."
] | python | train |
blockstack/blockstack-core | blockstack/lib/subdomains.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L441-L448 | def close(self):
"""
Close the index
"""
with self.subdomain_db_lock:
self.subdomain_db.close()
self.subdomain_db = None
self.subdomain_db_path = None | [
"def",
"close",
"(",
"self",
")",
":",
"with",
"self",
".",
"subdomain_db_lock",
":",
"self",
".",
"subdomain_db",
".",
"close",
"(",
")",
"self",
".",
"subdomain_db",
"=",
"None",
"self",
".",
"subdomain_db_path",
"=",
"None"
] | Close the index | [
"Close",
"the",
"index"
] | python | train |
twilio/twilio-python | twilio/rest/ip_messaging/v2/service/channel/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/ip_messaging/v2/service/channel/__init__.py#L41-L75 | def create(self, friendly_name=values.unset, unique_name=values.unset,
attributes=values.unset, type=values.unset,
date_created=values.unset, date_updated=values.unset,
created_by=values.unset):
"""
Create a new ChannelInstance
:param unicode friendl... | [
"def",
"create",
"(",
"self",
",",
"friendly_name",
"=",
"values",
".",
"unset",
",",
"unique_name",
"=",
"values",
".",
"unset",
",",
"attributes",
"=",
"values",
".",
"unset",
",",
"type",
"=",
"values",
".",
"unset",
",",
"date_created",
"=",
"values"... | Create a new ChannelInstance
:param unicode friendly_name: A string to describe the new resource
:param unicode unique_name: An application-defined string that uniquely identifies the resource
:param unicode attributes: A valid JSON string that contains application-specific data
:param ... | [
"Create",
"a",
"new",
"ChannelInstance"
] | python | train |
JensRantil/rewind | rewind/server/main.py | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/main.py#L55-L62 | def generate(self):
"""Generate a new string and return it."""
key = self._propose_new_key()
while self.key_exists(key):
_logger.warning('Previous candidate was used.'
' Regenerating another...')
key = self._propose_new_key()
return key | [
"def",
"generate",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"_propose_new_key",
"(",
")",
"while",
"self",
".",
"key_exists",
"(",
"key",
")",
":",
"_logger",
".",
"warning",
"(",
"'Previous candidate was used.'",
"' Regenerating another...'",
")",
"key... | Generate a new string and return it. | [
"Generate",
"a",
"new",
"string",
"and",
"return",
"it",
"."
] | python | train |
frawau/aiolifx | aiolifx/aiolifx.py | https://github.com/frawau/aiolifx/blob/9bd8c5e6d291f4c79314989402f7e2c6476d5851/aiolifx/aiolifx.py#L843-L858 | def get_color(self,callb=None):
"""Convenience method to request the colour status from the device
This method will check whether the value has already been retrieved from the device,
if so, it will simply return it. If no, it will request the information from the device
and request tha... | [
"def",
"get_color",
"(",
"self",
",",
"callb",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"req_with_resp",
"(",
"LightGet",
",",
"LightState",
",",
"callb",
"=",
"callb",
")",
"return",
"self",
".",
"color"
] | Convenience method to request the colour status from the device
This method will check whether the value has already been retrieved from the device,
if so, it will simply return it. If no, it will request the information from the device
and request that callb be executed when a response is rece... | [
"Convenience",
"method",
"to",
"request",
"the",
"colour",
"status",
"from",
"the",
"device"
] | python | train |
rigetti/grove | grove/simon/utils.py | https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/simon/utils.py#L33-L44 | def bitwise_xor(bs0: str, bs1: str) -> str:
"""
A helper to calculate the bitwise XOR of two bit string
:param bs0: String of 0's and 1's representing a number in binary representations
:param bs1: String of 0's and 1's representing a number in binary representations
:return: String of 0's and 1's ... | [
"def",
"bitwise_xor",
"(",
"bs0",
":",
"str",
",",
"bs1",
":",
"str",
")",
"->",
"str",
":",
"if",
"len",
"(",
"bs0",
")",
"!=",
"len",
"(",
"bs1",
")",
":",
"raise",
"ValueError",
"(",
"\"Bit strings are not of equal length\"",
")",
"n_bits",
"=",
"le... | A helper to calculate the bitwise XOR of two bit string
:param bs0: String of 0's and 1's representing a number in binary representations
:param bs1: String of 0's and 1's representing a number in binary representations
:return: String of 0's and 1's representing the XOR between bs0 and bs1 | [
"A",
"helper",
"to",
"calculate",
"the",
"bitwise",
"XOR",
"of",
"two",
"bit",
"string"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.