repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
robinandeer/puzzle | puzzle/server/blueprints/public/views.py | gene_list | def gene_list(list_id=None):
"""Display or add a gene list."""
all_case_ids = [case.case_id for case in app.db.cases()]
if list_id:
genelist_obj = app.db.gene_list(list_id)
case_ids = [case.case_id for case in app.db.cases()
if case not in genelist_obj.cases]
if genelist_obj is None:
return abort(404, "gene list not found: {}".format(list_id))
if 'download' in request.args:
response = make_response('\n'.join(genelist_obj.gene_ids))
filename = secure_filename("{}.txt".format(genelist_obj.list_id))
header = "attachment; filename={}".format(filename)
response.headers['Content-Disposition'] = header
return response
if request.method == 'POST':
if list_id:
# link a case to the gene list
case_ids = request.form.getlist('case_id')
for case_id in case_ids:
case_obj = app.db.case(case_id)
if case_obj not in genelist_obj.cases:
genelist_obj.cases.append(case_obj)
app.db.save()
else:
# upload a new gene list
req_file = request.files['file']
new_listid = (request.form['list_id'] or
secure_filename(req_file.filename))
if app.db.gene_list(new_listid):
return abort(500, 'Please provide a unique list name')
if not req_file:
return abort(500, 'Please provide a file for upload')
gene_ids = [line for line in req_file.stream
if not line.startswith('#')]
genelist_obj = app.db.add_genelist(new_listid, gene_ids)
case_ids = all_case_ids
return render_template('gene_list.html', gene_list=genelist_obj,
case_ids=case_ids) | python | def gene_list(list_id=None):
"""Display or add a gene list."""
all_case_ids = [case.case_id for case in app.db.cases()]
if list_id:
genelist_obj = app.db.gene_list(list_id)
case_ids = [case.case_id for case in app.db.cases()
if case not in genelist_obj.cases]
if genelist_obj is None:
return abort(404, "gene list not found: {}".format(list_id))
if 'download' in request.args:
response = make_response('\n'.join(genelist_obj.gene_ids))
filename = secure_filename("{}.txt".format(genelist_obj.list_id))
header = "attachment; filename={}".format(filename)
response.headers['Content-Disposition'] = header
return response
if request.method == 'POST':
if list_id:
# link a case to the gene list
case_ids = request.form.getlist('case_id')
for case_id in case_ids:
case_obj = app.db.case(case_id)
if case_obj not in genelist_obj.cases:
genelist_obj.cases.append(case_obj)
app.db.save()
else:
# upload a new gene list
req_file = request.files['file']
new_listid = (request.form['list_id'] or
secure_filename(req_file.filename))
if app.db.gene_list(new_listid):
return abort(500, 'Please provide a unique list name')
if not req_file:
return abort(500, 'Please provide a file for upload')
gene_ids = [line for line in req_file.stream
if not line.startswith('#')]
genelist_obj = app.db.add_genelist(new_listid, gene_ids)
case_ids = all_case_ids
return render_template('gene_list.html', gene_list=genelist_obj,
case_ids=case_ids) | [
"def",
"gene_list",
"(",
"list_id",
"=",
"None",
")",
":",
"all_case_ids",
"=",
"[",
"case",
".",
"case_id",
"for",
"case",
"in",
"app",
".",
"db",
".",
"cases",
"(",
")",
"]",
"if",
"list_id",
":",
"genelist_obj",
"=",
"app",
".",
"db",
".",
"gene_list",
"(",
"list_id",
")",
"case_ids",
"=",
"[",
"case",
".",
"case_id",
"for",
"case",
"in",
"app",
".",
"db",
".",
"cases",
"(",
")",
"if",
"case",
"not",
"in",
"genelist_obj",
".",
"cases",
"]",
"if",
"genelist_obj",
"is",
"None",
":",
"return",
"abort",
"(",
"404",
",",
"\"gene list not found: {}\"",
".",
"format",
"(",
"list_id",
")",
")",
"if",
"'download'",
"in",
"request",
".",
"args",
":",
"response",
"=",
"make_response",
"(",
"'\\n'",
".",
"join",
"(",
"genelist_obj",
".",
"gene_ids",
")",
")",
"filename",
"=",
"secure_filename",
"(",
"\"{}.txt\"",
".",
"format",
"(",
"genelist_obj",
".",
"list_id",
")",
")",
"header",
"=",
"\"attachment; filename={}\"",
".",
"format",
"(",
"filename",
")",
"response",
".",
"headers",
"[",
"'Content-Disposition'",
"]",
"=",
"header",
"return",
"response",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"if",
"list_id",
":",
"# link a case to the gene list",
"case_ids",
"=",
"request",
".",
"form",
".",
"getlist",
"(",
"'case_id'",
")",
"for",
"case_id",
"in",
"case_ids",
":",
"case_obj",
"=",
"app",
".",
"db",
".",
"case",
"(",
"case_id",
")",
"if",
"case_obj",
"not",
"in",
"genelist_obj",
".",
"cases",
":",
"genelist_obj",
".",
"cases",
".",
"append",
"(",
"case_obj",
")",
"app",
".",
"db",
".",
"save",
"(",
")",
"else",
":",
"# upload a new gene list",
"req_file",
"=",
"request",
".",
"files",
"[",
"'file'",
"]",
"new_listid",
"=",
"(",
"request",
".",
"form",
"[",
"'list_id'",
"]",
"or",
"secure_filename",
"(",
"req_file",
".",
"filename",
")",
")",
"if",
"app",
".",
"db",
".",
"gene_list",
"(",
"new_listid",
")",
":",
"return",
"abort",
"(",
"500",
",",
"'Please provide a unique list name'",
")",
"if",
"not",
"req_file",
":",
"return",
"abort",
"(",
"500",
",",
"'Please provide a file for upload'",
")",
"gene_ids",
"=",
"[",
"line",
"for",
"line",
"in",
"req_file",
".",
"stream",
"if",
"not",
"line",
".",
"startswith",
"(",
"'#'",
")",
"]",
"genelist_obj",
"=",
"app",
".",
"db",
".",
"add_genelist",
"(",
"new_listid",
",",
"gene_ids",
")",
"case_ids",
"=",
"all_case_ids",
"return",
"render_template",
"(",
"'gene_list.html'",
",",
"gene_list",
"=",
"genelist_obj",
",",
"case_ids",
"=",
"case_ids",
")"
] | Display or add a gene list. | [
"Display",
"or",
"add",
"a",
"gene",
"list",
"."
] | 9476f05b416d3a5135d25492cb31411fdf831c58 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/server/blueprints/public/views.py#L79-L123 | train |
robinandeer/puzzle | puzzle/server/blueprints/public/views.py | delete_genelist | def delete_genelist(list_id, case_id=None):
"""Delete a whole gene list with links to cases or a link."""
if case_id:
# unlink a case from a gene list
case_obj = app.db.case(case_id)
app.db.remove_genelist(list_id, case_obj=case_obj)
return redirect(request.referrer)
else:
# remove the whole gene list
app.db.remove_genelist(list_id)
return redirect(url_for('.index')) | python | def delete_genelist(list_id, case_id=None):
"""Delete a whole gene list with links to cases or a link."""
if case_id:
# unlink a case from a gene list
case_obj = app.db.case(case_id)
app.db.remove_genelist(list_id, case_obj=case_obj)
return redirect(request.referrer)
else:
# remove the whole gene list
app.db.remove_genelist(list_id)
return redirect(url_for('.index')) | [
"def",
"delete_genelist",
"(",
"list_id",
",",
"case_id",
"=",
"None",
")",
":",
"if",
"case_id",
":",
"# unlink a case from a gene list",
"case_obj",
"=",
"app",
".",
"db",
".",
"case",
"(",
"case_id",
")",
"app",
".",
"db",
".",
"remove_genelist",
"(",
"list_id",
",",
"case_obj",
"=",
"case_obj",
")",
"return",
"redirect",
"(",
"request",
".",
"referrer",
")",
"else",
":",
"# remove the whole gene list",
"app",
".",
"db",
".",
"remove_genelist",
"(",
"list_id",
")",
"return",
"redirect",
"(",
"url_for",
"(",
"'.index'",
")",
")"
] | Delete a whole gene list with links to cases or a link. | [
"Delete",
"a",
"whole",
"gene",
"list",
"with",
"links",
"to",
"cases",
"or",
"a",
"link",
"."
] | 9476f05b416d3a5135d25492cb31411fdf831c58 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/server/blueprints/public/views.py#L128-L138 | train |
robinandeer/puzzle | puzzle/server/blueprints/public/views.py | resources | def resources():
"""Upload a new resource for an individual."""
ind_id = request.form['ind_id']
upload_dir = os.path.abspath(app.config['UPLOAD_DIR'])
req_file = request.files['file']
filename = secure_filename(req_file.filename)
file_path = os.path.join(upload_dir, filename)
name = request.form['name'] or filename
req_file.save(file_path)
ind_obj = app.db.individual(ind_id)
app.db.add_resource(name, file_path, ind_obj)
return redirect(request.referrer) | python | def resources():
"""Upload a new resource for an individual."""
ind_id = request.form['ind_id']
upload_dir = os.path.abspath(app.config['UPLOAD_DIR'])
req_file = request.files['file']
filename = secure_filename(req_file.filename)
file_path = os.path.join(upload_dir, filename)
name = request.form['name'] or filename
req_file.save(file_path)
ind_obj = app.db.individual(ind_id)
app.db.add_resource(name, file_path, ind_obj)
return redirect(request.referrer) | [
"def",
"resources",
"(",
")",
":",
"ind_id",
"=",
"request",
".",
"form",
"[",
"'ind_id'",
"]",
"upload_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"app",
".",
"config",
"[",
"'UPLOAD_DIR'",
"]",
")",
"req_file",
"=",
"request",
".",
"files",
"[",
"'file'",
"]",
"filename",
"=",
"secure_filename",
"(",
"req_file",
".",
"filename",
")",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"upload_dir",
",",
"filename",
")",
"name",
"=",
"request",
".",
"form",
"[",
"'name'",
"]",
"or",
"filename",
"req_file",
".",
"save",
"(",
"file_path",
")",
"ind_obj",
"=",
"app",
".",
"db",
".",
"individual",
"(",
"ind_id",
")",
"app",
".",
"db",
".",
"add_resource",
"(",
"name",
",",
"file_path",
",",
"ind_obj",
")",
"return",
"redirect",
"(",
"request",
".",
"referrer",
")"
] | Upload a new resource for an individual. | [
"Upload",
"a",
"new",
"resource",
"for",
"an",
"individual",
"."
] | 9476f05b416d3a5135d25492cb31411fdf831c58 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/server/blueprints/public/views.py#L142-L155 | train |
robinandeer/puzzle | puzzle/server/blueprints/public/views.py | resource | def resource(resource_id):
"""Show a resource."""
resource_obj = app.db.resource(resource_id)
if 'raw' in request.args:
return send_from_directory(os.path.dirname(resource_obj.path),
os.path.basename(resource_obj.path))
return render_template('resource.html', resource=resource_obj) | python | def resource(resource_id):
"""Show a resource."""
resource_obj = app.db.resource(resource_id)
if 'raw' in request.args:
return send_from_directory(os.path.dirname(resource_obj.path),
os.path.basename(resource_obj.path))
return render_template('resource.html', resource=resource_obj) | [
"def",
"resource",
"(",
"resource_id",
")",
":",
"resource_obj",
"=",
"app",
".",
"db",
".",
"resource",
"(",
"resource_id",
")",
"if",
"'raw'",
"in",
"request",
".",
"args",
":",
"return",
"send_from_directory",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"resource_obj",
".",
"path",
")",
",",
"os",
".",
"path",
".",
"basename",
"(",
"resource_obj",
".",
"path",
")",
")",
"return",
"render_template",
"(",
"'resource.html'",
",",
"resource",
"=",
"resource_obj",
")"
] | Show a resource. | [
"Show",
"a",
"resource",
"."
] | 9476f05b416d3a5135d25492cb31411fdf831c58 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/server/blueprints/public/views.py#L159-L167 | train |
robinandeer/puzzle | puzzle/server/blueprints/public/views.py | comments | def comments(case_id):
"""Upload a new comment."""
text = request.form['text']
variant_id = request.form.get('variant_id')
username = request.form.get('username')
case_obj = app.db.case(case_id)
app.db.add_comment(case_obj, text, variant_id=variant_id, username=username)
return redirect(request.referrer) | python | def comments(case_id):
"""Upload a new comment."""
text = request.form['text']
variant_id = request.form.get('variant_id')
username = request.form.get('username')
case_obj = app.db.case(case_id)
app.db.add_comment(case_obj, text, variant_id=variant_id, username=username)
return redirect(request.referrer) | [
"def",
"comments",
"(",
"case_id",
")",
":",
"text",
"=",
"request",
".",
"form",
"[",
"'text'",
"]",
"variant_id",
"=",
"request",
".",
"form",
".",
"get",
"(",
"'variant_id'",
")",
"username",
"=",
"request",
".",
"form",
".",
"get",
"(",
"'username'",
")",
"case_obj",
"=",
"app",
".",
"db",
".",
"case",
"(",
"case_id",
")",
"app",
".",
"db",
".",
"add_comment",
"(",
"case_obj",
",",
"text",
",",
"variant_id",
"=",
"variant_id",
",",
"username",
"=",
"username",
")",
"return",
"redirect",
"(",
"request",
".",
"referrer",
")"
] | Upload a new comment. | [
"Upload",
"a",
"new",
"comment",
"."
] | 9476f05b416d3a5135d25492cb31411fdf831c58 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/server/blueprints/public/views.py#L184-L191 | train |
robinandeer/puzzle | puzzle/server/blueprints/public/views.py | individual | def individual(ind_id):
"""Show details for a specific individual."""
individual_obj = app.db.individual(ind_id)
return render_template('individual.html', individual=individual_obj) | python | def individual(ind_id):
"""Show details for a specific individual."""
individual_obj = app.db.individual(ind_id)
return render_template('individual.html', individual=individual_obj) | [
"def",
"individual",
"(",
"ind_id",
")",
":",
"individual_obj",
"=",
"app",
".",
"db",
".",
"individual",
"(",
"ind_id",
")",
"return",
"render_template",
"(",
"'individual.html'",
",",
"individual",
"=",
"individual_obj",
")"
] | Show details for a specific individual. | [
"Show",
"details",
"for",
"a",
"specific",
"individual",
"."
] | 9476f05b416d3a5135d25492cb31411fdf831c58 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/server/blueprints/public/views.py#L209-L212 | train |
robinandeer/puzzle | puzzle/server/blueprints/public/views.py | synopsis | def synopsis(case_id):
"""Update the case synopsis."""
text = request.form['text']
case_obj = app.db.case(case_id)
app.db.update_synopsis(case_obj, text)
return redirect(request.referrer) | python | def synopsis(case_id):
"""Update the case synopsis."""
text = request.form['text']
case_obj = app.db.case(case_id)
app.db.update_synopsis(case_obj, text)
return redirect(request.referrer) | [
"def",
"synopsis",
"(",
"case_id",
")",
":",
"text",
"=",
"request",
".",
"form",
"[",
"'text'",
"]",
"case_obj",
"=",
"app",
".",
"db",
".",
"case",
"(",
"case_id",
")",
"app",
".",
"db",
".",
"update_synopsis",
"(",
"case_obj",
",",
"text",
")",
"return",
"redirect",
"(",
"request",
".",
"referrer",
")"
] | Update the case synopsis. | [
"Update",
"the",
"case",
"synopsis",
"."
] | 9476f05b416d3a5135d25492cb31411fdf831c58 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/server/blueprints/public/views.py#L216-L221 | train |
robinandeer/puzzle | puzzle/server/blueprints/public/views.py | add_case | def add_case():
"""Make a new case out of a list of individuals."""
ind_ids = request.form.getlist('ind_id')
case_id = request.form['case_id']
source = request.form['source']
variant_type = request.form['type']
if len(ind_ids) == 0:
return abort(400, "must add at least one member of case")
# only GEMINI supported
new_case = Case(case_id=case_id, name=case_id, variant_source=source,
variant_type=variant_type, variant_mode='gemini')
# Add individuals to the correct case
for ind_id in ind_ids:
ind_obj = app.db.individual(ind_id)
new_case.individuals.append(ind_obj)
app.db.session.add(new_case)
app.db.save()
return redirect(url_for('.case', case_id=new_case.name)) | python | def add_case():
"""Make a new case out of a list of individuals."""
ind_ids = request.form.getlist('ind_id')
case_id = request.form['case_id']
source = request.form['source']
variant_type = request.form['type']
if len(ind_ids) == 0:
return abort(400, "must add at least one member of case")
# only GEMINI supported
new_case = Case(case_id=case_id, name=case_id, variant_source=source,
variant_type=variant_type, variant_mode='gemini')
# Add individuals to the correct case
for ind_id in ind_ids:
ind_obj = app.db.individual(ind_id)
new_case.individuals.append(ind_obj)
app.db.session.add(new_case)
app.db.save()
return redirect(url_for('.case', case_id=new_case.name)) | [
"def",
"add_case",
"(",
")",
":",
"ind_ids",
"=",
"request",
".",
"form",
".",
"getlist",
"(",
"'ind_id'",
")",
"case_id",
"=",
"request",
".",
"form",
"[",
"'case_id'",
"]",
"source",
"=",
"request",
".",
"form",
"[",
"'source'",
"]",
"variant_type",
"=",
"request",
".",
"form",
"[",
"'type'",
"]",
"if",
"len",
"(",
"ind_ids",
")",
"==",
"0",
":",
"return",
"abort",
"(",
"400",
",",
"\"must add at least one member of case\"",
")",
"# only GEMINI supported",
"new_case",
"=",
"Case",
"(",
"case_id",
"=",
"case_id",
",",
"name",
"=",
"case_id",
",",
"variant_source",
"=",
"source",
",",
"variant_type",
"=",
"variant_type",
",",
"variant_mode",
"=",
"'gemini'",
")",
"# Add individuals to the correct case",
"for",
"ind_id",
"in",
"ind_ids",
":",
"ind_obj",
"=",
"app",
".",
"db",
".",
"individual",
"(",
"ind_id",
")",
"new_case",
".",
"individuals",
".",
"append",
"(",
"ind_obj",
")",
"app",
".",
"db",
".",
"session",
".",
"add",
"(",
"new_case",
")",
"app",
".",
"db",
".",
"save",
"(",
")",
"return",
"redirect",
"(",
"url_for",
"(",
"'.case'",
",",
"case_id",
"=",
"new_case",
".",
"name",
")",
")"
] | Make a new case out of a list of individuals. | [
"Make",
"a",
"new",
"case",
"out",
"of",
"a",
"list",
"of",
"individuals",
"."
] | 9476f05b416d3a5135d25492cb31411fdf831c58 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/server/blueprints/public/views.py#L225-L247 | train |
eleme/meepo | meepo/sub/dummy.py | print_sub | def print_sub(tables):
"""Dummy print sub.
:param tables: print events of tables.
"""
logger = logging.getLogger("meepo.sub.print_sub")
logger.info("print_sub tables: %s" % ", ".join(tables))
if not isinstance(tables, (list, set)):
raise ValueError("tables should be list or set")
events = ("%s_%s" % (tb, action) for tb, action in
itertools.product(*[tables, ["write", "update", "delete"]]))
for event in events:
signal(event).connect(
lambda pk: logger.info("%s -> %s" % event, pk), weak=False) | python | def print_sub(tables):
"""Dummy print sub.
:param tables: print events of tables.
"""
logger = logging.getLogger("meepo.sub.print_sub")
logger.info("print_sub tables: %s" % ", ".join(tables))
if not isinstance(tables, (list, set)):
raise ValueError("tables should be list or set")
events = ("%s_%s" % (tb, action) for tb, action in
itertools.product(*[tables, ["write", "update", "delete"]]))
for event in events:
signal(event).connect(
lambda pk: logger.info("%s -> %s" % event, pk), weak=False) | [
"def",
"print_sub",
"(",
"tables",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"\"meepo.sub.print_sub\"",
")",
"logger",
".",
"info",
"(",
"\"print_sub tables: %s\"",
"%",
"\", \"",
".",
"join",
"(",
"tables",
")",
")",
"if",
"not",
"isinstance",
"(",
"tables",
",",
"(",
"list",
",",
"set",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"tables should be list or set\"",
")",
"events",
"=",
"(",
"\"%s_%s\"",
"%",
"(",
"tb",
",",
"action",
")",
"for",
"tb",
",",
"action",
"in",
"itertools",
".",
"product",
"(",
"*",
"[",
"tables",
",",
"[",
"\"write\"",
",",
"\"update\"",
",",
"\"delete\"",
"]",
"]",
")",
")",
"for",
"event",
"in",
"events",
":",
"signal",
"(",
"event",
")",
".",
"connect",
"(",
"lambda",
"pk",
":",
"logger",
".",
"info",
"(",
"\"%s -> %s\"",
"%",
"event",
",",
"pk",
")",
",",
"weak",
"=",
"False",
")"
] | Dummy print sub.
:param tables: print events of tables. | [
"Dummy",
"print",
"sub",
"."
] | 8212f0fe9b1d44be0c5de72d221a31c1d24bfe7a | https://github.com/eleme/meepo/blob/8212f0fe9b1d44be0c5de72d221a31c1d24bfe7a/meepo/sub/dummy.py#L11-L26 | train |
okeuday/erlang_py | erlang.py | binary_to_term | def binary_to_term(data):
"""
Decode Erlang terms within binary data into Python types
"""
if not isinstance(data, bytes):
raise ParseException('not bytes input')
size = len(data)
if size <= 1:
raise ParseException('null input')
if b_ord(data[0]) != _TAG_VERSION:
raise ParseException('invalid version')
try:
i, term = _binary_to_term(1, data)
if i != size:
raise ParseException('unparsed data')
return term
except struct.error:
raise ParseException('missing data')
except IndexError:
raise ParseException('missing data') | python | def binary_to_term(data):
"""
Decode Erlang terms within binary data into Python types
"""
if not isinstance(data, bytes):
raise ParseException('not bytes input')
size = len(data)
if size <= 1:
raise ParseException('null input')
if b_ord(data[0]) != _TAG_VERSION:
raise ParseException('invalid version')
try:
i, term = _binary_to_term(1, data)
if i != size:
raise ParseException('unparsed data')
return term
except struct.error:
raise ParseException('missing data')
except IndexError:
raise ParseException('missing data') | [
"def",
"binary_to_term",
"(",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"raise",
"ParseException",
"(",
"'not bytes input'",
")",
"size",
"=",
"len",
"(",
"data",
")",
"if",
"size",
"<=",
"1",
":",
"raise",
"ParseException",
"(",
"'null input'",
")",
"if",
"b_ord",
"(",
"data",
"[",
"0",
"]",
")",
"!=",
"_TAG_VERSION",
":",
"raise",
"ParseException",
"(",
"'invalid version'",
")",
"try",
":",
"i",
",",
"term",
"=",
"_binary_to_term",
"(",
"1",
",",
"data",
")",
"if",
"i",
"!=",
"size",
":",
"raise",
"ParseException",
"(",
"'unparsed data'",
")",
"return",
"term",
"except",
"struct",
".",
"error",
":",
"raise",
"ParseException",
"(",
"'missing data'",
")",
"except",
"IndexError",
":",
"raise",
"ParseException",
"(",
"'missing data'",
")"
] | Decode Erlang terms within binary data into Python types | [
"Decode",
"Erlang",
"terms",
"within",
"binary",
"data",
"into",
"Python",
"types"
] | 81b7c2ace66b6bdee23602a6802efff541223fa3 | https://github.com/okeuday/erlang_py/blob/81b7c2ace66b6bdee23602a6802efff541223fa3/erlang.py#L440-L459 | train |
okeuday/erlang_py | erlang.py | term_to_binary | def term_to_binary(term, compressed=False):
"""
Encode Python types into Erlang terms in binary data
"""
data_uncompressed = _term_to_binary(term)
if compressed is False:
return b_chr(_TAG_VERSION) + data_uncompressed
else:
if compressed is True:
compressed = 6
if compressed < 0 or compressed > 9:
raise InputException('compressed in [0..9]')
data_compressed = zlib.compress(data_uncompressed, compressed)
size_uncompressed = len(data_uncompressed)
if size_uncompressed > 4294967295:
raise OutputException('uint32 overflow')
return (
b_chr(_TAG_VERSION) + b_chr(_TAG_COMPRESSED_ZLIB) +
struct.pack(b'>I', size_uncompressed) + data_compressed
) | python | def term_to_binary(term, compressed=False):
"""
Encode Python types into Erlang terms in binary data
"""
data_uncompressed = _term_to_binary(term)
if compressed is False:
return b_chr(_TAG_VERSION) + data_uncompressed
else:
if compressed is True:
compressed = 6
if compressed < 0 or compressed > 9:
raise InputException('compressed in [0..9]')
data_compressed = zlib.compress(data_uncompressed, compressed)
size_uncompressed = len(data_uncompressed)
if size_uncompressed > 4294967295:
raise OutputException('uint32 overflow')
return (
b_chr(_TAG_VERSION) + b_chr(_TAG_COMPRESSED_ZLIB) +
struct.pack(b'>I', size_uncompressed) + data_compressed
) | [
"def",
"term_to_binary",
"(",
"term",
",",
"compressed",
"=",
"False",
")",
":",
"data_uncompressed",
"=",
"_term_to_binary",
"(",
"term",
")",
"if",
"compressed",
"is",
"False",
":",
"return",
"b_chr",
"(",
"_TAG_VERSION",
")",
"+",
"data_uncompressed",
"else",
":",
"if",
"compressed",
"is",
"True",
":",
"compressed",
"=",
"6",
"if",
"compressed",
"<",
"0",
"or",
"compressed",
">",
"9",
":",
"raise",
"InputException",
"(",
"'compressed in [0..9]'",
")",
"data_compressed",
"=",
"zlib",
".",
"compress",
"(",
"data_uncompressed",
",",
"compressed",
")",
"size_uncompressed",
"=",
"len",
"(",
"data_uncompressed",
")",
"if",
"size_uncompressed",
">",
"4294967295",
":",
"raise",
"OutputException",
"(",
"'uint32 overflow'",
")",
"return",
"(",
"b_chr",
"(",
"_TAG_VERSION",
")",
"+",
"b_chr",
"(",
"_TAG_COMPRESSED_ZLIB",
")",
"+",
"struct",
".",
"pack",
"(",
"b'>I'",
",",
"size_uncompressed",
")",
"+",
"data_compressed",
")"
] | Encode Python types into Erlang terms in binary data | [
"Encode",
"Python",
"types",
"into",
"Erlang",
"terms",
"in",
"binary",
"data"
] | 81b7c2ace66b6bdee23602a6802efff541223fa3 | https://github.com/okeuday/erlang_py/blob/81b7c2ace66b6bdee23602a6802efff541223fa3/erlang.py#L461-L480 | train |
TiagoBras/audio-clip-extractor | audioclipextractor/parser.py | SpecsParser._parseLine | def _parseLine(cls, line):
"""Parsers a single line of text and returns an AudioClipSpec
Line format:
<number> <number> [<text>]
Returns: list(AudioClipSpec) or None
"""
r = cls._PROG.match(line)
if not r:
raise ValueError("Error: parsing '%s'. Correct: \"<number> <number> [<text>]\"" % line)
d = r.groupdict()
if len(d['begin']) == 0 or len(d['end']) == 0:
raise ValueError("Error: parsing '%s'. Correct: \"<number> <number> [<text>]\"" % line)
return AudioClipSpec(d['begin'], d['end'], d['text'].strip()) | python | def _parseLine(cls, line):
"""Parsers a single line of text and returns an AudioClipSpec
Line format:
<number> <number> [<text>]
Returns: list(AudioClipSpec) or None
"""
r = cls._PROG.match(line)
if not r:
raise ValueError("Error: parsing '%s'. Correct: \"<number> <number> [<text>]\"" % line)
d = r.groupdict()
if len(d['begin']) == 0 or len(d['end']) == 0:
raise ValueError("Error: parsing '%s'. Correct: \"<number> <number> [<text>]\"" % line)
return AudioClipSpec(d['begin'], d['end'], d['text'].strip()) | [
"def",
"_parseLine",
"(",
"cls",
",",
"line",
")",
":",
"r",
"=",
"cls",
".",
"_PROG",
".",
"match",
"(",
"line",
")",
"if",
"not",
"r",
":",
"raise",
"ValueError",
"(",
"\"Error: parsing '%s'. Correct: \\\"<number> <number> [<text>]\\\"\"",
"%",
"line",
")",
"d",
"=",
"r",
".",
"groupdict",
"(",
")",
"if",
"len",
"(",
"d",
"[",
"'begin'",
"]",
")",
"==",
"0",
"or",
"len",
"(",
"d",
"[",
"'end'",
"]",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Error: parsing '%s'. Correct: \\\"<number> <number> [<text>]\\\"\"",
"%",
"line",
")",
"return",
"AudioClipSpec",
"(",
"d",
"[",
"'begin'",
"]",
",",
"d",
"[",
"'end'",
"]",
",",
"d",
"[",
"'text'",
"]",
".",
"strip",
"(",
")",
")"
] | Parsers a single line of text and returns an AudioClipSpec
Line format:
<number> <number> [<text>]
Returns: list(AudioClipSpec) or None | [
"Parsers",
"a",
"single",
"line",
"of",
"text",
"and",
"returns",
"an",
"AudioClipSpec"
] | b0dd90266656dcbf7e663b3e174dce4d09e74c32 | https://github.com/TiagoBras/audio-clip-extractor/blob/b0dd90266656dcbf7e663b3e174dce4d09e74c32/audioclipextractor/parser.py#L118-L136 | train |
Gawen/pytun | pytun.py | Tunnel.mode_name | def mode_name(self):
""" Returns the tunnel mode's name, for printing purpose. """
for name, id in self.MODES.iteritems():
if id == self.mode:
return name | python | def mode_name(self):
""" Returns the tunnel mode's name, for printing purpose. """
for name, id in self.MODES.iteritems():
if id == self.mode:
return name | [
"def",
"mode_name",
"(",
"self",
")",
":",
"for",
"name",
",",
"id",
"in",
"self",
".",
"MODES",
".",
"iteritems",
"(",
")",
":",
"if",
"id",
"==",
"self",
".",
"mode",
":",
"return",
"name"
] | Returns the tunnel mode's name, for printing purpose. | [
"Returns",
"the",
"tunnel",
"mode",
"s",
"name",
"for",
"printing",
"purpose",
"."
] | a1e1f86a5e2b5ed256e3b87dcdd4f6aedc6cde6d | https://github.com/Gawen/pytun/blob/a1e1f86a5e2b5ed256e3b87dcdd4f6aedc6cde6d/pytun.py#L106-L111 | train |
Gawen/pytun | pytun.py | Tunnel.open | def open(self):
""" Create the tunnel.
If the tunnel is already opened, the function will
raised an AlreadyOpened exception.
"""
if self.fd is not None:
raise self.AlreadyOpened()
logger.debug("Opening %s..." % (TUN_KO_PATH, ))
self.fd = os.open(TUN_KO_PATH, os.O_RDWR)
logger.debug("Opening %s tunnel '%s'..." % (self.mode_name.upper(), self.pattern, ))
try:
ret = fcntl.ioctl(self.fd, self.TUNSETIFF, struct.pack("16sH", self.pattern, self.mode | self.no_pi))
except IOError, e:
if e.errno == 1:
logger.error("Cannot open a %s tunnel because the operation is not permitted." % (self.mode_name.upper(), ))
raise self.NotPermitted()
raise
self.name = ret[:16].strip("\x00")
logger.info("Tunnel '%s' opened." % (self.name, )) | python | def open(self):
""" Create the tunnel.
If the tunnel is already opened, the function will
raised an AlreadyOpened exception.
"""
if self.fd is not None:
raise self.AlreadyOpened()
logger.debug("Opening %s..." % (TUN_KO_PATH, ))
self.fd = os.open(TUN_KO_PATH, os.O_RDWR)
logger.debug("Opening %s tunnel '%s'..." % (self.mode_name.upper(), self.pattern, ))
try:
ret = fcntl.ioctl(self.fd, self.TUNSETIFF, struct.pack("16sH", self.pattern, self.mode | self.no_pi))
except IOError, e:
if e.errno == 1:
logger.error("Cannot open a %s tunnel because the operation is not permitted." % (self.mode_name.upper(), ))
raise self.NotPermitted()
raise
self.name = ret[:16].strip("\x00")
logger.info("Tunnel '%s' opened." % (self.name, )) | [
"def",
"open",
"(",
"self",
")",
":",
"if",
"self",
".",
"fd",
"is",
"not",
"None",
":",
"raise",
"self",
".",
"AlreadyOpened",
"(",
")",
"logger",
".",
"debug",
"(",
"\"Opening %s...\"",
"%",
"(",
"TUN_KO_PATH",
",",
")",
")",
"self",
".",
"fd",
"=",
"os",
".",
"open",
"(",
"TUN_KO_PATH",
",",
"os",
".",
"O_RDWR",
")",
"logger",
".",
"debug",
"(",
"\"Opening %s tunnel '%s'...\"",
"%",
"(",
"self",
".",
"mode_name",
".",
"upper",
"(",
")",
",",
"self",
".",
"pattern",
",",
")",
")",
"try",
":",
"ret",
"=",
"fcntl",
".",
"ioctl",
"(",
"self",
".",
"fd",
",",
"self",
".",
"TUNSETIFF",
",",
"struct",
".",
"pack",
"(",
"\"16sH\"",
",",
"self",
".",
"pattern",
",",
"self",
".",
"mode",
"|",
"self",
".",
"no_pi",
")",
")",
"except",
"IOError",
",",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"1",
":",
"logger",
".",
"error",
"(",
"\"Cannot open a %s tunnel because the operation is not permitted.\"",
"%",
"(",
"self",
".",
"mode_name",
".",
"upper",
"(",
")",
",",
")",
")",
"raise",
"self",
".",
"NotPermitted",
"(",
")",
"raise",
"self",
".",
"name",
"=",
"ret",
"[",
":",
"16",
"]",
".",
"strip",
"(",
"\"\\x00\"",
")",
"logger",
".",
"info",
"(",
"\"Tunnel '%s' opened.\"",
"%",
"(",
"self",
".",
"name",
",",
")",
")"
] | Create the tunnel.
If the tunnel is already opened, the function will
raised an AlreadyOpened exception. | [
"Create",
"the",
"tunnel",
".",
"If",
"the",
"tunnel",
"is",
"already",
"opened",
"the",
"function",
"will",
"raised",
"an",
"AlreadyOpened",
"exception",
"."
] | a1e1f86a5e2b5ed256e3b87dcdd4f6aedc6cde6d | https://github.com/Gawen/pytun/blob/a1e1f86a5e2b5ed256e3b87dcdd4f6aedc6cde6d/pytun.py#L117-L142 | train |
Gawen/pytun | pytun.py | Tunnel.close | def close(self):
""" Close the tunnel.
If the tunnel is already closed or never opened,
do nothing.
"""
if self.fd is None:
return
logger.debug("Closing tunnel '%s'..." % (self.name or "", ))
# Close tun.ko file
os.close(self.fd)
self.fd = None
logger.info("Tunnel '%s' closed." % (self.name or "", )) | python | def close(self):
""" Close the tunnel.
If the tunnel is already closed or never opened,
do nothing.
"""
if self.fd is None:
return
logger.debug("Closing tunnel '%s'..." % (self.name or "", ))
# Close tun.ko file
os.close(self.fd)
self.fd = None
logger.info("Tunnel '%s' closed." % (self.name or "", )) | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"fd",
"is",
"None",
":",
"return",
"logger",
".",
"debug",
"(",
"\"Closing tunnel '%s'...\"",
"%",
"(",
"self",
".",
"name",
"or",
"\"\"",
",",
")",
")",
"# Close tun.ko file",
"os",
".",
"close",
"(",
"self",
".",
"fd",
")",
"self",
".",
"fd",
"=",
"None",
"logger",
".",
"info",
"(",
"\"Tunnel '%s' closed.\"",
"%",
"(",
"self",
".",
"name",
"or",
"\"\"",
",",
")",
")"
] | Close the tunnel.
If the tunnel is already closed or never opened,
do nothing. | [
"Close",
"the",
"tunnel",
".",
"If",
"the",
"tunnel",
"is",
"already",
"closed",
"or",
"never",
"opened",
"do",
"nothing",
"."
] | a1e1f86a5e2b5ed256e3b87dcdd4f6aedc6cde6d | https://github.com/Gawen/pytun/blob/a1e1f86a5e2b5ed256e3b87dcdd4f6aedc6cde6d/pytun.py#L144-L159 | train |
Gawen/pytun | pytun.py | Tunnel.recv | def recv(self, size = None):
""" Receive a buffer. The default size is 1500, the
classical MTU.
"""
size = size if size is not None else 1500
return os.read(self.fd, size) | python | def recv(self, size = None):
""" Receive a buffer. The default size is 1500, the
classical MTU.
"""
size = size if size is not None else 1500
return os.read(self.fd, size) | [
"def",
"recv",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"size",
"=",
"size",
"if",
"size",
"is",
"not",
"None",
"else",
"1500",
"return",
"os",
".",
"read",
"(",
"self",
".",
"fd",
",",
"size",
")"
] | Receive a buffer. The default size is 1500, the
classical MTU. | [
"Receive",
"a",
"buffer",
".",
"The",
"default",
"size",
"is",
"1500",
"the",
"classical",
"MTU",
"."
] | a1e1f86a5e2b5ed256e3b87dcdd4f6aedc6cde6d | https://github.com/Gawen/pytun/blob/a1e1f86a5e2b5ed256e3b87dcdd4f6aedc6cde6d/pytun.py#L165-L172 | train |
Shinichi-Nakagawa/pitchpx | pitchpx/mlbam.py | MlbAm.download | def download(self):
"""
MLBAM dataset download
"""
p = Pool()
p.map(self._download, self.days) | python | def download(self):
"""
MLBAM dataset download
"""
p = Pool()
p.map(self._download, self.days) | [
"def",
"download",
"(",
"self",
")",
":",
"p",
"=",
"Pool",
"(",
")",
"p",
".",
"map",
"(",
"self",
".",
"_download",
",",
"self",
".",
"days",
")"
] | MLBAM dataset download | [
"MLBAM",
"dataset",
"download"
] | 5747402a0b3416f5e910b479e100df858f0b6440 | https://github.com/Shinichi-Nakagawa/pitchpx/blob/5747402a0b3416f5e910b479e100df858f0b6440/pitchpx/mlbam.py#L49-L54 | train |
ldomic/lintools | lintools/analysis/salt_bridges.py | SaltBridges.count_by_type | def count_by_type(self):
"""Count how many times each individual salt bridge occured throughout the simulation.
Returns numpy array."""
saltbridges = defaultdict(int)
for contact in self.timeseries:
#count by residue name not by proteinring
pkey = (contact.ligandatomid,contact.ligandatomname, contact.resid,contact.resname,contact.segid)
saltbridges[pkey]+=1
dtype = [("ligand_atom_id",int),("ligand_atom_name","|U4"),("resid",int),("resname","|U4"),("segid","|U8"),("frequency",float) ]
out = np.empty((len(saltbridges),),dtype=dtype)
tsteps = float(len(self.timesteps))
for cursor,(key,count) in enumerate(saltbridges.iteritems()):
out[cursor] = key + (count / tsteps,)
return out.view(np.recarray) | python | def count_by_type(self):
"""Count how many times each individual salt bridge occured throughout the simulation.
Returns numpy array."""
saltbridges = defaultdict(int)
for contact in self.timeseries:
#count by residue name not by proteinring
pkey = (contact.ligandatomid,contact.ligandatomname, contact.resid,contact.resname,contact.segid)
saltbridges[pkey]+=1
dtype = [("ligand_atom_id",int),("ligand_atom_name","|U4"),("resid",int),("resname","|U4"),("segid","|U8"),("frequency",float) ]
out = np.empty((len(saltbridges),),dtype=dtype)
tsteps = float(len(self.timesteps))
for cursor,(key,count) in enumerate(saltbridges.iteritems()):
out[cursor] = key + (count / tsteps,)
return out.view(np.recarray) | [
"def",
"count_by_type",
"(",
"self",
")",
":",
"saltbridges",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"contact",
"in",
"self",
".",
"timeseries",
":",
"#count by residue name not by proteinring",
"pkey",
"=",
"(",
"contact",
".",
"ligandatomid",
",",
"contact",
".",
"ligandatomname",
",",
"contact",
".",
"resid",
",",
"contact",
".",
"resname",
",",
"contact",
".",
"segid",
")",
"saltbridges",
"[",
"pkey",
"]",
"+=",
"1",
"dtype",
"=",
"[",
"(",
"\"ligand_atom_id\"",
",",
"int",
")",
",",
"(",
"\"ligand_atom_name\"",
",",
"\"|U4\"",
")",
",",
"(",
"\"resid\"",
",",
"int",
")",
",",
"(",
"\"resname\"",
",",
"\"|U4\"",
")",
",",
"(",
"\"segid\"",
",",
"\"|U8\"",
")",
",",
"(",
"\"frequency\"",
",",
"float",
")",
"]",
"out",
"=",
"np",
".",
"empty",
"(",
"(",
"len",
"(",
"saltbridges",
")",
",",
")",
",",
"dtype",
"=",
"dtype",
")",
"tsteps",
"=",
"float",
"(",
"len",
"(",
"self",
".",
"timesteps",
")",
")",
"for",
"cursor",
",",
"(",
"key",
",",
"count",
")",
"in",
"enumerate",
"(",
"saltbridges",
".",
"iteritems",
"(",
")",
")",
":",
"out",
"[",
"cursor",
"]",
"=",
"key",
"+",
"(",
"count",
"/",
"tsteps",
",",
")",
"return",
"out",
".",
"view",
"(",
"np",
".",
"recarray",
")"
] | Count how many times each individual salt bridge occured throughout the simulation.
Returns numpy array. | [
"Count",
"how",
"many",
"times",
"each",
"individual",
"salt",
"bridge",
"occured",
"throughout",
"the",
"simulation",
".",
"Returns",
"numpy",
"array",
"."
] | d825a4a7b35f3f857d3b81b46c9aee72b0ec697a | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/analysis/salt_bridges.py#L143-L156 | train |
ldomic/lintools | lintools/analysis/salt_bridges.py | SaltBridges.count_by_time | def count_by_time(self):
"""Count how many salt bridges occured in each frame.
Returns numpy array."""
out = np.empty((len(self.timesteps),), dtype=[('time', float), ('count', int)])
for cursor,timestep in enumerate(self.timesteps):
out[cursor] = (timestep,len([x for x in self.timeseries if x.time==timestep]))
return out.view(np.recarray) | python | def count_by_time(self):
"""Count how many salt bridges occured in each frame.
Returns numpy array."""
out = np.empty((len(self.timesteps),), dtype=[('time', float), ('count', int)])
for cursor,timestep in enumerate(self.timesteps):
out[cursor] = (timestep,len([x for x in self.timeseries if x.time==timestep]))
return out.view(np.recarray) | [
"def",
"count_by_time",
"(",
"self",
")",
":",
"out",
"=",
"np",
".",
"empty",
"(",
"(",
"len",
"(",
"self",
".",
"timesteps",
")",
",",
")",
",",
"dtype",
"=",
"[",
"(",
"'time'",
",",
"float",
")",
",",
"(",
"'count'",
",",
"int",
")",
"]",
")",
"for",
"cursor",
",",
"timestep",
"in",
"enumerate",
"(",
"self",
".",
"timesteps",
")",
":",
"out",
"[",
"cursor",
"]",
"=",
"(",
"timestep",
",",
"len",
"(",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"timeseries",
"if",
"x",
".",
"time",
"==",
"timestep",
"]",
")",
")",
"return",
"out",
".",
"view",
"(",
"np",
".",
"recarray",
")"
] | Count how many salt bridges occured in each frame.
Returns numpy array. | [
"Count",
"how",
"many",
"salt",
"bridges",
"occured",
"in",
"each",
"frame",
".",
"Returns",
"numpy",
"array",
"."
] | d825a4a7b35f3f857d3b81b46c9aee72b0ec697a | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/analysis/salt_bridges.py#L158-L164 | train |
inveniosoftware-contrib/json-merger | json_merger/config.py | DictMergerOps.keep_longest | def keep_longest(head, update, down_path):
"""Keep longest field among `head` and `update`.
"""
if update is None:
return 'f'
if head is None:
return 's'
return 'f' if len(head) >= len(update) else 's' | python | def keep_longest(head, update, down_path):
"""Keep longest field among `head` and `update`.
"""
if update is None:
return 'f'
if head is None:
return 's'
return 'f' if len(head) >= len(update) else 's' | [
"def",
"keep_longest",
"(",
"head",
",",
"update",
",",
"down_path",
")",
":",
"if",
"update",
"is",
"None",
":",
"return",
"'f'",
"if",
"head",
"is",
"None",
":",
"return",
"'s'",
"return",
"'f'",
"if",
"len",
"(",
"head",
")",
">=",
"len",
"(",
"update",
")",
"else",
"'s'"
] | Keep longest field among `head` and `update`. | [
"Keep",
"longest",
"field",
"among",
"head",
"and",
"update",
"."
] | adc6d372da018427e1db7b92424d3471e01a4118 | https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/config.py#L40-L48 | train |
robinandeer/puzzle | puzzle/plugins/sql/mixins/actions/comment.py | CommentActions.comments | def comments(self, case_id=None, variant_id=None, username=None):
"""Return comments for a case or variant.
Args:
case_id (str): id for a related case
variant_id (Optional[str]): id for a related variant
"""
logger.debug("Looking for comments")
comment_objs = self.query(Comment)
if case_id:
comment_objs = comment_objs.filter_by(case_id=case_id)
if variant_id:
comment_objs = comment_objs.filter_by(variant_id=variant_id)
elif case_id:
comment_objs = comment_objs.filter_by(variant_id=None)
return comment_objs | python | def comments(self, case_id=None, variant_id=None, username=None):
"""Return comments for a case or variant.
Args:
case_id (str): id for a related case
variant_id (Optional[str]): id for a related variant
"""
logger.debug("Looking for comments")
comment_objs = self.query(Comment)
if case_id:
comment_objs = comment_objs.filter_by(case_id=case_id)
if variant_id:
comment_objs = comment_objs.filter_by(variant_id=variant_id)
elif case_id:
comment_objs = comment_objs.filter_by(variant_id=None)
return comment_objs | [
"def",
"comments",
"(",
"self",
",",
"case_id",
"=",
"None",
",",
"variant_id",
"=",
"None",
",",
"username",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"\"Looking for comments\"",
")",
"comment_objs",
"=",
"self",
".",
"query",
"(",
"Comment",
")",
"if",
"case_id",
":",
"comment_objs",
"=",
"comment_objs",
".",
"filter_by",
"(",
"case_id",
"=",
"case_id",
")",
"if",
"variant_id",
":",
"comment_objs",
"=",
"comment_objs",
".",
"filter_by",
"(",
"variant_id",
"=",
"variant_id",
")",
"elif",
"case_id",
":",
"comment_objs",
"=",
"comment_objs",
".",
"filter_by",
"(",
"variant_id",
"=",
"None",
")",
"return",
"comment_objs"
] | Return comments for a case or variant.
Args:
case_id (str): id for a related case
variant_id (Optional[str]): id for a related variant | [
"Return",
"comments",
"for",
"a",
"case",
"or",
"variant",
"."
] | 9476f05b416d3a5135d25492cb31411fdf831c58 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/sql/mixins/actions/comment.py#L10-L28 | train |
robinandeer/puzzle | puzzle/plugins/sql/mixins/actions/comment.py | CommentActions.add_comment | def add_comment(self, case_obj, text, variant_id=None, username=None):
"""Add a comment to a variant or a case"""
comment = Comment(
text=text,
username=username or 'Anonymous',
case=case_obj,
# md5 sum of chrom, pos, ref, alt
variant_id=variant_id
)
self.session.add(comment)
self.save()
return comment | python | def add_comment(self, case_obj, text, variant_id=None, username=None):
"""Add a comment to a variant or a case"""
comment = Comment(
text=text,
username=username or 'Anonymous',
case=case_obj,
# md5 sum of chrom, pos, ref, alt
variant_id=variant_id
)
self.session.add(comment)
self.save()
return comment | [
"def",
"add_comment",
"(",
"self",
",",
"case_obj",
",",
"text",
",",
"variant_id",
"=",
"None",
",",
"username",
"=",
"None",
")",
":",
"comment",
"=",
"Comment",
"(",
"text",
"=",
"text",
",",
"username",
"=",
"username",
"or",
"'Anonymous'",
",",
"case",
"=",
"case_obj",
",",
"# md5 sum of chrom, pos, ref, alt",
"variant_id",
"=",
"variant_id",
")",
"self",
".",
"session",
".",
"add",
"(",
"comment",
")",
"self",
".",
"save",
"(",
")",
"return",
"comment"
] | Add a comment to a variant or a case | [
"Add",
"a",
"comment",
"to",
"a",
"variant",
"or",
"a",
"case"
] | 9476f05b416d3a5135d25492cb31411fdf831c58 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/sql/mixins/actions/comment.py#L38-L50 | train |
robinandeer/puzzle | puzzle/plugins/vcf/mixins/variant_extras/consequences.py | ConsequenceExtras._add_consequences | def _add_consequences(self, variant_obj, raw_variant_line):
"""Add the consequences found for a variant
Args:
variant_obj (puzzle.models.Variant)
raw_variant_line (str): A raw vcf variant line
"""
consequences = []
for consequence in SO_TERMS:
if consequence in raw_variant_line:
consequences.append(consequence)
variant_obj.consequences = consequences | python | def _add_consequences(self, variant_obj, raw_variant_line):
"""Add the consequences found for a variant
Args:
variant_obj (puzzle.models.Variant)
raw_variant_line (str): A raw vcf variant line
"""
consequences = []
for consequence in SO_TERMS:
if consequence in raw_variant_line:
consequences.append(consequence)
variant_obj.consequences = consequences | [
"def",
"_add_consequences",
"(",
"self",
",",
"variant_obj",
",",
"raw_variant_line",
")",
":",
"consequences",
"=",
"[",
"]",
"for",
"consequence",
"in",
"SO_TERMS",
":",
"if",
"consequence",
"in",
"raw_variant_line",
":",
"consequences",
".",
"append",
"(",
"consequence",
")",
"variant_obj",
".",
"consequences",
"=",
"consequences"
] | Add the consequences found for a variant
Args:
variant_obj (puzzle.models.Variant)
raw_variant_line (str): A raw vcf variant line | [
"Add",
"the",
"consequences",
"found",
"for",
"a",
"variant"
] | 9476f05b416d3a5135d25492cb31411fdf831c58 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/plugins/vcf/mixins/variant_extras/consequences.py#L10-L22 | train |
ellethee/argparseinator | argparseinator/utils.py | collect_appendvars | def collect_appendvars(ap_, cls):
"""
colleziona elementi per le liste.
"""
for key, value in cls.__dict__.items():
if key.startswith('appendvars_'):
varname = key[11:]
if varname not in ap_.appendvars:
ap_.appendvars[varname] = []
if value not in ap_.appendvars[varname]:
if not isinstance(value, list):
value = [value]
ap_.appendvars[varname] += value | python | def collect_appendvars(ap_, cls):
"""
colleziona elementi per le liste.
"""
for key, value in cls.__dict__.items():
if key.startswith('appendvars_'):
varname = key[11:]
if varname not in ap_.appendvars:
ap_.appendvars[varname] = []
if value not in ap_.appendvars[varname]:
if not isinstance(value, list):
value = [value]
ap_.appendvars[varname] += value | [
"def",
"collect_appendvars",
"(",
"ap_",
",",
"cls",
")",
":",
"for",
"key",
",",
"value",
"in",
"cls",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"'appendvars_'",
")",
":",
"varname",
"=",
"key",
"[",
"11",
":",
"]",
"if",
"varname",
"not",
"in",
"ap_",
".",
"appendvars",
":",
"ap_",
".",
"appendvars",
"[",
"varname",
"]",
"=",
"[",
"]",
"if",
"value",
"not",
"in",
"ap_",
".",
"appendvars",
"[",
"varname",
"]",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value",
"=",
"[",
"value",
"]",
"ap_",
".",
"appendvars",
"[",
"varname",
"]",
"+=",
"value"
] | colleziona elementi per le liste. | [
"colleziona",
"elementi",
"per",
"le",
"liste",
"."
] | 05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e | https://github.com/ellethee/argparseinator/blob/05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e/argparseinator/utils.py#L88-L100 | train |
ellethee/argparseinator | argparseinator/utils.py | has_shared | def has_shared(arg, shared):
"""
Verifica se ci sono shared.
"""
try:
if isinstance(shared, list):
shared_arguments = shared
else:
shared_arguments = shared.__shared_arguments__
for idx, (args, kwargs) in enumerate(shared_arguments):
arg_name = kwargs.get(
'dest', args[-1].lstrip('-').replace('-', '_'))
if arg_name == arg:
return idx
idx = False
except (ValueError, AttributeError):
idx = False
return idx | python | def has_shared(arg, shared):
"""
Verifica se ci sono shared.
"""
try:
if isinstance(shared, list):
shared_arguments = shared
else:
shared_arguments = shared.__shared_arguments__
for idx, (args, kwargs) in enumerate(shared_arguments):
arg_name = kwargs.get(
'dest', args[-1].lstrip('-').replace('-', '_'))
if arg_name == arg:
return idx
idx = False
except (ValueError, AttributeError):
idx = False
return idx | [
"def",
"has_shared",
"(",
"arg",
",",
"shared",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"shared",
",",
"list",
")",
":",
"shared_arguments",
"=",
"shared",
"else",
":",
"shared_arguments",
"=",
"shared",
".",
"__shared_arguments__",
"for",
"idx",
",",
"(",
"args",
",",
"kwargs",
")",
"in",
"enumerate",
"(",
"shared_arguments",
")",
":",
"arg_name",
"=",
"kwargs",
".",
"get",
"(",
"'dest'",
",",
"args",
"[",
"-",
"1",
"]",
".",
"lstrip",
"(",
"'-'",
")",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
")",
"if",
"arg_name",
"==",
"arg",
":",
"return",
"idx",
"idx",
"=",
"False",
"except",
"(",
"ValueError",
",",
"AttributeError",
")",
":",
"idx",
"=",
"False",
"return",
"idx"
] | Verifica se ci sono shared. | [
"Verifica",
"se",
"ci",
"sono",
"shared",
"."
] | 05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e | https://github.com/ellethee/argparseinator/blob/05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e/argparseinator/utils.py#L136-L153 | train |
ellethee/argparseinator | argparseinator/utils.py | has_argument | def has_argument(arg, arguments):
"""
Verifica se ci sono argument con la classe.
"""
try:
if not isinstance(arguments, list):
arguments = arguments.__arguments__
for idx, (args, kwargs) in enumerate(arguments):
arg_name = kwargs.get(
'dest', args[-1].lstrip('-').replace('-', '_'))
if arg_name == arg:
return idx
idx = False
except (ValueError, AttributeError):
idx = False
return idx | python | def has_argument(arg, arguments):
"""
Verifica se ci sono argument con la classe.
"""
try:
if not isinstance(arguments, list):
arguments = arguments.__arguments__
for idx, (args, kwargs) in enumerate(arguments):
arg_name = kwargs.get(
'dest', args[-1].lstrip('-').replace('-', '_'))
if arg_name == arg:
return idx
idx = False
except (ValueError, AttributeError):
idx = False
return idx | [
"def",
"has_argument",
"(",
"arg",
",",
"arguments",
")",
":",
"try",
":",
"if",
"not",
"isinstance",
"(",
"arguments",
",",
"list",
")",
":",
"arguments",
"=",
"arguments",
".",
"__arguments__",
"for",
"idx",
",",
"(",
"args",
",",
"kwargs",
")",
"in",
"enumerate",
"(",
"arguments",
")",
":",
"arg_name",
"=",
"kwargs",
".",
"get",
"(",
"'dest'",
",",
"args",
"[",
"-",
"1",
"]",
".",
"lstrip",
"(",
"'-'",
")",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
")",
"if",
"arg_name",
"==",
"arg",
":",
"return",
"idx",
"idx",
"=",
"False",
"except",
"(",
"ValueError",
",",
"AttributeError",
")",
":",
"idx",
"=",
"False",
"return",
"idx"
] | Verifica se ci sono argument con la classe. | [
"Verifica",
"se",
"ci",
"sono",
"argument",
"con",
"la",
"classe",
"."
] | 05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e | https://github.com/ellethee/argparseinator/blob/05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e/argparseinator/utils.py#L156-L171 | train |
ellethee/argparseinator | argparseinator/utils.py | get_functarguments | def get_functarguments(func):
"""
Recupera gli argomenti dalla funzione stessa.
"""
argspec = inspect.getargspec(func)
if argspec.defaults is not None:
args = argspec.args[:-len(argspec.defaults)]
kwargs = dict(
zip(argspec.args[-len(argspec.defaults):], argspec.defaults))
else:
args = argspec.args
kwargs = {}
if args and args[0] == 'self':
args.pop(0)
func.__named__ = []
arguments = []
shared = get_shared(func)
for arg in args:
if has_shared(arg, shared) is not False:
continue
if has_argument(arg, func.__cls__) is not False:
continue
arguments.append(([arg], {}, ))
func.__named__.append(arg)
for key, val in kwargs.items():
if has_shared(key, shared) is not False:
continue
if has_argument(key, func.__cls__) is not False:
continue
if isinstance(val, dict):
flags = [val.pop('lflag', '--%s' % key)]
short = val.pop('flag', None)
dest = val.get('dest', key).replace('-', '_')
if short:
flags.insert(0, short)
else:
flags = ['--%s' % key]
val = dict(default=val)
dest = key.replace('-', '_')
func.__named__.append(dest)
arguments.append((flags, val, ))
return arguments | python | def get_functarguments(func):
"""
Recupera gli argomenti dalla funzione stessa.
"""
argspec = inspect.getargspec(func)
if argspec.defaults is not None:
args = argspec.args[:-len(argspec.defaults)]
kwargs = dict(
zip(argspec.args[-len(argspec.defaults):], argspec.defaults))
else:
args = argspec.args
kwargs = {}
if args and args[0] == 'self':
args.pop(0)
func.__named__ = []
arguments = []
shared = get_shared(func)
for arg in args:
if has_shared(arg, shared) is not False:
continue
if has_argument(arg, func.__cls__) is not False:
continue
arguments.append(([arg], {}, ))
func.__named__.append(arg)
for key, val in kwargs.items():
if has_shared(key, shared) is not False:
continue
if has_argument(key, func.__cls__) is not False:
continue
if isinstance(val, dict):
flags = [val.pop('lflag', '--%s' % key)]
short = val.pop('flag', None)
dest = val.get('dest', key).replace('-', '_')
if short:
flags.insert(0, short)
else:
flags = ['--%s' % key]
val = dict(default=val)
dest = key.replace('-', '_')
func.__named__.append(dest)
arguments.append((flags, val, ))
return arguments | [
"def",
"get_functarguments",
"(",
"func",
")",
":",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"if",
"argspec",
".",
"defaults",
"is",
"not",
"None",
":",
"args",
"=",
"argspec",
".",
"args",
"[",
":",
"-",
"len",
"(",
"argspec",
".",
"defaults",
")",
"]",
"kwargs",
"=",
"dict",
"(",
"zip",
"(",
"argspec",
".",
"args",
"[",
"-",
"len",
"(",
"argspec",
".",
"defaults",
")",
":",
"]",
",",
"argspec",
".",
"defaults",
")",
")",
"else",
":",
"args",
"=",
"argspec",
".",
"args",
"kwargs",
"=",
"{",
"}",
"if",
"args",
"and",
"args",
"[",
"0",
"]",
"==",
"'self'",
":",
"args",
".",
"pop",
"(",
"0",
")",
"func",
".",
"__named__",
"=",
"[",
"]",
"arguments",
"=",
"[",
"]",
"shared",
"=",
"get_shared",
"(",
"func",
")",
"for",
"arg",
"in",
"args",
":",
"if",
"has_shared",
"(",
"arg",
",",
"shared",
")",
"is",
"not",
"False",
":",
"continue",
"if",
"has_argument",
"(",
"arg",
",",
"func",
".",
"__cls__",
")",
"is",
"not",
"False",
":",
"continue",
"arguments",
".",
"append",
"(",
"(",
"[",
"arg",
"]",
",",
"{",
"}",
",",
")",
")",
"func",
".",
"__named__",
".",
"append",
"(",
"arg",
")",
"for",
"key",
",",
"val",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"has_shared",
"(",
"key",
",",
"shared",
")",
"is",
"not",
"False",
":",
"continue",
"if",
"has_argument",
"(",
"key",
",",
"func",
".",
"__cls__",
")",
"is",
"not",
"False",
":",
"continue",
"if",
"isinstance",
"(",
"val",
",",
"dict",
")",
":",
"flags",
"=",
"[",
"val",
".",
"pop",
"(",
"'lflag'",
",",
"'--%s'",
"%",
"key",
")",
"]",
"short",
"=",
"val",
".",
"pop",
"(",
"'flag'",
",",
"None",
")",
"dest",
"=",
"val",
".",
"get",
"(",
"'dest'",
",",
"key",
")",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"if",
"short",
":",
"flags",
".",
"insert",
"(",
"0",
",",
"short",
")",
"else",
":",
"flags",
"=",
"[",
"'--%s'",
"%",
"key",
"]",
"val",
"=",
"dict",
"(",
"default",
"=",
"val",
")",
"dest",
"=",
"key",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"func",
".",
"__named__",
".",
"append",
"(",
"dest",
")",
"arguments",
".",
"append",
"(",
"(",
"flags",
",",
"val",
",",
")",
")",
"return",
"arguments"
] | Recupera gli argomenti dalla funzione stessa. | [
"Recupera",
"gli",
"argomenti",
"dalla",
"funzione",
"stessa",
"."
] | 05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e | https://github.com/ellethee/argparseinator/blob/05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e/argparseinator/utils.py#L174-L215 | train |
ellethee/argparseinator | argparseinator/utils.py | get_parser | def get_parser(func, parent):
"""
Imposta il parser.
"""
parser = parent.add_parser(func.__cmd_name__, help=func.__doc__)
for args, kwargs in func.__arguments__:
parser.add_argument(*args, **kwargs)
return parser | python | def get_parser(func, parent):
"""
Imposta il parser.
"""
parser = parent.add_parser(func.__cmd_name__, help=func.__doc__)
for args, kwargs in func.__arguments__:
parser.add_argument(*args, **kwargs)
return parser | [
"def",
"get_parser",
"(",
"func",
",",
"parent",
")",
":",
"parser",
"=",
"parent",
".",
"add_parser",
"(",
"func",
".",
"__cmd_name__",
",",
"help",
"=",
"func",
".",
"__doc__",
")",
"for",
"args",
",",
"kwargs",
"in",
"func",
".",
"__arguments__",
":",
"parser",
".",
"add_argument",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"parser"
] | Imposta il parser. | [
"Imposta",
"il",
"parser",
"."
] | 05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e | https://github.com/ellethee/argparseinator/blob/05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e/argparseinator/utils.py#L218-L225 | train |
ellethee/argparseinator | argparseinator/utils.py | get_shared | def get_shared(func):
"""
return shared.
"""
shared = []
if not hasattr(func, '__cls__'):
return shared
if not hasattr(func.__cls__, '__shared_arguments__'):
return shared
if hasattr(func, '__no_share__'):
if func.__no_share__ is True:
return shared
else:
shared += [
s for s in func.__cls__.__shared_arguments__
if (s[0][-1].replace('--', '').replace('-', '_'))
not in func.__no_share__]
else:
shared = func.__cls__.__shared_arguments__
return shared | python | def get_shared(func):
"""
return shared.
"""
shared = []
if not hasattr(func, '__cls__'):
return shared
if not hasattr(func.__cls__, '__shared_arguments__'):
return shared
if hasattr(func, '__no_share__'):
if func.__no_share__ is True:
return shared
else:
shared += [
s for s in func.__cls__.__shared_arguments__
if (s[0][-1].replace('--', '').replace('-', '_'))
not in func.__no_share__]
else:
shared = func.__cls__.__shared_arguments__
return shared | [
"def",
"get_shared",
"(",
"func",
")",
":",
"shared",
"=",
"[",
"]",
"if",
"not",
"hasattr",
"(",
"func",
",",
"'__cls__'",
")",
":",
"return",
"shared",
"if",
"not",
"hasattr",
"(",
"func",
".",
"__cls__",
",",
"'__shared_arguments__'",
")",
":",
"return",
"shared",
"if",
"hasattr",
"(",
"func",
",",
"'__no_share__'",
")",
":",
"if",
"func",
".",
"__no_share__",
"is",
"True",
":",
"return",
"shared",
"else",
":",
"shared",
"+=",
"[",
"s",
"for",
"s",
"in",
"func",
".",
"__cls__",
".",
"__shared_arguments__",
"if",
"(",
"s",
"[",
"0",
"]",
"[",
"-",
"1",
"]",
".",
"replace",
"(",
"'--'",
",",
"''",
")",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
")",
"not",
"in",
"func",
".",
"__no_share__",
"]",
"else",
":",
"shared",
"=",
"func",
".",
"__cls__",
".",
"__shared_arguments__",
"return",
"shared"
] | return shared. | [
"return",
"shared",
"."
] | 05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e | https://github.com/ellethee/argparseinator/blob/05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e/argparseinator/utils.py#L228-L247 | train |
ellethee/argparseinator | argparseinator/utils.py | set_subcommands | def set_subcommands(func, parser):
"""
Set subcommands.
"""
if hasattr(func, '__subcommands__') and func.__subcommands__:
sub_parser = parser.add_subparsers(
title=SUBCOMMANDS_LIST_TITLE, dest='subcommand',
description=SUBCOMMANDS_LIST_DESCRIPTION.format(
func.__cmd_name__),
help=func.__doc__)
for sub_func in func.__subcommands__.values():
parser = get_parser(sub_func, sub_parser)
for args, kwargs in get_shared(sub_func):
parser.add_argument(*args, **kwargs)
else:
for args, kwargs in get_shared(func):
parser.add_argument(*args, **kwargs) | python | def set_subcommands(func, parser):
"""
Set subcommands.
"""
if hasattr(func, '__subcommands__') and func.__subcommands__:
sub_parser = parser.add_subparsers(
title=SUBCOMMANDS_LIST_TITLE, dest='subcommand',
description=SUBCOMMANDS_LIST_DESCRIPTION.format(
func.__cmd_name__),
help=func.__doc__)
for sub_func in func.__subcommands__.values():
parser = get_parser(sub_func, sub_parser)
for args, kwargs in get_shared(sub_func):
parser.add_argument(*args, **kwargs)
else:
for args, kwargs in get_shared(func):
parser.add_argument(*args, **kwargs) | [
"def",
"set_subcommands",
"(",
"func",
",",
"parser",
")",
":",
"if",
"hasattr",
"(",
"func",
",",
"'__subcommands__'",
")",
"and",
"func",
".",
"__subcommands__",
":",
"sub_parser",
"=",
"parser",
".",
"add_subparsers",
"(",
"title",
"=",
"SUBCOMMANDS_LIST_TITLE",
",",
"dest",
"=",
"'subcommand'",
",",
"description",
"=",
"SUBCOMMANDS_LIST_DESCRIPTION",
".",
"format",
"(",
"func",
".",
"__cmd_name__",
")",
",",
"help",
"=",
"func",
".",
"__doc__",
")",
"for",
"sub_func",
"in",
"func",
".",
"__subcommands__",
".",
"values",
"(",
")",
":",
"parser",
"=",
"get_parser",
"(",
"sub_func",
",",
"sub_parser",
")",
"for",
"args",
",",
"kwargs",
"in",
"get_shared",
"(",
"sub_func",
")",
":",
"parser",
".",
"add_argument",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"for",
"args",
",",
"kwargs",
"in",
"get_shared",
"(",
"func",
")",
":",
"parser",
".",
"add_argument",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Set subcommands. | [
"Set",
"subcommands",
"."
] | 05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e | https://github.com/ellethee/argparseinator/blob/05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e/argparseinator/utils.py#L250-L266 | train |
ellethee/argparseinator | argparseinator/utils.py | check_help | def check_help():
"""
check know args in argv.
"""
# know arguments
know = set(('-h', '--help', '-v', '--version'))
# arguments
args = set(sys.argv[1:])
# returns True if there is at least one known argument in arguments
return len(know.intersection(args)) > 0 | python | def check_help():
"""
check know args in argv.
"""
# know arguments
know = set(('-h', '--help', '-v', '--version'))
# arguments
args = set(sys.argv[1:])
# returns True if there is at least one known argument in arguments
return len(know.intersection(args)) > 0 | [
"def",
"check_help",
"(",
")",
":",
"# know arguments",
"know",
"=",
"set",
"(",
"(",
"'-h'",
",",
"'--help'",
",",
"'-v'",
",",
"'--version'",
")",
")",
"# arguments",
"args",
"=",
"set",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"# returns True if there is at least one known argument in arguments",
"return",
"len",
"(",
"know",
".",
"intersection",
"(",
"args",
")",
")",
">",
"0"
] | check know args in argv. | [
"check",
"know",
"args",
"in",
"argv",
"."
] | 05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e | https://github.com/ellethee/argparseinator/blob/05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e/argparseinator/utils.py#L269-L278 | train |
ldomic/lintools | lintools/lintools.py | Lintools.analysis_of_prot_lig_interactions | def analysis_of_prot_lig_interactions(self):
"""
The classes and function that deal with protein-ligand interaction analysis.
"""
self.hbonds = HBonds(self.topol_data,self.trajectory,self.start,self.end,self.skip,self.analysis_cutoff,distance=3)
self.pistacking = PiStacking(self.topol_data,self.trajectory,self.start,self.end,self.skip, self.analysis_cutoff)
self.sasa = SASA(self.topol_data,self.trajectory)
self.lig_descr = LigDescr(self.topol_data)
if self.trajectory!=[]:
self.rmsf = RMSF_measurements(self.topol_data,self.topology,self.trajectory,self.ligand,self.start,self.end,self.skip)
self.salt_bridges = SaltBridges(self.topol_data,self.trajectory,self.lig_descr,self.start,self.end,self.skip,self.analysis_cutoff) | python | def analysis_of_prot_lig_interactions(self):
"""
The classes and function that deal with protein-ligand interaction analysis.
"""
self.hbonds = HBonds(self.topol_data,self.trajectory,self.start,self.end,self.skip,self.analysis_cutoff,distance=3)
self.pistacking = PiStacking(self.topol_data,self.trajectory,self.start,self.end,self.skip, self.analysis_cutoff)
self.sasa = SASA(self.topol_data,self.trajectory)
self.lig_descr = LigDescr(self.topol_data)
if self.trajectory!=[]:
self.rmsf = RMSF_measurements(self.topol_data,self.topology,self.trajectory,self.ligand,self.start,self.end,self.skip)
self.salt_bridges = SaltBridges(self.topol_data,self.trajectory,self.lig_descr,self.start,self.end,self.skip,self.analysis_cutoff) | [
"def",
"analysis_of_prot_lig_interactions",
"(",
"self",
")",
":",
"self",
".",
"hbonds",
"=",
"HBonds",
"(",
"self",
".",
"topol_data",
",",
"self",
".",
"trajectory",
",",
"self",
".",
"start",
",",
"self",
".",
"end",
",",
"self",
".",
"skip",
",",
"self",
".",
"analysis_cutoff",
",",
"distance",
"=",
"3",
")",
"self",
".",
"pistacking",
"=",
"PiStacking",
"(",
"self",
".",
"topol_data",
",",
"self",
".",
"trajectory",
",",
"self",
".",
"start",
",",
"self",
".",
"end",
",",
"self",
".",
"skip",
",",
"self",
".",
"analysis_cutoff",
")",
"self",
".",
"sasa",
"=",
"SASA",
"(",
"self",
".",
"topol_data",
",",
"self",
".",
"trajectory",
")",
"self",
".",
"lig_descr",
"=",
"LigDescr",
"(",
"self",
".",
"topol_data",
")",
"if",
"self",
".",
"trajectory",
"!=",
"[",
"]",
":",
"self",
".",
"rmsf",
"=",
"RMSF_measurements",
"(",
"self",
".",
"topol_data",
",",
"self",
".",
"topology",
",",
"self",
".",
"trajectory",
",",
"self",
".",
"ligand",
",",
"self",
".",
"start",
",",
"self",
".",
"end",
",",
"self",
".",
"skip",
")",
"self",
".",
"salt_bridges",
"=",
"SaltBridges",
"(",
"self",
".",
"topol_data",
",",
"self",
".",
"trajectory",
",",
"self",
".",
"lig_descr",
",",
"self",
".",
"start",
",",
"self",
".",
"end",
",",
"self",
".",
"skip",
",",
"self",
".",
"analysis_cutoff",
")"
] | The classes and function that deal with protein-ligand interaction analysis. | [
"The",
"classes",
"and",
"function",
"that",
"deal",
"with",
"protein",
"-",
"ligand",
"interaction",
"analysis",
"."
] | d825a4a7b35f3f857d3b81b46c9aee72b0ec697a | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/lintools.py#L87-L97 | train |
ldomic/lintools | lintools/lintools.py | Lintools.save_files | def save_files(self):
"""Saves all output from LINTools run in a single directory named after the output name."""
while True:
try:
os.mkdir(self.output_name)
except Exception as e:
self.output_name = raw_input("This directory already exists - please enter a new name:")
else:
break
self.workdir = os.getcwd()
os.chdir(self.workdir+"/"+self.output_name) | python | def save_files(self):
"""Saves all output from LINTools run in a single directory named after the output name."""
while True:
try:
os.mkdir(self.output_name)
except Exception as e:
self.output_name = raw_input("This directory already exists - please enter a new name:")
else:
break
self.workdir = os.getcwd()
os.chdir(self.workdir+"/"+self.output_name) | [
"def",
"save_files",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"os",
".",
"mkdir",
"(",
"self",
".",
"output_name",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"output_name",
"=",
"raw_input",
"(",
"\"This directory already exists - please enter a new name:\"",
")",
"else",
":",
"break",
"self",
".",
"workdir",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"self",
".",
"workdir",
"+",
"\"/\"",
"+",
"self",
".",
"output_name",
")"
] | Saves all output from LINTools run in a single directory named after the output name. | [
"Saves",
"all",
"output",
"from",
"LINTools",
"run",
"in",
"a",
"single",
"directory",
"named",
"after",
"the",
"output",
"name",
"."
] | d825a4a7b35f3f857d3b81b46c9aee72b0ec697a | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/lintools.py#L120-L130 | train |
ldomic/lintools | lintools/lintools.py | Lintools.remove_files | def remove_files(self):
"""Removes intermediate files."""
file_list = ["molecule.svg","lig.pdb","HIS.pdb","PHE.pdb","TRP.pdb","TYR.pdb","lig.mol","test.xtc"]
for residue in self.topol_data.dict_of_plotted_res.keys():
file_list.append(residue[1]+residue[2]+".svg")
for f in file_list:
if os.path.isfile(f)==True:
os.remove(f) | python | def remove_files(self):
"""Removes intermediate files."""
file_list = ["molecule.svg","lig.pdb","HIS.pdb","PHE.pdb","TRP.pdb","TYR.pdb","lig.mol","test.xtc"]
for residue in self.topol_data.dict_of_plotted_res.keys():
file_list.append(residue[1]+residue[2]+".svg")
for f in file_list:
if os.path.isfile(f)==True:
os.remove(f) | [
"def",
"remove_files",
"(",
"self",
")",
":",
"file_list",
"=",
"[",
"\"molecule.svg\"",
",",
"\"lig.pdb\"",
",",
"\"HIS.pdb\"",
",",
"\"PHE.pdb\"",
",",
"\"TRP.pdb\"",
",",
"\"TYR.pdb\"",
",",
"\"lig.mol\"",
",",
"\"test.xtc\"",
"]",
"for",
"residue",
"in",
"self",
".",
"topol_data",
".",
"dict_of_plotted_res",
".",
"keys",
"(",
")",
":",
"file_list",
".",
"append",
"(",
"residue",
"[",
"1",
"]",
"+",
"residue",
"[",
"2",
"]",
"+",
"\".svg\"",
")",
"for",
"f",
"in",
"file_list",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"f",
")",
"==",
"True",
":",
"os",
".",
"remove",
"(",
"f",
")"
] | Removes intermediate files. | [
"Removes",
"intermediate",
"files",
"."
] | d825a4a7b35f3f857d3b81b46c9aee72b0ec697a | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/lintools.py#L162-L169 | train |
MonsieurV/PiPocketGeiger | PiPocketGeiger/__init__.py | RadiationWatch.setup | def setup(self):
"""Initialize the driver by setting up GPIO interrupts
and periodic statistics processing. """
# Initialize the statistics variables.
self.radiation_count = 0
self.noise_count = 0
self.count = 0
# Initialize count_history[].
self.count_history = [0] * HISTORY_LENGTH
self.history_index = 0
# Init measurement time.
self.previous_time = millis()
self.previous_history_time = millis()
self.duration = 0
# Init the GPIO context.
GPIO.setup(self.radiation_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(self.noise_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Register local callbacks.
GPIO.add_event_detect(
self.radiation_pin, GPIO.FALLING, callback=self._on_radiation
)
GPIO.add_event_detect(self.noise_pin, GPIO.FALLING, callback=self._on_noise)
# Enable the timer for processing the statistics periodically.
self._enable_timer()
return self | python | def setup(self):
"""Initialize the driver by setting up GPIO interrupts
and periodic statistics processing. """
# Initialize the statistics variables.
self.radiation_count = 0
self.noise_count = 0
self.count = 0
# Initialize count_history[].
self.count_history = [0] * HISTORY_LENGTH
self.history_index = 0
# Init measurement time.
self.previous_time = millis()
self.previous_history_time = millis()
self.duration = 0
# Init the GPIO context.
GPIO.setup(self.radiation_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(self.noise_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Register local callbacks.
GPIO.add_event_detect(
self.radiation_pin, GPIO.FALLING, callback=self._on_radiation
)
GPIO.add_event_detect(self.noise_pin, GPIO.FALLING, callback=self._on_noise)
# Enable the timer for processing the statistics periodically.
self._enable_timer()
return self | [
"def",
"setup",
"(",
"self",
")",
":",
"# Initialize the statistics variables.",
"self",
".",
"radiation_count",
"=",
"0",
"self",
".",
"noise_count",
"=",
"0",
"self",
".",
"count",
"=",
"0",
"# Initialize count_history[].",
"self",
".",
"count_history",
"=",
"[",
"0",
"]",
"*",
"HISTORY_LENGTH",
"self",
".",
"history_index",
"=",
"0",
"# Init measurement time.",
"self",
".",
"previous_time",
"=",
"millis",
"(",
")",
"self",
".",
"previous_history_time",
"=",
"millis",
"(",
")",
"self",
".",
"duration",
"=",
"0",
"# Init the GPIO context.",
"GPIO",
".",
"setup",
"(",
"self",
".",
"radiation_pin",
",",
"GPIO",
".",
"IN",
",",
"pull_up_down",
"=",
"GPIO",
".",
"PUD_UP",
")",
"GPIO",
".",
"setup",
"(",
"self",
".",
"noise_pin",
",",
"GPIO",
".",
"IN",
",",
"pull_up_down",
"=",
"GPIO",
".",
"PUD_UP",
")",
"# Register local callbacks.",
"GPIO",
".",
"add_event_detect",
"(",
"self",
".",
"radiation_pin",
",",
"GPIO",
".",
"FALLING",
",",
"callback",
"=",
"self",
".",
"_on_radiation",
")",
"GPIO",
".",
"add_event_detect",
"(",
"self",
".",
"noise_pin",
",",
"GPIO",
".",
"FALLING",
",",
"callback",
"=",
"self",
".",
"_on_noise",
")",
"# Enable the timer for processing the statistics periodically.",
"self",
".",
"_enable_timer",
"(",
")",
"return",
"self"
] | Initialize the driver by setting up GPIO interrupts
and periodic statistics processing. | [
"Initialize",
"the",
"driver",
"by",
"setting",
"up",
"GPIO",
"interrupts",
"and",
"periodic",
"statistics",
"processing",
"."
] | b0e7c303df46deeea3715fb8da3ebbefaf660f91 | https://github.com/MonsieurV/PiPocketGeiger/blob/b0e7c303df46deeea3715fb8da3ebbefaf660f91/PiPocketGeiger/__init__.py#L91-L115 | train |
robinandeer/puzzle | puzzle/cli/load.py | load | def load(ctx, variant_source, family_file, family_type, root):
"""
Load a variant source into the database.
If no database was found run puzzle init first.
1. VCF: If a vcf file is used it can be loaded with a ped file
2. GEMINI: Ped information will be retreived from the gemini db
"""
root = root or ctx.obj.get('root') or os.path.expanduser("~/.puzzle")
if os.path.isfile(root):
logger.error("'root' can't be a file")
ctx.abort()
logger.info("Root directory is: {}".format(root))
db_path = os.path.join(root, 'puzzle_db.sqlite3')
logger.info("db path is: {}".format(db_path))
if not os.path.exists(db_path):
logger.warn("database not initialized, run 'puzzle init'")
ctx.abort()
if not os.path.isfile(variant_source):
logger.error("Variant source has to be a file")
ctx.abort()
mode = get_file_type(variant_source)
if mode == 'unknown':
logger.error("Unknown file type")
ctx.abort()
#Test if gemini is installed
elif mode == 'gemini':
logger.debug("Initialzing GEMINI plugin")
if not GEMINI:
logger.error("Need to have gemini installed to use gemini plugin")
ctx.abort()
logger.debug('Set puzzle backend to {0}'.format(mode))
variant_type = get_variant_type(variant_source)
logger.debug('Set variant type to {0}'.format(variant_type))
cases = get_cases(
variant_source=variant_source,
case_lines=family_file,
case_type=family_type,
variant_type=variant_type,
variant_mode=mode
)
if len(cases) == 0:
logger.warning("No cases found")
ctx.abort()
logger.info("Initializing sqlite plugin")
store = SqlStore(db_path)
for case_obj in cases:
if store.case(case_obj.case_id) is not None:
logger.warn("{} already exists in the database"
.format(case_obj.case_id))
continue
# extract case information
logger.debug("adding case: {} to puzzle db".format(case_obj.case_id))
store.add_case(case_obj, vtype=variant_type, mode=mode) | python | def load(ctx, variant_source, family_file, family_type, root):
"""
Load a variant source into the database.
If no database was found run puzzle init first.
1. VCF: If a vcf file is used it can be loaded with a ped file
2. GEMINI: Ped information will be retreived from the gemini db
"""
root = root or ctx.obj.get('root') or os.path.expanduser("~/.puzzle")
if os.path.isfile(root):
logger.error("'root' can't be a file")
ctx.abort()
logger.info("Root directory is: {}".format(root))
db_path = os.path.join(root, 'puzzle_db.sqlite3')
logger.info("db path is: {}".format(db_path))
if not os.path.exists(db_path):
logger.warn("database not initialized, run 'puzzle init'")
ctx.abort()
if not os.path.isfile(variant_source):
logger.error("Variant source has to be a file")
ctx.abort()
mode = get_file_type(variant_source)
if mode == 'unknown':
logger.error("Unknown file type")
ctx.abort()
#Test if gemini is installed
elif mode == 'gemini':
logger.debug("Initialzing GEMINI plugin")
if not GEMINI:
logger.error("Need to have gemini installed to use gemini plugin")
ctx.abort()
logger.debug('Set puzzle backend to {0}'.format(mode))
variant_type = get_variant_type(variant_source)
logger.debug('Set variant type to {0}'.format(variant_type))
cases = get_cases(
variant_source=variant_source,
case_lines=family_file,
case_type=family_type,
variant_type=variant_type,
variant_mode=mode
)
if len(cases) == 0:
logger.warning("No cases found")
ctx.abort()
logger.info("Initializing sqlite plugin")
store = SqlStore(db_path)
for case_obj in cases:
if store.case(case_obj.case_id) is not None:
logger.warn("{} already exists in the database"
.format(case_obj.case_id))
continue
# extract case information
logger.debug("adding case: {} to puzzle db".format(case_obj.case_id))
store.add_case(case_obj, vtype=variant_type, mode=mode) | [
"def",
"load",
"(",
"ctx",
",",
"variant_source",
",",
"family_file",
",",
"family_type",
",",
"root",
")",
":",
"root",
"=",
"root",
"or",
"ctx",
".",
"obj",
".",
"get",
"(",
"'root'",
")",
"or",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~/.puzzle\"",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"root",
")",
":",
"logger",
".",
"error",
"(",
"\"'root' can't be a file\"",
")",
"ctx",
".",
"abort",
"(",
")",
"logger",
".",
"info",
"(",
"\"Root directory is: {}\"",
".",
"format",
"(",
"root",
")",
")",
"db_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"'puzzle_db.sqlite3'",
")",
"logger",
".",
"info",
"(",
"\"db path is: {}\"",
".",
"format",
"(",
"db_path",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"db_path",
")",
":",
"logger",
".",
"warn",
"(",
"\"database not initialized, run 'puzzle init'\"",
")",
"ctx",
".",
"abort",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"variant_source",
")",
":",
"logger",
".",
"error",
"(",
"\"Variant source has to be a file\"",
")",
"ctx",
".",
"abort",
"(",
")",
"mode",
"=",
"get_file_type",
"(",
"variant_source",
")",
"if",
"mode",
"==",
"'unknown'",
":",
"logger",
".",
"error",
"(",
"\"Unknown file type\"",
")",
"ctx",
".",
"abort",
"(",
")",
"#Test if gemini is installed",
"elif",
"mode",
"==",
"'gemini'",
":",
"logger",
".",
"debug",
"(",
"\"Initialzing GEMINI plugin\"",
")",
"if",
"not",
"GEMINI",
":",
"logger",
".",
"error",
"(",
"\"Need to have gemini installed to use gemini plugin\"",
")",
"ctx",
".",
"abort",
"(",
")",
"logger",
".",
"debug",
"(",
"'Set puzzle backend to {0}'",
".",
"format",
"(",
"mode",
")",
")",
"variant_type",
"=",
"get_variant_type",
"(",
"variant_source",
")",
"logger",
".",
"debug",
"(",
"'Set variant type to {0}'",
".",
"format",
"(",
"variant_type",
")",
")",
"cases",
"=",
"get_cases",
"(",
"variant_source",
"=",
"variant_source",
",",
"case_lines",
"=",
"family_file",
",",
"case_type",
"=",
"family_type",
",",
"variant_type",
"=",
"variant_type",
",",
"variant_mode",
"=",
"mode",
")",
"if",
"len",
"(",
"cases",
")",
"==",
"0",
":",
"logger",
".",
"warning",
"(",
"\"No cases found\"",
")",
"ctx",
".",
"abort",
"(",
")",
"logger",
".",
"info",
"(",
"\"Initializing sqlite plugin\"",
")",
"store",
"=",
"SqlStore",
"(",
"db_path",
")",
"for",
"case_obj",
"in",
"cases",
":",
"if",
"store",
".",
"case",
"(",
"case_obj",
".",
"case_id",
")",
"is",
"not",
"None",
":",
"logger",
".",
"warn",
"(",
"\"{} already exists in the database\"",
".",
"format",
"(",
"case_obj",
".",
"case_id",
")",
")",
"continue",
"# extract case information",
"logger",
".",
"debug",
"(",
"\"adding case: {} to puzzle db\"",
".",
"format",
"(",
"case_obj",
".",
"case_id",
")",
")",
"store",
".",
"add_case",
"(",
"case_obj",
",",
"vtype",
"=",
"variant_type",
",",
"mode",
"=",
"mode",
")"
] | Load a variant source into the database.
If no database was found run puzzle init first.
1. VCF: If a vcf file is used it can be loaded with a ped file
2. GEMINI: Ped information will be retreived from the gemini db | [
"Load",
"a",
"variant",
"source",
"into",
"the",
"database",
"."
] | 9476f05b416d3a5135d25492cb31411fdf831c58 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/cli/load.py#L30-L97 | train |
basecrm/basecrm-python | basecrm/services.py | AssociatedContactsService.list | def list(self, deal_id, **params):
"""
Retrieve deal's associated contacts
Returns all deal associated contacts
:calls: ``get /deals/{deal_id}/associated_contacts``
:param int deal_id: Unique identifier of a Deal.
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of AssociatedContacts.
:rtype: list
"""
_, _, associated_contacts = self.http_client.get("/deals/{deal_id}/associated_contacts".format(deal_id=deal_id), params=params)
return associated_contacts | python | def list(self, deal_id, **params):
"""
Retrieve deal's associated contacts
Returns all deal associated contacts
:calls: ``get /deals/{deal_id}/associated_contacts``
:param int deal_id: Unique identifier of a Deal.
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of AssociatedContacts.
:rtype: list
"""
_, _, associated_contacts = self.http_client.get("/deals/{deal_id}/associated_contacts".format(deal_id=deal_id), params=params)
return associated_contacts | [
"def",
"list",
"(",
"self",
",",
"deal_id",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"associated_contacts",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/deals/{deal_id}/associated_contacts\"",
".",
"format",
"(",
"deal_id",
"=",
"deal_id",
")",
",",
"params",
"=",
"params",
")",
"return",
"associated_contacts"
] | Retrieve deal's associated contacts
Returns all deal associated contacts
:calls: ``get /deals/{deal_id}/associated_contacts``
:param int deal_id: Unique identifier of a Deal.
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of AssociatedContacts.
:rtype: list | [
"Retrieve",
"deal",
"s",
"associated",
"contacts"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L65-L79 | train |
basecrm/basecrm-python | basecrm/services.py | AssociatedContactsService.create | def create(self, deal_id, *args, **kwargs):
"""
Create an associated contact
Creates a deal's associated contact and its role
If the specified deal or contact does not exist, the request will return an error
:calls: ``post /deals/{deal_id}/associated_contacts``
:param int deal_id: Unique identifier of a Deal.
:param tuple *args: (optional) Single object representing AssociatedContact resource.
:param dict **kwargs: (optional) AssociatedContact attributes.
:return: Dictionary that support attriubte-style access and represents newely created AssociatedContact resource.
:rtype: dict
"""
if not args and not kwargs:
raise Exception('attributes for AssociatedContact are missing')
attributes = args[0] if args else kwargs
attributes = dict((k, v) for k, v in attributes.iteritems() if k in self.OPTS_KEYS_TO_PERSIST)
_, _, associated_contact = self.http_client.post("/deals/{deal_id}/associated_contacts".format(deal_id=deal_id), body=attributes)
return associated_contact | python | def create(self, deal_id, *args, **kwargs):
"""
Create an associated contact
Creates a deal's associated contact and its role
If the specified deal or contact does not exist, the request will return an error
:calls: ``post /deals/{deal_id}/associated_contacts``
:param int deal_id: Unique identifier of a Deal.
:param tuple *args: (optional) Single object representing AssociatedContact resource.
:param dict **kwargs: (optional) AssociatedContact attributes.
:return: Dictionary that support attriubte-style access and represents newely created AssociatedContact resource.
:rtype: dict
"""
if not args and not kwargs:
raise Exception('attributes for AssociatedContact are missing')
attributes = args[0] if args else kwargs
attributes = dict((k, v) for k, v in attributes.iteritems() if k in self.OPTS_KEYS_TO_PERSIST)
_, _, associated_contact = self.http_client.post("/deals/{deal_id}/associated_contacts".format(deal_id=deal_id), body=attributes)
return associated_contact | [
"def",
"create",
"(",
"self",
",",
"deal_id",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"args",
"and",
"not",
"kwargs",
":",
"raise",
"Exception",
"(",
"'attributes for AssociatedContact are missing'",
")",
"attributes",
"=",
"args",
"[",
"0",
"]",
"if",
"args",
"else",
"kwargs",
"attributes",
"=",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"attributes",
".",
"iteritems",
"(",
")",
"if",
"k",
"in",
"self",
".",
"OPTS_KEYS_TO_PERSIST",
")",
"_",
",",
"_",
",",
"associated_contact",
"=",
"self",
".",
"http_client",
".",
"post",
"(",
"\"/deals/{deal_id}/associated_contacts\"",
".",
"format",
"(",
"deal_id",
"=",
"deal_id",
")",
",",
"body",
"=",
"attributes",
")",
"return",
"associated_contact"
] | Create an associated contact
Creates a deal's associated contact and its role
If the specified deal or contact does not exist, the request will return an error
:calls: ``post /deals/{deal_id}/associated_contacts``
:param int deal_id: Unique identifier of a Deal.
:param tuple *args: (optional) Single object representing AssociatedContact resource.
:param dict **kwargs: (optional) AssociatedContact attributes.
:return: Dictionary that support attriubte-style access and represents newely created AssociatedContact resource.
:rtype: dict | [
"Create",
"an",
"associated",
"contact"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L81-L103 | train |
basecrm/basecrm-python | basecrm/services.py | AssociatedContactsService.destroy | def destroy(self, deal_id, contact_id) :
"""
Remove an associated contact
Remove a deal's associated contact
If a deal with the supplied unique identifier does not exist, it returns an error
This operation cannot be undone
:calls: ``delete /deals/{deal_id}/associated_contacts/{contact_id}``
:param int deal_id: Unique identifier of a Deal.
:param int contact_id: Unique identifier of a Contact.
:return: True if the operation succeeded.
:rtype: bool
"""
status_code, _, _ = self.http_client.delete("/deals/{deal_id}/associated_contacts/{contact_id}".format(deal_id=deal_id, contact_id=contact_id))
return status_code == 204 | python | def destroy(self, deal_id, contact_id) :
"""
Remove an associated contact
Remove a deal's associated contact
If a deal with the supplied unique identifier does not exist, it returns an error
This operation cannot be undone
:calls: ``delete /deals/{deal_id}/associated_contacts/{contact_id}``
:param int deal_id: Unique identifier of a Deal.
:param int contact_id: Unique identifier of a Contact.
:return: True if the operation succeeded.
:rtype: bool
"""
status_code, _, _ = self.http_client.delete("/deals/{deal_id}/associated_contacts/{contact_id}".format(deal_id=deal_id, contact_id=contact_id))
return status_code == 204 | [
"def",
"destroy",
"(",
"self",
",",
"deal_id",
",",
"contact_id",
")",
":",
"status_code",
",",
"_",
",",
"_",
"=",
"self",
".",
"http_client",
".",
"delete",
"(",
"\"/deals/{deal_id}/associated_contacts/{contact_id}\"",
".",
"format",
"(",
"deal_id",
"=",
"deal_id",
",",
"contact_id",
"=",
"contact_id",
")",
")",
"return",
"status_code",
"==",
"204"
] | Remove an associated contact
Remove a deal's associated contact
If a deal with the supplied unique identifier does not exist, it returns an error
This operation cannot be undone
:calls: ``delete /deals/{deal_id}/associated_contacts/{contact_id}``
:param int deal_id: Unique identifier of a Deal.
:param int contact_id: Unique identifier of a Contact.
:return: True if the operation succeeded.
:rtype: bool | [
"Remove",
"an",
"associated",
"contact"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L105-L121 | train |
basecrm/basecrm-python | basecrm/services.py | ContactsService.list | def list(self, **params):
"""
Retrieve all contacts
Returns all contacts available to the user according to the parameters provided
:calls: ``get /contacts``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Contacts.
:rtype: list
"""
_, _, contacts = self.http_client.get("/contacts", params=params)
return contacts | python | def list(self, **params):
"""
Retrieve all contacts
Returns all contacts available to the user according to the parameters provided
:calls: ``get /contacts``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Contacts.
:rtype: list
"""
_, _, contacts = self.http_client.get("/contacts", params=params)
return contacts | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"contacts",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/contacts\"",
",",
"params",
"=",
"params",
")",
"return",
"contacts"
] | Retrieve all contacts
Returns all contacts available to the user according to the parameters provided
:calls: ``get /contacts``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Contacts.
:rtype: list | [
"Retrieve",
"all",
"contacts"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L148-L161 | train |
basecrm/basecrm-python | basecrm/services.py | ContactsService.retrieve | def retrieve(self, id) :
"""
Retrieve a single contact
Returns a single contact available to the user, according to the unique contact ID provided
If the specified contact does not exist, the request will return an error
:calls: ``get /contacts/{id}``
:param int id: Unique identifier of a Contact.
:return: Dictionary that support attriubte-style access and represent Contact resource.
:rtype: dict
"""
_, _, contact = self.http_client.get("/contacts/{id}".format(id=id))
return contact | python | def retrieve(self, id) :
"""
Retrieve a single contact
Returns a single contact available to the user, according to the unique contact ID provided
If the specified contact does not exist, the request will return an error
:calls: ``get /contacts/{id}``
:param int id: Unique identifier of a Contact.
:return: Dictionary that support attriubte-style access and represent Contact resource.
:rtype: dict
"""
_, _, contact = self.http_client.get("/contacts/{id}".format(id=id))
return contact | [
"def",
"retrieve",
"(",
"self",
",",
"id",
")",
":",
"_",
",",
"_",
",",
"contact",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/contacts/{id}\"",
".",
"format",
"(",
"id",
"=",
"id",
")",
")",
"return",
"contact"
] | Retrieve a single contact
Returns a single contact available to the user, according to the unique contact ID provided
If the specified contact does not exist, the request will return an error
:calls: ``get /contacts/{id}``
:param int id: Unique identifier of a Contact.
:return: Dictionary that support attriubte-style access and represent Contact resource.
:rtype: dict | [
"Retrieve",
"a",
"single",
"contact"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L186-L200 | train |
basecrm/basecrm-python | basecrm/services.py | DealsService.list | def list(self, **params):
"""
Retrieve all deals
Returns all deals available to the user according to the parameters provided
:calls: ``get /deals``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Deals.
:rtype: list
"""
_, _, deals = self.http_client.get("/deals", params=params)
for deal in deals:
deal['value'] = Coercion.to_decimal(deal['value'])
return deals | python | def list(self, **params):
"""
Retrieve all deals
Returns all deals available to the user according to the parameters provided
:calls: ``get /deals``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Deals.
:rtype: list
"""
_, _, deals = self.http_client.get("/deals", params=params)
for deal in deals:
deal['value'] = Coercion.to_decimal(deal['value'])
return deals | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"deals",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/deals\"",
",",
"params",
"=",
"params",
")",
"for",
"deal",
"in",
"deals",
":",
"deal",
"[",
"'value'",
"]",
"=",
"Coercion",
".",
"to_decimal",
"(",
"deal",
"[",
"'value'",
"]",
")",
"return",
"deals"
] | Retrieve all deals
Returns all deals available to the user according to the parameters provided
:calls: ``get /deals``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Deals.
:rtype: list | [
"Retrieve",
"all",
"deals"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L270-L286 | train |
basecrm/basecrm-python | basecrm/services.py | DealsService.create | def create(self, *args, **kwargs):
"""
Create a deal
Create a new deal
:calls: ``post /deals``
:param tuple *args: (optional) Single object representing Deal resource.
:param dict **kwargs: (optional) Deal attributes.
:return: Dictionary that support attriubte-style access and represents newely created Deal resource.
:rtype: dict
"""
if not args and not kwargs:
raise Exception('attributes for Deal are missing')
attributes = args[0] if args else kwargs
attributes = dict((k, v) for k, v in attributes.iteritems() if k in self.OPTS_KEYS_TO_PERSIST)
if "value" in attributes:
attributes["value"] = Coercion.to_string(attributes["value"])
_, _, deal = self.http_client.post("/deals", body=attributes)
deal["value"] = Coercion.to_decimal(deal["value"])
return deal | python | def create(self, *args, **kwargs):
"""
Create a deal
Create a new deal
:calls: ``post /deals``
:param tuple *args: (optional) Single object representing Deal resource.
:param dict **kwargs: (optional) Deal attributes.
:return: Dictionary that support attriubte-style access and represents newely created Deal resource.
:rtype: dict
"""
if not args and not kwargs:
raise Exception('attributes for Deal are missing')
attributes = args[0] if args else kwargs
attributes = dict((k, v) for k, v in attributes.iteritems() if k in self.OPTS_KEYS_TO_PERSIST)
if "value" in attributes:
attributes["value"] = Coercion.to_string(attributes["value"])
_, _, deal = self.http_client.post("/deals", body=attributes)
deal["value"] = Coercion.to_decimal(deal["value"])
return deal | [
"def",
"create",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"args",
"and",
"not",
"kwargs",
":",
"raise",
"Exception",
"(",
"'attributes for Deal are missing'",
")",
"attributes",
"=",
"args",
"[",
"0",
"]",
"if",
"args",
"else",
"kwargs",
"attributes",
"=",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"attributes",
".",
"iteritems",
"(",
")",
"if",
"k",
"in",
"self",
".",
"OPTS_KEYS_TO_PERSIST",
")",
"if",
"\"value\"",
"in",
"attributes",
":",
"attributes",
"[",
"\"value\"",
"]",
"=",
"Coercion",
".",
"to_string",
"(",
"attributes",
"[",
"\"value\"",
"]",
")",
"_",
",",
"_",
",",
"deal",
"=",
"self",
".",
"http_client",
".",
"post",
"(",
"\"/deals\"",
",",
"body",
"=",
"attributes",
")",
"deal",
"[",
"\"value\"",
"]",
"=",
"Coercion",
".",
"to_decimal",
"(",
"deal",
"[",
"\"value\"",
"]",
")",
"return",
"deal"
] | Create a deal
Create a new deal
:calls: ``post /deals``
:param tuple *args: (optional) Single object representing Deal resource.
:param dict **kwargs: (optional) Deal attributes.
:return: Dictionary that support attriubte-style access and represents newely created Deal resource.
:rtype: dict | [
"Create",
"a",
"deal"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L288-L311 | train |
basecrm/basecrm-python | basecrm/services.py | DealsService.retrieve | def retrieve(self, id) :
"""
Retrieve a single deal
Returns a single deal available to the user, according to the unique deal ID provided
If the specified deal does not exist, the request will return an error
:calls: ``get /deals/{id}``
:param int id: Unique identifier of a Deal.
:return: Dictionary that support attriubte-style access and represent Deal resource.
:rtype: dict
"""
_, _, deal = self.http_client.get("/deals/{id}".format(id=id))
deal["value"] = Coercion.to_decimal(deal["value"])
return deal | python | def retrieve(self, id) :
"""
Retrieve a single deal
Returns a single deal available to the user, according to the unique deal ID provided
If the specified deal does not exist, the request will return an error
:calls: ``get /deals/{id}``
:param int id: Unique identifier of a Deal.
:return: Dictionary that support attriubte-style access and represent Deal resource.
:rtype: dict
"""
_, _, deal = self.http_client.get("/deals/{id}".format(id=id))
deal["value"] = Coercion.to_decimal(deal["value"])
return deal | [
"def",
"retrieve",
"(",
"self",
",",
"id",
")",
":",
"_",
",",
"_",
",",
"deal",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/deals/{id}\"",
".",
"format",
"(",
"id",
"=",
"id",
")",
")",
"deal",
"[",
"\"value\"",
"]",
"=",
"Coercion",
".",
"to_decimal",
"(",
"deal",
"[",
"\"value\"",
"]",
")",
"return",
"deal"
] | Retrieve a single deal
Returns a single deal available to the user, according to the unique deal ID provided
If the specified deal does not exist, the request will return an error
:calls: ``get /deals/{id}``
:param int id: Unique identifier of a Deal.
:return: Dictionary that support attriubte-style access and represent Deal resource.
:rtype: dict | [
"Retrieve",
"a",
"single",
"deal"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L313-L328 | train |
basecrm/basecrm-python | basecrm/services.py | DealsService.update | def update(self, id, *args, **kwargs):
"""
Update a deal
Updates deal information
If the specified deal does not exist, the request will return an error
<figure class="notice">
In order to modify tags used on a record, you need to supply the entire set
`tags` are replaced every time they are used in a request
</figure>
:calls: ``put /deals/{id}``
:param int id: Unique identifier of a Deal.
:param tuple *args: (optional) Single object representing Deal resource which attributes should be updated.
:param dict **kwargs: (optional) Deal attributes to update.
:return: Dictionary that support attriubte-style access and represents updated Deal resource.
:rtype: dict
"""
if not args and not kwargs:
raise Exception('attributes for Deal are missing')
attributes = args[0] if args else kwargs
attributes = dict((k, v) for k, v in attributes.iteritems() if k in self.OPTS_KEYS_TO_PERSIST)
if "value" in attributes:
attributes["value"] = Coercion.to_string(attributes["value"])
_, _, deal = self.http_client.put("/deals/{id}".format(id=id), body=attributes)
deal["value"] = Coercion.to_decimal(deal["value"])
return deal | python | def update(self, id, *args, **kwargs):
"""
Update a deal
Updates deal information
If the specified deal does not exist, the request will return an error
<figure class="notice">
In order to modify tags used on a record, you need to supply the entire set
`tags` are replaced every time they are used in a request
</figure>
:calls: ``put /deals/{id}``
:param int id: Unique identifier of a Deal.
:param tuple *args: (optional) Single object representing Deal resource which attributes should be updated.
:param dict **kwargs: (optional) Deal attributes to update.
:return: Dictionary that support attriubte-style access and represents updated Deal resource.
:rtype: dict
"""
if not args and not kwargs:
raise Exception('attributes for Deal are missing')
attributes = args[0] if args else kwargs
attributes = dict((k, v) for k, v in attributes.iteritems() if k in self.OPTS_KEYS_TO_PERSIST)
if "value" in attributes:
attributes["value"] = Coercion.to_string(attributes["value"])
_, _, deal = self.http_client.put("/deals/{id}".format(id=id), body=attributes)
deal["value"] = Coercion.to_decimal(deal["value"])
return deal | [
"def",
"update",
"(",
"self",
",",
"id",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"args",
"and",
"not",
"kwargs",
":",
"raise",
"Exception",
"(",
"'attributes for Deal are missing'",
")",
"attributes",
"=",
"args",
"[",
"0",
"]",
"if",
"args",
"else",
"kwargs",
"attributes",
"=",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"attributes",
".",
"iteritems",
"(",
")",
"if",
"k",
"in",
"self",
".",
"OPTS_KEYS_TO_PERSIST",
")",
"if",
"\"value\"",
"in",
"attributes",
":",
"attributes",
"[",
"\"value\"",
"]",
"=",
"Coercion",
".",
"to_string",
"(",
"attributes",
"[",
"\"value\"",
"]",
")",
"_",
",",
"_",
",",
"deal",
"=",
"self",
".",
"http_client",
".",
"put",
"(",
"\"/deals/{id}\"",
".",
"format",
"(",
"id",
"=",
"id",
")",
",",
"body",
"=",
"attributes",
")",
"deal",
"[",
"\"value\"",
"]",
"=",
"Coercion",
".",
"to_decimal",
"(",
"deal",
"[",
"\"value\"",
"]",
")",
"return",
"deal"
] | Update a deal
Updates deal information
If the specified deal does not exist, the request will return an error
<figure class="notice">
In order to modify tags used on a record, you need to supply the entire set
`tags` are replaced every time they are used in a request
</figure>
:calls: ``put /deals/{id}``
:param int id: Unique identifier of a Deal.
:param tuple *args: (optional) Single object representing Deal resource which attributes should be updated.
:param dict **kwargs: (optional) Deal attributes to update.
:return: Dictionary that support attriubte-style access and represents updated Deal resource.
:rtype: dict | [
"Update",
"a",
"deal"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L330-L359 | train |
basecrm/basecrm-python | basecrm/services.py | DealSourcesService.update | def update(self, id, *args, **kwargs):
"""
Update a source
Updates source information
If the specified source does not exist, the request will return an error
<figure class="notice">
If you want to update a source, you **must** make sure source's name is unique
</figure>
:calls: ``put /deal_sources/{id}``
:param int id: Unique identifier of a DealSource.
:param tuple *args: (optional) Single object representing DealSource resource which attributes should be updated.
:param dict **kwargs: (optional) DealSource attributes to update.
:return: Dictionary that support attriubte-style access and represents updated DealSource resource.
:rtype: dict
"""
if not args and not kwargs:
raise Exception('attributes for DealSource are missing')
attributes = args[0] if args else kwargs
attributes = dict((k, v) for k, v in attributes.iteritems() if k in self.OPTS_KEYS_TO_PERSIST)
_, _, deal_source = self.http_client.put("/deal_sources/{id}".format(id=id), body=attributes)
return deal_source | python | def update(self, id, *args, **kwargs):
"""
Update a source
Updates source information
If the specified source does not exist, the request will return an error
<figure class="notice">
If you want to update a source, you **must** make sure source's name is unique
</figure>
:calls: ``put /deal_sources/{id}``
:param int id: Unique identifier of a DealSource.
:param tuple *args: (optional) Single object representing DealSource resource which attributes should be updated.
:param dict **kwargs: (optional) DealSource attributes to update.
:return: Dictionary that support attriubte-style access and represents updated DealSource resource.
:rtype: dict
"""
if not args and not kwargs:
raise Exception('attributes for DealSource are missing')
attributes = args[0] if args else kwargs
attributes = dict((k, v) for k, v in attributes.iteritems() if k in self.OPTS_KEYS_TO_PERSIST)
_, _, deal_source = self.http_client.put("/deal_sources/{id}".format(id=id), body=attributes)
return deal_source | [
"def",
"update",
"(",
"self",
",",
"id",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"args",
"and",
"not",
"kwargs",
":",
"raise",
"Exception",
"(",
"'attributes for DealSource are missing'",
")",
"attributes",
"=",
"args",
"[",
"0",
"]",
"if",
"args",
"else",
"kwargs",
"attributes",
"=",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"attributes",
".",
"iteritems",
"(",
")",
"if",
"k",
"in",
"self",
".",
"OPTS_KEYS_TO_PERSIST",
")",
"_",
",",
"_",
",",
"deal_source",
"=",
"self",
".",
"http_client",
".",
"put",
"(",
"\"/deal_sources/{id}\"",
".",
"format",
"(",
"id",
"=",
"id",
")",
",",
"body",
"=",
"attributes",
")",
"return",
"deal_source"
] | Update a source
Updates source information
If the specified source does not exist, the request will return an error
<figure class="notice">
If you want to update a source, you **must** make sure source's name is unique
</figure>
:calls: ``put /deal_sources/{id}``
:param int id: Unique identifier of a DealSource.
:param tuple *args: (optional) Single object representing DealSource resource which attributes should be updated.
:param dict **kwargs: (optional) DealSource attributes to update.
:return: Dictionary that support attriubte-style access and represents updated DealSource resource.
:rtype: dict | [
"Update",
"a",
"source"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L459-L484 | train |
basecrm/basecrm-python | basecrm/services.py | DealUnqualifiedReasonsService.list | def list(self, **params):
"""
Retrieve all deal unqualified reasons
Returns all deal unqualified reasons available to the user according to the parameters provided
:calls: ``get /deal_unqualified_reasons``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of DealUnqualifiedReasons.
:rtype: list
"""
_, _, deal_unqualified_reasons = self.http_client.get("/deal_unqualified_reasons", params=params)
return deal_unqualified_reasons | python | def list(self, **params):
"""
Retrieve all deal unqualified reasons
Returns all deal unqualified reasons available to the user according to the parameters provided
:calls: ``get /deal_unqualified_reasons``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of DealUnqualifiedReasons.
:rtype: list
"""
_, _, deal_unqualified_reasons = self.http_client.get("/deal_unqualified_reasons", params=params)
return deal_unqualified_reasons | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"deal_unqualified_reasons",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/deal_unqualified_reasons\"",
",",
"params",
"=",
"params",
")",
"return",
"deal_unqualified_reasons"
] | Retrieve all deal unqualified reasons
Returns all deal unqualified reasons available to the user according to the parameters provided
:calls: ``get /deal_unqualified_reasons``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of DealUnqualifiedReasons.
:rtype: list | [
"Retrieve",
"all",
"deal",
"unqualified",
"reasons"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L528-L541 | train |
basecrm/basecrm-python | basecrm/services.py | DealUnqualifiedReasonsService.retrieve | def retrieve(self, id) :
"""
Retrieve a single deal unqualified reason
Returns a single deal unqualified reason available to the user by the provided id
If a loss reason with the supplied unique identifier does not exist, it returns an error
:calls: ``get /deal_unqualified_reasons/{id}``
:param int id: Unique identifier of a DealUnqualifiedReason.
:return: Dictionary that support attriubte-style access and represent DealUnqualifiedReason resource.
:rtype: dict
"""
_, _, deal_unqualified_reason = self.http_client.get("/deal_unqualified_reasons/{id}".format(id=id))
return deal_unqualified_reason | python | def retrieve(self, id) :
"""
Retrieve a single deal unqualified reason
Returns a single deal unqualified reason available to the user by the provided id
If a loss reason with the supplied unique identifier does not exist, it returns an error
:calls: ``get /deal_unqualified_reasons/{id}``
:param int id: Unique identifier of a DealUnqualifiedReason.
:return: Dictionary that support attriubte-style access and represent DealUnqualifiedReason resource.
:rtype: dict
"""
_, _, deal_unqualified_reason = self.http_client.get("/deal_unqualified_reasons/{id}".format(id=id))
return deal_unqualified_reason | [
"def",
"retrieve",
"(",
"self",
",",
"id",
")",
":",
"_",
",",
"_",
",",
"deal_unqualified_reason",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/deal_unqualified_reasons/{id}\"",
".",
"format",
"(",
"id",
"=",
"id",
")",
")",
"return",
"deal_unqualified_reason"
] | Retrieve a single deal unqualified reason
Returns a single deal unqualified reason available to the user by the provided id
If a loss reason with the supplied unique identifier does not exist, it returns an error
:calls: ``get /deal_unqualified_reasons/{id}``
:param int id: Unique identifier of a DealUnqualifiedReason.
:return: Dictionary that support attriubte-style access and represent DealUnqualifiedReason resource.
:rtype: dict | [
"Retrieve",
"a",
"single",
"deal",
"unqualified",
"reason"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L568-L582 | train |
basecrm/basecrm-python | basecrm/services.py | LeadsService.list | def list(self, **params):
"""
Retrieve all leads
Returns all leads available to the user, according to the parameters provided
:calls: ``get /leads``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Leads.
:rtype: list
"""
_, _, leads = self.http_client.get("/leads", params=params)
return leads | python | def list(self, **params):
"""
Retrieve all leads
Returns all leads available to the user, according to the parameters provided
:calls: ``get /leads``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Leads.
:rtype: list
"""
_, _, leads = self.http_client.get("/leads", params=params)
return leads | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"leads",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/leads\"",
",",
"params",
"=",
"params",
")",
"return",
"leads"
] | Retrieve all leads
Returns all leads available to the user, according to the parameters provided
:calls: ``get /leads``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Leads.
:rtype: list | [
"Retrieve",
"all",
"leads"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L653-L666 | train |
basecrm/basecrm-python | basecrm/services.py | LeadsService.retrieve | def retrieve(self, id) :
"""
Retrieve a single lead
Returns a single lead available to the user, according to the unique lead ID provided
If the specified lead does not exist, this query returns an error
:calls: ``get /leads/{id}``
:param int id: Unique identifier of a Lead.
:return: Dictionary that support attriubte-style access and represent Lead resource.
:rtype: dict
"""
_, _, lead = self.http_client.get("/leads/{id}".format(id=id))
return lead | python | def retrieve(self, id) :
"""
Retrieve a single lead
Returns a single lead available to the user, according to the unique lead ID provided
If the specified lead does not exist, this query returns an error
:calls: ``get /leads/{id}``
:param int id: Unique identifier of a Lead.
:return: Dictionary that support attriubte-style access and represent Lead resource.
:rtype: dict
"""
_, _, lead = self.http_client.get("/leads/{id}".format(id=id))
return lead | [
"def",
"retrieve",
"(",
"self",
",",
"id",
")",
":",
"_",
",",
"_",
",",
"lead",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/leads/{id}\"",
".",
"format",
"(",
"id",
"=",
"id",
")",
")",
"return",
"lead"
] | Retrieve a single lead
Returns a single lead available to the user, according to the unique lead ID provided
If the specified lead does not exist, this query returns an error
:calls: ``get /leads/{id}``
:param int id: Unique identifier of a Lead.
:return: Dictionary that support attriubte-style access and represent Lead resource.
:rtype: dict | [
"Retrieve",
"a",
"single",
"lead"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L691-L705 | train |
basecrm/basecrm-python | basecrm/services.py | LeadUnqualifiedReasonsService.list | def list(self, **params):
"""
Retrieve all lead unqualified reasons
Returns all lead unqualified reasons available to the user according to the parameters provided
:calls: ``get /lead_unqualified_reasons``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of LeadUnqualifiedReasons.
:rtype: list
"""
_, _, lead_unqualified_reasons = self.http_client.get("/lead_unqualified_reasons", params=params)
return lead_unqualified_reasons | python | def list(self, **params):
"""
Retrieve all lead unqualified reasons
Returns all lead unqualified reasons available to the user according to the parameters provided
:calls: ``get /lead_unqualified_reasons``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of LeadUnqualifiedReasons.
:rtype: list
"""
_, _, lead_unqualified_reasons = self.http_client.get("/lead_unqualified_reasons", params=params)
return lead_unqualified_reasons | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"lead_unqualified_reasons",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/lead_unqualified_reasons\"",
",",
"params",
"=",
"params",
")",
"return",
"lead_unqualified_reasons"
] | Retrieve all lead unqualified reasons
Returns all lead unqualified reasons available to the user according to the parameters provided
:calls: ``get /lead_unqualified_reasons``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of LeadUnqualifiedReasons.
:rtype: list | [
"Retrieve",
"all",
"lead",
"unqualified",
"reasons"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L898-L911 | train |
basecrm/basecrm-python | basecrm/services.py | LineItemsService.list | def list(self, order_id, **params):
"""
Retrieve order's line items
Returns all line items associated to order
:calls: ``get /orders/{order_id}/line_items``
:param int order_id: Unique identifier of a Order.
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of LineItems.
:rtype: list
"""
_, _, line_items = self.http_client.get("/orders/{order_id}/line_items".format(order_id=order_id), params=params)
return line_items | python | def list(self, order_id, **params):
"""
Retrieve order's line items
Returns all line items associated to order
:calls: ``get /orders/{order_id}/line_items``
:param int order_id: Unique identifier of a Order.
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of LineItems.
:rtype: list
"""
_, _, line_items = self.http_client.get("/orders/{order_id}/line_items".format(order_id=order_id), params=params)
return line_items | [
"def",
"list",
"(",
"self",
",",
"order_id",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"line_items",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/orders/{order_id}/line_items\"",
".",
"format",
"(",
"order_id",
"=",
"order_id",
")",
",",
"params",
"=",
"params",
")",
"return",
"line_items"
] | Retrieve order's line items
Returns all line items associated to order
:calls: ``get /orders/{order_id}/line_items``
:param int order_id: Unique identifier of a Order.
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of LineItems.
:rtype: list | [
"Retrieve",
"order",
"s",
"line",
"items"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L938-L952 | train |
basecrm/basecrm-python | basecrm/services.py | LineItemsService.retrieve | def retrieve(self, order_id, id) :
"""
Retrieve a single line item
Returns a single line item of an order, according to the unique line item ID provided
:calls: ``get /orders/{order_id}/line_items/{id}``
:param int order_id: Unique identifier of a Order.
:param int id: Unique identifier of a LineItem.
:return: Dictionary that support attriubte-style access and represent LineItem resource.
:rtype: dict
"""
_, _, line_item = self.http_client.get("/orders/{order_id}/line_items/{id}".format(order_id=order_id, id=id))
return line_item | python | def retrieve(self, order_id, id) :
"""
Retrieve a single line item
Returns a single line item of an order, according to the unique line item ID provided
:calls: ``get /orders/{order_id}/line_items/{id}``
:param int order_id: Unique identifier of a Order.
:param int id: Unique identifier of a LineItem.
:return: Dictionary that support attriubte-style access and represent LineItem resource.
:rtype: dict
"""
_, _, line_item = self.http_client.get("/orders/{order_id}/line_items/{id}".format(order_id=order_id, id=id))
return line_item | [
"def",
"retrieve",
"(",
"self",
",",
"order_id",
",",
"id",
")",
":",
"_",
",",
"_",
",",
"line_item",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/orders/{order_id}/line_items/{id}\"",
".",
"format",
"(",
"order_id",
"=",
"order_id",
",",
"id",
"=",
"id",
")",
")",
"return",
"line_item"
] | Retrieve a single line item
Returns a single line item of an order, according to the unique line item ID provided
:calls: ``get /orders/{order_id}/line_items/{id}``
:param int order_id: Unique identifier of a Order.
:param int id: Unique identifier of a LineItem.
:return: Dictionary that support attriubte-style access and represent LineItem resource.
:rtype: dict | [
"Retrieve",
"a",
"single",
"line",
"item"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L979-L993 | train |
basecrm/basecrm-python | basecrm/services.py | LossReasonsService.list | def list(self, **params):
"""
Retrieve all reasons
Returns all deal loss reasons available to the user according to the parameters provided
:calls: ``get /loss_reasons``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of LossReasons.
:rtype: list
"""
_, _, loss_reasons = self.http_client.get("/loss_reasons", params=params)
return loss_reasons | python | def list(self, **params):
"""
Retrieve all reasons
Returns all deal loss reasons available to the user according to the parameters provided
:calls: ``get /loss_reasons``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of LossReasons.
:rtype: list
"""
_, _, loss_reasons = self.http_client.get("/loss_reasons", params=params)
return loss_reasons | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"loss_reasons",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/loss_reasons\"",
",",
"params",
"=",
"params",
")",
"return",
"loss_reasons"
] | Retrieve all reasons
Returns all deal loss reasons available to the user according to the parameters provided
:calls: ``get /loss_reasons``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of LossReasons.
:rtype: list | [
"Retrieve",
"all",
"reasons"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L1037-L1050 | train |
basecrm/basecrm-python | basecrm/services.py | LossReasonsService.retrieve | def retrieve(self, id) :
"""
Retrieve a single reason
Returns a single loss reason available to the user by the provided id
If a loss reason with the supplied unique identifier does not exist, it returns an error
:calls: ``get /loss_reasons/{id}``
:param int id: Unique identifier of a LossReason.
:return: Dictionary that support attriubte-style access and represent LossReason resource.
:rtype: dict
"""
_, _, loss_reason = self.http_client.get("/loss_reasons/{id}".format(id=id))
return loss_reason | python | def retrieve(self, id) :
"""
Retrieve a single reason
Returns a single loss reason available to the user by the provided id
If a loss reason with the supplied unique identifier does not exist, it returns an error
:calls: ``get /loss_reasons/{id}``
:param int id: Unique identifier of a LossReason.
:return: Dictionary that support attriubte-style access and represent LossReason resource.
:rtype: dict
"""
_, _, loss_reason = self.http_client.get("/loss_reasons/{id}".format(id=id))
return loss_reason | [
"def",
"retrieve",
"(",
"self",
",",
"id",
")",
":",
"_",
",",
"_",
",",
"loss_reason",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/loss_reasons/{id}\"",
".",
"format",
"(",
"id",
"=",
"id",
")",
")",
"return",
"loss_reason"
] | Retrieve a single reason
Returns a single loss reason available to the user by the provided id
If a loss reason with the supplied unique identifier does not exist, it returns an error
:calls: ``get /loss_reasons/{id}``
:param int id: Unique identifier of a LossReason.
:return: Dictionary that support attriubte-style access and represent LossReason resource.
:rtype: dict | [
"Retrieve",
"a",
"single",
"reason"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L1077-L1091 | train |
basecrm/basecrm-python | basecrm/services.py | NotesService.list | def list(self, **params):
"""
Retrieve all notes
Returns all notes available to the user, according to the parameters provided
:calls: ``get /notes``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Notes.
:rtype: list
"""
_, _, notes = self.http_client.get("/notes", params=params)
return notes | python | def list(self, **params):
"""
Retrieve all notes
Returns all notes available to the user, according to the parameters provided
:calls: ``get /notes``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Notes.
:rtype: list
"""
_, _, notes = self.http_client.get("/notes", params=params)
return notes | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"notes",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/notes\"",
",",
"params",
"=",
"params",
")",
"return",
"notes"
] | Retrieve all notes
Returns all notes available to the user, according to the parameters provided
:calls: ``get /notes``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Notes.
:rtype: list | [
"Retrieve",
"all",
"notes"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L1162-L1175 | train |
basecrm/basecrm-python | basecrm/services.py | NotesService.retrieve | def retrieve(self, id) :
"""
Retrieve a single note
Returns a single note available to the user, according to the unique note ID provided
If the note ID does not exist, this request will return an error
:calls: ``get /notes/{id}``
:param int id: Unique identifier of a Note.
:return: Dictionary that support attriubte-style access and represent Note resource.
:rtype: dict
"""
_, _, note = self.http_client.get("/notes/{id}".format(id=id))
return note | python | def retrieve(self, id) :
"""
Retrieve a single note
Returns a single note available to the user, according to the unique note ID provided
If the note ID does not exist, this request will return an error
:calls: ``get /notes/{id}``
:param int id: Unique identifier of a Note.
:return: Dictionary that support attriubte-style access and represent Note resource.
:rtype: dict
"""
_, _, note = self.http_client.get("/notes/{id}".format(id=id))
return note | [
"def",
"retrieve",
"(",
"self",
",",
"id",
")",
":",
"_",
",",
"_",
",",
"note",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/notes/{id}\"",
".",
"format",
"(",
"id",
"=",
"id",
")",
")",
"return",
"note"
] | Retrieve a single note
Returns a single note available to the user, according to the unique note ID provided
If the note ID does not exist, this request will return an error
:calls: ``get /notes/{id}``
:param int id: Unique identifier of a Note.
:return: Dictionary that support attriubte-style access and represent Note resource.
:rtype: dict | [
"Retrieve",
"a",
"single",
"note"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L1202-L1216 | train |
basecrm/basecrm-python | basecrm/services.py | OrdersService.list | def list(self, **params):
"""
Retrieve all orders
Returns all orders available to the user according to the parameters provided
:calls: ``get /orders``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Orders.
:rtype: list
"""
_, _, orders = self.http_client.get("/orders", params=params)
return orders | python | def list(self, **params):
"""
Retrieve all orders
Returns all orders available to the user according to the parameters provided
:calls: ``get /orders``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Orders.
:rtype: list
"""
_, _, orders = self.http_client.get("/orders", params=params)
return orders | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"orders",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/orders\"",
",",
"params",
"=",
"params",
")",
"return",
"orders"
] | Retrieve all orders
Returns all orders available to the user according to the parameters provided
:calls: ``get /orders``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Orders.
:rtype: list | [
"Retrieve",
"all",
"orders"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L1284-L1297 | train |
basecrm/basecrm-python | basecrm/services.py | OrdersService.retrieve | def retrieve(self, id) :
"""
Retrieve a single order
Returns a single order available to the user, according to the unique order ID provided
If the specified order does not exist, the request will return an error
:calls: ``get /orders/{id}``
:param int id: Unique identifier of a Order.
:return: Dictionary that support attriubte-style access and represent Order resource.
:rtype: dict
"""
_, _, order = self.http_client.get("/orders/{id}".format(id=id))
return order | python | def retrieve(self, id) :
"""
Retrieve a single order
Returns a single order available to the user, according to the unique order ID provided
If the specified order does not exist, the request will return an error
:calls: ``get /orders/{id}``
:param int id: Unique identifier of a Order.
:return: Dictionary that support attriubte-style access and represent Order resource.
:rtype: dict
"""
_, _, order = self.http_client.get("/orders/{id}".format(id=id))
return order | [
"def",
"retrieve",
"(",
"self",
",",
"id",
")",
":",
"_",
",",
"_",
",",
"order",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/orders/{id}\"",
".",
"format",
"(",
"id",
"=",
"id",
")",
")",
"return",
"order"
] | Retrieve a single order
Returns a single order available to the user, according to the unique order ID provided
If the specified order does not exist, the request will return an error
:calls: ``get /orders/{id}``
:param int id: Unique identifier of a Order.
:return: Dictionary that support attriubte-style access and represent Order resource.
:rtype: dict | [
"Retrieve",
"a",
"single",
"order"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L1323-L1337 | train |
basecrm/basecrm-python | basecrm/services.py | PipelinesService.list | def list(self, **params):
"""
Retrieve all pipelines
Returns all pipelines available to the user, according to the parameters provided
:calls: ``get /pipelines``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Pipelines.
:rtype: list
"""
_, _, pipelines = self.http_client.get("/pipelines", params=params)
return pipelines | python | def list(self, **params):
"""
Retrieve all pipelines
Returns all pipelines available to the user, according to the parameters provided
:calls: ``get /pipelines``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Pipelines.
:rtype: list
"""
_, _, pipelines = self.http_client.get("/pipelines", params=params)
return pipelines | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"pipelines",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/pipelines\"",
",",
"params",
"=",
"params",
")",
"return",
"pipelines"
] | Retrieve all pipelines
Returns all pipelines available to the user, according to the parameters provided
:calls: ``get /pipelines``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Pipelines.
:rtype: list | [
"Retrieve",
"all",
"pipelines"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L1401-L1414 | train |
basecrm/basecrm-python | basecrm/services.py | ProductsService.list | def list(self, **params):
"""
Retrieve all products
Returns all products available to the user according to the parameters provided
:calls: ``get /products``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Products.
:rtype: list
"""
_, _, products = self.http_client.get("/products", params=params)
return products | python | def list(self, **params):
"""
Retrieve all products
Returns all products available to the user according to the parameters provided
:calls: ``get /products``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Products.
:rtype: list
"""
_, _, products = self.http_client.get("/products", params=params)
return products | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"products",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/products\"",
",",
"params",
"=",
"params",
")",
"return",
"products"
] | Retrieve all products
Returns all products available to the user according to the parameters provided
:calls: ``get /products``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Products.
:rtype: list | [
"Retrieve",
"all",
"products"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L1441-L1454 | train |
basecrm/basecrm-python | basecrm/services.py | ProductsService.retrieve | def retrieve(self, id) :
"""
Retrieve a single product
Returns a single product, according to the unique product ID provided
If the specified product does not exist, the request will return an error
:calls: ``get /products/{id}``
:param int id: Unique identifier of a Product.
:return: Dictionary that support attriubte-style access and represent Product resource.
:rtype: dict
"""
_, _, product = self.http_client.get("/products/{id}".format(id=id))
return product | python | def retrieve(self, id) :
"""
Retrieve a single product
Returns a single product, according to the unique product ID provided
If the specified product does not exist, the request will return an error
:calls: ``get /products/{id}``
:param int id: Unique identifier of a Product.
:return: Dictionary that support attriubte-style access and represent Product resource.
:rtype: dict
"""
_, _, product = self.http_client.get("/products/{id}".format(id=id))
return product | [
"def",
"retrieve",
"(",
"self",
",",
"id",
")",
":",
"_",
",",
"_",
",",
"product",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/products/{id}\"",
".",
"format",
"(",
"id",
"=",
"id",
")",
")",
"return",
"product"
] | Retrieve a single product
Returns a single product, according to the unique product ID provided
If the specified product does not exist, the request will return an error
:calls: ``get /products/{id}``
:param int id: Unique identifier of a Product.
:return: Dictionary that support attriubte-style access and represent Product resource.
:rtype: dict | [
"Retrieve",
"a",
"single",
"product"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L1478-L1492 | train |
basecrm/basecrm-python | basecrm/services.py | StagesService.list | def list(self, **params):
"""
Retrieve all stages
Returns all stages available to the user, according to the parameters provided
:calls: ``get /stages``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Stages.
:rtype: list
"""
_, _, stages = self.http_client.get("/stages", params=params)
return stages | python | def list(self, **params):
"""
Retrieve all stages
Returns all stages available to the user, according to the parameters provided
:calls: ``get /stages``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Stages.
:rtype: list
"""
_, _, stages = self.http_client.get("/stages", params=params)
return stages | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"stages",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/stages\"",
",",
"params",
"=",
"params",
")",
"return",
"stages"
] | Retrieve all stages
Returns all stages available to the user, according to the parameters provided
:calls: ``get /stages``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Stages.
:rtype: list | [
"Retrieve",
"all",
"stages"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L1686-L1699 | train |
basecrm/basecrm-python | basecrm/services.py | TagsService.list | def list(self, **params):
"""
Retrieve all tags
Returns all tags available to the user, according to the parameters provided
:calls: ``get /tags``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Tags.
:rtype: list
"""
_, _, tags = self.http_client.get("/tags", params=params)
return tags | python | def list(self, **params):
"""
Retrieve all tags
Returns all tags available to the user, according to the parameters provided
:calls: ``get /tags``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Tags.
:rtype: list
"""
_, _, tags = self.http_client.get("/tags", params=params)
return tags | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"tags",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/tags\"",
",",
"params",
"=",
"params",
")",
"return",
"tags"
] | Retrieve all tags
Returns all tags available to the user, according to the parameters provided
:calls: ``get /tags``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Tags.
:rtype: list | [
"Retrieve",
"all",
"tags"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L1726-L1739 | train |
basecrm/basecrm-python | basecrm/services.py | TagsService.retrieve | def retrieve(self, id) :
"""
Retrieve a single tag
Returns a single tag available to the user according to the unique ID provided
If the specified tag does not exist, this query will return an error
:calls: ``get /tags/{id}``
:param int id: Unique identifier of a Tag.
:return: Dictionary that support attriubte-style access and represent Tag resource.
:rtype: dict
"""
_, _, tag = self.http_client.get("/tags/{id}".format(id=id))
return tag | python | def retrieve(self, id) :
"""
Retrieve a single tag
Returns a single tag available to the user according to the unique ID provided
If the specified tag does not exist, this query will return an error
:calls: ``get /tags/{id}``
:param int id: Unique identifier of a Tag.
:return: Dictionary that support attriubte-style access and represent Tag resource.
:rtype: dict
"""
_, _, tag = self.http_client.get("/tags/{id}".format(id=id))
return tag | [
"def",
"retrieve",
"(",
"self",
",",
"id",
")",
":",
"_",
",",
"_",
",",
"tag",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/tags/{id}\"",
".",
"format",
"(",
"id",
"=",
"id",
")",
")",
"return",
"tag"
] | Retrieve a single tag
Returns a single tag available to the user according to the unique ID provided
If the specified tag does not exist, this query will return an error
:calls: ``get /tags/{id}``
:param int id: Unique identifier of a Tag.
:return: Dictionary that support attriubte-style access and represent Tag resource.
:rtype: dict | [
"Retrieve",
"a",
"single",
"tag"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L1764-L1778 | train |
basecrm/basecrm-python | basecrm/services.py | TasksService.list | def list(self, **params):
"""
Retrieve all tasks
Returns all tasks available to the user, according to the parameters provided
If you ask for tasks without any parameter provided Base API will return you both **floating** and **related** tasks
Although you can narrow the search set to either of them via query parameters
:calls: ``get /tasks``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Tasks.
:rtype: list
"""
_, _, tasks = self.http_client.get("/tasks", params=params)
return tasks | python | def list(self, **params):
"""
Retrieve all tasks
Returns all tasks available to the user, according to the parameters provided
If you ask for tasks without any parameter provided Base API will return you both **floating** and **related** tasks
Although you can narrow the search set to either of them via query parameters
:calls: ``get /tasks``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Tasks.
:rtype: list
"""
_, _, tasks = self.http_client.get("/tasks", params=params)
return tasks | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"tasks",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/tasks\"",
",",
"params",
"=",
"params",
")",
"return",
"tasks"
] | Retrieve all tasks
Returns all tasks available to the user, according to the parameters provided
If you ask for tasks without any parameter provided Base API will return you both **floating** and **related** tasks
Although you can narrow the search set to either of them via query parameters
:calls: ``get /tasks``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Tasks.
:rtype: list | [
"Retrieve",
"all",
"tasks"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L1848-L1863 | train |
basecrm/basecrm-python | basecrm/services.py | TasksService.retrieve | def retrieve(self, id) :
"""
Retrieve a single task
Returns a single task available to the user according to the unique task ID provided
If the specified task does not exist, this query will return an error
:calls: ``get /tasks/{id}``
:param int id: Unique identifier of a Task.
:return: Dictionary that support attriubte-style access and represent Task resource.
:rtype: dict
"""
_, _, task = self.http_client.get("/tasks/{id}".format(id=id))
return task | python | def retrieve(self, id) :
"""
Retrieve a single task
Returns a single task available to the user according to the unique task ID provided
If the specified task does not exist, this query will return an error
:calls: ``get /tasks/{id}``
:param int id: Unique identifier of a Task.
:return: Dictionary that support attriubte-style access and represent Task resource.
:rtype: dict
"""
_, _, task = self.http_client.get("/tasks/{id}".format(id=id))
return task | [
"def",
"retrieve",
"(",
"self",
",",
"id",
")",
":",
"_",
",",
"_",
",",
"task",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/tasks/{id}\"",
".",
"format",
"(",
"id",
"=",
"id",
")",
")",
"return",
"task"
] | Retrieve a single task
Returns a single task available to the user according to the unique task ID provided
If the specified task does not exist, this query will return an error
:calls: ``get /tasks/{id}``
:param int id: Unique identifier of a Task.
:return: Dictionary that support attriubte-style access and represent Task resource.
:rtype: dict | [
"Retrieve",
"a",
"single",
"task"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L1891-L1905 | train |
basecrm/basecrm-python | basecrm/services.py | TextMessagesService.list | def list(self, **params):
"""
Retrieve text messages
Returns Text Messages, according to the parameters provided
:calls: ``get /text_messages``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of TextMessages.
:rtype: list
"""
_, _, text_messages = self.http_client.get("/text_messages", params=params)
return text_messages | python | def list(self, **params):
"""
Retrieve text messages
Returns Text Messages, according to the parameters provided
:calls: ``get /text_messages``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of TextMessages.
:rtype: list
"""
_, _, text_messages = self.http_client.get("/text_messages", params=params)
return text_messages | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"text_messages",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/text_messages\"",
",",
"params",
"=",
"params",
")",
"return",
"text_messages"
] | Retrieve text messages
Returns Text Messages, according to the parameters provided
:calls: ``get /text_messages``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of TextMessages.
:rtype: list | [
"Retrieve",
"text",
"messages"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L1969-L1982 | train |
basecrm/basecrm-python | basecrm/services.py | TextMessagesService.retrieve | def retrieve(self, id) :
"""
Retrieve a single text message
Returns a single text message according to the unique ID provided
If the specified user does not exist, this query returns an error
:calls: ``get /text_messages/{id}``
:param int id: Unique identifier of a TextMessage.
:return: Dictionary that support attriubte-style access and represent TextMessage resource.
:rtype: dict
"""
_, _, text_message = self.http_client.get("/text_messages/{id}".format(id=id))
return text_message | python | def retrieve(self, id) :
"""
Retrieve a single text message
Returns a single text message according to the unique ID provided
If the specified user does not exist, this query returns an error
:calls: ``get /text_messages/{id}``
:param int id: Unique identifier of a TextMessage.
:return: Dictionary that support attriubte-style access and represent TextMessage resource.
:rtype: dict
"""
_, _, text_message = self.http_client.get("/text_messages/{id}".format(id=id))
return text_message | [
"def",
"retrieve",
"(",
"self",
",",
"id",
")",
":",
"_",
",",
"_",
",",
"text_message",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/text_messages/{id}\"",
".",
"format",
"(",
"id",
"=",
"id",
")",
")",
"return",
"text_message"
] | Retrieve a single text message
Returns a single text message according to the unique ID provided
If the specified user does not exist, this query returns an error
:calls: ``get /text_messages/{id}``
:param int id: Unique identifier of a TextMessage.
:return: Dictionary that support attriubte-style access and represent TextMessage resource.
:rtype: dict | [
"Retrieve",
"a",
"single",
"text",
"message"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L1984-L1998 | train |
basecrm/basecrm-python | basecrm/services.py | UsersService.list | def list(self, **params):
"""
Retrieve all users
Returns all users, according to the parameters provided
:calls: ``get /users``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Users.
:rtype: list
"""
_, _, users = self.http_client.get("/users", params=params)
return users | python | def list(self, **params):
"""
Retrieve all users
Returns all users, according to the parameters provided
:calls: ``get /users``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Users.
:rtype: list
"""
_, _, users = self.http_client.get("/users", params=params)
return users | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"users",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/users\"",
",",
"params",
"=",
"params",
")",
"return",
"users"
] | Retrieve all users
Returns all users, according to the parameters provided
:calls: ``get /users``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Users.
:rtype: list | [
"Retrieve",
"all",
"users"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L2021-L2034 | train |
basecrm/basecrm-python | basecrm/services.py | UsersService.retrieve | def retrieve(self, id) :
"""
Retrieve a single user
Returns a single user according to the unique user ID provided
If the specified user does not exist, this query returns an error
:calls: ``get /users/{id}``
:param int id: Unique identifier of a User.
:return: Dictionary that support attriubte-style access and represent User resource.
:rtype: dict
"""
_, _, user = self.http_client.get("/users/{id}".format(id=id))
return user | python | def retrieve(self, id) :
"""
Retrieve a single user
Returns a single user according to the unique user ID provided
If the specified user does not exist, this query returns an error
:calls: ``get /users/{id}``
:param int id: Unique identifier of a User.
:return: Dictionary that support attriubte-style access and represent User resource.
:rtype: dict
"""
_, _, user = self.http_client.get("/users/{id}".format(id=id))
return user | [
"def",
"retrieve",
"(",
"self",
",",
"id",
")",
":",
"_",
",",
"_",
",",
"user",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/users/{id}\"",
".",
"format",
"(",
"id",
"=",
"id",
")",
")",
"return",
"user"
] | Retrieve a single user
Returns a single user according to the unique user ID provided
If the specified user does not exist, this query returns an error
:calls: ``get /users/{id}``
:param int id: Unique identifier of a User.
:return: Dictionary that support attriubte-style access and represent User resource.
:rtype: dict | [
"Retrieve",
"a",
"single",
"user"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L2036-L2050 | train |
basecrm/basecrm-python | basecrm/services.py | VisitOutcomesService.list | def list(self, **params):
"""
Retrieve visit outcomes
Returns Visit Outcomes, according to the parameters provided
:calls: ``get /visit_outcomes``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of VisitOutcomes.
:rtype: list
"""
_, _, visit_outcomes = self.http_client.get("/visit_outcomes", params=params)
return visit_outcomes | python | def list(self, **params):
"""
Retrieve visit outcomes
Returns Visit Outcomes, according to the parameters provided
:calls: ``get /visit_outcomes``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of VisitOutcomes.
:rtype: list
"""
_, _, visit_outcomes = self.http_client.get("/visit_outcomes", params=params)
return visit_outcomes | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"visit_outcomes",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/visit_outcomes\"",
",",
"params",
"=",
"params",
")",
"return",
"visit_outcomes"
] | Retrieve visit outcomes
Returns Visit Outcomes, according to the parameters provided
:calls: ``get /visit_outcomes``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of VisitOutcomes.
:rtype: list | [
"Retrieve",
"visit",
"outcomes"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L2122-L2135 | train |
jalmeroth/pymusiccast | pymusiccast/helpers.py | request | def request(url, *args, **kwargs):
"""Do the HTTP Request and return data"""
method = kwargs.get('method', 'GET')
timeout = kwargs.pop('timeout', 10) # hass default timeout
req = requests.request(method, url, *args, timeout=timeout, **kwargs)
data = req.json()
_LOGGER.debug(json.dumps(data))
return data | python | def request(url, *args, **kwargs):
"""Do the HTTP Request and return data"""
method = kwargs.get('method', 'GET')
timeout = kwargs.pop('timeout', 10) # hass default timeout
req = requests.request(method, url, *args, timeout=timeout, **kwargs)
data = req.json()
_LOGGER.debug(json.dumps(data))
return data | [
"def",
"request",
"(",
"url",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"method",
"=",
"kwargs",
".",
"get",
"(",
"'method'",
",",
"'GET'",
")",
"timeout",
"=",
"kwargs",
".",
"pop",
"(",
"'timeout'",
",",
"10",
")",
"# hass default timeout",
"req",
"=",
"requests",
".",
"request",
"(",
"method",
",",
"url",
",",
"*",
"args",
",",
"timeout",
"=",
"timeout",
",",
"*",
"*",
"kwargs",
")",
"data",
"=",
"req",
".",
"json",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"return",
"data"
] | Do the HTTP Request and return data | [
"Do",
"the",
"HTTP",
"Request",
"and",
"return",
"data"
] | 616379ae22d6b518c61042d58be6d18a46242168 | https://github.com/jalmeroth/pymusiccast/blob/616379ae22d6b518c61042d58be6d18a46242168/pymusiccast/helpers.py#L10-L17 | train |
jalmeroth/pymusiccast | pymusiccast/helpers.py | message_worker | def message_worker(device):
"""Loop through messages and pass them on to right device"""
_LOGGER.debug("Starting Worker Thread.")
msg_q = device.messages
while True:
if not msg_q.empty():
message = msg_q.get()
data = {}
try:
data = json.loads(message.decode("utf-8"))
except ValueError:
_LOGGER.error("Received invalid message: %s", message)
if 'device_id' in data:
device_id = data.get('device_id')
if device_id == device.device_id:
device.handle_event(data)
else:
_LOGGER.warning("Received message for unknown device.")
msg_q.task_done()
time.sleep(0.2) | python | def message_worker(device):
"""Loop through messages and pass them on to right device"""
_LOGGER.debug("Starting Worker Thread.")
msg_q = device.messages
while True:
if not msg_q.empty():
message = msg_q.get()
data = {}
try:
data = json.loads(message.decode("utf-8"))
except ValueError:
_LOGGER.error("Received invalid message: %s", message)
if 'device_id' in data:
device_id = data.get('device_id')
if device_id == device.device_id:
device.handle_event(data)
else:
_LOGGER.warning("Received message for unknown device.")
msg_q.task_done()
time.sleep(0.2) | [
"def",
"message_worker",
"(",
"device",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Starting Worker Thread.\"",
")",
"msg_q",
"=",
"device",
".",
"messages",
"while",
"True",
":",
"if",
"not",
"msg_q",
".",
"empty",
"(",
")",
":",
"message",
"=",
"msg_q",
".",
"get",
"(",
")",
"data",
"=",
"{",
"}",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"message",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"except",
"ValueError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Received invalid message: %s\"",
",",
"message",
")",
"if",
"'device_id'",
"in",
"data",
":",
"device_id",
"=",
"data",
".",
"get",
"(",
"'device_id'",
")",
"if",
"device_id",
"==",
"device",
".",
"device_id",
":",
"device",
".",
"handle_event",
"(",
"data",
")",
"else",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Received message for unknown device.\"",
")",
"msg_q",
".",
"task_done",
"(",
")",
"time",
".",
"sleep",
"(",
"0.2",
")"
] | Loop through messages and pass them on to right device | [
"Loop",
"through",
"messages",
"and",
"pass",
"them",
"on",
"to",
"right",
"device"
] | 616379ae22d6b518c61042d58be6d18a46242168 | https://github.com/jalmeroth/pymusiccast/blob/616379ae22d6b518c61042d58be6d18a46242168/pymusiccast/helpers.py#L20-L44 | train |
jalmeroth/pymusiccast | pymusiccast/helpers.py | socket_worker | def socket_worker(sock, msg_q):
"""Socket Loop that fills message queue"""
_LOGGER.debug("Starting Socket Thread.")
while True:
try:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
except OSError as err:
_LOGGER.error(err)
else:
_LOGGER.debug("received message: %s from %s", data, addr)
msg_q.put(data)
time.sleep(0.2) | python | def socket_worker(sock, msg_q):
"""Socket Loop that fills message queue"""
_LOGGER.debug("Starting Socket Thread.")
while True:
try:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
except OSError as err:
_LOGGER.error(err)
else:
_LOGGER.debug("received message: %s from %s", data, addr)
msg_q.put(data)
time.sleep(0.2) | [
"def",
"socket_worker",
"(",
"sock",
",",
"msg_q",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Starting Socket Thread.\"",
")",
"while",
"True",
":",
"try",
":",
"data",
",",
"addr",
"=",
"sock",
".",
"recvfrom",
"(",
"1024",
")",
"# buffer size is 1024 bytes",
"except",
"OSError",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"err",
")",
"else",
":",
"_LOGGER",
".",
"debug",
"(",
"\"received message: %s from %s\"",
",",
"data",
",",
"addr",
")",
"msg_q",
".",
"put",
"(",
"data",
")",
"time",
".",
"sleep",
"(",
"0.2",
")"
] | Socket Loop that fills message queue | [
"Socket",
"Loop",
"that",
"fills",
"message",
"queue"
] | 616379ae22d6b518c61042d58be6d18a46242168 | https://github.com/jalmeroth/pymusiccast/blob/616379ae22d6b518c61042d58be6d18a46242168/pymusiccast/helpers.py#L47-L58 | train |
inveniosoftware-contrib/json-merger | json_merger/graph_builder.py | toposort | def toposort(graph, pick_first='head'):
"""Toplogically sorts a list match graph.
Tries to perform a topological sort using as tiebreaker the pick_first
argument. If the graph contains cycles, raise ValueError.
"""
in_deg = {}
for node, next_nodes in six.iteritems(graph):
for next_node in [next_nodes.head_node, next_nodes.update_node]:
if next_node is None:
continue
in_deg[next_node] = in_deg.get(next_node, 0) + 1
stk = [FIRST]
ordered = []
visited = set()
while stk:
node = stk.pop()
visited.add(node)
if node != FIRST:
ordered.append(node)
traversal = _get_traversal(graph.get(node, BeforeNodes()), pick_first)
for next_node in traversal:
if next_node is None:
continue
if next_node in visited:
raise ValueError('Graph has a cycle')
in_deg[next_node] -= 1
if in_deg[next_node] == 0:
stk.append(next_node)
# Nodes may not be walked because they don't reach in degree 0.
if len(ordered) != len(graph) - 1:
raise ValueError('Graph has a cycle')
return ordered | python | def toposort(graph, pick_first='head'):
"""Toplogically sorts a list match graph.
Tries to perform a topological sort using as tiebreaker the pick_first
argument. If the graph contains cycles, raise ValueError.
"""
in_deg = {}
for node, next_nodes in six.iteritems(graph):
for next_node in [next_nodes.head_node, next_nodes.update_node]:
if next_node is None:
continue
in_deg[next_node] = in_deg.get(next_node, 0) + 1
stk = [FIRST]
ordered = []
visited = set()
while stk:
node = stk.pop()
visited.add(node)
if node != FIRST:
ordered.append(node)
traversal = _get_traversal(graph.get(node, BeforeNodes()), pick_first)
for next_node in traversal:
if next_node is None:
continue
if next_node in visited:
raise ValueError('Graph has a cycle')
in_deg[next_node] -= 1
if in_deg[next_node] == 0:
stk.append(next_node)
# Nodes may not be walked because they don't reach in degree 0.
if len(ordered) != len(graph) - 1:
raise ValueError('Graph has a cycle')
return ordered | [
"def",
"toposort",
"(",
"graph",
",",
"pick_first",
"=",
"'head'",
")",
":",
"in_deg",
"=",
"{",
"}",
"for",
"node",
",",
"next_nodes",
"in",
"six",
".",
"iteritems",
"(",
"graph",
")",
":",
"for",
"next_node",
"in",
"[",
"next_nodes",
".",
"head_node",
",",
"next_nodes",
".",
"update_node",
"]",
":",
"if",
"next_node",
"is",
"None",
":",
"continue",
"in_deg",
"[",
"next_node",
"]",
"=",
"in_deg",
".",
"get",
"(",
"next_node",
",",
"0",
")",
"+",
"1",
"stk",
"=",
"[",
"FIRST",
"]",
"ordered",
"=",
"[",
"]",
"visited",
"=",
"set",
"(",
")",
"while",
"stk",
":",
"node",
"=",
"stk",
".",
"pop",
"(",
")",
"visited",
".",
"add",
"(",
"node",
")",
"if",
"node",
"!=",
"FIRST",
":",
"ordered",
".",
"append",
"(",
"node",
")",
"traversal",
"=",
"_get_traversal",
"(",
"graph",
".",
"get",
"(",
"node",
",",
"BeforeNodes",
"(",
")",
")",
",",
"pick_first",
")",
"for",
"next_node",
"in",
"traversal",
":",
"if",
"next_node",
"is",
"None",
":",
"continue",
"if",
"next_node",
"in",
"visited",
":",
"raise",
"ValueError",
"(",
"'Graph has a cycle'",
")",
"in_deg",
"[",
"next_node",
"]",
"-=",
"1",
"if",
"in_deg",
"[",
"next_node",
"]",
"==",
"0",
":",
"stk",
".",
"append",
"(",
"next_node",
")",
"# Nodes may not be walked because they don't reach in degree 0.",
"if",
"len",
"(",
"ordered",
")",
"!=",
"len",
"(",
"graph",
")",
"-",
"1",
":",
"raise",
"ValueError",
"(",
"'Graph has a cycle'",
")",
"return",
"ordered"
] | Toplogically sorts a list match graph.
Tries to perform a topological sort using as tiebreaker the pick_first
argument. If the graph contains cycles, raise ValueError. | [
"Toplogically",
"sorts",
"a",
"list",
"match",
"graph",
"."
] | adc6d372da018427e1db7b92424d3471e01a4118 | https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/graph_builder.py#L231-L266 | train |
inveniosoftware-contrib/json-merger | json_merger/graph_builder.py | sort_cyclic_graph_best_effort | def sort_cyclic_graph_best_effort(graph, pick_first='head'):
"""Fallback for cases in which the graph has cycles."""
ordered = []
visited = set()
# Go first on the pick_first chain then go back again on the others
# that were not visited. Given the way the graph is built both chains
# will always contain all the elements.
if pick_first == 'head':
fst_attr, snd_attr = ('head_node', 'update_node')
else:
fst_attr, snd_attr = ('update_node', 'head_node')
current = FIRST
while current is not None:
visited.add(current)
current = getattr(graph[current], fst_attr)
if current not in visited and current is not None:
ordered.append(current)
current = FIRST
while current is not None:
visited.add(current)
current = getattr(graph[current], snd_attr)
if current not in visited and current is not None:
ordered.append(current)
return ordered | python | def sort_cyclic_graph_best_effort(graph, pick_first='head'):
"""Fallback for cases in which the graph has cycles."""
ordered = []
visited = set()
# Go first on the pick_first chain then go back again on the others
# that were not visited. Given the way the graph is built both chains
# will always contain all the elements.
if pick_first == 'head':
fst_attr, snd_attr = ('head_node', 'update_node')
else:
fst_attr, snd_attr = ('update_node', 'head_node')
current = FIRST
while current is not None:
visited.add(current)
current = getattr(graph[current], fst_attr)
if current not in visited and current is not None:
ordered.append(current)
current = FIRST
while current is not None:
visited.add(current)
current = getattr(graph[current], snd_attr)
if current not in visited and current is not None:
ordered.append(current)
return ordered | [
"def",
"sort_cyclic_graph_best_effort",
"(",
"graph",
",",
"pick_first",
"=",
"'head'",
")",
":",
"ordered",
"=",
"[",
"]",
"visited",
"=",
"set",
"(",
")",
"# Go first on the pick_first chain then go back again on the others",
"# that were not visited. Given the way the graph is built both chains",
"# will always contain all the elements.",
"if",
"pick_first",
"==",
"'head'",
":",
"fst_attr",
",",
"snd_attr",
"=",
"(",
"'head_node'",
",",
"'update_node'",
")",
"else",
":",
"fst_attr",
",",
"snd_attr",
"=",
"(",
"'update_node'",
",",
"'head_node'",
")",
"current",
"=",
"FIRST",
"while",
"current",
"is",
"not",
"None",
":",
"visited",
".",
"add",
"(",
"current",
")",
"current",
"=",
"getattr",
"(",
"graph",
"[",
"current",
"]",
",",
"fst_attr",
")",
"if",
"current",
"not",
"in",
"visited",
"and",
"current",
"is",
"not",
"None",
":",
"ordered",
".",
"append",
"(",
"current",
")",
"current",
"=",
"FIRST",
"while",
"current",
"is",
"not",
"None",
":",
"visited",
".",
"add",
"(",
"current",
")",
"current",
"=",
"getattr",
"(",
"graph",
"[",
"current",
"]",
",",
"snd_attr",
")",
"if",
"current",
"not",
"in",
"visited",
"and",
"current",
"is",
"not",
"None",
":",
"ordered",
".",
"append",
"(",
"current",
")",
"return",
"ordered"
] | Fallback for cases in which the graph has cycles. | [
"Fallback",
"for",
"cases",
"in",
"which",
"the",
"graph",
"has",
"cycles",
"."
] | adc6d372da018427e1db7b92424d3471e01a4118 | https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/graph_builder.py#L269-L293 | train |
ellethee/argparseinator | examples/httprequest.py | get | def get(url):
"""Retrieve an url."""
writeln("Getting data from url", url)
response = requests.get(url)
if response.status_code == 200:
writeln(response.text)
else:
writeln(str(response.status_code), response.reason) | python | def get(url):
"""Retrieve an url."""
writeln("Getting data from url", url)
response = requests.get(url)
if response.status_code == 200:
writeln(response.text)
else:
writeln(str(response.status_code), response.reason) | [
"def",
"get",
"(",
"url",
")",
":",
"writeln",
"(",
"\"Getting data from url\"",
",",
"url",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"writeln",
"(",
"response",
".",
"text",
")",
"else",
":",
"writeln",
"(",
"str",
"(",
"response",
".",
"status_code",
")",
",",
"response",
".",
"reason",
")"
] | Retrieve an url. | [
"Retrieve",
"an",
"url",
"."
] | 05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e | https://github.com/ellethee/argparseinator/blob/05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e/examples/httprequest.py#L11-L18 | train |
ellethee/argparseinator | examples/httprequest.py | post | def post(url, var):
"""Post data to an url."""
data = {b[0]: b[1] for b in [a.split("=") for a in var]}
writeln("Sending data to url", url)
response = requests.post(url, data=data)
if response.status_code == 200:
writeln(response.text)
else:
writeln(str(response.status_code), response.reason) | python | def post(url, var):
"""Post data to an url."""
data = {b[0]: b[1] for b in [a.split("=") for a in var]}
writeln("Sending data to url", url)
response = requests.post(url, data=data)
if response.status_code == 200:
writeln(response.text)
else:
writeln(str(response.status_code), response.reason) | [
"def",
"post",
"(",
"url",
",",
"var",
")",
":",
"data",
"=",
"{",
"b",
"[",
"0",
"]",
":",
"b",
"[",
"1",
"]",
"for",
"b",
"in",
"[",
"a",
".",
"split",
"(",
"\"=\"",
")",
"for",
"a",
"in",
"var",
"]",
"}",
"writeln",
"(",
"\"Sending data to url\"",
",",
"url",
")",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"data",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"writeln",
"(",
"response",
".",
"text",
")",
"else",
":",
"writeln",
"(",
"str",
"(",
"response",
".",
"status_code",
")",
",",
"response",
".",
"reason",
")"
] | Post data to an url. | [
"Post",
"data",
"to",
"an",
"url",
"."
] | 05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e | https://github.com/ellethee/argparseinator/blob/05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e/examples/httprequest.py#L23-L31 | train |
eleme/meepo | meepo/utils.py | cast_bytes | def cast_bytes(s, encoding='utf8', errors='strict'):
"""cast str or bytes to bytes"""
if isinstance(s, bytes):
return s
elif isinstance(s, str):
return s.encode(encoding, errors)
else:
raise TypeError("Expected unicode or bytes, got %r" % s) | python | def cast_bytes(s, encoding='utf8', errors='strict'):
"""cast str or bytes to bytes"""
if isinstance(s, bytes):
return s
elif isinstance(s, str):
return s.encode(encoding, errors)
else:
raise TypeError("Expected unicode or bytes, got %r" % s) | [
"def",
"cast_bytes",
"(",
"s",
",",
"encoding",
"=",
"'utf8'",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"return",
"s",
"elif",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"return",
"s",
".",
"encode",
"(",
"encoding",
",",
"errors",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Expected unicode or bytes, got %r\"",
"%",
"s",
")"
] | cast str or bytes to bytes | [
"cast",
"str",
"or",
"bytes",
"to",
"bytes"
] | 8212f0fe9b1d44be0c5de72d221a31c1d24bfe7a | https://github.com/eleme/meepo/blob/8212f0fe9b1d44be0c5de72d221a31c1d24bfe7a/meepo/utils.py#L46-L53 | train |
eleme/meepo | meepo/utils.py | cast_str | def cast_str(s, encoding='utf8', errors='strict'):
"""cast bytes or str to str"""
if isinstance(s, bytes):
return s.decode(encoding, errors)
elif isinstance(s, str):
return s
else:
raise TypeError("Expected unicode or bytes, got %r" % s) | python | def cast_str(s, encoding='utf8', errors='strict'):
"""cast bytes or str to str"""
if isinstance(s, bytes):
return s.decode(encoding, errors)
elif isinstance(s, str):
return s
else:
raise TypeError("Expected unicode or bytes, got %r" % s) | [
"def",
"cast_str",
"(",
"s",
",",
"encoding",
"=",
"'utf8'",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"return",
"s",
".",
"decode",
"(",
"encoding",
",",
"errors",
")",
"elif",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"return",
"s",
"else",
":",
"raise",
"TypeError",
"(",
"\"Expected unicode or bytes, got %r\"",
"%",
"s",
")"
] | cast bytes or str to str | [
"cast",
"bytes",
"or",
"str",
"to",
"str"
] | 8212f0fe9b1d44be0c5de72d221a31c1d24bfe7a | https://github.com/eleme/meepo/blob/8212f0fe9b1d44be0c5de72d221a31c1d24bfe7a/meepo/utils.py#L57-L64 | train |
eleme/meepo | meepo/utils.py | cast_datetime | def cast_datetime(ts, fmt=None):
"""cast timestamp to datetime or date str"""
dt = datetime.datetime.fromtimestamp(ts)
if fmt:
return dt.strftime(fmt)
return dt | python | def cast_datetime(ts, fmt=None):
"""cast timestamp to datetime or date str"""
dt = datetime.datetime.fromtimestamp(ts)
if fmt:
return dt.strftime(fmt)
return dt | [
"def",
"cast_datetime",
"(",
"ts",
",",
"fmt",
"=",
"None",
")",
":",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"ts",
")",
"if",
"fmt",
":",
"return",
"dt",
".",
"strftime",
"(",
"fmt",
")",
"return",
"dt"
] | cast timestamp to datetime or date str | [
"cast",
"timestamp",
"to",
"datetime",
"or",
"date",
"str"
] | 8212f0fe9b1d44be0c5de72d221a31c1d24bfe7a | https://github.com/eleme/meepo/blob/8212f0fe9b1d44be0c5de72d221a31c1d24bfe7a/meepo/utils.py#L68-L73 | train |
thautwarm/Redy | Redy/Magic/Classic.py | singleton_init_by | def singleton_init_by(init_fn=None):
"""
>>> from Redy.Magic.Classic import singleton
>>> @singleton
>>> class S:
>>> pass
>>> assert isinstance(S, S)
"""
if not init_fn:
def wrap_init(origin_init):
return origin_init
else:
def wrap_init(origin_init):
def __init__(self):
origin_init(self)
init_fn(self)
return __init__
def inner(cls_def: type):
if not hasattr(cls_def, '__instancecheck__') or isinstance(cls_def.__instancecheck__,
(types.BuiltinMethodType, _slot_wrapper)):
def __instancecheck__(self, instance):
return instance is self
cls_def.__instancecheck__ = __instancecheck__
_origin_init = cls_def.__init__
cls_def.__init__ = wrap_init(_origin_init)
return cls_def()
return inner | python | def singleton_init_by(init_fn=None):
"""
>>> from Redy.Magic.Classic import singleton
>>> @singleton
>>> class S:
>>> pass
>>> assert isinstance(S, S)
"""
if not init_fn:
def wrap_init(origin_init):
return origin_init
else:
def wrap_init(origin_init):
def __init__(self):
origin_init(self)
init_fn(self)
return __init__
def inner(cls_def: type):
if not hasattr(cls_def, '__instancecheck__') or isinstance(cls_def.__instancecheck__,
(types.BuiltinMethodType, _slot_wrapper)):
def __instancecheck__(self, instance):
return instance is self
cls_def.__instancecheck__ = __instancecheck__
_origin_init = cls_def.__init__
cls_def.__init__ = wrap_init(_origin_init)
return cls_def()
return inner | [
"def",
"singleton_init_by",
"(",
"init_fn",
"=",
"None",
")",
":",
"if",
"not",
"init_fn",
":",
"def",
"wrap_init",
"(",
"origin_init",
")",
":",
"return",
"origin_init",
"else",
":",
"def",
"wrap_init",
"(",
"origin_init",
")",
":",
"def",
"__init__",
"(",
"self",
")",
":",
"origin_init",
"(",
"self",
")",
"init_fn",
"(",
"self",
")",
"return",
"__init__",
"def",
"inner",
"(",
"cls_def",
":",
"type",
")",
":",
"if",
"not",
"hasattr",
"(",
"cls_def",
",",
"'__instancecheck__'",
")",
"or",
"isinstance",
"(",
"cls_def",
".",
"__instancecheck__",
",",
"(",
"types",
".",
"BuiltinMethodType",
",",
"_slot_wrapper",
")",
")",
":",
"def",
"__instancecheck__",
"(",
"self",
",",
"instance",
")",
":",
"return",
"instance",
"is",
"self",
"cls_def",
".",
"__instancecheck__",
"=",
"__instancecheck__",
"_origin_init",
"=",
"cls_def",
".",
"__init__",
"cls_def",
".",
"__init__",
"=",
"wrap_init",
"(",
"_origin_init",
")",
"return",
"cls_def",
"(",
")",
"return",
"inner"
] | >>> from Redy.Magic.Classic import singleton
>>> @singleton
>>> class S:
>>> pass
>>> assert isinstance(S, S) | [
">>>",
"from",
"Redy",
".",
"Magic",
".",
"Classic",
"import",
"singleton",
">>>"
] | 8beee5c5f752edfd2754bb1e6b5f4acb016a7770 | https://github.com/thautwarm/Redy/blob/8beee5c5f752edfd2754bb1e6b5f4acb016a7770/Redy/Magic/Classic.py#L18-L51 | train |
thautwarm/Redy | Redy/Magic/Classic.py | const_return | def const_return(func):
"""
>>> from Redy.Magic.Classic import const_return
>>> @const_return
>>> def f(x):
>>> return x
>>> r1 = f(1)
>>> assert r1 is 1 and r1 is f(2)
"""
result = _undef
def ret_call(*args, **kwargs):
nonlocal result
if result is _undef:
result = func(*args, **kwargs)
return result
return ret_call | python | def const_return(func):
"""
>>> from Redy.Magic.Classic import const_return
>>> @const_return
>>> def f(x):
>>> return x
>>> r1 = f(1)
>>> assert r1 is 1 and r1 is f(2)
"""
result = _undef
def ret_call(*args, **kwargs):
nonlocal result
if result is _undef:
result = func(*args, **kwargs)
return result
return ret_call | [
"def",
"const_return",
"(",
"func",
")",
":",
"result",
"=",
"_undef",
"def",
"ret_call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"nonlocal",
"result",
"if",
"result",
"is",
"_undef",
":",
"result",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"result",
"return",
"ret_call"
] | >>> from Redy.Magic.Classic import const_return
>>> @const_return
>>> def f(x):
>>> return x
>>> r1 = f(1)
>>> assert r1 is 1 and r1 is f(2) | [
">>>",
"from",
"Redy",
".",
"Magic",
".",
"Classic",
"import",
"const_return",
">>>"
] | 8beee5c5f752edfd2754bb1e6b5f4acb016a7770 | https://github.com/thautwarm/Redy/blob/8beee5c5f752edfd2754bb1e6b5f4acb016a7770/Redy/Magic/Classic.py#L57-L74 | train |
thautwarm/Redy | Redy/Magic/Classic.py | execute | def execute(func: types.FunctionType):
"""
>>> from Redy.Magic.Classic import execute
>>> x = 1
>>> @execute
>>> def f(x = x) -> int:
>>> return x + 1
>>> assert f is 2
"""
spec = getfullargspec(func)
default = spec.defaults
arg_cursor = 0
def get_item(name):
nonlocal arg_cursor
ctx = func.__globals__
value = ctx.get(name, _undef)
if value is _undef:
try:
value = default[arg_cursor]
arg_cursor += 1
except (TypeError, IndexError):
raise ValueError(f"Current context has no variable `{name}`")
return value
return func(*(get_item(arg_name) for arg_name in spec.args)) | python | def execute(func: types.FunctionType):
"""
>>> from Redy.Magic.Classic import execute
>>> x = 1
>>> @execute
>>> def f(x = x) -> int:
>>> return x + 1
>>> assert f is 2
"""
spec = getfullargspec(func)
default = spec.defaults
arg_cursor = 0
def get_item(name):
nonlocal arg_cursor
ctx = func.__globals__
value = ctx.get(name, _undef)
if value is _undef:
try:
value = default[arg_cursor]
arg_cursor += 1
except (TypeError, IndexError):
raise ValueError(f"Current context has no variable `{name}`")
return value
return func(*(get_item(arg_name) for arg_name in spec.args)) | [
"def",
"execute",
"(",
"func",
":",
"types",
".",
"FunctionType",
")",
":",
"spec",
"=",
"getfullargspec",
"(",
"func",
")",
"default",
"=",
"spec",
".",
"defaults",
"arg_cursor",
"=",
"0",
"def",
"get_item",
"(",
"name",
")",
":",
"nonlocal",
"arg_cursor",
"ctx",
"=",
"func",
".",
"__globals__",
"value",
"=",
"ctx",
".",
"get",
"(",
"name",
",",
"_undef",
")",
"if",
"value",
"is",
"_undef",
":",
"try",
":",
"value",
"=",
"default",
"[",
"arg_cursor",
"]",
"arg_cursor",
"+=",
"1",
"except",
"(",
"TypeError",
",",
"IndexError",
")",
":",
"raise",
"ValueError",
"(",
"f\"Current context has no variable `{name}`\"",
")",
"return",
"value",
"return",
"func",
"(",
"*",
"(",
"get_item",
"(",
"arg_name",
")",
"for",
"arg_name",
"in",
"spec",
".",
"args",
")",
")"
] | >>> from Redy.Magic.Classic import execute
>>> x = 1
>>> @execute
>>> def f(x = x) -> int:
>>> return x + 1
>>> assert f is 2 | [
">>>",
"from",
"Redy",
".",
"Magic",
".",
"Classic",
"import",
"execute",
">>>",
"x",
"=",
"1",
">>>"
] | 8beee5c5f752edfd2754bb1e6b5f4acb016a7770 | https://github.com/thautwarm/Redy/blob/8beee5c5f752edfd2754bb1e6b5f4acb016a7770/Redy/Magic/Classic.py#L77-L102 | train |
thautwarm/Redy | Redy/Magic/Classic.py | cast | def cast(cast_fn):
"""
>>> from Redy.Magic.Classic import cast
>>> @cast(list)
>>> def f(x):
>>> for each in x:
>>> if each % 2:
>>> continue
>>> yield each
"""
def inner(func):
def call(*args, **kwargs):
return cast_fn(func(*args, **kwargs))
functools.update_wrapper(call, func)
return call
return inner | python | def cast(cast_fn):
"""
>>> from Redy.Magic.Classic import cast
>>> @cast(list)
>>> def f(x):
>>> for each in x:
>>> if each % 2:
>>> continue
>>> yield each
"""
def inner(func):
def call(*args, **kwargs):
return cast_fn(func(*args, **kwargs))
functools.update_wrapper(call, func)
return call
return inner | [
"def",
"cast",
"(",
"cast_fn",
")",
":",
"def",
"inner",
"(",
"func",
")",
":",
"def",
"call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cast_fn",
"(",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"functools",
".",
"update_wrapper",
"(",
"call",
",",
"func",
")",
"return",
"call",
"return",
"inner"
] | >>> from Redy.Magic.Classic import cast
>>> @cast(list)
>>> def f(x):
>>> for each in x:
>>> if each % 2:
>>> continue
>>> yield each | [
">>>",
"from",
"Redy",
".",
"Magic",
".",
"Classic",
"import",
"cast",
">>>"
] | 8beee5c5f752edfd2754bb1e6b5f4acb016a7770 | https://github.com/thautwarm/Redy/blob/8beee5c5f752edfd2754bb1e6b5f4acb016a7770/Redy/Magic/Classic.py#L105-L123 | train |
thautwarm/Redy | Redy/Async/Delegate.py | Delegate.insert | def insert(self, action: Action, where: 'Union[int, Delegate.Where]'):
"""
add a new action with specific priority
>>> delegate: Delegate
>>> delegate.insert(lambda task, product, ctx: print(product), where=Delegate.Where.after(lambda action: action.__name__ == 'myfunc'))
the codes above inserts an action after the specific action whose name is 'myfunc'.
"""
if isinstance(where, int):
self.actions.insert(where, action)
return
here = where(self.actions)
self.actions.insert(here, action) | python | def insert(self, action: Action, where: 'Union[int, Delegate.Where]'):
"""
add a new action with specific priority
>>> delegate: Delegate
>>> delegate.insert(lambda task, product, ctx: print(product), where=Delegate.Where.after(lambda action: action.__name__ == 'myfunc'))
the codes above inserts an action after the specific action whose name is 'myfunc'.
"""
if isinstance(where, int):
self.actions.insert(where, action)
return
here = where(self.actions)
self.actions.insert(here, action) | [
"def",
"insert",
"(",
"self",
",",
"action",
":",
"Action",
",",
"where",
":",
"'Union[int, Delegate.Where]'",
")",
":",
"if",
"isinstance",
"(",
"where",
",",
"int",
")",
":",
"self",
".",
"actions",
".",
"insert",
"(",
"where",
",",
"action",
")",
"return",
"here",
"=",
"where",
"(",
"self",
".",
"actions",
")",
"self",
".",
"actions",
".",
"insert",
"(",
"here",
",",
"action",
")"
] | add a new action with specific priority
>>> delegate: Delegate
>>> delegate.insert(lambda task, product, ctx: print(product), where=Delegate.Where.after(lambda action: action.__name__ == 'myfunc'))
the codes above inserts an action after the specific action whose name is 'myfunc'. | [
"add",
"a",
"new",
"action",
"with",
"specific",
"priority"
] | 8beee5c5f752edfd2754bb1e6b5f4acb016a7770 | https://github.com/thautwarm/Redy/blob/8beee5c5f752edfd2754bb1e6b5f4acb016a7770/Redy/Async/Delegate.py#L55-L68 | train |
inveniosoftware-contrib/json-merger | json_merger/dict_merger.py | patch_to_conflict_set | def patch_to_conflict_set(patch):
"""Translates a dictdiffer conflict into a json_merger one."""
patch_type, patched_key, value = patch
if isinstance(patched_key, list):
key_path = tuple(patched_key)
else:
key_path = tuple(k for k in patched_key.split('.') if k)
conflicts = set()
if patch_type == REMOVE:
conflict_type = ConflictType.REMOVE_FIELD
for key, obj in value:
conflicts.add(Conflict(conflict_type, key_path + (key, ), None))
elif patch_type == CHANGE:
conflict_type = ConflictType.SET_FIELD
first_val, second_val = value
conflicts.add(Conflict(conflict_type, key_path, second_val))
elif patch_type == ADD:
conflict_type = ConflictType.SET_FIELD
for key, obj in value:
conflicts.add(Conflict(conflict_type, key_path + (key, ), obj))
return conflicts | python | def patch_to_conflict_set(patch):
"""Translates a dictdiffer conflict into a json_merger one."""
patch_type, patched_key, value = patch
if isinstance(patched_key, list):
key_path = tuple(patched_key)
else:
key_path = tuple(k for k in patched_key.split('.') if k)
conflicts = set()
if patch_type == REMOVE:
conflict_type = ConflictType.REMOVE_FIELD
for key, obj in value:
conflicts.add(Conflict(conflict_type, key_path + (key, ), None))
elif patch_type == CHANGE:
conflict_type = ConflictType.SET_FIELD
first_val, second_val = value
conflicts.add(Conflict(conflict_type, key_path, second_val))
elif patch_type == ADD:
conflict_type = ConflictType.SET_FIELD
for key, obj in value:
conflicts.add(Conflict(conflict_type, key_path + (key, ), obj))
return conflicts | [
"def",
"patch_to_conflict_set",
"(",
"patch",
")",
":",
"patch_type",
",",
"patched_key",
",",
"value",
"=",
"patch",
"if",
"isinstance",
"(",
"patched_key",
",",
"list",
")",
":",
"key_path",
"=",
"tuple",
"(",
"patched_key",
")",
"else",
":",
"key_path",
"=",
"tuple",
"(",
"k",
"for",
"k",
"in",
"patched_key",
".",
"split",
"(",
"'.'",
")",
"if",
"k",
")",
"conflicts",
"=",
"set",
"(",
")",
"if",
"patch_type",
"==",
"REMOVE",
":",
"conflict_type",
"=",
"ConflictType",
".",
"REMOVE_FIELD",
"for",
"key",
",",
"obj",
"in",
"value",
":",
"conflicts",
".",
"add",
"(",
"Conflict",
"(",
"conflict_type",
",",
"key_path",
"+",
"(",
"key",
",",
")",
",",
"None",
")",
")",
"elif",
"patch_type",
"==",
"CHANGE",
":",
"conflict_type",
"=",
"ConflictType",
".",
"SET_FIELD",
"first_val",
",",
"second_val",
"=",
"value",
"conflicts",
".",
"add",
"(",
"Conflict",
"(",
"conflict_type",
",",
"key_path",
",",
"second_val",
")",
")",
"elif",
"patch_type",
"==",
"ADD",
":",
"conflict_type",
"=",
"ConflictType",
".",
"SET_FIELD",
"for",
"key",
",",
"obj",
"in",
"value",
":",
"conflicts",
".",
"add",
"(",
"Conflict",
"(",
"conflict_type",
",",
"key_path",
"+",
"(",
"key",
",",
")",
",",
"obj",
")",
")",
"return",
"conflicts"
] | Translates a dictdiffer conflict into a json_merger one. | [
"Translates",
"a",
"dictdiffer",
"conflict",
"into",
"a",
"json_merger",
"one",
"."
] | adc6d372da018427e1db7b92424d3471e01a4118 | https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/dict_merger.py#L54-L76 | train |
inveniosoftware-contrib/json-merger | json_merger/dict_merger.py | SkipListsMerger.merge | def merge(self):
"""Perform merge of head and update starting from root."""
if isinstance(self.head, dict) and isinstance(self.update, dict):
if not isinstance(self.root, dict):
self.root = {}
self._merge_dicts()
else:
self._merge_base_values()
if self.conflict_set:
raise MergeError('Dictdiffer Errors', self.conflicts) | python | def merge(self):
"""Perform merge of head and update starting from root."""
if isinstance(self.head, dict) and isinstance(self.update, dict):
if not isinstance(self.root, dict):
self.root = {}
self._merge_dicts()
else:
self._merge_base_values()
if self.conflict_set:
raise MergeError('Dictdiffer Errors', self.conflicts) | [
"def",
"merge",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"head",
",",
"dict",
")",
"and",
"isinstance",
"(",
"self",
".",
"update",
",",
"dict",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"root",
",",
"dict",
")",
":",
"self",
".",
"root",
"=",
"{",
"}",
"self",
".",
"_merge_dicts",
"(",
")",
"else",
":",
"self",
".",
"_merge_base_values",
"(",
")",
"if",
"self",
".",
"conflict_set",
":",
"raise",
"MergeError",
"(",
"'Dictdiffer Errors'",
",",
"self",
".",
"conflicts",
")"
] | Perform merge of head and update starting from root. | [
"Perform",
"merge",
"of",
"head",
"and",
"update",
"starting",
"from",
"root",
"."
] | adc6d372da018427e1db7b92424d3471e01a4118 | https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/dict_merger.py#L236-L246 | train |
dpmcmlxxvi/pixelscan | pixelscan/pixelscan.py | chebyshev | def chebyshev(point1, point2):
"""Computes distance between 2D points using chebyshev metric
:param point1: 1st point
:type point1: list
:param point2: 2nd point
:type point2: list
:returns: Distance between point1 and point2
:rtype: float
"""
return max(abs(point1[0] - point2[0]), abs(point1[1] - point2[1])) | python | def chebyshev(point1, point2):
"""Computes distance between 2D points using chebyshev metric
:param point1: 1st point
:type point1: list
:param point2: 2nd point
:type point2: list
:returns: Distance between point1 and point2
:rtype: float
"""
return max(abs(point1[0] - point2[0]), abs(point1[1] - point2[1])) | [
"def",
"chebyshev",
"(",
"point1",
",",
"point2",
")",
":",
"return",
"max",
"(",
"abs",
"(",
"point1",
"[",
"0",
"]",
"-",
"point2",
"[",
"0",
"]",
")",
",",
"abs",
"(",
"point1",
"[",
"1",
"]",
"-",
"point2",
"[",
"1",
"]",
")",
")"
] | Computes distance between 2D points using chebyshev metric
:param point1: 1st point
:type point1: list
:param point2: 2nd point
:type point2: list
:returns: Distance between point1 and point2
:rtype: float | [
"Computes",
"distance",
"between",
"2D",
"points",
"using",
"chebyshev",
"metric"
] | d641207b13a8fc5bf7ac9964b982971652bb0a7e | https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L26-L37 | train |
dpmcmlxxvi/pixelscan | pixelscan/pixelscan.py | circlescan | def circlescan(x0, y0, r1, r2):
"""Scan pixels in a circle pattern around a center point
:param x0: Center x-coordinate
:type x0: float
:param y0: Center y-coordinate
:type y0: float
:param r1: Initial radius
:type r1: float
:param r2: Final radius
:type r2: float
:returns: Coordinate generator
:rtype: function
"""
# Validate inputs
if r1 < 0: raise ValueError("Initial radius must be non-negative")
if r2 < 0: raise ValueError("Final radius must be non-negative")
# List of pixels visited in previous diameter
previous = []
# Scan distances outward (1) or inward (-1)
rstep = 1 if r2 >= r1 else -1
for distance in range(r1, r2 + rstep, rstep):
if distance == 0:
yield x0, y0
else:
# Computes points for first octant and the rotate by multiples of
# 45 degrees to compute the other octants
a = 0.707107
rotations = {0: [[ 1, 0], [ 0, 1]],
1: [[ a, a], [-a, a]],
2: [[ 0, 1], [-1, 0]],
3: [[-a, a], [-a,-a]],
4: [[-1, 0], [ 0,-1]],
5: [[-a,-a], [ a,-a]],
6: [[ 0,-1], [ 1, 0]],
7: [[ a,-a], [ a, a]]}
nangles = len(rotations)
# List of pixels visited in current diameter
current = []
for angle in range(nangles):
x = 0
y = distance
d = 1 - distance
while x < y:
xr = rotations[angle][0][0]*x + rotations[angle][0][1]*y
yr = rotations[angle][1][0]*x + rotations[angle][1][1]*y
xr = x0 + xr
yr = y0 + yr
# First check if point was in previous diameter
# since our scan pattern can lead to duplicates in
# neighboring diameters
point = (int(round(xr)), int(round(yr)))
if point not in previous:
yield xr, yr
current.append(point)
# Move pixel according to circle constraint
if (d < 0):
d += 3 + 2 * x
else:
d += 5 - 2 * (y-x)
y -= 1
x += 1
previous = current | python | def circlescan(x0, y0, r1, r2):
"""Scan pixels in a circle pattern around a center point
:param x0: Center x-coordinate
:type x0: float
:param y0: Center y-coordinate
:type y0: float
:param r1: Initial radius
:type r1: float
:param r2: Final radius
:type r2: float
:returns: Coordinate generator
:rtype: function
"""
# Validate inputs
if r1 < 0: raise ValueError("Initial radius must be non-negative")
if r2 < 0: raise ValueError("Final radius must be non-negative")
# List of pixels visited in previous diameter
previous = []
# Scan distances outward (1) or inward (-1)
rstep = 1 if r2 >= r1 else -1
for distance in range(r1, r2 + rstep, rstep):
if distance == 0:
yield x0, y0
else:
# Computes points for first octant and the rotate by multiples of
# 45 degrees to compute the other octants
a = 0.707107
rotations = {0: [[ 1, 0], [ 0, 1]],
1: [[ a, a], [-a, a]],
2: [[ 0, 1], [-1, 0]],
3: [[-a, a], [-a,-a]],
4: [[-1, 0], [ 0,-1]],
5: [[-a,-a], [ a,-a]],
6: [[ 0,-1], [ 1, 0]],
7: [[ a,-a], [ a, a]]}
nangles = len(rotations)
# List of pixels visited in current diameter
current = []
for angle in range(nangles):
x = 0
y = distance
d = 1 - distance
while x < y:
xr = rotations[angle][0][0]*x + rotations[angle][0][1]*y
yr = rotations[angle][1][0]*x + rotations[angle][1][1]*y
xr = x0 + xr
yr = y0 + yr
# First check if point was in previous diameter
# since our scan pattern can lead to duplicates in
# neighboring diameters
point = (int(round(xr)), int(round(yr)))
if point not in previous:
yield xr, yr
current.append(point)
# Move pixel according to circle constraint
if (d < 0):
d += 3 + 2 * x
else:
d += 5 - 2 * (y-x)
y -= 1
x += 1
previous = current | [
"def",
"circlescan",
"(",
"x0",
",",
"y0",
",",
"r1",
",",
"r2",
")",
":",
"# Validate inputs",
"if",
"r1",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Initial radius must be non-negative\"",
")",
"if",
"r2",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Final radius must be non-negative\"",
")",
"# List of pixels visited in previous diameter",
"previous",
"=",
"[",
"]",
"# Scan distances outward (1) or inward (-1)",
"rstep",
"=",
"1",
"if",
"r2",
">=",
"r1",
"else",
"-",
"1",
"for",
"distance",
"in",
"range",
"(",
"r1",
",",
"r2",
"+",
"rstep",
",",
"rstep",
")",
":",
"if",
"distance",
"==",
"0",
":",
"yield",
"x0",
",",
"y0",
"else",
":",
"# Computes points for first octant and the rotate by multiples of",
"# 45 degrees to compute the other octants",
"a",
"=",
"0.707107",
"rotations",
"=",
"{",
"0",
":",
"[",
"[",
"1",
",",
"0",
"]",
",",
"[",
"0",
",",
"1",
"]",
"]",
",",
"1",
":",
"[",
"[",
"a",
",",
"a",
"]",
",",
"[",
"-",
"a",
",",
"a",
"]",
"]",
",",
"2",
":",
"[",
"[",
"0",
",",
"1",
"]",
",",
"[",
"-",
"1",
",",
"0",
"]",
"]",
",",
"3",
":",
"[",
"[",
"-",
"a",
",",
"a",
"]",
",",
"[",
"-",
"a",
",",
"-",
"a",
"]",
"]",
",",
"4",
":",
"[",
"[",
"-",
"1",
",",
"0",
"]",
",",
"[",
"0",
",",
"-",
"1",
"]",
"]",
",",
"5",
":",
"[",
"[",
"-",
"a",
",",
"-",
"a",
"]",
",",
"[",
"a",
",",
"-",
"a",
"]",
"]",
",",
"6",
":",
"[",
"[",
"0",
",",
"-",
"1",
"]",
",",
"[",
"1",
",",
"0",
"]",
"]",
",",
"7",
":",
"[",
"[",
"a",
",",
"-",
"a",
"]",
",",
"[",
"a",
",",
"a",
"]",
"]",
"}",
"nangles",
"=",
"len",
"(",
"rotations",
")",
"# List of pixels visited in current diameter",
"current",
"=",
"[",
"]",
"for",
"angle",
"in",
"range",
"(",
"nangles",
")",
":",
"x",
"=",
"0",
"y",
"=",
"distance",
"d",
"=",
"1",
"-",
"distance",
"while",
"x",
"<",
"y",
":",
"xr",
"=",
"rotations",
"[",
"angle",
"]",
"[",
"0",
"]",
"[",
"0",
"]",
"*",
"x",
"+",
"rotations",
"[",
"angle",
"]",
"[",
"0",
"]",
"[",
"1",
"]",
"*",
"y",
"yr",
"=",
"rotations",
"[",
"angle",
"]",
"[",
"1",
"]",
"[",
"0",
"]",
"*",
"x",
"+",
"rotations",
"[",
"angle",
"]",
"[",
"1",
"]",
"[",
"1",
"]",
"*",
"y",
"xr",
"=",
"x0",
"+",
"xr",
"yr",
"=",
"y0",
"+",
"yr",
"# First check if point was in previous diameter",
"# since our scan pattern can lead to duplicates in",
"# neighboring diameters",
"point",
"=",
"(",
"int",
"(",
"round",
"(",
"xr",
")",
")",
",",
"int",
"(",
"round",
"(",
"yr",
")",
")",
")",
"if",
"point",
"not",
"in",
"previous",
":",
"yield",
"xr",
",",
"yr",
"current",
".",
"append",
"(",
"point",
")",
"# Move pixel according to circle constraint",
"if",
"(",
"d",
"<",
"0",
")",
":",
"d",
"+=",
"3",
"+",
"2",
"*",
"x",
"else",
":",
"d",
"+=",
"5",
"-",
"2",
"*",
"(",
"y",
"-",
"x",
")",
"y",
"-=",
"1",
"x",
"+=",
"1",
"previous",
"=",
"current"
] | Scan pixels in a circle pattern around a center point
:param x0: Center x-coordinate
:type x0: float
:param y0: Center y-coordinate
:type y0: float
:param r1: Initial radius
:type r1: float
:param r2: Final radius
:type r2: float
:returns: Coordinate generator
:rtype: function | [
"Scan",
"pixels",
"in",
"a",
"circle",
"pattern",
"around",
"a",
"center",
"point"
] | d641207b13a8fc5bf7ac9964b982971652bb0a7e | https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L392-L466 | train |
dpmcmlxxvi/pixelscan | pixelscan/pixelscan.py | gridscan | def gridscan(xi, yi, xf, yf, stepx=1, stepy=1):
"""Scan pixels in a grid pattern along the x-coordinate then y-coordinate
:param xi: Initial x-coordinate
:type xi: int
:param yi: Initial y-coordinate
:type yi: int
:param xf: Final x-coordinate
:type xf: int
:param yf: Final y-coordinate
:type yf: int
:param stepx: Step size in x-coordinate
:type stepx: int
:param stepy: Step size in y-coordinate
:type stepy: int
:returns: Coordinate generator
:rtype: function
"""
if stepx <= 0: raise ValueError("X-step must be positive")
if stepy <= 0: raise ValueError("Y-step must be positive")
# Determine direction to move
dx = stepx if xf >= xi else -stepx
dy = stepy if yf >= yi else -stepy
for y in range(yi, yf + dy, dy):
for x in range(xi, xf + dx, dx):
yield x, y | python | def gridscan(xi, yi, xf, yf, stepx=1, stepy=1):
"""Scan pixels in a grid pattern along the x-coordinate then y-coordinate
:param xi: Initial x-coordinate
:type xi: int
:param yi: Initial y-coordinate
:type yi: int
:param xf: Final x-coordinate
:type xf: int
:param yf: Final y-coordinate
:type yf: int
:param stepx: Step size in x-coordinate
:type stepx: int
:param stepy: Step size in y-coordinate
:type stepy: int
:returns: Coordinate generator
:rtype: function
"""
if stepx <= 0: raise ValueError("X-step must be positive")
if stepy <= 0: raise ValueError("Y-step must be positive")
# Determine direction to move
dx = stepx if xf >= xi else -stepx
dy = stepy if yf >= yi else -stepy
for y in range(yi, yf + dy, dy):
for x in range(xi, xf + dx, dx):
yield x, y | [
"def",
"gridscan",
"(",
"xi",
",",
"yi",
",",
"xf",
",",
"yf",
",",
"stepx",
"=",
"1",
",",
"stepy",
"=",
"1",
")",
":",
"if",
"stepx",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"X-step must be positive\"",
")",
"if",
"stepy",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"Y-step must be positive\"",
")",
"# Determine direction to move",
"dx",
"=",
"stepx",
"if",
"xf",
">=",
"xi",
"else",
"-",
"stepx",
"dy",
"=",
"stepy",
"if",
"yf",
">=",
"yi",
"else",
"-",
"stepy",
"for",
"y",
"in",
"range",
"(",
"yi",
",",
"yf",
"+",
"dy",
",",
"dy",
")",
":",
"for",
"x",
"in",
"range",
"(",
"xi",
",",
"xf",
"+",
"dx",
",",
"dx",
")",
":",
"yield",
"x",
",",
"y"
] | Scan pixels in a grid pattern along the x-coordinate then y-coordinate
:param xi: Initial x-coordinate
:type xi: int
:param yi: Initial y-coordinate
:type yi: int
:param xf: Final x-coordinate
:type xf: int
:param yf: Final y-coordinate
:type yf: int
:param stepx: Step size in x-coordinate
:type stepx: int
:param stepy: Step size in y-coordinate
:type stepy: int
:returns: Coordinate generator
:rtype: function | [
"Scan",
"pixels",
"in",
"a",
"grid",
"pattern",
"along",
"the",
"x",
"-",
"coordinate",
"then",
"y",
"-",
"coordinate"
] | d641207b13a8fc5bf7ac9964b982971652bb0a7e | https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L468-L496 | train |
dpmcmlxxvi/pixelscan | pixelscan/pixelscan.py | ringscan | def ringscan(x0, y0, r1, r2, metric=chebyshev):
"""Scan pixels in a ring pattern around a center point clockwise
:param x0: Center x-coordinate
:type x0: int
:param y0: Center y-coordinate
:type y0: int
:param r1: Initial radius
:type r1: int
:param r2: Final radius
:type r2: int
:param metric: Distance metric
:type metric: function
:returns: Coordinate generator
:rtype: function
"""
# Validate inputs
if r1 < 0: raise ValueError("Initial radius must be non-negative")
if r2 < 0: raise ValueError("Final radius must be non-negative")
if not hasattr(metric, "__call__"): raise TypeError("Metric not callable")
# Define clockwise step directions
direction = 0
steps = {0: [ 1, 0],
1: [ 1,-1],
2: [ 0,-1],
3: [-1,-1],
4: [-1, 0],
5: [-1, 1],
6: [ 0, 1],
7: [ 1, 1]}
nsteps = len(steps)
center = [x0, y0]
# Scan distances outward (1) or inward (-1)
rstep = 1 if r2 >= r1 else -1
for distance in range(r1, r2 + rstep, rstep):
initial = [x0, y0 + distance]
current = initial
# Number of tries to find a valid neighrbor
ntrys = 0
while True:
# Short-circuit special case
if distance == 0:
yield current[0], current[1]
break
# Try and take a step and check if still within distance
nextpoint = [current[i] + steps[direction][i] for i in range(2)]
if metric(center, nextpoint) != distance:
# Check if we tried all step directions and failed
ntrys += 1
if ntrys == nsteps:
break
# Try the next direction
direction = (direction + 1) % nsteps
continue
ntrys = 0
yield current[0], current[1]
# Check if we have come all the way around
current = nextpoint
if current == initial:
break
# Check if we tried all step directions and failed
if ntrys == nsteps:
break | python | def ringscan(x0, y0, r1, r2, metric=chebyshev):
"""Scan pixels in a ring pattern around a center point clockwise
:param x0: Center x-coordinate
:type x0: int
:param y0: Center y-coordinate
:type y0: int
:param r1: Initial radius
:type r1: int
:param r2: Final radius
:type r2: int
:param metric: Distance metric
:type metric: function
:returns: Coordinate generator
:rtype: function
"""
# Validate inputs
if r1 < 0: raise ValueError("Initial radius must be non-negative")
if r2 < 0: raise ValueError("Final radius must be non-negative")
if not hasattr(metric, "__call__"): raise TypeError("Metric not callable")
# Define clockwise step directions
direction = 0
steps = {0: [ 1, 0],
1: [ 1,-1],
2: [ 0,-1],
3: [-1,-1],
4: [-1, 0],
5: [-1, 1],
6: [ 0, 1],
7: [ 1, 1]}
nsteps = len(steps)
center = [x0, y0]
# Scan distances outward (1) or inward (-1)
rstep = 1 if r2 >= r1 else -1
for distance in range(r1, r2 + rstep, rstep):
initial = [x0, y0 + distance]
current = initial
# Number of tries to find a valid neighrbor
ntrys = 0
while True:
# Short-circuit special case
if distance == 0:
yield current[0], current[1]
break
# Try and take a step and check if still within distance
nextpoint = [current[i] + steps[direction][i] for i in range(2)]
if metric(center, nextpoint) != distance:
# Check if we tried all step directions and failed
ntrys += 1
if ntrys == nsteps:
break
# Try the next direction
direction = (direction + 1) % nsteps
continue
ntrys = 0
yield current[0], current[1]
# Check if we have come all the way around
current = nextpoint
if current == initial:
break
# Check if we tried all step directions and failed
if ntrys == nsteps:
break | [
"def",
"ringscan",
"(",
"x0",
",",
"y0",
",",
"r1",
",",
"r2",
",",
"metric",
"=",
"chebyshev",
")",
":",
"# Validate inputs",
"if",
"r1",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Initial radius must be non-negative\"",
")",
"if",
"r2",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Final radius must be non-negative\"",
")",
"if",
"not",
"hasattr",
"(",
"metric",
",",
"\"__call__\"",
")",
":",
"raise",
"TypeError",
"(",
"\"Metric not callable\"",
")",
"# Define clockwise step directions",
"direction",
"=",
"0",
"steps",
"=",
"{",
"0",
":",
"[",
"1",
",",
"0",
"]",
",",
"1",
":",
"[",
"1",
",",
"-",
"1",
"]",
",",
"2",
":",
"[",
"0",
",",
"-",
"1",
"]",
",",
"3",
":",
"[",
"-",
"1",
",",
"-",
"1",
"]",
",",
"4",
":",
"[",
"-",
"1",
",",
"0",
"]",
",",
"5",
":",
"[",
"-",
"1",
",",
"1",
"]",
",",
"6",
":",
"[",
"0",
",",
"1",
"]",
",",
"7",
":",
"[",
"1",
",",
"1",
"]",
"}",
"nsteps",
"=",
"len",
"(",
"steps",
")",
"center",
"=",
"[",
"x0",
",",
"y0",
"]",
"# Scan distances outward (1) or inward (-1)",
"rstep",
"=",
"1",
"if",
"r2",
">=",
"r1",
"else",
"-",
"1",
"for",
"distance",
"in",
"range",
"(",
"r1",
",",
"r2",
"+",
"rstep",
",",
"rstep",
")",
":",
"initial",
"=",
"[",
"x0",
",",
"y0",
"+",
"distance",
"]",
"current",
"=",
"initial",
"# Number of tries to find a valid neighrbor",
"ntrys",
"=",
"0",
"while",
"True",
":",
"# Short-circuit special case",
"if",
"distance",
"==",
"0",
":",
"yield",
"current",
"[",
"0",
"]",
",",
"current",
"[",
"1",
"]",
"break",
"# Try and take a step and check if still within distance",
"nextpoint",
"=",
"[",
"current",
"[",
"i",
"]",
"+",
"steps",
"[",
"direction",
"]",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"2",
")",
"]",
"if",
"metric",
"(",
"center",
",",
"nextpoint",
")",
"!=",
"distance",
":",
"# Check if we tried all step directions and failed",
"ntrys",
"+=",
"1",
"if",
"ntrys",
"==",
"nsteps",
":",
"break",
"# Try the next direction",
"direction",
"=",
"(",
"direction",
"+",
"1",
")",
"%",
"nsteps",
"continue",
"ntrys",
"=",
"0",
"yield",
"current",
"[",
"0",
"]",
",",
"current",
"[",
"1",
"]",
"# Check if we have come all the way around",
"current",
"=",
"nextpoint",
"if",
"current",
"==",
"initial",
":",
"break",
"# Check if we tried all step directions and failed",
"if",
"ntrys",
"==",
"nsteps",
":",
"break"
] | Scan pixels in a ring pattern around a center point clockwise
:param x0: Center x-coordinate
:type x0: int
:param y0: Center y-coordinate
:type y0: int
:param r1: Initial radius
:type r1: int
:param r2: Final radius
:type r2: int
:param metric: Distance metric
:type metric: function
:returns: Coordinate generator
:rtype: function | [
"Scan",
"pixels",
"in",
"a",
"ring",
"pattern",
"around",
"a",
"center",
"point",
"clockwise"
] | d641207b13a8fc5bf7ac9964b982971652bb0a7e | https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L528-L604 | train |
dpmcmlxxvi/pixelscan | pixelscan/pixelscan.py | snakescan | def snakescan(xi, yi, xf, yf):
"""Scan pixels in a snake pattern along the x-coordinate then y-coordinate
:param xi: Initial x-coordinate
:type xi: int
:param yi: Initial y-coordinate
:type yi: int
:param xf: Final x-coordinate
:type xf: int
:param yf: Final y-coordinate
:type yf: int
:returns: Coordinate generator
:rtype: function
"""
# Determine direction to move
dx = 1 if xf >= xi else -1
dy = 1 if yf >= yi else -1
# Scan pixels first along x-coordinate then y-coordinate and flip
# x-direction when the end of the line is reached
x, xa, xb = xi, xi, xf
for y in range(yi, yf + dy, dy):
for x in range(xa, xb + dx, dx):
yield x, y
# Swap x-direction
if x == xa or x == xb:
dx *= -1
xa, xb = xb, xa | python | def snakescan(xi, yi, xf, yf):
"""Scan pixels in a snake pattern along the x-coordinate then y-coordinate
:param xi: Initial x-coordinate
:type xi: int
:param yi: Initial y-coordinate
:type yi: int
:param xf: Final x-coordinate
:type xf: int
:param yf: Final y-coordinate
:type yf: int
:returns: Coordinate generator
:rtype: function
"""
# Determine direction to move
dx = 1 if xf >= xi else -1
dy = 1 if yf >= yi else -1
# Scan pixels first along x-coordinate then y-coordinate and flip
# x-direction when the end of the line is reached
x, xa, xb = xi, xi, xf
for y in range(yi, yf + dy, dy):
for x in range(xa, xb + dx, dx):
yield x, y
# Swap x-direction
if x == xa or x == xb:
dx *= -1
xa, xb = xb, xa | [
"def",
"snakescan",
"(",
"xi",
",",
"yi",
",",
"xf",
",",
"yf",
")",
":",
"# Determine direction to move",
"dx",
"=",
"1",
"if",
"xf",
">=",
"xi",
"else",
"-",
"1",
"dy",
"=",
"1",
"if",
"yf",
">=",
"yi",
"else",
"-",
"1",
"# Scan pixels first along x-coordinate then y-coordinate and flip",
"# x-direction when the end of the line is reached",
"x",
",",
"xa",
",",
"xb",
"=",
"xi",
",",
"xi",
",",
"xf",
"for",
"y",
"in",
"range",
"(",
"yi",
",",
"yf",
"+",
"dy",
",",
"dy",
")",
":",
"for",
"x",
"in",
"range",
"(",
"xa",
",",
"xb",
"+",
"dx",
",",
"dx",
")",
":",
"yield",
"x",
",",
"y",
"# Swap x-direction",
"if",
"x",
"==",
"xa",
"or",
"x",
"==",
"xb",
":",
"dx",
"*=",
"-",
"1",
"xa",
",",
"xb",
"=",
"xb",
",",
"xa"
] | Scan pixels in a snake pattern along the x-coordinate then y-coordinate
:param xi: Initial x-coordinate
:type xi: int
:param yi: Initial y-coordinate
:type yi: int
:param xf: Final x-coordinate
:type xf: int
:param yf: Final y-coordinate
:type yf: int
:returns: Coordinate generator
:rtype: function | [
"Scan",
"pixels",
"in",
"a",
"snake",
"pattern",
"along",
"the",
"x",
"-",
"coordinate",
"then",
"y",
"-",
"coordinate"
] | d641207b13a8fc5bf7ac9964b982971652bb0a7e | https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L606-L635 | train |
dpmcmlxxvi/pixelscan | pixelscan/pixelscan.py | walkscan | def walkscan(x0, y0, xn=0.25, xp=0.25, yn=0.25, yp=0.25):
"""Scan pixels in a random walk pattern with given step probabilities. The
random walk will continue indefinitely unless a skip transformation is used
with the 'stop' parameter set or a clip transformation is used with the
'abort' parameter set to True. The probabilities are normalized to sum to 1.
:param x0: Initial x-coordinate
:type x0: int
:param y0: Initial y-coordinate
:type y0: int
:param xn: Probability of moving in the negative x direction
:type xn: float
:param xp: Probability of moving in the positive x direction
:type xp: float
:param yn: Probability of moving in the negative y direction
:type yn: float
:param yp: Probability of moving in the positive y direction
:type yp: float
"""
# Validate inputs
if xn < 0: raise ValueError("Negative x probabilty must be non-negative")
if xp < 0: raise ValueError("Positive x probabilty must be non-negative")
if yn < 0: raise ValueError("Negative y probabilty must be non-negative")
if yp < 0: raise ValueError("Positive y probabilty must be non-negative")
# Compute normalized probability
total = xp + xn + yp + yn
xn /= total
xp /= total
yn /= total
yp /= total
# Compute cumulative probability
cxn = xn
cxp = cxn + xp
cyn = cxp + yn
# Initialize position
x, y = x0, y0
while True:
yield x, y
# Take random step
probability = random.random()
if probability <= cxn:
x -= 1
elif probability <= cxp:
x += 1
elif probability <= cyn:
y -= 1
else:
y += 1 | python | def walkscan(x0, y0, xn=0.25, xp=0.25, yn=0.25, yp=0.25):
"""Scan pixels in a random walk pattern with given step probabilities. The
random walk will continue indefinitely unless a skip transformation is used
with the 'stop' parameter set or a clip transformation is used with the
'abort' parameter set to True. The probabilities are normalized to sum to 1.
:param x0: Initial x-coordinate
:type x0: int
:param y0: Initial y-coordinate
:type y0: int
:param xn: Probability of moving in the negative x direction
:type xn: float
:param xp: Probability of moving in the positive x direction
:type xp: float
:param yn: Probability of moving in the negative y direction
:type yn: float
:param yp: Probability of moving in the positive y direction
:type yp: float
"""
# Validate inputs
if xn < 0: raise ValueError("Negative x probabilty must be non-negative")
if xp < 0: raise ValueError("Positive x probabilty must be non-negative")
if yn < 0: raise ValueError("Negative y probabilty must be non-negative")
if yp < 0: raise ValueError("Positive y probabilty must be non-negative")
# Compute normalized probability
total = xp + xn + yp + yn
xn /= total
xp /= total
yn /= total
yp /= total
# Compute cumulative probability
cxn = xn
cxp = cxn + xp
cyn = cxp + yn
# Initialize position
x, y = x0, y0
while True:
yield x, y
# Take random step
probability = random.random()
if probability <= cxn:
x -= 1
elif probability <= cxp:
x += 1
elif probability <= cyn:
y -= 1
else:
y += 1 | [
"def",
"walkscan",
"(",
"x0",
",",
"y0",
",",
"xn",
"=",
"0.25",
",",
"xp",
"=",
"0.25",
",",
"yn",
"=",
"0.25",
",",
"yp",
"=",
"0.25",
")",
":",
"# Validate inputs",
"if",
"xn",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Negative x probabilty must be non-negative\"",
")",
"if",
"xp",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Positive x probabilty must be non-negative\"",
")",
"if",
"yn",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Negative y probabilty must be non-negative\"",
")",
"if",
"yp",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Positive y probabilty must be non-negative\"",
")",
"# Compute normalized probability",
"total",
"=",
"xp",
"+",
"xn",
"+",
"yp",
"+",
"yn",
"xn",
"/=",
"total",
"xp",
"/=",
"total",
"yn",
"/=",
"total",
"yp",
"/=",
"total",
"# Compute cumulative probability",
"cxn",
"=",
"xn",
"cxp",
"=",
"cxn",
"+",
"xp",
"cyn",
"=",
"cxp",
"+",
"yn",
"# Initialize position",
"x",
",",
"y",
"=",
"x0",
",",
"y0",
"while",
"True",
":",
"yield",
"x",
",",
"y",
"# Take random step",
"probability",
"=",
"random",
".",
"random",
"(",
")",
"if",
"probability",
"<=",
"cxn",
":",
"x",
"-=",
"1",
"elif",
"probability",
"<=",
"cxp",
":",
"x",
"+=",
"1",
"elif",
"probability",
"<=",
"cyn",
":",
"y",
"-=",
"1",
"else",
":",
"y",
"+=",
"1"
] | Scan pixels in a random walk pattern with given step probabilities. The
random walk will continue indefinitely unless a skip transformation is used
with the 'stop' parameter set or a clip transformation is used with the
'abort' parameter set to True. The probabilities are normalized to sum to 1.
:param x0: Initial x-coordinate
:type x0: int
:param y0: Initial y-coordinate
:type y0: int
:param xn: Probability of moving in the negative x direction
:type xn: float
:param xp: Probability of moving in the positive x direction
:type xp: float
:param yn: Probability of moving in the negative y direction
:type yn: float
:param yp: Probability of moving in the positive y direction
:type yp: float | [
"Scan",
"pixels",
"in",
"a",
"random",
"walk",
"pattern",
"with",
"given",
"step",
"probabilities",
".",
"The",
"random",
"walk",
"will",
"continue",
"indefinitely",
"unless",
"a",
"skip",
"transformation",
"is",
"used",
"with",
"the",
"stop",
"parameter",
"set",
"or",
"a",
"clip",
"transformation",
"is",
"used",
"with",
"the",
"abort",
"parameter",
"set",
"to",
"True",
".",
"The",
"probabilities",
"are",
"normalized",
"to",
"sum",
"to",
"1",
"."
] | d641207b13a8fc5bf7ac9964b982971652bb0a7e | https://github.com/dpmcmlxxvi/pixelscan/blob/d641207b13a8fc5bf7ac9964b982971652bb0a7e/pixelscan/pixelscan.py#L637-L691 | train |
basecrm/basecrm-python | basecrm/configuration.py | Configuration.validate | def validate(self):
"""Validates whether a configuration is valid.
:rtype: bool
:raises ConfigurationError: if no ``access_token`` provided.
:raises ConfigurationError: if provided ``access_token`` is invalid - contains disallowed characters.
:raises ConfigurationError: if provided ``access_token`` is invalid - has invalid length.
:raises ConfigurationError: if provided ``base_url`` is invalid.
"""
if self.access_token is None:
raise ConfigurationError('No access token provided. '
'Set your access token during client initialization using: '
'"basecrm.Client(access_token= <YOUR_PERSONAL_ACCESS_TOKEN>)"')
if re.search(r'\s', self.access_token):
raise ConfigurationError('Provided access token is invalid '
'as it contains disallowed characters. '
'Please double-check you access token.')
if len(self.access_token) != 64:
raise ConfigurationError('Provided access token is invalid '
'as it has invalid length. '
'Please double-check your access token.')
if not self.base_url or not re.match(self.URL_REGEXP, self.base_url):
raise ConfigurationError('Provided base url is invalid '
'as it not a valid URI. '
'Please make sure it incldues the schema part, '
'both http and https are accepted, '
'and the hierarchical part')
return True | python | def validate(self):
"""Validates whether a configuration is valid.
:rtype: bool
:raises ConfigurationError: if no ``access_token`` provided.
:raises ConfigurationError: if provided ``access_token`` is invalid - contains disallowed characters.
:raises ConfigurationError: if provided ``access_token`` is invalid - has invalid length.
:raises ConfigurationError: if provided ``base_url`` is invalid.
"""
if self.access_token is None:
raise ConfigurationError('No access token provided. '
'Set your access token during client initialization using: '
'"basecrm.Client(access_token= <YOUR_PERSONAL_ACCESS_TOKEN>)"')
if re.search(r'\s', self.access_token):
raise ConfigurationError('Provided access token is invalid '
'as it contains disallowed characters. '
'Please double-check you access token.')
if len(self.access_token) != 64:
raise ConfigurationError('Provided access token is invalid '
'as it has invalid length. '
'Please double-check your access token.')
if not self.base_url or not re.match(self.URL_REGEXP, self.base_url):
raise ConfigurationError('Provided base url is invalid '
'as it not a valid URI. '
'Please make sure it incldues the schema part, '
'both http and https are accepted, '
'and the hierarchical part')
return True | [
"def",
"validate",
"(",
"self",
")",
":",
"if",
"self",
".",
"access_token",
"is",
"None",
":",
"raise",
"ConfigurationError",
"(",
"'No access token provided. '",
"'Set your access token during client initialization using: '",
"'\"basecrm.Client(access_token= <YOUR_PERSONAL_ACCESS_TOKEN>)\"'",
")",
"if",
"re",
".",
"search",
"(",
"r'\\s'",
",",
"self",
".",
"access_token",
")",
":",
"raise",
"ConfigurationError",
"(",
"'Provided access token is invalid '",
"'as it contains disallowed characters. '",
"'Please double-check you access token.'",
")",
"if",
"len",
"(",
"self",
".",
"access_token",
")",
"!=",
"64",
":",
"raise",
"ConfigurationError",
"(",
"'Provided access token is invalid '",
"'as it has invalid length. '",
"'Please double-check your access token.'",
")",
"if",
"not",
"self",
".",
"base_url",
"or",
"not",
"re",
".",
"match",
"(",
"self",
".",
"URL_REGEXP",
",",
"self",
".",
"base_url",
")",
":",
"raise",
"ConfigurationError",
"(",
"'Provided base url is invalid '",
"'as it not a valid URI. '",
"'Please make sure it incldues the schema part, '",
"'both http and https are accepted, '",
"'and the hierarchical part'",
")",
"return",
"True"
] | Validates whether a configuration is valid.
:rtype: bool
:raises ConfigurationError: if no ``access_token`` provided.
:raises ConfigurationError: if provided ``access_token`` is invalid - contains disallowed characters.
:raises ConfigurationError: if provided ``access_token`` is invalid - has invalid length.
:raises ConfigurationError: if provided ``base_url`` is invalid. | [
"Validates",
"whether",
"a",
"configuration",
"is",
"valid",
"."
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/configuration.py#L35-L66 | train |
basecrm/basecrm-python | basecrm/sync.py | SyncService.start | def start(self, device_uuid):
"""
Start synchronization flow
Starts a new synchronization session.
This is the first endpoint to call, in order to start a new synchronization session.
:calls: ``post /sync/start``
:param string device_uuid: Device's UUID for which to perform synchronization.
:return: Dictionary that support attribute-style access and represents newely created Synchronization Session or None.
:rtype: dict
"""
status_code, _, session = self.http_client.post('/sync/start',
body=None,
headers=self.build_headers(device_uuid))
return None if status_code == 204 else session | python | def start(self, device_uuid):
"""
Start synchronization flow
Starts a new synchronization session.
This is the first endpoint to call, in order to start a new synchronization session.
:calls: ``post /sync/start``
:param string device_uuid: Device's UUID for which to perform synchronization.
:return: Dictionary that support attribute-style access and represents newely created Synchronization Session or None.
:rtype: dict
"""
status_code, _, session = self.http_client.post('/sync/start',
body=None,
headers=self.build_headers(device_uuid))
return None if status_code == 204 else session | [
"def",
"start",
"(",
"self",
",",
"device_uuid",
")",
":",
"status_code",
",",
"_",
",",
"session",
"=",
"self",
".",
"http_client",
".",
"post",
"(",
"'/sync/start'",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"self",
".",
"build_headers",
"(",
"device_uuid",
")",
")",
"return",
"None",
"if",
"status_code",
"==",
"204",
"else",
"session"
] | Start synchronization flow
Starts a new synchronization session.
This is the first endpoint to call, in order to start a new synchronization session.
:calls: ``post /sync/start``
:param string device_uuid: Device's UUID for which to perform synchronization.
:return: Dictionary that support attribute-style access and represents newely created Synchronization Session or None.
:rtype: dict | [
"Start",
"synchronization",
"flow"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/sync.py#L18-L35 | train |
basecrm/basecrm-python | basecrm/sync.py | SyncService.fetch | def fetch(self, device_uuid, session_id):
"""
Get data from queue
Fetch fresh data from the named queue.
Using session identifier you call continously the `#fetch` method to drain the named queue.
:calls: ``get /sync/{session_id}/queues/main``
:param string device_uuid: Device's UUID for which to perform synchronization.
:param string session_id: Unique identifier of a synchronization session.
:param string queue: (optional) Queue name.
:return: List of dictionaries that support attribute-style access,
which represent resources (data) and associated meta data (meta).
Empty list if there is no more data to synchronize.
:rtype: list
"""
status_code, _, root = self.http_client.get("/sync/{session_id}/queues/main".format(session_id=session_id),
params=None,
headers=self.build_headers(device_uuid),
raw=True)
return [] if status_code == 204 else root['items'] | python | def fetch(self, device_uuid, session_id):
"""
Get data from queue
Fetch fresh data from the named queue.
Using session identifier you call continously the `#fetch` method to drain the named queue.
:calls: ``get /sync/{session_id}/queues/main``
:param string device_uuid: Device's UUID for which to perform synchronization.
:param string session_id: Unique identifier of a synchronization session.
:param string queue: (optional) Queue name.
:return: List of dictionaries that support attribute-style access,
which represent resources (data) and associated meta data (meta).
Empty list if there is no more data to synchronize.
:rtype: list
"""
status_code, _, root = self.http_client.get("/sync/{session_id}/queues/main".format(session_id=session_id),
params=None,
headers=self.build_headers(device_uuid),
raw=True)
return [] if status_code == 204 else root['items'] | [
"def",
"fetch",
"(",
"self",
",",
"device_uuid",
",",
"session_id",
")",
":",
"status_code",
",",
"_",
",",
"root",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/sync/{session_id}/queues/main\"",
".",
"format",
"(",
"session_id",
"=",
"session_id",
")",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"self",
".",
"build_headers",
"(",
"device_uuid",
")",
",",
"raw",
"=",
"True",
")",
"return",
"[",
"]",
"if",
"status_code",
"==",
"204",
"else",
"root",
"[",
"'items'",
"]"
] | Get data from queue
Fetch fresh data from the named queue.
Using session identifier you call continously the `#fetch` method to drain the named queue.
:calls: ``get /sync/{session_id}/queues/main``
:param string device_uuid: Device's UUID for which to perform synchronization.
:param string session_id: Unique identifier of a synchronization session.
:param string queue: (optional) Queue name.
:return: List of dictionaries that support attribute-style access,
which represent resources (data) and associated meta data (meta).
Empty list if there is no more data to synchronize.
:rtype: list | [
"Get",
"data",
"from",
"queue"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/sync.py#L37-L59 | train |
basecrm/basecrm-python | basecrm/sync.py | SyncService.ack | def ack(self, device_uuid, ack_keys):
"""
Acknowledge received data
Send acknowledgement keys to let know the Sync service which data you have.
As you fetch new data, you need to send acknowledgement keys.
:calls: ``post /sync/ack``
:param string device_uuid: Device's UUID for which to perform synchronization.
:param list ack_keys: List of acknowledgement keys.
:return: True if the operation succeeded.
:rtype: bool
"""
attributes = {'ack_keys': ack_keys}
status_code, _, _ = self.http_client.post('/sync/ack',
body=attributes,
headers=self.build_headers(device_uuid))
return status_code == 202 | python | def ack(self, device_uuid, ack_keys):
"""
Acknowledge received data
Send acknowledgement keys to let know the Sync service which data you have.
As you fetch new data, you need to send acknowledgement keys.
:calls: ``post /sync/ack``
:param string device_uuid: Device's UUID for which to perform synchronization.
:param list ack_keys: List of acknowledgement keys.
:return: True if the operation succeeded.
:rtype: bool
"""
attributes = {'ack_keys': ack_keys}
status_code, _, _ = self.http_client.post('/sync/ack',
body=attributes,
headers=self.build_headers(device_uuid))
return status_code == 202 | [
"def",
"ack",
"(",
"self",
",",
"device_uuid",
",",
"ack_keys",
")",
":",
"attributes",
"=",
"{",
"'ack_keys'",
":",
"ack_keys",
"}",
"status_code",
",",
"_",
",",
"_",
"=",
"self",
".",
"http_client",
".",
"post",
"(",
"'/sync/ack'",
",",
"body",
"=",
"attributes",
",",
"headers",
"=",
"self",
".",
"build_headers",
"(",
"device_uuid",
")",
")",
"return",
"status_code",
"==",
"202"
] | Acknowledge received data
Send acknowledgement keys to let know the Sync service which data you have.
As you fetch new data, you need to send acknowledgement keys.
:calls: ``post /sync/ack``
:param string device_uuid: Device's UUID for which to perform synchronization.
:param list ack_keys: List of acknowledgement keys.
:return: True if the operation succeeded.
:rtype: bool | [
"Acknowledge",
"received",
"data"
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/sync.py#L61-L80 | train |
basecrm/basecrm-python | basecrm/sync.py | Sync.fetch | def fetch(self, callback):
"""
Perform a full synchronization flow.
.. code-block:: python
:linenos:
>>> client = basecrm.Client(access_token='<YOUR_PERSONAL_ACCESS_TOKEN>')
>>> sync = basecrm.Sync(client=client, device_uuid='<YOUR_DEVICES_UUID>')
>>> sync.fetch(lambda meta, data: basecrm.Sync.ACK)
:param callback: Callback that will be called for every item in a queue.
Takes two input arguments: synchronization meta data and assodicated data.
It must return either ack or nack.
"""
# Set up a new synchronization session for a given device's UUID
session = self.client.sync.start(self.device_uuid)
# Check if there is anything to synchronize
if session is None or 'id' not in session:
return
# Drain the main queue until there is no more data (empty array)
while True:
# Fetch the main queue
queue_items = self.client.sync.fetch(self.device_uuid, session['id'])
# nothing more to synchronize ?
if not queue_items:
break
# let client know about both data and meta
ack_keys = []
for item in queue_items:
if callback(item['meta'], item['data']):
ack_keys.append(item['meta']['sync']['ack_key'])
# As we fetch new data, we need to send acknowledgement keys
# if any ..
if ack_keys:
self.client.sync.ack(self.device_uuid, ack_keys) | python | def fetch(self, callback):
"""
Perform a full synchronization flow.
.. code-block:: python
:linenos:
>>> client = basecrm.Client(access_token='<YOUR_PERSONAL_ACCESS_TOKEN>')
>>> sync = basecrm.Sync(client=client, device_uuid='<YOUR_DEVICES_UUID>')
>>> sync.fetch(lambda meta, data: basecrm.Sync.ACK)
:param callback: Callback that will be called for every item in a queue.
Takes two input arguments: synchronization meta data and assodicated data.
It must return either ack or nack.
"""
# Set up a new synchronization session for a given device's UUID
session = self.client.sync.start(self.device_uuid)
# Check if there is anything to synchronize
if session is None or 'id' not in session:
return
# Drain the main queue until there is no more data (empty array)
while True:
# Fetch the main queue
queue_items = self.client.sync.fetch(self.device_uuid, session['id'])
# nothing more to synchronize ?
if not queue_items:
break
# let client know about both data and meta
ack_keys = []
for item in queue_items:
if callback(item['meta'], item['data']):
ack_keys.append(item['meta']['sync']['ack_key'])
# As we fetch new data, we need to send acknowledgement keys
# if any ..
if ack_keys:
self.client.sync.ack(self.device_uuid, ack_keys) | [
"def",
"fetch",
"(",
"self",
",",
"callback",
")",
":",
"# Set up a new synchronization session for a given device's UUID",
"session",
"=",
"self",
".",
"client",
".",
"sync",
".",
"start",
"(",
"self",
".",
"device_uuid",
")",
"# Check if there is anything to synchronize",
"if",
"session",
"is",
"None",
"or",
"'id'",
"not",
"in",
"session",
":",
"return",
"# Drain the main queue until there is no more data (empty array)",
"while",
"True",
":",
"# Fetch the main queue",
"queue_items",
"=",
"self",
".",
"client",
".",
"sync",
".",
"fetch",
"(",
"self",
".",
"device_uuid",
",",
"session",
"[",
"'id'",
"]",
")",
"# nothing more to synchronize ?",
"if",
"not",
"queue_items",
":",
"break",
"# let client know about both data and meta",
"ack_keys",
"=",
"[",
"]",
"for",
"item",
"in",
"queue_items",
":",
"if",
"callback",
"(",
"item",
"[",
"'meta'",
"]",
",",
"item",
"[",
"'data'",
"]",
")",
":",
"ack_keys",
".",
"append",
"(",
"item",
"[",
"'meta'",
"]",
"[",
"'sync'",
"]",
"[",
"'ack_key'",
"]",
")",
"# As we fetch new data, we need to send acknowledgement keys",
"# if any ..",
"if",
"ack_keys",
":",
"self",
".",
"client",
".",
"sync",
".",
"ack",
"(",
"self",
".",
"device_uuid",
",",
"ack_keys",
")"
] | Perform a full synchronization flow.
.. code-block:: python
:linenos:
>>> client = basecrm.Client(access_token='<YOUR_PERSONAL_ACCESS_TOKEN>')
>>> sync = basecrm.Sync(client=client, device_uuid='<YOUR_DEVICES_UUID>')
>>> sync.fetch(lambda meta, data: basecrm.Sync.ACK)
:param callback: Callback that will be called for every item in a queue.
Takes two input arguments: synchronization meta data and assodicated data.
It must return either ack or nack. | [
"Perform",
"a",
"full",
"synchronization",
"flow",
"."
] | 7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6 | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/sync.py#L117-L159 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.