hexsha
stringlengths
40
40
repo
stringlengths
7
114
path
stringlengths
4
124
license
listlengths
1
9
language
stringclasses
1 value
identifier
stringlengths
1
71
return_type
stringlengths
1
749
original_string
stringlengths
76
22.7k
original_docstring
stringlengths
16
7.61k
docstring
stringlengths
16
2.47k
docstring_tokens
listlengths
6
477
code
stringlengths
14
10.2k
code_tokens
listlengths
6
996
short_docstring
stringlengths
2
644
short_docstring_tokens
listlengths
1
116
comment
listlengths
1
89
parameters
listlengths
0
64
docstring_params
dict
9a741ed1cb90a7d4c4d1cdf6a2855519a4f319fd
baidu/Quanlse
Quanlse/Utils/ODESolver.py
[ "Apache-2.0" ]
Python
solverAdaptive
<not_specific>
def solverAdaptive(ham: 'QHamiltonian', state0: ndarray = None, shot=None, tolerance: float = 0.01, accelerate=False): """ Run the program calculating the unitary evolution operator for Hamiltonian. This is the adaptive algorithm for piecewise-constant, using the pulse sequences given in `hamiltonian`. ...
Run the program calculating the unitary evolution operator for Hamiltonian. This is the adaptive algorithm for piecewise-constant, using the pulse sequences given in `hamiltonian`. In this algorithm, it applies the strategy of adaptive-step to accelerate the calculation. :param ham: QHamiltonian objec...
Run the program calculating the unitary evolution operator for Hamiltonian. This is the adaptive algorithm for piecewise-constant, using the pulse sequences given in `hamiltonian`. In this algorithm, it applies the strategy of adaptive-step to accelerate the calculation.
[ "Run", "the", "program", "calculating", "the", "unitary", "evolution", "operator", "for", "Hamiltonian", ".", "This", "is", "the", "adaptive", "algorithm", "for", "piecewise", "-", "constant", "using", "the", "pulse", "sequences", "given", "in", "`", "hamiltonia...
def solverAdaptive(ham: 'QHamiltonian', state0: ndarray = None, shot=None, tolerance: float = 0.01, accelerate=False): if accelerate: try: from Quanlse.Utils.NumbaSupport import expm except ImportError: raise Error.Error("You should install Numba to activate the acceleration;...
[ "def", "solverAdaptive", "(", "ham", ":", "'QHamiltonian'", ",", "state0", ":", "ndarray", "=", "None", ",", "shot", "=", "None", ",", "tolerance", ":", "float", "=", "0.01", ",", "accelerate", "=", "False", ")", ":", "if", "accelerate", ":", "try", ":...
Run the program calculating the unitary evolution operator for Hamiltonian.
[ "Run", "the", "program", "calculating", "the", "unitary", "evolution", "operator", "for", "Hamiltonian", "." ]
[ "\"\"\"\n Run the program calculating the unitary evolution operator for Hamiltonian.\n This is the adaptive algorithm for piecewise-constant, using the pulse sequences given in `hamiltonian`.\n In this algorithm, it applies the strategy of adaptive-step to accelerate the calculation.\n\n :param ham: QH...
[ { "param": "ham", "type": "'QHamiltonian'" }, { "param": "state0", "type": "ndarray" }, { "param": "shot", "type": null }, { "param": "tolerance", "type": "float" }, { "param": "accelerate", "type": null } ]
{ "returns": [ { "docstring": "Return a dictionary containing the result.", "docstring_tokens": [ "Return", "a", "dictionary", "containing", "the", "result", "." ], "type": null } ], "raises": [], "params": [ { "id...
9a741ed1cb90a7d4c4d1cdf6a2855519a4f319fd
baidu/Quanlse
Quanlse/Utils/ODESolver.py
[ "Apache-2.0" ]
Python
solverOpenSystem
<not_specific>
def solverOpenSystem(ham: 'QHamiltonian', state0=None, recordEvolution=False, accelerate=False): """ Calculate the unitary evolution operator with a given Hamiltonian. This function supports both single-job and batch-job processing. :param ham: QHamiltonian object :param state0: the initial state v...
Calculate the unitary evolution operator with a given Hamiltonian. This function supports both single-job and batch-job processing. :param ham: QHamiltonian object :param state0: the initial state vector. If None is given, this function will return the time-ordered evolution operato...
Calculate the unitary evolution operator with a given Hamiltonian. This function supports both single-job and batch-job processing.
[ "Calculate", "the", "unitary", "evolution", "operator", "with", "a", "given", "Hamiltonian", ".", "This", "function", "supports", "both", "single", "-", "job", "and", "batch", "-", "job", "processing", "." ]
def solverOpenSystem(ham: 'QHamiltonian', state0=None, recordEvolution=False, accelerate=False): if state0.shape[1] == 1: rho0 = state0 @ dagger(state0) else: if isRho(state0): rho0 = state0 else: raise Error.ArgumentError('The input state is neither a density mat...
[ "def", "solverOpenSystem", "(", "ham", ":", "'QHamiltonian'", ",", "state0", "=", "None", ",", "recordEvolution", "=", "False", ",", "accelerate", "=", "False", ")", ":", "if", "state0", ".", "shape", "[", "1", "]", "==", "1", ":", "rho0", "=", "state0...
Calculate the unitary evolution operator with a given Hamiltonian.
[ "Calculate", "the", "unitary", "evolution", "operator", "with", "a", "given", "Hamiltonian", "." ]
[ "\"\"\"\n Calculate the unitary evolution operator with a given Hamiltonian. This function supports\n both single-job and batch-job processing.\n\n :param ham: QHamiltonian object\n :param state0: the initial state vector. If None is given, this function will return the time-ordered\n ...
[ { "param": "ham", "type": "'QHamiltonian'" }, { "param": "state0", "type": null }, { "param": "recordEvolution", "type": null }, { "param": "accelerate", "type": null } ]
{ "returns": [ { "docstring": "result dictionary (or a list of result dictionaries when ``jobList`` is provided)", "docstring_tokens": [ "result", "dictionary", "(", "or", "a", "list", "of", "result", "dictionaries", "when...
553bea1dc2fd1e57dc9df49dc06a50498cd2f822
baidu/Quanlse
Quanlse/QTask.py
[ "Apache-2.0" ]
Python
_retryWhileNetworkError
<not_specific>
def _retryWhileNetworkError(func): """ The decorator for retrying function when network failed """ def _func(*args, **kwargs): retryCount = 0 while retryCount < waitTaskRetrys: try: return func(*args, **kwargs) except Error.NetworkError: ...
The decorator for retrying function when network failed
The decorator for retrying function when network failed
[ "The", "decorator", "for", "retrying", "function", "when", "network", "failed" ]
def _retryWhileNetworkError(func): def _func(*args, **kwargs): retryCount = 0 while retryCount < waitTaskRetrys: try: return func(*args, **kwargs) except Error.NetworkError: print(f"network error for {func.__name__}, retrying, {retryCount}") ...
[ "def", "_retryWhileNetworkError", "(", "func", ")", ":", "def", "_func", "(", "*", "args", ",", "**", "kwargs", ")", ":", "retryCount", "=", "0", "while", "retryCount", "<", "waitTaskRetrys", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*...
The decorator for retrying function when network failed
[ "The", "decorator", "for", "retrying", "function", "when", "network", "failed" ]
[ "\"\"\"\n The decorator for retrying function when network failed\n \"\"\"", "# retry if that's a network related error", "# other errors will be raised" ]
[ { "param": "func", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "func", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
553bea1dc2fd1e57dc9df49dc06a50498cd2f822
baidu/Quanlse
Quanlse/QTask.py
[ "Apache-2.0" ]
Python
_getSTSToken
<not_specific>
def _getSTSToken(): """ Get the token to upload the file :return: """ if not Define.hubToken: raise Error.ArgumentError("please provide a valid token") config = invokeBackend("circuit/genSTS", {"token": Define.hubToken}) bosClient = BosClient( BceClientConfiguration( ...
Get the token to upload the file :return:
Get the token to upload the file
[ "Get", "the", "token", "to", "upload", "the", "file" ]
def _getSTSToken(): if not Define.hubToken: raise Error.ArgumentError("please provide a valid token") config = invokeBackend("circuit/genSTS", {"token": Define.hubToken}) bosClient = BosClient( BceClientConfiguration( credentials=BceCredentials( str( ...
[ "def", "_getSTSToken", "(", ")", ":", "if", "not", "Define", ".", "hubToken", ":", "raise", "Error", ".", "ArgumentError", "(", "\"please provide a valid token\"", ")", "config", "=", "invokeBackend", "(", "\"circuit/genSTS\"", ",", "{", "\"token\"", ":", "Defin...
Get the token to upload the file
[ "Get", "the", "token", "to", "upload", "the", "file" ]
[ "\"\"\"\n Get the token to upload the file\n\n :return:\n \"\"\"" ]
[]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [], "outlier_params": [], "others": [] }
553bea1dc2fd1e57dc9df49dc06a50498cd2f822
baidu/Quanlse
Quanlse/QTask.py
[ "Apache-2.0" ]
Python
_downloadToFile
<not_specific>
def _downloadToFile(url, localFile): """ Download from a url to a local file """ total = 0 with requests.get(url, stream=True) as req: req.raise_for_status() with open(localFile, 'wb') as fObj: for chunk in req.iter_content(chunk_size=8192): if chunk: # ...
Download from a url to a local file
Download from a url to a local file
[ "Download", "from", "a", "url", "to", "a", "local", "file" ]
def _downloadToFile(url, localFile): total = 0 with requests.get(url, stream=True) as req: req.raise_for_status() with open(localFile, 'wb') as fObj: for chunk in req.iter_content(chunk_size=8192): if chunk: fObj.write(chunk) ...
[ "def", "_downloadToFile", "(", "url", ",", "localFile", ")", ":", "total", "=", "0", "with", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "as", "req", ":", "req", ".", "raise_for_status", "(", ")", "with", "open", "(", "localF...
Download from a url to a local file
[ "Download", "from", "a", "url", "to", "a", "local", "file" ]
[ "\"\"\"\n Download from a url to a local file\n \"\"\"", "# filter out keep-alive new chunks", "# f.flush()" ]
[ { "param": "url", "type": null }, { "param": "localFile", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "url", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "localFile", "type": null, "docstring": null, "docstring_tokens...
553bea1dc2fd1e57dc9df49dc06a50498cd2f822
baidu/Quanlse
Quanlse/QTask.py
[ "Apache-2.0" ]
Python
_fetchResult
<not_specific>
def _fetchResult(token, taskId): """ Fetch the result files from the taskId """ params = {"token": token, "taskId": taskId} ret = invokeBackend("task/getTaskInfo", params) result = ret["result"] originUrl = result["originUrl"] # originSize = result["originSize"] try: orig...
Fetch the result files from the taskId
Fetch the result files from the taskId
[ "Fetch", "the", "result", "files", "from", "the", "taskId" ]
def _fetchResult(token, taskId): params = {"token": token, "taskId": taskId} ret = invokeBackend("task/getTaskInfo", params) result = ret["result"] originUrl = result["originUrl"] try: originFile, downSize = _downloadToFile(originUrl, os.path.join(outputPath, f"remote.{taskId}.origin.json"))...
[ "def", "_fetchResult", "(", "token", ",", "taskId", ")", ":", "params", "=", "{", "\"token\"", ":", "token", ",", "\"taskId\"", ":", "taskId", "}", "ret", "=", "invokeBackend", "(", "\"task/getTaskInfo\"", ",", "params", ")", "result", "=", "ret", "[", "...
Fetch the result files from the taskId
[ "Fetch", "the", "result", "files", "from", "the", "taskId" ]
[ "\"\"\"\n Fetch the result files from the taskId\n \"\"\"", "# originSize = result[\"originSize\"]", "# TODO split the disk write error" ]
[ { "param": "token", "type": null }, { "param": "taskId", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "token", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "taskId", "type": null, "docstring": null, "docstring_tokens"...
553bea1dc2fd1e57dc9df49dc06a50498cd2f822
baidu/Quanlse
Quanlse/QTask.py
[ "Apache-2.0" ]
Python
_fetchMeasureResult
<not_specific>
def _fetchMeasureResult(taskId): """ Dump the measurement content of the file from taskId """ localFile = os.path.join(outputPath, f'remote.{taskId}.origin.json') if os.path.exists(localFile): with open(localFile, "rb") as fObj: data = json.loads(fObj.read()) return ...
Dump the measurement content of the file from taskId
Dump the measurement content of the file from taskId
[ "Dump", "the", "measurement", "content", "of", "the", "file", "from", "taskId" ]
def _fetchMeasureResult(taskId): localFile = os.path.join(outputPath, f'remote.{taskId}.origin.json') if os.path.exists(localFile): with open(localFile, "rb") as fObj: data = json.loads(fObj.read()) return data else: return None
[ "def", "_fetchMeasureResult", "(", "taskId", ")", ":", "localFile", "=", "os", ".", "path", ".", "join", "(", "outputPath", ",", "f'remote.{taskId}.origin.json'", ")", "if", "os", ".", "path", ".", "exists", "(", "localFile", ")", ":", "with", "open", "(",...
Dump the measurement content of the file from taskId
[ "Dump", "the", "measurement", "content", "of", "the", "file", "from", "taskId" ]
[ "\"\"\"\n Dump the measurement content of the file from taskId\n \"\"\"" ]
[ { "param": "taskId", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "taskId", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
553bea1dc2fd1e57dc9df49dc06a50498cd2f822
baidu/Quanlse
Quanlse/QTask.py
[ "Apache-2.0" ]
Python
_waitTask
<not_specific>
def _waitTask(token, taskId, downloadResult=True): """ Wait for a task from the taskId """ if outputInfo: print(f'Task {taskId} is running, please wait...') task = { "token": token, "taskId": taskId } stepStatus = "waiting" while True: try: t...
Wait for a task from the taskId
Wait for a task from the taskId
[ "Wait", "for", "a", "task", "from", "the", "taskId" ]
def _waitTask(token, taskId, downloadResult=True): if outputInfo: print(f'Task {taskId} is running, please wait...') task = { "token": token, "taskId": taskId } stepStatus = "waiting" while True: try: time.sleep(pollInterval) ret = invokeBacken...
[ "def", "_waitTask", "(", "token", ",", "taskId", ",", "downloadResult", "=", "True", ")", ":", "if", "outputInfo", ":", "print", "(", "f'Task {taskId} is running, please wait...'", ")", "task", "=", "{", "\"token\"", ":", "token", ",", "\"taskId\"", ":", "task...
Wait for a task from the taskId
[ "Wait", "for", "a", "task", "from", "the", "taskId" ]
[ "\"\"\"\n Wait for a task from the taskId\n \"\"\"", "# go on loop" ]
[ { "param": "token", "type": null }, { "param": "taskId", "type": null }, { "param": "downloadResult", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "token", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "taskId", "type": null, "docstring": null, "docstring_tokens"...
555686663e8ca008e98273bb652f1074bfaefea0
baidu/Quanlse
Quanlse/Scheduler/GatePulsePair.py
[ "Apache-2.0" ]
Python
onSubSys
List[int]
def onSubSys(self) -> List[int]: """ The sub-systems which the pulses work on. """ return self._onSubSys
The sub-systems which the pulses work on.
The sub-systems which the pulses work on.
[ "The", "sub", "-", "systems", "which", "the", "pulses", "work", "on", "." ]
def onSubSys(self) -> List[int]: return self._onSubSys
[ "def", "onSubSys", "(", "self", ")", "->", "List", "[", "int", "]", ":", "return", "self", ".", "_onSubSys" ]
The sub-systems which the pulses work on.
[ "The", "sub", "-", "systems", "which", "the", "pulses", "work", "on", "." ]
[ "\"\"\"\n The sub-systems which the pulses work on.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fdec44765ce1fc97658ab7813915443622b69d16
baidu/Quanlse
Quanlse/Utils/RandomizedBenchmarking.py
[ "Apache-2.0" ]
Python
RB
float
def RB(model: PulseModel, targetQubitNum: int, initialState: ndarray, size: int, width: int, sche: SchedulerSuperconduct, dt: float, targetGate: FixedGateOP = None, interleaved: bool = False, isOpen: bool = False) -> float: r""" Return the sequence's average fidelity for different number of Cliffo...
r""" Return the sequence's average fidelity for different number of Clifford. :param model: the QHamiltonian object of the multi-qubit system. :param targetQubitNum: the index of the qubit being benchmarked. :param initialState: the initial state of the system. :param size: the number of Cliffords ...
r""" Return the sequence's average fidelity for different number of Clifford.
[ "r", "\"", "\"", "\"", "Return", "the", "sequence", "'", "s", "average", "fidelity", "for", "different", "number", "of", "Clifford", "." ]
def RB(model: PulseModel, targetQubitNum: int, initialState: ndarray, size: int, width: int, sche: SchedulerSuperconduct, dt: float, targetGate: FixedGateOP = None, interleaved: bool = False, isOpen: bool = False) -> float: if not isinstance(targetQubitNum, int): raise Error.ArgumentError("We ...
[ "def", "RB", "(", "model", ":", "PulseModel", ",", "targetQubitNum", ":", "int", ",", "initialState", ":", "ndarray", ",", "size", ":", "int", ",", "width", ":", "int", ",", "sche", ":", "SchedulerSuperconduct", ",", "dt", ":", "float", ",", "targetGate"...
r""" Return the sequence's average fidelity for different number of Clifford.
[ "r", "\"", "\"", "\"", "Return", "the", "sequence", "'", "s", "average", "fidelity", "for", "different", "number", "of", "Clifford", "." ]
[ "r\"\"\"\n Return the sequence's average fidelity for different number of Clifford.\n\n :param model: the QHamiltonian object of the multi-qubit system.\n :param targetQubitNum: the index of the qubit being benchmarked.\n :param initialState: the initial state of the system.\n :param size: the number...
[ { "param": "model", "type": "PulseModel" }, { "param": "targetQubitNum", "type": "int" }, { "param": "initialState", "type": "ndarray" }, { "param": "size", "type": "int" }, { "param": "width", "type": "int" }, { "param": "sche", "type": "Scheduler...
{ "returns": [ { "docstring": "the average sequence fidelity of different number of Cliffords.", "docstring_tokens": [ "the", "average", "sequence", "fidelity", "of", "different", "number", "of", "Cliffords", "." ], ...
969d2a6a92cb06d286fd5af383ecf571d916dc23
baidu/Quanlse
Quanlse/Calibration/SingleQubit.py
[ "Apache-2.0" ]
Python
ampRabi
[list, list]
def ampRabi(pulseModel: PulseModel, pulseFreq: Union[int, float], ampRange: list, tg: int, sample: int = 100) -> [list, list]: """ Perform a Rabi Oscillation by varying the pulse amplitudes. This function returns a list of amplitudes scanned and a list of populations. :param pulseModel: a p...
Perform a Rabi Oscillation by varying the pulse amplitudes. This function returns a list of amplitudes scanned and a list of populations. :param pulseModel: a pulseModel object :param pulseFreq: frequency of the pulse :param ampRange: a list of amplitude bounds :param tg: fixed pulse duration ...
Perform a Rabi Oscillation by varying the pulse amplitudes. This function returns a list of amplitudes scanned and a list of populations.
[ "Perform", "a", "Rabi", "Oscillation", "by", "varying", "the", "pulse", "amplitudes", ".", "This", "function", "returns", "a", "list", "of", "amplitudes", "scanned", "and", "a", "list", "of", "populations", "." ]
def ampRabi(pulseModel: PulseModel, pulseFreq: Union[int, float], ampRange: list, tg: int, sample: int = 100) -> [list, list]: popList = [] ampList = linspace(ampRange[0], ampRange[1], sample) qJobList = pulseModel.ham.createJobList() for amp in ampList: qJob = pulseModel.ham.createJ...
[ "def", "ampRabi", "(", "pulseModel", ":", "PulseModel", ",", "pulseFreq", ":", "Union", "[", "int", ",", "float", "]", ",", "ampRange", ":", "list", ",", "tg", ":", "int", ",", "sample", ":", "int", "=", "100", ")", "->", "[", "list", ",", "list", ...
Perform a Rabi Oscillation by varying the pulse amplitudes.
[ "Perform", "a", "Rabi", "Oscillation", "by", "varying", "the", "pulse", "amplitudes", "." ]
[ "\"\"\"\n Perform a Rabi Oscillation by varying the pulse amplitudes. This function returns a list of amplitudes scanned\n and a list of populations.\n\n :param pulseModel: a pulseModel object\n :param pulseFreq: frequency of the pulse\n :param ampRange: a list of amplitude bounds\n :param tg: fix...
[ { "param": "pulseModel", "type": "PulseModel" }, { "param": "pulseFreq", "type": "Union[int, float]" }, { "param": "ampRange", "type": "list" }, { "param": "tg", "type": "int" }, { "param": "sample", "type": "int" } ]
{ "returns": [ { "docstring": "a list of amplitudes scanned and a list of populations", "docstring_tokens": [ "a", "list", "of", "amplitudes", "scanned", "and", "a", "list", "of", "populations" ], "type": null ...
969d2a6a92cb06d286fd5af383ecf571d916dc23
baidu/Quanlse
Quanlse/Calibration/SingleQubit.py
[ "Apache-2.0" ]
Python
tRabi
[list, list]
def tRabi(pulseModel: PulseModel, pulseFreq: Union[int, float], tRange: list, amp: float, sample: int = 100) -> [list, list]: """ Perform a Rabi Oscillation by varying the pulse duration. This function returns a list of pulse duration scanned and a list of populations. :param pulseModel: a pu...
Perform a Rabi Oscillation by varying the pulse duration. This function returns a list of pulse duration scanned and a list of populations. :param pulseModel: a pulseModel object :param pulseFreq: frequency of the pulse :param amp: fixed pulse amplitude :param tRange: a list of duration bounds...
Perform a Rabi Oscillation by varying the pulse duration. This function returns a list of pulse duration scanned and a list of populations.
[ "Perform", "a", "Rabi", "Oscillation", "by", "varying", "the", "pulse", "duration", ".", "This", "function", "returns", "a", "list", "of", "pulse", "duration", "scanned", "and", "a", "list", "of", "populations", "." ]
def tRabi(pulseModel: PulseModel, pulseFreq: Union[int, float], tRange: list, amp: float, sample: int = 100) -> [list, list]: popList = [] tList = linspace(tRange[0], tRange[1], sample) qJobList = pulseModel.ham.createJobList() for t in tList: qJob = pulseModel.ham.createJob() ...
[ "def", "tRabi", "(", "pulseModel", ":", "PulseModel", ",", "pulseFreq", ":", "Union", "[", "int", ",", "float", "]", ",", "tRange", ":", "list", ",", "amp", ":", "float", ",", "sample", ":", "int", "=", "100", ")", "->", "[", "list", ",", "list", ...
Perform a Rabi Oscillation by varying the pulse duration.
[ "Perform", "a", "Rabi", "Oscillation", "by", "varying", "the", "pulse", "duration", "." ]
[ "\"\"\"\n Perform a Rabi Oscillation by varying the pulse duration. This function returns a list of pulse duration scanned\n and a list of populations.\n\n :param pulseModel: a pulseModel object\n :param pulseFreq: frequency of the pulse\n :param amp: fixed pulse amplitude\n :param tRange: a list ...
[ { "param": "pulseModel", "type": "PulseModel" }, { "param": "pulseFreq", "type": "Union[int, float]" }, { "param": "tRange", "type": "list" }, { "param": "amp", "type": "float" }, { "param": "sample", "type": "int" } ]
{ "returns": [ { "docstring": "a list of pulse duration scanned and a list of populations", "docstring_tokens": [ "a", "list", "of", "pulse", "duration", "scanned", "and", "a", "list", "of", "populations" ], ...
969d2a6a92cb06d286fd5af383ecf571d916dc23
baidu/Quanlse
Quanlse/Calibration/SingleQubit.py
[ "Apache-2.0" ]
Python
ramsey
[list, list]
def ramsey(pulseModel: PulseModel, pulseFreq: float, tg: float, x90: float, sample: int = 100, maxTime: int = 800, detuning: float = None) -> [list, list]: """ Perform a Ramsey experiment. This function takes a PulseModel object, pulse frequency, pi/2 pulse length, pi/2 pulse amplitude, sample si...
Perform a Ramsey experiment. This function takes a PulseModel object, pulse frequency, pi/2 pulse length, pi/2 pulse amplitude, sample size, maximum idling time and detuning pulse amplitude. This function returns a list of idling time and a list of population. :param pulseModel: a PulseModel object ...
Perform a Ramsey experiment. This function takes a PulseModel object, pulse frequency, pi/2 pulse length, pi/2 pulse amplitude, sample size, maximum idling time and detuning pulse amplitude. This function returns a list of idling time and a list of population.
[ "Perform", "a", "Ramsey", "experiment", ".", "This", "function", "takes", "a", "PulseModel", "object", "pulse", "frequency", "pi", "/", "2", "pulse", "length", "pi", "/", "2", "pulse", "amplitude", "sample", "size", "maximum", "idling", "time", "and", "detun...
def ramsey(pulseModel: PulseModel, pulseFreq: float, tg: float, x90: float, sample: int = 100, maxTime: int = 800, detuning: float = None) -> [list, list]: ham = pulseModel.createQHamiltonian(frameMode='lab') if detuning is None: detuning = 2 * pi * 8. / maxTime tList = np.linspace(0, max...
[ "def", "ramsey", "(", "pulseModel", ":", "PulseModel", ",", "pulseFreq", ":", "float", ",", "tg", ":", "float", ",", "x90", ":", "float", ",", "sample", ":", "int", "=", "100", ",", "maxTime", ":", "int", "=", "800", ",", "detuning", ":", "float", ...
Perform a Ramsey experiment.
[ "Perform", "a", "Ramsey", "experiment", "." ]
[ "\"\"\"\n Perform a Ramsey experiment. This function takes a PulseModel object, pulse frequency, pi/2 pulse length,\n pi/2 pulse amplitude, sample size, maximum idling time and detuning pulse amplitude. This function returns\n a list of idling time and a list of population.\n\n :param pulseModel: a Puls...
[ { "param": "pulseModel", "type": "PulseModel" }, { "param": "pulseFreq", "type": "float" }, { "param": "tg", "type": "float" }, { "param": "x90", "type": "float" }, { "param": "sample", "type": "int" }, { "param": "maxTime", "type": "int" }, { ...
{ "returns": [], "raises": [], "params": [ { "identifier": "pulseModel", "type": "PulseModel", "docstring": "a PulseModel object", "docstring_tokens": [ "a", "PulseModel", "object" ], "default": null, "is_optional": null }, { "ide...
969d2a6a92cb06d286fd5af383ecf571d916dc23
baidu/Quanlse
Quanlse/Calibration/SingleQubit.py
[ "Apache-2.0" ]
Python
fitRamsey
[float, list]
def fitRamsey(t1: float, popList: list, tList: list, detuning: float) -> [float, list]: r""" Find T2 from Ramsey's result. This function takes a estimated T1 value, a list of population, a list of idling time and the amplitude of the detuning. The fitting function takes form: :math:`y = - 0.5 \cdot \cos...
r""" Find T2 from Ramsey's result. This function takes a estimated T1 value, a list of population, a list of idling time and the amplitude of the detuning. The fitting function takes form: :math:`y = - 0.5 \cdot \cos(a \cdot x) \exp(-b \cdot x) + 0.5` :param t1: estimated T1. :param popList: a list...
r""" Find T2 from Ramsey's result. This function takes a estimated T1 value, a list of population, a list of idling time and the amplitude of the detuning. The fitting function takes form.
[ "r", "\"", "\"", "\"", "Find", "T2", "from", "Ramsey", "'", "s", "result", ".", "This", "function", "takes", "a", "estimated", "T1", "value", "a", "list", "of", "population", "a", "list", "of", "idling", "time", "and", "the", "amplitude", "of", "the", ...
def fitRamsey(t1: float, popList: list, tList: list, detuning: float) -> [float, list]: def fitRam(x, a, b): return - np.cos(a * x) * np.exp(- b * x) * 0.5 + 0.5 paraFit, _ = curve_fit(fitRam, tList, popList, [detuning, 0.]) t2 = 1 / (paraFit[1] - 1 / (2 * t1)) return t2, list(- np.cos(paraFit[0...
[ "def", "fitRamsey", "(", "t1", ":", "float", ",", "popList", ":", "list", ",", "tList", ":", "list", ",", "detuning", ":", "float", ")", "->", "[", "float", ",", "list", "]", ":", "def", "fitRam", "(", "x", ",", "a", ",", "b", ")", ":", "return...
r""" Find T2 from Ramsey's result.
[ "r", "\"", "\"", "\"", "Find", "T2", "from", "Ramsey", "'", "s", "result", "." ]
[ "r\"\"\"\n Find T2 from Ramsey's result. This function takes a estimated T1 value, a list of population, a list\n of idling time and the amplitude of the detuning. The fitting function takes form:\n :math:`y = - 0.5 \\cdot \\cos(a \\cdot x) \\exp(-b \\cdot x) + 0.5`\n\n :param t1: estimated T1.\n :pa...
[ { "param": "t1", "type": "float" }, { "param": "popList", "type": "list" }, { "param": "tList", "type": "list" }, { "param": "detuning", "type": "float" } ]
{ "returns": [ { "docstring": "estimated t2, a list of population on the fitted curve", "docstring_tokens": [ "estimated", "t2", "a", "list", "of", "population", "on", "the", "fitted", "curve" ], "type": null ...
969d2a6a92cb06d286fd5af383ecf571d916dc23
baidu/Quanlse
Quanlse/Calibration/SingleQubit.py
[ "Apache-2.0" ]
Python
qubitSpec
[list, list]
def qubitSpec(pulseModel: PulseModel, freqRange: list, sample: int, amp: float, t: float) -> [list, list]: """ Qubit Spectroscopy. This function finds the qubit frequency by scanning the pulse frequency from a user-defined range. :param pulseModel: a pulseModel type object :param freqRange: a list ...
Qubit Spectroscopy. This function finds the qubit frequency by scanning the pulse frequency from a user-defined range. :param pulseModel: a pulseModel type object :param freqRange: a list of LO frequency's range :param sample: how many samples to scan within the freqRange :param amp: pulse amp...
Qubit Spectroscopy. This function finds the qubit frequency by scanning the pulse frequency from a user-defined range.
[ "Qubit", "Spectroscopy", ".", "This", "function", "finds", "the", "qubit", "frequency", "by", "scanning", "the", "pulse", "frequency", "from", "a", "user", "-", "defined", "range", "." ]
def qubitSpec(pulseModel: PulseModel, freqRange: list, sample: int, amp: float, t: float) -> [list, list]: freqList = linspace(freqRange[0], freqRange[1], sample) QSpecJob = pulseModel.ham.createJobList() for freq in freqList: job = pulseModel.ham.createJob() job.setLO(driveX(3), 0, freq=fre...
[ "def", "qubitSpec", "(", "pulseModel", ":", "PulseModel", ",", "freqRange", ":", "list", ",", "sample", ":", "int", ",", "amp", ":", "float", ",", "t", ":", "float", ")", "->", "[", "list", ",", "list", "]", ":", "freqList", "=", "linspace", "(", "...
Qubit Spectroscopy.
[ "Qubit", "Spectroscopy", "." ]
[ "\"\"\"\n Qubit Spectroscopy. This function finds the qubit frequency by scanning the pulse frequency\n from a user-defined range.\n\n :param pulseModel: a pulseModel type object\n :param freqRange: a list of LO frequency's range\n :param sample: how many samples to scan within the freqRange\n :pa...
[ { "param": "pulseModel", "type": "PulseModel" }, { "param": "freqRange", "type": "list" }, { "param": "sample", "type": "int" }, { "param": "amp", "type": "float" }, { "param": "t", "type": "float" } ]
{ "returns": [ { "docstring": "a list of pulse frequency scanned and a list of population", "docstring_tokens": [ "a", "list", "of", "pulse", "frequency", "scanned", "and", "a", "list", "of", "population" ], ...
d716071cdde50e4dc67fdf87882ff3bf655e206b
baidu/Quanlse
Quanlse/Calibration/Readout.py
[ "Apache-2.0" ]
Python
fitLorentzian
Union[ndarray, Iterable, int, float]
def fitLorentzian(x: ndarray, y: ndarray) -> Union[ndarray, Iterable, int, float]: """ Fit the curve using Lorentzian function. :param x: a list of x data. :param y: a list of y data. :return: the result of curve fitting. """ yMax = max(y) yMaxIdx = find_peaks(y, height=yMax)[0][0] ...
Fit the curve using Lorentzian function. :param x: a list of x data. :param y: a list of y data. :return: the result of curve fitting.
Fit the curve using Lorentzian function.
[ "Fit", "the", "curve", "using", "Lorentzian", "function", "." ]
def fitLorentzian(x: ndarray, y: ndarray) -> Union[ndarray, Iterable, int, float]: yMax = max(y) yMaxIdx = find_peaks(y, height=yMax)[0][0] yHalf = 0.5 * yMax yHalfIdx = argmin(abs(y - yHalf)) freqCenter = x[yMaxIdx] width = 2 * (x[yMaxIdx] - x[yHalfIdx]) param, cov = curve_fit(lorentzian, x...
[ "def", "fitLorentzian", "(", "x", ":", "ndarray", ",", "y", ":", "ndarray", ")", "->", "Union", "[", "ndarray", ",", "Iterable", ",", "int", ",", "float", "]", ":", "yMax", "=", "max", "(", "y", ")", "yMaxIdx", "=", "find_peaks", "(", "y", ",", "...
Fit the curve using Lorentzian function.
[ "Fit", "the", "curve", "using", "Lorentzian", "function", "." ]
[ "\"\"\"\n Fit the curve using Lorentzian function.\n\n :param x: a list of x data.\n :param y: a list of y data.\n :return: the result of curve fitting.\n \"\"\"" ]
[ { "param": "x", "type": "ndarray" }, { "param": "y", "type": "ndarray" } ]
{ "returns": [ { "docstring": "the result of curve fitting.", "docstring_tokens": [ "the", "result", "of", "curve", "fitting", "." ], "type": null } ], "raises": [], "params": [ { "identifier": "x", "type": "ndarray"...
d716071cdde50e4dc67fdf87882ff3bf655e206b
baidu/Quanlse
Quanlse/Calibration/Readout.py
[ "Apache-2.0" ]
Python
findFreq
Tuple[ndarray, dict]
def findFreq(y: Iterable) -> Tuple[ndarray, dict]: """ Find the index of the peak. :param y: a list of signals. :return: the index of the peak. """ yMax = max(y) yHalf = yMax / 2 idx = find_peaks(y, height=yHalf) return idx
Find the index of the peak. :param y: a list of signals. :return: the index of the peak.
Find the index of the peak.
[ "Find", "the", "index", "of", "the", "peak", "." ]
def findFreq(y: Iterable) -> Tuple[ndarray, dict]: yMax = max(y) yHalf = yMax / 2 idx = find_peaks(y, height=yHalf) return idx
[ "def", "findFreq", "(", "y", ":", "Iterable", ")", "->", "Tuple", "[", "ndarray", ",", "dict", "]", ":", "yMax", "=", "max", "(", "y", ")", "yHalf", "=", "yMax", "/", "2", "idx", "=", "find_peaks", "(", "y", ",", "height", "=", "yHalf", ")", "r...
Find the index of the peak.
[ "Find", "the", "index", "of", "the", "peak", "." ]
[ "\"\"\"\n Find the index of the peak.\n\n :param y: a list of signals.\n :return: the index of the peak.\n \"\"\"" ]
[ { "param": "y", "type": "Iterable" } ]
{ "returns": [ { "docstring": "the index of the peak.", "docstring_tokens": [ "the", "index", "of", "the", "peak", "." ], "type": null } ], "raises": [], "params": [ { "identifier": "y", "type": "Iterable", "do...
3ca003ab7d19d8013e75db83ab4008d5ff2fefca
baidu/Quanlse
Quanlse/Utils/Bloch.py
[ "Apache-2.0" ]
Python
rho2Coordinate
list
def rho2Coordinate(rho: np.ndarray) -> list: """ Convert a density matrix to the list of Cartesian coordinates. :param rho: The density matrix. :return: The list of Cartesian coordinates for given density matrix. """ x1 = 2 * rho[0][1].real x2 = 2 * rho[1][0].imag x3 = (rho[0][0] - rho...
Convert a density matrix to the list of Cartesian coordinates. :param rho: The density matrix. :return: The list of Cartesian coordinates for given density matrix.
Convert a density matrix to the list of Cartesian coordinates.
[ "Convert", "a", "density", "matrix", "to", "the", "list", "of", "Cartesian", "coordinates", "." ]
def rho2Coordinate(rho: np.ndarray) -> list: x1 = 2 * rho[0][1].real x2 = 2 * rho[1][0].imag x3 = (rho[0][0] - rho[1][1]).real return [x1, x2, x3]
[ "def", "rho2Coordinate", "(", "rho", ":", "np", ".", "ndarray", ")", "->", "list", ":", "x1", "=", "2", "*", "rho", "[", "0", "]", "[", "1", "]", ".", "real", "x2", "=", "2", "*", "rho", "[", "1", "]", "[", "0", "]", ".", "imag", "x3", "=...
Convert a density matrix to the list of Cartesian coordinates.
[ "Convert", "a", "density", "matrix", "to", "the", "list", "of", "Cartesian", "coordinates", "." ]
[ "\"\"\"\n Convert a density matrix to the list of Cartesian coordinates.\n\n :param rho: The density matrix.\n :return: The list of Cartesian coordinates for given density matrix.\n \"\"\"" ]
[ { "param": "rho", "type": "np.ndarray" } ]
{ "returns": [ { "docstring": "The list of Cartesian coordinates for given density matrix.", "docstring_tokens": [ "The", "list", "of", "Cartesian", "coordinates", "for", "given", "density", "matrix", "." ], "t...
692614a44a56c7069b57c7e3b8f7db55d1bac0d9
interlockledger/interlockledger-rest-client-python
il2_rest/models.py
[ "BSD-3-Clause" ]
Python
default
<not_specific>
def default(self, obj) : """ Set the behavior of the encoder depending on the type of obj. """ if isinstance(obj, datetime.datetime) : t = obj.strftime('%Y-%m-%dT%H:%M:%S.%f') z = obj.strftime('%z') if len(z) >=5 : z = z[:-2] + ':' + t...
Set the behavior of the encoder depending on the type of obj.
Set the behavior of the encoder depending on the type of obj.
[ "Set", "the", "behavior", "of", "the", "encoder", "depending", "on", "the", "type", "of", "obj", "." ]
def default(self, obj) : if isinstance(obj, datetime.datetime) : t = obj.strftime('%Y-%m-%dT%H:%M:%S.%f') z = obj.strftime('%z') if len(z) >=5 : z = z[:-2] + ':' + t[-2:] return t + z elif isinstance(obj, Color) : return obj.web...
[ "def", "default", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "datetime", ".", "datetime", ")", ":", "t", "=", "obj", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%S.%f'", ")", "z", "=", "obj", ".", "strftime", "(", "'%z'", ")",...
Set the behavior of the encoder depending on the type of obj.
[ "Set", "the", "behavior", "of", "the", "encoder", "depending", "on", "the", "type", "of", "obj", "." ]
[ "\"\"\"\n Set the behavior of the encoder depending on the type of obj.\n\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "obj", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "obj", "type": null, "docstring": null, "docstring_tokens": []...
692614a44a56c7069b57c7e3b8f7db55d1bac0d9
interlockledger/interlockledger-rest-client-python
il2_rest/models.py
[ "BSD-3-Clause" ]
Python
json
<not_specific>
def json(self, hide_null=True, return_as_str=False) : """ Convert a BaseModel class to a dict (JSON like). Args: hide_null (:obj:`bool`, optional): If True, discards every item (key, value) where value is None. return_as_str (:obj:`bool`, optional): If True, return the J...
Convert a BaseModel class to a dict (JSON like). Args: hide_null (:obj:`bool`, optional): If True, discards every item (key, value) where value is None. return_as_str (:obj:`bool`, optional): If True, return the JSON as a string instead of a dict. Returns: ...
Convert a BaseModel class to a dict (JSON like).
[ "Convert", "a", "BaseModel", "class", "to", "a", "dict", "(", "JSON", "like", ")", "." ]
def json(self, hide_null=True, return_as_str=False) : return BaseModel.to_json(self, hide_null, return_as_str)
[ "def", "json", "(", "self", ",", "hide_null", "=", "True", ",", "return_as_str", "=", "False", ")", ":", "return", "BaseModel", ".", "to_json", "(", "self", ",", "hide_null", ",", "return_as_str", ")" ]
Convert a BaseModel class to a dict (JSON like).
[ "Convert", "a", "BaseModel", "class", "to", "a", "dict", "(", "JSON", "like", ")", "." ]
[ "\"\"\"\n Convert a BaseModel class to a dict (JSON like).\n\n Args:\n hide_null (:obj:`bool`, optional): If True, discards every item (key, value) where value is None.\n return_as_str (:obj:`bool`, optional): If True, return the JSON as a string instead of a dict.\n\n Ret...
[ { "param": "self", "type": null }, { "param": "hide_null", "type": null }, { "param": "return_as_str", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
692614a44a56c7069b57c7e3b8f7db55d1bac0d9
interlockledger/interlockledger-rest-client-python
il2_rest/models.py
[ "BSD-3-Clause" ]
Python
to_json
<not_specific>
def to_json(cls, obj, hide_null=True, return_as_str=False) : """ Convert an object to a dict (JSON like). Args: obj (:obj:`list`/:obj:`dict`/:obj:`BaseModel`): Object to be converted to JSON. hide_null (:obj:`bool`, optional): If True, discards every item (key, value) wh...
Convert an object to a dict (JSON like). Args: obj (:obj:`list`/:obj:`dict`/:obj:`BaseModel`): Object to be converted to JSON. hide_null (:obj:`bool`, optional): If True, discards every item (key, value) where value is None. return_as_str (:obj:`bool`, optional): If...
Convert an object to a dict (JSON like).
[ "Convert", "an", "object", "to", "a", "dict", "(", "JSON", "like", ")", "." ]
def to_json(cls, obj, hide_null=True, return_as_str=False) : ret_json = json.loads(json.dumps(obj, cls=CustomEncoder)) if hide_null : ret_json = filter_none(ret_json) if isinstance(ret_json,dict) and 'JSON' in ret_json.keys() : ret_json['json'] = ret_json['JSON'] ...
[ "def", "to_json", "(", "cls", ",", "obj", ",", "hide_null", "=", "True", ",", "return_as_str", "=", "False", ")", ":", "ret_json", "=", "json", ".", "loads", "(", "json", ".", "dumps", "(", "obj", ",", "cls", "=", "CustomEncoder", ")", ")", "if", "...
Convert an object to a dict (JSON like).
[ "Convert", "an", "object", "to", "a", "dict", "(", "JSON", "like", ")", "." ]
[ "\"\"\"\n Convert an object to a dict (JSON like).\n\n Args:\n obj (:obj:`list`/:obj:`dict`/:obj:`BaseModel`): Object to be converted to JSON.\n hide_null (:obj:`bool`, optional): If True, discards every item (key, value) where value is None.\n return_as_str (:obj:`boo...
[ { "param": "cls", "type": null }, { "param": "obj", "type": null }, { "param": "hide_null", "type": null }, { "param": "return_as_str", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
692614a44a56c7069b57c7e3b8f7db55d1bac0d9
interlockledger/interlockledger-rest-client-python
il2_rest/models.py
[ "BSD-3-Clause" ]
Python
decode_with
<not_specific>
def decode_with(self, certificate) : """ Decode the encrypted JSON Document text using the keys inside the certificate. Args: certificate (:obj:`il2_rest.util.PKCS12Certificate`): PKCS12 certificate with the keys to decode the text. Returns: :obj:`dict`: Decoded...
Decode the encrypted JSON Document text using the keys inside the certificate. Args: certificate (:obj:`il2_rest.util.PKCS12Certificate`): PKCS12 certificate with the keys to decode the text. Returns: :obj:`dict`: Decoded JSON. Example: >>> node = ...
Decode the encrypted JSON Document text using the keys inside the certificate.
[ "Decode", "the", "encrypted", "JSON", "Document", "text", "using", "the", "keys", "inside", "the", "certificate", "." ]
def decode_with(self, certificate) : if not self.cipher : raise ValueError(f' No cipher detected.') if self.cipher != CipherAlgorithms.AES256 : raise ValueError(f'Cipher {self.cipher} is not currently supported.') if not certificate : raise ValueError('No key ...
[ "def", "decode_with", "(", "self", ",", "certificate", ")", ":", "if", "not", "self", ".", "cipher", ":", "raise", "ValueError", "(", "f' No cipher detected.'", ")", "if", "self", ".", "cipher", "!=", "CipherAlgorithms", ".", "AES256", ":", "raise", "ValueEr...
Decode the encrypted JSON Document text using the keys inside the certificate.
[ "Decode", "the", "encrypted", "JSON", "Document", "text", "using", "the", "keys", "inside", "the", "certificate", "." ]
[ "\"\"\"\n Decode the encrypted JSON Document text using the keys inside the certificate.\n\n Args:\n certificate (:obj:`il2_rest.util.PKCS12Certificate`): PKCS12 certificate with the keys to decode the text.\n\n Returns:\n :obj:`dict`: Decoded JSON.\n\n Example:\n ...
[ { "param": "self", "type": null }, { "param": "certificate", "type": null } ]
{ "returns": [ { "docstring": ":obj:`dict`: Decoded JSON.", "docstring_tokens": [ ":", "obj", ":", "`", "dict", "`", ":", "Decoded", "JSON", "." ], "type": null } ], "raises": [], "params": [ { ...
e044ef276b44988e5f0a7e0048068bc23a321755
interlockledger/interlockledger-rest-client-python
il2_rest/util.py
[ "BSD-3-Clause" ]
Python
null_condition_attribute
<not_specific>
def null_condition_attribute(obj, attribute) : """ Return the value of the item with key equals to attribute. Args: obj (:obj:`dict`) : Dictionary object. attribute (:obj:`str`) : Attribute name of obj. Returns: The value of the item. If obj is None, return None. ""...
Return the value of the item with key equals to attribute. Args: obj (:obj:`dict`) : Dictionary object. attribute (:obj:`str`) : Attribute name of obj. Returns: The value of the item. If obj is None, return None.
Return the value of the item with key equals to attribute.
[ "Return", "the", "value", "of", "the", "item", "with", "key", "equals", "to", "attribute", "." ]
def null_condition_attribute(obj, attribute) : if (obj is None): return None else : return getattr(obj, attribute)
[ "def", "null_condition_attribute", "(", "obj", ",", "attribute", ")", ":", "if", "(", "obj", "is", "None", ")", ":", "return", "None", "else", ":", "return", "getattr", "(", "obj", ",", "attribute", ")" ]
Return the value of the item with key equals to attribute.
[ "Return", "the", "value", "of", "the", "item", "with", "key", "equals", "to", "attribute", "." ]
[ "\"\"\"\n Return the value of the item with key equals to attribute.\n\n Args:\n obj (:obj:`dict`) : Dictionary object.\n attribute (:obj:`str`) : Attribute name of obj.\n\n Returns:\n The value of the item.\n If obj is None, return None.\n \"\"\"" ]
[ { "param": "obj", "type": null }, { "param": "attribute", "type": null } ]
{ "returns": [ { "docstring": "The value of the item.\nIf obj is None, return None.", "docstring_tokens": [ "The", "value", "of", "the", "item", ".", "If", "obj", "is", "None", "return", "None", "."...
e044ef276b44988e5f0a7e0048068bc23a321755
interlockledger/interlockledger-rest-client-python
il2_rest/util.py
[ "BSD-3-Clause" ]
Python
filter_none
<not_specific>
def filter_none(d) : """ Remove items of a dictionary with None values. Args: d (:obj:`dict`): Dictionary object. Returns: :obj:`dict`: Dictionary without None items. """ if isinstance(d, dict) : return {k: filter_none(v) for k,v in d.items() if v is not None} elif ...
Remove items of a dictionary with None values. Args: d (:obj:`dict`): Dictionary object. Returns: :obj:`dict`: Dictionary without None items.
Remove items of a dictionary with None values.
[ "Remove", "items", "of", "a", "dictionary", "with", "None", "values", "." ]
def filter_none(d) : if isinstance(d, dict) : return {k: filter_none(v) for k,v in d.items() if v is not None} elif isinstance(d, list) : return [filter_none(v) for v in d] else : return d
[ "def", "filter_none", "(", "d", ")", ":", "if", "isinstance", "(", "d", ",", "dict", ")", ":", "return", "{", "k", ":", "filter_none", "(", "v", ")", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}"...
Remove items of a dictionary with None values.
[ "Remove", "items", "of", "a", "dictionary", "with", "None", "values", "." ]
[ "\"\"\"\n Remove items of a dictionary with None values.\n\n Args:\n d (:obj:`dict`): Dictionary object.\n\n Returns:\n :obj:`dict`: Dictionary without None items.\n \"\"\"" ]
[ { "param": "d", "type": null } ]
{ "returns": [ { "docstring": ":obj:`dict`: Dictionary without None items.", "docstring_tokens": [ ":", "obj", ":", "`", "dict", "`", ":", "Dictionary", "without", "None", "items", "." ], "type"...
e044ef276b44988e5f0a7e0048068bc23a321755
interlockledger/interlockledger-rest-client-python
il2_rest/util.py
[ "BSD-3-Clause" ]
Python
build_query
<not_specific>
def build_query(args_names, args_values) : """ Transform a list of names and values in a HTTP query string. Args: args_names (:obj:`list` of :obj:`str`): List of names. args_values (:obj:`list`): List of values, must have same length of args_names. Returns: :obj:`str` : Quer...
Transform a list of names and values in a HTTP query string. Args: args_names (:obj:`list` of :obj:`str`): List of names. args_values (:obj:`list`): List of values, must have same length of args_names. Returns: :obj:`str` : Query string.
Transform a list of names and values in a HTTP query string.
[ "Transform", "a", "list", "of", "names", "and", "values", "in", "a", "HTTP", "query", "string", "." ]
def build_query(args_names, args_values) : ret_str = '' first = True for (name, value) in zip(args_names, args_values) : if value : if first : ret_str += '?' first = False else : ret_str += '&' ret_str += f'{name}={v...
[ "def", "build_query", "(", "args_names", ",", "args_values", ")", ":", "ret_str", "=", "''", "first", "=", "True", "for", "(", "name", ",", "value", ")", "in", "zip", "(", "args_names", ",", "args_values", ")", ":", "if", "value", ":", "if", "first", ...
Transform a list of names and values in a HTTP query string.
[ "Transform", "a", "list", "of", "names", "and", "values", "in", "a", "HTTP", "query", "string", "." ]
[ "\"\"\"\n Transform a list of names and values in a HTTP query string.\n \n Args:\n args_names (:obj:`list` of :obj:`str`): List of names.\n args_values (:obj:`list`): List of values, must have same length of args_names.\n Returns:\n :obj:`str` : Query string.\n \"\"\"" ]
[ { "param": "args_names", "type": null }, { "param": "args_values", "type": null } ]
{ "returns": [ { "docstring": ":obj:`str` : Query string.", "docstring_tokens": [ ":", "obj", ":", "`", "str", "`", ":", "Query", "string", "." ], "type": null } ], "raises": [], "params": [ { ...
e044ef276b44988e5f0a7e0048068bc23a321755
interlockledger/interlockledger-rest-client-python
il2_rest/util.py
[ "BSD-3-Clause" ]
Python
overlaps_with
<not_specific>
def overlaps_with(self, other) : """ Check if there is an overlap between the intervals of self and other. Returns: :obj:`bool`: Return True if there is an overlap. """ return other.start in self or other.end in self or self in other
Check if there is an overlap between the intervals of self and other. Returns: :obj:`bool`: Return True if there is an overlap.
Check if there is an overlap between the intervals of self and other.
[ "Check", "if", "there", "is", "an", "overlap", "between", "the", "intervals", "of", "self", "and", "other", "." ]
def overlaps_with(self, other) : return other.start in self or other.end in self or self in other
[ "def", "overlaps_with", "(", "self", ",", "other", ")", ":", "return", "other", ".", "start", "in", "self", "or", "other", ".", "end", "in", "self", "or", "self", "in", "other" ]
Check if there is an overlap between the intervals of self and other.
[ "Check", "if", "there", "is", "an", "overlap", "between", "the", "intervals", "of", "self", "and", "other", "." ]
[ "\"\"\"\n Check if there is an overlap between the intervals of self and other.\n\n Returns:\n :obj:`bool`: Return True if there is an overlap.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "other", "type": null } ]
{ "returns": [ { "docstring": ":obj:`bool`: Return True if there is an overlap.", "docstring_tokens": [ ":", "obj", ":", "`", "bool", "`", ":", "Return", "True", "if", "there", "is", "an", "...
e044ef276b44988e5f0a7e0048068bc23a321755
interlockledger/interlockledger-rest-client-python
il2_rest/util.py
[ "BSD-3-Clause" ]
Python
has_pk
<not_specific>
def has_pk(self) : """ Check if the certificate has a primary key. Returns: :obj:`bool`: True if the certificate has a primary key. """ return self.__pkcs12_cert[0] is not None
Check if the certificate has a primary key. Returns: :obj:`bool`: True if the certificate has a primary key.
Check if the certificate has a primary key.
[ "Check", "if", "the", "certificate", "has", "a", "primary", "key", "." ]
def has_pk(self) : return self.__pkcs12_cert[0] is not None
[ "def", "has_pk", "(", "self", ")", ":", "return", "self", ".", "__pkcs12_cert", "[", "0", "]", "is", "not", "None" ]
Check if the certificate has a primary key.
[ "Check", "if", "the", "certificate", "has", "a", "primary", "key", "." ]
[ "\"\"\"\n Check if the certificate has a primary key.\n \n Returns:\n :obj:`bool`: True if the certificate has a primary key.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": ":obj:`bool`: True if the certificate has a primary key.", "docstring_tokens": [ ":", "obj", ":", "`", "bool", "`", ":", "True", "if", "the", "certificate", "has", "a",...
e044ef276b44988e5f0a7e0048068bc23a321755
interlockledger/interlockledger-rest-client-python
il2_rest/util.py
[ "BSD-3-Clause" ]
Python
decrypt
<not_specific>
def decrypt(self, cypher_text) : """ Decode a encrypted message using RSA with SHA1. Args: cypher_text (:obj:`bytes`): Encrypted message. Returns: :obj:`bytes`: Decrypted message. """ msg = self.__pkcs12_cert[0].decrypt(cypher_tex...
Decode a encrypted message using RSA with SHA1. Args: cypher_text (:obj:`bytes`): Encrypted message. Returns: :obj:`bytes`: Decrypted message.
Decode a encrypted message using RSA with SHA1.
[ "Decode", "a", "encrypted", "message", "using", "RSA", "with", "SHA1", "." ]
def decrypt(self, cypher_text) : msg = self.__pkcs12_cert[0].decrypt(cypher_text, padding=padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None )) return msg
[ "def", "decrypt", "(", "self", ",", "cypher_text", ")", ":", "msg", "=", "self", ".", "__pkcs12_cert", "[", "0", "]", ".", "decrypt", "(", "cypher_text", ",", "padding", "=", "padding", ".", "OAEP", "(", "mgf", "=", "padding", ".", "MGF1", "(", "algo...
Decode a encrypted message using RSA with SHA1.
[ "Decode", "a", "encrypted", "message", "using", "RSA", "with", "SHA1", "." ]
[ "\"\"\"\n Decode a encrypted message using RSA with SHA1.\n \n Args:\n cypher_text (:obj:`bytes`): Encrypted message.\n\n Returns:\n :obj:`bytes`: Decrypted message.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "cypher_text", "type": null } ]
{ "returns": [ { "docstring": ":obj:`bytes`: Decrypted message.", "docstring_tokens": [ ":", "obj", ":", "`", "bytes", "`", ":", "Decrypted", "message", "." ], "type": null } ], "raises": [], "params"...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
interlocks
<not_specific>
def interlocks(self, howManyFromLast=0, page=0, pageSize=10) : """ Get list of interlocks registered for the chain. Args: howManyFromLast (:obj:`int`): How many interlocking records to return. If ommited or 0 returns all. page (:obj:`int`): Page to return. pa...
Get list of interlocks registered for the chain. Args: howManyFromLast (:obj:`int`): How many interlocking records to return. If ommited or 0 returns all. page (:obj:`int`): Page to return. pageSize (:obj:`int`): Number of items per page. If 0 returns all. ...
Get list of interlocks registered for the chain.
[ "Get", "list", "of", "interlocks", "registered", "for", "the", "chain", "." ]
def interlocks(self, howManyFromLast=0, page=0, pageSize=10) : json_data = self.__rest._get(f'/chain/{self.id}/interlockings?howManyFromLast={howManyFromLast}&page={page}&pageSize={pageSize}') json_data['itemClass'] = InterlockingRecordModel return PageOfModel.from_json(json_data)
[ "def", "interlocks", "(", "self", ",", "howManyFromLast", "=", "0", ",", "page", "=", "0", ",", "pageSize", "=", "10", ")", ":", "json_data", "=", "self", ".", "__rest", ".", "_get", "(", "f'/chain/{self.id}/interlockings?howManyFromLast={howManyFromLast}&page={pa...
Get list of interlocks registered for the chain.
[ "Get", "list", "of", "interlocks", "registered", "for", "the", "chain", "." ]
[ "\"\"\"\n Get list of interlocks registered for the chain.\n\n Args:\n howManyFromLast (:obj:`int`): How many interlocking records to return. If ommited or 0 returns all.\n page (:obj:`int`): Page to return.\n pageSize (:obj:`int`): Number of items per page. If 0 retur...
[ { "param": "self", "type": null }, { "param": "howManyFromLast", "type": null }, { "param": "page", "type": null }, { "param": "pageSize", "type": null } ]
{ "returns": [ { "docstring": ":obj:`il2_rest.models.PageOfModel` of :obj:`il2_rest.models.InterlockingRecordModel`: List of interlocks registered in the chain.", "docstring_tokens": [ ":", "obj", ":", "`", "il2_rest", ".", "models", ".",...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
add_record_unpacked
<not_specific>
def add_record_unpacked(self, applicationId, payloadTagId, rec_bytes, rec_type=RecordType.Data) : """ Add a new record with an unpacked payload. Payload inner bytes MUST go in the body, in binary form. These inner bytes will be prefixed with the payloadTagId and the lenght, both encoded...
Add a new record with an unpacked payload. Payload inner bytes MUST go in the body, in binary form. These inner bytes will be prefixed with the payloadTagId and the lenght, both encoded as ILInt, as required to assemble the record effective payload. Args: applicationId (:o...
Add a new record with an unpacked payload. Payload inner bytes MUST go in the body, in binary form. These inner bytes will be prefixed with the payloadTagId and the lenght, both encoded as ILInt, as required to assemble the record effective payload.
[ "Add", "a", "new", "record", "with", "an", "unpacked", "payload", ".", "Payload", "inner", "bytes", "MUST", "go", "in", "the", "body", "in", "binary", "form", ".", "These", "inner", "bytes", "will", "be", "prefixed", "with", "the", "payloadTagId", "and", ...
def add_record_unpacked(self, applicationId, payloadTagId, rec_bytes, rec_type=RecordType.Data) : cur_url = f"/records@{self.id}/with?applicationId={applicationId}&payloadTagId={payloadTagId}&type={rec_type.value}" return RecordModel.from_json(self.__rest._post_raw(cur_url, rec_bytes, "application/inter...
[ "def", "add_record_unpacked", "(", "self", ",", "applicationId", ",", "payloadTagId", ",", "rec_bytes", ",", "rec_type", "=", "RecordType", ".", "Data", ")", ":", "cur_url", "=", "f\"/records@{self.id}/with?applicationId={applicationId}&payloadTagId={payloadTagId}&type={rec_t...
Add a new record with an unpacked payload.
[ "Add", "a", "new", "record", "with", "an", "unpacked", "payload", "." ]
[ "\"\"\"\n Add a new record with an unpacked payload. \n Payload inner bytes MUST go in the body, in binary form.\n These inner bytes will be prefixed with the payloadTagId and the lenght, both encoded as ILInt, as required to assemble the record effective payload.\n\n Args:\n ...
[ { "param": "self", "type": null }, { "param": "applicationId", "type": null }, { "param": "payloadTagId", "type": null }, { "param": "rec_bytes", "type": null }, { "param": "rec_type", "type": null } ]
{ "returns": [ { "docstring": ":obj:`il2_rest.models.RecordModel`: Added record information.", "docstring_tokens": [ ":", "obj", ":", "`", "il2_rest", ".", "models", ".", "RecordModel", "`", ":", "Added", ...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
add_record_as_json
<not_specific>
def add_record_as_json(self, applicationId=None, payloadTagId=None, payload=None, rec_type=RecordType.Data, model=None) : """ Add a new record with a payload encoded as JSON. The JSON value will be mapped to the payload tagged format as described by the metadata associated with the payloadTagId ...
Add a new record with a payload encoded as JSON. The JSON value will be mapped to the payload tagged format as described by the metadata associated with the payloadTagId Args: applicationId (:obj:`int`): Application id of the record. payloadTagId (:obj:`int`): Payload t...
Add a new record with a payload encoded as JSON. The JSON value will be mapped to the payload tagged format as described by the metadata associated with the payloadTagId
[ "Add", "a", "new", "record", "with", "a", "payload", "encoded", "as", "JSON", ".", "The", "JSON", "value", "will", "be", "mapped", "to", "the", "payload", "tagged", "format", "as", "described", "by", "the", "metadata", "associated", "with", "the", "payload...
def add_record_as_json(self, applicationId=None, payloadTagId=None, payload=None, rec_type=RecordType.Data, model=None) : if model : if not isinstance(model, NewRecordModelAsJson) : raise TypeError('model must be NewRecordModelAsJson') return RecordModelAsJson.from_json(s...
[ "def", "add_record_as_json", "(", "self", ",", "applicationId", "=", "None", ",", "payloadTagId", "=", "None", ",", "payload", "=", "None", ",", "rec_type", "=", "RecordType", ".", "Data", ",", "model", "=", "None", ")", ":", "if", "model", ":", "if", ...
Add a new record with a payload encoded as JSON.
[ "Add", "a", "new", "record", "with", "a", "payload", "encoded", "as", "JSON", "." ]
[ "\"\"\"\n Add a new record with a payload encoded as JSON.\n The JSON value will be mapped to the payload tagged format as described by the metadata associated with the payloadTagId\n\n Args:\n applicationId (:obj:`int`): Application id of the record.\n payloadTagId (:obj:...
[ { "param": "self", "type": null }, { "param": "applicationId", "type": null }, { "param": "payloadTagId", "type": null }, { "param": "payload", "type": null }, { "param": "rec_type", "type": null }, { "param": "model", "type": null } ]
{ "returns": [ { "docstring": ":obj:`il2_rest.models.RecordModel`: Added record information.", "docstring_tokens": [ ":", "obj", ":", "`", "il2_rest", ".", "models", ".", "RecordModel", "`", ":", "Added", ...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
force_interlock
<not_specific>
def force_interlock(self, model) : """ Forces an interlock on a target chain. Args: model (:obj:`il2_rest.models.ForceInterlockModel`): Force interlock command details. Returns: :obj:`il2_rest.models.InterlockingRecordModel`: Interlocking details. Examp...
Forces an interlock on a target chain. Args: model (:obj:`il2_rest.models.ForceInterlockModel`): Force interlock command details. Returns: :obj:`il2_rest.models.InterlockingRecordModel`: Interlocking details. Example: >>> node = RestNode(cert_file='...
Forces an interlock on a target chain.
[ "Forces", "an", "interlock", "on", "a", "target", "chain", "." ]
def force_interlock(self, model) : return InterlockingRecordModel.from_json(self.__rest._post(f"/chain/{self.id}/interlockings", model))
[ "def", "force_interlock", "(", "self", ",", "model", ")", ":", "return", "InterlockingRecordModel", ".", "from_json", "(", "self", ".", "__rest", ".", "_post", "(", "f\"/chain/{self.id}/interlockings\"", ",", "model", ")", ")" ]
Forces an interlock on a target chain.
[ "Forces", "an", "interlock", "on", "a", "target", "chain", "." ]
[ "\"\"\"\n Forces an interlock on a target chain.\n\n Args:\n model (:obj:`il2_rest.models.ForceInterlockModel`): Force interlock command details.\n\n Returns:\n :obj:`il2_rest.models.InterlockingRecordModel`: Interlocking details.\n Example:\n >>> node = ...
[ { "param": "self", "type": null }, { "param": "model", "type": null } ]
{ "returns": [ { "docstring": ":obj:`il2_rest.models.InterlockingRecordModel`: Interlocking details.", "docstring_tokens": [ ":", "obj", ":", "`", "il2_rest", ".", "models", ".", "InterlockingRecordModel", "`", ":"...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
permit_apps
<not_specific>
def permit_apps(self, apps_to_permit) : """ Add apps to the permitted list for the chain. Args: apps_to_permit (:obj:`list` of :obj:`int`): List of apps (by number) to be permitted. Returns: :obj:`list` of :obj:`int`: Enumerate apps that are currently permitted ...
Add apps to the permitted list for the chain. Args: apps_to_permit (:obj:`list` of :obj:`int`): List of apps (by number) to be permitted. Returns: :obj:`list` of :obj:`int`: Enumerate apps that are currently permitted on this chain. Example: >>> no...
Add apps to the permitted list for the chain.
[ "Add", "apps", "to", "the", "permitted", "list", "for", "the", "chain", "." ]
def permit_apps(self, apps_to_permit) : return self.__rest._post(f"/chain/{self.id}/activeApps", apps_to_permit)
[ "def", "permit_apps", "(", "self", ",", "apps_to_permit", ")", ":", "return", "self", ".", "__rest", ".", "_post", "(", "f\"/chain/{self.id}/activeApps\"", ",", "apps_to_permit", ")" ]
Add apps to the permitted list for the chain.
[ "Add", "apps", "to", "the", "permitted", "list", "for", "the", "chain", "." ]
[ "\"\"\"\n Add apps to the permitted list for the chain.\n\n Args:\n apps_to_permit (:obj:`list` of :obj:`int`): List of apps (by number) to be permitted.\n\n Returns:\n :obj:`list` of :obj:`int`: Enumerate apps that are currently permitted on this chain.\n\n Example...
[ { "param": "self", "type": null }, { "param": "apps_to_permit", "type": null } ]
{ "returns": [ { "docstring": ":obj:`list` of :obj:`int`: Enumerate apps that are currently permitted on this chain.", "docstring_tokens": [ ":", "obj", ":", "`", "list", "`", "of", ":", "obj", ":", "`", "i...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
permit_keys
<not_specific>
def permit_keys(self, keys_to_permit) : """ Add keys to the permitted list for the chain. Args: keys_to_permit (:obj:`list` of :obj:`il2_rest.models.KeyPermitModel`): List of keys to permitted. Returns: :obj:`list` of :obj:`il2_rest.models.KeyModel`: Enumerate k...
Add keys to the permitted list for the chain. Args: keys_to_permit (:obj:`list` of :obj:`il2_rest.models.KeyPermitModel`): List of keys to permitted. Returns: :obj:`list` of :obj:`il2_rest.models.KeyModel`: Enumerate keys that are currently permitted on chain. ...
Add keys to the permitted list for the chain.
[ "Add", "keys", "to", "the", "permitted", "list", "for", "the", "chain", "." ]
def permit_keys(self, keys_to_permit) : json_data = self.__rest._post(f"/chain/{self.id}/key", keys_to_permit) return [KeyModel.from_json(item) for item in json_data]
[ "def", "permit_keys", "(", "self", ",", "keys_to_permit", ")", ":", "json_data", "=", "self", ".", "__rest", ".", "_post", "(", "f\"/chain/{self.id}/key\"", ",", "keys_to_permit", ")", "return", "[", "KeyModel", ".", "from_json", "(", "item", ")", "for", "it...
Add keys to the permitted list for the chain.
[ "Add", "keys", "to", "the", "permitted", "list", "for", "the", "chain", "." ]
[ "\"\"\"\n Add keys to the permitted list for the chain.\n\n Args:\n keys_to_permit (:obj:`list` of :obj:`il2_rest.models.KeyPermitModel`): List of keys to permitted.\n\n Returns:\n :obj:`list` of :obj:`il2_rest.models.KeyModel`: Enumerate keys that are currently permitted ...
[ { "param": "self", "type": null }, { "param": "keys_to_permit", "type": null } ]
{ "returns": [ { "docstring": ":obj:`list` of :obj:`il2_rest.models.KeyModel`: Enumerate keys that are currently permitted on chain.", "docstring_tokens": [ ":", "obj", ":", "`", "list", "`", "of", ":", "obj", ":", ...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
records
<not_specific>
def records(self, firstSerial=None, lastSerial=None, page=0, pageSize=10, lastToFirst=False) : """ Get list of records starting from a given serial number. Args: firstSerial (:obj:`int`, optional): Starting serial number. lastSerial (:obj:`int`, optional): Last serial nu...
Get list of records starting from a given serial number. Args: firstSerial (:obj:`int`, optional): Starting serial number. lastSerial (:obj:`int`, optional): Last serial number. page (:obj:`int`, optional): Page to return (Default is 0). pageSize (:obj:`...
Get list of records starting from a given serial number.
[ "Get", "list", "of", "records", "starting", "from", "a", "given", "serial", "number", "." ]
def records(self, firstSerial=None, lastSerial=None, page=0, pageSize=10, lastToFirst=False) : cur_curl = f"/records@{self.id}?page={page}&pageSize={pageSize}&lastToFirst={lastToFirst}" if firstSerial : cur_curl += f"&firstSerial={firstSerial}" if lastSerial : cur_curl +=...
[ "def", "records", "(", "self", ",", "firstSerial", "=", "None", ",", "lastSerial", "=", "None", ",", "page", "=", "0", ",", "pageSize", "=", "10", ",", "lastToFirst", "=", "False", ")", ":", "cur_curl", "=", "f\"/records@{self.id}?page={page}&pageSize={pageSiz...
Get list of records starting from a given serial number.
[ "Get", "list", "of", "records", "starting", "from", "a", "given", "serial", "number", "." ]
[ "\"\"\"\n Get list of records starting from a given serial number.\n\n Args:\n firstSerial (:obj:`int`, optional): Starting serial number.\n lastSerial (:obj:`int`, optional): Last serial number.\n page (:obj:`int`, optional): Page to return (Default is 0).\n ...
[ { "param": "self", "type": null }, { "param": "firstSerial", "type": null }, { "param": "lastSerial", "type": null }, { "param": "page", "type": null }, { "param": "pageSize", "type": null }, { "param": "lastToFirst", "type": null } ]
{ "returns": [ { "docstring": ":obj:`il2_rest.models.PageOfModel` of :obj:`il2_rest.models.RecordModel`: List of records in the given interval.", "docstring_tokens": [ ":", "obj", ":", "`", "il2_rest", ".", "models", ".", "PageOfM...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
records_as_json
<not_specific>
def records_as_json(self, firstSerial=None, lastSerial=None, page=0, pageSize=10, lastToFirst=False) : """ Get list of records with payload mapped to JSON starting from a given serial number. Args: firstSerial (:obj:`int`, optional): Starting serial number. lastSerial (:...
Get list of records with payload mapped to JSON starting from a given serial number. Args: firstSerial (:obj:`int`, optional): Starting serial number. lastSerial (:obj:`int`, optional): Last serial number. page (:obj:`int`, optional): Page to return (Default is 0). ...
Get list of records with payload mapped to JSON starting from a given serial number.
[ "Get", "list", "of", "records", "with", "payload", "mapped", "to", "JSON", "starting", "from", "a", "given", "serial", "number", "." ]
def records_as_json(self, firstSerial=None, lastSerial=None, page=0, pageSize=10, lastToFirst=False) : cur_curl = f"/records@{self.id}/asJson?page={page}&pageSize={pageSize}&lastToFirst={lastToFirst}" if firstSerial : cur_curl += f"&firstSerial={firstSerial}" if lastSerial : ...
[ "def", "records_as_json", "(", "self", ",", "firstSerial", "=", "None", ",", "lastSerial", "=", "None", ",", "page", "=", "0", ",", "pageSize", "=", "10", ",", "lastToFirst", "=", "False", ")", ":", "cur_curl", "=", "f\"/records@{self.id}/asJson?page={page}&pa...
Get list of records with payload mapped to JSON starting from a given serial number.
[ "Get", "list", "of", "records", "with", "payload", "mapped", "to", "JSON", "starting", "from", "a", "given", "serial", "number", "." ]
[ "\"\"\"\n Get list of records with payload mapped to JSON starting from a given serial number.\n\n Args:\n firstSerial (:obj:`int`, optional): Starting serial number.\n lastSerial (:obj:`int`, optional): Last serial number.\n page (:obj:`int`, optional): Page to return...
[ { "param": "self", "type": null }, { "param": "firstSerial", "type": null }, { "param": "lastSerial", "type": null }, { "param": "page", "type": null }, { "param": "pageSize", "type": null }, { "param": "lastToFirst", "type": null } ]
{ "returns": [ { "docstring": ":obj:`il2_rest.models.PageOfModel` of :obj:`il2_rest.models.RecordModelAsJson`: List of records mapped to JSON in the given interval.", "docstring_tokens": [ ":", "obj", ":", "`", "il2_rest", ".", "models", ...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
record_at_as_json
<not_specific>
def record_at_as_json(self, serial) : """ Get an specific record with payload mapped to json. Args: serial (:obj:`int`): Record serial number. Returns: :obj:`il2_rest.models.RecordModelAsJson`: Record mapped to JSON with the specific serial number. """ ...
Get an specific record with payload mapped to json. Args: serial (:obj:`int`): Record serial number. Returns: :obj:`il2_rest.models.RecordModelAsJson`: Record mapped to JSON with the specific serial number.
Get an specific record with payload mapped to json.
[ "Get", "an", "specific", "record", "with", "payload", "mapped", "to", "json", "." ]
def record_at_as_json(self, serial) : return RecordModelAsJson.from_json(self.__rest._get(f"/records@{self.id}/{serial}/asJson"))
[ "def", "record_at_as_json", "(", "self", ",", "serial", ")", ":", "return", "RecordModelAsJson", ".", "from_json", "(", "self", ".", "__rest", ".", "_get", "(", "f\"/records@{self.id}/{serial}/asJson\"", ")", ")" ]
Get an specific record with payload mapped to json.
[ "Get", "an", "specific", "record", "with", "payload", "mapped", "to", "json", "." ]
[ "\"\"\"\n Get an specific record with payload mapped to json.\n\n Args:\n serial (:obj:`int`): Record serial number.\n\n Returns:\n :obj:`il2_rest.models.RecordModelAsJson`: Record mapped to JSON with the specific serial number.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "serial", "type": null } ]
{ "returns": [ { "docstring": ":obj:`il2_rest.models.RecordModelAsJson`: Record mapped to JSON with the specific serial number.", "docstring_tokens": [ ":", "obj", ":", "`", "il2_rest", ".", "models", ".", "RecordModelAsJson", ...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
json_document_at
<not_specific>
def json_document_at(self, serial): """ Get a specific JSON document stored in the chain. Args: serial (:obj:`int`): Serial number of the record. Returns: :obj:`il2_rest.models.JsonDocumentRecordModel`: JSON document record. """ return JsonDocumen...
Get a specific JSON document stored in the chain. Args: serial (:obj:`int`): Serial number of the record. Returns: :obj:`il2_rest.models.JsonDocumentRecordModel`: JSON document record.
Get a specific JSON document stored in the chain.
[ "Get", "a", "specific", "JSON", "document", "stored", "in", "the", "chain", "." ]
def json_document_at(self, serial): return JsonDocumentRecordModel.from_json(self.__rest._get(f'/jsonDocuments@{self.id}/{serial}'))
[ "def", "json_document_at", "(", "self", ",", "serial", ")", ":", "return", "JsonDocumentRecordModel", ".", "from_json", "(", "self", ".", "__rest", ".", "_get", "(", "f'/jsonDocuments@{self.id}/{serial}'", ")", ")" ]
Get a specific JSON document stored in the chain.
[ "Get", "a", "specific", "JSON", "document", "stored", "in", "the", "chain", "." ]
[ "\"\"\"\n Get a specific JSON document stored in the chain.\n Args:\n serial (:obj:`int`): Serial number of the record.\n\n Returns:\n :obj:`il2_rest.models.JsonDocumentRecordModel`: JSON document record.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "serial", "type": null } ]
{ "returns": [ { "docstring": ":obj:`il2_rest.models.JsonDocumentRecordModel`: JSON document record.", "docstring_tokens": [ ":", "obj", ":", "`", "il2_rest", ".", "models", ".", "JsonDocumentRecordModel", "`", ":"...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
store_json_document
<not_specific>
def store_json_document(self, payload) : """ Store a JSON document record. Args: payload (:obj:`dict`): A valid JSON. Returns: :obj:`il2_rest.models.JsonDocumentRecordModel`: Added JSON document details. Example: >>> node = R...
Store a JSON document record. Args: payload (:obj:`dict`): A valid JSON. Returns: :obj:`il2_rest.models.JsonDocumentRecordModel`: Added JSON document details. Example: >>> node = RestNode(cert_file='documenter.pfx', cert_pass='passw...
Store a JSON document record.
[ "Store", "a", "JSON", "document", "record", "." ]
def store_json_document(self, payload) : return JsonDocumentRecordModel.from_json(self.__rest._post(f"/jsonDocuments@{self.id}", payload))
[ "def", "store_json_document", "(", "self", ",", "payload", ")", ":", "return", "JsonDocumentRecordModel", ".", "from_json", "(", "self", ".", "__rest", ".", "_post", "(", "f\"/jsonDocuments@{self.id}\"", ",", "payload", ")", ")" ]
Store a JSON document record.
[ "Store", "a", "JSON", "document", "record", "." ]
[ "\"\"\"\n Store a JSON document record.\n \n Args:\n payload (:obj:`dict`): A valid JSON.\n\n Returns:\n :obj:`il2_rest.models.JsonDocumentRecordModel`: Added JSON document details.\n \n Example:\n >>> node = RestNode(cert_file='documenter.p...
[ { "param": "self", "type": null }, { "param": "payload", "type": null } ]
{ "returns": [ { "docstring": ":obj:`il2_rest.models.JsonDocumentRecordModel`: Added JSON document details.", "docstring_tokens": [ ":", "obj", ":", "`", "il2_rest", ".", "models", ".", "JsonDocumentRecordModel", "`", ...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
documents_transaction_status
<not_specific>
def documents_transaction_status(self, transaction_id) : """ Get the ongoing status of a transaction. Args: transaction_id (:obj:`str`): Id of the transaction. Returns: :obj:`il2_rest.models.DocumentsTransactionModel`: Transaction identifier and limits. ...
Get the ongoing status of a transaction. Args: transaction_id (:obj:`str`): Id of the transaction. Returns: :obj:`il2_rest.models.DocumentsTransactionModel`: Transaction identifier and limits. Example: >>> node = RestNode(cert_file=...
Get the ongoing status of a transaction.
[ "Get", "the", "ongoing", "status", "of", "a", "transaction", "." ]
def documents_transaction_status(self, transaction_id) : return DocumentsTransactionModel.from_json(self.__rest._get(f"/documents/transaction/{transaction_id}"))
[ "def", "documents_transaction_status", "(", "self", ",", "transaction_id", ")", ":", "return", "DocumentsTransactionModel", ".", "from_json", "(", "self", ".", "__rest", ".", "_get", "(", "f\"/documents/transaction/{transaction_id}\"", ")", ")" ]
Get the ongoing status of a transaction.
[ "Get", "the", "ongoing", "status", "of", "a", "transaction", "." ]
[ "\"\"\"\n Get the ongoing status of a transaction.\n\n Args:\n transaction_id (:obj:`str`): Id of the transaction.\n \n Returns:\n :obj:`il2_rest.models.DocumentsTransactionModel`: Transaction identifier and limits.\n \n Example:\n >>> node ...
[ { "param": "self", "type": null }, { "param": "transaction_id", "type": null } ]
{ "returns": [ { "docstring": ":obj:`il2_rest.models.DocumentsTransactionModel`: Transaction identifier and limits.", "docstring_tokens": [ ":", "obj", ":", "`", "il2_rest", ".", "models", ".", "DocumentsTransactionModel", ...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
documents_transaction_metadata
<not_specific>
def documents_transaction_metadata(self, locator): """ Retrieve the metadata for the set of documents from chain. Args: locator (:obj:`str`): A Documents Storage Locator. Returns: :obj:`il2_rest.models.DocumentsMetadataModel`: Metadata associated to a Mu...
Retrieve the metadata for the set of documents from chain. Args: locator (:obj:`str`): A Documents Storage Locator. Returns: :obj:`il2_rest.models.DocumentsMetadataModel`: Metadata associated to a Multi-Document Storage Locator Example: ...
Retrieve the metadata for the set of documents from chain.
[ "Retrieve", "the", "metadata", "for", "the", "set", "of", "documents", "from", "chain", "." ]
def documents_transaction_metadata(self, locator): return DocumentsMetadataModel.from_json(self.__rest._get(f"/documents/{locator}/metadata"))
[ "def", "documents_transaction_metadata", "(", "self", ",", "locator", ")", ":", "return", "DocumentsMetadataModel", ".", "from_json", "(", "self", ".", "__rest", ".", "_get", "(", "f\"/documents/{locator}/metadata\"", ")", ")" ]
Retrieve the metadata for the set of documents from chain.
[ "Retrieve", "the", "metadata", "for", "the", "set", "of", "documents", "from", "chain", "." ]
[ "\"\"\"\n Retrieve the metadata for the set of documents from chain.\n\n Args:\n locator (:obj:`str`): A Documents Storage Locator.\n \n Returns:\n :obj:`il2_rest.models.DocumentsMetadataModel`: Metadata associated to a Multi-Document Storage Locator\n \n ...
[ { "param": "self", "type": null }, { "param": "locator", "type": null } ]
{ "returns": [ { "docstring": ":obj:`il2_rest.models.DocumentsMetadataModel`: Metadata associated to a Multi-Document Storage Locator", "docstring_tokens": [ ":", "obj", ":", "`", "il2_rest", ".", "models", ".", "DocumentsMetadata...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
download_single_document_at
<not_specific>
def download_single_document_at(self, locator, index, dst_path='./') : """ Download document by position from the set of documents to a folder (default: current folder). Args: locator (:obj:`str`): A Documents Storage Locator. index (:obj:`int`): Index of the file. ...
Download document by position from the set of documents to a folder (default: current folder). Args: locator (:obj:`str`): A Documents Storage Locator. index (:obj:`int`): Index of the file. dst_path (:obj:`str`): Download the file to this folder. Example: ...
Download document by position from the set of documents to a folder (default: current folder).
[ "Download", "document", "by", "position", "from", "the", "set", "of", "documents", "to", "a", "folder", "(", "default", ":", "current", "folder", ")", "." ]
def download_single_document_at(self, locator, index, dst_path='./') : self.__rest._download_file(f"/documents/{locator}/{index}", dst_path=dst_path) return
[ "def", "download_single_document_at", "(", "self", ",", "locator", ",", "index", ",", "dst_path", "=", "'./'", ")", ":", "self", ".", "__rest", ".", "_download_file", "(", "f\"/documents/{locator}/{index}\"", ",", "dst_path", "=", "dst_path", ")", "return" ]
Download document by position from the set of documents to a folder (default: current folder).
[ "Download", "document", "by", "position", "from", "the", "set", "of", "documents", "to", "a", "folder", "(", "default", ":", "current", "folder", ")", "." ]
[ "\"\"\"\n Download document by position from the set of documents to a folder (default: current folder).\n\n Args:\n locator (:obj:`str`): A Documents Storage Locator.\n index (:obj:`int`): Index of the file.\n dst_path (:obj:`str`): Download the file to this folder.\n...
[ { "param": "self", "type": null }, { "param": "locator", "type": null }, { "param": "index", "type": null }, { "param": "dst_path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "locator", "type": null, "docstring": null, "docstring_tokens"...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
download_documents_as_zip
<not_specific>
def download_documents_as_zip(self, locator, dst_path='./') : """ Download a compressed file with all documents to a folder (default: current folder). Args: locator (:obj:`str`): A Documents Storage Locator. dst_path (:obj:`str`): Download the file to this folder. ...
Download a compressed file with all documents to a folder (default: current folder). Args: locator (:obj:`str`): A Documents Storage Locator. dst_path (:obj:`str`): Download the file to this folder. Example: >>> node = RestNode(cert_file='documenter.pfx', c...
Download a compressed file with all documents to a folder (default: current folder).
[ "Download", "a", "compressed", "file", "with", "all", "documents", "to", "a", "folder", "(", "default", ":", "current", "folder", ")", "." ]
def download_documents_as_zip(self, locator, dst_path='./') : self.__rest._download_file(f"/documents/{locator}/zip", dst_path=dst_path) return
[ "def", "download_documents_as_zip", "(", "self", ",", "locator", ",", "dst_path", "=", "'./'", ")", ":", "self", ".", "__rest", ".", "_download_file", "(", "f\"/documents/{locator}/zip\"", ",", "dst_path", "=", "dst_path", ")", "return" ]
Download a compressed file with all documents to a folder (default: current folder).
[ "Download", "a", "compressed", "file", "with", "all", "documents", "to", "a", "folder", "(", "default", ":", "current", "folder", ")", "." ]
[ "\"\"\"\n Download a compressed file with all documents to a folder (default: current folder).\n\n Args:\n locator (:obj:`str`): A Documents Storage Locator.\n dst_path (:obj:`str`): Download the file to this folder.\n\n Example:\n >>> node = RestNode(cert_file=...
[ { "param": "self", "type": null }, { "param": "locator", "type": null }, { "param": "dst_path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "locator", "type": null, "docstring": null, "docstring_tokens"...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
documents_begin_transaction
<not_specific>
def documents_begin_transaction(self, comment=None, compression=None, generatePublicDirectory=None, iterations=None, encryption=None, password=None, model=None) : """ Begin a transaction to store a set of documents. May rollback on timeout or errors. Args: comment (:obj:`str...
Begin a transaction to store a set of documents. May rollback on timeout or errors. Args: comment (:obj:`str`): Any additional information about the set of documents to be stored. compression (:obj:`il2_rest.enumerations.DocumentsCompression`): Compression algorithm. ...
Begin a transaction to store a set of documents. May rollback on timeout or errors.
[ "Begin", "a", "transaction", "to", "store", "a", "set", "of", "documents", ".", "May", "rollback", "on", "timeout", "or", "errors", "." ]
def documents_begin_transaction(self, comment=None, compression=None, generatePublicDirectory=None, iterations=None, encryption=None, password=None, model=None) : if model : if model.chain != self.id : raise TypeError(f"self.id == '{self.id}' does not match model.chain == '{model.cha...
[ "def", "documents_begin_transaction", "(", "self", ",", "comment", "=", "None", ",", "compression", "=", "None", ",", "generatePublicDirectory", "=", "None", ",", "iterations", "=", "None", ",", "encryption", "=", "None", ",", "password", "=", "None", ",", "...
Begin a transaction to store a set of documents.
[ "Begin", "a", "transaction", "to", "store", "a", "set", "of", "documents", "." ]
[ "\"\"\"\n Begin a transaction to store a set of documents. May rollback on timeout or errors.\n \n Args:\n comment (:obj:`str`): Any additional information about the set of documents to be stored.\n compression (:obj:`il2_rest.enumerations.DocumentsCompression`): Compressi...
[ { "param": "self", "type": null }, { "param": "comment", "type": null }, { "param": "compression", "type": null }, { "param": "generatePublicDirectory", "type": null }, { "param": "iterations", "type": null }, { "param": "encryption", "type": null ...
{ "returns": [ { "docstring": ":obj:`il2_rest.models.DocumentsTransactionModel`: Started transaction identifier and limits.", "docstring_tokens": [ ":", "obj", ":", "`", "il2_rest", ".", "models", ".", "DocumentsTransactionModel",...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
documents_transaction_add_item
<not_specific>
def documents_transaction_add_item(self, transaction_id, name, filepath, content_type=None, comment=None) : """ Adds another document to a pending transaction of multi-documents. Args: transaction_id (:obj:`str`): Id of the ongoing transaction. name (:obj:`str`): File na...
Adds another document to a pending transaction of multi-documents. Args: transaction_id (:obj:`str`): Id of the ongoing transaction. name (:obj:`str`): File name. filepath (:obj:`str`): Path to the file to upload. content_type (:obj:`str`, optional): Fil...
Adds another document to a pending transaction of multi-documents.
[ "Adds", "another", "document", "to", "a", "pending", "transaction", "of", "multi", "-", "documents", "." ]
def documents_transaction_add_item(self, transaction_id, name, filepath, content_type=None, comment=None) : query = f"/documents/transaction/{transaction_id}?name={name}" if comment : query += f"&comment={comment}" if not content_type : content_type = mimetypes.MimeTypes(...
[ "def", "documents_transaction_add_item", "(", "self", ",", "transaction_id", ",", "name", ",", "filepath", ",", "content_type", "=", "None", ",", "comment", "=", "None", ")", ":", "query", "=", "f\"/documents/transaction/{transaction_id}?name={name}\"", "if", "comment...
Adds another document to a pending transaction of multi-documents.
[ "Adds", "another", "document", "to", "a", "pending", "transaction", "of", "multi", "-", "documents", "." ]
[ "\"\"\"\n Adds another document to a pending transaction of multi-documents.\n\n Args:\n transaction_id (:obj:`str`): Id of the ongoing transaction.\n name (:obj:`str`): File name.\n filepath (:obj:`str`): Path to the file to upload.\n content_type (:obj:`st...
[ { "param": "self", "type": null }, { "param": "transaction_id", "type": null }, { "param": "name", "type": null }, { "param": "filepath", "type": null }, { "param": "content_type", "type": null }, { "param": "comment", "type": null } ]
{ "returns": [ { "docstring": ":obj:`bool`: True if success", "docstring_tokens": [ ":", "obj", ":", "`", "bool", "`", ":", "True", "if", "success" ], "type": null } ], "raises": [], "params": [ {...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
documents_transaction_commit
<not_specific>
def documents_transaction_commit(self, transaction_id) : """ Store set of uploaded documents. *Note:* Rementer to save the locator after commiting. Args: transaction_id (:obj:`str`): Id of the ongoing transaction. Returns: :obj:`str`: Documents ...
Store set of uploaded documents. *Note:* Rementer to save the locator after commiting. Args: transaction_id (:obj:`str`): Id of the ongoing transaction. Returns: :obj:`str`: Documents storage locator. Example: >>> node = RestNode(c...
Store set of uploaded documents. Note:* Rementer to save the locator after commiting.
[ "Store", "set", "of", "uploaded", "documents", ".", "Note", ":", "*", "Rementer", "to", "save", "the", "locator", "after", "commiting", "." ]
def documents_transaction_commit(self, transaction_id) : resp = self.__rest._post(f"/documents/transaction/{transaction_id}/commit", None) return resp
[ "def", "documents_transaction_commit", "(", "self", ",", "transaction_id", ")", ":", "resp", "=", "self", ".", "__rest", ".", "_post", "(", "f\"/documents/transaction/{transaction_id}/commit\"", ",", "None", ")", "return", "resp" ]
Store set of uploaded documents.
[ "Store", "set", "of", "uploaded", "documents", "." ]
[ "\"\"\"\n Store set of uploaded documents.\n\n *Note:* Rementer to save the locator after commiting.\n\n Args:\n transaction_id (:obj:`str`): Id of the ongoing transaction.\n \n Returns:\n :obj:`str`: Documents storage locator.\n\n Example:\n ...
[ { "param": "self", "type": null }, { "param": "transaction_id", "type": null } ]
{ "returns": [ { "docstring": ":obj:`str`: Documents storage locator.", "docstring_tokens": [ ":", "obj", ":", "`", "str", "`", ":", "Documents", "storage", "locator", "." ], "type": null } ], "...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
add_mirrors_of
<not_specific>
def add_mirrors_of(self, new_mirrors) : """ Add new mirrors in this node. Args: new_mirrors (:obj:`list` of :obj:`str`): List of chain ids you want to mirror. Returns: :obj:`list` of :obj:`il2_rest.models.ChainIdModel`: List of the chain information. ...
Add new mirrors in this node. Args: new_mirrors (:obj:`list` of :obj:`str`): List of chain ids you want to mirror. Returns: :obj:`list` of :obj:`il2_rest.models.ChainIdModel`: List of the chain information.
Add new mirrors in this node.
[ "Add", "new", "mirrors", "in", "this", "node", "." ]
def add_mirrors_of(self, new_mirrors) : json_data = self._post("/mirrors", new_mirrors) return [ChainIdModel.from_json(item) for item in json_data]
[ "def", "add_mirrors_of", "(", "self", ",", "new_mirrors", ")", ":", "json_data", "=", "self", ".", "_post", "(", "\"/mirrors\"", ",", "new_mirrors", ")", "return", "[", "ChainIdModel", ".", "from_json", "(", "item", ")", "for", "item", "in", "json_data", "...
Add new mirrors in this node.
[ "Add", "new", "mirrors", "in", "this", "node", "." ]
[ "\"\"\"\n Add new mirrors in this node.\n \n Args:\n new_mirrors (:obj:`list` of :obj:`str`): List of chain ids you want to mirror.\n\n Returns:\n :obj:`list` of :obj:`il2_rest.models.ChainIdModel`: List of the chain information.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "new_mirrors", "type": null } ]
{ "returns": [ { "docstring": ":obj:`list` of :obj:`il2_rest.models.ChainIdModel`: List of the chain information.", "docstring_tokens": [ ":", "obj", ":", "`", "list", "`", "of", ":", "obj", ":", "`", "il2_...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
chain_by_id
<not_specific>
def chain_by_id(self, chain_id) : """ Get a chain by id. Args: chain_id (:obj:`str`): Chain id. Returns: :obj:`RestChain`: Chain instance with the corresponding id. Example: >>> node = RestNode(cert_file='documenter.pfx', cert_pass='pass...
Get a chain by id. Args: chain_id (:obj:`str`): Chain id. Returns: :obj:`RestChain`: Chain instance with the corresponding id. Example: >>> node = RestNode(cert_file='documenter.pfx', cert_pass='password', port=32020) >>> chain = no...
Get a chain by id.
[ "Get", "a", "chain", "by", "id", "." ]
def chain_by_id(self, chain_id) : json_data = self._get(f'/chain/{chain_id}') return RestChain(self, ChainIdModel.from_json(json_data))
[ "def", "chain_by_id", "(", "self", ",", "chain_id", ")", ":", "json_data", "=", "self", ".", "_get", "(", "f'/chain/{chain_id}'", ")", "return", "RestChain", "(", "self", ",", "ChainIdModel", ".", "from_json", "(", "json_data", ")", ")" ]
Get a chain by id.
[ "Get", "a", "chain", "by", "id", "." ]
[ "\"\"\"\n Get a chain by id.\n \n Args:\n chain_id (:obj:`str`): Chain id.\n\n Returns:\n :obj:`RestChain`: Chain instance with the corresponding id.\n\n Example:\n >>> node = RestNode(cert_file='documenter.pfx', cert_pass='password', port=32020)\n ...
[ { "param": "self", "type": null }, { "param": "chain_id", "type": null } ]
{ "returns": [ { "docstring": ":obj:`RestChain`: Chain instance with the corresponding id.", "docstring_tokens": [ ":", "obj", ":", "`", "RestChain", "`", ":", "Chain", "instance", "with", "the", "correspon...
cf4c4bdf6bfb910ac8b9d576de58051a88aec2b8
interlockledger/interlockledger-rest-client-python
il2_rest/client.py
[ "BSD-3-Clause" ]
Python
interlocks_of
<not_specific>
def interlocks_of(self, chain) : """ Get the list of interlocking records pointing to a target chain instance. Args: chain (:obj:`str`): Chain id. Returns: :obj:`list` of :obj:`il2_rest.models.InterlockingRecordModel`: List of interlockings. Example...
Get the list of interlocking records pointing to a target chain instance. Args: chain (:obj:`str`): Chain id. Returns: :obj:`list` of :obj:`il2_rest.models.InterlockingRecordModel`: List of interlockings. Example: >>> node = RestNode(cert_file=...
Get the list of interlocking records pointing to a target chain instance.
[ "Get", "the", "list", "of", "interlocking", "records", "pointing", "to", "a", "target", "chain", "instance", "." ]
def interlocks_of(self, chain) : json_data = self._get(f"/interlockings/{chain}") return [InterlockingRecordModel.from_json(item) for item in json_data]
[ "def", "interlocks_of", "(", "self", ",", "chain", ")", ":", "json_data", "=", "self", ".", "_get", "(", "f\"/interlockings/{chain}\"", ")", "return", "[", "InterlockingRecordModel", ".", "from_json", "(", "item", ")", "for", "item", "in", "json_data", "]" ]
Get the list of interlocking records pointing to a target chain instance.
[ "Get", "the", "list", "of", "interlocking", "records", "pointing", "to", "a", "target", "chain", "instance", "." ]
[ "\"\"\"\n Get the list of interlocking records pointing to a target chain instance.\n \n Args:\n chain (:obj:`str`): Chain id.\n\n Returns:\n :obj:`list` of :obj:`il2_rest.models.InterlockingRecordModel`: List of interlockings.\n\n Example:\n >>> node ...
[ { "param": "self", "type": null }, { "param": "chain", "type": null } ]
{ "returns": [ { "docstring": ":obj:`list` of :obj:`il2_rest.models.InterlockingRecordModel`: List of interlockings.", "docstring_tokens": [ ":", "obj", ":", "`", "list", "`", "of", ":", "obj", ":", "`", "i...
236e8c52a396d27af3c6ba06a9575b58c05a436b
jimmysong/python-bitcoinlib
bitcoin/core/script.py
[ "MIT" ]
Python
RawSignatureHash
<not_specific>
def RawSignatureHash(script, txTo, inIdx, hashtype): """Consensus-correct SignatureHash Returns (hash, err) to precisely match the consensus-critical behavior of the SIGHASH_SINGLE bug. (inIdx is *not* checked for validity) If you're just writing wallet software you probably want SignatureHash() i...
Consensus-correct SignatureHash Returns (hash, err) to precisely match the consensus-critical behavior of the SIGHASH_SINGLE bug. (inIdx is *not* checked for validity) If you're just writing wallet software you probably want SignatureHash() instead.
Consensus-correct SignatureHash Returns (hash, err) to precisely match the consensus-critical behavior of the SIGHASH_SINGLE bug. (inIdx is *not* checked for validity) If you're just writing wallet software you probably want SignatureHash() instead.
[ "Consensus", "-", "correct", "SignatureHash", "Returns", "(", "hash", "err", ")", "to", "precisely", "match", "the", "consensus", "-", "critical", "behavior", "of", "the", "SIGHASH_SINGLE", "bug", ".", "(", "inIdx", "is", "*", "not", "*", "checked", "for", ...
def RawSignatureHash(script, txTo, inIdx, hashtype): HASH_ONE = b'\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' if inIdx >= len(txTo.vin): return (HASH_ONE, "inIdx %d out of range (%d)" % (inIdx, len(txTo.vin))) txtm...
[ "def", "RawSignatureHash", "(", "script", ",", "txTo", ",", "inIdx", ",", "hashtype", ")", ":", "HASH_ONE", "=", "b'\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'", "if", ...
Consensus-correct SignatureHash Returns (hash, err) to precisely match the consensus-critical behavior of the SIGHASH_SINGLE bug.
[ "Consensus", "-", "correct", "SignatureHash", "Returns", "(", "hash", "err", ")", "to", "precisely", "match", "the", "consensus", "-", "critical", "behavior", "of", "the", "SIGHASH_SINGLE", "bug", "." ]
[ "\"\"\"Consensus-correct SignatureHash\n\n Returns (hash, err) to precisely match the consensus-critical behavior of\n the SIGHASH_SINGLE bug. (inIdx is *not* checked for validity)\n\n If you're just writing wallet software you probably want SignatureHash()\n instead.\n \"\"\"" ]
[ { "param": "script", "type": null }, { "param": "txTo", "type": null }, { "param": "inIdx", "type": null }, { "param": "hashtype", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "script", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "txTo", "type": null, "docstring": null, "docstring_tokens":...
5534fe56da715a815b6b121c12da62c010dc48fb
metocean/cf-json
cfjson/xrdataset.py
[ "Apache-2.0" ]
Python
to_dict
<not_specific>
def to_dict(self,mapping): """ Dumps the dataset as an ordered dictionary following the same conventions as ncdump. """ res=OrderedDict() try: res['dimensions']=OrderedDict() for dim in self._obj.dims: if self._obj.dims[dim]>1: ...
Dumps the dataset as an ordered dictionary following the same conventions as ncdump.
Dumps the dataset as an ordered dictionary following the same conventions as ncdump.
[ "Dumps", "the", "dataset", "as", "an", "ordered", "dictionary", "following", "the", "same", "conventions", "as", "ncdump", "." ]
def to_dict(self,mapping): res=OrderedDict() try: res['dimensions']=OrderedDict() for dim in self._obj.dims: if self._obj.dims[dim]>1: res['dimensions'][dim]=self._obj.dims[dim] except: print('Failed to export dimensions') ...
[ "def", "to_dict", "(", "self", ",", "mapping", ")", ":", "res", "=", "OrderedDict", "(", ")", "try", ":", "res", "[", "'dimensions'", "]", "=", "OrderedDict", "(", ")", "for", "dim", "in", "self", ".", "_obj", ".", "dims", ":", "if", "self", ".", ...
Dumps the dataset as an ordered dictionary following the same conventions as ncdump.
[ "Dumps", "the", "dataset", "as", "an", "ordered", "dictionary", "following", "the", "same", "conventions", "as", "ncdump", "." ]
[ "\"\"\"\n Dumps the dataset as an ordered dictionary following the same conventions as ncdump.\n \"\"\"", "#Put axis variables first", "#This is a UDS artefact" ]
[ { "param": "self", "type": null }, { "param": "mapping", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "mapping", "type": null, "docstring": null, "docstring_tokens"...
5534fe56da715a815b6b121c12da62c010dc48fb
metocean/cf-json
cfjson/xrdataset.py
[ "Apache-2.0" ]
Python
json_dumps
<not_specific>
def json_dumps(self, indent=2, separators=None, mapping={}, attributes={}): """ Dumps a JSON representation of the Dataset following the same conventions as ncdump. Assumes the Dataset is CF complient. """ dico=self.to_dict(mapping) try: dico['attributes'].upd...
Dumps a JSON representation of the Dataset following the same conventions as ncdump. Assumes the Dataset is CF complient.
Dumps a JSON representation of the Dataset following the same conventions as ncdump. Assumes the Dataset is CF complient.
[ "Dumps", "a", "JSON", "representation", "of", "the", "Dataset", "following", "the", "same", "conventions", "as", "ncdump", ".", "Assumes", "the", "Dataset", "is", "CF", "complient", "." ]
def json_dumps(self, indent=2, separators=None, mapping={}, attributes={}): dico=self.to_dict(mapping) try: dico['attributes'].update(attributes) except: print('Failed to set global attributes %s'%(attributes)) return json.dumps(dico, indent=indent, separators=sep...
[ "def", "json_dumps", "(", "self", ",", "indent", "=", "2", ",", "separators", "=", "None", ",", "mapping", "=", "{", "}", ",", "attributes", "=", "{", "}", ")", ":", "dico", "=", "self", ".", "to_dict", "(", "mapping", ")", "try", ":", "dico", "[...
Dumps a JSON representation of the Dataset following the same conventions as ncdump.
[ "Dumps", "a", "JSON", "representation", "of", "the", "Dataset", "following", "the", "same", "conventions", "as", "ncdump", "." ]
[ "\"\"\"\n Dumps a JSON representation of the Dataset following the same conventions as ncdump.\n Assumes the Dataset is CF complient.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "indent", "type": null }, { "param": "separators", "type": null }, { "param": "mapping", "type": null }, { "param": "attributes", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "indent", "type": null, "docstring": null, "docstring_tokens":...
5534fe56da715a815b6b121c12da62c010dc48fb
metocean/cf-json
cfjson/xrdataset.py
[ "Apache-2.0" ]
Python
from_json
null
def from_json(self, js): """Convert CF-JSON string or dictionary to xarray Dataset Example: import xarray as xr from cfjson import xrdataset cfjson_string = '{"dimensions": {"time": 1}, "variables": {"x": {"shape": ["time"], "data": [1], "attributes": {}}}}' dataset = xr....
Convert CF-JSON string or dictionary to xarray Dataset Example: import xarray as xr from cfjson import xrdataset cfjson_string = '{"dimensions": {"time": 1}, "variables": {"x": {"shape": ["time"], "data": [1], "attributes": {}}}}' dataset = xr.Dataset() dataset.cfjson.fro...
Convert CF-JSON string or dictionary to xarray Dataset
[ "Convert", "CF", "-", "JSON", "string", "or", "dictionary", "to", "xarray", "Dataset" ]
def from_json(self, js): if isinstance(js, six.string_types): try: dico = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(js) except: print('Could not decode JSON string') raise else: dico = js if 'attribu...
[ "def", "from_json", "(", "self", ",", "js", ")", ":", "if", "isinstance", "(", "js", ",", "six", ".", "string_types", ")", ":", "try", ":", "dico", "=", "json", ".", "JSONDecoder", "(", "object_pairs_hook", "=", "OrderedDict", ")", ".", "decode", "(", ...
Convert CF-JSON string or dictionary to xarray Dataset
[ "Convert", "CF", "-", "JSON", "string", "or", "dictionary", "to", "xarray", "Dataset" ]
[ "\"\"\"Convert CF-JSON string or dictionary to xarray Dataset\n Example:\n import xarray as xr\n from cfjson import xrdataset\n cfjson_string = '{\"dimensions\": {\"time\": 1}, \"variables\": {\"x\": {\"shape\": [\"time\"], \"data\": [1], \"attributes\": {}}}}'\n dataset = xr.Data...
[ { "param": "self", "type": null }, { "param": "js", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "js", "type": null, "docstring": null, "docstring_tokens": [],...
1a2c68082a40ca43883504d65b15f095cf05a14c
AllenTiTaiWang/NLP_words
words.py
[ "Apache-2.0" ]
Python
most_common
List[Tuple[Text, int]]
def most_common(word_pos_path: Text, word_regex=".*", pos_regex=".*", n=10) -> List[Tuple[Text, int]]: """Finds the most common words and/or parts of speech in a file. :param word_pos_path: The path of a file containing part-of-speech tagged text. The file sh...
Finds the most common words and/or parts of speech in a file. :param word_pos_path: The path of a file containing part-of-speech tagged text. The file should be formatted as a sequence of tokens separated by whitespace. Each token should be a word and a part-of-speech tag, separated by a slash. For exa...
Finds the most common words and/or parts of speech in a file.
[ "Finds", "the", "most", "common", "words", "and", "/", "or", "parts", "of", "speech", "in", "a", "file", "." ]
def most_common(word_pos_path: Text, word_regex=".*", pos_regex=".*", n=10) -> List[Tuple[Text, int]]: with open(word_pos_path) as f: data = f.read() line = data.split() if pos_regex is not None and word_regex is None: line = [item....
[ "def", "most_common", "(", "word_pos_path", ":", "Text", ",", "word_regex", "=", "\".*\"", ",", "pos_regex", "=", "\".*\"", ",", "n", "=", "10", ")", "->", "List", "[", "Tuple", "[", "Text", ",", "int", "]", "]", ":", "with", "open", "(", "word_pos_p...
Finds the most common words and/or parts of speech in a file.
[ "Finds", "the", "most", "common", "words", "and", "/", "or", "parts", "of", "speech", "in", "a", "file", "." ]
[ "\"\"\"Finds the most common words and/or parts of speech in a file.\n\n :param word_pos_path: The path of a file containing part-of-speech tagged\n text. The file should be formatted as a sequence of tokens separated by\n whitespace. Each token should be a word and a part-of-speech tag, separated\n by ...
[ { "param": "word_pos_path", "type": "Text" }, { "param": "word_regex", "type": null }, { "param": "pos_regex", "type": null }, { "param": "n", "type": null } ]
{ "returns": [ { "docstring": "A list of (token, count) tuples for the most frequent words and/or\nparts-of-speech in the file. Note that, depending on word_regex and\npos_regex (as described above), the returned tokens will contain either\nwords, part-of-speech tags, or both.", "docstring_tokens": [ ...
1a2c68082a40ca43883504d65b15f095cf05a14c
AllenTiTaiWang/NLP_words
words.py
[ "Apache-2.0" ]
Python
most_similar
List[Tuple[Text, int]]
def most_similar(self, word: Text, n=10) -> List[Tuple[Text, int]]: """Finds the most similar words to a query word. Similarity is measured by cosine similarity (https://en.wikipedia.org/wiki/Cosine_similarity) over the word vectors. :param word: The query word. :param n: The nu...
Finds the most similar words to a query word. Similarity is measured by cosine similarity (https://en.wikipedia.org/wiki/Cosine_similarity) over the word vectors. :param word: The query word. :param n: The number of most similar words to return. :return: The n most similar words...
Finds the most similar words to a query word. Similarity is measured by cosine similarity over the word vectors.
[ "Finds", "the", "most", "similar", "words", "to", "a", "query", "word", ".", "Similarity", "is", "measured", "by", "cosine", "similarity", "over", "the", "word", "vectors", "." ]
def most_similar(self, word: Text, n=10) -> List[Tuple[Text, int]]: word_vec = self.dic[word] cs_list = [] for key, value in self.dic.items(): cs = cosine_similarity(word_vec.reshape(1, -1), value.reshape(1, -1)) cs_list.append((key, float(cs))) result = heapq.nla...
[ "def", "most_similar", "(", "self", ",", "word", ":", "Text", ",", "n", "=", "10", ")", "->", "List", "[", "Tuple", "[", "Text", ",", "int", "]", "]", ":", "word_vec", "=", "self", ".", "dic", "[", "word", "]", "cs_list", "=", "[", "]", "for", ...
Finds the most similar words to a query word.
[ "Finds", "the", "most", "similar", "words", "to", "a", "query", "word", "." ]
[ "\"\"\"Finds the most similar words to a query word. Similarity is measured\n by cosine similarity (https://en.wikipedia.org/wiki/Cosine_similarity)\n over the word vectors.\n\n :param word: The query word.\n :param n: The number of most similar words to return.\n :return: The n m...
[ { "param": "self", "type": null }, { "param": "word", "type": "Text" }, { "param": "n", "type": null } ]
{ "returns": [ { "docstring": "The n most similar words to the query word.", "docstring_tokens": [ "The", "n", "most", "similar", "words", "to", "the", "query", "word", "." ], "type": null } ], "raises"...
c447c6743079a4c8596471dacd32b0b06078a9ff
csc-training/geocomputing
machineLearning/05_cnn_keras/model_solaris.py
[ "CC-BY-4.0" ]
Python
cosmiq_sn4_baseline
<not_specific>
def cosmiq_sn4_baseline(input_shape=(512, 512, 3), base_depth=64, no_of_classes=2): """Keras implementation of untrained TernausNet model architecture. Arguments: ---------- input_shape (3-tuple): a tuple defining the shape of the input image. base_depth (int): the base convolution filter depth for...
Keras implementation of untrained TernausNet model architecture. Arguments: ---------- input_shape (3-tuple): a tuple defining the shape of the input image. base_depth (int): the base convolution filter depth for the first layer of the model. Must be divisible by two, as the final layer uses ...
Keras implementation of untrained TernausNet model architecture. Arguments. input_shape (3-tuple): a tuple defining the shape of the input image. base_depth (int): the base convolution filter depth for the first layer of the model. Must be divisible by two, as the final layer uses base_depth/2 filters. The default val...
[ "Keras", "implementation", "of", "untrained", "TernausNet", "model", "architecture", ".", "Arguments", ".", "input_shape", "(", "3", "-", "tuple", ")", ":", "a", "tuple", "defining", "the", "shape", "of", "the", "input", "image", ".", "base_depth", "(", "int...
def cosmiq_sn4_baseline(input_shape=(512, 512, 3), base_depth=64, no_of_classes=2): inputs = Input(input_shape) conv1 = Conv2D(base_depth, 3, activation='relu', padding='same')(inputs) pool1 = MaxPooling2D(pool_size=(2, 2))(conv1) conv2_1 = Conv2D(base_depth*2, 3, activation='relu', ...
[ "def", "cosmiq_sn4_baseline", "(", "input_shape", "=", "(", "512", ",", "512", ",", "3", ")", ",", "base_depth", "=", "64", ",", "no_of_classes", "=", "2", ")", ":", "inputs", "=", "Input", "(", "input_shape", ")", "conv1", "=", "Conv2D", "(", "base_de...
Keras implementation of untrained TernausNet model architecture.
[ "Keras", "implementation", "of", "untrained", "TernausNet", "model", "architecture", "." ]
[ "\"\"\"Keras implementation of untrained TernausNet model architecture.\n\n Arguments:\n ----------\n input_shape (3-tuple): a tuple defining the shape of the input image.\n base_depth (int): the base convolution filter depth for the first layer\n of the model. Must be divisible by two, as the fi...
[ { "param": "input_shape", "type": null }, { "param": "base_depth", "type": null }, { "param": "no_of_classes", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "input_shape", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "base_depth", "type": null, "docstring": null, "docstri...
fc2674f145bf3086d7887b25644052fc8798a2ff
maartenbreddels/conf_site
conf_site/proposals/models.py
[ "MIT" ]
Python
_get_cached_vote_count
<not_specific>
def _get_cached_vote_count(self, cache_key, vote_score): """Helper method to retrieve cached vote counts.""" cached_vote_count = cache.get(cache_key, False) if cached_vote_count is not False: return cached_vote_count vote_count = ProposalVote.objects.filter( propo...
Helper method to retrieve cached vote counts.
Helper method to retrieve cached vote counts.
[ "Helper", "method", "to", "retrieve", "cached", "vote", "counts", "." ]
def _get_cached_vote_count(self, cache_key, vote_score): cached_vote_count = cache.get(cache_key, False) if cached_vote_count is not False: return cached_vote_count vote_count = ProposalVote.objects.filter( proposal=self, score=vote_score ).count() cache.s...
[ "def", "_get_cached_vote_count", "(", "self", ",", "cache_key", ",", "vote_score", ")", ":", "cached_vote_count", "=", "cache", ".", "get", "(", "cache_key", ",", "False", ")", "if", "cached_vote_count", "is", "not", "False", ":", "return", "cached_vote_count", ...
Helper method to retrieve cached vote counts.
[ "Helper", "method", "to", "retrieve", "cached", "vote", "counts", "." ]
[ "\"\"\"Helper method to retrieve cached vote counts.\"\"\"", "# We can use a longer timeout because we update invididual", "# vote counts when ProposalVotes are created or modified." ]
[ { "param": "self", "type": null }, { "param": "cache_key", "type": null }, { "param": "vote_score", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "cache_key", "type": null, "docstring": null, "docstring_token...
fc2674f145bf3086d7887b25644052fc8798a2ff
maartenbreddels/conf_site
conf_site/proposals/models.py
[ "MIT" ]
Python
_refresh_feedback_count
<not_specific>
def _refresh_feedback_count(self): """Helper method to manually refresh a proposal's feedback count.""" cache_key = self._feedback_count_cache_key() feedback_count = self.review_feedback.count() cache.set(cache_key, feedback_count, settings.CACHE_TIMEOUT_LONG) return feedback_cou...
Helper method to manually refresh a proposal's feedback count.
Helper method to manually refresh a proposal's feedback count.
[ "Helper", "method", "to", "manually", "refresh", "a", "proposal", "'", "s", "feedback", "count", "." ]
def _refresh_feedback_count(self): cache_key = self._feedback_count_cache_key() feedback_count = self.review_feedback.count() cache.set(cache_key, feedback_count, settings.CACHE_TIMEOUT_LONG) return feedback_count
[ "def", "_refresh_feedback_count", "(", "self", ")", ":", "cache_key", "=", "self", ".", "_feedback_count_cache_key", "(", ")", "feedback_count", "=", "self", ".", "review_feedback", ".", "count", "(", ")", "cache", ".", "set", "(", "cache_key", ",", "feedback_...
Helper method to manually refresh a proposal's feedback count.
[ "Helper", "method", "to", "manually", "refresh", "a", "proposal", "'", "s", "feedback", "count", "." ]
[ "\"\"\"Helper method to manually refresh a proposal's feedback count.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fc2674f145bf3086d7887b25644052fc8798a2ff
maartenbreddels/conf_site
conf_site/proposals/models.py
[ "MIT" ]
Python
_refresh_vote_counts
null
def _refresh_vote_counts(self): """Helper method to manually refresh a proposal's vote counts.""" vote_count_dict = { "proposal_{}_plus_one".format(self.pk): ProposalVote.PLUS_ONE, "proposal_{}_plus_zero".format(self.pk): ProposalVote.PLUS_ZERO, "proposal_{}_minus_zer...
Helper method to manually refresh a proposal's vote counts.
Helper method to manually refresh a proposal's vote counts.
[ "Helper", "method", "to", "manually", "refresh", "a", "proposal", "'", "s", "vote", "counts", "." ]
def _refresh_vote_counts(self): vote_count_dict = { "proposal_{}_plus_one".format(self.pk): ProposalVote.PLUS_ONE, "proposal_{}_plus_zero".format(self.pk): ProposalVote.PLUS_ZERO, "proposal_{}_minus_zero".format(self.pk): ProposalVote.MINUS_ZERO, "proposal_{}_minu...
[ "def", "_refresh_vote_counts", "(", "self", ")", ":", "vote_count_dict", "=", "{", "\"proposal_{}_plus_one\"", ".", "format", "(", "self", ".", "pk", ")", ":", "ProposalVote", ".", "PLUS_ONE", ",", "\"proposal_{}_plus_zero\"", ".", "format", "(", "self", ".", ...
Helper method to manually refresh a proposal's vote counts.
[ "Helper", "method", "to", "manually", "refresh", "a", "proposal", "'", "s", "vote", "counts", "." ]
[ "\"\"\"Helper method to manually refresh a proposal's vote counts.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fc2674f145bf3086d7887b25644052fc8798a2ff
maartenbreddels/conf_site
conf_site/proposals/models.py
[ "MIT" ]
Python
feedback_count
<not_specific>
def feedback_count(self): """Helper method to retrieve feedback count.""" cache_key = self._feedback_count_cache_key() feedback_count = cache.get(cache_key, False) if feedback_count is not False: return feedback_count return self._refresh_feedback_count()
Helper method to retrieve feedback count.
Helper method to retrieve feedback count.
[ "Helper", "method", "to", "retrieve", "feedback", "count", "." ]
def feedback_count(self): cache_key = self._feedback_count_cache_key() feedback_count = cache.get(cache_key, False) if feedback_count is not False: return feedback_count return self._refresh_feedback_count()
[ "def", "feedback_count", "(", "self", ")", ":", "cache_key", "=", "self", ".", "_feedback_count_cache_key", "(", ")", "feedback_count", "=", "cache", ".", "get", "(", "cache_key", ",", "False", ")", "if", "feedback_count", "is", "not", "False", ":", "return"...
Helper method to retrieve feedback count.
[ "Helper", "method", "to", "retrieve", "feedback", "count", "." ]
[ "\"\"\"Helper method to retrieve feedback count.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fc2674f145bf3086d7887b25644052fc8798a2ff
maartenbreddels/conf_site
conf_site/proposals/models.py
[ "MIT" ]
Python
plus_one
<not_specific>
def plus_one(self): """Enumerate number of +1 reviews.""" return self._get_cached_vote_count( "proposal_{}_plus_one".format(self.pk), ProposalVote.PLUS_ONE )
Enumerate number of +1 reviews.
Enumerate number of +1 reviews.
[ "Enumerate", "number", "of", "+", "1", "reviews", "." ]
def plus_one(self): return self._get_cached_vote_count( "proposal_{}_plus_one".format(self.pk), ProposalVote.PLUS_ONE )
[ "def", "plus_one", "(", "self", ")", ":", "return", "self", ".", "_get_cached_vote_count", "(", "\"proposal_{}_plus_one\"", ".", "format", "(", "self", ".", "pk", ")", ",", "ProposalVote", ".", "PLUS_ONE", ")" ]
Enumerate number of +1 reviews.
[ "Enumerate", "number", "of", "+", "1", "reviews", "." ]
[ "\"\"\"Enumerate number of +1 reviews.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fc2674f145bf3086d7887b25644052fc8798a2ff
maartenbreddels/conf_site
conf_site/proposals/models.py
[ "MIT" ]
Python
plus_zero
<not_specific>
def plus_zero(self): """Enumerate number of +0 reviews.""" return self._get_cached_vote_count( "proposal_{}_plus_zero".format(self.pk), ProposalVote.PLUS_ZERO )
Enumerate number of +0 reviews.
Enumerate number of +0 reviews.
[ "Enumerate", "number", "of", "+", "0", "reviews", "." ]
def plus_zero(self): return self._get_cached_vote_count( "proposal_{}_plus_zero".format(self.pk), ProposalVote.PLUS_ZERO )
[ "def", "plus_zero", "(", "self", ")", ":", "return", "self", ".", "_get_cached_vote_count", "(", "\"proposal_{}_plus_zero\"", ".", "format", "(", "self", ".", "pk", ")", ",", "ProposalVote", ".", "PLUS_ZERO", ")" ]
Enumerate number of +0 reviews.
[ "Enumerate", "number", "of", "+", "0", "reviews", "." ]
[ "\"\"\"Enumerate number of +0 reviews.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fc2674f145bf3086d7887b25644052fc8798a2ff
maartenbreddels/conf_site
conf_site/proposals/models.py
[ "MIT" ]
Python
minus_zero
<not_specific>
def minus_zero(self): """Enumerate number of -0 reviews.""" return self._get_cached_vote_count( "proposal_{}_minus_zero".format(self.pk), ProposalVote.MINUS_ZERO, )
Enumerate number of -0 reviews.
Enumerate number of -0 reviews.
[ "Enumerate", "number", "of", "-", "0", "reviews", "." ]
def minus_zero(self): return self._get_cached_vote_count( "proposal_{}_minus_zero".format(self.pk), ProposalVote.MINUS_ZERO, )
[ "def", "minus_zero", "(", "self", ")", ":", "return", "self", ".", "_get_cached_vote_count", "(", "\"proposal_{}_minus_zero\"", ".", "format", "(", "self", ".", "pk", ")", ",", "ProposalVote", ".", "MINUS_ZERO", ",", ")" ]
Enumerate number of -0 reviews.
[ "Enumerate", "number", "of", "-", "0", "reviews", "." ]
[ "\"\"\"Enumerate number of -0 reviews.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fc2674f145bf3086d7887b25644052fc8798a2ff
maartenbreddels/conf_site
conf_site/proposals/models.py
[ "MIT" ]
Python
minus_one
<not_specific>
def minus_one(self): """Enumerate number of -1 reviews.""" return self._get_cached_vote_count( "proposal_{}_minus_one".format(self.pk), ProposalVote.MINUS_ONE )
Enumerate number of -1 reviews.
Enumerate number of -1 reviews.
[ "Enumerate", "number", "of", "-", "1", "reviews", "." ]
def minus_one(self): return self._get_cached_vote_count( "proposal_{}_minus_one".format(self.pk), ProposalVote.MINUS_ONE )
[ "def", "minus_one", "(", "self", ")", ":", "return", "self", ".", "_get_cached_vote_count", "(", "\"proposal_{}_minus_one\"", ".", "format", "(", "self", ".", "pk", ")", ",", "ProposalVote", ".", "MINUS_ONE", ")" ]
Enumerate number of -1 reviews.
[ "Enumerate", "number", "of", "-", "1", "reviews", "." ]
[ "\"\"\"Enumerate number of -1 reviews.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
3e81ca949bea080002056a527e50a40576c53ad9
maartenbreddels/conf_site
conf_site/proposals/views.py
[ "MIT" ]
Python
_write_submitter_row
null
def _write_submitter_row(self, submitter, proposal): """Utility method to write a row for an individual submitter.""" self.csv_writer.writerow( [ submitter.name, submitter.email, proposal.title, proposal.kind.name, ]...
Utility method to write a row for an individual submitter.
Utility method to write a row for an individual submitter.
[ "Utility", "method", "to", "write", "a", "row", "for", "an", "individual", "submitter", "." ]
def _write_submitter_row(self, submitter, proposal): self.csv_writer.writerow( [ submitter.name, submitter.email, proposal.title, proposal.kind.name, ] )
[ "def", "_write_submitter_row", "(", "self", ",", "submitter", ",", "proposal", ")", ":", "self", ".", "csv_writer", ".", "writerow", "(", "[", "submitter", ".", "name", ",", "submitter", ".", "email", ",", "proposal", ".", "title", ",", "proposal", ".", ...
Utility method to write a row for an individual submitter.
[ "Utility", "method", "to", "write", "a", "row", "for", "an", "individual", "submitter", "." ]
[ "\"\"\"Utility method to write a row for an individual submitter.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "submitter", "type": null }, { "param": "proposal", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "submitter", "type": null, "docstring": null, "docstring_token...
fa4ff82106a3326b015cb032f3743327590a5047
maartenbreddels/conf_site
conf_site/core/views.py
[ "MIT" ]
Python
csrf_failure
<not_specific>
def csrf_failure(request, reason=""): """ Custom view for users who encounter CSRF errors. https://docs.djangoproject.com/en/1.9/ref/settings/#csrf-failure-view When we upgrade to Django 1.10, this view can be removed. """ response = TemplateResponse( request=request, template="403_cs...
Custom view for users who encounter CSRF errors. https://docs.djangoproject.com/en/1.9/ref/settings/#csrf-failure-view When we upgrade to Django 1.10, this view can be removed.
Custom view for users who encounter CSRF errors. When we upgrade to Django 1.10, this view can be removed.
[ "Custom", "view", "for", "users", "who", "encounter", "CSRF", "errors", ".", "When", "we", "upgrade", "to", "Django", "1", ".", "10", "this", "view", "can", "be", "removed", "." ]
def csrf_failure(request, reason=""): response = TemplateResponse( request=request, template="403_csrf.html", status=403 ) return response
[ "def", "csrf_failure", "(", "request", ",", "reason", "=", "\"\"", ")", ":", "response", "=", "TemplateResponse", "(", "request", "=", "request", ",", "template", "=", "\"403_csrf.html\"", ",", "status", "=", "403", ")", "return", "response" ]
Custom view for users who encounter CSRF errors.
[ "Custom", "view", "for", "users", "who", "encounter", "CSRF", "errors", "." ]
[ "\"\"\"\n Custom view for users who encounter CSRF errors.\n\n https://docs.djangoproject.com/en/1.9/ref/settings/#csrf-failure-view\n\n When we upgrade to Django 1.10, this view can be removed.\n\n \"\"\"" ]
[ { "param": "request", "type": null }, { "param": "reason", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "request", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "reason", "type": null, "docstring": null, "docstring_token...
44b2a3ee5963f3d656682b61e74ca5f8de6af0f6
maartenbreddels/conf_site
conf_site/core/context_processors.py
[ "MIT" ]
Python
core_context
<not_specific>
def core_context(self): """Context processor for elements appearing on every page.""" context = {} context["google_analytics_id"] = settings.GOOGLE_ANALYTICS_PROPERTY_ID context["sentry_public_dsn"] = settings.SENTRY_PUBLIC_DSN return context
Context processor for elements appearing on every page.
Context processor for elements appearing on every page.
[ "Context", "processor", "for", "elements", "appearing", "on", "every", "page", "." ]
def core_context(self): context = {} context["google_analytics_id"] = settings.GOOGLE_ANALYTICS_PROPERTY_ID context["sentry_public_dsn"] = settings.SENTRY_PUBLIC_DSN return context
[ "def", "core_context", "(", "self", ")", ":", "context", "=", "{", "}", "context", "[", "\"google_analytics_id\"", "]", "=", "settings", ".", "GOOGLE_ANALYTICS_PROPERTY_ID", "context", "[", "\"sentry_public_dsn\"", "]", "=", "settings", ".", "SENTRY_PUBLIC_DSN", "...
Context processor for elements appearing on every page.
[ "Context", "processor", "for", "elements", "appearing", "on", "every", "page", "." ]
[ "\"\"\"Context processor for elements appearing on every page.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
62db17d8e754bd91bb28c9e58f411a54d2daf95b
maartenbreddels/conf_site
conf_site/cms/context_processors.py
[ "MIT" ]
Python
homepage_context
<not_specific>
def homepage_context(request): """ Add homepage information into context. Add certain homepage fields into the general context so that they are available from all pages, regardless of whether they were generated with Wagtail or Symposion. """ context = {} # Assume that the homepage is t...
Add homepage information into context. Add certain homepage fields into the general context so that they are available from all pages, regardless of whether they were generated with Wagtail or Symposion.
Add homepage information into context. Add certain homepage fields into the general context so that they are available from all pages, regardless of whether they were generated with Wagtail or Symposion.
[ "Add", "homepage", "information", "into", "context", ".", "Add", "certain", "homepage", "fields", "into", "the", "general", "context", "so", "that", "they", "are", "available", "from", "all", "pages", "regardless", "of", "whether", "they", "were", "generated", ...
def homepage_context(request): context = {} home_page = request.site.root_page.specific if home_page.seo_title: context["conference_title"] = home_page.seo_title else: context["conference_title"] = home_page.title if type(home_page) == HomePage: context["logo_image"] = home_p...
[ "def", "homepage_context", "(", "request", ")", ":", "context", "=", "{", "}", "home_page", "=", "request", ".", "site", ".", "root_page", ".", "specific", "if", "home_page", ".", "seo_title", ":", "context", "[", "\"conference_title\"", "]", "=", "home_page...
Add homepage information into context.
[ "Add", "homepage", "information", "into", "context", "." ]
[ "\"\"\"\n Add homepage information into context.\n\n Add certain homepage fields into the general context so that they\n are available from all pages, regardless of whether they were\n generated with Wagtail or Symposion.\n \"\"\"", "# Assume that the homepage is the root page in Wagtail.", "# If...
[ { "param": "request", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "request", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
3993fe581b4b60e6e7c3fe25a1fa83908a25f4c1
maartenbreddels/conf_site
conf_site/reviews/tests/test_proposal_voting.py
[ "MIT" ]
Python
_get_cached_vote_score
<not_specific>
def _get_cached_vote_score(self): """Helper method to retrieve a cached vote score.""" return cache.get( proposalvote_score_cache_key(self.proposal, self.user) )
Helper method to retrieve a cached vote score.
Helper method to retrieve a cached vote score.
[ "Helper", "method", "to", "retrieve", "a", "cached", "vote", "score", "." ]
def _get_cached_vote_score(self): return cache.get( proposalvote_score_cache_key(self.proposal, self.user) )
[ "def", "_get_cached_vote_score", "(", "self", ")", ":", "return", "cache", ".", "get", "(", "proposalvote_score_cache_key", "(", "self", ".", "proposal", ",", "self", ".", "user", ")", ")" ]
Helper method to retrieve a cached vote score.
[ "Helper", "method", "to", "retrieve", "a", "cached", "vote", "score", "." ]
[ "\"\"\"Helper method to retrieve a cached vote score.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
9c86d858a37d46b09025b6414642abb02a07700f
maartenbreddels/conf_site
conf_site/reviews/models.py
[ "MIT" ]
Python
proposalvote_score_cache_key
<not_specific>
def proposalvote_score_cache_key(proposal, voter): """ Return the cache key for a ProposalVote's score based on the proposal and voting user. """ return "proposalvote_{}_{}_score".format(proposal.pk, voter.pk)
Return the cache key for a ProposalVote's score based on the proposal and voting user.
Return the cache key for a ProposalVote's score based on the proposal and voting user.
[ "Return", "the", "cache", "key", "for", "a", "ProposalVote", "'", "s", "score", "based", "on", "the", "proposal", "and", "voting", "user", "." ]
def proposalvote_score_cache_key(proposal, voter): return "proposalvote_{}_{}_score".format(proposal.pk, voter.pk)
[ "def", "proposalvote_score_cache_key", "(", "proposal", ",", "voter", ")", ":", "return", "\"proposalvote_{}_{}_score\"", ".", "format", "(", "proposal", ".", "pk", ",", "voter", ".", "pk", ")" ]
Return the cache key for a ProposalVote's score based on the proposal and voting user.
[ "Return", "the", "cache", "key", "for", "a", "ProposalVote", "'", "s", "score", "based", "on", "the", "proposal", "and", "voting", "user", "." ]
[ "\"\"\"\n Return the cache key for a ProposalVote's score\n based on the proposal and voting user.\n \"\"\"" ]
[ { "param": "proposal", "type": null }, { "param": "voter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "proposal", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "voter", "type": null, "docstring": null, "docstring_token...
9c86d858a37d46b09025b6414642abb02a07700f
maartenbreddels/conf_site
conf_site/reviews/models.py
[ "MIT" ]
Python
send_email
<not_specific>
def send_email(self): """Returns a list of speakers without email addresses.""" email_messages = [] unemailed = [] # Create a message for each email address. # This is necessary because we are not using BCC. for proposal in self.proposals.all(): # In order to ...
Returns a list of speakers without email addresses.
Returns a list of speakers without email addresses.
[ "Returns", "a", "list", "of", "speakers", "without", "email", "addresses", "." ]
def send_email(self): email_messages = [] unemailed = [] for proposal in self.proposals.all(): message_body = Template(self.body).render( Context({"proposal": proposal.notification_email_context()}) ) for speaker in proposal.speakers(): ...
[ "def", "send_email", "(", "self", ")", ":", "email_messages", "=", "[", "]", "unemailed", "=", "[", "]", "for", "proposal", "in", "self", ".", "proposals", ".", "all", "(", ")", ":", "message_body", "=", "Template", "(", "self", ".", "body", ")", "."...
Returns a list of speakers without email addresses.
[ "Returns", "a", "list", "of", "speakers", "without", "email", "addresses", "." ]
[ "\"\"\"Returns a list of speakers without email addresses.\"\"\"", "# Create a message for each email address.", "# This is necessary because we are not using BCC.", "# In order to support the \"variable substitution\"", "# supported by the previous reviews system, the", "# message needs to be templated a...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
a5c802b2040f18359f75858dd884a7933f9073b6
maartenbreddels/conf_site
conf_site/reviews/templatetags/review_tags.py
[ "MIT" ]
Python
user_score
<not_specific>
def user_score(proposal, user): """For the selected proposal, display the current user's review score.""" # Try to retrieve score from cache. score_cache_key = proposalvote_score_cache_key(proposal, user) cached_score = cache.get(score_cache_key) if cached_score: return cached_score try:...
For the selected proposal, display the current user's review score.
For the selected proposal, display the current user's review score.
[ "For", "the", "selected", "proposal", "display", "the", "current", "user", "'", "s", "review", "score", "." ]
def user_score(proposal, user): score_cache_key = proposalvote_score_cache_key(proposal, user) cached_score = cache.get(score_cache_key) if cached_score: return cached_score try: uncached_score = ProposalVote.objects.get( proposal=proposal, voter=user ).get_numeric_sc...
[ "def", "user_score", "(", "proposal", ",", "user", ")", ":", "score_cache_key", "=", "proposalvote_score_cache_key", "(", "proposal", ",", "user", ")", "cached_score", "=", "cache", ".", "get", "(", "score_cache_key", ")", "if", "cached_score", ":", "return", ...
For the selected proposal, display the current user's review score.
[ "For", "the", "selected", "proposal", "display", "the", "current", "user", "'", "s", "review", "score", "." ]
[ "\"\"\"For the selected proposal, display the current user's review score.\"\"\"", "# Try to retrieve score from cache." ]
[ { "param": "proposal", "type": null }, { "param": "user", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "proposal", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "user", "type": null, "docstring": null, "docstring_tokens...
a5c802b2040f18359f75858dd884a7933f9073b6
maartenbreddels/conf_site
conf_site/reviews/templatetags/review_tags.py
[ "MIT" ]
Python
is_reviewer
<not_specific>
def is_reviewer(user): """Determine whether selected user is in the Reviewers user group.""" try: reviewers_group = Group.objects.get(name="Reviewers") except Group.DoesNotExist: return False return True if reviewers_group in user.groups.all() else False
Determine whether selected user is in the Reviewers user group.
Determine whether selected user is in the Reviewers user group.
[ "Determine", "whether", "selected", "user", "is", "in", "the", "Reviewers", "user", "group", "." ]
def is_reviewer(user): try: reviewers_group = Group.objects.get(name="Reviewers") except Group.DoesNotExist: return False return True if reviewers_group in user.groups.all() else False
[ "def", "is_reviewer", "(", "user", ")", ":", "try", ":", "reviewers_group", "=", "Group", ".", "objects", ".", "get", "(", "name", "=", "\"Reviewers\"", ")", "except", "Group", ".", "DoesNotExist", ":", "return", "False", "return", "True", "if", "reviewers...
Determine whether selected user is in the Reviewers user group.
[ "Determine", "whether", "selected", "user", "is", "in", "the", "Reviewers", "user", "group", "." ]
[ "\"\"\"Determine whether selected user is in the Reviewers user group.\"\"\"" ]
[ { "param": "user", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "user", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
e5b10883f3f1ea3e29778de17d3a9bd2197b83ef
ThorbenWoelk/SERP-Screenshot-Module
screenshot.py
[ "MIT" ]
Python
create_file_location
<not_specific>
def create_file_location(for_engines): """create new folder labeled by date and subfolder for search engine""" now = datetime.datetime.now() directory = 'screenshots\\'+now.strftime("%Y-%m-%d_%H-%M") if not os.path.exists(directory): os.makedirs(directory) if 'Google' in for_engines: ...
create new folder labeled by date and subfolder for search engine
create new folder labeled by date and subfolder for search engine
[ "create", "new", "folder", "labeled", "by", "date", "and", "subfolder", "for", "search", "engine" ]
def create_file_location(for_engines): now = datetime.datetime.now() directory = 'screenshots\\'+now.strftime("%Y-%m-%d_%H-%M") if not os.path.exists(directory): os.makedirs(directory) if 'Google' in for_engines: os.makedirs(directory+'\\Google') if 'Bing' in for_engines:...
[ "def", "create_file_location", "(", "for_engines", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "directory", "=", "'screenshots\\\\'", "+", "now", ".", "strftime", "(", "\"%Y-%m-%d_%H-%M\"", ")", "if", "not", "os", ".", "path", ...
create new folder labeled by date and subfolder for search engine
[ "create", "new", "folder", "labeled", "by", "date", "and", "subfolder", "for", "search", "engine" ]
[ "\"\"\"create new folder labeled by date and subfolder for search engine\"\"\"" ]
[ { "param": "for_engines", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "for_engines", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
e5b10883f3f1ea3e29778de17d3a9bd2197b83ef
ThorbenWoelk/SERP-Screenshot-Module
screenshot.py
[ "MIT" ]
Python
make_screenshot
null
def make_screenshot(keyword_data, chrome_args, size, engines): """make screenshots for a set of input keywords""" # get keywords keywords = get_keywords(keyword_data) # create folders to save screenshots in and get path and date path, date = create_file_location(engines) # configure Chromedriver...
make screenshots for a set of input keywords
make screenshots for a set of input keywords
[ "make", "screenshots", "for", "a", "set", "of", "input", "keywords" ]
def make_screenshot(keyword_data, chrome_args, size, engines): keywords = get_keywords(keyword_data) path, date = create_file_location(engines) chrome_options = Options() for argument in chrome_args: chrome_options.add_argument(argument) if 'MOBILE_EMULATION' in globals(): chrome_opt...
[ "def", "make_screenshot", "(", "keyword_data", ",", "chrome_args", ",", "size", ",", "engines", ")", ":", "keywords", "=", "get_keywords", "(", "keyword_data", ")", "path", ",", "date", "=", "create_file_location", "(", "engines", ")", "chrome_options", "=", "...
make screenshots for a set of input keywords
[ "make", "screenshots", "for", "a", "set", "of", "input", "keywords" ]
[ "\"\"\"make screenshots for a set of input keywords\"\"\"", "# get keywords", "# create folders to save screenshots in and get path and date", "# configure Chromedriver options", "# set the window size that you need", "# make screenshots" ]
[ { "param": "keyword_data", "type": null }, { "param": "chrome_args", "type": null }, { "param": "size", "type": null }, { "param": "engines", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "keyword_data", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "chrome_args", "type": null, "docstring": null, "docst...
ae1354d64fbfa0e588b1f5aef32db189b0d1e753
voitau/aws-data-wrangler
awswrangler/athena/_read.py
[ "Apache-2.0" ]
Python
_resolve_query_with_cache
Union[pd.DataFrame, Iterator[pd.DataFrame]]
def _resolve_query_with_cache( cache_info: _CacheInfo, categories: Optional[List[str]], chunksize: Optional[Union[int, bool]], use_threads: Union[bool, int], session: Optional[boto3.Session], s3_additional_kwargs: Optional[Dict[str, Any]], pyarrow_additional_kwargs: Optional[Dict[str, Any]] ...
Fetch cached data and return it as a pandas DataFrame (or list of DataFrames).
Fetch cached data and return it as a pandas DataFrame (or list of DataFrames).
[ "Fetch", "cached", "data", "and", "return", "it", "as", "a", "pandas", "DataFrame", "(", "or", "list", "of", "DataFrames", ")", "." ]
def _resolve_query_with_cache( cache_info: _CacheInfo, categories: Optional[List[str]], chunksize: Optional[Union[int, bool]], use_threads: Union[bool, int], session: Optional[boto3.Session], s3_additional_kwargs: Optional[Dict[str, Any]], pyarrow_additional_kwargs: Optional[Dict[str, Any]] ...
[ "def", "_resolve_query_with_cache", "(", "cache_info", ":", "_CacheInfo", ",", "categories", ":", "Optional", "[", "List", "[", "str", "]", "]", ",", "chunksize", ":", "Optional", "[", "Union", "[", "int", ",", "bool", "]", "]", ",", "use_threads", ":", ...
Fetch cached data and return it as a pandas DataFrame (or list of DataFrames).
[ "Fetch", "cached", "data", "and", "return", "it", "as", "a", "pandas", "DataFrame", "(", "or", "list", "of", "DataFrames", ")", "." ]
[ "\"\"\"Fetch cached data and return it as a pandas DataFrame (or list of DataFrames).\"\"\"" ]
[ { "param": "cache_info", "type": "_CacheInfo" }, { "param": "categories", "type": "Optional[List[str]]" }, { "param": "chunksize", "type": "Optional[Union[int, bool]]" }, { "param": "use_threads", "type": "Union[bool, int]" }, { "param": "session", "type": "Op...
{ "returns": [], "raises": [], "params": [ { "identifier": "cache_info", "type": "_CacheInfo", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "categories", "type": "Optional[List[str]]", "docstrin...
ae1354d64fbfa0e588b1f5aef32db189b0d1e753
voitau/aws-data-wrangler
awswrangler/athena/_read.py
[ "Apache-2.0" ]
Python
_resolve_query_without_cache
Union[pd.DataFrame, Iterator[pd.DataFrame]]
def _resolve_query_without_cache( # pylint: disable=too-many-branches,too-many-locals,too-many-return-statements,too-many-statements sql: str, database: str, data_source: Optional[str], ctas_approach: bool, categories: Optional[List[str]], chunksize: Union[int, bool, None], s3_output: Op...
Execute a query in Athena and returns results as DataFrame, back to `read_sql_query`. Usually called by `read_sql_query` when using cache is not possible.
Execute a query in Athena and returns results as DataFrame, back to `read_sql_query`. Usually called by `read_sql_query` when using cache is not possible.
[ "Execute", "a", "query", "in", "Athena", "and", "returns", "results", "as", "DataFrame", "back", "to", "`", "read_sql_query", "`", ".", "Usually", "called", "by", "`", "read_sql_query", "`", "when", "using", "cache", "is", "not", "possible", "." ]
def _resolve_query_without_cache( sql: str, database: str, data_source: Optional[str], ctas_approach: bool, categories: Optional[List[str]], chunksize: Union[int, bool, None], s3_output: Optional[str], workgroup: Optional[str], encryption: Optional[str], kms_key: Optional[str], ...
[ "def", "_resolve_query_without_cache", "(", "sql", ":", "str", ",", "database", ":", "str", ",", "data_source", ":", "Optional", "[", "str", "]", ",", "ctas_approach", ":", "bool", ",", "categories", ":", "Optional", "[", "List", "[", "str", "]", "]", ",...
Execute a query in Athena and returns results as DataFrame, back to `read_sql_query`.
[ "Execute", "a", "query", "in", "Athena", "and", "returns", "results", "as", "DataFrame", "back", "to", "`", "read_sql_query", "`", "." ]
[ "# pylint: disable=too-many-branches,too-many-locals,too-many-return-statements,too-many-statements", "\"\"\"\n Execute a query in Athena and returns results as DataFrame, back to `read_sql_query`.\n\n Usually called by `read_sql_query` when using cache is not possible.\n \"\"\"" ]
[ { "param": "sql", "type": "str" }, { "param": "database", "type": "str" }, { "param": "data_source", "type": "Optional[str]" }, { "param": "ctas_approach", "type": "bool" }, { "param": "categories", "type": "Optional[List[str]]" }, { "param": "chunksiz...
{ "returns": [], "raises": [], "params": [ { "identifier": "sql", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "database", "type": "str", "docstring": null, "docstring_token...
8a647e2042b9e32fee05450063ccd4402bd6ed8b
CS-Build-Week-02/adventure
miner/miner.py
[ "MIT" ]
Python
proof_of_work
<not_specific>
def proof_of_work(last_proof, difficulty): """ Simple Proof of Work Algorithm Find a number p such that hash(last_block_string, p) contains 6 leading zeroes """ print("starting work on a new proof") proof = 0 guess = f'{last_proof}{proof}'.encode() print(hashlib.sha256(guess).hexdige...
Simple Proof of Work Algorithm Find a number p such that hash(last_block_string, p) contains 6 leading zeroes
Simple Proof of Work Algorithm Find a number p such that hash(last_block_string, p) contains 6 leading zeroes
[ "Simple", "Proof", "of", "Work", "Algorithm", "Find", "a", "number", "p", "such", "that", "hash", "(", "last_block_string", "p", ")", "contains", "6", "leading", "zeroes" ]
def proof_of_work(last_proof, difficulty): print("starting work on a new proof") proof = 0 guess = f'{last_proof}{proof}'.encode() print(hashlib.sha256(guess).hexdigest()) print(proof) while valid_proof(last_proof, proof, difficulty) is False: proof += 1 return proof
[ "def", "proof_of_work", "(", "last_proof", ",", "difficulty", ")", ":", "print", "(", "\"starting work on a new proof\"", ")", "proof", "=", "0", "guess", "=", "f'{last_proof}{proof}'", ".", "encode", "(", ")", "print", "(", "hashlib", ".", "sha256", "(", "gue...
Simple Proof of Work Algorithm Find a number p such that hash(last_block_string, p) contains 6 leading zeroes
[ "Simple", "Proof", "of", "Work", "Algorithm", "Find", "a", "number", "p", "such", "that", "hash", "(", "last_block_string", "p", ")", "contains", "6", "leading", "zeroes" ]
[ "\"\"\"\n Simple Proof of Work Algorithm\n Find a number p such that hash(last_block_string, p) contains 6 leading\n zeroes\n \"\"\"" ]
[ { "param": "last_proof", "type": null }, { "param": "difficulty", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "last_proof", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "difficulty", "type": null, "docstring": null, "docstrin...
8a647e2042b9e32fee05450063ccd4402bd6ed8b
CS-Build-Week-02/adventure
miner/miner.py
[ "MIT" ]
Python
valid_proof
<not_specific>
def valid_proof(last_proof, proof, difficulty): """ Validates the Proof: Does hash(block_string, proof) contain 6 leading zeroes? difficutly returned by last proof function """ guess = f'{last_proof}{proof}'.encode() guess_hash = hashlib.sha256(guess).hexdigest() beg = guess_...
Validates the Proof: Does hash(block_string, proof) contain 6 leading zeroes? difficutly returned by last proof function
Validates the Proof: Does hash(block_string, proof) contain 6 leading zeroes. difficutly returned by last proof function
[ "Validates", "the", "Proof", ":", "Does", "hash", "(", "block_string", "proof", ")", "contain", "6", "leading", "zeroes", ".", "difficutly", "returned", "by", "last", "proof", "function" ]
def valid_proof(last_proof, proof, difficulty): guess = f'{last_proof}{proof}'.encode() guess_hash = hashlib.sha256(guess).hexdigest() beg = guess_hash[:difficulty] dif = difficulty string= "0" while dif > 1: string += "0" dif -= 1 if beg == string: print("HEEEEELLLLL...
[ "def", "valid_proof", "(", "last_proof", ",", "proof", ",", "difficulty", ")", ":", "guess", "=", "f'{last_proof}{proof}'", ".", "encode", "(", ")", "guess_hash", "=", "hashlib", ".", "sha256", "(", "guess", ")", ".", "hexdigest", "(", ")", "beg", "=", "...
Validates the Proof: Does hash(block_string, proof) contain 6 leading zeroes?
[ "Validates", "the", "Proof", ":", "Does", "hash", "(", "block_string", "proof", ")", "contain", "6", "leading", "zeroes?" ]
[ "\"\"\"\n Validates the Proof: Does hash(block_string, proof) contain 6\n leading zeroes?\n difficutly returned by last proof function\n \"\"\"", "# TODO", "# pass" ]
[ { "param": "last_proof", "type": null }, { "param": "proof", "type": null }, { "param": "difficulty", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "last_proof", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "proof", "type": null, "docstring": null, "docstring_tok...
75bd659682d59e40b3eff01451cc512d2283a6b7
cenavia/skylynx
old_backend/lahause/users/serializers/users.py
[ "MIT" ]
Python
create
<not_specific>
def create(self, data): """Handle user and profile creation.""" data.pop('password_confirmation') user = User.objects.create_user(**data, is_verified=False) # send_confirmation_email.delay(user_pk=user.pk) return user
Handle user and profile creation.
Handle user and profile creation.
[ "Handle", "user", "and", "profile", "creation", "." ]
def create(self, data): data.pop('password_confirmation') user = User.objects.create_user(**data, is_verified=False) return user
[ "def", "create", "(", "self", ",", "data", ")", ":", "data", ".", "pop", "(", "'password_confirmation'", ")", "user", "=", "User", ".", "objects", ".", "create_user", "(", "**", "data", ",", "is_verified", "=", "False", ")", "return", "user" ]
Handle user and profile creation.
[ "Handle", "user", "and", "profile", "creation", "." ]
[ "\"\"\"Handle user and profile creation.\"\"\"", "# send_confirmation_email.delay(user_pk=user.pk)" ]
[ { "param": "self", "type": null }, { "param": "data", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "data", "type": null, "docstring": null, "docstring_tokens": [...
5e46f80b91d0c386663bc6d5bce468fdaca7c51a
atoaiari/mmdetection
mmdet/models/detectors/orientation_cascade_rcnn_no.py
[ "Apache-2.0" ]
Python
show_result
<not_specific>
def show_result(self, data, result, **kwargs): """Show prediction results of the detector. Args: data (str or np.ndarray): Image filename or loaded image. result (Tensor or tuple): The results to draw over `img` bbox_result or (bbox_result, segm_result). ...
Show prediction results of the detector. Args: data (str or np.ndarray): Image filename or loaded image. result (Tensor or tuple): The results to draw over `img` bbox_result or (bbox_result, segm_result). Returns: np.ndarray: The image with bboxes dr...
Show prediction results of the detector.
[ "Show", "prediction", "results", "of", "the", "detector", "." ]
def show_result(self, data, result, **kwargs): if self.with_mask: ms_bbox_result, ms_segm_result = result if isinstance(ms_bbox_result, dict): result = (ms_bbox_result['ensemble'], ms_segm_result['ensemble']) else: if isinstan...
[ "def", "show_result", "(", "self", ",", "data", ",", "result", ",", "**", "kwargs", ")", ":", "if", "self", ".", "with_mask", ":", "ms_bbox_result", ",", "ms_segm_result", "=", "result", "if", "isinstance", "(", "ms_bbox_result", ",", "dict", ")", ":", "...
Show prediction results of the detector.
[ "Show", "prediction", "results", "of", "the", "detector", "." ]
[ "\"\"\"Show prediction results of the detector.\n\n Args:\n data (str or np.ndarray): Image filename or loaded image.\n result (Tensor or tuple): The results to draw over `img`\n bbox_result or (bbox_result, segm_result).\n\n Returns:\n np.ndarray: The i...
[ { "param": "self", "type": null }, { "param": "data", "type": null }, { "param": "result", "type": null } ]
{ "returns": [ { "docstring": "The image with bboxes drawn on it.", "docstring_tokens": [ "The", "image", "with", "bboxes", "drawn", "on", "it", "." ], "type": "np.ndarray" } ], "raises": [], "params": [ { ...
7e1fde48b8ee2c61eafd0c5c8f54b04ca760dc79
atoaiari/mmdetection
mmdet/datasets/coco_orientation.py
[ "Apache-2.0" ]
Python
_parse_ann_info
<not_specific>
def _parse_ann_info(self, img_info, ann_info): """Parse bbox and mask annotation. Args: ann_info (list[dict]): Annotation info of an image. with_mask (bool): Whether to parse mask annotations. Returns: dict: A dict containing the following keys: bboxes, bbox...
Parse bbox and mask annotation. Args: ann_info (list[dict]): Annotation info of an image. with_mask (bool): Whether to parse mask annotations. Returns: dict: A dict containing the following keys: bboxes, bboxes_ignore,\ labels, masks, seg_map. "masks...
Parse bbox and mask annotation.
[ "Parse", "bbox", "and", "mask", "annotation", "." ]
def _parse_ann_info(self, img_info, ann_info): gt_bboxes = [] gt_labels = [] gt_bboxes_ignore = [] gt_masks_ann = [] gt_orientations = [] orientation_kernel_len = 72 sigma = 4.0 for i, ann in enumerate(ann_info): if ann.get('ignore', False): ...
[ "def", "_parse_ann_info", "(", "self", ",", "img_info", ",", "ann_info", ")", ":", "gt_bboxes", "=", "[", "]", "gt_labels", "=", "[", "]", "gt_bboxes_ignore", "=", "[", "]", "gt_masks_ann", "=", "[", "]", "gt_orientations", "=", "[", "]", "orientation_kern...
Parse bbox and mask annotation.
[ "Parse", "bbox", "and", "mask", "annotation", "." ]
[ "\"\"\"Parse bbox and mask annotation.\n\n Args:\n ann_info (list[dict]): Annotation info of an image.\n with_mask (bool): Whether to parse mask annotations.\n\n Returns:\n dict: A dict containing the following keys: bboxes, bboxes_ignore,\\\n labels, ma...
[ { "param": "self", "type": null }, { "param": "img_info", "type": null }, { "param": "ann_info", "type": null } ]
{ "returns": [ { "docstring": "A dict containing the following keys: bboxes, bboxes_ignore,\\\nlabels, masks, seg_map. \"masks\" are raw annotations and not \\\ndecoded into binary masks.", "docstring_tokens": [ "A", "dict", "containing", "the", "following", ...
a02f18d71117894aaa81cf6093767a9ee0ec2972
sheffieldnlp/TransQuest
algo/transformers/run_model.py
[ "Apache-2.0" ]
Python
train_model
null
def train_model( self, train_df, multi_label=False, output_dir=None, show_running_loss=True, args=None, eval_df=None, verbose=True, **kwargs, ): """ Trains the model using 'train_df' Args: train_df: Pandas D...
Trains the model using 'train_df' Args: train_df: Pandas Dataframe containing at least two columns. If the Dataframe has a header, it should contain a 'text' and a 'labels' column. If no header is present, the Dataframe should contain at least two columns, with the first column...
Trains the model using 'train_df' Args: train_df: Pandas Dataframe containing at least two columns. If the Dataframe has a header, it should contain a 'text' and a 'labels' column. If no header is present, the Dataframe should contain at least two columns, with the first column containing the text, and the second colum...
[ "Trains", "the", "model", "using", "'", "train_df", "'", "Args", ":", "train_df", ":", "Pandas", "Dataframe", "containing", "at", "least", "two", "columns", ".", "If", "the", "Dataframe", "has", "a", "header", "it", "should", "contain", "a", "'", "text", ...
def train_model( self, train_df, multi_label=False, output_dir=None, show_running_loss=True, args=None, eval_df=None, verbose=True, **kwargs, ): if args: self.args.update(args) if self.args["silent"]: sho...
[ "def", "train_model", "(", "self", ",", "train_df", ",", "multi_label", "=", "False", ",", "output_dir", "=", "None", ",", "show_running_loss", "=", "True", ",", "args", "=", "None", ",", "eval_df", "=", "None", ",", "verbose", "=", "True", ",", "**", ...
Trains the model using 'train_df' Args: train_df: Pandas Dataframe containing at least two columns.
[ "Trains", "the", "model", "using", "'", "train_df", "'", "Args", ":", "train_df", ":", "Pandas", "Dataframe", "containing", "at", "least", "two", "columns", "." ]
[ "\"\"\"\n Trains the model using 'train_df'\n\n Args:\n train_df: Pandas Dataframe containing at least two columns. If the Dataframe has a header, it should contain a 'text' and a 'labels' column. If no header is present,\n the Dataframe should contain at least two columns, with ...
[ { "param": "self", "type": null }, { "param": "train_df", "type": null }, { "param": "multi_label", "type": null }, { "param": "output_dir", "type": null }, { "param": "show_running_loss", "type": null }, { "param": "args", "type": null }, { ...
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "train_df", "type": null, "docstring": null, "docstring_tokens...
a02f18d71117894aaa81cf6093767a9ee0ec2972
sheffieldnlp/TransQuest
algo/transformers/run_model.py
[ "Apache-2.0" ]
Python
eval_model
<not_specific>
def eval_model(self, eval_df, multi_label=False, output_dir=None, verbose=True, silent=False, **kwargs): """ Evaluates the model on eval_df. Saves results to output_dir. Args: eval_df: Pandas Dataframe containing at least two columns. If the Dataframe has a header, it should contain...
Evaluates the model on eval_df. Saves results to output_dir. Args: eval_df: Pandas Dataframe containing at least two columns. If the Dataframe has a header, it should contain a 'text' and a 'labels' column. If no header is present, the Dataframe should contain at least two colu...
Evaluates the model on eval_df. Saves results to output_dir. Args: eval_df: Pandas Dataframe containing at least two columns. If the Dataframe has a header, it should contain a 'text' and a 'labels' column. If no header is present, the Dataframe should contain at least two columns, with the first column containing the ...
[ "Evaluates", "the", "model", "on", "eval_df", ".", "Saves", "results", "to", "output_dir", ".", "Args", ":", "eval_df", ":", "Pandas", "Dataframe", "containing", "at", "least", "two", "columns", ".", "If", "the", "Dataframe", "has", "a", "header", "it", "s...
def eval_model(self, eval_df, multi_label=False, output_dir=None, verbose=True, silent=False, **kwargs): if not output_dir: output_dir = self.args["output_dir"] self._move_model_to_device() result, model_outputs, wrong_preds = self.evaluate( eval_df, output_dir, multi_lab...
[ "def", "eval_model", "(", "self", ",", "eval_df", ",", "multi_label", "=", "False", ",", "output_dir", "=", "None", ",", "verbose", "=", "True", ",", "silent", "=", "False", ",", "**", "kwargs", ")", ":", "if", "not", "output_dir", ":", "output_dir", "...
Evaluates the model on eval_df.
[ "Evaluates", "the", "model", "on", "eval_df", "." ]
[ "\"\"\"\n Evaluates the model on eval_df. Saves results to output_dir.\n\n Args:\n eval_df: Pandas Dataframe containing at least two columns. If the Dataframe has a header, it should contain a 'text' and a 'labels' column. If no header is present,\n the Dataframe should contain a...
[ { "param": "self", "type": null }, { "param": "eval_df", "type": null }, { "param": "multi_label", "type": null }, { "param": "output_dir", "type": null }, { "param": "verbose", "type": null }, { "param": "silent", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "eval_df", "type": null, "docstring": null, "docstring_tokens"...
a02f18d71117894aaa81cf6093767a9ee0ec2972
sheffieldnlp/TransQuest
algo/transformers/run_model.py
[ "Apache-2.0" ]
Python
evaluate
<not_specific>
def evaluate(self, eval_df, output_dir, multi_label=False, prefix="", verbose=True, silent=False, **kwargs): """ Evaluates the model on eval_df. Utility function to be used by the eval_model() method. Not intended to be used directly. """ device = self.device model = se...
Evaluates the model on eval_df. Utility function to be used by the eval_model() method. Not intended to be used directly.
Evaluates the model on eval_df. Utility function to be used by the eval_model() method. Not intended to be used directly.
[ "Evaluates", "the", "model", "on", "eval_df", ".", "Utility", "function", "to", "be", "used", "by", "the", "eval_model", "()", "method", ".", "Not", "intended", "to", "be", "used", "directly", "." ]
def evaluate(self, eval_df, output_dir, multi_label=False, prefix="", verbose=True, silent=False, **kwargs): device = self.device model = self.model args = self.args eval_output_dir = output_dir results = {} if "text" in eval_df.columns and "labels" in eval_df.columns: ...
[ "def", "evaluate", "(", "self", ",", "eval_df", ",", "output_dir", ",", "multi_label", "=", "False", ",", "prefix", "=", "\"\"", ",", "verbose", "=", "True", ",", "silent", "=", "False", ",", "**", "kwargs", ")", ":", "device", "=", "self", ".", "dev...
Evaluates the model on eval_df.
[ "Evaluates", "the", "model", "on", "eval_df", "." ]
[ "\"\"\"\n Evaluates the model on eval_df.\n\n Utility function to be used by the eval_model() method. Not intended to be used directly.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "eval_df", "type": null }, { "param": "output_dir", "type": null }, { "param": "multi_label", "type": null }, { "param": "prefix", "type": null }, { "param": "verbose", "type": null }, { "param"...
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "eval_df", "type": null, "docstring": null, "docstring_tokens"...
a02f18d71117894aaa81cf6093767a9ee0ec2972
sheffieldnlp/TransQuest
algo/transformers/run_model.py
[ "Apache-2.0" ]
Python
load_and_cache_examples
<not_specific>
def load_and_cache_examples( self, examples, evaluate=False, no_cache=False, multi_label=False, verbose=True, silent=False ): """ Converts a list of InputExample objects to a TensorDataset containing InputFeatures. Caches the InputFeatures. Utility function for train() and eval() me...
Converts a list of InputExample objects to a TensorDataset containing InputFeatures. Caches the InputFeatures. Utility function for train() and eval() methods. Not intended to be used directly.
Converts a list of InputExample objects to a TensorDataset containing InputFeatures.
[ "Converts", "a", "list", "of", "InputExample", "objects", "to", "a", "TensorDataset", "containing", "InputFeatures", "." ]
def load_and_cache_examples( self, examples, evaluate=False, no_cache=False, multi_label=False, verbose=True, silent=False ): process_count = self.args["process_count"] tokenizer = self.tokenizer args = self.args if not no_cache: no_cache = args["no_cache"] ...
[ "def", "load_and_cache_examples", "(", "self", ",", "examples", ",", "evaluate", "=", "False", ",", "no_cache", "=", "False", ",", "multi_label", "=", "False", ",", "verbose", "=", "True", ",", "silent", "=", "False", ")", ":", "process_count", "=", "self"...
Converts a list of InputExample objects to a TensorDataset containing InputFeatures.
[ "Converts", "a", "list", "of", "InputExample", "objects", "to", "a", "TensorDataset", "containing", "InputFeatures", "." ]
[ "\"\"\"\n Converts a list of InputExample objects to a TensorDataset containing InputFeatures. Caches the InputFeatures.\n\n Utility function for train() and eval() methods. Not intended to be used directly.\n \"\"\"", "# XLNet has a CLS token at the end", "# RoBERTa uses an extra separator...
[ { "param": "self", "type": null }, { "param": "examples", "type": null }, { "param": "evaluate", "type": null }, { "param": "no_cache", "type": null }, { "param": "multi_label", "type": null }, { "param": "verbose", "type": null }, { "param...
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "examples", "type": null, "docstring": null, "docstring_tokens...
a02f18d71117894aaa81cf6093767a9ee0ec2972
sheffieldnlp/TransQuest
algo/transformers/run_model.py
[ "Apache-2.0" ]
Python
compute_metrics
<not_specific>
def compute_metrics(self, preds, labels, eval_examples, multi_label=False, **kwargs): """ Computes the evaluation metrics for the model predictions. Args: preds: Model predictions labels: Ground truth labels eval_examples: List of examples on which evaluation...
Computes the evaluation metrics for the model predictions. Args: preds: Model predictions labels: Ground truth labels eval_examples: List of examples on which evaluation was performed **kwargs: Additional metrics that should be used. Pass in the metrics ...
Computes the evaluation metrics for the model predictions.
[ "Computes", "the", "evaluation", "metrics", "for", "the", "model", "predictions", "." ]
def compute_metrics(self, preds, labels, eval_examples, multi_label=False, **kwargs): assert len(preds) == len(labels) extra_metrics = {} for metric, func in kwargs.items(): extra_metrics[metric] = func(labels, preds) mismatched = labels != preds wrong = [i for (i, v)...
[ "def", "compute_metrics", "(", "self", ",", "preds", ",", "labels", ",", "eval_examples", ",", "multi_label", "=", "False", ",", "**", "kwargs", ")", ":", "assert", "len", "(", "preds", ")", "==", "len", "(", "labels", ")", "extra_metrics", "=", "{", "...
Computes the evaluation metrics for the model predictions.
[ "Computes", "the", "evaluation", "metrics", "for", "the", "model", "predictions", "." ]
[ "\"\"\"\n Computes the evaluation metrics for the model predictions.\n\n Args:\n preds: Model predictions\n labels: Ground truth labels\n eval_examples: List of examples on which evaluation was performed\n **kwargs: Additional metrics that should be used. Pa...
[ { "param": "self", "type": null }, { "param": "preds", "type": null }, { "param": "labels", "type": null }, { "param": "eval_examples", "type": null }, { "param": "multi_label", "type": null } ]
{ "returns": [ { "docstring": "Dictionary containing evaluation results. (Matthews correlation coefficient, tp, tn, fp, fn)\nwrong: List of InputExample objects corresponding to each incorrect prediction by the model", "docstring_tokens": [ "Dictionary", "containing", "evaluati...
a02f18d71117894aaa81cf6093767a9ee0ec2972
sheffieldnlp/TransQuest
algo/transformers/run_model.py
[ "Apache-2.0" ]
Python
predict
<not_specific>
def predict(self, to_predict, multi_label=False): """ Performs predictions on a list of text. Args: to_predict: A python list of text (str) to be sent to the model for prediction. Returns: preds: A python list of the predictions (0 or 1) for each text. ...
Performs predictions on a list of text. Args: to_predict: A python list of text (str) to be sent to the model for prediction. Returns: preds: A python list of the predictions (0 or 1) for each text. model_outputs: A python list of the raw model outputs for ...
Performs predictions on a list of text.
[ "Performs", "predictions", "on", "a", "list", "of", "text", "." ]
def predict(self, to_predict, multi_label=False): device = self.device model = self.model args = self.args self._move_model_to_device() if multi_label: eval_examples = [ InputExample(i, text, None, [0 for i in range(self.num_labels)]) for i, text in en...
[ "def", "predict", "(", "self", ",", "to_predict", ",", "multi_label", "=", "False", ")", ":", "device", "=", "self", ".", "device", "model", "=", "self", ".", "model", "args", "=", "self", ".", "args", "self", ".", "_move_model_to_device", "(", ")", "i...
Performs predictions on a list of text.
[ "Performs", "predictions", "on", "a", "list", "of", "text", "." ]
[ "\"\"\"\n Performs predictions on a list of text.\n\n Args:\n to_predict: A python list of text (str) to be sent to the model for prediction.\n\n Returns:\n preds: A python list of the predictions (0 or 1) for each text.\n model_outputs: A python list of the raw...
[ { "param": "self", "type": null }, { "param": "to_predict", "type": null }, { "param": "multi_label", "type": null } ]
{ "returns": [ { "docstring": "A python list of the predictions (0 or 1) for each text.\nmodel_outputs: A python list of the raw model outputs for each text.", "docstring_tokens": [ "A", "python", "list", "of", "the", "predictions", "(", ...
3079c235d43cc675af33326ae885fb0de2c0a3a5
allen-cell-animated/simularium-conversion
simulariumio/data_objects/dimension_data.py
[ "Apache-2.0" ]
Python
add
DimensionData
def add(self, added_dimensions: DimensionData, axis: int = 1) -> DimensionData: """ Add the given dimensions with this object's and return a copy """ if axis == 1: if ( self.total_steps > 0 and added_dimensions.total_steps != self.total_steps ...
Add the given dimensions with this object's and return a copy
Add the given dimensions with this object's and return a copy
[ "Add", "the", "given", "dimensions", "with", "this", "object", "'", "s", "and", "return", "a", "copy" ]
def add(self, added_dimensions: DimensionData, axis: int = 1) -> DimensionData: if axis == 1: if ( self.total_steps > 0 and added_dimensions.total_steps != self.total_steps ): raise DataError( "Total steps must be equal ...
[ "def", "add", "(", "self", ",", "added_dimensions", ":", "DimensionData", ",", "axis", ":", "int", "=", "1", ")", "->", "DimensionData", ":", "if", "axis", "==", "1", ":", "if", "(", "self", ".", "total_steps", ">", "0", "and", "added_dimensions", ".",...
Add the given dimensions with this object's and return a copy
[ "Add", "the", "given", "dimensions", "with", "this", "object", "'", "s", "and", "return", "a", "copy" ]
[ "\"\"\"\n Add the given dimensions with this object's and return a copy\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "added_dimensions", "type": "DimensionData" }, { "param": "axis", "type": "int" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "added_dimensions", "type": "DimensionData", "docstring": null, ...
d6eaf73fb4ada0687afddac61a2801d3f6f80118
allen-cell-animated/simularium-conversion
simulariumio/readdy/readdy_converter.py
[ "Apache-2.0" ]
Python
_get_raw_trajectory_data
Tuple[AgentData, Any, np.ndarray]
def _get_raw_trajectory_data( input_data: ReaddyData, ) -> Tuple[AgentData, Any, np.ndarray]: """ Return agent data populated from a ReaDDy .h5 trajectory file """ # load the trajectory traj = readdy.Trajectory(input_data.path_to_readdy_h5) n_agents, positions...
Return agent data populated from a ReaDDy .h5 trajectory file
Return agent data populated from a ReaDDy .h5 trajectory file
[ "Return", "agent", "data", "populated", "from", "a", "ReaDDy", ".", "h5", "trajectory", "file" ]
def _get_raw_trajectory_data( input_data: ReaddyData, ) -> Tuple[AgentData, Any, np.ndarray]: traj = readdy.Trajectory(input_data.path_to_readdy_h5) n_agents, positions, type_ids, ids = traj.to_numpy(start=0, stop=None) return (traj, n_agents, positions, type_ids, ids)
[ "def", "_get_raw_trajectory_data", "(", "input_data", ":", "ReaddyData", ",", ")", "->", "Tuple", "[", "AgentData", ",", "Any", ",", "np", ".", "ndarray", "]", ":", "traj", "=", "readdy", ".", "Trajectory", "(", "input_data", ".", "path_to_readdy_h5", ")", ...
Return agent data populated from a ReaDDy .h5 trajectory file
[ "Return", "agent", "data", "populated", "from", "a", "ReaDDy", ".", "h5", "trajectory", "file" ]
[ "\"\"\"\n Return agent data populated from a ReaDDy .h5 trajectory file\n \"\"\"", "# load the trajectory" ]
[ { "param": "input_data", "type": "ReaddyData" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "input_data", "type": "ReaddyData", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
d6eaf73fb4ada0687afddac61a2801d3f6f80118
allen-cell-animated/simularium-conversion
simulariumio/readdy/readdy_converter.py
[ "Apache-2.0" ]
Python
_get_agent_data
AgentData
def _get_agent_data( input_data: ReaddyData, ) -> AgentData: """ Pack raw ReaDDy trajectory data into AgentData, ignoring particles with type names in ignore_types """ ( traj, n_agents, positions, type_ids, i...
Pack raw ReaDDy trajectory data into AgentData, ignoring particles with type names in ignore_types
Pack raw ReaDDy trajectory data into AgentData, ignoring particles with type names in ignore_types
[ "Pack", "raw", "ReaDDy", "trajectory", "data", "into", "AgentData", "ignoring", "particles", "with", "type", "names", "in", "ignore_types" ]
def _get_agent_data( input_data: ReaddyData, ) -> AgentData: ( traj, n_agents, positions, type_ids, ids, ) = ReaddyConverter._get_raw_trajectory_data(input_data) data_dimensions = DimensionData( total_steps=n_age...
[ "def", "_get_agent_data", "(", "input_data", ":", "ReaddyData", ",", ")", "->", "AgentData", ":", "(", "traj", ",", "n_agents", ",", "positions", ",", "type_ids", ",", "ids", ",", ")", "=", "ReaddyConverter", ".", "_get_raw_trajectory_data", "(", "input_data",...
Pack raw ReaDDy trajectory data into AgentData, ignoring particles with type names in ignore_types
[ "Pack", "raw", "ReaDDy", "trajectory", "data", "into", "AgentData", "ignoring", "particles", "with", "type", "names", "in", "ignore_types" ]
[ "\"\"\"\n Pack raw ReaDDy trajectory data into AgentData,\n ignoring particles with type names in ignore_types\n \"\"\"" ]
[ { "param": "input_data", "type": "ReaddyData" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "input_data", "type": "ReaddyData", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
d6eaf73fb4ada0687afddac61a2801d3f6f80118
allen-cell-animated/simularium-conversion
simulariumio/readdy/readdy_converter.py
[ "Apache-2.0" ]
Python
_read
TrajectoryData
def _read(input_data: ReaddyData) -> TrajectoryData: """ Return an object containing the data shaped for Simularium format """ print("Reading ReaDDy Data -------------") agent_data = ReaddyConverter._get_agent_data(input_data) # get display data (geometry and color) ...
Return an object containing the data shaped for Simularium format
Return an object containing the data shaped for Simularium format
[ "Return", "an", "object", "containing", "the", "data", "shaped", "for", "Simularium", "format" ]
def _read(input_data: ReaddyData) -> TrajectoryData: print("Reading ReaDDy Data -------------") agent_data = ReaddyConverter._get_agent_data(input_data) for tid in input_data.display_data: display_data = input_data.display_data[tid] agent_data.display_data[display_data.na...
[ "def", "_read", "(", "input_data", ":", "ReaddyData", ")", "->", "TrajectoryData", ":", "print", "(", "\"Reading ReaDDy Data -------------\"", ")", "agent_data", "=", "ReaddyConverter", ".", "_get_agent_data", "(", "input_data", ")", "for", "tid", "in", "input_data"...
Return an object containing the data shaped for Simularium format
[ "Return", "an", "object", "containing", "the", "data", "shaped", "for", "Simularium", "format" ]
[ "\"\"\"\n Return an object containing the data shaped for Simularium format\n \"\"\"", "# get display data (geometry and color)" ]
[ { "param": "input_data", "type": "ReaddyData" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "input_data", "type": "ReaddyData", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
ab28e06c7d562a75268378f4c1e05c5b787340c7
allen-cell-animated/simularium-conversion
simulariumio/filters/every_nth_agent_filter.py
[ "Apache-2.0" ]
Python
apply
TrajectoryData
def apply(self, data: TrajectoryData) -> TrajectoryData: """ Reduce the number of agents in each frame of the simularium data by filtering out all but every nth agent """ print("Filtering: every Nth agent -------------") # get filtered data start_dimensions = data...
Reduce the number of agents in each frame of the simularium data by filtering out all but every nth agent
Reduce the number of agents in each frame of the simularium data by filtering out all but every nth agent
[ "Reduce", "the", "number", "of", "agents", "in", "each", "frame", "of", "the", "simularium", "data", "by", "filtering", "out", "all", "but", "every", "nth", "agent" ]
def apply(self, data: TrajectoryData) -> TrajectoryData: print("Filtering: every Nth agent -------------") start_dimensions = data.agent_data.get_dimensions() result = AgentData.from_dimensions(start_dimensions) result.times = data.agent_data.times result.draw_fiber_points = data...
[ "def", "apply", "(", "self", ",", "data", ":", "TrajectoryData", ")", "->", "TrajectoryData", ":", "print", "(", "\"Filtering: every Nth agent -------------\"", ")", "start_dimensions", "=", "data", ".", "agent_data", ".", "get_dimensions", "(", ")", "result", "="...
Reduce the number of agents in each frame of the simularium data by filtering out all but every nth agent
[ "Reduce", "the", "number", "of", "agents", "in", "each", "frame", "of", "the", "simularium", "data", "by", "filtering", "out", "all", "but", "every", "nth", "agent" ]
[ "\"\"\"\n Reduce the number of agents in each frame of the simularium\n data by filtering out all but every nth agent\n \"\"\"", "# get filtered data" ]
[ { "param": "self", "type": null }, { "param": "data", "type": "TrajectoryData" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "data", "type": "TrajectoryData", "docstring": null, "docstrin...
9b2457e01c6fc21306d4d5404142e96f041b1204
allen-cell-animated/simularium-conversion
simulariumio/constants.py
[ "Apache-2.0" ]
Python
JMOL_COLORS
pd.DataFrame
def JMOL_COLORS() -> pd.DataFrame: """ Get a dataframe with Jmol colors for atomic element types """ this_dir, _ = os.path.split(__file__) return pd.read_csv(os.path.join(this_dir, JMOL_COLORS_CSV_PATH))
Get a dataframe with Jmol colors for atomic element types
Get a dataframe with Jmol colors for atomic element types
[ "Get", "a", "dataframe", "with", "Jmol", "colors", "for", "atomic", "element", "types" ]
def JMOL_COLORS() -> pd.DataFrame: this_dir, _ = os.path.split(__file__) return pd.read_csv(os.path.join(this_dir, JMOL_COLORS_CSV_PATH))
[ "def", "JMOL_COLORS", "(", ")", "->", "pd", ".", "DataFrame", ":", "this_dir", ",", "_", "=", "os", ".", "path", ".", "split", "(", "__file__", ")", "return", "pd", ".", "read_csv", "(", "os", ".", "path", ".", "join", "(", "this_dir", ",", "JMOL_C...
Get a dataframe with Jmol colors for atomic element types
[ "Get", "a", "dataframe", "with", "Jmol", "colors", "for", "atomic", "element", "types" ]
[ "\"\"\"\n Get a dataframe with Jmol colors for atomic element types\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
88bb494ac3d0fca90223a1add9ca3e1930d73fb2
allen-cell-animated/simularium-conversion
simulariumio/filters/transform_spatial_axes_filter.py
[ "Apache-2.0" ]
Python
_transform_coordinate
np.ndarray
def _transform_coordinate( self, position: np.ndarray, set_direction: bool = True ) -> np.ndarray: """ Transform an +X+Y+Z coordinate according to axes_mapping """ result = np.zeros_like(position) for d in range(len(self.axes_mapping)): axis = self.axes_ma...
Transform an +X+Y+Z coordinate according to axes_mapping
Transform an +X+Y+Z coordinate according to axes_mapping
[ "Transform", "an", "+", "X", "+", "Y", "+", "Z", "coordinate", "according", "to", "axes_mapping" ]
def _transform_coordinate( self, position: np.ndarray, set_direction: bool = True ) -> np.ndarray: result = np.zeros_like(position) for d in range(len(self.axes_mapping)): axis = self.axes_mapping[d] if "x" in axis: result[d] = position[0] ...
[ "def", "_transform_coordinate", "(", "self", ",", "position", ":", "np", ".", "ndarray", ",", "set_direction", ":", "bool", "=", "True", ")", "->", "np", ".", "ndarray", ":", "result", "=", "np", ".", "zeros_like", "(", "position", ")", "for", "d", "in...
Transform an +X+Y+Z coordinate according to axes_mapping
[ "Transform", "an", "+", "X", "+", "Y", "+", "Z", "coordinate", "according", "to", "axes_mapping" ]
[ "\"\"\"\n Transform an +X+Y+Z coordinate according to axes_mapping\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "position", "type": "np.ndarray" }, { "param": "set_direction", "type": "bool" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "position", "type": "np.ndarray", "docstring": null, "docstrin...
88bb494ac3d0fca90223a1add9ca3e1930d73fb2
allen-cell-animated/simularium-conversion
simulariumio/filters/transform_spatial_axes_filter.py
[ "Apache-2.0" ]
Python
apply
TrajectoryData
def apply(self, data: TrajectoryData) -> TrajectoryData: """ Transform spatial coordinates to rotate and/or reflect the scene """ print(f"Filtering: transform spatial axes {self.axes_mapping} -------------") # box size data.meta_data.box_size = self._transform_coordinate(...
Transform spatial coordinates to rotate and/or reflect the scene
Transform spatial coordinates to rotate and/or reflect the scene
[ "Transform", "spatial", "coordinates", "to", "rotate", "and", "/", "or", "reflect", "the", "scene" ]
def apply(self, data: TrajectoryData) -> TrajectoryData: print(f"Filtering: transform spatial axes {self.axes_mapping} -------------") data.meta_data.box_size = self._transform_coordinate( data.meta_data.box_size, False ) start_dimensions = data.agent_data.get_dimensions() ...
[ "def", "apply", "(", "self", ",", "data", ":", "TrajectoryData", ")", "->", "TrajectoryData", ":", "print", "(", "f\"Filtering: transform spatial axes {self.axes_mapping} -------------\"", ")", "data", ".", "meta_data", ".", "box_size", "=", "self", ".", "_transform_c...
Transform spatial coordinates to rotate and/or reflect the scene
[ "Transform", "spatial", "coordinates", "to", "rotate", "and", "/", "or", "reflect", "the", "scene" ]
[ "\"\"\"\n Transform spatial coordinates to rotate and/or reflect the scene\n \"\"\"", "# box size", "# get dimensions", "# get filtered data" ]
[ { "param": "self", "type": null }, { "param": "data", "type": "TrajectoryData" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "data", "type": "TrajectoryData", "docstring": null, "docstrin...
c8d44757193191510da694540c9538ff1594c5bc
allen-cell-animated/simularium-conversion
simulariumio/data_objects/trajectory_data.py
[ "Apache-2.0" ]
Python
from_buffer_data
<not_specific>
def from_buffer_data(cls, buffer_data: Dict[str, Any]): """ Create TrajectoryData from a simularium JSON dict containing buffers """ return cls( meta_data=MetaData.from_buffer_data(buffer_data), agent_data=AgentData.from_buffer_data(buffer_data), time_...
Create TrajectoryData from a simularium JSON dict containing buffers
Create TrajectoryData from a simularium JSON dict containing buffers
[ "Create", "TrajectoryData", "from", "a", "simularium", "JSON", "dict", "containing", "buffers" ]
def from_buffer_data(cls, buffer_data: Dict[str, Any]): return cls( meta_data=MetaData.from_buffer_data(buffer_data), agent_data=AgentData.from_buffer_data(buffer_data), time_units=UnitData( buffer_data["trajectoryInfo"]["timeUnits"]["name"], f...
[ "def", "from_buffer_data", "(", "cls", ",", "buffer_data", ":", "Dict", "[", "str", ",", "Any", "]", ")", ":", "return", "cls", "(", "meta_data", "=", "MetaData", ".", "from_buffer_data", "(", "buffer_data", ")", ",", "agent_data", "=", "AgentData", ".", ...
Create TrajectoryData from a simularium JSON dict containing buffers
[ "Create", "TrajectoryData", "from", "a", "simularium", "JSON", "dict", "containing", "buffers" ]
[ "\"\"\"\n Create TrajectoryData from a simularium JSON dict containing buffers\n \"\"\"" ]
[ { "param": "cls", "type": null }, { "param": "buffer_data", "type": "Dict[str, Any]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "buffer_data", "type": "Dict[str, Any]", "docstring": null, "do...
c8d44757193191510da694540c9538ff1594c5bc
allen-cell-animated/simularium-conversion
simulariumio/data_objects/trajectory_data.py
[ "Apache-2.0" ]
Python
append_agents
null
def append_agents(self, new_agents: AgentData): """ Concatenate the new AgentData with the current data, generate new unique IDs and type IDs as needed """ # create appropriate length buffer with current agents current_dimensions = self.agent_data.get_dimensions() ...
Concatenate the new AgentData with the current data, generate new unique IDs and type IDs as needed
Concatenate the new AgentData with the current data, generate new unique IDs and type IDs as needed
[ "Concatenate", "the", "new", "AgentData", "with", "the", "current", "data", "generate", "new", "unique", "IDs", "and", "type", "IDs", "as", "needed" ]
def append_agents(self, new_agents: AgentData): current_dimensions = self.agent_data.get_dimensions() added_dimensions = new_agents.get_dimensions() new_dimensions = current_dimensions.add(added_dimensions, axis=1) result = self.agent_data.check_increase_buffer_size( new_dime...
[ "def", "append_agents", "(", "self", ",", "new_agents", ":", "AgentData", ")", ":", "current_dimensions", "=", "self", ".", "agent_data", ".", "get_dimensions", "(", ")", "added_dimensions", "=", "new_agents", ".", "get_dimensions", "(", ")", "new_dimensions", "...
Concatenate the new AgentData with the current data, generate new unique IDs and type IDs as needed
[ "Concatenate", "the", "new", "AgentData", "with", "the", "current", "data", "generate", "new", "unique", "IDs", "and", "type", "IDs", "as", "needed" ]
[ "\"\"\"\n Concatenate the new AgentData with the current data,\n generate new unique IDs and type IDs as needed\n \"\"\"", "# create appropriate length buffer with current agents", "# add new agents", "# generate new unique IDs and type IDs so they don't overlap" ]
[ { "param": "self", "type": null }, { "param": "new_agents", "type": "AgentData" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "new_agents", "type": "AgentData", "docstring": null, "docstri...
4623bc8aac6f5c832645d02582e2f3a3da0d1291
allen-cell-animated/simularium-conversion
simulariumio/md/md_converter.py
[ "Apache-2.0" ]
Python
_read_universe_dimensions
AgentData
def _read_universe_dimensions( input_data: MdData, ) -> AgentData: """ Use a MD Universe to get the number of timesteps and maximum agents per timestep """ result = DimensionData( total_steps=0, max_agents=0, ) for ts in input_d...
Use a MD Universe to get the number of timesteps and maximum agents per timestep
Use a MD Universe to get the number of timesteps and maximum agents per timestep
[ "Use", "a", "MD", "Universe", "to", "get", "the", "number", "of", "timesteps", "and", "maximum", "agents", "per", "timestep" ]
def _read_universe_dimensions( input_data: MdData, ) -> AgentData: result = DimensionData( total_steps=0, max_agents=0, ) for ts in input_data.md_universe.trajectory[:: input_data.nth_timestep_to_read]: result.total_steps += 1 n_agents ...
[ "def", "_read_universe_dimensions", "(", "input_data", ":", "MdData", ",", ")", "->", "AgentData", ":", "result", "=", "DimensionData", "(", "total_steps", "=", "0", ",", "max_agents", "=", "0", ",", ")", "for", "ts", "in", "input_data", ".", "md_universe", ...
Use a MD Universe to get the number of timesteps and maximum agents per timestep
[ "Use", "a", "MD", "Universe", "to", "get", "the", "number", "of", "timesteps", "and", "maximum", "agents", "per", "timestep" ]
[ "\"\"\"\n Use a MD Universe to get the number of timesteps\n and maximum agents per timestep\n \"\"\"" ]
[ { "param": "input_data", "type": "MdData" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "input_data", "type": "MdData", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4623bc8aac6f5c832645d02582e2f3a3da0d1291
allen-cell-animated/simularium-conversion
simulariumio/md/md_converter.py
[ "Apache-2.0" ]
Python
_get_type_name
float
def _get_type_name(raw_type_name: str, input_data: MdData) -> float: """ Get the type_name to use for the particle with the given raw type_name """ if raw_type_name in input_data.display_data: return input_data.display_data[raw_type_name].name element_type = guess_ato...
Get the type_name to use for the particle with the given raw type_name
Get the type_name to use for the particle with the given raw type_name
[ "Get", "the", "type_name", "to", "use", "for", "the", "particle", "with", "the", "given", "raw", "type_name" ]
def _get_type_name(raw_type_name: str, input_data: MdData) -> float: if raw_type_name in input_data.display_data: return input_data.display_data[raw_type_name].name element_type = guess_atom_element(raw_type_name) if element_type in input_data.display_data: return input_d...
[ "def", "_get_type_name", "(", "raw_type_name", ":", "str", ",", "input_data", ":", "MdData", ")", "->", "float", ":", "if", "raw_type_name", "in", "input_data", ".", "display_data", ":", "return", "input_data", ".", "display_data", "[", "raw_type_name", "]", "...
Get the type_name to use for the particle with the given raw type_name
[ "Get", "the", "type_name", "to", "use", "for", "the", "particle", "with", "the", "given", "raw", "type_name" ]
[ "\"\"\"\n Get the type_name to use for the particle with the given raw type_name\n \"\"\"" ]
[ { "param": "raw_type_name", "type": "str" }, { "param": "input_data", "type": "MdData" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "raw_type_name", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "input_data", "type": "MdData", "docstring": null, "...