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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
jilljenn/tryalgo | tryalgo/binary_search.py | continuous_binary_search | def continuous_binary_search(f, lo, hi, gap=1e-4):
"""Binary search for a function
:param f: boolean monotone function with f(hi) = True
:param int lo:
:param int hi: with hi >= lo
:param float gap:
:returns: first value x in [lo,hi] such that f(x),
x is computed up to some precision
:complexity: `O(log((hi-lo)/gap))`
"""
while hi - lo > gap:
# in other languages you can force floating division by using 2.0
mid = (lo + hi) / 2.
if f(mid):
hi = mid
else:
lo = mid
return lo | python | def continuous_binary_search(f, lo, hi, gap=1e-4):
"""Binary search for a function
:param f: boolean monotone function with f(hi) = True
:param int lo:
:param int hi: with hi >= lo
:param float gap:
:returns: first value x in [lo,hi] such that f(x),
x is computed up to some precision
:complexity: `O(log((hi-lo)/gap))`
"""
while hi - lo > gap:
# in other languages you can force floating division by using 2.0
mid = (lo + hi) / 2.
if f(mid):
hi = mid
else:
lo = mid
return lo | [
"def",
"continuous_binary_search",
"(",
"f",
",",
"lo",
",",
"hi",
",",
"gap",
"=",
"1e-4",
")",
":",
"while",
"hi",
"-",
"lo",
">",
"gap",
":",
"# in other languages you can force floating division by using 2.0",
"mid",
"=",
"(",
"lo",
"+",
"hi",
")",
"/",
... | Binary search for a function
:param f: boolean monotone function with f(hi) = True
:param int lo:
:param int hi: with hi >= lo
:param float gap:
:returns: first value x in [lo,hi] such that f(x),
x is computed up to some precision
:complexity: `O(log((hi-lo)/gap))` | [
"Binary",
"search",
"for",
"a",
"function"
] | 89a4dd9655e7b6b0a176f72b4c60d0196420dfe1 | https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/binary_search.py#L46-L64 | train | 208,800 |
jilljenn/tryalgo | tryalgo/binary_search.py | ternary_search | def ternary_search(f, lo, hi, gap=1e-10):
"""Ternary maximum search for a bitonic function
:param f: boolean bitonic function (increasing then decreasing, not necessarily strictly)
:param int lo:
:param int hi: with hi >= lo
:param float gap:
:returns: value x in [lo,hi] maximizing f(x),
x is computed up to some precision
:complexity: `O(log((hi-lo)/gap))`
"""
while hi - lo > gap:
step = (hi - lo) / 3.
if f(lo + step) < f(lo + 2 * step):
lo += step
else:
hi -= step
return lo | python | def ternary_search(f, lo, hi, gap=1e-10):
"""Ternary maximum search for a bitonic function
:param f: boolean bitonic function (increasing then decreasing, not necessarily strictly)
:param int lo:
:param int hi: with hi >= lo
:param float gap:
:returns: value x in [lo,hi] maximizing f(x),
x is computed up to some precision
:complexity: `O(log((hi-lo)/gap))`
"""
while hi - lo > gap:
step = (hi - lo) / 3.
if f(lo + step) < f(lo + 2 * step):
lo += step
else:
hi -= step
return lo | [
"def",
"ternary_search",
"(",
"f",
",",
"lo",
",",
"hi",
",",
"gap",
"=",
"1e-10",
")",
":",
"while",
"hi",
"-",
"lo",
">",
"gap",
":",
"step",
"=",
"(",
"hi",
"-",
"lo",
")",
"/",
"3.",
"if",
"f",
"(",
"lo",
"+",
"step",
")",
"<",
"f",
"... | Ternary maximum search for a bitonic function
:param f: boolean bitonic function (increasing then decreasing, not necessarily strictly)
:param int lo:
:param int hi: with hi >= lo
:param float gap:
:returns: value x in [lo,hi] maximizing f(x),
x is computed up to some precision
:complexity: `O(log((hi-lo)/gap))` | [
"Ternary",
"maximum",
"search",
"for",
"a",
"bitonic",
"function"
] | 89a4dd9655e7b6b0a176f72b4c60d0196420dfe1 | https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/binary_search.py#L108-L125 | train | 208,801 |
jilljenn/tryalgo | tryalgo/anagrams.py | anagrams | def anagrams(w):
"""group a list of words into anagrams
:param w: list of strings
:returns: list of lists
:complexity:
:math:`O(n k \log k)` in average, for n words of length at most k.
:math:`O(n^2 k \log k)` in worst case due to the usage of a dictionary.
"""
w = list(set(w)) # remove duplicates
d = {} # group words according to some signature
for i in range(len(w)):
s = ''.join(sorted(w[i])) # signature
if s in d:
d[s].append(i)
else:
d[s] = [i]
# -- extract anagrams
answer = []
for s in d:
if len(d[s]) > 1: # ignore words without anagram
answer.append([w[i] for i in d[s]])
return answer | python | def anagrams(w):
"""group a list of words into anagrams
:param w: list of strings
:returns: list of lists
:complexity:
:math:`O(n k \log k)` in average, for n words of length at most k.
:math:`O(n^2 k \log k)` in worst case due to the usage of a dictionary.
"""
w = list(set(w)) # remove duplicates
d = {} # group words according to some signature
for i in range(len(w)):
s = ''.join(sorted(w[i])) # signature
if s in d:
d[s].append(i)
else:
d[s] = [i]
# -- extract anagrams
answer = []
for s in d:
if len(d[s]) > 1: # ignore words without anagram
answer.append([w[i] for i in d[s]])
return answer | [
"def",
"anagrams",
"(",
"w",
")",
":",
"w",
"=",
"list",
"(",
"set",
"(",
"w",
")",
")",
"# remove duplicates",
"d",
"=",
"{",
"}",
"# group words according to some signature",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"w",
")",
")",
":",
"s",
"=",... | group a list of words into anagrams
:param w: list of strings
:returns: list of lists
:complexity:
:math:`O(n k \log k)` in average, for n words of length at most k.
:math:`O(n^2 k \log k)` in worst case due to the usage of a dictionary. | [
"group",
"a",
"list",
"of",
"words",
"into",
"anagrams"
] | 89a4dd9655e7b6b0a176f72b4c60d0196420dfe1 | https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/anagrams.py#L9-L32 | train | 208,802 |
jilljenn/tryalgo | tryalgo/subsetsum_divide.py | subset_sum | def subset_sum(x, R):
"""Subsetsum by splitting
:param x: table of values
:param R: target value
:returns bool: if there is a subsequence of x with total sum R
:complexity: :math:`O(n^{\\lceil n/2 \\rceil})`
"""
k = len(x) // 2 # divide input
Y = [v for v in part_sum(x[:k])]
Z = [R - v for v in part_sum(x[k:])]
Y.sort() # test of intersection between Y and Z
Z.sort()
i = 0
j = 0
while i < len(Y) and j < len(Z):
if Y[i] == Z[j]:
return True
elif Y[i] < Z[j]: # increment index of smallest element
i += 1
else:
j += 1
return False | python | def subset_sum(x, R):
"""Subsetsum by splitting
:param x: table of values
:param R: target value
:returns bool: if there is a subsequence of x with total sum R
:complexity: :math:`O(n^{\\lceil n/2 \\rceil})`
"""
k = len(x) // 2 # divide input
Y = [v for v in part_sum(x[:k])]
Z = [R - v for v in part_sum(x[k:])]
Y.sort() # test of intersection between Y and Z
Z.sort()
i = 0
j = 0
while i < len(Y) and j < len(Z):
if Y[i] == Z[j]:
return True
elif Y[i] < Z[j]: # increment index of smallest element
i += 1
else:
j += 1
return False | [
"def",
"subset_sum",
"(",
"x",
",",
"R",
")",
":",
"k",
"=",
"len",
"(",
"x",
")",
"//",
"2",
"# divide input",
"Y",
"=",
"[",
"v",
"for",
"v",
"in",
"part_sum",
"(",
"x",
"[",
":",
"k",
"]",
")",
"]",
"Z",
"=",
"[",
"R",
"-",
"v",
"for",... | Subsetsum by splitting
:param x: table of values
:param R: target value
:returns bool: if there is a subsequence of x with total sum R
:complexity: :math:`O(n^{\\lceil n/2 \\rceil})` | [
"Subsetsum",
"by",
"splitting"
] | 89a4dd9655e7b6b0a176f72b4c60d0196420dfe1 | https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/subsetsum_divide.py#L24-L46 | train | 208,803 |
jilljenn/tryalgo | tryalgo/strongly_connected_components.py | tarjan_recursif | def tarjan_recursif(graph):
"""Strongly connected components by Tarjan, recursive implementation
:param graph: directed graph in listlist format, cannot be listdict
:returns: list of lists for each component
:complexity: linear
"""
global sccp, waiting, dfs_time, dfs_num
sccp = []
waiting = []
waits = [False] * len(graph)
dfs_time = 0
dfs_num = [None] * len(graph)
def dfs(node):
global sccp, waiting, dfs_time, dfs_num
waiting.append(node) # new node is waiting
waits[node] = True
dfs_num[node] = dfs_time # mark visit
dfs_time += 1
dfs_min = dfs_num[node] # compute dfs_min
for neighbor in graph[node]:
if dfs_num[neighbor] is None:
dfs_min = min(dfs_min, dfs(neighbor))
elif waits[neighbor] and dfs_min > dfs_num[neighbor]:
dfs_min = dfs_num[neighbor]
if dfs_min == dfs_num[node]: # representative of a component
sccp.append([]) # make a component
while True: # add waiting nodes
u = waiting.pop()
waits[u] = False
sccp[-1].append(u)
if u == node: # until representative
break
return dfs_min
for node in range(len(graph)):
if dfs_num[node] is None:
dfs(node)
return sccp | python | def tarjan_recursif(graph):
"""Strongly connected components by Tarjan, recursive implementation
:param graph: directed graph in listlist format, cannot be listdict
:returns: list of lists for each component
:complexity: linear
"""
global sccp, waiting, dfs_time, dfs_num
sccp = []
waiting = []
waits = [False] * len(graph)
dfs_time = 0
dfs_num = [None] * len(graph)
def dfs(node):
global sccp, waiting, dfs_time, dfs_num
waiting.append(node) # new node is waiting
waits[node] = True
dfs_num[node] = dfs_time # mark visit
dfs_time += 1
dfs_min = dfs_num[node] # compute dfs_min
for neighbor in graph[node]:
if dfs_num[neighbor] is None:
dfs_min = min(dfs_min, dfs(neighbor))
elif waits[neighbor] and dfs_min > dfs_num[neighbor]:
dfs_min = dfs_num[neighbor]
if dfs_min == dfs_num[node]: # representative of a component
sccp.append([]) # make a component
while True: # add waiting nodes
u = waiting.pop()
waits[u] = False
sccp[-1].append(u)
if u == node: # until representative
break
return dfs_min
for node in range(len(graph)):
if dfs_num[node] is None:
dfs(node)
return sccp | [
"def",
"tarjan_recursif",
"(",
"graph",
")",
":",
"global",
"sccp",
",",
"waiting",
",",
"dfs_time",
",",
"dfs_num",
"sccp",
"=",
"[",
"]",
"waiting",
"=",
"[",
"]",
"waits",
"=",
"[",
"False",
"]",
"*",
"len",
"(",
"graph",
")",
"dfs_time",
"=",
"... | Strongly connected components by Tarjan, recursive implementation
:param graph: directed graph in listlist format, cannot be listdict
:returns: list of lists for each component
:complexity: linear | [
"Strongly",
"connected",
"components",
"by",
"Tarjan",
"recursive",
"implementation"
] | 89a4dd9655e7b6b0a176f72b4c60d0196420dfe1 | https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/strongly_connected_components.py#L11-L50 | train | 208,804 |
jilljenn/tryalgo | tryalgo/strongly_connected_components.py | tarjan | def tarjan(graph):
"""Strongly connected components by Tarjan, iterative implementation
:param graph: directed graph in listlist format, cannot be listdict
:returns: list of lists for each component
:complexity: linear
"""
n = len(graph)
dfs_num = [None] * n
dfs_min = [n] * n
waiting = []
waits = [False] * n # invariant: waits[v] iff v in waiting
sccp = [] # list of detected components
dfs_time = 0
times_seen = [-1] * n
for start in range(n):
if times_seen[start] == -1: # initiate path
times_seen[start] = 0
to_visit = [start]
while to_visit:
node = to_visit[-1] # top of stack
if times_seen[node] == 0: # start process
dfs_num[node] = dfs_time
dfs_min[node] = dfs_time
dfs_time += 1
waiting.append(node)
waits[node] = True
children = graph[node]
if times_seen[node] == len(children): # end of process
to_visit.pop() # remove from stack
dfs_min[node] = dfs_num[node] # compute dfs_min
for child in children:
if waits[child] and dfs_min[child] < dfs_min[node]:
dfs_min[node] = dfs_min[child]
if dfs_min[node] == dfs_num[node]: # representative
component = [] # make component
while True: # add nodes
u = waiting.pop()
waits[u] = False
component.append(u)
if u == node: # until repr.
break
sccp.append(component)
else:
child = children[times_seen[node]]
times_seen[node] += 1
if times_seen[child] == -1: # not visited yet
times_seen[child] = 0
to_visit.append(child)
return sccp | python | def tarjan(graph):
"""Strongly connected components by Tarjan, iterative implementation
:param graph: directed graph in listlist format, cannot be listdict
:returns: list of lists for each component
:complexity: linear
"""
n = len(graph)
dfs_num = [None] * n
dfs_min = [n] * n
waiting = []
waits = [False] * n # invariant: waits[v] iff v in waiting
sccp = [] # list of detected components
dfs_time = 0
times_seen = [-1] * n
for start in range(n):
if times_seen[start] == -1: # initiate path
times_seen[start] = 0
to_visit = [start]
while to_visit:
node = to_visit[-1] # top of stack
if times_seen[node] == 0: # start process
dfs_num[node] = dfs_time
dfs_min[node] = dfs_time
dfs_time += 1
waiting.append(node)
waits[node] = True
children = graph[node]
if times_seen[node] == len(children): # end of process
to_visit.pop() # remove from stack
dfs_min[node] = dfs_num[node] # compute dfs_min
for child in children:
if waits[child] and dfs_min[child] < dfs_min[node]:
dfs_min[node] = dfs_min[child]
if dfs_min[node] == dfs_num[node]: # representative
component = [] # make component
while True: # add nodes
u = waiting.pop()
waits[u] = False
component.append(u)
if u == node: # until repr.
break
sccp.append(component)
else:
child = children[times_seen[node]]
times_seen[node] += 1
if times_seen[child] == -1: # not visited yet
times_seen[child] = 0
to_visit.append(child)
return sccp | [
"def",
"tarjan",
"(",
"graph",
")",
":",
"n",
"=",
"len",
"(",
"graph",
")",
"dfs_num",
"=",
"[",
"None",
"]",
"*",
"n",
"dfs_min",
"=",
"[",
"n",
"]",
"*",
"n",
"waiting",
"=",
"[",
"]",
"waits",
"=",
"[",
"False",
"]",
"*",
"n",
"# invarian... | Strongly connected components by Tarjan, iterative implementation
:param graph: directed graph in listlist format, cannot be listdict
:returns: list of lists for each component
:complexity: linear | [
"Strongly",
"connected",
"components",
"by",
"Tarjan",
"iterative",
"implementation"
] | 89a4dd9655e7b6b0a176f72b4c60d0196420dfe1 | https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/strongly_connected_components.py#L55-L104 | train | 208,805 |
jilljenn/tryalgo | tryalgo/strongly_connected_components.py | kosaraju | def kosaraju(graph):
"""Strongly connected components by Kosaraju
:param graph: directed graph in listlist format, cannot be listdict
:returns: list of lists for each component
:complexity: linear
"""
n = len(graph)
order = []
sccp = []
kosaraju_dfs(graph, range(n), order, [])
kosaraju_dfs(reverse(graph), order[::-1], [], sccp)
return sccp[::-1] | python | def kosaraju(graph):
"""Strongly connected components by Kosaraju
:param graph: directed graph in listlist format, cannot be listdict
:returns: list of lists for each component
:complexity: linear
"""
n = len(graph)
order = []
sccp = []
kosaraju_dfs(graph, range(n), order, [])
kosaraju_dfs(reverse(graph), order[::-1], [], sccp)
return sccp[::-1] | [
"def",
"kosaraju",
"(",
"graph",
")",
":",
"n",
"=",
"len",
"(",
"graph",
")",
"order",
"=",
"[",
"]",
"sccp",
"=",
"[",
"]",
"kosaraju_dfs",
"(",
"graph",
",",
"range",
"(",
"n",
")",
",",
"order",
",",
"[",
"]",
")",
"kosaraju_dfs",
"(",
"rev... | Strongly connected components by Kosaraju
:param graph: directed graph in listlist format, cannot be listdict
:returns: list of lists for each component
:complexity: linear | [
"Strongly",
"connected",
"components",
"by",
"Kosaraju"
] | 89a4dd9655e7b6b0a176f72b4c60d0196420dfe1 | https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/strongly_connected_components.py#L140-L152 | train | 208,806 |
InspectorMustache/base16-builder-python | pybase16_builder/builder.py | get_template_dirs | def get_template_dirs():
"""Return a set of all template directories."""
temp_glob = rel_to_cwd('templates', '**', 'templates', 'config.yaml')
temp_groups = glob(temp_glob)
temp_groups = [get_parent_dir(path, 2) for path in temp_groups]
return set(temp_groups) | python | def get_template_dirs():
"""Return a set of all template directories."""
temp_glob = rel_to_cwd('templates', '**', 'templates', 'config.yaml')
temp_groups = glob(temp_glob)
temp_groups = [get_parent_dir(path, 2) for path in temp_groups]
return set(temp_groups) | [
"def",
"get_template_dirs",
"(",
")",
":",
"temp_glob",
"=",
"rel_to_cwd",
"(",
"'templates'",
",",
"'**'",
",",
"'templates'",
",",
"'config.yaml'",
")",
"temp_groups",
"=",
"glob",
"(",
"temp_glob",
")",
"temp_groups",
"=",
"[",
"get_parent_dir",
"(",
"path"... | Return a set of all template directories. | [
"Return",
"a",
"set",
"of",
"all",
"template",
"directories",
"."
] | 586f1f87ee9f70696ab19c542af6ef55c6548a2e | https://github.com/InspectorMustache/base16-builder-python/blob/586f1f87ee9f70696ab19c542af6ef55c6548a2e/pybase16_builder/builder.py#L56-L61 | train | 208,807 |
InspectorMustache/base16-builder-python | pybase16_builder/builder.py | get_scheme_dirs | def get_scheme_dirs():
"""Return a set of all scheme directories."""
scheme_glob = rel_to_cwd('schemes', '**', '*.yaml')
scheme_groups = glob(scheme_glob)
scheme_groups = [get_parent_dir(path) for path in scheme_groups]
return set(scheme_groups) | python | def get_scheme_dirs():
"""Return a set of all scheme directories."""
scheme_glob = rel_to_cwd('schemes', '**', '*.yaml')
scheme_groups = glob(scheme_glob)
scheme_groups = [get_parent_dir(path) for path in scheme_groups]
return set(scheme_groups) | [
"def",
"get_scheme_dirs",
"(",
")",
":",
"scheme_glob",
"=",
"rel_to_cwd",
"(",
"'schemes'",
",",
"'**'",
",",
"'*.yaml'",
")",
"scheme_groups",
"=",
"glob",
"(",
"scheme_glob",
")",
"scheme_groups",
"=",
"[",
"get_parent_dir",
"(",
"path",
")",
"for",
"path... | Return a set of all scheme directories. | [
"Return",
"a",
"set",
"of",
"all",
"scheme",
"directories",
"."
] | 586f1f87ee9f70696ab19c542af6ef55c6548a2e | https://github.com/InspectorMustache/base16-builder-python/blob/586f1f87ee9f70696ab19c542af6ef55c6548a2e/pybase16_builder/builder.py#L64-L69 | train | 208,808 |
InspectorMustache/base16-builder-python | pybase16_builder/builder.py | build | def build(templates=None, schemes=None, base_output_dir=None):
"""Main build function to initiate building process."""
template_dirs = templates or get_template_dirs()
scheme_files = get_scheme_files(schemes)
base_output_dir = base_output_dir or rel_to_cwd('output')
# raise LookupError if there is not at least one template or scheme
# to work with
if not template_dirs or not scheme_files:
raise LookupError
# raise PermissionError if user has no write acces for $base_output_dir
try:
os.makedirs(base_output_dir)
except FileExistsError:
pass
if not os.access(base_output_dir, os.W_OK):
raise PermissionError
templates = [TemplateGroup(path) for path in template_dirs]
build_from_job_list(scheme_files, templates, base_output_dir)
print('Finished building process.') | python | def build(templates=None, schemes=None, base_output_dir=None):
"""Main build function to initiate building process."""
template_dirs = templates or get_template_dirs()
scheme_files = get_scheme_files(schemes)
base_output_dir = base_output_dir or rel_to_cwd('output')
# raise LookupError if there is not at least one template or scheme
# to work with
if not template_dirs or not scheme_files:
raise LookupError
# raise PermissionError if user has no write acces for $base_output_dir
try:
os.makedirs(base_output_dir)
except FileExistsError:
pass
if not os.access(base_output_dir, os.W_OK):
raise PermissionError
templates = [TemplateGroup(path) for path in template_dirs]
build_from_job_list(scheme_files, templates, base_output_dir)
print('Finished building process.') | [
"def",
"build",
"(",
"templates",
"=",
"None",
",",
"schemes",
"=",
"None",
",",
"base_output_dir",
"=",
"None",
")",
":",
"template_dirs",
"=",
"templates",
"or",
"get_template_dirs",
"(",
")",
"scheme_files",
"=",
"get_scheme_files",
"(",
"schemes",
")",
"... | Main build function to initiate building process. | [
"Main",
"build",
"function",
"to",
"initiate",
"building",
"process",
"."
] | 586f1f87ee9f70696ab19c542af6ef55c6548a2e | https://github.com/InspectorMustache/base16-builder-python/blob/586f1f87ee9f70696ab19c542af6ef55c6548a2e/pybase16_builder/builder.py#L193-L216 | train | 208,809 |
InspectorMustache/base16-builder-python | pybase16_builder/updater.py | write_sources_file | def write_sources_file():
"""Write a sources.yaml file to current working dir."""
file_content = (
'schemes: '
'https://github.com/chriskempson/base16-schemes-source.git\n'
'templates: '
'https://github.com/chriskempson/base16-templates-source.git'
)
file_path = rel_to_cwd('sources.yaml')
with open(file_path, 'w') as file_:
file_.write(file_content) | python | def write_sources_file():
"""Write a sources.yaml file to current working dir."""
file_content = (
'schemes: '
'https://github.com/chriskempson/base16-schemes-source.git\n'
'templates: '
'https://github.com/chriskempson/base16-templates-source.git'
)
file_path = rel_to_cwd('sources.yaml')
with open(file_path, 'w') as file_:
file_.write(file_content) | [
"def",
"write_sources_file",
"(",
")",
":",
"file_content",
"=",
"(",
"'schemes: '",
"'https://github.com/chriskempson/base16-schemes-source.git\\n'",
"'templates: '",
"'https://github.com/chriskempson/base16-templates-source.git'",
")",
"file_path",
"=",
"rel_to_cwd",
"(",
"'sourc... | Write a sources.yaml file to current working dir. | [
"Write",
"a",
"sources",
".",
"yaml",
"file",
"to",
"current",
"working",
"dir",
"."
] | 586f1f87ee9f70696ab19c542af6ef55c6548a2e | https://github.com/InspectorMustache/base16-builder-python/blob/586f1f87ee9f70696ab19c542af6ef55c6548a2e/pybase16_builder/updater.py#L10-L20 | train | 208,810 |
InspectorMustache/base16-builder-python | pybase16_builder/shared.py | get_yaml_dict | def get_yaml_dict(yaml_file):
"""Return a yaml_dict from reading yaml_file. If yaml_file is empty or
doesn't exist, return an empty dict instead."""
try:
with open(yaml_file, 'r') as file_:
yaml_dict = yaml.safe_load(file_.read()) or {}
return yaml_dict
except FileNotFoundError:
return {} | python | def get_yaml_dict(yaml_file):
"""Return a yaml_dict from reading yaml_file. If yaml_file is empty or
doesn't exist, return an empty dict instead."""
try:
with open(yaml_file, 'r') as file_:
yaml_dict = yaml.safe_load(file_.read()) or {}
return yaml_dict
except FileNotFoundError:
return {} | [
"def",
"get_yaml_dict",
"(",
"yaml_file",
")",
":",
"try",
":",
"with",
"open",
"(",
"yaml_file",
",",
"'r'",
")",
"as",
"file_",
":",
"yaml_dict",
"=",
"yaml",
".",
"safe_load",
"(",
"file_",
".",
"read",
"(",
")",
")",
"or",
"{",
"}",
"return",
"... | Return a yaml_dict from reading yaml_file. If yaml_file is empty or
doesn't exist, return an empty dict instead. | [
"Return",
"a",
"yaml_dict",
"from",
"reading",
"yaml_file",
".",
"If",
"yaml_file",
"is",
"empty",
"or",
"doesn",
"t",
"exist",
"return",
"an",
"empty",
"dict",
"instead",
"."
] | 586f1f87ee9f70696ab19c542af6ef55c6548a2e | https://github.com/InspectorMustache/base16-builder-python/blob/586f1f87ee9f70696ab19c542af6ef55c6548a2e/pybase16_builder/shared.py#L12-L20 | train | 208,811 |
InspectorMustache/base16-builder-python | pybase16_builder/injector.py | Recipient._get_temp | def _get_temp(self, content):
"""Get the string that points to a specific base16 scheme."""
temp = None
for line in content.splitlines():
# make sure there's both start and end line
if not temp:
match = TEMP_NEEDLE.match(line)
if match:
temp = match.group(1).strip()
continue
else:
match = TEMP_END_NEEDLE.match(line)
if match:
return temp
raise IndexError(self.path) | python | def _get_temp(self, content):
"""Get the string that points to a specific base16 scheme."""
temp = None
for line in content.splitlines():
# make sure there's both start and end line
if not temp:
match = TEMP_NEEDLE.match(line)
if match:
temp = match.group(1).strip()
continue
else:
match = TEMP_END_NEEDLE.match(line)
if match:
return temp
raise IndexError(self.path) | [
"def",
"_get_temp",
"(",
"self",
",",
"content",
")",
":",
"temp",
"=",
"None",
"for",
"line",
"in",
"content",
".",
"splitlines",
"(",
")",
":",
"# make sure there's both start and end line",
"if",
"not",
"temp",
":",
"match",
"=",
"TEMP_NEEDLE",
".",
"matc... | Get the string that points to a specific base16 scheme. | [
"Get",
"the",
"string",
"that",
"points",
"to",
"a",
"specific",
"base16",
"scheme",
"."
] | 586f1f87ee9f70696ab19c542af6ef55c6548a2e | https://github.com/InspectorMustache/base16-builder-python/blob/586f1f87ee9f70696ab19c542af6ef55c6548a2e/pybase16_builder/injector.py#L24-L40 | train | 208,812 |
InspectorMustache/base16-builder-python | pybase16_builder/injector.py | Recipient.get_colorscheme | def get_colorscheme(self, scheme_file):
"""Return a string object with the colorscheme that is to be
inserted."""
scheme = get_yaml_dict(scheme_file)
scheme_slug = builder.slugify(scheme_file)
builder.format_scheme(scheme, scheme_slug)
try:
temp_base, temp_sub = self.temp.split('##')
except ValueError:
temp_base, temp_sub = (self.temp.strip('##'), 'default')
temp_path = rel_to_cwd('templates', temp_base)
temp_group = builder.TemplateGroup(temp_path)
try:
single_temp = temp_group.templates[temp_sub]
except KeyError:
raise FileNotFoundError(None,
None,
self.path + ' (sub-template)')
colorscheme = pystache.render(single_temp['parsed'], scheme)
return colorscheme | python | def get_colorscheme(self, scheme_file):
"""Return a string object with the colorscheme that is to be
inserted."""
scheme = get_yaml_dict(scheme_file)
scheme_slug = builder.slugify(scheme_file)
builder.format_scheme(scheme, scheme_slug)
try:
temp_base, temp_sub = self.temp.split('##')
except ValueError:
temp_base, temp_sub = (self.temp.strip('##'), 'default')
temp_path = rel_to_cwd('templates', temp_base)
temp_group = builder.TemplateGroup(temp_path)
try:
single_temp = temp_group.templates[temp_sub]
except KeyError:
raise FileNotFoundError(None,
None,
self.path + ' (sub-template)')
colorscheme = pystache.render(single_temp['parsed'], scheme)
return colorscheme | [
"def",
"get_colorscheme",
"(",
"self",
",",
"scheme_file",
")",
":",
"scheme",
"=",
"get_yaml_dict",
"(",
"scheme_file",
")",
"scheme_slug",
"=",
"builder",
".",
"slugify",
"(",
"scheme_file",
")",
"builder",
".",
"format_scheme",
"(",
"scheme",
",",
"scheme_s... | Return a string object with the colorscheme that is to be
inserted. | [
"Return",
"a",
"string",
"object",
"with",
"the",
"colorscheme",
"that",
"is",
"to",
"be",
"inserted",
"."
] | 586f1f87ee9f70696ab19c542af6ef55c6548a2e | https://github.com/InspectorMustache/base16-builder-python/blob/586f1f87ee9f70696ab19c542af6ef55c6548a2e/pybase16_builder/injector.py#L42-L64 | train | 208,813 |
InspectorMustache/base16-builder-python | pybase16_builder/injector.py | Recipient.write | def write(self):
"""Write content back to file."""
with open(self.path, 'w') as file_:
file_.write(self.content) | python | def write(self):
"""Write content back to file."""
with open(self.path, 'w') as file_:
file_.write(self.content) | [
"def",
"write",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"path",
",",
"'w'",
")",
"as",
"file_",
":",
"file_",
".",
"write",
"(",
"self",
".",
"content",
")"
] | Write content back to file. | [
"Write",
"content",
"back",
"to",
"file",
"."
] | 586f1f87ee9f70696ab19c542af6ef55c6548a2e | https://github.com/InspectorMustache/base16-builder-python/blob/586f1f87ee9f70696ab19c542af6ef55c6548a2e/pybase16_builder/injector.py#L89-L92 | train | 208,814 |
InspectorMustache/base16-builder-python | pybase16_builder/cli.py | update_mode | def update_mode(arg_namespace):
"""Check command line arguments and run update function."""
try:
updater.update(custom_sources=arg_namespace.custom)
except (PermissionError, FileNotFoundError) as exception:
if isinstance(exception, PermissionError):
print('No write permission for current working directory.')
if isinstance(exception, FileNotFoundError):
print('Necessary resources for updating not found in current '
'working directory.') | python | def update_mode(arg_namespace):
"""Check command line arguments and run update function."""
try:
updater.update(custom_sources=arg_namespace.custom)
except (PermissionError, FileNotFoundError) as exception:
if isinstance(exception, PermissionError):
print('No write permission for current working directory.')
if isinstance(exception, FileNotFoundError):
print('Necessary resources for updating not found in current '
'working directory.') | [
"def",
"update_mode",
"(",
"arg_namespace",
")",
":",
"try",
":",
"updater",
".",
"update",
"(",
"custom_sources",
"=",
"arg_namespace",
".",
"custom",
")",
"except",
"(",
"PermissionError",
",",
"FileNotFoundError",
")",
"as",
"exception",
":",
"if",
"isinsta... | Check command line arguments and run update function. | [
"Check",
"command",
"line",
"arguments",
"and",
"run",
"update",
"function",
"."
] | 586f1f87ee9f70696ab19c542af6ef55c6548a2e | https://github.com/InspectorMustache/base16-builder-python/blob/586f1f87ee9f70696ab19c542af6ef55c6548a2e/pybase16_builder/cli.py#L43-L52 | train | 208,815 |
blockcypher/blockcypher-python | blockcypher/api.py | get_address_details | def get_address_details(address, coin_symbol='btc', txn_limit=None, api_key=None, before_bh=None, after_bh=None, unspent_only=False, show_confidence=False, confirmations=0, include_script=False):
'''
Takes an address and coin_symbol and returns the address details
Optional:
- txn_limit: # transactions to include
- before_bh: filters response to only include transactions below before
height in the blockchain.
- after_bh: filters response to only include transactions above after
height in the blockchain.
- confirmations: returns the balance and TXRefs that have this number
of confirmations
- unspent_only: filters response to only include unspent TXRefs.
- show_confidence: adds confidence information to unconfirmed TXRefs.
For batching a list of addresses, see get_addresses_details
'''
assert is_valid_address_for_coinsymbol(
b58_address=address,
coin_symbol=coin_symbol), address
assert isinstance(show_confidence, bool), show_confidence
url = make_url(coin_symbol, **dict(addrs=address))
params = {}
if txn_limit:
params['limit'] = txn_limit
if api_key:
params['token'] = api_key
if before_bh:
params['before'] = before_bh
if after_bh:
params['after'] = after_bh
if confirmations:
params['confirmations'] = confirmations
if unspent_only:
params['unspentOnly'] = 'true'
if show_confidence:
params['includeConfidence'] = 'true'
if include_script:
params['includeScript'] = 'true'
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
r = get_valid_json(r)
return _clean_tx(response_dict=r) | python | def get_address_details(address, coin_symbol='btc', txn_limit=None, api_key=None, before_bh=None, after_bh=None, unspent_only=False, show_confidence=False, confirmations=0, include_script=False):
'''
Takes an address and coin_symbol and returns the address details
Optional:
- txn_limit: # transactions to include
- before_bh: filters response to only include transactions below before
height in the blockchain.
- after_bh: filters response to only include transactions above after
height in the blockchain.
- confirmations: returns the balance and TXRefs that have this number
of confirmations
- unspent_only: filters response to only include unspent TXRefs.
- show_confidence: adds confidence information to unconfirmed TXRefs.
For batching a list of addresses, see get_addresses_details
'''
assert is_valid_address_for_coinsymbol(
b58_address=address,
coin_symbol=coin_symbol), address
assert isinstance(show_confidence, bool), show_confidence
url = make_url(coin_symbol, **dict(addrs=address))
params = {}
if txn_limit:
params['limit'] = txn_limit
if api_key:
params['token'] = api_key
if before_bh:
params['before'] = before_bh
if after_bh:
params['after'] = after_bh
if confirmations:
params['confirmations'] = confirmations
if unspent_only:
params['unspentOnly'] = 'true'
if show_confidence:
params['includeConfidence'] = 'true'
if include_script:
params['includeScript'] = 'true'
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
r = get_valid_json(r)
return _clean_tx(response_dict=r) | [
"def",
"get_address_details",
"(",
"address",
",",
"coin_symbol",
"=",
"'btc'",
",",
"txn_limit",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"before_bh",
"=",
"None",
",",
"after_bh",
"=",
"None",
",",
"unspent_only",
"=",
"False",
",",
"show_confidence"... | Takes an address and coin_symbol and returns the address details
Optional:
- txn_limit: # transactions to include
- before_bh: filters response to only include transactions below before
height in the blockchain.
- after_bh: filters response to only include transactions above after
height in the blockchain.
- confirmations: returns the balance and TXRefs that have this number
of confirmations
- unspent_only: filters response to only include unspent TXRefs.
- show_confidence: adds confidence information to unconfirmed TXRefs.
For batching a list of addresses, see get_addresses_details | [
"Takes",
"an",
"address",
"and",
"coin_symbol",
"and",
"returns",
"the",
"address",
"details"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L103-L149 | train | 208,816 |
blockcypher/blockcypher-python | blockcypher/api.py | get_addresses_details | def get_addresses_details(address_list, coin_symbol='btc', txn_limit=None, api_key=None,
before_bh=None, after_bh=None, unspent_only=False, show_confidence=False,
confirmations=0, include_script=False):
'''
Batch version of get_address_details method
'''
for address in address_list:
assert is_valid_address_for_coinsymbol(
b58_address=address,
coin_symbol=coin_symbol), address
assert isinstance(show_confidence, bool), show_confidence
kwargs = dict(addrs=';'.join([str(addr) for addr in address_list]))
url = make_url(coin_symbol, **kwargs)
params = {}
if txn_limit:
params['limit'] = txn_limit
if api_key:
params['token'] = api_key
if before_bh:
params['before'] = before_bh
if after_bh:
params['after'] = after_bh
if confirmations:
params['confirmations'] = confirmations
if unspent_only:
params['unspentOnly'] = 'true'
if show_confidence:
params['includeConfidence'] = 'true'
if include_script:
params['includeScript'] = 'true'
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
r = get_valid_json(r)
return [_clean_tx(response_dict=d) for d in r] | python | def get_addresses_details(address_list, coin_symbol='btc', txn_limit=None, api_key=None,
before_bh=None, after_bh=None, unspent_only=False, show_confidence=False,
confirmations=0, include_script=False):
'''
Batch version of get_address_details method
'''
for address in address_list:
assert is_valid_address_for_coinsymbol(
b58_address=address,
coin_symbol=coin_symbol), address
assert isinstance(show_confidence, bool), show_confidence
kwargs = dict(addrs=';'.join([str(addr) for addr in address_list]))
url = make_url(coin_symbol, **kwargs)
params = {}
if txn_limit:
params['limit'] = txn_limit
if api_key:
params['token'] = api_key
if before_bh:
params['before'] = before_bh
if after_bh:
params['after'] = after_bh
if confirmations:
params['confirmations'] = confirmations
if unspent_only:
params['unspentOnly'] = 'true'
if show_confidence:
params['includeConfidence'] = 'true'
if include_script:
params['includeScript'] = 'true'
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
r = get_valid_json(r)
return [_clean_tx(response_dict=d) for d in r] | [
"def",
"get_addresses_details",
"(",
"address_list",
",",
"coin_symbol",
"=",
"'btc'",
",",
"txn_limit",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"before_bh",
"=",
"None",
",",
"after_bh",
"=",
"None",
",",
"unspent_only",
"=",
"False",
",",
"show_conf... | Batch version of get_address_details method | [
"Batch",
"version",
"of",
"get_address_details",
"method"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L152-L188 | train | 208,817 |
blockcypher/blockcypher-python | blockcypher/api.py | get_wallet_transactions | def get_wallet_transactions(wallet_name, api_key, coin_symbol='btc',
before_bh=None, after_bh=None, txn_limit=None, omit_addresses=False,
unspent_only=False, show_confidence=False, confirmations=0):
'''
Takes a wallet, api_key, coin_symbol and returns the wallet's details
Optional:
- txn_limit: # transactions to include
- before_bh: filters response to only include transactions below before
height in the blockchain.
- after_bh: filters response to only include transactions above after
height in the blockchain.
- confirmations: returns the balance and TXRefs that have this number
of confirmations
- unspent_only: filters response to only include unspent TXRefs.
- show_confidence: adds confidence information to unconfirmed TXRefs.
'''
assert len(wallet_name) <= 25, wallet_name
assert api_key
assert is_valid_coin_symbol(coin_symbol=coin_symbol)
assert isinstance(show_confidence, bool), show_confidence
assert isinstance(omit_addresses, bool), omit_addresses
url = make_url(coin_symbol, **dict(addrs=wallet_name))
params = {}
if txn_limit:
params['limit'] = txn_limit
if api_key:
params['token'] = api_key
if before_bh:
params['before'] = before_bh
if after_bh:
params['after'] = after_bh
if confirmations:
params['confirmations'] = confirmations
if unspent_only:
params['unspentOnly'] = 'true'
if show_confidence:
params['includeConfidence'] = 'true'
if omit_addresses:
params['omitWalletAddresses'] = 'true'
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return _clean_tx(get_valid_json(r)) | python | def get_wallet_transactions(wallet_name, api_key, coin_symbol='btc',
before_bh=None, after_bh=None, txn_limit=None, omit_addresses=False,
unspent_only=False, show_confidence=False, confirmations=0):
'''
Takes a wallet, api_key, coin_symbol and returns the wallet's details
Optional:
- txn_limit: # transactions to include
- before_bh: filters response to only include transactions below before
height in the blockchain.
- after_bh: filters response to only include transactions above after
height in the blockchain.
- confirmations: returns the balance and TXRefs that have this number
of confirmations
- unspent_only: filters response to only include unspent TXRefs.
- show_confidence: adds confidence information to unconfirmed TXRefs.
'''
assert len(wallet_name) <= 25, wallet_name
assert api_key
assert is_valid_coin_symbol(coin_symbol=coin_symbol)
assert isinstance(show_confidence, bool), show_confidence
assert isinstance(omit_addresses, bool), omit_addresses
url = make_url(coin_symbol, **dict(addrs=wallet_name))
params = {}
if txn_limit:
params['limit'] = txn_limit
if api_key:
params['token'] = api_key
if before_bh:
params['before'] = before_bh
if after_bh:
params['after'] = after_bh
if confirmations:
params['confirmations'] = confirmations
if unspent_only:
params['unspentOnly'] = 'true'
if show_confidence:
params['includeConfidence'] = 'true'
if omit_addresses:
params['omitWalletAddresses'] = 'true'
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return _clean_tx(get_valid_json(r)) | [
"def",
"get_wallet_transactions",
"(",
"wallet_name",
",",
"api_key",
",",
"coin_symbol",
"=",
"'btc'",
",",
"before_bh",
"=",
"None",
",",
"after_bh",
"=",
"None",
",",
"txn_limit",
"=",
"None",
",",
"omit_addresses",
"=",
"False",
",",
"unspent_only",
"=",
... | Takes a wallet, api_key, coin_symbol and returns the wallet's details
Optional:
- txn_limit: # transactions to include
- before_bh: filters response to only include transactions below before
height in the blockchain.
- after_bh: filters response to only include transactions above after
height in the blockchain.
- confirmations: returns the balance and TXRefs that have this number
of confirmations
- unspent_only: filters response to only include unspent TXRefs.
- show_confidence: adds confidence information to unconfirmed TXRefs. | [
"Takes",
"a",
"wallet",
"api_key",
"coin_symbol",
"and",
"returns",
"the",
"wallet",
"s",
"details"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L232-L278 | train | 208,818 |
blockcypher/blockcypher-python | blockcypher/api.py | get_address_overview | def get_address_overview(address, coin_symbol='btc', api_key=None):
'''
Takes an address and coin_symbol and return the address details
'''
assert is_valid_address_for_coinsymbol(b58_address=address,
coin_symbol=coin_symbol)
url = make_url(coin_symbol, 'addrs', **{address: 'balance'})
params = {}
if api_key:
params['token'] = api_key
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) | python | def get_address_overview(address, coin_symbol='btc', api_key=None):
'''
Takes an address and coin_symbol and return the address details
'''
assert is_valid_address_for_coinsymbol(b58_address=address,
coin_symbol=coin_symbol)
url = make_url(coin_symbol, 'addrs', **{address: 'balance'})
params = {}
if api_key:
params['token'] = api_key
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) | [
"def",
"get_address_overview",
"(",
"address",
",",
"coin_symbol",
"=",
"'btc'",
",",
"api_key",
"=",
"None",
")",
":",
"assert",
"is_valid_address_for_coinsymbol",
"(",
"b58_address",
"=",
"address",
",",
"coin_symbol",
"=",
"coin_symbol",
")",
"url",
"=",
"mak... | Takes an address and coin_symbol and return the address details | [
"Takes",
"an",
"address",
"and",
"coin_symbol",
"and",
"return",
"the",
"address",
"details"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L281-L296 | train | 208,819 |
blockcypher/blockcypher-python | blockcypher/api.py | generate_new_address | def generate_new_address(coin_symbol='btc', api_key=None):
'''
Takes a coin_symbol and returns a new address with it's public and private keys.
This method will create the address server side, which is inherently insecure and should only be used for testing.
If you want to create a secure address client-side using python, please check out bitmerchant:
from bitmerchant.wallet import Wallet
Wallet.new_random_wallet()
https://github.com/sbuss/bitmerchant
'''
assert api_key, 'api_key required'
assert is_valid_coin_symbol(coin_symbol)
if coin_symbol not in ('btc-testnet', 'bcy'):
WARNING_MSG = [
'Generating private key details server-side.',
'You really should do this client-side.',
'See https://github.com/sbuss/bitmerchant for an example.',
]
print(' '.join(WARNING_MSG))
url = make_url(coin_symbol, 'addrs')
params = {'token': api_key}
r = requests.post(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) | python | def generate_new_address(coin_symbol='btc', api_key=None):
'''
Takes a coin_symbol and returns a new address with it's public and private keys.
This method will create the address server side, which is inherently insecure and should only be used for testing.
If you want to create a secure address client-side using python, please check out bitmerchant:
from bitmerchant.wallet import Wallet
Wallet.new_random_wallet()
https://github.com/sbuss/bitmerchant
'''
assert api_key, 'api_key required'
assert is_valid_coin_symbol(coin_symbol)
if coin_symbol not in ('btc-testnet', 'bcy'):
WARNING_MSG = [
'Generating private key details server-side.',
'You really should do this client-side.',
'See https://github.com/sbuss/bitmerchant for an example.',
]
print(' '.join(WARNING_MSG))
url = make_url(coin_symbol, 'addrs')
params = {'token': api_key}
r = requests.post(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) | [
"def",
"generate_new_address",
"(",
"coin_symbol",
"=",
"'btc'",
",",
"api_key",
"=",
"None",
")",
":",
"assert",
"api_key",
",",
"'api_key required'",
"assert",
"is_valid_coin_symbol",
"(",
"coin_symbol",
")",
"if",
"coin_symbol",
"not",
"in",
"(",
"'btc-testnet'... | Takes a coin_symbol and returns a new address with it's public and private keys.
This method will create the address server side, which is inherently insecure and should only be used for testing.
If you want to create a secure address client-side using python, please check out bitmerchant:
from bitmerchant.wallet import Wallet
Wallet.new_random_wallet()
https://github.com/sbuss/bitmerchant | [
"Takes",
"a",
"coin_symbol",
"and",
"returns",
"a",
"new",
"address",
"with",
"it",
"s",
"public",
"and",
"private",
"keys",
"."
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L349-L378 | train | 208,820 |
blockcypher/blockcypher-python | blockcypher/api.py | get_transaction_details | def get_transaction_details(tx_hash, coin_symbol='btc', limit=None, tx_input_offset=None, tx_output_offset=None,
include_hex=False, show_confidence=False, confidence_only=False, api_key=None):
"""
Takes a tx_hash, coin_symbol, and limit and returns the transaction details
Optional:
- limit: # inputs/ouputs to include (applies to both)
- tx_input_offset: input offset
- tx_output_offset: output offset
- include_hex: include the raw TX hex
- show_confidence: adds confidence information to unconfirmed TXRefs.
- confidence_only: show only the confidence statistics and don't return the rest of the endpoint details (faster)
"""
assert is_valid_hash(tx_hash), tx_hash
assert is_valid_coin_symbol(coin_symbol), coin_symbol
added = 'txs/{}{}'.format(tx_hash, '/confidence' if confidence_only else '')
url = make_url(coin_symbol, added)
params = {}
if api_key:
params['token'] = api_key
if limit:
params['limit'] = limit
if tx_input_offset:
params['inStart'] = tx_input_offset
if tx_output_offset:
params['outStart'] = tx_output_offset
if include_hex:
params['includeHex'] = 'true'
if show_confidence and not confidence_only:
params['includeConfidence'] = 'true'
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
if 'error' not in response_dict and not confidence_only:
if response_dict['block_height'] > 0:
response_dict['confirmed'] = parser.parse(response_dict['confirmed'])
else:
response_dict['block_height'] = None
# Blockcypher reports fake times if it's not in a block
response_dict['confirmed'] = None
# format this string as a datetime object
response_dict['received'] = parser.parse(response_dict['received'])
return response_dict | python | def get_transaction_details(tx_hash, coin_symbol='btc', limit=None, tx_input_offset=None, tx_output_offset=None,
include_hex=False, show_confidence=False, confidence_only=False, api_key=None):
"""
Takes a tx_hash, coin_symbol, and limit and returns the transaction details
Optional:
- limit: # inputs/ouputs to include (applies to both)
- tx_input_offset: input offset
- tx_output_offset: output offset
- include_hex: include the raw TX hex
- show_confidence: adds confidence information to unconfirmed TXRefs.
- confidence_only: show only the confidence statistics and don't return the rest of the endpoint details (faster)
"""
assert is_valid_hash(tx_hash), tx_hash
assert is_valid_coin_symbol(coin_symbol), coin_symbol
added = 'txs/{}{}'.format(tx_hash, '/confidence' if confidence_only else '')
url = make_url(coin_symbol, added)
params = {}
if api_key:
params['token'] = api_key
if limit:
params['limit'] = limit
if tx_input_offset:
params['inStart'] = tx_input_offset
if tx_output_offset:
params['outStart'] = tx_output_offset
if include_hex:
params['includeHex'] = 'true'
if show_confidence and not confidence_only:
params['includeConfidence'] = 'true'
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
if 'error' not in response_dict and not confidence_only:
if response_dict['block_height'] > 0:
response_dict['confirmed'] = parser.parse(response_dict['confirmed'])
else:
response_dict['block_height'] = None
# Blockcypher reports fake times if it's not in a block
response_dict['confirmed'] = None
# format this string as a datetime object
response_dict['received'] = parser.parse(response_dict['received'])
return response_dict | [
"def",
"get_transaction_details",
"(",
"tx_hash",
",",
"coin_symbol",
"=",
"'btc'",
",",
"limit",
"=",
"None",
",",
"tx_input_offset",
"=",
"None",
",",
"tx_output_offset",
"=",
"None",
",",
"include_hex",
"=",
"False",
",",
"show_confidence",
"=",
"False",
",... | Takes a tx_hash, coin_symbol, and limit and returns the transaction details
Optional:
- limit: # inputs/ouputs to include (applies to both)
- tx_input_offset: input offset
- tx_output_offset: output offset
- include_hex: include the raw TX hex
- show_confidence: adds confidence information to unconfirmed TXRefs.
- confidence_only: show only the confidence statistics and don't return the rest of the endpoint details (faster) | [
"Takes",
"a",
"tx_hash",
"coin_symbol",
"and",
"limit",
"and",
"returns",
"the",
"transaction",
"details"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L411-L460 | train | 208,821 |
blockcypher/blockcypher-python | blockcypher/api.py | get_transactions_details | def get_transactions_details(tx_hash_list, coin_symbol='btc', limit=None, api_key=None):
"""
Takes a list of tx_hashes, coin_symbol, and limit and returns the transaction details
Limit applies to both num inputs and num outputs.
TODO: add offsetting once supported
"""
for tx_hash in tx_hash_list:
assert is_valid_hash(tx_hash)
assert is_valid_coin_symbol(coin_symbol)
if len(tx_hash_list) == 0:
return []
elif len(tx_hash_list) == 1:
return [get_transaction_details(tx_hash=tx_hash_list[0],
coin_symbol=coin_symbol,
limit=limit,
api_key=api_key
)]
url = make_url(coin_symbol, **dict(txs=';'.join(tx_hash_list)))
params = {}
if api_key:
params['token'] = api_key
if limit:
params['limit'] = limit
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict_list = get_valid_json(r)
cleaned_dict_list = []
for response_dict in response_dict_list:
if 'error' not in response_dict:
if response_dict['block_height'] > 0:
response_dict['confirmed'] = parser.parse(response_dict['confirmed'])
else:
# Blockcypher reports fake times if it's not in a block
response_dict['confirmed'] = None
response_dict['block_height'] = None
# format this string as a datetime object
response_dict['received'] = parser.parse(response_dict['received'])
cleaned_dict_list.append(response_dict)
return cleaned_dict_list | python | def get_transactions_details(tx_hash_list, coin_symbol='btc', limit=None, api_key=None):
"""
Takes a list of tx_hashes, coin_symbol, and limit and returns the transaction details
Limit applies to both num inputs and num outputs.
TODO: add offsetting once supported
"""
for tx_hash in tx_hash_list:
assert is_valid_hash(tx_hash)
assert is_valid_coin_symbol(coin_symbol)
if len(tx_hash_list) == 0:
return []
elif len(tx_hash_list) == 1:
return [get_transaction_details(tx_hash=tx_hash_list[0],
coin_symbol=coin_symbol,
limit=limit,
api_key=api_key
)]
url = make_url(coin_symbol, **dict(txs=';'.join(tx_hash_list)))
params = {}
if api_key:
params['token'] = api_key
if limit:
params['limit'] = limit
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict_list = get_valid_json(r)
cleaned_dict_list = []
for response_dict in response_dict_list:
if 'error' not in response_dict:
if response_dict['block_height'] > 0:
response_dict['confirmed'] = parser.parse(response_dict['confirmed'])
else:
# Blockcypher reports fake times if it's not in a block
response_dict['confirmed'] = None
response_dict['block_height'] = None
# format this string as a datetime object
response_dict['received'] = parser.parse(response_dict['received'])
cleaned_dict_list.append(response_dict)
return cleaned_dict_list | [
"def",
"get_transactions_details",
"(",
"tx_hash_list",
",",
"coin_symbol",
"=",
"'btc'",
",",
"limit",
"=",
"None",
",",
"api_key",
"=",
"None",
")",
":",
"for",
"tx_hash",
"in",
"tx_hash_list",
":",
"assert",
"is_valid_hash",
"(",
"tx_hash",
")",
"assert",
... | Takes a list of tx_hashes, coin_symbol, and limit and returns the transaction details
Limit applies to both num inputs and num outputs.
TODO: add offsetting once supported | [
"Takes",
"a",
"list",
"of",
"tx_hashes",
"coin_symbol",
"and",
"limit",
"and",
"returns",
"the",
"transaction",
"details"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L463-L510 | train | 208,822 |
blockcypher/blockcypher-python | blockcypher/api.py | get_num_confirmations | def get_num_confirmations(tx_hash, coin_symbol='btc', api_key=None):
'''
Given a tx_hash, return the number of confirmations that transactions has.
Answer is going to be from 0 - current_block_height.
'''
return get_transaction_details(tx_hash=tx_hash, coin_symbol=coin_symbol,
limit=1, api_key=api_key).get('confirmations') | python | def get_num_confirmations(tx_hash, coin_symbol='btc', api_key=None):
'''
Given a tx_hash, return the number of confirmations that transactions has.
Answer is going to be from 0 - current_block_height.
'''
return get_transaction_details(tx_hash=tx_hash, coin_symbol=coin_symbol,
limit=1, api_key=api_key).get('confirmations') | [
"def",
"get_num_confirmations",
"(",
"tx_hash",
",",
"coin_symbol",
"=",
"'btc'",
",",
"api_key",
"=",
"None",
")",
":",
"return",
"get_transaction_details",
"(",
"tx_hash",
"=",
"tx_hash",
",",
"coin_symbol",
"=",
"coin_symbol",
",",
"limit",
"=",
"1",
",",
... | Given a tx_hash, return the number of confirmations that transactions has.
Answer is going to be from 0 - current_block_height. | [
"Given",
"a",
"tx_hash",
"return",
"the",
"number",
"of",
"confirmations",
"that",
"transactions",
"has",
"."
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L513-L520 | train | 208,823 |
blockcypher/blockcypher-python | blockcypher/api.py | get_broadcast_transactions | def get_broadcast_transactions(coin_symbol='btc', limit=10, api_key=None):
"""
Get a list of broadcast but unconfirmed transactions
Similar to bitcoind's getrawmempool method
"""
url = make_url(coin_symbol, 'txs')
params = {}
if api_key:
params['token'] = api_key
if limit:
params['limit'] = limit
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
unconfirmed_txs = []
for unconfirmed_tx in response_dict:
unconfirmed_tx['received'] = parser.parse(unconfirmed_tx['received'])
unconfirmed_txs.append(unconfirmed_tx)
return unconfirmed_txs | python | def get_broadcast_transactions(coin_symbol='btc', limit=10, api_key=None):
"""
Get a list of broadcast but unconfirmed transactions
Similar to bitcoind's getrawmempool method
"""
url = make_url(coin_symbol, 'txs')
params = {}
if api_key:
params['token'] = api_key
if limit:
params['limit'] = limit
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
unconfirmed_txs = []
for unconfirmed_tx in response_dict:
unconfirmed_tx['received'] = parser.parse(unconfirmed_tx['received'])
unconfirmed_txs.append(unconfirmed_tx)
return unconfirmed_txs | [
"def",
"get_broadcast_transactions",
"(",
"coin_symbol",
"=",
"'btc'",
",",
"limit",
"=",
"10",
",",
"api_key",
"=",
"None",
")",
":",
"url",
"=",
"make_url",
"(",
"coin_symbol",
",",
"'txs'",
")",
"params",
"=",
"{",
"}",
"if",
"api_key",
":",
"params",... | Get a list of broadcast but unconfirmed transactions
Similar to bitcoind's getrawmempool method | [
"Get",
"a",
"list",
"of",
"broadcast",
"but",
"unconfirmed",
"transactions",
"Similar",
"to",
"bitcoind",
"s",
"getrawmempool",
"method"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L548-L568 | train | 208,824 |
blockcypher/blockcypher-python | blockcypher/api.py | get_block_overview | def get_block_overview(block_representation, coin_symbol='btc', txn_limit=None,
txn_offset=None, api_key=None):
"""
Takes a block_representation, coin_symbol and txn_limit and gets an overview
of that block, including up to X transaction ids.
Note that block_representation may be the block number or block hash
"""
assert is_valid_coin_symbol(coin_symbol)
assert is_valid_block_representation(
block_representation=block_representation,
coin_symbol=coin_symbol)
url = make_url(coin_symbol, **dict(blocks=block_representation))
params = {}
if api_key:
params['token'] = api_key
if txn_limit:
params['limit'] = txn_limit
if txn_offset:
params['txstart'] = txn_offset
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
if 'error' in response_dict:
return response_dict
return _clean_block(response_dict=response_dict) | python | def get_block_overview(block_representation, coin_symbol='btc', txn_limit=None,
txn_offset=None, api_key=None):
"""
Takes a block_representation, coin_symbol and txn_limit and gets an overview
of that block, including up to X transaction ids.
Note that block_representation may be the block number or block hash
"""
assert is_valid_coin_symbol(coin_symbol)
assert is_valid_block_representation(
block_representation=block_representation,
coin_symbol=coin_symbol)
url = make_url(coin_symbol, **dict(blocks=block_representation))
params = {}
if api_key:
params['token'] = api_key
if txn_limit:
params['limit'] = txn_limit
if txn_offset:
params['txstart'] = txn_offset
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
if 'error' in response_dict:
return response_dict
return _clean_block(response_dict=response_dict) | [
"def",
"get_block_overview",
"(",
"block_representation",
",",
"coin_symbol",
"=",
"'btc'",
",",
"txn_limit",
"=",
"None",
",",
"txn_offset",
"=",
"None",
",",
"api_key",
"=",
"None",
")",
":",
"assert",
"is_valid_coin_symbol",
"(",
"coin_symbol",
")",
"assert",... | Takes a block_representation, coin_symbol and txn_limit and gets an overview
of that block, including up to X transaction ids.
Note that block_representation may be the block number or block hash | [
"Takes",
"a",
"block_representation",
"coin_symbol",
"and",
"txn_limit",
"and",
"gets",
"an",
"overview",
"of",
"that",
"block",
"including",
"up",
"to",
"X",
"transaction",
"ids",
".",
"Note",
"that",
"block_representation",
"may",
"be",
"the",
"block",
"number... | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L584-L612 | train | 208,825 |
blockcypher/blockcypher-python | blockcypher/api.py | get_blocks_overview | def get_blocks_overview(block_representation_list, coin_symbol='btc', txn_limit=None, api_key=None):
'''
Batch request version of get_blocks_overview
'''
for block_representation in block_representation_list:
assert is_valid_block_representation(
block_representation=block_representation,
coin_symbol=coin_symbol)
assert is_valid_coin_symbol(coin_symbol)
blocks = ';'.join([str(x) for x in block_representation_list])
url = make_url(coin_symbol, **dict(blocks=blocks))
logger.info(url)
params = {}
if api_key:
params['token'] = api_key
if txn_limit:
params['limit'] = txn_limit
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
r = get_valid_json(r)
return [_clean_tx(response_dict=d) for d in r] | python | def get_blocks_overview(block_representation_list, coin_symbol='btc', txn_limit=None, api_key=None):
'''
Batch request version of get_blocks_overview
'''
for block_representation in block_representation_list:
assert is_valid_block_representation(
block_representation=block_representation,
coin_symbol=coin_symbol)
assert is_valid_coin_symbol(coin_symbol)
blocks = ';'.join([str(x) for x in block_representation_list])
url = make_url(coin_symbol, **dict(blocks=blocks))
logger.info(url)
params = {}
if api_key:
params['token'] = api_key
if txn_limit:
params['limit'] = txn_limit
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
r = get_valid_json(r)
return [_clean_tx(response_dict=d) for d in r] | [
"def",
"get_blocks_overview",
"(",
"block_representation_list",
",",
"coin_symbol",
"=",
"'btc'",
",",
"txn_limit",
"=",
"None",
",",
"api_key",
"=",
"None",
")",
":",
"for",
"block_representation",
"in",
"block_representation_list",
":",
"assert",
"is_valid_block_rep... | Batch request version of get_blocks_overview | [
"Batch",
"request",
"version",
"of",
"get_blocks_overview"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L615-L638 | train | 208,826 |
blockcypher/blockcypher-python | blockcypher/api.py | get_merkle_root | def get_merkle_root(block_representation, coin_symbol='btc', api_key=None):
'''
Takes a block_representation and returns the merkle root
'''
return get_block_overview(block_representation=block_representation,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['mrkl_root'] | python | def get_merkle_root(block_representation, coin_symbol='btc', api_key=None):
'''
Takes a block_representation and returns the merkle root
'''
return get_block_overview(block_representation=block_representation,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['mrkl_root'] | [
"def",
"get_merkle_root",
"(",
"block_representation",
",",
"coin_symbol",
"=",
"'btc'",
",",
"api_key",
"=",
"None",
")",
":",
"return",
"get_block_overview",
"(",
"block_representation",
"=",
"block_representation",
",",
"coin_symbol",
"=",
"coin_symbol",
",",
"tx... | Takes a block_representation and returns the merkle root | [
"Takes",
"a",
"block_representation",
"and",
"returns",
"the",
"merkle",
"root"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L641-L646 | train | 208,827 |
blockcypher/blockcypher-python | blockcypher/api.py | get_bits | def get_bits(block_representation, coin_symbol='btc', api_key=None):
'''
Takes a block_representation and returns the number of bits
'''
return get_block_overview(block_representation=block_representation,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['bits'] | python | def get_bits(block_representation, coin_symbol='btc', api_key=None):
'''
Takes a block_representation and returns the number of bits
'''
return get_block_overview(block_representation=block_representation,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['bits'] | [
"def",
"get_bits",
"(",
"block_representation",
",",
"coin_symbol",
"=",
"'btc'",
",",
"api_key",
"=",
"None",
")",
":",
"return",
"get_block_overview",
"(",
"block_representation",
"=",
"block_representation",
",",
"coin_symbol",
"=",
"coin_symbol",
",",
"txn_limit... | Takes a block_representation and returns the number of bits | [
"Takes",
"a",
"block_representation",
"and",
"returns",
"the",
"number",
"of",
"bits"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L649-L654 | train | 208,828 |
blockcypher/blockcypher-python | blockcypher/api.py | get_nonce | def get_nonce(block_representation, coin_symbol='btc', api_key=None):
'''
Takes a block_representation and returns the nonce
'''
return get_block_overview(block_representation=block_representation,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['bits'] | python | def get_nonce(block_representation, coin_symbol='btc', api_key=None):
'''
Takes a block_representation and returns the nonce
'''
return get_block_overview(block_representation=block_representation,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['bits'] | [
"def",
"get_nonce",
"(",
"block_representation",
",",
"coin_symbol",
"=",
"'btc'",
",",
"api_key",
"=",
"None",
")",
":",
"return",
"get_block_overview",
"(",
"block_representation",
"=",
"block_representation",
",",
"coin_symbol",
"=",
"coin_symbol",
",",
"txn_limi... | Takes a block_representation and returns the nonce | [
"Takes",
"a",
"block_representation",
"and",
"returns",
"the",
"nonce"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L657-L662 | train | 208,829 |
blockcypher/blockcypher-python | blockcypher/api.py | get_prev_block_hash | def get_prev_block_hash(block_representation, coin_symbol='btc', api_key=None):
'''
Takes a block_representation and returns the previous block hash
'''
return get_block_overview(block_representation=block_representation,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['prev_block'] | python | def get_prev_block_hash(block_representation, coin_symbol='btc', api_key=None):
'''
Takes a block_representation and returns the previous block hash
'''
return get_block_overview(block_representation=block_representation,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['prev_block'] | [
"def",
"get_prev_block_hash",
"(",
"block_representation",
",",
"coin_symbol",
"=",
"'btc'",
",",
"api_key",
"=",
"None",
")",
":",
"return",
"get_block_overview",
"(",
"block_representation",
"=",
"block_representation",
",",
"coin_symbol",
"=",
"coin_symbol",
",",
... | Takes a block_representation and returns the previous block hash | [
"Takes",
"a",
"block_representation",
"and",
"returns",
"the",
"previous",
"block",
"hash"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L665-L670 | train | 208,830 |
blockcypher/blockcypher-python | blockcypher/api.py | get_block_hash | def get_block_hash(block_height, coin_symbol='btc', api_key=None):
'''
Takes a block_height and returns the block_hash
'''
return get_block_overview(block_representation=block_height,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['hash'] | python | def get_block_hash(block_height, coin_symbol='btc', api_key=None):
'''
Takes a block_height and returns the block_hash
'''
return get_block_overview(block_representation=block_height,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['hash'] | [
"def",
"get_block_hash",
"(",
"block_height",
",",
"coin_symbol",
"=",
"'btc'",
",",
"api_key",
"=",
"None",
")",
":",
"return",
"get_block_overview",
"(",
"block_representation",
"=",
"block_height",
",",
"coin_symbol",
"=",
"coin_symbol",
",",
"txn_limit",
"=",
... | Takes a block_height and returns the block_hash | [
"Takes",
"a",
"block_height",
"and",
"returns",
"the",
"block_hash"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L673-L678 | train | 208,831 |
blockcypher/blockcypher-python | blockcypher/api.py | get_block_height | def get_block_height(block_hash, coin_symbol='btc', api_key=None):
'''
Takes a block_hash and returns the block_height
'''
return get_block_overview(block_representation=block_hash,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['height'] | python | def get_block_height(block_hash, coin_symbol='btc', api_key=None):
'''
Takes a block_hash and returns the block_height
'''
return get_block_overview(block_representation=block_hash,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['height'] | [
"def",
"get_block_height",
"(",
"block_hash",
",",
"coin_symbol",
"=",
"'btc'",
",",
"api_key",
"=",
"None",
")",
":",
"return",
"get_block_overview",
"(",
"block_representation",
"=",
"block_hash",
",",
"coin_symbol",
"=",
"coin_symbol",
",",
"txn_limit",
"=",
... | Takes a block_hash and returns the block_height | [
"Takes",
"a",
"block_hash",
"and",
"returns",
"the",
"block_height"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L681-L686 | train | 208,832 |
blockcypher/blockcypher-python | blockcypher/api.py | get_block_details | def get_block_details(block_representation, coin_symbol='btc', txn_limit=None,
txn_offset=None, in_out_limit=None, api_key=None):
"""
Takes a block_representation, coin_symbol and txn_limit and
1) Gets the block overview
2) Makes a separate API call to get specific data on txn_limit transactions
Note: block_representation may be the block number or block hash
WARNING: using a high txn_limit will make this *extremely* slow.
"""
assert is_valid_coin_symbol(coin_symbol)
block_overview = get_block_overview(
block_representation=block_representation,
coin_symbol=coin_symbol,
txn_limit=txn_limit,
txn_offset=txn_offset,
api_key=api_key,
)
if 'error' in block_overview:
return block_overview
txids_to_lookup = block_overview['txids']
txs_details = get_transactions_details(
tx_hash_list=txids_to_lookup,
coin_symbol=coin_symbol,
limit=in_out_limit,
api_key=api_key,
)
if 'error' in txs_details:
return txs_details
# build comparator dict to use for fast sorting of batched results later
txids_comparator_dict = {}
for cnt, tx_id in enumerate(txids_to_lookup):
txids_comparator_dict[tx_id] = cnt
# sort results using comparator dict
block_overview['txids'] = sorted(
txs_details,
key=lambda k: txids_comparator_dict.get(k.get('hash'), 9999), # anything that fails goes last
)
return block_overview | python | def get_block_details(block_representation, coin_symbol='btc', txn_limit=None,
txn_offset=None, in_out_limit=None, api_key=None):
"""
Takes a block_representation, coin_symbol and txn_limit and
1) Gets the block overview
2) Makes a separate API call to get specific data on txn_limit transactions
Note: block_representation may be the block number or block hash
WARNING: using a high txn_limit will make this *extremely* slow.
"""
assert is_valid_coin_symbol(coin_symbol)
block_overview = get_block_overview(
block_representation=block_representation,
coin_symbol=coin_symbol,
txn_limit=txn_limit,
txn_offset=txn_offset,
api_key=api_key,
)
if 'error' in block_overview:
return block_overview
txids_to_lookup = block_overview['txids']
txs_details = get_transactions_details(
tx_hash_list=txids_to_lookup,
coin_symbol=coin_symbol,
limit=in_out_limit,
api_key=api_key,
)
if 'error' in txs_details:
return txs_details
# build comparator dict to use for fast sorting of batched results later
txids_comparator_dict = {}
for cnt, tx_id in enumerate(txids_to_lookup):
txids_comparator_dict[tx_id] = cnt
# sort results using comparator dict
block_overview['txids'] = sorted(
txs_details,
key=lambda k: txids_comparator_dict.get(k.get('hash'), 9999), # anything that fails goes last
)
return block_overview | [
"def",
"get_block_details",
"(",
"block_representation",
",",
"coin_symbol",
"=",
"'btc'",
",",
"txn_limit",
"=",
"None",
",",
"txn_offset",
"=",
"None",
",",
"in_out_limit",
"=",
"None",
",",
"api_key",
"=",
"None",
")",
":",
"assert",
"is_valid_coin_symbol",
... | Takes a block_representation, coin_symbol and txn_limit and
1) Gets the block overview
2) Makes a separate API call to get specific data on txn_limit transactions
Note: block_representation may be the block number or block hash
WARNING: using a high txn_limit will make this *extremely* slow. | [
"Takes",
"a",
"block_representation",
"coin_symbol",
"and",
"txn_limit",
"and",
"1",
")",
"Gets",
"the",
"block",
"overview",
"2",
")",
"Makes",
"a",
"separate",
"API",
"call",
"to",
"get",
"specific",
"data",
"on",
"txn_limit",
"transactions"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L689-L737 | train | 208,833 |
blockcypher/blockcypher-python | blockcypher/api.py | get_blockchain_fee_estimates | def get_blockchain_fee_estimates(coin_symbol='btc', api_key=None):
"""
Returns high, medium, and low fee estimates for a given blockchain.
"""
overview = get_blockchain_overview(coin_symbol=coin_symbol, api_key=api_key)
return {
'high_fee_per_kb': overview['high_fee_per_kb'],
'medium_fee_per_kb': overview['medium_fee_per_kb'],
'low_fee_per_kb': overview['low_fee_per_kb'],
} | python | def get_blockchain_fee_estimates(coin_symbol='btc', api_key=None):
"""
Returns high, medium, and low fee estimates for a given blockchain.
"""
overview = get_blockchain_overview(coin_symbol=coin_symbol, api_key=api_key)
return {
'high_fee_per_kb': overview['high_fee_per_kb'],
'medium_fee_per_kb': overview['medium_fee_per_kb'],
'low_fee_per_kb': overview['low_fee_per_kb'],
} | [
"def",
"get_blockchain_fee_estimates",
"(",
"coin_symbol",
"=",
"'btc'",
",",
"api_key",
"=",
"None",
")",
":",
"overview",
"=",
"get_blockchain_overview",
"(",
"coin_symbol",
"=",
"coin_symbol",
",",
"api_key",
"=",
"api_key",
")",
"return",
"{",
"'high_fee_per_k... | Returns high, medium, and low fee estimates for a given blockchain. | [
"Returns",
"high",
"medium",
"and",
"low",
"fee",
"estimates",
"for",
"a",
"given",
"blockchain",
"."
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L776-L785 | train | 208,834 |
blockcypher/blockcypher-python | blockcypher/api.py | get_forwarding_address_details | def get_forwarding_address_details(destination_address, api_key, callback_url=None, coin_symbol='btc'):
"""
Give a destination address and return the details of the input address
that will automatically forward to the destination address
Note: a blockcypher api_key is required for this method
"""
assert is_valid_coin_symbol(coin_symbol)
assert api_key, 'api_key required'
url = make_url(coin_symbol, 'payments')
logger.info(url)
params = {'token': api_key}
data = {
'destination': destination_address,
}
if callback_url:
data['callback_url'] = callback_url
r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) | python | def get_forwarding_address_details(destination_address, api_key, callback_url=None, coin_symbol='btc'):
"""
Give a destination address and return the details of the input address
that will automatically forward to the destination address
Note: a blockcypher api_key is required for this method
"""
assert is_valid_coin_symbol(coin_symbol)
assert api_key, 'api_key required'
url = make_url(coin_symbol, 'payments')
logger.info(url)
params = {'token': api_key}
data = {
'destination': destination_address,
}
if callback_url:
data['callback_url'] = callback_url
r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) | [
"def",
"get_forwarding_address_details",
"(",
"destination_address",
",",
"api_key",
",",
"callback_url",
"=",
"None",
",",
"coin_symbol",
"=",
"'btc'",
")",
":",
"assert",
"is_valid_coin_symbol",
"(",
"coin_symbol",
")",
"assert",
"api_key",
",",
"'api_key required'"... | Give a destination address and return the details of the input address
that will automatically forward to the destination address
Note: a blockcypher api_key is required for this method | [
"Give",
"a",
"destination",
"address",
"and",
"return",
"the",
"details",
"of",
"the",
"input",
"address",
"that",
"will",
"automatically",
"forward",
"to",
"the",
"destination",
"address"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L817-L840 | train | 208,835 |
blockcypher/blockcypher-python | blockcypher/api.py | get_forwarding_address | def get_forwarding_address(destination_address, api_key, callback_url=None, coin_symbol='btc'):
"""
Give a destination address and return an input address that will
automatically forward to the destination address. See
get_forwarding_address_details if you also need the forwarding address ID.
Note: a blockcypher api_key is required for this method
"""
assert api_key, 'api_key required'
resp_dict = get_forwarding_address_details(
destination_address=destination_address,
api_key=api_key,
callback_url=callback_url,
coin_symbol=coin_symbol
)
return resp_dict['input_address'] | python | def get_forwarding_address(destination_address, api_key, callback_url=None, coin_symbol='btc'):
"""
Give a destination address and return an input address that will
automatically forward to the destination address. See
get_forwarding_address_details if you also need the forwarding address ID.
Note: a blockcypher api_key is required for this method
"""
assert api_key, 'api_key required'
resp_dict = get_forwarding_address_details(
destination_address=destination_address,
api_key=api_key,
callback_url=callback_url,
coin_symbol=coin_symbol
)
return resp_dict['input_address'] | [
"def",
"get_forwarding_address",
"(",
"destination_address",
",",
"api_key",
",",
"callback_url",
"=",
"None",
",",
"coin_symbol",
"=",
"'btc'",
")",
":",
"assert",
"api_key",
",",
"'api_key required'",
"resp_dict",
"=",
"get_forwarding_address_details",
"(",
"destina... | Give a destination address and return an input address that will
automatically forward to the destination address. See
get_forwarding_address_details if you also need the forwarding address ID.
Note: a blockcypher api_key is required for this method | [
"Give",
"a",
"destination",
"address",
"and",
"return",
"an",
"input",
"address",
"that",
"will",
"automatically",
"forward",
"to",
"the",
"destination",
"address",
".",
"See",
"get_forwarding_address_details",
"if",
"you",
"also",
"need",
"the",
"forwarding",
"ad... | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L843-L860 | train | 208,836 |
blockcypher/blockcypher-python | blockcypher/api.py | delete_forwarding_address | def delete_forwarding_address(payment_id, coin_symbol='btc', api_key=None):
'''
Delete a forwarding address on a specific blockchain, using its
payment id
'''
assert payment_id, 'payment_id required'
assert is_valid_coin_symbol(coin_symbol)
assert api_key, 'api_key required'
params = {'token': api_key}
url = make_url(**dict(payments=payment_id))
r = requests.delete(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r, allow_204=True) | python | def delete_forwarding_address(payment_id, coin_symbol='btc', api_key=None):
'''
Delete a forwarding address on a specific blockchain, using its
payment id
'''
assert payment_id, 'payment_id required'
assert is_valid_coin_symbol(coin_symbol)
assert api_key, 'api_key required'
params = {'token': api_key}
url = make_url(**dict(payments=payment_id))
r = requests.delete(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r, allow_204=True) | [
"def",
"delete_forwarding_address",
"(",
"payment_id",
",",
"coin_symbol",
"=",
"'btc'",
",",
"api_key",
"=",
"None",
")",
":",
"assert",
"payment_id",
",",
"'payment_id required'",
"assert",
"is_valid_coin_symbol",
"(",
"coin_symbol",
")",
"assert",
"api_key",
",",... | Delete a forwarding address on a specific blockchain, using its
payment id | [
"Delete",
"a",
"forwarding",
"address",
"on",
"a",
"specific",
"blockchain",
"using",
"its",
"payment",
"id"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L887-L902 | train | 208,837 |
blockcypher/blockcypher-python | blockcypher/api.py | send_faucet_coins | def send_faucet_coins(address_to_fund, satoshis, api_key, coin_symbol='bcy'):
'''
Send yourself test coins on the bitcoin or blockcypher testnet
You can see your balance info at:
- https://live.blockcypher.com/bcy/ for BCY
- https://live.blockcypher.com/btc-testnet/ for BTC Testnet
'''
assert coin_symbol in ('bcy', 'btc-testnet')
assert is_valid_address_for_coinsymbol(b58_address=address_to_fund, coin_symbol=coin_symbol)
assert satoshis > 0
assert api_key, 'api_key required'
url = make_url(coin_symbol, 'faucet')
data = {
'address': address_to_fund,
'amount': satoshis,
}
params = {'token': api_key}
r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) | python | def send_faucet_coins(address_to_fund, satoshis, api_key, coin_symbol='bcy'):
'''
Send yourself test coins on the bitcoin or blockcypher testnet
You can see your balance info at:
- https://live.blockcypher.com/bcy/ for BCY
- https://live.blockcypher.com/btc-testnet/ for BTC Testnet
'''
assert coin_symbol in ('bcy', 'btc-testnet')
assert is_valid_address_for_coinsymbol(b58_address=address_to_fund, coin_symbol=coin_symbol)
assert satoshis > 0
assert api_key, 'api_key required'
url = make_url(coin_symbol, 'faucet')
data = {
'address': address_to_fund,
'amount': satoshis,
}
params = {'token': api_key}
r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) | [
"def",
"send_faucet_coins",
"(",
"address_to_fund",
",",
"satoshis",
",",
"api_key",
",",
"coin_symbol",
"=",
"'bcy'",
")",
":",
"assert",
"coin_symbol",
"in",
"(",
"'bcy'",
",",
"'btc-testnet'",
")",
"assert",
"is_valid_address_for_coinsymbol",
"(",
"b58_address",
... | Send yourself test coins on the bitcoin or blockcypher testnet
You can see your balance info at:
- https://live.blockcypher.com/bcy/ for BCY
- https://live.blockcypher.com/btc-testnet/ for BTC Testnet | [
"Send",
"yourself",
"test",
"coins",
"on",
"the",
"bitcoin",
"or",
"blockcypher",
"testnet"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L996-L1018 | train | 208,838 |
blockcypher/blockcypher-python | blockcypher/api.py | list_wallet_names | def list_wallet_names(api_key, is_hd_wallet=False, coin_symbol='btc'):
''' Get all the wallets belonging to an API key '''
assert is_valid_coin_symbol(coin_symbol), coin_symbol
assert api_key
params = {'token': api_key}
kwargs = dict(wallets='hd' if is_hd_wallet else '')
url = make_url(coin_symbol, **kwargs)
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) | python | def list_wallet_names(api_key, is_hd_wallet=False, coin_symbol='btc'):
''' Get all the wallets belonging to an API key '''
assert is_valid_coin_symbol(coin_symbol), coin_symbol
assert api_key
params = {'token': api_key}
kwargs = dict(wallets='hd' if is_hd_wallet else '')
url = make_url(coin_symbol, **kwargs)
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) | [
"def",
"list_wallet_names",
"(",
"api_key",
",",
"is_hd_wallet",
"=",
"False",
",",
"coin_symbol",
"=",
"'btc'",
")",
":",
"assert",
"is_valid_coin_symbol",
"(",
"coin_symbol",
")",
",",
"coin_symbol",
"assert",
"api_key",
"params",
"=",
"{",
"'token'",
":",
"... | Get all the wallets belonging to an API key | [
"Get",
"all",
"the",
"wallets",
"belonging",
"to",
"an",
"API",
"key"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L1081-L1092 | train | 208,839 |
blockcypher/blockcypher-python | blockcypher/api.py | create_wallet_from_address | def create_wallet_from_address(wallet_name, address, api_key, coin_symbol='btc'):
'''
Create a new wallet with one address
You can add addresses with the add_address_to_wallet method below
You can delete the wallet with the delete_wallet method below
'''
assert is_valid_address_for_coinsymbol(address, coin_symbol)
assert api_key
assert is_valid_wallet_name(wallet_name), wallet_name
data = {
'name': wallet_name,
'addresses': [address, ],
}
params = {'token': api_key}
url = make_url(coin_symbol, 'wallets')
r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) | python | def create_wallet_from_address(wallet_name, address, api_key, coin_symbol='btc'):
'''
Create a new wallet with one address
You can add addresses with the add_address_to_wallet method below
You can delete the wallet with the delete_wallet method below
'''
assert is_valid_address_for_coinsymbol(address, coin_symbol)
assert api_key
assert is_valid_wallet_name(wallet_name), wallet_name
data = {
'name': wallet_name,
'addresses': [address, ],
}
params = {'token': api_key}
url = make_url(coin_symbol, 'wallets')
r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) | [
"def",
"create_wallet_from_address",
"(",
"wallet_name",
",",
"address",
",",
"api_key",
",",
"coin_symbol",
"=",
"'btc'",
")",
":",
"assert",
"is_valid_address_for_coinsymbol",
"(",
"address",
",",
"coin_symbol",
")",
"assert",
"api_key",
"assert",
"is_valid_wallet_n... | Create a new wallet with one address
You can add addresses with the add_address_to_wallet method below
You can delete the wallet with the delete_wallet method below | [
"Create",
"a",
"new",
"wallet",
"with",
"one",
"address"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L1094-L1113 | train | 208,840 |
blockcypher/blockcypher-python | blockcypher/api.py | get_wallet_addresses | def get_wallet_addresses(wallet_name, api_key, is_hd_wallet=False,
zero_balance=None, used=None, omit_addresses=False, coin_symbol='btc'):
'''
Returns a list of wallet addresses as well as some meta-data
'''
assert is_valid_coin_symbol(coin_symbol)
assert api_key
assert len(wallet_name) <= 25, wallet_name
assert zero_balance in (None, True, False)
assert used in (None, True, False)
assert isinstance(omit_addresses, bool), omit_addresses
params = {'token': api_key}
kwargs = {'hd/' if is_hd_wallet else '': wallet_name} # hack!
url = make_url(coin_symbol, 'wallets', **kwargs)
if zero_balance is True:
params['zerobalance'] = 'true'
elif zero_balance is False:
params['zerobalance'] = 'false'
if used is True:
params['used'] = 'true'
elif used is False:
params['used'] = 'false'
if omit_addresses:
params['omitWalletAddresses'] = 'true'
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) | python | def get_wallet_addresses(wallet_name, api_key, is_hd_wallet=False,
zero_balance=None, used=None, omit_addresses=False, coin_symbol='btc'):
'''
Returns a list of wallet addresses as well as some meta-data
'''
assert is_valid_coin_symbol(coin_symbol)
assert api_key
assert len(wallet_name) <= 25, wallet_name
assert zero_balance in (None, True, False)
assert used in (None, True, False)
assert isinstance(omit_addresses, bool), omit_addresses
params = {'token': api_key}
kwargs = {'hd/' if is_hd_wallet else '': wallet_name} # hack!
url = make_url(coin_symbol, 'wallets', **kwargs)
if zero_balance is True:
params['zerobalance'] = 'true'
elif zero_balance is False:
params['zerobalance'] = 'false'
if used is True:
params['used'] = 'true'
elif used is False:
params['used'] = 'false'
if omit_addresses:
params['omitWalletAddresses'] = 'true'
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) | [
"def",
"get_wallet_addresses",
"(",
"wallet_name",
",",
"api_key",
",",
"is_hd_wallet",
"=",
"False",
",",
"zero_balance",
"=",
"None",
",",
"used",
"=",
"None",
",",
"omit_addresses",
"=",
"False",
",",
"coin_symbol",
"=",
"'btc'",
")",
":",
"assert",
"is_v... | Returns a list of wallet addresses as well as some meta-data | [
"Returns",
"a",
"list",
"of",
"wallet",
"addresses",
"as",
"well",
"as",
"some",
"meta",
"-",
"data"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L1143-L1171 | train | 208,841 |
blockcypher/blockcypher-python | blockcypher/api.py | make_tx_signatures | def make_tx_signatures(txs_to_sign, privkey_list, pubkey_list):
"""
Loops through txs_to_sign and makes signatures using privkey_list and pubkey_list
Not sure what privkeys and pubkeys to supply?
Use get_input_addresses() to return a list of addresses.
Matching those addresses to keys is up to you and how you store your private keys.
A future version of this library may handle this for you, but it is not trivial.
Note that if spending multisig funds the process is significantly more complicated.
Each tx_to_sign must be signed by *each* private key.
In a 2-of-3 transaction, two of [privkey1, privkey2, privkey3] must sign each tx_to_sign
http://dev.blockcypher.com/#multisig-transactions
"""
assert len(privkey_list) == len(pubkey_list) == len(txs_to_sign)
# in the event of multiple inputs using the same pub/privkey,
# that privkey should be included multiple times
signatures = []
for cnt, tx_to_sign in enumerate(txs_to_sign):
sig = der_encode_sig(*ecdsa_raw_sign(tx_to_sign.rstrip(' \t\r\n\0'), privkey_list[cnt]))
err_msg = 'Bad Signature: sig %s for tx %s with pubkey %s' % (
sig,
tx_to_sign,
pubkey_list[cnt],
)
assert ecdsa_raw_verify(tx_to_sign, der_decode_sig(sig), pubkey_list[cnt]), err_msg
signatures.append(sig)
return signatures | python | def make_tx_signatures(txs_to_sign, privkey_list, pubkey_list):
"""
Loops through txs_to_sign and makes signatures using privkey_list and pubkey_list
Not sure what privkeys and pubkeys to supply?
Use get_input_addresses() to return a list of addresses.
Matching those addresses to keys is up to you and how you store your private keys.
A future version of this library may handle this for you, but it is not trivial.
Note that if spending multisig funds the process is significantly more complicated.
Each tx_to_sign must be signed by *each* private key.
In a 2-of-3 transaction, two of [privkey1, privkey2, privkey3] must sign each tx_to_sign
http://dev.blockcypher.com/#multisig-transactions
"""
assert len(privkey_list) == len(pubkey_list) == len(txs_to_sign)
# in the event of multiple inputs using the same pub/privkey,
# that privkey should be included multiple times
signatures = []
for cnt, tx_to_sign in enumerate(txs_to_sign):
sig = der_encode_sig(*ecdsa_raw_sign(tx_to_sign.rstrip(' \t\r\n\0'), privkey_list[cnt]))
err_msg = 'Bad Signature: sig %s for tx %s with pubkey %s' % (
sig,
tx_to_sign,
pubkey_list[cnt],
)
assert ecdsa_raw_verify(tx_to_sign, der_decode_sig(sig), pubkey_list[cnt]), err_msg
signatures.append(sig)
return signatures | [
"def",
"make_tx_signatures",
"(",
"txs_to_sign",
",",
"privkey_list",
",",
"pubkey_list",
")",
":",
"assert",
"len",
"(",
"privkey_list",
")",
"==",
"len",
"(",
"pubkey_list",
")",
"==",
"len",
"(",
"txs_to_sign",
")",
"# in the event of multiple inputs using the sa... | Loops through txs_to_sign and makes signatures using privkey_list and pubkey_list
Not sure what privkeys and pubkeys to supply?
Use get_input_addresses() to return a list of addresses.
Matching those addresses to keys is up to you and how you store your private keys.
A future version of this library may handle this for you, but it is not trivial.
Note that if spending multisig funds the process is significantly more complicated.
Each tx_to_sign must be signed by *each* private key.
In a 2-of-3 transaction, two of [privkey1, privkey2, privkey3] must sign each tx_to_sign
http://dev.blockcypher.com/#multisig-transactions | [
"Loops",
"through",
"txs_to_sign",
"and",
"makes",
"signatures",
"using",
"privkey_list",
"and",
"pubkey_list"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L1530-L1559 | train | 208,842 |
blockcypher/blockcypher-python | blockcypher/api.py | broadcast_signed_transaction | def broadcast_signed_transaction(unsigned_tx, signatures, pubkeys, coin_symbol='btc', api_key=None):
'''
Broadcasts the transaction from create_unsigned_tx
'''
assert 'errors' not in unsigned_tx, unsigned_tx
assert api_key, 'api_key required'
url = make_url(coin_symbol, **dict(txs='send'))
data = unsigned_tx.copy()
data['signatures'] = signatures
data['pubkeys'] = pubkeys
params = {'token': api_key}
r = requests.post(url, params=params, json=data, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
if response_dict.get('tx') and response_dict.get('received'):
response_dict['tx']['received'] = parser.parse(response_dict['tx']['received'])
return response_dict | python | def broadcast_signed_transaction(unsigned_tx, signatures, pubkeys, coin_symbol='btc', api_key=None):
'''
Broadcasts the transaction from create_unsigned_tx
'''
assert 'errors' not in unsigned_tx, unsigned_tx
assert api_key, 'api_key required'
url = make_url(coin_symbol, **dict(txs='send'))
data = unsigned_tx.copy()
data['signatures'] = signatures
data['pubkeys'] = pubkeys
params = {'token': api_key}
r = requests.post(url, params=params, json=data, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
if response_dict.get('tx') and response_dict.get('received'):
response_dict['tx']['received'] = parser.parse(response_dict['tx']['received'])
return response_dict | [
"def",
"broadcast_signed_transaction",
"(",
"unsigned_tx",
",",
"signatures",
",",
"pubkeys",
",",
"coin_symbol",
"=",
"'btc'",
",",
"api_key",
"=",
"None",
")",
":",
"assert",
"'errors'",
"not",
"in",
"unsigned_tx",
",",
"unsigned_tx",
"assert",
"api_key",
",",... | Broadcasts the transaction from create_unsigned_tx | [
"Broadcasts",
"the",
"transaction",
"from",
"create_unsigned_tx"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L1562-L1584 | train | 208,843 |
blockcypher/blockcypher-python | blockcypher/api.py | simple_spend | def simple_spend(from_privkey, to_address, to_satoshis, change_address=None,
privkey_is_compressed=True, min_confirmations=0, api_key=None, coin_symbol='btc'):
'''
Simple method to spend from one single-key address to another.
Signature takes place locally (client-side) after unsigned transaction is verified.
Returns the tx_hash of the newly broadcast tx.
If no change_address specified, change will be sent back to sender address.
Note that this violates the best practice.
To sweep, set to_satoshis=-1
Compressed public keys (and their corresponding addresses) have been the standard since v0.6,
set privkey_is_compressed=False if using uncompressed addresses.
Note that this currently only supports spending from single key addresses.
'''
assert is_valid_coin_symbol(coin_symbol), coin_symbol
assert isinstance(to_satoshis, int), to_satoshis
assert api_key, 'api_key required'
if privkey_is_compressed:
from_pubkey = compress(privkey_to_pubkey(from_privkey))
else:
from_pubkey = privkey_to_pubkey(from_privkey)
from_address = pubkey_to_address(
pubkey=from_pubkey,
# this method only supports paying from pubkey anyway
magicbyte=COIN_SYMBOL_MAPPINGS[coin_symbol]['vbyte_pubkey'],
)
inputs = [{'address': from_address}, ]
logger.info('inputs: %s' % inputs)
outputs = [{'address': to_address, 'value': to_satoshis}, ]
logger.info('outputs: %s' % outputs)
# will fail loudly if tx doesn't verify client-side
unsigned_tx = create_unsigned_tx(
inputs=inputs,
outputs=outputs,
# may build with no change address, but if so will verify change in next step
# done for extra security in case of client-side bug in change address generation
change_address=change_address,
coin_symbol=coin_symbol,
min_confirmations=min_confirmations,
verify_tosigntx=False, # will verify in next step
include_tosigntx=True,
api_key=api_key,
)
logger.info('unsigned_tx: %s' % unsigned_tx)
if 'errors' in unsigned_tx:
print('TX Error(s): Tx NOT Signed or Broadcast')
for error in unsigned_tx['errors']:
print(error['error'])
# Abandon
raise Exception('Build Unsigned TX Error')
if change_address:
change_address_to_use = change_address
else:
change_address_to_use = from_address
tx_is_correct, err_msg = verify_unsigned_tx(
unsigned_tx=unsigned_tx,
inputs=inputs,
outputs=outputs,
sweep_funds=bool(to_satoshis == -1),
change_address=change_address_to_use,
coin_symbol=coin_symbol,
)
if not tx_is_correct:
print(unsigned_tx) # for debug
raise Exception('TX Verification Error: %s' % err_msg)
privkey_list, pubkey_list = [], []
for proposed_input in unsigned_tx['tx']['inputs']:
privkey_list.append(from_privkey)
pubkey_list.append(from_pubkey)
# paying from a single key should only mean one address per input:
assert len(proposed_input['addresses']) == 1, proposed_input['addresses']
# logger.info('privkey_list: %s' % privkey_list)
logger.info('pubkey_list: %s' % pubkey_list)
# sign locally
tx_signatures = make_tx_signatures(
txs_to_sign=unsigned_tx['tosign'],
privkey_list=privkey_list,
pubkey_list=pubkey_list,
)
logger.info('tx_signatures: %s' % tx_signatures)
# broadcast TX
broadcasted_tx = broadcast_signed_transaction(
unsigned_tx=unsigned_tx,
signatures=tx_signatures,
pubkeys=pubkey_list,
coin_symbol=coin_symbol,
api_key=api_key,
)
logger.info('broadcasted_tx: %s' % broadcasted_tx)
if 'errors' in broadcasted_tx:
print('TX Error(s): Tx May NOT Have Been Broadcast')
for error in broadcasted_tx['errors']:
print(error['error'])
print(broadcasted_tx)
return
return broadcasted_tx['tx']['hash'] | python | def simple_spend(from_privkey, to_address, to_satoshis, change_address=None,
privkey_is_compressed=True, min_confirmations=0, api_key=None, coin_symbol='btc'):
'''
Simple method to spend from one single-key address to another.
Signature takes place locally (client-side) after unsigned transaction is verified.
Returns the tx_hash of the newly broadcast tx.
If no change_address specified, change will be sent back to sender address.
Note that this violates the best practice.
To sweep, set to_satoshis=-1
Compressed public keys (and their corresponding addresses) have been the standard since v0.6,
set privkey_is_compressed=False if using uncompressed addresses.
Note that this currently only supports spending from single key addresses.
'''
assert is_valid_coin_symbol(coin_symbol), coin_symbol
assert isinstance(to_satoshis, int), to_satoshis
assert api_key, 'api_key required'
if privkey_is_compressed:
from_pubkey = compress(privkey_to_pubkey(from_privkey))
else:
from_pubkey = privkey_to_pubkey(from_privkey)
from_address = pubkey_to_address(
pubkey=from_pubkey,
# this method only supports paying from pubkey anyway
magicbyte=COIN_SYMBOL_MAPPINGS[coin_symbol]['vbyte_pubkey'],
)
inputs = [{'address': from_address}, ]
logger.info('inputs: %s' % inputs)
outputs = [{'address': to_address, 'value': to_satoshis}, ]
logger.info('outputs: %s' % outputs)
# will fail loudly if tx doesn't verify client-side
unsigned_tx = create_unsigned_tx(
inputs=inputs,
outputs=outputs,
# may build with no change address, but if so will verify change in next step
# done for extra security in case of client-side bug in change address generation
change_address=change_address,
coin_symbol=coin_symbol,
min_confirmations=min_confirmations,
verify_tosigntx=False, # will verify in next step
include_tosigntx=True,
api_key=api_key,
)
logger.info('unsigned_tx: %s' % unsigned_tx)
if 'errors' in unsigned_tx:
print('TX Error(s): Tx NOT Signed or Broadcast')
for error in unsigned_tx['errors']:
print(error['error'])
# Abandon
raise Exception('Build Unsigned TX Error')
if change_address:
change_address_to_use = change_address
else:
change_address_to_use = from_address
tx_is_correct, err_msg = verify_unsigned_tx(
unsigned_tx=unsigned_tx,
inputs=inputs,
outputs=outputs,
sweep_funds=bool(to_satoshis == -1),
change_address=change_address_to_use,
coin_symbol=coin_symbol,
)
if not tx_is_correct:
print(unsigned_tx) # for debug
raise Exception('TX Verification Error: %s' % err_msg)
privkey_list, pubkey_list = [], []
for proposed_input in unsigned_tx['tx']['inputs']:
privkey_list.append(from_privkey)
pubkey_list.append(from_pubkey)
# paying from a single key should only mean one address per input:
assert len(proposed_input['addresses']) == 1, proposed_input['addresses']
# logger.info('privkey_list: %s' % privkey_list)
logger.info('pubkey_list: %s' % pubkey_list)
# sign locally
tx_signatures = make_tx_signatures(
txs_to_sign=unsigned_tx['tosign'],
privkey_list=privkey_list,
pubkey_list=pubkey_list,
)
logger.info('tx_signatures: %s' % tx_signatures)
# broadcast TX
broadcasted_tx = broadcast_signed_transaction(
unsigned_tx=unsigned_tx,
signatures=tx_signatures,
pubkeys=pubkey_list,
coin_symbol=coin_symbol,
api_key=api_key,
)
logger.info('broadcasted_tx: %s' % broadcasted_tx)
if 'errors' in broadcasted_tx:
print('TX Error(s): Tx May NOT Have Been Broadcast')
for error in broadcasted_tx['errors']:
print(error['error'])
print(broadcasted_tx)
return
return broadcasted_tx['tx']['hash'] | [
"def",
"simple_spend",
"(",
"from_privkey",
",",
"to_address",
",",
"to_satoshis",
",",
"change_address",
"=",
"None",
",",
"privkey_is_compressed",
"=",
"True",
",",
"min_confirmations",
"=",
"0",
",",
"api_key",
"=",
"None",
",",
"coin_symbol",
"=",
"'btc'",
... | Simple method to spend from one single-key address to another.
Signature takes place locally (client-side) after unsigned transaction is verified.
Returns the tx_hash of the newly broadcast tx.
If no change_address specified, change will be sent back to sender address.
Note that this violates the best practice.
To sweep, set to_satoshis=-1
Compressed public keys (and their corresponding addresses) have been the standard since v0.6,
set privkey_is_compressed=False if using uncompressed addresses.
Note that this currently only supports spending from single key addresses. | [
"Simple",
"method",
"to",
"spend",
"from",
"one",
"single",
"-",
"key",
"address",
"to",
"another",
"."
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L1587-L1698 | train | 208,844 |
blockcypher/blockcypher-python | blockcypher/api.py | get_metadata | def get_metadata(address=None, tx_hash=None, block_hash=None, api_key=None, private=True, coin_symbol='btc'):
'''
Get metadata using blockcypher's API.
This is data on blockcypher's servers and not embedded into the bitcoin (or other) blockchain.
'''
assert is_valid_coin_symbol(coin_symbol), coin_symbol
assert api_key or not private, 'Cannot see private metadata without an API key'
kwarg = get_valid_metadata_identifier(
coin_symbol=coin_symbol,
address=address,
tx_hash=tx_hash,
block_hash=block_hash,
)
url = make_url(coin_symbol, meta=True, **kwarg)
params = {'token': api_key} if api_key else {'private': 'true'}
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
return response_dict | python | def get_metadata(address=None, tx_hash=None, block_hash=None, api_key=None, private=True, coin_symbol='btc'):
'''
Get metadata using blockcypher's API.
This is data on blockcypher's servers and not embedded into the bitcoin (or other) blockchain.
'''
assert is_valid_coin_symbol(coin_symbol), coin_symbol
assert api_key or not private, 'Cannot see private metadata without an API key'
kwarg = get_valid_metadata_identifier(
coin_symbol=coin_symbol,
address=address,
tx_hash=tx_hash,
block_hash=block_hash,
)
url = make_url(coin_symbol, meta=True, **kwarg)
params = {'token': api_key} if api_key else {'private': 'true'}
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
return response_dict | [
"def",
"get_metadata",
"(",
"address",
"=",
"None",
",",
"tx_hash",
"=",
"None",
",",
"block_hash",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"private",
"=",
"True",
",",
"coin_symbol",
"=",
"'btc'",
")",
":",
"assert",
"is_valid_coin_symbol",
"(",
... | Get metadata using blockcypher's API.
This is data on blockcypher's servers and not embedded into the bitcoin (or other) blockchain. | [
"Get",
"metadata",
"using",
"blockcypher",
"s",
"API",
"."
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L1904-L1927 | train | 208,845 |
blockcypher/blockcypher-python | blockcypher/api.py | put_metadata | def put_metadata(metadata_dict, address=None, tx_hash=None, block_hash=None, api_key=None, private=True, coin_symbol='btc'):
'''
Embed metadata using blockcypher's API.
This is not embedded into the bitcoin (or other) blockchain,
and is only stored on blockcypher's servers.
'''
assert is_valid_coin_symbol(coin_symbol), coin_symbol
assert api_key
assert metadata_dict and isinstance(metadata_dict, dict), metadata_dict
kwarg = get_valid_metadata_identifier(
coin_symbol=coin_symbol,
address=address,
tx_hash=tx_hash,
block_hash=block_hash,
)
url = make_url(coin_symbol, meta=True, **kwarg)
params = {'token': api_key}
if private:
params['private'] = 'true'
r = requests.put(url, json=metadata_dict, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r, allow_204=True) | python | def put_metadata(metadata_dict, address=None, tx_hash=None, block_hash=None, api_key=None, private=True, coin_symbol='btc'):
'''
Embed metadata using blockcypher's API.
This is not embedded into the bitcoin (or other) blockchain,
and is only stored on blockcypher's servers.
'''
assert is_valid_coin_symbol(coin_symbol), coin_symbol
assert api_key
assert metadata_dict and isinstance(metadata_dict, dict), metadata_dict
kwarg = get_valid_metadata_identifier(
coin_symbol=coin_symbol,
address=address,
tx_hash=tx_hash,
block_hash=block_hash,
)
url = make_url(coin_symbol, meta=True, **kwarg)
params = {'token': api_key}
if private:
params['private'] = 'true'
r = requests.put(url, json=metadata_dict, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r, allow_204=True) | [
"def",
"put_metadata",
"(",
"metadata_dict",
",",
"address",
"=",
"None",
",",
"tx_hash",
"=",
"None",
",",
"block_hash",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"private",
"=",
"True",
",",
"coin_symbol",
"=",
"'btc'",
")",
":",
"assert",
"is_val... | Embed metadata using blockcypher's API.
This is not embedded into the bitcoin (or other) blockchain,
and is only stored on blockcypher's servers. | [
"Embed",
"metadata",
"using",
"blockcypher",
"s",
"API",
"."
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L1930-L1955 | train | 208,846 |
blockcypher/blockcypher-python | blockcypher/api.py | delete_metadata | def delete_metadata(address=None, tx_hash=None, block_hash=None, api_key=None, coin_symbol='btc'):
'''
Only available for metadata that was embedded privately.
'''
assert is_valid_coin_symbol(coin_symbol), coin_symbol
assert api_key, 'api_key required'
kwarg = get_valid_metadata_identifier(
coin_symbol=coin_symbol,
address=address,
tx_hash=tx_hash,
block_hash=block_hash,
)
url = make_url(coin_symbol, meta=True, **kwarg)
params = {'token': api_key}
r = requests.delete(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r, allow_204=True) | python | def delete_metadata(address=None, tx_hash=None, block_hash=None, api_key=None, coin_symbol='btc'):
'''
Only available for metadata that was embedded privately.
'''
assert is_valid_coin_symbol(coin_symbol), coin_symbol
assert api_key, 'api_key required'
kwarg = get_valid_metadata_identifier(
coin_symbol=coin_symbol,
address=address,
tx_hash=tx_hash,
block_hash=block_hash,
)
url = make_url(coin_symbol, meta=True, **kwarg)
params = {'token': api_key}
r = requests.delete(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r, allow_204=True) | [
"def",
"delete_metadata",
"(",
"address",
"=",
"None",
",",
"tx_hash",
"=",
"None",
",",
"block_hash",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"coin_symbol",
"=",
"'btc'",
")",
":",
"assert",
"is_valid_coin_symbol",
"(",
"coin_symbol",
")",
",",
"co... | Only available for metadata that was embedded privately. | [
"Only",
"available",
"for",
"metadata",
"that",
"was",
"embedded",
"privately",
"."
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/api.py#L1957-L1976 | train | 208,847 |
blockcypher/blockcypher-python | blockcypher/utils.py | to_satoshis | def to_satoshis(input_quantity, input_type):
''' convert to satoshis, no rounding '''
assert input_type in UNIT_CHOICES, input_type
# convert to satoshis
if input_type in ('btc', 'mbtc', 'bit'):
satoshis = float(input_quantity) * float(UNIT_MAPPINGS[input_type]['satoshis_per'])
elif input_type == 'satoshi':
satoshis = input_quantity
else:
raise Exception('Invalid Unit Choice: %s' % input_type)
return int(satoshis) | python | def to_satoshis(input_quantity, input_type):
''' convert to satoshis, no rounding '''
assert input_type in UNIT_CHOICES, input_type
# convert to satoshis
if input_type in ('btc', 'mbtc', 'bit'):
satoshis = float(input_quantity) * float(UNIT_MAPPINGS[input_type]['satoshis_per'])
elif input_type == 'satoshi':
satoshis = input_quantity
else:
raise Exception('Invalid Unit Choice: %s' % input_type)
return int(satoshis) | [
"def",
"to_satoshis",
"(",
"input_quantity",
",",
"input_type",
")",
":",
"assert",
"input_type",
"in",
"UNIT_CHOICES",
",",
"input_type",
"# convert to satoshis",
"if",
"input_type",
"in",
"(",
"'btc'",
",",
"'mbtc'",
",",
"'bit'",
")",
":",
"satoshis",
"=",
... | convert to satoshis, no rounding | [
"convert",
"to",
"satoshis",
"no",
"rounding"
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/utils.py#L27-L39 | train | 208,848 |
blockcypher/blockcypher-python | blockcypher/utils.py | get_txn_outputs | def get_txn_outputs(raw_tx_hex, output_addr_list, coin_symbol):
'''
Used to verify a transaction hex does what's expected of it.
Must supply a list of output addresses so that the library can try to
convert from script to address using both pubkey and script.
Returns a list of the following form:
[{'value': 12345, 'address': '1abc...'}, ...]
Uses @vbuterin's decoding methods.
'''
# Defensive checks:
err_msg = 'Library not able to parse %s transactions' % coin_symbol
assert lib_can_deserialize_cs(coin_symbol), err_msg
assert isinstance(output_addr_list, (list, tuple))
for output_addr in output_addr_list:
assert is_valid_address(output_addr), output_addr
output_addr_set = set(output_addr_list) # speed optimization
outputs = []
deserialized_tx = deserialize(str(raw_tx_hex))
for out in deserialized_tx.get('outs', []):
output = {'value': out['value']}
# determine if the address is a pubkey address, script address, or op_return
pubkey_addr = script_to_address(out['script'],
vbyte=COIN_SYMBOL_MAPPINGS[coin_symbol]['vbyte_pubkey'])
script_addr = script_to_address(out['script'],
vbyte=COIN_SYMBOL_MAPPINGS[coin_symbol]['vbyte_script'])
nulldata = out['script'] if out['script'][0:2] == '6a' else None
if pubkey_addr in output_addr_set:
address = pubkey_addr
output['address'] = address
elif script_addr in output_addr_set:
address = script_addr
output['address'] = address
elif nulldata:
output['script'] = nulldata
output['script_type'] = 'null-data'
else:
raise Exception('Script %s Does Not Contain a Valid Output Address: %s' % (
out['script'],
output_addr_set,
))
outputs.append(output)
return outputs | python | def get_txn_outputs(raw_tx_hex, output_addr_list, coin_symbol):
'''
Used to verify a transaction hex does what's expected of it.
Must supply a list of output addresses so that the library can try to
convert from script to address using both pubkey and script.
Returns a list of the following form:
[{'value': 12345, 'address': '1abc...'}, ...]
Uses @vbuterin's decoding methods.
'''
# Defensive checks:
err_msg = 'Library not able to parse %s transactions' % coin_symbol
assert lib_can_deserialize_cs(coin_symbol), err_msg
assert isinstance(output_addr_list, (list, tuple))
for output_addr in output_addr_list:
assert is_valid_address(output_addr), output_addr
output_addr_set = set(output_addr_list) # speed optimization
outputs = []
deserialized_tx = deserialize(str(raw_tx_hex))
for out in deserialized_tx.get('outs', []):
output = {'value': out['value']}
# determine if the address is a pubkey address, script address, or op_return
pubkey_addr = script_to_address(out['script'],
vbyte=COIN_SYMBOL_MAPPINGS[coin_symbol]['vbyte_pubkey'])
script_addr = script_to_address(out['script'],
vbyte=COIN_SYMBOL_MAPPINGS[coin_symbol]['vbyte_script'])
nulldata = out['script'] if out['script'][0:2] == '6a' else None
if pubkey_addr in output_addr_set:
address = pubkey_addr
output['address'] = address
elif script_addr in output_addr_set:
address = script_addr
output['address'] = address
elif nulldata:
output['script'] = nulldata
output['script_type'] = 'null-data'
else:
raise Exception('Script %s Does Not Contain a Valid Output Address: %s' % (
out['script'],
output_addr_set,
))
outputs.append(output)
return outputs | [
"def",
"get_txn_outputs",
"(",
"raw_tx_hex",
",",
"output_addr_list",
",",
"coin_symbol",
")",
":",
"# Defensive checks:",
"err_msg",
"=",
"'Library not able to parse %s transactions'",
"%",
"coin_symbol",
"assert",
"lib_can_deserialize_cs",
"(",
"coin_symbol",
")",
",",
... | Used to verify a transaction hex does what's expected of it.
Must supply a list of output addresses so that the library can try to
convert from script to address using both pubkey and script.
Returns a list of the following form:
[{'value': 12345, 'address': '1abc...'}, ...]
Uses @vbuterin's decoding methods. | [
"Used",
"to",
"verify",
"a",
"transaction",
"hex",
"does",
"what",
"s",
"expected",
"of",
"it",
"."
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/utils.py#L153-L201 | train | 208,849 |
blockcypher/blockcypher-python | blockcypher/utils.py | get_blockcypher_walletname_from_mpub | def get_blockcypher_walletname_from_mpub(mpub, subchain_indices=[]):
'''
Blockcypher limits wallet names to 25 chars.
Hash the master pubkey (with subchain indexes) and take the first 25 chars.
Hackey determinstic method for naming.
'''
# http://stackoverflow.com/a/19877309/1754586
mpub = mpub.encode('utf-8')
if subchain_indices:
mpub += ','.join([str(x) for x in subchain_indices]).encode('utf-8')
return 'X%s' % sha256(mpub).hexdigest()[:24] | python | def get_blockcypher_walletname_from_mpub(mpub, subchain_indices=[]):
'''
Blockcypher limits wallet names to 25 chars.
Hash the master pubkey (with subchain indexes) and take the first 25 chars.
Hackey determinstic method for naming.
'''
# http://stackoverflow.com/a/19877309/1754586
mpub = mpub.encode('utf-8')
if subchain_indices:
mpub += ','.join([str(x) for x in subchain_indices]).encode('utf-8')
return 'X%s' % sha256(mpub).hexdigest()[:24] | [
"def",
"get_blockcypher_walletname_from_mpub",
"(",
"mpub",
",",
"subchain_indices",
"=",
"[",
"]",
")",
":",
"# http://stackoverflow.com/a/19877309/1754586",
"mpub",
"=",
"mpub",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"subchain_indices",
":",
"mpub",
"+=",
"','... | Blockcypher limits wallet names to 25 chars.
Hash the master pubkey (with subchain indexes) and take the first 25 chars.
Hackey determinstic method for naming. | [
"Blockcypher",
"limits",
"wallet",
"names",
"to",
"25",
"chars",
"."
] | 7601ea21916957ff279384fd699527ff9c28a56e | https://github.com/blockcypher/blockcypher-python/blob/7601ea21916957ff279384fd699527ff9c28a56e/blockcypher/utils.py#L274-L288 | train | 208,850 |
openwisp/django-x509 | django_x509/base/models.py | AbstractCa.crl | def crl(self):
"""
Returns up to date CRL of this CA
"""
revoked_certs = self.get_revoked_certs()
crl = crypto.CRL()
now_str = timezone.now().strftime(generalized_time)
for cert in revoked_certs:
revoked = crypto.Revoked()
revoked.set_serial(bytes_compat(cert.serial_number))
revoked.set_reason(b'unspecified')
revoked.set_rev_date(bytes_compat(now_str))
crl.add_revoked(revoked)
return crl.export(self.x509, self.pkey, days=1, digest=b'sha256') | python | def crl(self):
"""
Returns up to date CRL of this CA
"""
revoked_certs = self.get_revoked_certs()
crl = crypto.CRL()
now_str = timezone.now().strftime(generalized_time)
for cert in revoked_certs:
revoked = crypto.Revoked()
revoked.set_serial(bytes_compat(cert.serial_number))
revoked.set_reason(b'unspecified')
revoked.set_rev_date(bytes_compat(now_str))
crl.add_revoked(revoked)
return crl.export(self.x509, self.pkey, days=1, digest=b'sha256') | [
"def",
"crl",
"(",
"self",
")",
":",
"revoked_certs",
"=",
"self",
".",
"get_revoked_certs",
"(",
")",
"crl",
"=",
"crypto",
".",
"CRL",
"(",
")",
"now_str",
"=",
"timezone",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"generalized_time",
")",
"for",
... | Returns up to date CRL of this CA | [
"Returns",
"up",
"to",
"date",
"CRL",
"of",
"this",
"CA"
] | 7f6cc937d6b13a10ce6511e0bb2a9a1345e45a2c | https://github.com/openwisp/django-x509/blob/7f6cc937d6b13a10ce6511e0bb2a9a1345e45a2c/django_x509/base/models.py#L450-L463 | train | 208,851 |
openwisp/django-x509 | django_x509/base/views.py | crl | def crl(request, pk):
"""
returns CRL of a CA
"""
authenticated = request.user.is_authenticated
authenticated = authenticated() if callable(authenticated) else authenticated
if app_settings.CRL_PROTECTED and not authenticated:
return HttpResponse(_('Forbidden'),
status=403,
content_type='text/plain')
ca = crl.ca_model.objects.get(pk=pk)
return HttpResponse(ca.crl,
status=200,
content_type='application/x-pem-file') | python | def crl(request, pk):
"""
returns CRL of a CA
"""
authenticated = request.user.is_authenticated
authenticated = authenticated() if callable(authenticated) else authenticated
if app_settings.CRL_PROTECTED and not authenticated:
return HttpResponse(_('Forbidden'),
status=403,
content_type='text/plain')
ca = crl.ca_model.objects.get(pk=pk)
return HttpResponse(ca.crl,
status=200,
content_type='application/x-pem-file') | [
"def",
"crl",
"(",
"request",
",",
"pk",
")",
":",
"authenticated",
"=",
"request",
".",
"user",
".",
"is_authenticated",
"authenticated",
"=",
"authenticated",
"(",
")",
"if",
"callable",
"(",
"authenticated",
")",
"else",
"authenticated",
"if",
"app_settings... | returns CRL of a CA | [
"returns",
"CRL",
"of",
"a",
"CA"
] | 7f6cc937d6b13a10ce6511e0bb2a9a1345e45a2c | https://github.com/openwisp/django-x509/blob/7f6cc937d6b13a10ce6511e0bb2a9a1345e45a2c/django_x509/base/views.py#L7-L20 | train | 208,852 |
sepandhaghighi/art | art/art.py | font_list | def font_list(text="test", test=False):
"""
Print all fonts.
:param text : input text
:type text : str
:param test: test flag
:type test: bool
:return: None
"""
fonts = set(FONT_MAP.keys())
if test:
fonts = fonts - set(TEST_FILTERED_FONTS)
for item in sorted(list(fonts)):
print(str(item) + " : ")
text_temp = text
try:
tprint(text_temp, str(item))
except Exception:
print(FONT_ENVIRONMENT_WARNING) | python | def font_list(text="test", test=False):
"""
Print all fonts.
:param text : input text
:type text : str
:param test: test flag
:type test: bool
:return: None
"""
fonts = set(FONT_MAP.keys())
if test:
fonts = fonts - set(TEST_FILTERED_FONTS)
for item in sorted(list(fonts)):
print(str(item) + " : ")
text_temp = text
try:
tprint(text_temp, str(item))
except Exception:
print(FONT_ENVIRONMENT_WARNING) | [
"def",
"font_list",
"(",
"text",
"=",
"\"test\"",
",",
"test",
"=",
"False",
")",
":",
"fonts",
"=",
"set",
"(",
"FONT_MAP",
".",
"keys",
"(",
")",
")",
"if",
"test",
":",
"fonts",
"=",
"fonts",
"-",
"set",
"(",
"TEST_FILTERED_FONTS",
")",
"for",
"... | Print all fonts.
:param text : input text
:type text : str
:param test: test flag
:type test: bool
:return: None | [
"Print",
"all",
"fonts",
"."
] | c5b0409de76464b0714c377f8fca17716f3a9482 | https://github.com/sepandhaghighi/art/blob/c5b0409de76464b0714c377f8fca17716f3a9482/art/art.py#L62-L81 | train | 208,853 |
sepandhaghighi/art | art/art.py | art_list | def art_list(test=False):
"""
Print all 1-Line arts.
:param test : exception test flag
:type test : bool
:return: None
"""
for i in sorted(list(art_dic.keys())):
try:
if test:
raise Exception
print(i)
aprint(i)
line()
except Exception:
print(ART_ENVIRONMENT_WARNING)
line()
if test:
break | python | def art_list(test=False):
"""
Print all 1-Line arts.
:param test : exception test flag
:type test : bool
:return: None
"""
for i in sorted(list(art_dic.keys())):
try:
if test:
raise Exception
print(i)
aprint(i)
line()
except Exception:
print(ART_ENVIRONMENT_WARNING)
line()
if test:
break | [
"def",
"art_list",
"(",
"test",
"=",
"False",
")",
":",
"for",
"i",
"in",
"sorted",
"(",
"list",
"(",
"art_dic",
".",
"keys",
"(",
")",
")",
")",
":",
"try",
":",
"if",
"test",
":",
"raise",
"Exception",
"print",
"(",
"i",
")",
"aprint",
"(",
"... | Print all 1-Line arts.
:param test : exception test flag
:type test : bool
:return: None | [
"Print",
"all",
"1",
"-",
"Line",
"arts",
"."
] | c5b0409de76464b0714c377f8fca17716f3a9482 | https://github.com/sepandhaghighi/art/blob/c5b0409de76464b0714c377f8fca17716f3a9482/art/art.py#L84-L103 | train | 208,854 |
sepandhaghighi/art | art/art.py | help_func | def help_func():
"""
Print help page.
:return: None
"""
tprint("art")
tprint("v" + VERSION)
print(DESCRIPTION + "\n")
print("Webpage : http://art.shaghighi.ir\n")
print("Help : \n")
print(" - list --> (list of arts)\n")
print(" - fonts --> (list of fonts)\n")
print(" - test --> (run tests)\n")
print(" - text 'yourtext' 'font(optional)' --> (text art) Example : 'python -m art text exampletext block'\n")
print(" - shape 'shapename' --> (shape art) Example : 'python -m art shape butterfly'\n")
print(" - save 'yourtext' 'font(optional)' --> Example : 'python -m art save exampletext block'\n")
print(" - all 'yourtext' --> Example : 'python -m art all exampletext'") | python | def help_func():
"""
Print help page.
:return: None
"""
tprint("art")
tprint("v" + VERSION)
print(DESCRIPTION + "\n")
print("Webpage : http://art.shaghighi.ir\n")
print("Help : \n")
print(" - list --> (list of arts)\n")
print(" - fonts --> (list of fonts)\n")
print(" - test --> (run tests)\n")
print(" - text 'yourtext' 'font(optional)' --> (text art) Example : 'python -m art text exampletext block'\n")
print(" - shape 'shapename' --> (shape art) Example : 'python -m art shape butterfly'\n")
print(" - save 'yourtext' 'font(optional)' --> Example : 'python -m art save exampletext block'\n")
print(" - all 'yourtext' --> Example : 'python -m art all exampletext'") | [
"def",
"help_func",
"(",
")",
":",
"tprint",
"(",
"\"art\"",
")",
"tprint",
"(",
"\"v\"",
"+",
"VERSION",
")",
"print",
"(",
"DESCRIPTION",
"+",
"\"\\n\"",
")",
"print",
"(",
"\"Webpage : http://art.shaghighi.ir\\n\"",
")",
"print",
"(",
"\"Help : \\n\"",
")",... | Print help page.
:return: None | [
"Print",
"help",
"page",
"."
] | c5b0409de76464b0714c377f8fca17716f3a9482 | https://github.com/sepandhaghighi/art/blob/c5b0409de76464b0714c377f8fca17716f3a9482/art/art.py#L106-L123 | train | 208,855 |
sepandhaghighi/art | art/art.py | aprint | def aprint(artname, number=1, text=""):
"""
Print 1-line art.
:param artname: artname
:type artname : str
:return: None
"""
print(art(artname=artname, number=number, text=text)) | python | def aprint(artname, number=1, text=""):
"""
Print 1-line art.
:param artname: artname
:type artname : str
:return: None
"""
print(art(artname=artname, number=number, text=text)) | [
"def",
"aprint",
"(",
"artname",
",",
"number",
"=",
"1",
",",
"text",
"=",
"\"\"",
")",
":",
"print",
"(",
"art",
"(",
"artname",
"=",
"artname",
",",
"number",
"=",
"number",
",",
"text",
"=",
"text",
")",
")"
] | Print 1-line art.
:param artname: artname
:type artname : str
:return: None | [
"Print",
"1",
"-",
"line",
"art",
"."
] | c5b0409de76464b0714c377f8fca17716f3a9482 | https://github.com/sepandhaghighi/art/blob/c5b0409de76464b0714c377f8fca17716f3a9482/art/art.py#L126-L134 | train | 208,856 |
sepandhaghighi/art | art/art.py | art | def art(artname, number=1, text=""):
"""
Return 1-line art.
:param artname: artname
:type artname : str
:return: ascii art as str
"""
if isinstance(artname, str) is False:
raise artError(ART_TYPE_ERROR)
artname = artname.lower()
arts = sorted(art_dic.keys())
if artname == "random" or artname == "rand" or artname == "rnd":
filtered_arts = list(set(arts) - set(RANDOM_FILTERED_ARTS))
artname = random.choice(filtered_arts)
elif artname not in art_dic.keys():
distance_list = list(map(lambda x: distance_calc(artname, x),
arts))
min_distance = min(distance_list)
selected_art = arts[distance_list.index(min_distance)]
threshold = max(len(artname), len(selected_art)) / 2
if min_distance < threshold:
artname = selected_art
else:
raise artError(ART_NAME_ERROR)
art_value = art_dic[artname]
if isinstance(number, int) is False:
raise artError(NUMBER_TYPE_ERROR)
if isinstance(art_value, str):
return (art_value + " ") * number
if isinstance(text, str) is False:
raise artError(TEXT_TYPE_ERROR)
return (art_value[0] + text + art_value[1] + " ") * number | python | def art(artname, number=1, text=""):
"""
Return 1-line art.
:param artname: artname
:type artname : str
:return: ascii art as str
"""
if isinstance(artname, str) is False:
raise artError(ART_TYPE_ERROR)
artname = artname.lower()
arts = sorted(art_dic.keys())
if artname == "random" or artname == "rand" or artname == "rnd":
filtered_arts = list(set(arts) - set(RANDOM_FILTERED_ARTS))
artname = random.choice(filtered_arts)
elif artname not in art_dic.keys():
distance_list = list(map(lambda x: distance_calc(artname, x),
arts))
min_distance = min(distance_list)
selected_art = arts[distance_list.index(min_distance)]
threshold = max(len(artname), len(selected_art)) / 2
if min_distance < threshold:
artname = selected_art
else:
raise artError(ART_NAME_ERROR)
art_value = art_dic[artname]
if isinstance(number, int) is False:
raise artError(NUMBER_TYPE_ERROR)
if isinstance(art_value, str):
return (art_value + " ") * number
if isinstance(text, str) is False:
raise artError(TEXT_TYPE_ERROR)
return (art_value[0] + text + art_value[1] + " ") * number | [
"def",
"art",
"(",
"artname",
",",
"number",
"=",
"1",
",",
"text",
"=",
"\"\"",
")",
":",
"if",
"isinstance",
"(",
"artname",
",",
"str",
")",
"is",
"False",
":",
"raise",
"artError",
"(",
"ART_TYPE_ERROR",
")",
"artname",
"=",
"artname",
".",
"lowe... | Return 1-line art.
:param artname: artname
:type artname : str
:return: ascii art as str | [
"Return",
"1",
"-",
"line",
"art",
"."
] | c5b0409de76464b0714c377f8fca17716f3a9482 | https://github.com/sepandhaghighi/art/blob/c5b0409de76464b0714c377f8fca17716f3a9482/art/art.py#L137-L169 | train | 208,857 |
sepandhaghighi/art | art/art.py | distance_calc | def distance_calc(s1, s2):
"""
Calculate Levenshtein distance between two words.
:param s1: first word
:type s1 : str
:param s2: second word
:type s2 : str
:return: distance between two word
References :
1- https://stackoverflow.com/questions/2460177/edit-distance-in-python
2- https://en.wikipedia.org/wiki/Levenshtein_distance
"""
if len(s1) > len(s2):
s1, s2 = s2, s1
distances = range(len(s1) + 1)
for i2, c2 in enumerate(s2):
distances_ = [i2 + 1]
for i1, c1 in enumerate(s1):
if c1 == c2:
distances_.append(distances[i1])
else:
distances_.append(
1 + min((distances[i1], distances[i1 + 1], distances_[-1])))
distances = distances_
return distances[-1] | python | def distance_calc(s1, s2):
"""
Calculate Levenshtein distance between two words.
:param s1: first word
:type s1 : str
:param s2: second word
:type s2 : str
:return: distance between two word
References :
1- https://stackoverflow.com/questions/2460177/edit-distance-in-python
2- https://en.wikipedia.org/wiki/Levenshtein_distance
"""
if len(s1) > len(s2):
s1, s2 = s2, s1
distances = range(len(s1) + 1)
for i2, c2 in enumerate(s2):
distances_ = [i2 + 1]
for i1, c1 in enumerate(s1):
if c1 == c2:
distances_.append(distances[i1])
else:
distances_.append(
1 + min((distances[i1], distances[i1 + 1], distances_[-1])))
distances = distances_
return distances[-1] | [
"def",
"distance_calc",
"(",
"s1",
",",
"s2",
")",
":",
"if",
"len",
"(",
"s1",
")",
">",
"len",
"(",
"s2",
")",
":",
"s1",
",",
"s2",
"=",
"s2",
",",
"s1",
"distances",
"=",
"range",
"(",
"len",
"(",
"s1",
")",
"+",
"1",
")",
"for",
"i2",
... | Calculate Levenshtein distance between two words.
:param s1: first word
:type s1 : str
:param s2: second word
:type s2 : str
:return: distance between two word
References :
1- https://stackoverflow.com/questions/2460177/edit-distance-in-python
2- https://en.wikipedia.org/wiki/Levenshtein_distance | [
"Calculate",
"Levenshtein",
"distance",
"between",
"two",
"words",
"."
] | c5b0409de76464b0714c377f8fca17716f3a9482 | https://github.com/sepandhaghighi/art/blob/c5b0409de76464b0714c377f8fca17716f3a9482/art/art.py#L249-L276 | train | 208,858 |
sepandhaghighi/art | art/art.py | wizard_font | def wizard_font(text):
"""
Check input text length for wizard mode.
:param text: input text
:type text:str
:return: font as str
"""
text_length = len(text)
if text_length <= TEXT_XLARGE_THRESHOLD:
font = random.choice(XLARGE_WIZARD_FONT)
elif text_length > TEXT_XLARGE_THRESHOLD and text_length <= TEXT_LARGE_THRESHOLD:
font = random.choice(LARGE_WIZARD_FONT)
elif text_length > TEXT_LARGE_THRESHOLD and text_length <= TEXT_MEDIUM_THRESHOLD:
font = random.choice(MEDIUM_WIZARD_FONT)
else:
font = random.choice(SMALL_WIZARD_FONT)
return font | python | def wizard_font(text):
"""
Check input text length for wizard mode.
:param text: input text
:type text:str
:return: font as str
"""
text_length = len(text)
if text_length <= TEXT_XLARGE_THRESHOLD:
font = random.choice(XLARGE_WIZARD_FONT)
elif text_length > TEXT_XLARGE_THRESHOLD and text_length <= TEXT_LARGE_THRESHOLD:
font = random.choice(LARGE_WIZARD_FONT)
elif text_length > TEXT_LARGE_THRESHOLD and text_length <= TEXT_MEDIUM_THRESHOLD:
font = random.choice(MEDIUM_WIZARD_FONT)
else:
font = random.choice(SMALL_WIZARD_FONT)
return font | [
"def",
"wizard_font",
"(",
"text",
")",
":",
"text_length",
"=",
"len",
"(",
"text",
")",
"if",
"text_length",
"<=",
"TEXT_XLARGE_THRESHOLD",
":",
"font",
"=",
"random",
".",
"choice",
"(",
"XLARGE_WIZARD_FONT",
")",
"elif",
"text_length",
">",
"TEXT_XLARGE_TH... | Check input text length for wizard mode.
:param text: input text
:type text:str
:return: font as str | [
"Check",
"input",
"text",
"length",
"for",
"wizard",
"mode",
"."
] | c5b0409de76464b0714c377f8fca17716f3a9482 | https://github.com/sepandhaghighi/art/blob/c5b0409de76464b0714c377f8fca17716f3a9482/art/art.py#L279-L296 | train | 208,859 |
sepandhaghighi/art | art/art.py | indirect_font | def indirect_font(font, fonts, text):
"""
Check input font for indirect modes.
:param font: input font
:type font : str
:param fonts: fonts list
:type fonts : list
:param text: input text
:type text:str
:return: font as str
"""
if font == "rnd-small" or font == "random-small" or font == "rand-small":
font = random.choice(RND_SIZE_DICT["small_list"])
return font
if font == "rnd-medium" or font == "random-medium" or font == "rand-medium":
font = random.choice(RND_SIZE_DICT["medium_list"])
return font
if font == "rnd-large" or font == "random-large" or font == "rand-large":
font = random.choice(RND_SIZE_DICT["large_list"])
return font
if font == "rnd-xlarge" or font == "random-xlarge" or font == "rand-xlarge":
font = random.choice(RND_SIZE_DICT["xlarge_list"])
return font
if font == "random" or font == "rand" or font == "rnd":
filtered_fonts = list(set(fonts) - set(RANDOM_FILTERED_FONTS))
font = random.choice(filtered_fonts)
return font
if font == "wizard" or font == "wiz" or font == "magic":
font = wizard_font(text)
return font
if font == "rnd-na" or font == "random-na" or font == "rand-na":
font = random.choice(TEST_FILTERED_FONTS)
return font
if font not in FONT_MAP.keys():
distance_list = list(map(lambda x: distance_calc(font, x), fonts))
font = fonts[distance_list.index(min(distance_list))]
return font | python | def indirect_font(font, fonts, text):
"""
Check input font for indirect modes.
:param font: input font
:type font : str
:param fonts: fonts list
:type fonts : list
:param text: input text
:type text:str
:return: font as str
"""
if font == "rnd-small" or font == "random-small" or font == "rand-small":
font = random.choice(RND_SIZE_DICT["small_list"])
return font
if font == "rnd-medium" or font == "random-medium" or font == "rand-medium":
font = random.choice(RND_SIZE_DICT["medium_list"])
return font
if font == "rnd-large" or font == "random-large" or font == "rand-large":
font = random.choice(RND_SIZE_DICT["large_list"])
return font
if font == "rnd-xlarge" or font == "random-xlarge" or font == "rand-xlarge":
font = random.choice(RND_SIZE_DICT["xlarge_list"])
return font
if font == "random" or font == "rand" or font == "rnd":
filtered_fonts = list(set(fonts) - set(RANDOM_FILTERED_FONTS))
font = random.choice(filtered_fonts)
return font
if font == "wizard" or font == "wiz" or font == "magic":
font = wizard_font(text)
return font
if font == "rnd-na" or font == "random-na" or font == "rand-na":
font = random.choice(TEST_FILTERED_FONTS)
return font
if font not in FONT_MAP.keys():
distance_list = list(map(lambda x: distance_calc(font, x), fonts))
font = fonts[distance_list.index(min(distance_list))]
return font | [
"def",
"indirect_font",
"(",
"font",
",",
"fonts",
",",
"text",
")",
":",
"if",
"font",
"==",
"\"rnd-small\"",
"or",
"font",
"==",
"\"random-small\"",
"or",
"font",
"==",
"\"rand-small\"",
":",
"font",
"=",
"random",
".",
"choice",
"(",
"RND_SIZE_DICT",
"[... | Check input font for indirect modes.
:param font: input font
:type font : str
:param fonts: fonts list
:type fonts : list
:param text: input text
:type text:str
:return: font as str | [
"Check",
"input",
"font",
"for",
"indirect",
"modes",
"."
] | c5b0409de76464b0714c377f8fca17716f3a9482 | https://github.com/sepandhaghighi/art/blob/c5b0409de76464b0714c377f8fca17716f3a9482/art/art.py#L299-L336 | train | 208,860 |
sepandhaghighi/art | art/art.py | __word2art | def __word2art(word, font, chr_ignore, letters):
"""
Return art word.
:param word: input word
:type word: str
:param font: input font
:type font: str
:param chr_ignore: ignore not supported character
:type chr_ignore: bool
:param letters: font letters table
:type letters: dict
:return: ascii art as str
"""
split_list = []
result_list = []
splitter = "\n"
for i in word:
if (ord(i) == 9) or (ord(i) == 32 and font == "block"):
continue
if (i not in letters.keys()):
if (chr_ignore):
continue
else:
raise artError(str(i) + " is invalid.")
if len(letters[i]) == 0:
continue
split_list.append(letters[i].split("\n"))
if font in ["mirror", "mirror_flip"]:
split_list.reverse()
if len(split_list) == 0:
return ""
for i in range(len(split_list[0])):
temp = ""
for j in range(len(split_list)):
if j > 0 and (
i == 1 or i == len(
split_list[0]) -
2) and font == "block":
temp = temp + " "
temp = temp + split_list[j][i]
result_list.append(temp)
if "win32" != sys.platform:
splitter = "\r\n"
result = (splitter).join(result_list)
if result[-1] != "\n":
result += splitter
return result | python | def __word2art(word, font, chr_ignore, letters):
"""
Return art word.
:param word: input word
:type word: str
:param font: input font
:type font: str
:param chr_ignore: ignore not supported character
:type chr_ignore: bool
:param letters: font letters table
:type letters: dict
:return: ascii art as str
"""
split_list = []
result_list = []
splitter = "\n"
for i in word:
if (ord(i) == 9) or (ord(i) == 32 and font == "block"):
continue
if (i not in letters.keys()):
if (chr_ignore):
continue
else:
raise artError(str(i) + " is invalid.")
if len(letters[i]) == 0:
continue
split_list.append(letters[i].split("\n"))
if font in ["mirror", "mirror_flip"]:
split_list.reverse()
if len(split_list) == 0:
return ""
for i in range(len(split_list[0])):
temp = ""
for j in range(len(split_list)):
if j > 0 and (
i == 1 or i == len(
split_list[0]) -
2) and font == "block":
temp = temp + " "
temp = temp + split_list[j][i]
result_list.append(temp)
if "win32" != sys.platform:
splitter = "\r\n"
result = (splitter).join(result_list)
if result[-1] != "\n":
result += splitter
return result | [
"def",
"__word2art",
"(",
"word",
",",
"font",
",",
"chr_ignore",
",",
"letters",
")",
":",
"split_list",
"=",
"[",
"]",
"result_list",
"=",
"[",
"]",
"splitter",
"=",
"\"\\n\"",
"for",
"i",
"in",
"word",
":",
"if",
"(",
"ord",
"(",
"i",
")",
"==",... | Return art word.
:param word: input word
:type word: str
:param font: input font
:type font: str
:param chr_ignore: ignore not supported character
:type chr_ignore: bool
:param letters: font letters table
:type letters: dict
:return: ascii art as str | [
"Return",
"art",
"word",
"."
] | c5b0409de76464b0714c377f8fca17716f3a9482 | https://github.com/sepandhaghighi/art/blob/c5b0409de76464b0714c377f8fca17716f3a9482/art/art.py#L339-L386 | train | 208,861 |
sepandhaghighi/art | art/art.py | set_default | def set_default(font=DEFAULT_FONT, chr_ignore=True, filename="art",
print_status=True):
"""
Change text2art, tprint and tsave default values.
:param font: input font
:type font:str
:param chr_ignore: ignore not supported character
:type chr_ignore:bool
:param filename: output file name (only tsave)
:type filename:str
:param print_status : save message print flag (only tsave)
:type print_status:bool
:return: None
"""
if isinstance(font, str) is False:
raise artError(FONT_TYPE_ERROR)
if isinstance(chr_ignore, bool) is False:
raise artError(CHR_IGNORE_TYPE_ERROR)
if isinstance(filename, str) is False:
raise artError(FILE_TYPE_ERROR)
if isinstance(print_status, bool) is False:
raise artError(PRINT_STATUS_TYPE_ERROR)
tprint.__defaults__ = (font, chr_ignore)
tsave.__defaults__ = (font, filename, chr_ignore, print_status)
text2art.__defaults__ = (font, chr_ignore) | python | def set_default(font=DEFAULT_FONT, chr_ignore=True, filename="art",
print_status=True):
"""
Change text2art, tprint and tsave default values.
:param font: input font
:type font:str
:param chr_ignore: ignore not supported character
:type chr_ignore:bool
:param filename: output file name (only tsave)
:type filename:str
:param print_status : save message print flag (only tsave)
:type print_status:bool
:return: None
"""
if isinstance(font, str) is False:
raise artError(FONT_TYPE_ERROR)
if isinstance(chr_ignore, bool) is False:
raise artError(CHR_IGNORE_TYPE_ERROR)
if isinstance(filename, str) is False:
raise artError(FILE_TYPE_ERROR)
if isinstance(print_status, bool) is False:
raise artError(PRINT_STATUS_TYPE_ERROR)
tprint.__defaults__ = (font, chr_ignore)
tsave.__defaults__ = (font, filename, chr_ignore, print_status)
text2art.__defaults__ = (font, chr_ignore) | [
"def",
"set_default",
"(",
"font",
"=",
"DEFAULT_FONT",
",",
"chr_ignore",
"=",
"True",
",",
"filename",
"=",
"\"art\"",
",",
"print_status",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"font",
",",
"str",
")",
"is",
"False",
":",
"raise",
"artError"... | Change text2art, tprint and tsave default values.
:param font: input font
:type font:str
:param chr_ignore: ignore not supported character
:type chr_ignore:bool
:param filename: output file name (only tsave)
:type filename:str
:param print_status : save message print flag (only tsave)
:type print_status:bool
:return: None | [
"Change",
"text2art",
"tprint",
"and",
"tsave",
"default",
"values",
"."
] | c5b0409de76464b0714c377f8fca17716f3a9482 | https://github.com/sepandhaghighi/art/blob/c5b0409de76464b0714c377f8fca17716f3a9482/art/art.py#L426-L451 | train | 208,862 |
dfunckt/django-rules | rules/contrib/views.py | objectgetter | def objectgetter(model, attr_name='pk', field_name='pk'):
"""
Helper that returns a function suitable for use as the ``fn`` argument
to the ``permission_required`` decorator. Internally uses
``get_object_or_404``, so keep in mind that this may raise ``Http404``.
``model`` can be a model class, manager or queryset.
``attr_name`` is the name of the view attribute.
``field_name`` is the model's field name by which the lookup is made, eg.
"id", "slug", etc.
"""
def _getter(request, *view_args, **view_kwargs):
if attr_name not in view_kwargs:
raise ImproperlyConfigured(
'Argument {0} is not available. Given arguments: [{1}]'
.format(attr_name, ', '.join(view_kwargs.keys())))
try:
return get_object_or_404(model, **{field_name: view_kwargs[attr_name]})
except FieldError:
raise ImproperlyConfigured(
'Model {0} has no field named {1}'
.format(model, field_name))
return _getter | python | def objectgetter(model, attr_name='pk', field_name='pk'):
"""
Helper that returns a function suitable for use as the ``fn`` argument
to the ``permission_required`` decorator. Internally uses
``get_object_or_404``, so keep in mind that this may raise ``Http404``.
``model`` can be a model class, manager or queryset.
``attr_name`` is the name of the view attribute.
``field_name`` is the model's field name by which the lookup is made, eg.
"id", "slug", etc.
"""
def _getter(request, *view_args, **view_kwargs):
if attr_name not in view_kwargs:
raise ImproperlyConfigured(
'Argument {0} is not available. Given arguments: [{1}]'
.format(attr_name, ', '.join(view_kwargs.keys())))
try:
return get_object_or_404(model, **{field_name: view_kwargs[attr_name]})
except FieldError:
raise ImproperlyConfigured(
'Model {0} has no field named {1}'
.format(model, field_name))
return _getter | [
"def",
"objectgetter",
"(",
"model",
",",
"attr_name",
"=",
"'pk'",
",",
"field_name",
"=",
"'pk'",
")",
":",
"def",
"_getter",
"(",
"request",
",",
"*",
"view_args",
",",
"*",
"*",
"view_kwargs",
")",
":",
"if",
"attr_name",
"not",
"in",
"view_kwargs",
... | Helper that returns a function suitable for use as the ``fn`` argument
to the ``permission_required`` decorator. Internally uses
``get_object_or_404``, so keep in mind that this may raise ``Http404``.
``model`` can be a model class, manager or queryset.
``attr_name`` is the name of the view attribute.
``field_name`` is the model's field name by which the lookup is made, eg.
"id", "slug", etc. | [
"Helper",
"that",
"returns",
"a",
"function",
"suitable",
"for",
"use",
"as",
"the",
"fn",
"argument",
"to",
"the",
"permission_required",
"decorator",
".",
"Internally",
"uses",
"get_object_or_404",
"so",
"keep",
"in",
"mind",
"that",
"this",
"may",
"raise",
... | fcf3711122243c0c0c8124e9bb9bbb829f42ce1b | https://github.com/dfunckt/django-rules/blob/fcf3711122243c0c0c8124e9bb9bbb829f42ce1b/rules/contrib/views.py#L52-L76 | train | 208,863 |
pyqt/python-qt5 | PyQt5/uic/properties.py | Properties.set_base_dir | def set_base_dir(self, base_dir):
""" Set the base directory to be used for all relative filenames. """
self._base_dir = base_dir
self.icon_cache.set_base_dir(base_dir) | python | def set_base_dir(self, base_dir):
""" Set the base directory to be used for all relative filenames. """
self._base_dir = base_dir
self.icon_cache.set_base_dir(base_dir) | [
"def",
"set_base_dir",
"(",
"self",
",",
"base_dir",
")",
":",
"self",
".",
"_base_dir",
"=",
"base_dir",
"self",
".",
"icon_cache",
".",
"set_base_dir",
"(",
"base_dir",
")"
] | Set the base directory to be used for all relative filenames. | [
"Set",
"the",
"base",
"directory",
"to",
"be",
"used",
"for",
"all",
"relative",
"filenames",
"."
] | c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f | https://github.com/pyqt/python-qt5/blob/c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f/PyQt5/uic/properties.py#L92-L96 | train | 208,864 |
pyqt/python-qt5 | PyQt5/uic/uiparser.py | _parse_alignment | def _parse_alignment(alignment):
""" Convert a C++ alignment to the corresponding flags. """
align_flags = None
for qt_align in alignment.split('|'):
_, qt_align = qt_align.split('::')
align = getattr(QtCore.Qt, qt_align)
if align_flags is None:
align_flags = align
else:
align_flags |= align
return align_flags | python | def _parse_alignment(alignment):
""" Convert a C++ alignment to the corresponding flags. """
align_flags = None
for qt_align in alignment.split('|'):
_, qt_align = qt_align.split('::')
align = getattr(QtCore.Qt, qt_align)
if align_flags is None:
align_flags = align
else:
align_flags |= align
return align_flags | [
"def",
"_parse_alignment",
"(",
"alignment",
")",
":",
"align_flags",
"=",
"None",
"for",
"qt_align",
"in",
"alignment",
".",
"split",
"(",
"'|'",
")",
":",
"_",
",",
"qt_align",
"=",
"qt_align",
".",
"split",
"(",
"'::'",
")",
"align",
"=",
"getattr",
... | Convert a C++ alignment to the corresponding flags. | [
"Convert",
"a",
"C",
"++",
"alignment",
"to",
"the",
"corresponding",
"flags",
"."
] | c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f | https://github.com/pyqt/python-qt5/blob/c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f/PyQt5/uic/uiparser.py#L58-L71 | train | 208,865 |
pyqt/python-qt5 | PyQt5/uic/uiparser.py | UIParser.any_i18n | def any_i18n(*args):
""" Return True if any argument appears to be an i18n string. """
for a in args:
if a is not None and not isinstance(a, str):
return True
return False | python | def any_i18n(*args):
""" Return True if any argument appears to be an i18n string. """
for a in args:
if a is not None and not isinstance(a, str):
return True
return False | [
"def",
"any_i18n",
"(",
"*",
"args",
")",
":",
"for",
"a",
"in",
"args",
":",
"if",
"a",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"a",
",",
"str",
")",
":",
"return",
"True",
"return",
"False"
] | Return True if any argument appears to be an i18n string. | [
"Return",
"True",
"if",
"any",
"argument",
"appears",
"to",
"be",
"an",
"i18n",
"string",
"."
] | c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f | https://github.com/pyqt/python-qt5/blob/c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f/PyQt5/uic/uiparser.py#L626-L633 | train | 208,866 |
pyqt/python-qt5 | PyQt5/uic/uiparser.py | UIParser.createWidgetItem | def createWidgetItem(self, item_type, elem, getter, *getter_args):
""" Create a specific type of widget item. """
item = self.factory.createQObject(item_type, "item", (), False)
props = self.wprops
# Note that not all types of widget items support the full set of
# properties.
text = props.getProperty(elem, 'text')
status_tip = props.getProperty(elem, 'statusTip')
tool_tip = props.getProperty(elem, 'toolTip')
whats_this = props.getProperty(elem, 'whatsThis')
if self.any_i18n(text, status_tip, tool_tip, whats_this):
self.factory.invoke("item", getter, getter_args)
if text:
item.setText(text)
if status_tip:
item.setStatusTip(status_tip)
if tool_tip:
item.setToolTip(tool_tip)
if whats_this:
item.setWhatsThis(whats_this)
text_alignment = props.getProperty(elem, 'textAlignment')
if text_alignment:
item.setTextAlignment(text_alignment)
font = props.getProperty(elem, 'font')
if font:
item.setFont(font)
icon = props.getProperty(elem, 'icon')
if icon:
item.setIcon(icon)
background = props.getProperty(elem, 'background')
if background:
item.setBackground(background)
foreground = props.getProperty(elem, 'foreground')
if foreground:
item.setForeground(foreground)
flags = props.getProperty(elem, 'flags')
if flags:
item.setFlags(flags)
check_state = props.getProperty(elem, 'checkState')
if check_state:
item.setCheckState(check_state)
return item | python | def createWidgetItem(self, item_type, elem, getter, *getter_args):
""" Create a specific type of widget item. """
item = self.factory.createQObject(item_type, "item", (), False)
props = self.wprops
# Note that not all types of widget items support the full set of
# properties.
text = props.getProperty(elem, 'text')
status_tip = props.getProperty(elem, 'statusTip')
tool_tip = props.getProperty(elem, 'toolTip')
whats_this = props.getProperty(elem, 'whatsThis')
if self.any_i18n(text, status_tip, tool_tip, whats_this):
self.factory.invoke("item", getter, getter_args)
if text:
item.setText(text)
if status_tip:
item.setStatusTip(status_tip)
if tool_tip:
item.setToolTip(tool_tip)
if whats_this:
item.setWhatsThis(whats_this)
text_alignment = props.getProperty(elem, 'textAlignment')
if text_alignment:
item.setTextAlignment(text_alignment)
font = props.getProperty(elem, 'font')
if font:
item.setFont(font)
icon = props.getProperty(elem, 'icon')
if icon:
item.setIcon(icon)
background = props.getProperty(elem, 'background')
if background:
item.setBackground(background)
foreground = props.getProperty(elem, 'foreground')
if foreground:
item.setForeground(foreground)
flags = props.getProperty(elem, 'flags')
if flags:
item.setFlags(flags)
check_state = props.getProperty(elem, 'checkState')
if check_state:
item.setCheckState(check_state)
return item | [
"def",
"createWidgetItem",
"(",
"self",
",",
"item_type",
",",
"elem",
",",
"getter",
",",
"*",
"getter_args",
")",
":",
"item",
"=",
"self",
".",
"factory",
".",
"createQObject",
"(",
"item_type",
",",
"\"item\"",
",",
"(",
")",
",",
"False",
")",
"pr... | Create a specific type of widget item. | [
"Create",
"a",
"specific",
"type",
"of",
"widget",
"item",
"."
] | c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f | https://github.com/pyqt/python-qt5/blob/c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f/PyQt5/uic/uiparser.py#L635-L692 | train | 208,867 |
pyqt/python-qt5 | PyQt5/uic/uiparser.py | UIParser.readResources | def readResources(self, elem):
"""
Read a "resources" tag and add the module to import to the parser's
list of them.
"""
try:
iterator = getattr(elem, 'iter')
except AttributeError:
iterator = getattr(elem, 'getiterator')
for include in iterator("include"):
loc = include.attrib.get("location")
# Apply the convention for naming the Python files generated by
# pyrcc5.
if loc and loc.endswith('.qrc'):
mname = os.path.basename(loc[:-4] + self._resource_suffix)
if mname not in self.resources:
self.resources.append(mname) | python | def readResources(self, elem):
"""
Read a "resources" tag and add the module to import to the parser's
list of them.
"""
try:
iterator = getattr(elem, 'iter')
except AttributeError:
iterator = getattr(elem, 'getiterator')
for include in iterator("include"):
loc = include.attrib.get("location")
# Apply the convention for naming the Python files generated by
# pyrcc5.
if loc and loc.endswith('.qrc'):
mname = os.path.basename(loc[:-4] + self._resource_suffix)
if mname not in self.resources:
self.resources.append(mname) | [
"def",
"readResources",
"(",
"self",
",",
"elem",
")",
":",
"try",
":",
"iterator",
"=",
"getattr",
"(",
"elem",
",",
"'iter'",
")",
"except",
"AttributeError",
":",
"iterator",
"=",
"getattr",
"(",
"elem",
",",
"'getiterator'",
")",
"for",
"include",
"i... | Read a "resources" tag and add the module to import to the parser's
list of them. | [
"Read",
"a",
"resources",
"tag",
"and",
"add",
"the",
"module",
"to",
"import",
"to",
"the",
"parser",
"s",
"list",
"of",
"them",
"."
] | c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f | https://github.com/pyqt/python-qt5/blob/c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f/PyQt5/uic/uiparser.py#L884-L902 | train | 208,868 |
pyqt/python-qt5 | PyQt5/uic/icon_cache.py | IconCache.get_icon | def get_icon(self, iconset):
"""Return an icon described by the given iconset tag."""
# Handle a themed icon.
theme = iconset.attrib.get('theme')
if theme is not None:
return self._object_factory.createQObject("QIcon.fromTheme",
'icon', (self._object_factory.asString(theme), ),
is_attribute=False)
# Handle an empty iconset property.
if iconset.text is None:
return None
iset = _IconSet(iconset, self._base_dir)
try:
idx = self._cache.index(iset)
except ValueError:
idx = -1
if idx >= 0:
# Return the icon from the cache.
iset = self._cache[idx]
else:
# Follow uic's naming convention.
name = 'icon'
idx = len(self._cache)
if idx > 0:
name += str(idx)
icon = self._object_factory.createQObject("QIcon", name, (),
is_attribute=False)
iset.set_icon(icon, self._qtgui_module)
self._cache.append(iset)
return iset.icon | python | def get_icon(self, iconset):
"""Return an icon described by the given iconset tag."""
# Handle a themed icon.
theme = iconset.attrib.get('theme')
if theme is not None:
return self._object_factory.createQObject("QIcon.fromTheme",
'icon', (self._object_factory.asString(theme), ),
is_attribute=False)
# Handle an empty iconset property.
if iconset.text is None:
return None
iset = _IconSet(iconset, self._base_dir)
try:
idx = self._cache.index(iset)
except ValueError:
idx = -1
if idx >= 0:
# Return the icon from the cache.
iset = self._cache[idx]
else:
# Follow uic's naming convention.
name = 'icon'
idx = len(self._cache)
if idx > 0:
name += str(idx)
icon = self._object_factory.createQObject("QIcon", name, (),
is_attribute=False)
iset.set_icon(icon, self._qtgui_module)
self._cache.append(iset)
return iset.icon | [
"def",
"get_icon",
"(",
"self",
",",
"iconset",
")",
":",
"# Handle a themed icon.",
"theme",
"=",
"iconset",
".",
"attrib",
".",
"get",
"(",
"'theme'",
")",
"if",
"theme",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_object_factory",
".",
"createQOb... | Return an icon described by the given iconset tag. | [
"Return",
"an",
"icon",
"described",
"by",
"the",
"given",
"iconset",
"tag",
"."
] | c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f | https://github.com/pyqt/python-qt5/blob/c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f/PyQt5/uic/icon_cache.py#L44-L81 | train | 208,869 |
pyqt/python-qt5 | PyQt5/uic/icon_cache.py | _IconSet._file_name | def _file_name(fname, base_dir):
""" Convert a relative filename if we have a base directory. """
fname = fname.replace("\\", "\\\\")
if base_dir != '' and fname[0] != ':' and not os.path.isabs(fname):
fname = os.path.join(base_dir, fname)
return fname | python | def _file_name(fname, base_dir):
""" Convert a relative filename if we have a base directory. """
fname = fname.replace("\\", "\\\\")
if base_dir != '' and fname[0] != ':' and not os.path.isabs(fname):
fname = os.path.join(base_dir, fname)
return fname | [
"def",
"_file_name",
"(",
"fname",
",",
"base_dir",
")",
":",
"fname",
"=",
"fname",
".",
"replace",
"(",
"\"\\\\\"",
",",
"\"\\\\\\\\\"",
")",
"if",
"base_dir",
"!=",
"''",
"and",
"fname",
"[",
"0",
"]",
"!=",
"':'",
"and",
"not",
"os",
".",
"path",... | Convert a relative filename if we have a base directory. | [
"Convert",
"a",
"relative",
"filename",
"if",
"we",
"have",
"a",
"base",
"directory",
"."
] | c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f | https://github.com/pyqt/python-qt5/blob/c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f/PyQt5/uic/icon_cache.py#L109-L117 | train | 208,870 |
pyqt/python-qt5 | PyQt5/uic/icon_cache.py | _IconSet.set_icon | def set_icon(self, icon, qtgui_module):
"""Save the icon and set its attributes."""
if self._use_fallback:
icon.addFile(self._fallback)
else:
for role, pixmap in self._roles.items():
if role.endswith("off"):
mode = role[:-3]
state = qtgui_module.QIcon.Off
elif role.endswith("on"):
mode = role[:-2]
state = qtgui_module.QIcon.On
else:
continue
mode = getattr(qtgui_module.QIcon, mode.title())
if pixmap:
icon.addPixmap(qtgui_module.QPixmap(pixmap), mode, state)
else:
icon.addPixmap(qtgui_module.QPixmap(), mode, state)
self.icon = icon | python | def set_icon(self, icon, qtgui_module):
"""Save the icon and set its attributes."""
if self._use_fallback:
icon.addFile(self._fallback)
else:
for role, pixmap in self._roles.items():
if role.endswith("off"):
mode = role[:-3]
state = qtgui_module.QIcon.Off
elif role.endswith("on"):
mode = role[:-2]
state = qtgui_module.QIcon.On
else:
continue
mode = getattr(qtgui_module.QIcon, mode.title())
if pixmap:
icon.addPixmap(qtgui_module.QPixmap(pixmap), mode, state)
else:
icon.addPixmap(qtgui_module.QPixmap(), mode, state)
self.icon = icon | [
"def",
"set_icon",
"(",
"self",
",",
"icon",
",",
"qtgui_module",
")",
":",
"if",
"self",
".",
"_use_fallback",
":",
"icon",
".",
"addFile",
"(",
"self",
".",
"_fallback",
")",
"else",
":",
"for",
"role",
",",
"pixmap",
"in",
"self",
".",
"_roles",
"... | Save the icon and set its attributes. | [
"Save",
"the",
"icon",
"and",
"set",
"its",
"attributes",
"."
] | c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f | https://github.com/pyqt/python-qt5/blob/c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f/PyQt5/uic/icon_cache.py#L119-L142 | train | 208,871 |
pyqt/python-qt5 | setup.py | get_package_data | def get_package_data():
"""Include all files from all sub-directories"""
package_data = dict()
package_data['PyQt5'] = list()
for subdir in ("doc/", "examples/", "include/",
"mkspecs/", "plugins/", "qml/",
"qsci/", "sip/", "translations/", "uic/"):
abspath = os.path.abspath("PyQt5/" + subdir)
for root, dirs, files in os.walk(abspath):
for f in files:
fpath = os.path.join(root, f)
relpath = os.path.relpath(fpath, abspath)
relpath = relpath.replace("\\", "/")
package_data['PyQt5'].append(subdir + relpath)
package_data['PyQt5'].extend(["*.exe",
"*.dll",
"*.pyd",
"*.conf",
"*.api",
"*.qm",
"*.bat"])
return package_data | python | def get_package_data():
"""Include all files from all sub-directories"""
package_data = dict()
package_data['PyQt5'] = list()
for subdir in ("doc/", "examples/", "include/",
"mkspecs/", "plugins/", "qml/",
"qsci/", "sip/", "translations/", "uic/"):
abspath = os.path.abspath("PyQt5/" + subdir)
for root, dirs, files in os.walk(abspath):
for f in files:
fpath = os.path.join(root, f)
relpath = os.path.relpath(fpath, abspath)
relpath = relpath.replace("\\", "/")
package_data['PyQt5'].append(subdir + relpath)
package_data['PyQt5'].extend(["*.exe",
"*.dll",
"*.pyd",
"*.conf",
"*.api",
"*.qm",
"*.bat"])
return package_data | [
"def",
"get_package_data",
"(",
")",
":",
"package_data",
"=",
"dict",
"(",
")",
"package_data",
"[",
"'PyQt5'",
"]",
"=",
"list",
"(",
")",
"for",
"subdir",
"in",
"(",
"\"doc/\"",
",",
"\"examples/\"",
",",
"\"include/\"",
",",
"\"mkspecs/\"",
",",
"\"plu... | Include all files from all sub-directories | [
"Include",
"all",
"files",
"from",
"all",
"sub",
"-",
"directories"
] | c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f | https://github.com/pyqt/python-qt5/blob/c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f/setup.py#L35-L58 | train | 208,872 |
pyqt/python-qt5 | PyQt5/uic/driver.py | Driver._preview | def _preview(self):
""" Preview the .ui file. Return the exit status to be passed back to
the parent process.
"""
from PyQt5 import QtWidgets
app = QtWidgets.QApplication([self._ui_file])
widget = loadUi(self._ui_file)
widget.show()
return app.exec_() | python | def _preview(self):
""" Preview the .ui file. Return the exit status to be passed back to
the parent process.
"""
from PyQt5 import QtWidgets
app = QtWidgets.QApplication([self._ui_file])
widget = loadUi(self._ui_file)
widget.show()
return app.exec_() | [
"def",
"_preview",
"(",
"self",
")",
":",
"from",
"PyQt5",
"import",
"QtWidgets",
"app",
"=",
"QtWidgets",
".",
"QApplication",
"(",
"[",
"self",
".",
"_ui_file",
"]",
")",
"widget",
"=",
"loadUi",
"(",
"self",
".",
"_ui_file",
")",
"widget",
".",
"sho... | Preview the .ui file. Return the exit status to be passed back to
the parent process. | [
"Preview",
"the",
".",
"ui",
"file",
".",
"Return",
"the",
"exit",
"status",
"to",
"be",
"passed",
"back",
"to",
"the",
"parent",
"process",
"."
] | c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f | https://github.com/pyqt/python-qt5/blob/c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f/PyQt5/uic/driver.py#L63-L74 | train | 208,873 |
pyqt/python-qt5 | PyQt5/uic/driver.py | Driver._generate | def _generate(self):
""" Generate the Python code. """
needs_close = False
if sys.hexversion >= 0x03000000:
if self._opts.output == '-':
from io import TextIOWrapper
pyfile = TextIOWrapper(sys.stdout.buffer, encoding='utf8')
else:
pyfile = open(self._opts.output, 'wt', encoding='utf8')
needs_close = True
else:
if self._opts.output == '-':
pyfile = sys.stdout
else:
pyfile = open(self._opts.output, 'wt')
needs_close = True
import_from = self._opts.import_from
if import_from:
from_imports = True
elif self._opts.from_imports:
from_imports = True
import_from = '.'
else:
from_imports = False
compileUi(self._ui_file, pyfile, self._opts.execute, self._opts.indent,
from_imports, self._opts.resource_suffix, import_from)
if needs_close:
pyfile.close() | python | def _generate(self):
""" Generate the Python code. """
needs_close = False
if sys.hexversion >= 0x03000000:
if self._opts.output == '-':
from io import TextIOWrapper
pyfile = TextIOWrapper(sys.stdout.buffer, encoding='utf8')
else:
pyfile = open(self._opts.output, 'wt', encoding='utf8')
needs_close = True
else:
if self._opts.output == '-':
pyfile = sys.stdout
else:
pyfile = open(self._opts.output, 'wt')
needs_close = True
import_from = self._opts.import_from
if import_from:
from_imports = True
elif self._opts.from_imports:
from_imports = True
import_from = '.'
else:
from_imports = False
compileUi(self._ui_file, pyfile, self._opts.execute, self._opts.indent,
from_imports, self._opts.resource_suffix, import_from)
if needs_close:
pyfile.close() | [
"def",
"_generate",
"(",
"self",
")",
":",
"needs_close",
"=",
"False",
"if",
"sys",
".",
"hexversion",
">=",
"0x03000000",
":",
"if",
"self",
".",
"_opts",
".",
"output",
"==",
"'-'",
":",
"from",
"io",
"import",
"TextIOWrapper",
"pyfile",
"=",
"TextIOW... | Generate the Python code. | [
"Generate",
"the",
"Python",
"code",
"."
] | c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f | https://github.com/pyqt/python-qt5/blob/c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f/PyQt5/uic/driver.py#L76-L110 | train | 208,874 |
pyqt/python-qt5 | PyQt5/uic/driver.py | Driver.on_IOError | def on_IOError(self, e):
""" Handle an IOError exception. """
sys.stderr.write("Error: %s: \"%s\"\n" % (e.strerror, e.filename)) | python | def on_IOError(self, e):
""" Handle an IOError exception. """
sys.stderr.write("Error: %s: \"%s\"\n" % (e.strerror, e.filename)) | [
"def",
"on_IOError",
"(",
"self",
",",
"e",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Error: %s: \\\"%s\\\"\\n\"",
"%",
"(",
"e",
".",
"strerror",
",",
"e",
".",
"filename",
")",
")"
] | Handle an IOError exception. | [
"Handle",
"an",
"IOError",
"exception",
"."
] | c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f | https://github.com/pyqt/python-qt5/blob/c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f/PyQt5/uic/driver.py#L112-L115 | train | 208,875 |
pyqt/python-qt5 | PyQt5/uic/objcreator.py | QObjectCreator.load_plugin | def load_plugin(filename, plugin_globals, plugin_locals):
""" Load the plugin from the given file. Return True if the plugin was
loaded, or False if it wanted to be ignored. Raise an exception if
there was an error.
"""
plugin = open(filename, 'rU')
try:
exec(plugin.read(), plugin_globals, plugin_locals)
except ImportError:
return False
except Exception as e:
raise WidgetPluginError("%s: %s" % (e.__class__, str(e)))
finally:
plugin.close()
return True | python | def load_plugin(filename, plugin_globals, plugin_locals):
""" Load the plugin from the given file. Return True if the plugin was
loaded, or False if it wanted to be ignored. Raise an exception if
there was an error.
"""
plugin = open(filename, 'rU')
try:
exec(plugin.read(), plugin_globals, plugin_locals)
except ImportError:
return False
except Exception as e:
raise WidgetPluginError("%s: %s" % (e.__class__, str(e)))
finally:
plugin.close()
return True | [
"def",
"load_plugin",
"(",
"filename",
",",
"plugin_globals",
",",
"plugin_locals",
")",
":",
"plugin",
"=",
"open",
"(",
"filename",
",",
"'rU'",
")",
"try",
":",
"exec",
"(",
"plugin",
".",
"read",
"(",
")",
",",
"plugin_globals",
",",
"plugin_locals",
... | Load the plugin from the given file. Return True if the plugin was
loaded, or False if it wanted to be ignored. Raise an exception if
there was an error. | [
"Load",
"the",
"plugin",
"from",
"the",
"given",
"file",
".",
"Return",
"True",
"if",
"the",
"plugin",
"was",
"loaded",
"or",
"False",
"if",
"it",
"wanted",
"to",
"be",
"ignored",
".",
"Raise",
"an",
"exception",
"if",
"there",
"was",
"an",
"error",
".... | c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f | https://github.com/pyqt/python-qt5/blob/c9ed180c56f6fd3521ffe5fb70904bc5d3f50e5f/PyQt5/uic/objcreator.py#L146-L163 | train | 208,876 |
bear/parsedatetime | parsedatetime/__init__.py | _initSymbols | def _initSymbols(ptc):
"""
Initialize symbols and single character constants.
"""
# build am and pm lists to contain
# original case, lowercase, first-char and dotted
# versions of the meridian text
ptc.am = ['', '']
ptc.pm = ['', '']
for idx, xm in enumerate(ptc.locale.meridian[:2]):
# 0: am
# 1: pm
target = ['am', 'pm'][idx]
setattr(ptc, target, [xm])
target = getattr(ptc, target)
if xm:
lxm = xm.lower()
target.extend((xm[0], '{0}.{1}.'.format(*xm),
lxm, lxm[0], '{0}.{1}.'.format(*lxm))) | python | def _initSymbols(ptc):
"""
Initialize symbols and single character constants.
"""
# build am and pm lists to contain
# original case, lowercase, first-char and dotted
# versions of the meridian text
ptc.am = ['', '']
ptc.pm = ['', '']
for idx, xm in enumerate(ptc.locale.meridian[:2]):
# 0: am
# 1: pm
target = ['am', 'pm'][idx]
setattr(ptc, target, [xm])
target = getattr(ptc, target)
if xm:
lxm = xm.lower()
target.extend((xm[0], '{0}.{1}.'.format(*xm),
lxm, lxm[0], '{0}.{1}.'.format(*lxm))) | [
"def",
"_initSymbols",
"(",
"ptc",
")",
":",
"# build am and pm lists to contain",
"# original case, lowercase, first-char and dotted",
"# versions of the meridian text",
"ptc",
".",
"am",
"=",
"[",
"''",
",",
"''",
"]",
"ptc",
".",
"pm",
"=",
"[",
"''",
",",
"''",
... | Initialize symbols and single character constants. | [
"Initialize",
"symbols",
"and",
"single",
"character",
"constants",
"."
] | 830775dc5e36395622b41f12317f5e10c303d3a2 | https://github.com/bear/parsedatetime/blob/830775dc5e36395622b41f12317f5e10c303d3a2/parsedatetime/__init__.py#L2247-L2265 | train | 208,877 |
bear/parsedatetime | parsedatetime/__init__.py | Calendar._convertUnitAsWords | def _convertUnitAsWords(self, unitText):
"""
Converts text units into their number value.
@type unitText: string
@param unitText: number text to convert
@rtype: integer
@return: numerical value of unitText
"""
word_list, a, b = re.split(r"[,\s-]+", unitText), 0, 0
for word in word_list:
x = self.ptc.small.get(word)
if x is not None:
a += x
elif word == "hundred":
a *= 100
else:
x = self.ptc.magnitude.get(word)
if x is not None:
b += a * x
a = 0
elif word in self.ptc.ignore:
pass
else:
raise Exception("Unknown number: " + word)
return a + b | python | def _convertUnitAsWords(self, unitText):
"""
Converts text units into their number value.
@type unitText: string
@param unitText: number text to convert
@rtype: integer
@return: numerical value of unitText
"""
word_list, a, b = re.split(r"[,\s-]+", unitText), 0, 0
for word in word_list:
x = self.ptc.small.get(word)
if x is not None:
a += x
elif word == "hundred":
a *= 100
else:
x = self.ptc.magnitude.get(word)
if x is not None:
b += a * x
a = 0
elif word in self.ptc.ignore:
pass
else:
raise Exception("Unknown number: " + word)
return a + b | [
"def",
"_convertUnitAsWords",
"(",
"self",
",",
"unitText",
")",
":",
"word_list",
",",
"a",
",",
"b",
"=",
"re",
".",
"split",
"(",
"r\"[,\\s-]+\"",
",",
"unitText",
")",
",",
"0",
",",
"0",
"for",
"word",
"in",
"word_list",
":",
"x",
"=",
"self",
... | Converts text units into their number value.
@type unitText: string
@param unitText: number text to convert
@rtype: integer
@return: numerical value of unitText | [
"Converts",
"text",
"units",
"into",
"their",
"number",
"value",
"."
] | 830775dc5e36395622b41f12317f5e10c303d3a2 | https://github.com/bear/parsedatetime/blob/830775dc5e36395622b41f12317f5e10c303d3a2/parsedatetime/__init__.py#L297-L323 | train | 208,878 |
bear/parsedatetime | parsedatetime/__init__.py | Calendar._quantityToReal | def _quantityToReal(self, quantity):
"""
Convert a quantity, either spelled-out or numeric, to a float
@type quantity: string
@param quantity: quantity to parse to float
@rtype: int
@return: the quantity as an float, defaulting to 0.0
"""
if not quantity:
return 1.0
try:
return float(quantity.replace(',', '.'))
except ValueError:
pass
try:
return float(self.ptc.numbers[quantity])
except KeyError:
pass
return 0.0 | python | def _quantityToReal(self, quantity):
"""
Convert a quantity, either spelled-out or numeric, to a float
@type quantity: string
@param quantity: quantity to parse to float
@rtype: int
@return: the quantity as an float, defaulting to 0.0
"""
if not quantity:
return 1.0
try:
return float(quantity.replace(',', '.'))
except ValueError:
pass
try:
return float(self.ptc.numbers[quantity])
except KeyError:
pass
return 0.0 | [
"def",
"_quantityToReal",
"(",
"self",
",",
"quantity",
")",
":",
"if",
"not",
"quantity",
":",
"return",
"1.0",
"try",
":",
"return",
"float",
"(",
"quantity",
".",
"replace",
"(",
"','",
",",
"'.'",
")",
")",
"except",
"ValueError",
":",
"pass",
"try... | Convert a quantity, either spelled-out or numeric, to a float
@type quantity: string
@param quantity: quantity to parse to float
@rtype: int
@return: the quantity as an float, defaulting to 0.0 | [
"Convert",
"a",
"quantity",
"either",
"spelled",
"-",
"out",
"or",
"numeric",
"to",
"a",
"float"
] | 830775dc5e36395622b41f12317f5e10c303d3a2 | https://github.com/bear/parsedatetime/blob/830775dc5e36395622b41f12317f5e10c303d3a2/parsedatetime/__init__.py#L738-L760 | train | 208,879 |
bear/parsedatetime | parsedatetime/__init__.py | Calendar._evalDT | def _evalDT(self, datetimeString, sourceTime):
"""
Calculate the datetime from known format like RFC822 or W3CDTF
Examples handled::
RFC822, W3CDTF formatted dates
HH:MM[:SS][ am/pm]
MM/DD/YYYY
DD MMMM YYYY
@type datetimeString: string
@param datetimeString: text to try and parse as more "traditional"
date/time text
@type sourceTime: struct_time
@param sourceTime: C{struct_time} value to use as the base
@rtype: datetime
@return: calculated C{struct_time} value or current C{struct_time}
if not parsed
"""
ctx = self.currentContext
s = datetimeString.strip()
# Given string date is a RFC822 date
if sourceTime is None:
sourceTime = _parse_date_rfc822(s)
debug and log.debug(
'attempt to parse as rfc822 - %s', str(sourceTime))
if sourceTime is not None:
(yr, mth, dy, hr, mn, sec, wd, yd, isdst, _) = sourceTime
ctx.updateAccuracy(ctx.ACU_YEAR, ctx.ACU_MONTH, ctx.ACU_DAY)
if hr != 0 and mn != 0 and sec != 0:
ctx.updateAccuracy(ctx.ACU_HOUR, ctx.ACU_MIN, ctx.ACU_SEC)
sourceTime = (yr, mth, dy, hr, mn, sec, wd, yd, isdst)
# Given string date is a W3CDTF date
if sourceTime is None:
sourceTime = _parse_date_w3dtf(s)
if sourceTime is not None:
ctx.updateAccuracy(ctx.ACU_YEAR, ctx.ACU_MONTH, ctx.ACU_DAY,
ctx.ACU_HOUR, ctx.ACU_MIN, ctx.ACU_SEC)
if sourceTime is None:
sourceTime = time.localtime()
return sourceTime | python | def _evalDT(self, datetimeString, sourceTime):
"""
Calculate the datetime from known format like RFC822 or W3CDTF
Examples handled::
RFC822, W3CDTF formatted dates
HH:MM[:SS][ am/pm]
MM/DD/YYYY
DD MMMM YYYY
@type datetimeString: string
@param datetimeString: text to try and parse as more "traditional"
date/time text
@type sourceTime: struct_time
@param sourceTime: C{struct_time} value to use as the base
@rtype: datetime
@return: calculated C{struct_time} value or current C{struct_time}
if not parsed
"""
ctx = self.currentContext
s = datetimeString.strip()
# Given string date is a RFC822 date
if sourceTime is None:
sourceTime = _parse_date_rfc822(s)
debug and log.debug(
'attempt to parse as rfc822 - %s', str(sourceTime))
if sourceTime is not None:
(yr, mth, dy, hr, mn, sec, wd, yd, isdst, _) = sourceTime
ctx.updateAccuracy(ctx.ACU_YEAR, ctx.ACU_MONTH, ctx.ACU_DAY)
if hr != 0 and mn != 0 and sec != 0:
ctx.updateAccuracy(ctx.ACU_HOUR, ctx.ACU_MIN, ctx.ACU_SEC)
sourceTime = (yr, mth, dy, hr, mn, sec, wd, yd, isdst)
# Given string date is a W3CDTF date
if sourceTime is None:
sourceTime = _parse_date_w3dtf(s)
if sourceTime is not None:
ctx.updateAccuracy(ctx.ACU_YEAR, ctx.ACU_MONTH, ctx.ACU_DAY,
ctx.ACU_HOUR, ctx.ACU_MIN, ctx.ACU_SEC)
if sourceTime is None:
sourceTime = time.localtime()
return sourceTime | [
"def",
"_evalDT",
"(",
"self",
",",
"datetimeString",
",",
"sourceTime",
")",
":",
"ctx",
"=",
"self",
".",
"currentContext",
"s",
"=",
"datetimeString",
".",
"strip",
"(",
")",
"# Given string date is a RFC822 date",
"if",
"sourceTime",
"is",
"None",
":",
"so... | Calculate the datetime from known format like RFC822 or W3CDTF
Examples handled::
RFC822, W3CDTF formatted dates
HH:MM[:SS][ am/pm]
MM/DD/YYYY
DD MMMM YYYY
@type datetimeString: string
@param datetimeString: text to try and parse as more "traditional"
date/time text
@type sourceTime: struct_time
@param sourceTime: C{struct_time} value to use as the base
@rtype: datetime
@return: calculated C{struct_time} value or current C{struct_time}
if not parsed | [
"Calculate",
"the",
"datetime",
"from",
"known",
"format",
"like",
"RFC822",
"or",
"W3CDTF"
] | 830775dc5e36395622b41f12317f5e10c303d3a2 | https://github.com/bear/parsedatetime/blob/830775dc5e36395622b41f12317f5e10c303d3a2/parsedatetime/__init__.py#L1017-L1066 | train | 208,880 |
bear/parsedatetime | parsedatetime/context.py | pdtContext.updateAccuracy | def updateAccuracy(self, *accuracy):
"""
Updates current accuracy flag
"""
for acc in accuracy:
if not isinstance(acc, int):
acc = self._ACCURACY_REVERSE_MAPPING[acc]
self.accuracy |= acc | python | def updateAccuracy(self, *accuracy):
"""
Updates current accuracy flag
"""
for acc in accuracy:
if not isinstance(acc, int):
acc = self._ACCURACY_REVERSE_MAPPING[acc]
self.accuracy |= acc | [
"def",
"updateAccuracy",
"(",
"self",
",",
"*",
"accuracy",
")",
":",
"for",
"acc",
"in",
"accuracy",
":",
"if",
"not",
"isinstance",
"(",
"acc",
",",
"int",
")",
":",
"acc",
"=",
"self",
".",
"_ACCURACY_REVERSE_MAPPING",
"[",
"acc",
"]",
"self",
".",
... | Updates current accuracy flag | [
"Updates",
"current",
"accuracy",
"flag"
] | 830775dc5e36395622b41f12317f5e10c303d3a2 | https://github.com/bear/parsedatetime/blob/830775dc5e36395622b41f12317f5e10c303d3a2/parsedatetime/context.py#L131-L138 | train | 208,881 |
horejsek/python-fastjsonschema | fastjsonschema/indent.py | indent | def indent(func):
"""
Decorator for allowing to use method as normal method or with
context manager for auto-indenting code blocks.
"""
def wrapper(self, *args, **kwds):
func(self, *args, **kwds)
return Indent(self)
return wrapper | python | def indent(func):
"""
Decorator for allowing to use method as normal method or with
context manager for auto-indenting code blocks.
"""
def wrapper(self, *args, **kwds):
func(self, *args, **kwds)
return Indent(self)
return wrapper | [
"def",
"indent",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"return",
"Indent",
"(",
"self",
")",
"return",
"wrappe... | Decorator for allowing to use method as normal method or with
context manager for auto-indenting code blocks. | [
"Decorator",
"for",
"allowing",
"to",
"use",
"method",
"as",
"normal",
"method",
"or",
"with",
"context",
"manager",
"for",
"auto",
"-",
"indenting",
"code",
"blocks",
"."
] | 8c38d0f91fa5d928ff629080cdb75ab23f96590f | https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/indent.py#L1-L9 | train | 208,882 |
horejsek/python-fastjsonschema | fastjsonschema/ref_resolver.py | RefResolver.in_scope | def in_scope(self, scope: str):
"""
Context manager to handle current scope.
"""
old_scope = self.resolution_scope
self.resolution_scope = urlparse.urljoin(old_scope, scope)
try:
yield
finally:
self.resolution_scope = old_scope | python | def in_scope(self, scope: str):
"""
Context manager to handle current scope.
"""
old_scope = self.resolution_scope
self.resolution_scope = urlparse.urljoin(old_scope, scope)
try:
yield
finally:
self.resolution_scope = old_scope | [
"def",
"in_scope",
"(",
"self",
",",
"scope",
":",
"str",
")",
":",
"old_scope",
"=",
"self",
".",
"resolution_scope",
"self",
".",
"resolution_scope",
"=",
"urlparse",
".",
"urljoin",
"(",
"old_scope",
",",
"scope",
")",
"try",
":",
"yield",
"finally",
... | Context manager to handle current scope. | [
"Context",
"manager",
"to",
"handle",
"current",
"scope",
"."
] | 8c38d0f91fa5d928ff629080cdb75ab23f96590f | https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/ref_resolver.py#L93-L102 | train | 208,883 |
horejsek/python-fastjsonschema | fastjsonschema/ref_resolver.py | RefResolver.get_scope_name | def get_scope_name(self):
"""
Get current scope and return it as a valid function name.
"""
name = 'validate_' + unquote(self.resolution_scope).replace('~1', '_').replace('~0', '_')
name = re.sub(r'[:/#\.\-\%]', '_', name)
name = name.lower().rstrip('_')
return name | python | def get_scope_name(self):
"""
Get current scope and return it as a valid function name.
"""
name = 'validate_' + unquote(self.resolution_scope).replace('~1', '_').replace('~0', '_')
name = re.sub(r'[:/#\.\-\%]', '_', name)
name = name.lower().rstrip('_')
return name | [
"def",
"get_scope_name",
"(",
"self",
")",
":",
"name",
"=",
"'validate_'",
"+",
"unquote",
"(",
"self",
".",
"resolution_scope",
")",
".",
"replace",
"(",
"'~1'",
",",
"'_'",
")",
".",
"replace",
"(",
"'~0'",
",",
"'_'",
")",
"name",
"=",
"re",
".",... | Get current scope and return it as a valid function name. | [
"Get",
"current",
"scope",
"and",
"return",
"it",
"as",
"a",
"valid",
"function",
"name",
"."
] | 8c38d0f91fa5d928ff629080cdb75ab23f96590f | https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/ref_resolver.py#L133-L140 | train | 208,884 |
horejsek/python-fastjsonschema | fastjsonschema/draft06.py | CodeGeneratorDraft06.generate_type | def generate_type(self):
"""
Validation of type. Can be one type or list of types.
Since draft 06 a float without fractional part is an integer.
.. code-block:: python
{'type': 'string'}
{'type': ['string', 'number']}
"""
types = enforce_list(self._definition['type'])
try:
python_types = ', '.join(JSON_TYPE_TO_PYTHON_TYPE[t] for t in types)
except KeyError as exc:
raise JsonSchemaDefinitionException('Unknown type: {}'.format(exc))
extra = ''
if 'integer' in types:
extra += ' and not (isinstance({variable}, float) and {variable}.is_integer())'.format(
variable=self._variable,
)
if ('number' in types or 'integer' in types) and 'boolean' not in types:
extra += ' or isinstance({variable}, bool)'.format(variable=self._variable)
with self.l('if not isinstance({variable}, ({})){}:', python_types, extra):
self.l('raise JsonSchemaException("{name} must be {}")', ' or '.join(types)) | python | def generate_type(self):
"""
Validation of type. Can be one type or list of types.
Since draft 06 a float without fractional part is an integer.
.. code-block:: python
{'type': 'string'}
{'type': ['string', 'number']}
"""
types = enforce_list(self._definition['type'])
try:
python_types = ', '.join(JSON_TYPE_TO_PYTHON_TYPE[t] for t in types)
except KeyError as exc:
raise JsonSchemaDefinitionException('Unknown type: {}'.format(exc))
extra = ''
if 'integer' in types:
extra += ' and not (isinstance({variable}, float) and {variable}.is_integer())'.format(
variable=self._variable,
)
if ('number' in types or 'integer' in types) and 'boolean' not in types:
extra += ' or isinstance({variable}, bool)'.format(variable=self._variable)
with self.l('if not isinstance({variable}, ({})){}:', python_types, extra):
self.l('raise JsonSchemaException("{name} must be {}")', ' or '.join(types)) | [
"def",
"generate_type",
"(",
"self",
")",
":",
"types",
"=",
"enforce_list",
"(",
"self",
".",
"_definition",
"[",
"'type'",
"]",
")",
"try",
":",
"python_types",
"=",
"', '",
".",
"join",
"(",
"JSON_TYPE_TO_PYTHON_TYPE",
"[",
"t",
"]",
"for",
"t",
"in",... | Validation of type. Can be one type or list of types.
Since draft 06 a float without fractional part is an integer.
.. code-block:: python
{'type': 'string'}
{'type': ['string', 'number']} | [
"Validation",
"of",
"type",
".",
"Can",
"be",
"one",
"type",
"or",
"list",
"of",
"types",
"."
] | 8c38d0f91fa5d928ff629080cdb75ab23f96590f | https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/draft06.py#L45-L73 | train | 208,885 |
horejsek/python-fastjsonschema | fastjsonschema/draft06.py | CodeGeneratorDraft06.generate_property_names | def generate_property_names(self):
"""
Means that keys of object must to follow this definition.
.. code-block:: python
{
'propertyNames': {
'maxLength': 3,
},
}
Valid keys of object for this definition are foo, bar, ... but not foobar for example.
"""
property_names_definition = self._definition.get('propertyNames', {})
if property_names_definition is True:
pass
elif property_names_definition is False:
self.create_variable_keys()
with self.l('if {variable}_keys:'):
self.l('raise JsonSchemaException("{name} must not be there")')
else:
self.create_variable_is_dict()
with self.l('if {variable}_is_dict:'):
self.create_variable_with_length()
with self.l('if {variable}_len != 0:'):
self.l('{variable}_property_names = True')
with self.l('for {variable}_key in {variable}:'):
with self.l('try:'):
self.generate_func_code_block(
property_names_definition,
'{}_key'.format(self._variable),
self._variable_name,
clear_variables=True,
)
with self.l('except JsonSchemaException:'):
self.l('{variable}_property_names = False')
with self.l('if not {variable}_property_names:'):
self.l('raise JsonSchemaException("{name} must be named by propertyName definition")') | python | def generate_property_names(self):
"""
Means that keys of object must to follow this definition.
.. code-block:: python
{
'propertyNames': {
'maxLength': 3,
},
}
Valid keys of object for this definition are foo, bar, ... but not foobar for example.
"""
property_names_definition = self._definition.get('propertyNames', {})
if property_names_definition is True:
pass
elif property_names_definition is False:
self.create_variable_keys()
with self.l('if {variable}_keys:'):
self.l('raise JsonSchemaException("{name} must not be there")')
else:
self.create_variable_is_dict()
with self.l('if {variable}_is_dict:'):
self.create_variable_with_length()
with self.l('if {variable}_len != 0:'):
self.l('{variable}_property_names = True')
with self.l('for {variable}_key in {variable}:'):
with self.l('try:'):
self.generate_func_code_block(
property_names_definition,
'{}_key'.format(self._variable),
self._variable_name,
clear_variables=True,
)
with self.l('except JsonSchemaException:'):
self.l('{variable}_property_names = False')
with self.l('if not {variable}_property_names:'):
self.l('raise JsonSchemaException("{name} must be named by propertyName definition")') | [
"def",
"generate_property_names",
"(",
"self",
")",
":",
"property_names_definition",
"=",
"self",
".",
"_definition",
".",
"get",
"(",
"'propertyNames'",
",",
"{",
"}",
")",
"if",
"property_names_definition",
"is",
"True",
":",
"pass",
"elif",
"property_names_def... | Means that keys of object must to follow this definition.
.. code-block:: python
{
'propertyNames': {
'maxLength': 3,
},
}
Valid keys of object for this definition are foo, bar, ... but not foobar for example. | [
"Means",
"that",
"keys",
"of",
"object",
"must",
"to",
"follow",
"this",
"definition",
"."
] | 8c38d0f91fa5d928ff629080cdb75ab23f96590f | https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/draft06.py#L89-L127 | train | 208,886 |
horejsek/python-fastjsonschema | fastjsonschema/draft06.py | CodeGeneratorDraft06.generate_contains | def generate_contains(self):
"""
Means that array must contain at least one defined item.
.. code-block:: python
{
'contains': {
'type': 'number',
},
}
Valid array is any with at least one number.
"""
self.create_variable_is_list()
with self.l('if {variable}_is_list:'):
contains_definition = self._definition['contains']
if contains_definition is False:
self.l('raise JsonSchemaException("{name} is always invalid")')
elif contains_definition is True:
with self.l('if not {variable}:'):
self.l('raise JsonSchemaException("{name} must not be empty")')
else:
self.l('{variable}_contains = False')
with self.l('for {variable}_key in {variable}:'):
with self.l('try:'):
self.generate_func_code_block(
contains_definition,
'{}_key'.format(self._variable),
self._variable_name,
clear_variables=True,
)
self.l('{variable}_contains = True')
self.l('break')
self.l('except JsonSchemaException: pass')
with self.l('if not {variable}_contains:'):
self.l('raise JsonSchemaException("{name} must contain one of contains definition")') | python | def generate_contains(self):
"""
Means that array must contain at least one defined item.
.. code-block:: python
{
'contains': {
'type': 'number',
},
}
Valid array is any with at least one number.
"""
self.create_variable_is_list()
with self.l('if {variable}_is_list:'):
contains_definition = self._definition['contains']
if contains_definition is False:
self.l('raise JsonSchemaException("{name} is always invalid")')
elif contains_definition is True:
with self.l('if not {variable}:'):
self.l('raise JsonSchemaException("{name} must not be empty")')
else:
self.l('{variable}_contains = False')
with self.l('for {variable}_key in {variable}:'):
with self.l('try:'):
self.generate_func_code_block(
contains_definition,
'{}_key'.format(self._variable),
self._variable_name,
clear_variables=True,
)
self.l('{variable}_contains = True')
self.l('break')
self.l('except JsonSchemaException: pass')
with self.l('if not {variable}_contains:'):
self.l('raise JsonSchemaException("{name} must contain one of contains definition")') | [
"def",
"generate_contains",
"(",
"self",
")",
":",
"self",
".",
"create_variable_is_list",
"(",
")",
"with",
"self",
".",
"l",
"(",
"'if {variable}_is_list:'",
")",
":",
"contains_definition",
"=",
"self",
".",
"_definition",
"[",
"'contains'",
"]",
"if",
"con... | Means that array must contain at least one defined item.
.. code-block:: python
{
'contains': {
'type': 'number',
},
}
Valid array is any with at least one number. | [
"Means",
"that",
"array",
"must",
"contain",
"at",
"least",
"one",
"defined",
"item",
"."
] | 8c38d0f91fa5d928ff629080cdb75ab23f96590f | https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/draft06.py#L129-L167 | train | 208,887 |
horejsek/python-fastjsonschema | fastjsonschema/draft06.py | CodeGeneratorDraft06.generate_const | def generate_const(self):
"""
Means that value is valid when is equeal to const definition.
.. code-block:: python
{
'const': 42,
}
Only valid value is 42 in this example.
"""
const = self._definition['const']
if isinstance(const, str):
const = '"{}"'.format(const)
with self.l('if {variable} != {}:', const):
self.l('raise JsonSchemaException("{name} must be same as const definition")') | python | def generate_const(self):
"""
Means that value is valid when is equeal to const definition.
.. code-block:: python
{
'const': 42,
}
Only valid value is 42 in this example.
"""
const = self._definition['const']
if isinstance(const, str):
const = '"{}"'.format(const)
with self.l('if {variable} != {}:', const):
self.l('raise JsonSchemaException("{name} must be same as const definition")') | [
"def",
"generate_const",
"(",
"self",
")",
":",
"const",
"=",
"self",
".",
"_definition",
"[",
"'const'",
"]",
"if",
"isinstance",
"(",
"const",
",",
"str",
")",
":",
"const",
"=",
"'\"{}\"'",
".",
"format",
"(",
"const",
")",
"with",
"self",
".",
"l... | Means that value is valid when is equeal to const definition.
.. code-block:: python
{
'const': 42,
}
Only valid value is 42 in this example. | [
"Means",
"that",
"value",
"is",
"valid",
"when",
"is",
"equeal",
"to",
"const",
"definition",
"."
] | 8c38d0f91fa5d928ff629080cdb75ab23f96590f | https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/draft06.py#L169-L185 | train | 208,888 |
horejsek/python-fastjsonschema | fastjsonschema/generator.py | CodeGenerator.global_state | def global_state(self):
"""
Returns global variables for generating function from ``func_code``. Includes
compiled regular expressions and imports, so it does not have to do it every
time when validation function is called.
"""
self._generate_func_code()
return dict(
REGEX_PATTERNS=self._compile_regexps,
re=re,
JsonSchemaException=JsonSchemaException,
) | python | def global_state(self):
"""
Returns global variables for generating function from ``func_code``. Includes
compiled regular expressions and imports, so it does not have to do it every
time when validation function is called.
"""
self._generate_func_code()
return dict(
REGEX_PATTERNS=self._compile_regexps,
re=re,
JsonSchemaException=JsonSchemaException,
) | [
"def",
"global_state",
"(",
"self",
")",
":",
"self",
".",
"_generate_func_code",
"(",
")",
"return",
"dict",
"(",
"REGEX_PATTERNS",
"=",
"self",
".",
"_compile_regexps",
",",
"re",
"=",
"re",
",",
"JsonSchemaException",
"=",
"JsonSchemaException",
",",
")"
] | Returns global variables for generating function from ``func_code``. Includes
compiled regular expressions and imports, so it does not have to do it every
time when validation function is called. | [
"Returns",
"global",
"variables",
"for",
"generating",
"function",
"from",
"func_code",
".",
"Includes",
"compiled",
"regular",
"expressions",
"and",
"imports",
"so",
"it",
"does",
"not",
"have",
"to",
"do",
"it",
"every",
"time",
"when",
"validation",
"function... | 8c38d0f91fa5d928ff629080cdb75ab23f96590f | https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/generator.py#L66-L78 | train | 208,889 |
horejsek/python-fastjsonschema | fastjsonschema/generator.py | CodeGenerator.global_state_code | def global_state_code(self):
"""
Returns global variables for generating function from ``func_code`` as code.
Includes compiled regular expressions and imports.
"""
self._generate_func_code()
if not self._compile_regexps:
return '\n'.join(
[
'from fastjsonschema import JsonSchemaException',
'',
'',
]
)
regexs = ['"{}": re.compile(r"{}")'.format(key, value.pattern) for key, value in self._compile_regexps.items()]
return '\n'.join(
[
'import re',
'from fastjsonschema import JsonSchemaException',
'',
'',
'REGEX_PATTERNS = {',
' ' + ',\n '.join(regexs),
'}',
'',
]
) | python | def global_state_code(self):
"""
Returns global variables for generating function from ``func_code`` as code.
Includes compiled regular expressions and imports.
"""
self._generate_func_code()
if not self._compile_regexps:
return '\n'.join(
[
'from fastjsonschema import JsonSchemaException',
'',
'',
]
)
regexs = ['"{}": re.compile(r"{}")'.format(key, value.pattern) for key, value in self._compile_regexps.items()]
return '\n'.join(
[
'import re',
'from fastjsonschema import JsonSchemaException',
'',
'',
'REGEX_PATTERNS = {',
' ' + ',\n '.join(regexs),
'}',
'',
]
) | [
"def",
"global_state_code",
"(",
"self",
")",
":",
"self",
".",
"_generate_func_code",
"(",
")",
"if",
"not",
"self",
".",
"_compile_regexps",
":",
"return",
"'\\n'",
".",
"join",
"(",
"[",
"'from fastjsonschema import JsonSchemaException'",
",",
"''",
",",
"''"... | Returns global variables for generating function from ``func_code`` as code.
Includes compiled regular expressions and imports. | [
"Returns",
"global",
"variables",
"for",
"generating",
"function",
"from",
"func_code",
"as",
"code",
".",
"Includes",
"compiled",
"regular",
"expressions",
"and",
"imports",
"."
] | 8c38d0f91fa5d928ff629080cdb75ab23f96590f | https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/generator.py#L81-L108 | train | 208,890 |
horejsek/python-fastjsonschema | fastjsonschema/generator.py | CodeGenerator.generate_func_code | def generate_func_code(self):
"""
Creates base code of validation function and calls helper
for creating code by definition.
"""
self.l('NoneType = type(None)')
# Generate parts that are referenced and not yet generated
while self._needed_validation_functions:
# During generation of validation function, could be needed to generate
# new one that is added again to `_needed_validation_functions`.
# Therefore usage of while instead of for loop.
uri, name = self._needed_validation_functions.popitem()
self.generate_validation_function(uri, name) | python | def generate_func_code(self):
"""
Creates base code of validation function and calls helper
for creating code by definition.
"""
self.l('NoneType = type(None)')
# Generate parts that are referenced and not yet generated
while self._needed_validation_functions:
# During generation of validation function, could be needed to generate
# new one that is added again to `_needed_validation_functions`.
# Therefore usage of while instead of for loop.
uri, name = self._needed_validation_functions.popitem()
self.generate_validation_function(uri, name) | [
"def",
"generate_func_code",
"(",
"self",
")",
":",
"self",
".",
"l",
"(",
"'NoneType = type(None)'",
")",
"# Generate parts that are referenced and not yet generated",
"while",
"self",
".",
"_needed_validation_functions",
":",
"# During generation of validation function, could b... | Creates base code of validation function and calls helper
for creating code by definition. | [
"Creates",
"base",
"code",
"of",
"validation",
"function",
"and",
"calls",
"helper",
"for",
"creating",
"code",
"by",
"definition",
"."
] | 8c38d0f91fa5d928ff629080cdb75ab23f96590f | https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/generator.py#L115-L127 | train | 208,891 |
horejsek/python-fastjsonschema | fastjsonschema/generator.py | CodeGenerator.generate_validation_function | def generate_validation_function(self, uri, name):
"""
Generate validation function for given uri with given name
"""
self._validation_functions_done.add(uri)
self.l('')
with self._resolver.resolving(uri) as definition:
with self.l('def {}(data):', name):
self.generate_func_code_block(definition, 'data', 'data', clear_variables=True)
self.l('return data') | python | def generate_validation_function(self, uri, name):
"""
Generate validation function for given uri with given name
"""
self._validation_functions_done.add(uri)
self.l('')
with self._resolver.resolving(uri) as definition:
with self.l('def {}(data):', name):
self.generate_func_code_block(definition, 'data', 'data', clear_variables=True)
self.l('return data') | [
"def",
"generate_validation_function",
"(",
"self",
",",
"uri",
",",
"name",
")",
":",
"self",
".",
"_validation_functions_done",
".",
"add",
"(",
"uri",
")",
"self",
".",
"l",
"(",
"''",
")",
"with",
"self",
".",
"_resolver",
".",
"resolving",
"(",
"uri... | Generate validation function for given uri with given name | [
"Generate",
"validation",
"function",
"for",
"given",
"uri",
"with",
"given",
"name"
] | 8c38d0f91fa5d928ff629080cdb75ab23f96590f | https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/generator.py#L129-L138 | train | 208,892 |
horejsek/python-fastjsonschema | fastjsonschema/generator.py | CodeGenerator.generate_func_code_block | def generate_func_code_block(self, definition, variable, variable_name, clear_variables=False):
"""
Creates validation rules for current definition.
"""
backup = self._definition, self._variable, self._variable_name
self._definition, self._variable, self._variable_name = definition, variable, variable_name
if clear_variables:
backup_variables = self._variables
self._variables = set()
self._generate_func_code_block(definition)
self._definition, self._variable, self._variable_name = backup
if clear_variables:
self._variables = backup_variables | python | def generate_func_code_block(self, definition, variable, variable_name, clear_variables=False):
"""
Creates validation rules for current definition.
"""
backup = self._definition, self._variable, self._variable_name
self._definition, self._variable, self._variable_name = definition, variable, variable_name
if clear_variables:
backup_variables = self._variables
self._variables = set()
self._generate_func_code_block(definition)
self._definition, self._variable, self._variable_name = backup
if clear_variables:
self._variables = backup_variables | [
"def",
"generate_func_code_block",
"(",
"self",
",",
"definition",
",",
"variable",
",",
"variable_name",
",",
"clear_variables",
"=",
"False",
")",
":",
"backup",
"=",
"self",
".",
"_definition",
",",
"self",
".",
"_variable",
",",
"self",
".",
"_variable_nam... | Creates validation rules for current definition. | [
"Creates",
"validation",
"rules",
"for",
"current",
"definition",
"."
] | 8c38d0f91fa5d928ff629080cdb75ab23f96590f | https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/generator.py#L140-L154 | train | 208,893 |
horejsek/python-fastjsonschema | fastjsonschema/generator.py | CodeGenerator.generate_ref | def generate_ref(self):
"""
Ref can be link to remote or local definition.
.. code-block:: python
{'$ref': 'http://json-schema.org/draft-04/schema#'}
{
'properties': {
'foo': {'type': 'integer'},
'bar': {'$ref': '#/properties/foo'}
}
}
"""
with self._resolver.in_scope(self._definition['$ref']):
name = self._resolver.get_scope_name()
uri = self._resolver.get_uri()
if uri not in self._validation_functions_done:
self._needed_validation_functions[uri] = name
# call validation function
self.l('{}({variable})', name) | python | def generate_ref(self):
"""
Ref can be link to remote or local definition.
.. code-block:: python
{'$ref': 'http://json-schema.org/draft-04/schema#'}
{
'properties': {
'foo': {'type': 'integer'},
'bar': {'$ref': '#/properties/foo'}
}
}
"""
with self._resolver.in_scope(self._definition['$ref']):
name = self._resolver.get_scope_name()
uri = self._resolver.get_uri()
if uri not in self._validation_functions_done:
self._needed_validation_functions[uri] = name
# call validation function
self.l('{}({variable})', name) | [
"def",
"generate_ref",
"(",
"self",
")",
":",
"with",
"self",
".",
"_resolver",
".",
"in_scope",
"(",
"self",
".",
"_definition",
"[",
"'$ref'",
"]",
")",
":",
"name",
"=",
"self",
".",
"_resolver",
".",
"get_scope_name",
"(",
")",
"uri",
"=",
"self",
... | Ref can be link to remote or local definition.
.. code-block:: python
{'$ref': 'http://json-schema.org/draft-04/schema#'}
{
'properties': {
'foo': {'type': 'integer'},
'bar': {'$ref': '#/properties/foo'}
}
} | [
"Ref",
"can",
"be",
"link",
"to",
"remote",
"or",
"local",
"definition",
"."
] | 8c38d0f91fa5d928ff629080cdb75ab23f96590f | https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/generator.py#L168-L188 | train | 208,894 |
horejsek/python-fastjsonschema | fastjsonschema/draft07.py | CodeGeneratorDraft07.generate_if_then_else | def generate_if_then_else(self):
"""
Implementation of if-then-else.
.. code-block:: python
{
'if': {
'exclusiveMaximum': 0,
},
'then': {
'minimum': -10,
},
'else': {
'multipleOf': 2,
},
}
Valid values are any between -10 and 0 or any multiplication of two.
"""
with self.l('try:'):
self.generate_func_code_block(
self._definition['if'],
self._variable,
self._variable_name,
clear_variables=True
)
with self.l('except JsonSchemaException:'):
if 'else' in self._definition:
self.generate_func_code_block(
self._definition['else'],
self._variable,
self._variable_name,
clear_variables=True
)
else:
self.l('pass')
if 'then' in self._definition:
with self.l('else:'):
self.generate_func_code_block(
self._definition['then'],
self._variable,
self._variable_name,
clear_variables=True
) | python | def generate_if_then_else(self):
"""
Implementation of if-then-else.
.. code-block:: python
{
'if': {
'exclusiveMaximum': 0,
},
'then': {
'minimum': -10,
},
'else': {
'multipleOf': 2,
},
}
Valid values are any between -10 and 0 or any multiplication of two.
"""
with self.l('try:'):
self.generate_func_code_block(
self._definition['if'],
self._variable,
self._variable_name,
clear_variables=True
)
with self.l('except JsonSchemaException:'):
if 'else' in self._definition:
self.generate_func_code_block(
self._definition['else'],
self._variable,
self._variable_name,
clear_variables=True
)
else:
self.l('pass')
if 'then' in self._definition:
with self.l('else:'):
self.generate_func_code_block(
self._definition['then'],
self._variable,
self._variable_name,
clear_variables=True
) | [
"def",
"generate_if_then_else",
"(",
"self",
")",
":",
"with",
"self",
".",
"l",
"(",
"'try:'",
")",
":",
"self",
".",
"generate_func_code_block",
"(",
"self",
".",
"_definition",
"[",
"'if'",
"]",
",",
"self",
".",
"_variable",
",",
"self",
".",
"_varia... | Implementation of if-then-else.
.. code-block:: python
{
'if': {
'exclusiveMaximum': 0,
},
'then': {
'minimum': -10,
},
'else': {
'multipleOf': 2,
},
}
Valid values are any between -10 and 0 or any multiplication of two. | [
"Implementation",
"of",
"if",
"-",
"then",
"-",
"else",
"."
] | 8c38d0f91fa5d928ff629080cdb75ab23f96590f | https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/draft07.py#L29-L73 | train | 208,895 |
horejsek/python-fastjsonschema | fastjsonschema/draft07.py | CodeGeneratorDraft07.generate_content_encoding | def generate_content_encoding(self):
"""
Means decoding value when it's encoded by base64.
.. code-block:: python
{
'contentEncoding': 'base64',
}
"""
if self._definition['contentEncoding'] == 'base64':
with self.l('if isinstance({variable}, str):'):
with self.l('try:'):
self.l('import base64')
self.l('{variable} = base64.b64decode({variable})')
with self.l('except Exception:'):
self.l('raise JsonSchemaException("{name} must be encoded by base64")')
with self.l('if {variable} == "":'):
self.l('raise JsonSchemaException("contentEncoding must be base64")') | python | def generate_content_encoding(self):
"""
Means decoding value when it's encoded by base64.
.. code-block:: python
{
'contentEncoding': 'base64',
}
"""
if self._definition['contentEncoding'] == 'base64':
with self.l('if isinstance({variable}, str):'):
with self.l('try:'):
self.l('import base64')
self.l('{variable} = base64.b64decode({variable})')
with self.l('except Exception:'):
self.l('raise JsonSchemaException("{name} must be encoded by base64")')
with self.l('if {variable} == "":'):
self.l('raise JsonSchemaException("contentEncoding must be base64")') | [
"def",
"generate_content_encoding",
"(",
"self",
")",
":",
"if",
"self",
".",
"_definition",
"[",
"'contentEncoding'",
"]",
"==",
"'base64'",
":",
"with",
"self",
".",
"l",
"(",
"'if isinstance({variable}, str):'",
")",
":",
"with",
"self",
".",
"l",
"(",
"'... | Means decoding value when it's encoded by base64.
.. code-block:: python
{
'contentEncoding': 'base64',
} | [
"Means",
"decoding",
"value",
"when",
"it",
"s",
"encoded",
"by",
"base64",
"."
] | 8c38d0f91fa5d928ff629080cdb75ab23f96590f | https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/draft07.py#L75-L93 | train | 208,896 |
horejsek/python-fastjsonschema | fastjsonschema/draft07.py | CodeGeneratorDraft07.generate_content_media_type | def generate_content_media_type(self):
"""
Means loading value when it's specified as JSON.
.. code-block:: python
{
'contentMediaType': 'application/json',
}
"""
if self._definition['contentMediaType'] == 'application/json':
with self.l('if isinstance({variable}, bytes):'):
with self.l('try:'):
self.l('{variable} = {variable}.decode("utf-8")')
with self.l('except Exception:'):
self.l('raise JsonSchemaException("{name} must encoded by utf8")')
with self.l('if isinstance({variable}, str):'):
with self.l('try:'):
self.l('import json')
self.l('{variable} = json.loads({variable})')
with self.l('except Exception:'):
self.l('raise JsonSchemaException("{name} must be valid JSON")') | python | def generate_content_media_type(self):
"""
Means loading value when it's specified as JSON.
.. code-block:: python
{
'contentMediaType': 'application/json',
}
"""
if self._definition['contentMediaType'] == 'application/json':
with self.l('if isinstance({variable}, bytes):'):
with self.l('try:'):
self.l('{variable} = {variable}.decode("utf-8")')
with self.l('except Exception:'):
self.l('raise JsonSchemaException("{name} must encoded by utf8")')
with self.l('if isinstance({variable}, str):'):
with self.l('try:'):
self.l('import json')
self.l('{variable} = json.loads({variable})')
with self.l('except Exception:'):
self.l('raise JsonSchemaException("{name} must be valid JSON")') | [
"def",
"generate_content_media_type",
"(",
"self",
")",
":",
"if",
"self",
".",
"_definition",
"[",
"'contentMediaType'",
"]",
"==",
"'application/json'",
":",
"with",
"self",
".",
"l",
"(",
"'if isinstance({variable}, bytes):'",
")",
":",
"with",
"self",
".",
"... | Means loading value when it's specified as JSON.
.. code-block:: python
{
'contentMediaType': 'application/json',
} | [
"Means",
"loading",
"value",
"when",
"it",
"s",
"specified",
"as",
"JSON",
"."
] | 8c38d0f91fa5d928ff629080cdb75ab23f96590f | https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/draft07.py#L95-L116 | train | 208,897 |
horejsek/python-fastjsonschema | fastjsonschema/draft04.py | CodeGeneratorDraft04.generate_enum | def generate_enum(self):
"""
Means that only value specified in the enum is valid.
.. code-block:: python
{
'enum': ['a', 'b'],
}
"""
enum = self._definition['enum']
if not isinstance(enum, (list, tuple)):
raise JsonSchemaDefinitionException('enum must be an array')
with self.l('if {variable} not in {enum}:'):
enum = str(enum).replace('"', '\\"')
self.l('raise JsonSchemaException("{name} must be one of {}")', enum) | python | def generate_enum(self):
"""
Means that only value specified in the enum is valid.
.. code-block:: python
{
'enum': ['a', 'b'],
}
"""
enum = self._definition['enum']
if not isinstance(enum, (list, tuple)):
raise JsonSchemaDefinitionException('enum must be an array')
with self.l('if {variable} not in {enum}:'):
enum = str(enum).replace('"', '\\"')
self.l('raise JsonSchemaException("{name} must be one of {}")', enum) | [
"def",
"generate_enum",
"(",
"self",
")",
":",
"enum",
"=",
"self",
".",
"_definition",
"[",
"'enum'",
"]",
"if",
"not",
"isinstance",
"(",
"enum",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"raise",
"JsonSchemaDefinitionException",
"(",
"'enum must be... | Means that only value specified in the enum is valid.
.. code-block:: python
{
'enum': ['a', 'b'],
} | [
"Means",
"that",
"only",
"value",
"specified",
"in",
"the",
"enum",
"is",
"valid",
"."
] | 8c38d0f91fa5d928ff629080cdb75ab23f96590f | https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/draft04.py#L87-L102 | train | 208,898 |
horejsek/python-fastjsonschema | fastjsonschema/draft04.py | CodeGeneratorDraft04.generate_all_of | def generate_all_of(self):
"""
Means that value have to be valid by all of those definitions. It's like put it in
one big definition.
.. code-block:: python
{
'allOf': [
{'type': 'number'},
{'minimum': 5},
],
}
Valid values for this definition are 5, 6, 7, ... but not 4 or 'abc' for example.
"""
for definition_item in self._definition['allOf']:
self.generate_func_code_block(definition_item, self._variable, self._variable_name, clear_variables=True) | python | def generate_all_of(self):
"""
Means that value have to be valid by all of those definitions. It's like put it in
one big definition.
.. code-block:: python
{
'allOf': [
{'type': 'number'},
{'minimum': 5},
],
}
Valid values for this definition are 5, 6, 7, ... but not 4 or 'abc' for example.
"""
for definition_item in self._definition['allOf']:
self.generate_func_code_block(definition_item, self._variable, self._variable_name, clear_variables=True) | [
"def",
"generate_all_of",
"(",
"self",
")",
":",
"for",
"definition_item",
"in",
"self",
".",
"_definition",
"[",
"'allOf'",
"]",
":",
"self",
".",
"generate_func_code_block",
"(",
"definition_item",
",",
"self",
".",
"_variable",
",",
"self",
".",
"_variable_... | Means that value have to be valid by all of those definitions. It's like put it in
one big definition.
.. code-block:: python
{
'allOf': [
{'type': 'number'},
{'minimum': 5},
],
}
Valid values for this definition are 5, 6, 7, ... but not 4 or 'abc' for example. | [
"Means",
"that",
"value",
"have",
"to",
"be",
"valid",
"by",
"all",
"of",
"those",
"definitions",
".",
"It",
"s",
"like",
"put",
"it",
"in",
"one",
"big",
"definition",
"."
] | 8c38d0f91fa5d928ff629080cdb75ab23f96590f | https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/draft04.py#L104-L121 | train | 208,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.