body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
66349065dfdc598c14ec732072388432ff66b859e2d9a6eb4475bba9176cff0f
def build(self, block: ListItemBlock, child_text: str) -> str: '\n リスト子要素のHTML文字列を組み立て\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: HTMLのliタグを含む文字列\n ' list_item = self.TEMPLATE.replace(self.INDENT_EXPRESSION, get_indent_text_from_depth(block.indent_depth)).replace(self.CLASSNAME_EXPRESSION, setting['class_name']['li']).replace(self.TEXT_EXPRESSION, child_text) return list_item
リスト子要素のHTML文字列を組み立て :param block: 組み立て元Block要素 :param child_text: 子要素文字列 :return: HTMLのliタグを含む文字列
app/html/block_builder.py
build
a-pompom/Python-markdownParser
0
python
def build(self, block: ListItemBlock, child_text: str) -> str: '\n リスト子要素のHTML文字列を組み立て\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: HTMLのliタグを含む文字列\n ' list_item = self.TEMPLATE.replace(self.INDENT_EXPRESSION, get_indent_text_from_depth(block.indent_depth)).replace(self.CLASSNAME_EXPRESSION, setting['class_name']['li']).replace(self.TEXT_EXPRESSION, child_text) return list_item
def build(self, block: ListItemBlock, child_text: str) -> str: '\n リスト子要素のHTML文字列を組み立て\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: HTMLのliタグを含む文字列\n ' list_item = self.TEMPLATE.replace(self.INDENT_EXPRESSION, get_indent_text_from_depth(block.indent_depth)).replace(self.CLASSNAME_EXPRESSION, setting['class_name']['li']).replace(self.TEXT_EXPRESSION, child_text) return list_item<|docstring|>リスト子要素のHTML文字列を組み立て :param block: 組み立て元Block要素 :param child_text: 子要素文字列 :return: HTMLのliタグを含む文字列<|endoftext|>
4d00d1e0ce3d9edcfffe188ef91d4a4e208386043bc7dab9b99bb8de1b23cefd
def build(self, block: CodeBlock, child_text: str) -> str: '\n コードブロック要素のHTML文字列を組み立て\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: HTMLのpre, codeタグを含む文字列\n ' language_class_name = setting['class_name_with_template']['code_block'].replace(self.LANGUAGE_EXPRESSION, block.language.lower()) code_block = self.TEMPLATE.replace(self.LANGUAGE_EXPRESSION, language_class_name).replace(self.TEXT_EXPRESSION, child_text) return code_block
コードブロック要素のHTML文字列を組み立て :param block: 組み立て元Block要素 :param child_text: 子要素文字列 :return: HTMLのpre, codeタグを含む文字列
app/html/block_builder.py
build
a-pompom/Python-markdownParser
0
python
def build(self, block: CodeBlock, child_text: str) -> str: '\n コードブロック要素のHTML文字列を組み立て\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: HTMLのpre, codeタグを含む文字列\n ' language_class_name = setting['class_name_with_template']['code_block'].replace(self.LANGUAGE_EXPRESSION, block.language.lower()) code_block = self.TEMPLATE.replace(self.LANGUAGE_EXPRESSION, language_class_name).replace(self.TEXT_EXPRESSION, child_text) return code_block
def build(self, block: CodeBlock, child_text: str) -> str: '\n コードブロック要素のHTML文字列を組み立て\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: HTMLのpre, codeタグを含む文字列\n ' language_class_name = setting['class_name_with_template']['code_block'].replace(self.LANGUAGE_EXPRESSION, block.language.lower()) code_block = self.TEMPLATE.replace(self.LANGUAGE_EXPRESSION, language_class_name).replace(self.TEXT_EXPRESSION, child_text) return code_block<|docstring|>コードブロック要素のHTML文字列を組み立て :param block: 組み立て元Block要素 :param child_text: 子要素文字列 :return: HTMLのpre, codeタグを含む文字列<|endoftext|>
9b9c0339947dd3f182687998fbbddc90626d23cf0a63e0ae214efde9ab3c663a
def build(self, block: HorizontalRuleBlock, child_text: str) -> str: '\n hrタグ文字列を組み立て\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: hrタグ文字列\n ' return self.TEMPLATE.replace(self.CLASSNAME_EXPRESSION, setting['class_name']['hr'])
hrタグ文字列を組み立て :param block: 組み立て元Block要素 :param child_text: 子要素文字列 :return: hrタグ文字列
app/html/block_builder.py
build
a-pompom/Python-markdownParser
0
python
def build(self, block: HorizontalRuleBlock, child_text: str) -> str: '\n hrタグ文字列を組み立て\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: hrタグ文字列\n ' return self.TEMPLATE.replace(self.CLASSNAME_EXPRESSION, setting['class_name']['hr'])
def build(self, block: HorizontalRuleBlock, child_text: str) -> str: '\n hrタグ文字列を組み立て\n\n :param block: 組み立て元Block要素\n :param child_text: 子要素文字列\n :return: hrタグ文字列\n ' return self.TEMPLATE.replace(self.CLASSNAME_EXPRESSION, setting['class_name']['hr'])<|docstring|>hrタグ文字列を組み立て :param block: 組み立て元Block要素 :param child_text: 子要素文字列 :return: hrタグ文字列<|endoftext|>
b52c0770adee2c129649d6a756e521cb6f7ddbefecd3253f49f30f84ac1a951f
def __init__(self): ' Constructor for the class ' super(ClocEagle) super().__init__() self.cmd = '' self.report_path = None
Constructor for the class
eaglevision/cloc_eagle.py
__init__
philips-software/EagleVision
0
python
def __init__(self): ' ' super(ClocEagle) super().__init__() self.cmd = self.report_path = None
def __init__(self): ' ' super(ClocEagle) super().__init__() self.cmd = self.report_path = None<|docstring|>Constructor for the class<|endoftext|>
8ede1a42205b24efbbb5793b7f852252736be1d312aab057a653c761666cba6e
def __cmd_builder(self): ' Function to form the cloc command to be executed ' args = '' if self.get_cloc_args(): args = self.get_cloc_args() file_out = os.path.join(self.report_path, 'cloc.csv') self.cmd = ('cloc "%s" --csv --out="%s" %s' % (self.get_proj_path().replace('\\', '/'), file_out.replace('\\', '/'), args)) print(self.cmd)
Function to form the cloc command to be executed
eaglevision/cloc_eagle.py
__cmd_builder
philips-software/EagleVision
0
python
def __cmd_builder(self): ' ' args = if self.get_cloc_args(): args = self.get_cloc_args() file_out = os.path.join(self.report_path, 'cloc.csv') self.cmd = ('cloc "%s" --csv --out="%s" %s' % (self.get_proj_path().replace('\\', '/'), file_out.replace('\\', '/'), args)) print(self.cmd)
def __cmd_builder(self): ' ' args = if self.get_cloc_args(): args = self.get_cloc_args() file_out = os.path.join(self.report_path, 'cloc.csv') self.cmd = ('cloc "%s" --csv --out="%s" %s' % (self.get_proj_path().replace('\\', '/'), file_out.replace('\\', '/'), args)) print(self.cmd)<|docstring|>Function to form the cloc command to be executed<|endoftext|>
09e1439204ec2a6b69fab6b395f6c7e7437eed11d29a2f35a006c3254692ebe5
def __write_cmd(self): ' Function to create a batch file to execute cloc ' file_out = open(os.path.join(self.report_path, 'cloc.cmd'), 'w') file_out.write(self.cmd) file_out.close()
Function to create a batch file to execute cloc
eaglevision/cloc_eagle.py
__write_cmd
philips-software/EagleVision
0
python
def __write_cmd(self): ' ' file_out = open(os.path.join(self.report_path, 'cloc.cmd'), 'w') file_out.write(self.cmd) file_out.close()
def __write_cmd(self): ' ' file_out = open(os.path.join(self.report_path, 'cloc.cmd'), 'w') file_out.write(self.cmd) file_out.close()<|docstring|>Function to create a batch file to execute cloc<|endoftext|>
9291c31c093ce909688436b947bd0fdcae84a26df5d7acdb049366222a7fa130
def __subprocess_out(self): ' Function to execute cloc command ' self.__write_cmd() status = subprocess.call(os.path.join(self.report_path, 'cloc.cmd')) if status: print('There was error while processing the sub process command') return status
Function to execute cloc command
eaglevision/cloc_eagle.py
__subprocess_out
philips-software/EagleVision
0
python
def __subprocess_out(self): ' ' self.__write_cmd() status = subprocess.call(os.path.join(self.report_path, 'cloc.cmd')) if status: print('There was error while processing the sub process command') return status
def __subprocess_out(self): ' ' self.__write_cmd() status = subprocess.call(os.path.join(self.report_path, 'cloc.cmd')) if status: print('There was error while processing the sub process command') return status<|docstring|>Function to execute cloc command<|endoftext|>
c459e6eff46e65c86074b8d630901a628c026b3cd193078e81732683f9d8aac2
def __report(self): ' Function to report the execution report of cloc' dataframe = pd.read_csv(os.path.join(self.report_path, 'cloc.csv')) dataframe.drop(dataframe.columns[(len(dataframe.columns) - 1)], axis=1, inplace=True) self.report_html(os.path.join(self.report_path, 'cloc-report.html'), dataframe, 'Cloc Report')
Function to report the execution report of cloc
eaglevision/cloc_eagle.py
__report
philips-software/EagleVision
0
python
def __report(self): ' ' dataframe = pd.read_csv(os.path.join(self.report_path, 'cloc.csv')) dataframe.drop(dataframe.columns[(len(dataframe.columns) - 1)], axis=1, inplace=True) self.report_html(os.path.join(self.report_path, 'cloc-report.html'), dataframe, 'Cloc Report')
def __report(self): ' ' dataframe = pd.read_csv(os.path.join(self.report_path, 'cloc.csv')) dataframe.drop(dataframe.columns[(len(dataframe.columns) - 1)], axis=1, inplace=True) self.report_html(os.path.join(self.report_path, 'cloc-report.html'), dataframe, 'Cloc Report')<|docstring|>Function to report the execution report of cloc<|endoftext|>
9bdbab8b04354cea70d899b39e67ab52191219abcf3685e65aae54762412e846
def __set_report_path(self): ' Function to set the report path' self.report_path = os.path.join(self.get_report_path(), 'cloc_report') Path(self.report_path).mkdir(parents=True, exist_ok=True)
Function to set the report path
eaglevision/cloc_eagle.py
__set_report_path
philips-software/EagleVision
0
python
def __set_report_path(self): ' ' self.report_path = os.path.join(self.get_report_path(), 'cloc_report') Path(self.report_path).mkdir(parents=True, exist_ok=True)
def __set_report_path(self): ' ' self.report_path = os.path.join(self.get_report_path(), 'cloc_report') Path(self.report_path).mkdir(parents=True, exist_ok=True)<|docstring|>Function to set the report path<|endoftext|>
b848a94a6dc612855edf7ecf3b30d6c0b87d754282aef1e23076d50bf1484cdd
def orchestrate_cloc(self, json): ' Function which orchestrate the cloc execution' print('\n\n=================================') print('Please wait while [Cloc analysis Tool] process your inputs') self.populate_data(json) self.__set_report_path() self.__cmd_builder() if (not self.__subprocess_out()): self.__report() print(('\n\n[Cloc analysis Tool] saved the reports @ %s' % self.report_path)) print('=================================')
Function which orchestrate the cloc execution
eaglevision/cloc_eagle.py
orchestrate_cloc
philips-software/EagleVision
0
python
def orchestrate_cloc(self, json): ' ' print('\n\n=================================') print('Please wait while [Cloc analysis Tool] process your inputs') self.populate_data(json) self.__set_report_path() self.__cmd_builder() if (not self.__subprocess_out()): self.__report() print(('\n\n[Cloc analysis Tool] saved the reports @ %s' % self.report_path)) print('=================================')
def orchestrate_cloc(self, json): ' ' print('\n\n=================================') print('Please wait while [Cloc analysis Tool] process your inputs') self.populate_data(json) self.__set_report_path() self.__cmd_builder() if (not self.__subprocess_out()): self.__report() print(('\n\n[Cloc analysis Tool] saved the reports @ %s' % self.report_path)) print('=================================')<|docstring|>Function which orchestrate the cloc execution<|endoftext|>
adf0c5834c47f7ed5192e76bfb756b557a1a225f538db8e74feffeb16da97f99
def get_fft_plan(a, shape=None, axes=None, value_type='C2C'): " Generate a CUDA FFT plan for transforming up to three axes.\n\n Args:\n a (cupy.ndarray): Array to be transform, assumed to be either C- or\n F- contiguous.\n shape (None or tuple of ints): Shape of the transformed axes of the\n output. If ``shape`` is not given, the lengths of the input along\n the axes specified by ``axes`` are used.\n axes (None or int or tuple of int): The axes of the array to\n transform. If `None`, it is assumed that all axes are transformed.\n\n Currently, for performing N-D transform these must be a set of up\n to three adjacent axes, and must include either the first or the\n last axis of the array.\n value_type ('C2C'): The FFT type to perform.\n Currently only complex-to-complex transforms are supported.\n\n Returns:\n plan: a cuFFT plan for either 1D transform (cupy.cuda.cufft.Plan1d)\n or N-D transform (cupy.cuda.cufft.PlanNd).\n " if a.flags.c_contiguous: order = 'C' elif a.flags.f_contiguous: order = 'F' else: raise ValueError('Input array a must be contiguous') if (axes is None): n = a.ndim axes = tuple((i for i in range(n))) if (n == 1): axis1D = 0 elif isinstance(axes, int): n = 1 axis1D = axes axes = (axes,) if ((axis1D >= a.ndim) or (axis1D < (- a.ndim))): raise ValueError('The chosen axis ({0}) exceeds the number of dimensions of a ({1})'.format(axis1D, a.ndim)) else: n = len(axes) if (n == 1): axis1D = axes[0] elif (n > 3): raise ValueError('Only up to three axes is supported') if isinstance(shape, int): shape = (shape,) if ((shape is not None) and (len(shape) != n)): raise ValueError('Shape and axes have different lengths.') transformed_shape = shape shape = list(a.shape) if (transformed_shape is not None): for (s, axis) in zip(transformed_shape, axes): shape[axis] = s shape = tuple(shape) fft_type = _convert_fft_type(a, value_type) if ((n > 1) and (fft_type not in [cufft.CUFFT_C2C, cufft.CUFFT_Z2Z])): raise NotImplementedError('Only C2C and Z2Z are supported for N-dim transform.') if (n > 1): plan = _get_cufft_plan_nd(shape, fft_type, axes=axes, order=order) else: out_size = shape[axis1D] batch = (prod(shape) // out_size) plan = cufft.Plan1d(out_size, fft_type, batch) return plan
Generate a CUDA FFT plan for transforming up to three axes. Args: a (cupy.ndarray): Array to be transform, assumed to be either C- or F- contiguous. shape (None or tuple of ints): Shape of the transformed axes of the output. If ``shape`` is not given, the lengths of the input along the axes specified by ``axes`` are used. axes (None or int or tuple of int): The axes of the array to transform. If `None`, it is assumed that all axes are transformed. Currently, for performing N-D transform these must be a set of up to three adjacent axes, and must include either the first or the last axis of the array. value_type ('C2C'): The FFT type to perform. Currently only complex-to-complex transforms are supported. Returns: plan: a cuFFT plan for either 1D transform (cupy.cuda.cufft.Plan1d) or N-D transform (cupy.cuda.cufft.PlanNd).
cupyx/scipy/fftpack/fft.py
get_fft_plan
darothen/cupy
1
python
def get_fft_plan(a, shape=None, axes=None, value_type='C2C'): " Generate a CUDA FFT plan for transforming up to three axes.\n\n Args:\n a (cupy.ndarray): Array to be transform, assumed to be either C- or\n F- contiguous.\n shape (None or tuple of ints): Shape of the transformed axes of the\n output. If ``shape`` is not given, the lengths of the input along\n the axes specified by ``axes`` are used.\n axes (None or int or tuple of int): The axes of the array to\n transform. If `None`, it is assumed that all axes are transformed.\n\n Currently, for performing N-D transform these must be a set of up\n to three adjacent axes, and must include either the first or the\n last axis of the array.\n value_type ('C2C'): The FFT type to perform.\n Currently only complex-to-complex transforms are supported.\n\n Returns:\n plan: a cuFFT plan for either 1D transform (cupy.cuda.cufft.Plan1d)\n or N-D transform (cupy.cuda.cufft.PlanNd).\n " if a.flags.c_contiguous: order = 'C' elif a.flags.f_contiguous: order = 'F' else: raise ValueError('Input array a must be contiguous') if (axes is None): n = a.ndim axes = tuple((i for i in range(n))) if (n == 1): axis1D = 0 elif isinstance(axes, int): n = 1 axis1D = axes axes = (axes,) if ((axis1D >= a.ndim) or (axis1D < (- a.ndim))): raise ValueError('The chosen axis ({0}) exceeds the number of dimensions of a ({1})'.format(axis1D, a.ndim)) else: n = len(axes) if (n == 1): axis1D = axes[0] elif (n > 3): raise ValueError('Only up to three axes is supported') if isinstance(shape, int): shape = (shape,) if ((shape is not None) and (len(shape) != n)): raise ValueError('Shape and axes have different lengths.') transformed_shape = shape shape = list(a.shape) if (transformed_shape is not None): for (s, axis) in zip(transformed_shape, axes): shape[axis] = s shape = tuple(shape) fft_type = _convert_fft_type(a, value_type) if ((n > 1) and (fft_type not in [cufft.CUFFT_C2C, cufft.CUFFT_Z2Z])): raise NotImplementedError('Only C2C and Z2Z are supported for N-dim transform.') if (n > 1): plan = _get_cufft_plan_nd(shape, fft_type, axes=axes, order=order) else: out_size = shape[axis1D] batch = (prod(shape) // out_size) plan = cufft.Plan1d(out_size, fft_type, batch) return plan
def get_fft_plan(a, shape=None, axes=None, value_type='C2C'): " Generate a CUDA FFT plan for transforming up to three axes.\n\n Args:\n a (cupy.ndarray): Array to be transform, assumed to be either C- or\n F- contiguous.\n shape (None or tuple of ints): Shape of the transformed axes of the\n output. If ``shape`` is not given, the lengths of the input along\n the axes specified by ``axes`` are used.\n axes (None or int or tuple of int): The axes of the array to\n transform. If `None`, it is assumed that all axes are transformed.\n\n Currently, for performing N-D transform these must be a set of up\n to three adjacent axes, and must include either the first or the\n last axis of the array.\n value_type ('C2C'): The FFT type to perform.\n Currently only complex-to-complex transforms are supported.\n\n Returns:\n plan: a cuFFT plan for either 1D transform (cupy.cuda.cufft.Plan1d)\n or N-D transform (cupy.cuda.cufft.PlanNd).\n " if a.flags.c_contiguous: order = 'C' elif a.flags.f_contiguous: order = 'F' else: raise ValueError('Input array a must be contiguous') if (axes is None): n = a.ndim axes = tuple((i for i in range(n))) if (n == 1): axis1D = 0 elif isinstance(axes, int): n = 1 axis1D = axes axes = (axes,) if ((axis1D >= a.ndim) or (axis1D < (- a.ndim))): raise ValueError('The chosen axis ({0}) exceeds the number of dimensions of a ({1})'.format(axis1D, a.ndim)) else: n = len(axes) if (n == 1): axis1D = axes[0] elif (n > 3): raise ValueError('Only up to three axes is supported') if isinstance(shape, int): shape = (shape,) if ((shape is not None) and (len(shape) != n)): raise ValueError('Shape and axes have different lengths.') transformed_shape = shape shape = list(a.shape) if (transformed_shape is not None): for (s, axis) in zip(transformed_shape, axes): shape[axis] = s shape = tuple(shape) fft_type = _convert_fft_type(a, value_type) if ((n > 1) and (fft_type not in [cufft.CUFFT_C2C, cufft.CUFFT_Z2Z])): raise NotImplementedError('Only C2C and Z2Z are supported for N-dim transform.') if (n > 1): plan = _get_cufft_plan_nd(shape, fft_type, axes=axes, order=order) else: out_size = shape[axis1D] batch = (prod(shape) // out_size) plan = cufft.Plan1d(out_size, fft_type, batch) return plan<|docstring|>Generate a CUDA FFT plan for transforming up to three axes. Args: a (cupy.ndarray): Array to be transform, assumed to be either C- or F- contiguous. shape (None or tuple of ints): Shape of the transformed axes of the output. If ``shape`` is not given, the lengths of the input along the axes specified by ``axes`` are used. axes (None or int or tuple of int): The axes of the array to transform. If `None`, it is assumed that all axes are transformed. Currently, for performing N-D transform these must be a set of up to three adjacent axes, and must include either the first or the last axis of the array. value_type ('C2C'): The FFT type to perform. Currently only complex-to-complex transforms are supported. Returns: plan: a cuFFT plan for either 1D transform (cupy.cuda.cufft.Plan1d) or N-D transform (cupy.cuda.cufft.PlanNd).<|endoftext|>
8eee6983c8302f106765ab8ace05295843d96159817826b2f2617065da467846
def fft(x, n=None, axis=(- 1), overwrite_x=False, plan=None): 'Compute the one-dimensional FFT.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n n (None or int): Length of the transformed axis of the output. If ``n``\n is not given, the length of the input along the axis specified by\n ``axis`` is used.\n axis (int): Axis over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n plan (cupy.cuda.cufft.Plan1d): a cuFFT plan for transforming ``x``\n over ``axis``, which can be obtained using::\n\n plan = cupyx.scipy.fftpack.get_fft_plan(x, axis)\n\n Note that `plan` is defaulted to None, meaning CuPy will use an\n auto-generated plan behind the scene.\n\n Returns:\n cupy.ndarray:\n The transformed array which shape is specified by ``n`` and type\n will convert to complex if that of the input is another.\n\n .. note::\n The argument `plan` is currently experimental and the interface may be\n changed in the future version.\n\n .. seealso:: :func:`scipy.fftpack.fft`\n ' return _fft(x, (n,), (axis,), None, cufft.CUFFT_FORWARD, overwrite_x=overwrite_x, plan=plan)
Compute the one-dimensional FFT. Args: x (cupy.ndarray): Array to be transformed. n (None or int): Length of the transformed axis of the output. If ``n`` is not given, the length of the input along the axis specified by ``axis`` is used. axis (int): Axis over which to compute the FFT. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (cupy.cuda.cufft.Plan1d): a cuFFT plan for transforming ``x`` over ``axis``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, axis) Note that `plan` is defaulted to None, meaning CuPy will use an auto-generated plan behind the scene. Returns: cupy.ndarray: The transformed array which shape is specified by ``n`` and type will convert to complex if that of the input is another. .. note:: The argument `plan` is currently experimental and the interface may be changed in the future version. .. seealso:: :func:`scipy.fftpack.fft`
cupyx/scipy/fftpack/fft.py
fft
darothen/cupy
1
python
def fft(x, n=None, axis=(- 1), overwrite_x=False, plan=None): 'Compute the one-dimensional FFT.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n n (None or int): Length of the transformed axis of the output. If ``n``\n is not given, the length of the input along the axis specified by\n ``axis`` is used.\n axis (int): Axis over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n plan (cupy.cuda.cufft.Plan1d): a cuFFT plan for transforming ``x``\n over ``axis``, which can be obtained using::\n\n plan = cupyx.scipy.fftpack.get_fft_plan(x, axis)\n\n Note that `plan` is defaulted to None, meaning CuPy will use an\n auto-generated plan behind the scene.\n\n Returns:\n cupy.ndarray:\n The transformed array which shape is specified by ``n`` and type\n will convert to complex if that of the input is another.\n\n .. note::\n The argument `plan` is currently experimental and the interface may be\n changed in the future version.\n\n .. seealso:: :func:`scipy.fftpack.fft`\n ' return _fft(x, (n,), (axis,), None, cufft.CUFFT_FORWARD, overwrite_x=overwrite_x, plan=plan)
def fft(x, n=None, axis=(- 1), overwrite_x=False, plan=None): 'Compute the one-dimensional FFT.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n n (None or int): Length of the transformed axis of the output. If ``n``\n is not given, the length of the input along the axis specified by\n ``axis`` is used.\n axis (int): Axis over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n plan (cupy.cuda.cufft.Plan1d): a cuFFT plan for transforming ``x``\n over ``axis``, which can be obtained using::\n\n plan = cupyx.scipy.fftpack.get_fft_plan(x, axis)\n\n Note that `plan` is defaulted to None, meaning CuPy will use an\n auto-generated plan behind the scene.\n\n Returns:\n cupy.ndarray:\n The transformed array which shape is specified by ``n`` and type\n will convert to complex if that of the input is another.\n\n .. note::\n The argument `plan` is currently experimental and the interface may be\n changed in the future version.\n\n .. seealso:: :func:`scipy.fftpack.fft`\n ' return _fft(x, (n,), (axis,), None, cufft.CUFFT_FORWARD, overwrite_x=overwrite_x, plan=plan)<|docstring|>Compute the one-dimensional FFT. Args: x (cupy.ndarray): Array to be transformed. n (None or int): Length of the transformed axis of the output. If ``n`` is not given, the length of the input along the axis specified by ``axis`` is used. axis (int): Axis over which to compute the FFT. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (cupy.cuda.cufft.Plan1d): a cuFFT plan for transforming ``x`` over ``axis``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, axis) Note that `plan` is defaulted to None, meaning CuPy will use an auto-generated plan behind the scene. Returns: cupy.ndarray: The transformed array which shape is specified by ``n`` and type will convert to complex if that of the input is another. .. note:: The argument `plan` is currently experimental and the interface may be changed in the future version. .. seealso:: :func:`scipy.fftpack.fft`<|endoftext|>
1b787742c9b06653b600ac52fbb71f543314951204d2dae9e6b5442cae0e4697
def ifft(x, n=None, axis=(- 1), overwrite_x=False, plan=None): 'Compute the one-dimensional inverse FFT.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n n (None or int): Length of the transformed axis of the output. If ``n``\n is not given, the length of the input along the axis specified by\n ``axis`` is used.\n axis (int): Axis over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n plan (cupy.cuda.cufft.Plan1d): a cuFFT plan for transforming ``x``\n over ``axis``, which can be obtained using::\n\n plan = cupyx.scipy.fftpack.get_fft_plan(x, axis)\n\n Note that `plan` is defaulted to None, meaning CuPy will use an\n auto-generated plan behind the scene.\n\n Returns:\n cupy.ndarray:\n The transformed array which shape is specified by ``n`` and type\n will convert to complex if that of the input is another.\n\n .. note::\n The argument `plan` is currently experimental and the interface may be\n changed in the future version.\n\n .. seealso:: :func:`scipy.fftpack.ifft`\n ' return _fft(x, (n,), (axis,), None, cufft.CUFFT_INVERSE, overwrite_x=overwrite_x, plan=plan)
Compute the one-dimensional inverse FFT. Args: x (cupy.ndarray): Array to be transformed. n (None or int): Length of the transformed axis of the output. If ``n`` is not given, the length of the input along the axis specified by ``axis`` is used. axis (int): Axis over which to compute the FFT. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (cupy.cuda.cufft.Plan1d): a cuFFT plan for transforming ``x`` over ``axis``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, axis) Note that `plan` is defaulted to None, meaning CuPy will use an auto-generated plan behind the scene. Returns: cupy.ndarray: The transformed array which shape is specified by ``n`` and type will convert to complex if that of the input is another. .. note:: The argument `plan` is currently experimental and the interface may be changed in the future version. .. seealso:: :func:`scipy.fftpack.ifft`
cupyx/scipy/fftpack/fft.py
ifft
darothen/cupy
1
python
def ifft(x, n=None, axis=(- 1), overwrite_x=False, plan=None): 'Compute the one-dimensional inverse FFT.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n n (None or int): Length of the transformed axis of the output. If ``n``\n is not given, the length of the input along the axis specified by\n ``axis`` is used.\n axis (int): Axis over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n plan (cupy.cuda.cufft.Plan1d): a cuFFT plan for transforming ``x``\n over ``axis``, which can be obtained using::\n\n plan = cupyx.scipy.fftpack.get_fft_plan(x, axis)\n\n Note that `plan` is defaulted to None, meaning CuPy will use an\n auto-generated plan behind the scene.\n\n Returns:\n cupy.ndarray:\n The transformed array which shape is specified by ``n`` and type\n will convert to complex if that of the input is another.\n\n .. note::\n The argument `plan` is currently experimental and the interface may be\n changed in the future version.\n\n .. seealso:: :func:`scipy.fftpack.ifft`\n ' return _fft(x, (n,), (axis,), None, cufft.CUFFT_INVERSE, overwrite_x=overwrite_x, plan=plan)
def ifft(x, n=None, axis=(- 1), overwrite_x=False, plan=None): 'Compute the one-dimensional inverse FFT.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n n (None or int): Length of the transformed axis of the output. If ``n``\n is not given, the length of the input along the axis specified by\n ``axis`` is used.\n axis (int): Axis over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n plan (cupy.cuda.cufft.Plan1d): a cuFFT plan for transforming ``x``\n over ``axis``, which can be obtained using::\n\n plan = cupyx.scipy.fftpack.get_fft_plan(x, axis)\n\n Note that `plan` is defaulted to None, meaning CuPy will use an\n auto-generated plan behind the scene.\n\n Returns:\n cupy.ndarray:\n The transformed array which shape is specified by ``n`` and type\n will convert to complex if that of the input is another.\n\n .. note::\n The argument `plan` is currently experimental and the interface may be\n changed in the future version.\n\n .. seealso:: :func:`scipy.fftpack.ifft`\n ' return _fft(x, (n,), (axis,), None, cufft.CUFFT_INVERSE, overwrite_x=overwrite_x, plan=plan)<|docstring|>Compute the one-dimensional inverse FFT. Args: x (cupy.ndarray): Array to be transformed. n (None or int): Length of the transformed axis of the output. If ``n`` is not given, the length of the input along the axis specified by ``axis`` is used. axis (int): Axis over which to compute the FFT. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (cupy.cuda.cufft.Plan1d): a cuFFT plan for transforming ``x`` over ``axis``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, axis) Note that `plan` is defaulted to None, meaning CuPy will use an auto-generated plan behind the scene. Returns: cupy.ndarray: The transformed array which shape is specified by ``n`` and type will convert to complex if that of the input is another. .. note:: The argument `plan` is currently experimental and the interface may be changed in the future version. .. seealso:: :func:`scipy.fftpack.ifft`<|endoftext|>
8d689103dcffd5110ecb6f241bdba65b4b11c49bd1a67f475ce3f5c23cc1a4c9
def fft2(x, shape=None, axes=((- 2), (- 1)), overwrite_x=False, plan=None): 'Compute the two-dimensional FFT.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n shape (None or tuple of ints): Shape of the transformed axes of the\n output. If ``shape`` is not given, the lengths of the input along\n the axes specified by ``axes`` are used.\n axes (tuple of ints): Axes over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x``\n over ``axes``, which can be obtained using::\n\n plan = cupyx.scipy.fftpack.get_fft_plan(x, axes)\n\n Note that `plan` is defaulted to None, meaning CuPy will either\n use an auto-generated plan behind the scene if cupy.fft.config.\n enable_nd_planning = True, or use no cuFFT plan if it is set to\n False.\n\n Returns:\n cupy.ndarray:\n The transformed array which shape is specified by ``shape`` and\n type will convert to complex if that of the input is another.\n\n .. seealso:: :func:`scipy.fftpack.fft2`\n\n .. note::\n The argument `plan` is currently experimental and the interface may be\n changed in the future version.\n ' func = _default_fft_func(x, shape, axes, plan) return func(x, shape, axes, None, cufft.CUFFT_FORWARD, overwrite_x=overwrite_x, plan=plan)
Compute the two-dimensional FFT. Args: x (cupy.ndarray): Array to be transformed. shape (None or tuple of ints): Shape of the transformed axes of the output. If ``shape`` is not given, the lengths of the input along the axes specified by ``axes`` are used. axes (tuple of ints): Axes over which to compute the FFT. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x`` over ``axes``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, axes) Note that `plan` is defaulted to None, meaning CuPy will either use an auto-generated plan behind the scene if cupy.fft.config. enable_nd_planning = True, or use no cuFFT plan if it is set to False. Returns: cupy.ndarray: The transformed array which shape is specified by ``shape`` and type will convert to complex if that of the input is another. .. seealso:: :func:`scipy.fftpack.fft2` .. note:: The argument `plan` is currently experimental and the interface may be changed in the future version.
cupyx/scipy/fftpack/fft.py
fft2
darothen/cupy
1
python
def fft2(x, shape=None, axes=((- 2), (- 1)), overwrite_x=False, plan=None): 'Compute the two-dimensional FFT.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n shape (None or tuple of ints): Shape of the transformed axes of the\n output. If ``shape`` is not given, the lengths of the input along\n the axes specified by ``axes`` are used.\n axes (tuple of ints): Axes over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x``\n over ``axes``, which can be obtained using::\n\n plan = cupyx.scipy.fftpack.get_fft_plan(x, axes)\n\n Note that `plan` is defaulted to None, meaning CuPy will either\n use an auto-generated plan behind the scene if cupy.fft.config.\n enable_nd_planning = True, or use no cuFFT plan if it is set to\n False.\n\n Returns:\n cupy.ndarray:\n The transformed array which shape is specified by ``shape`` and\n type will convert to complex if that of the input is another.\n\n .. seealso:: :func:`scipy.fftpack.fft2`\n\n .. note::\n The argument `plan` is currently experimental and the interface may be\n changed in the future version.\n ' func = _default_fft_func(x, shape, axes, plan) return func(x, shape, axes, None, cufft.CUFFT_FORWARD, overwrite_x=overwrite_x, plan=plan)
def fft2(x, shape=None, axes=((- 2), (- 1)), overwrite_x=False, plan=None): 'Compute the two-dimensional FFT.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n shape (None or tuple of ints): Shape of the transformed axes of the\n output. If ``shape`` is not given, the lengths of the input along\n the axes specified by ``axes`` are used.\n axes (tuple of ints): Axes over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x``\n over ``axes``, which can be obtained using::\n\n plan = cupyx.scipy.fftpack.get_fft_plan(x, axes)\n\n Note that `plan` is defaulted to None, meaning CuPy will either\n use an auto-generated plan behind the scene if cupy.fft.config.\n enable_nd_planning = True, or use no cuFFT plan if it is set to\n False.\n\n Returns:\n cupy.ndarray:\n The transformed array which shape is specified by ``shape`` and\n type will convert to complex if that of the input is another.\n\n .. seealso:: :func:`scipy.fftpack.fft2`\n\n .. note::\n The argument `plan` is currently experimental and the interface may be\n changed in the future version.\n ' func = _default_fft_func(x, shape, axes, plan) return func(x, shape, axes, None, cufft.CUFFT_FORWARD, overwrite_x=overwrite_x, plan=plan)<|docstring|>Compute the two-dimensional FFT. Args: x (cupy.ndarray): Array to be transformed. shape (None or tuple of ints): Shape of the transformed axes of the output. If ``shape`` is not given, the lengths of the input along the axes specified by ``axes`` are used. axes (tuple of ints): Axes over which to compute the FFT. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x`` over ``axes``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, axes) Note that `plan` is defaulted to None, meaning CuPy will either use an auto-generated plan behind the scene if cupy.fft.config. enable_nd_planning = True, or use no cuFFT plan if it is set to False. Returns: cupy.ndarray: The transformed array which shape is specified by ``shape`` and type will convert to complex if that of the input is another. .. seealso:: :func:`scipy.fftpack.fft2` .. note:: The argument `plan` is currently experimental and the interface may be changed in the future version.<|endoftext|>
cfe39bcb6f3a3cd53c963de0eec66f35978c47b268fb174c103b2d98d9dc5d4b
def ifft2(x, shape=None, axes=((- 2), (- 1)), overwrite_x=False, plan=None): 'Compute the two-dimensional inverse FFT.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n shape (None or tuple of ints): Shape of the transformed axes of the\n output. If ``shape`` is not given, the lengths of the input along\n the axes specified by ``axes`` are used.\n axes (tuple of ints): Axes over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x``\n over ``axes``, which can be obtained using::\n\n plan = cupyx.scipy.fftpack.get_fft_plan(x, axes)\n\n Note that `plan` is defaulted to None, meaning CuPy will either\n use an auto-generated plan behind the scene if cupy.fft.config.\n enable_nd_planning = True, or use no cuFFT plan if it is set to\n False.\n\n Returns:\n cupy.ndarray:\n The transformed array which shape is specified by ``shape`` and\n type will convert to complex if that of the input is another.\n\n .. seealso:: :func:`scipy.fftpack.ifft2`\n\n .. note::\n The argument `plan` is currently experimental and the interface may be\n changed in the future version.\n ' func = _default_fft_func(x, shape, axes, plan) return func(x, shape, axes, None, cufft.CUFFT_INVERSE, overwrite_x=overwrite_x, plan=plan)
Compute the two-dimensional inverse FFT. Args: x (cupy.ndarray): Array to be transformed. shape (None or tuple of ints): Shape of the transformed axes of the output. If ``shape`` is not given, the lengths of the input along the axes specified by ``axes`` are used. axes (tuple of ints): Axes over which to compute the FFT. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x`` over ``axes``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, axes) Note that `plan` is defaulted to None, meaning CuPy will either use an auto-generated plan behind the scene if cupy.fft.config. enable_nd_planning = True, or use no cuFFT plan if it is set to False. Returns: cupy.ndarray: The transformed array which shape is specified by ``shape`` and type will convert to complex if that of the input is another. .. seealso:: :func:`scipy.fftpack.ifft2` .. note:: The argument `plan` is currently experimental and the interface may be changed in the future version.
cupyx/scipy/fftpack/fft.py
ifft2
darothen/cupy
1
python
def ifft2(x, shape=None, axes=((- 2), (- 1)), overwrite_x=False, plan=None): 'Compute the two-dimensional inverse FFT.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n shape (None or tuple of ints): Shape of the transformed axes of the\n output. If ``shape`` is not given, the lengths of the input along\n the axes specified by ``axes`` are used.\n axes (tuple of ints): Axes over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x``\n over ``axes``, which can be obtained using::\n\n plan = cupyx.scipy.fftpack.get_fft_plan(x, axes)\n\n Note that `plan` is defaulted to None, meaning CuPy will either\n use an auto-generated plan behind the scene if cupy.fft.config.\n enable_nd_planning = True, or use no cuFFT plan if it is set to\n False.\n\n Returns:\n cupy.ndarray:\n The transformed array which shape is specified by ``shape`` and\n type will convert to complex if that of the input is another.\n\n .. seealso:: :func:`scipy.fftpack.ifft2`\n\n .. note::\n The argument `plan` is currently experimental and the interface may be\n changed in the future version.\n ' func = _default_fft_func(x, shape, axes, plan) return func(x, shape, axes, None, cufft.CUFFT_INVERSE, overwrite_x=overwrite_x, plan=plan)
def ifft2(x, shape=None, axes=((- 2), (- 1)), overwrite_x=False, plan=None): 'Compute the two-dimensional inverse FFT.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n shape (None or tuple of ints): Shape of the transformed axes of the\n output. If ``shape`` is not given, the lengths of the input along\n the axes specified by ``axes`` are used.\n axes (tuple of ints): Axes over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x``\n over ``axes``, which can be obtained using::\n\n plan = cupyx.scipy.fftpack.get_fft_plan(x, axes)\n\n Note that `plan` is defaulted to None, meaning CuPy will either\n use an auto-generated plan behind the scene if cupy.fft.config.\n enable_nd_planning = True, or use no cuFFT plan if it is set to\n False.\n\n Returns:\n cupy.ndarray:\n The transformed array which shape is specified by ``shape`` and\n type will convert to complex if that of the input is another.\n\n .. seealso:: :func:`scipy.fftpack.ifft2`\n\n .. note::\n The argument `plan` is currently experimental and the interface may be\n changed in the future version.\n ' func = _default_fft_func(x, shape, axes, plan) return func(x, shape, axes, None, cufft.CUFFT_INVERSE, overwrite_x=overwrite_x, plan=plan)<|docstring|>Compute the two-dimensional inverse FFT. Args: x (cupy.ndarray): Array to be transformed. shape (None or tuple of ints): Shape of the transformed axes of the output. If ``shape`` is not given, the lengths of the input along the axes specified by ``axes`` are used. axes (tuple of ints): Axes over which to compute the FFT. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x`` over ``axes``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, axes) Note that `plan` is defaulted to None, meaning CuPy will either use an auto-generated plan behind the scene if cupy.fft.config. enable_nd_planning = True, or use no cuFFT plan if it is set to False. Returns: cupy.ndarray: The transformed array which shape is specified by ``shape`` and type will convert to complex if that of the input is another. .. seealso:: :func:`scipy.fftpack.ifft2` .. note:: The argument `plan` is currently experimental and the interface may be changed in the future version.<|endoftext|>
346aee35b56c25f9319d7a4254f2e695dcdb0653866581294919a7c1da412bb9
def fftn(x, shape=None, axes=None, overwrite_x=False, plan=None): 'Compute the N-dimensional FFT.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n shape (None or tuple of ints): Shape of the transformed axes of the\n output. If ``shape`` is not given, the lengths of the input along\n the axes specified by ``axes`` are used.\n axes (tuple of ints): Axes over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x``\n over ``axes``, which can be obtained using::\n\n plan = cupyx.scipy.fftpack.get_fft_plan(x, axes)\n\n Note that `plan` is defaulted to None, meaning CuPy will either\n use an auto-generated plan behind the scene if cupy.fft.config.\n enable_nd_planning = True, or use no cuFFT plan if it is set to\n False.\n\n Returns:\n cupy.ndarray:\n The transformed array which shape is specified by ``shape`` and\n type will convert to complex if that of the input is another.\n\n .. seealso:: :func:`scipy.fftpack.fftn`\n\n .. note::\n The argument `plan` is currently experimental and the interface may be\n changed in the future version.\n ' func = _default_fft_func(x, shape, axes, plan) return func(x, shape, axes, None, cufft.CUFFT_FORWARD, overwrite_x=overwrite_x, plan=plan)
Compute the N-dimensional FFT. Args: x (cupy.ndarray): Array to be transformed. shape (None or tuple of ints): Shape of the transformed axes of the output. If ``shape`` is not given, the lengths of the input along the axes specified by ``axes`` are used. axes (tuple of ints): Axes over which to compute the FFT. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x`` over ``axes``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, axes) Note that `plan` is defaulted to None, meaning CuPy will either use an auto-generated plan behind the scene if cupy.fft.config. enable_nd_planning = True, or use no cuFFT plan if it is set to False. Returns: cupy.ndarray: The transformed array which shape is specified by ``shape`` and type will convert to complex if that of the input is another. .. seealso:: :func:`scipy.fftpack.fftn` .. note:: The argument `plan` is currently experimental and the interface may be changed in the future version.
cupyx/scipy/fftpack/fft.py
fftn
darothen/cupy
1
python
def fftn(x, shape=None, axes=None, overwrite_x=False, plan=None): 'Compute the N-dimensional FFT.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n shape (None or tuple of ints): Shape of the transformed axes of the\n output. If ``shape`` is not given, the lengths of the input along\n the axes specified by ``axes`` are used.\n axes (tuple of ints): Axes over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x``\n over ``axes``, which can be obtained using::\n\n plan = cupyx.scipy.fftpack.get_fft_plan(x, axes)\n\n Note that `plan` is defaulted to None, meaning CuPy will either\n use an auto-generated plan behind the scene if cupy.fft.config.\n enable_nd_planning = True, or use no cuFFT plan if it is set to\n False.\n\n Returns:\n cupy.ndarray:\n The transformed array which shape is specified by ``shape`` and\n type will convert to complex if that of the input is another.\n\n .. seealso:: :func:`scipy.fftpack.fftn`\n\n .. note::\n The argument `plan` is currently experimental and the interface may be\n changed in the future version.\n ' func = _default_fft_func(x, shape, axes, plan) return func(x, shape, axes, None, cufft.CUFFT_FORWARD, overwrite_x=overwrite_x, plan=plan)
def fftn(x, shape=None, axes=None, overwrite_x=False, plan=None): 'Compute the N-dimensional FFT.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n shape (None or tuple of ints): Shape of the transformed axes of the\n output. If ``shape`` is not given, the lengths of the input along\n the axes specified by ``axes`` are used.\n axes (tuple of ints): Axes over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x``\n over ``axes``, which can be obtained using::\n\n plan = cupyx.scipy.fftpack.get_fft_plan(x, axes)\n\n Note that `plan` is defaulted to None, meaning CuPy will either\n use an auto-generated plan behind the scene if cupy.fft.config.\n enable_nd_planning = True, or use no cuFFT plan if it is set to\n False.\n\n Returns:\n cupy.ndarray:\n The transformed array which shape is specified by ``shape`` and\n type will convert to complex if that of the input is another.\n\n .. seealso:: :func:`scipy.fftpack.fftn`\n\n .. note::\n The argument `plan` is currently experimental and the interface may be\n changed in the future version.\n ' func = _default_fft_func(x, shape, axes, plan) return func(x, shape, axes, None, cufft.CUFFT_FORWARD, overwrite_x=overwrite_x, plan=plan)<|docstring|>Compute the N-dimensional FFT. Args: x (cupy.ndarray): Array to be transformed. shape (None or tuple of ints): Shape of the transformed axes of the output. If ``shape`` is not given, the lengths of the input along the axes specified by ``axes`` are used. axes (tuple of ints): Axes over which to compute the FFT. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x`` over ``axes``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, axes) Note that `plan` is defaulted to None, meaning CuPy will either use an auto-generated plan behind the scene if cupy.fft.config. enable_nd_planning = True, or use no cuFFT plan if it is set to False. Returns: cupy.ndarray: The transformed array which shape is specified by ``shape`` and type will convert to complex if that of the input is another. .. seealso:: :func:`scipy.fftpack.fftn` .. note:: The argument `plan` is currently experimental and the interface may be changed in the future version.<|endoftext|>
2d002913041595f32afd06fa127bf951d1b42f7fe0d8e95d83f122b8683d4721
def ifftn(x, shape=None, axes=None, overwrite_x=False, plan=None): 'Compute the N-dimensional inverse FFT.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n shape (None or tuple of ints): Shape of the transformed axes of the\n output. If ``shape`` is not given, the lengths of the input along\n the axes specified by ``axes`` are used.\n axes (tuple of ints): Axes over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x``\n over ``axes``, which can be obtained using::\n\n plan = cupyx.scipy.fftpack.get_fft_plan(x, axes)\n\n Note that `plan` is defaulted to None, meaning CuPy will either\n use an auto-generated plan behind the scene if cupy.fft.config.\n enable_nd_planning = True, or use no cuFFT plan if it is set to\n False.\n\n Returns:\n cupy.ndarray:\n The transformed array which shape is specified by ``shape`` and\n type will convert to complex if that of the input is another.\n\n .. seealso:: :func:`scipy.fftpack.ifftn`\n\n .. note::\n The argument `plan` is currently experimental and the interface may be\n changed in the future version.\n ' func = _default_fft_func(x, shape, axes, plan) return func(x, shape, axes, None, cufft.CUFFT_INVERSE, overwrite_x=overwrite_x, plan=plan)
Compute the N-dimensional inverse FFT. Args: x (cupy.ndarray): Array to be transformed. shape (None or tuple of ints): Shape of the transformed axes of the output. If ``shape`` is not given, the lengths of the input along the axes specified by ``axes`` are used. axes (tuple of ints): Axes over which to compute the FFT. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x`` over ``axes``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, axes) Note that `plan` is defaulted to None, meaning CuPy will either use an auto-generated plan behind the scene if cupy.fft.config. enable_nd_planning = True, or use no cuFFT plan if it is set to False. Returns: cupy.ndarray: The transformed array which shape is specified by ``shape`` and type will convert to complex if that of the input is another. .. seealso:: :func:`scipy.fftpack.ifftn` .. note:: The argument `plan` is currently experimental and the interface may be changed in the future version.
cupyx/scipy/fftpack/fft.py
ifftn
darothen/cupy
1
python
def ifftn(x, shape=None, axes=None, overwrite_x=False, plan=None): 'Compute the N-dimensional inverse FFT.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n shape (None or tuple of ints): Shape of the transformed axes of the\n output. If ``shape`` is not given, the lengths of the input along\n the axes specified by ``axes`` are used.\n axes (tuple of ints): Axes over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x``\n over ``axes``, which can be obtained using::\n\n plan = cupyx.scipy.fftpack.get_fft_plan(x, axes)\n\n Note that `plan` is defaulted to None, meaning CuPy will either\n use an auto-generated plan behind the scene if cupy.fft.config.\n enable_nd_planning = True, or use no cuFFT plan if it is set to\n False.\n\n Returns:\n cupy.ndarray:\n The transformed array which shape is specified by ``shape`` and\n type will convert to complex if that of the input is another.\n\n .. seealso:: :func:`scipy.fftpack.ifftn`\n\n .. note::\n The argument `plan` is currently experimental and the interface may be\n changed in the future version.\n ' func = _default_fft_func(x, shape, axes, plan) return func(x, shape, axes, None, cufft.CUFFT_INVERSE, overwrite_x=overwrite_x, plan=plan)
def ifftn(x, shape=None, axes=None, overwrite_x=False, plan=None): 'Compute the N-dimensional inverse FFT.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n shape (None or tuple of ints): Shape of the transformed axes of the\n output. If ``shape`` is not given, the lengths of the input along\n the axes specified by ``axes`` are used.\n axes (tuple of ints): Axes over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x``\n over ``axes``, which can be obtained using::\n\n plan = cupyx.scipy.fftpack.get_fft_plan(x, axes)\n\n Note that `plan` is defaulted to None, meaning CuPy will either\n use an auto-generated plan behind the scene if cupy.fft.config.\n enable_nd_planning = True, or use no cuFFT plan if it is set to\n False.\n\n Returns:\n cupy.ndarray:\n The transformed array which shape is specified by ``shape`` and\n type will convert to complex if that of the input is another.\n\n .. seealso:: :func:`scipy.fftpack.ifftn`\n\n .. note::\n The argument `plan` is currently experimental and the interface may be\n changed in the future version.\n ' func = _default_fft_func(x, shape, axes, plan) return func(x, shape, axes, None, cufft.CUFFT_INVERSE, overwrite_x=overwrite_x, plan=plan)<|docstring|>Compute the N-dimensional inverse FFT. Args: x (cupy.ndarray): Array to be transformed. shape (None or tuple of ints): Shape of the transformed axes of the output. If ``shape`` is not given, the lengths of the input along the axes specified by ``axes`` are used. axes (tuple of ints): Axes over which to compute the FFT. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. plan (cupy.cuda.cufft.PlanNd): a cuFFT plan for transforming ``x`` over ``axes``, which can be obtained using:: plan = cupyx.scipy.fftpack.get_fft_plan(x, axes) Note that `plan` is defaulted to None, meaning CuPy will either use an auto-generated plan behind the scene if cupy.fft.config. enable_nd_planning = True, or use no cuFFT plan if it is set to False. Returns: cupy.ndarray: The transformed array which shape is specified by ``shape`` and type will convert to complex if that of the input is another. .. seealso:: :func:`scipy.fftpack.ifftn` .. note:: The argument `plan` is currently experimental and the interface may be changed in the future version.<|endoftext|>
fa38e34e2d076d1dde04c17f0df8fb53ca1571b3adf16d5190db3244b6e31600
def rfft(x, n=None, axis=(- 1), overwrite_x=False): 'Compute the one-dimensional FFT for real input.\n\n The returned real array contains\n\n .. code-block:: python\n\n [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2))] # if n is even\n [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2)),Im(y(n/2))] # if n is odd\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n n (None or int): Length of the transformed axis of the output. If ``n``\n is not given, the length of the input along the axis specified by\n ``axis`` is used.\n axis (int): Axis over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n\n Returns:\n cupy.ndarray:\n The transformed array.\n\n .. seealso:: :func:`scipy.fftpack.rfft`\n ' if (n is None): n = x.shape[axis] shape = list(x.shape) shape[axis] = n f = _fft(x, (n,), (axis,), None, cufft.CUFFT_FORWARD, 'R2C', overwrite_x=overwrite_x) z = cupy.empty(shape, f.real.dtype) slice_z = ([slice(None)] * x.ndim) slice_f = ([slice(None)] * x.ndim) slice_z[axis] = slice(1) slice_f[axis] = slice(1) z[slice_z] = f[slice_f].real slice_z[axis] = slice(1, None, 2) slice_f[axis] = slice(1, None) z[slice_z] = f[slice_f].real slice_z[axis] = slice(2, None, 2) slice_f[axis] = slice(1, ((n - f.shape[axis]) + 1)) z[slice_z] = f[slice_f].imag return z
Compute the one-dimensional FFT for real input. The returned real array contains .. code-block:: python [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2))] # if n is even [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2)),Im(y(n/2))] # if n is odd Args: x (cupy.ndarray): Array to be transformed. n (None or int): Length of the transformed axis of the output. If ``n`` is not given, the length of the input along the axis specified by ``axis`` is used. axis (int): Axis over which to compute the FFT. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. Returns: cupy.ndarray: The transformed array. .. seealso:: :func:`scipy.fftpack.rfft`
cupyx/scipy/fftpack/fft.py
rfft
darothen/cupy
1
python
def rfft(x, n=None, axis=(- 1), overwrite_x=False): 'Compute the one-dimensional FFT for real input.\n\n The returned real array contains\n\n .. code-block:: python\n\n [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2))] # if n is even\n [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2)),Im(y(n/2))] # if n is odd\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n n (None or int): Length of the transformed axis of the output. If ``n``\n is not given, the length of the input along the axis specified by\n ``axis`` is used.\n axis (int): Axis over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n\n Returns:\n cupy.ndarray:\n The transformed array.\n\n .. seealso:: :func:`scipy.fftpack.rfft`\n ' if (n is None): n = x.shape[axis] shape = list(x.shape) shape[axis] = n f = _fft(x, (n,), (axis,), None, cufft.CUFFT_FORWARD, 'R2C', overwrite_x=overwrite_x) z = cupy.empty(shape, f.real.dtype) slice_z = ([slice(None)] * x.ndim) slice_f = ([slice(None)] * x.ndim) slice_z[axis] = slice(1) slice_f[axis] = slice(1) z[slice_z] = f[slice_f].real slice_z[axis] = slice(1, None, 2) slice_f[axis] = slice(1, None) z[slice_z] = f[slice_f].real slice_z[axis] = slice(2, None, 2) slice_f[axis] = slice(1, ((n - f.shape[axis]) + 1)) z[slice_z] = f[slice_f].imag return z
def rfft(x, n=None, axis=(- 1), overwrite_x=False): 'Compute the one-dimensional FFT for real input.\n\n The returned real array contains\n\n .. code-block:: python\n\n [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2))] # if n is even\n [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2)),Im(y(n/2))] # if n is odd\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n n (None or int): Length of the transformed axis of the output. If ``n``\n is not given, the length of the input along the axis specified by\n ``axis`` is used.\n axis (int): Axis over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n\n Returns:\n cupy.ndarray:\n The transformed array.\n\n .. seealso:: :func:`scipy.fftpack.rfft`\n ' if (n is None): n = x.shape[axis] shape = list(x.shape) shape[axis] = n f = _fft(x, (n,), (axis,), None, cufft.CUFFT_FORWARD, 'R2C', overwrite_x=overwrite_x) z = cupy.empty(shape, f.real.dtype) slice_z = ([slice(None)] * x.ndim) slice_f = ([slice(None)] * x.ndim) slice_z[axis] = slice(1) slice_f[axis] = slice(1) z[slice_z] = f[slice_f].real slice_z[axis] = slice(1, None, 2) slice_f[axis] = slice(1, None) z[slice_z] = f[slice_f].real slice_z[axis] = slice(2, None, 2) slice_f[axis] = slice(1, ((n - f.shape[axis]) + 1)) z[slice_z] = f[slice_f].imag return z<|docstring|>Compute the one-dimensional FFT for real input. The returned real array contains .. code-block:: python [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2))] # if n is even [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2)),Im(y(n/2))] # if n is odd Args: x (cupy.ndarray): Array to be transformed. n (None or int): Length of the transformed axis of the output. If ``n`` is not given, the length of the input along the axis specified by ``axis`` is used. axis (int): Axis over which to compute the FFT. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. Returns: cupy.ndarray: The transformed array. .. seealso:: :func:`scipy.fftpack.rfft`<|endoftext|>
b0e8b42affc829997e7c5a6f46d97d91abcb5e5588cb08938d088392fb1f45ee
def irfft(x, n=None, axis=(- 1), overwrite_x=False): 'Compute the one-dimensional inverse FFT for real input.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n n (None or int): Length of the transformed axis of the output. If ``n``\n is not given, the length of the input along the axis specified by\n ``axis`` is used.\n axis (int): Axis over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n\n Returns:\n cupy.ndarray:\n The transformed array.\n\n .. seealso:: :func:`scipy.fftpack.irfft`\n ' if (n is None): n = x.shape[axis] m = min(n, x.shape[axis]) shape = list(x.shape) shape[axis] = ((n // 2) + 1) if (x.dtype in (cupy.float16, cupy.float32)): z = cupy.zeros(shape, dtype=cupy.complex64) else: z = cupy.zeros(shape, dtype=cupy.complex128) slice_x = ([slice(None)] * x.ndim) slice_z = ([slice(None)] * x.ndim) slice_x[axis] = slice(1) slice_z[axis] = slice(1) z[slice_z].real = x[slice_x] slice_x[axis] = slice(1, m, 2) slice_z[axis] = slice(1, ((m // 2) + 1)) z[slice_z].real = x[slice_x] slice_x[axis] = slice(2, m, 2) slice_z[axis] = slice(1, ((m + 1) // 2)) z[slice_z].imag = x[slice_x] return _fft(z, (n,), (axis,), None, cufft.CUFFT_INVERSE, 'C2R', overwrite_x=overwrite_x)
Compute the one-dimensional inverse FFT for real input. Args: x (cupy.ndarray): Array to be transformed. n (None or int): Length of the transformed axis of the output. If ``n`` is not given, the length of the input along the axis specified by ``axis`` is used. axis (int): Axis over which to compute the FFT. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. Returns: cupy.ndarray: The transformed array. .. seealso:: :func:`scipy.fftpack.irfft`
cupyx/scipy/fftpack/fft.py
irfft
darothen/cupy
1
python
def irfft(x, n=None, axis=(- 1), overwrite_x=False): 'Compute the one-dimensional inverse FFT for real input.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n n (None or int): Length of the transformed axis of the output. If ``n``\n is not given, the length of the input along the axis specified by\n ``axis`` is used.\n axis (int): Axis over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n\n Returns:\n cupy.ndarray:\n The transformed array.\n\n .. seealso:: :func:`scipy.fftpack.irfft`\n ' if (n is None): n = x.shape[axis] m = min(n, x.shape[axis]) shape = list(x.shape) shape[axis] = ((n // 2) + 1) if (x.dtype in (cupy.float16, cupy.float32)): z = cupy.zeros(shape, dtype=cupy.complex64) else: z = cupy.zeros(shape, dtype=cupy.complex128) slice_x = ([slice(None)] * x.ndim) slice_z = ([slice(None)] * x.ndim) slice_x[axis] = slice(1) slice_z[axis] = slice(1) z[slice_z].real = x[slice_x] slice_x[axis] = slice(1, m, 2) slice_z[axis] = slice(1, ((m // 2) + 1)) z[slice_z].real = x[slice_x] slice_x[axis] = slice(2, m, 2) slice_z[axis] = slice(1, ((m + 1) // 2)) z[slice_z].imag = x[slice_x] return _fft(z, (n,), (axis,), None, cufft.CUFFT_INVERSE, 'C2R', overwrite_x=overwrite_x)
def irfft(x, n=None, axis=(- 1), overwrite_x=False): 'Compute the one-dimensional inverse FFT for real input.\n\n Args:\n x (cupy.ndarray): Array to be transformed.\n n (None or int): Length of the transformed axis of the output. If ``n``\n is not given, the length of the input along the axis specified by\n ``axis`` is used.\n axis (int): Axis over which to compute the FFT.\n overwrite_x (bool): If True, the contents of ``x`` can be destroyed.\n\n Returns:\n cupy.ndarray:\n The transformed array.\n\n .. seealso:: :func:`scipy.fftpack.irfft`\n ' if (n is None): n = x.shape[axis] m = min(n, x.shape[axis]) shape = list(x.shape) shape[axis] = ((n // 2) + 1) if (x.dtype in (cupy.float16, cupy.float32)): z = cupy.zeros(shape, dtype=cupy.complex64) else: z = cupy.zeros(shape, dtype=cupy.complex128) slice_x = ([slice(None)] * x.ndim) slice_z = ([slice(None)] * x.ndim) slice_x[axis] = slice(1) slice_z[axis] = slice(1) z[slice_z].real = x[slice_x] slice_x[axis] = slice(1, m, 2) slice_z[axis] = slice(1, ((m // 2) + 1)) z[slice_z].real = x[slice_x] slice_x[axis] = slice(2, m, 2) slice_z[axis] = slice(1, ((m + 1) // 2)) z[slice_z].imag = x[slice_x] return _fft(z, (n,), (axis,), None, cufft.CUFFT_INVERSE, 'C2R', overwrite_x=overwrite_x)<|docstring|>Compute the one-dimensional inverse FFT for real input. Args: x (cupy.ndarray): Array to be transformed. n (None or int): Length of the transformed axis of the output. If ``n`` is not given, the length of the input along the axis specified by ``axis`` is used. axis (int): Axis over which to compute the FFT. overwrite_x (bool): If True, the contents of ``x`` can be destroyed. Returns: cupy.ndarray: The transformed array. .. seealso:: :func:`scipy.fftpack.irfft`<|endoftext|>
cbcd50bff1f0e060f5bfee14cde9f41da3684a5c903c6ab6336e8dfb64284238
async def initialize_usb(self, port=None, baudrate=230400, writeChunkMaxSize=0): '\n writing in chunks solves issues writing to certain JLink chips. A max chunkSize of 64 was found to work well for our case.\n For normal usage with Crownstones this is not required.\n writeChunkMaxSize of 0 will not send the payload in chunks\n :param port:\n :param baudrate:\n :param writeChunkMaxSize:\n :return:\n ' self.uartManager.config(port, baudrate, writeChunkMaxSize) result = [False] def handleMessage(result, data): result[0] = True event = UartEventBus.subscribe(SystemTopics.connectionEstablished, (lambda data: handleMessage(result, data))) self.uartManager.start() while ((not result[0]) and self.running): (await asyncio.sleep(0.1)) UartEventBus.unsubscribe(event)
writing in chunks solves issues writing to certain JLink chips. A max chunkSize of 64 was found to work well for our case. For normal usage with Crownstones this is not required. writeChunkMaxSize of 0 will not send the payload in chunks :param port: :param baudrate: :param writeChunkMaxSize: :return:
crownstone_uart/core/CrownstoneUart.py
initialize_usb
RicArch97/crownstone-lib-python-uart
0
python
async def initialize_usb(self, port=None, baudrate=230400, writeChunkMaxSize=0): '\n writing in chunks solves issues writing to certain JLink chips. A max chunkSize of 64 was found to work well for our case.\n For normal usage with Crownstones this is not required.\n writeChunkMaxSize of 0 will not send the payload in chunks\n :param port:\n :param baudrate:\n :param writeChunkMaxSize:\n :return:\n ' self.uartManager.config(port, baudrate, writeChunkMaxSize) result = [False] def handleMessage(result, data): result[0] = True event = UartEventBus.subscribe(SystemTopics.connectionEstablished, (lambda data: handleMessage(result, data))) self.uartManager.start() while ((not result[0]) and self.running): (await asyncio.sleep(0.1)) UartEventBus.unsubscribe(event)
async def initialize_usb(self, port=None, baudrate=230400, writeChunkMaxSize=0): '\n writing in chunks solves issues writing to certain JLink chips. A max chunkSize of 64 was found to work well for our case.\n For normal usage with Crownstones this is not required.\n writeChunkMaxSize of 0 will not send the payload in chunks\n :param port:\n :param baudrate:\n :param writeChunkMaxSize:\n :return:\n ' self.uartManager.config(port, baudrate, writeChunkMaxSize) result = [False] def handleMessage(result, data): result[0] = True event = UartEventBus.subscribe(SystemTopics.connectionEstablished, (lambda data: handleMessage(result, data))) self.uartManager.start() while ((not result[0]) and self.running): (await asyncio.sleep(0.1)) UartEventBus.unsubscribe(event)<|docstring|>writing in chunks solves issues writing to certain JLink chips. A max chunkSize of 64 was found to work well for our case. For normal usage with Crownstones this is not required. writeChunkMaxSize of 0 will not send the payload in chunks :param port: :param baudrate: :param writeChunkMaxSize: :return:<|endoftext|>
77c9fe1d6c1421c714f8ae2157bd1a36d1770a2731c0f3f4bdd7e88196053dec
def initialize_usb_sync(self, port=None, baudrate=230400, writeChunkMaxSize=0): '\n writing in chunks solves issues writing to certain JLink chips. A max chunkSize of 64 was found to work well for our case.\n For normal usage with Crownstones this is not required.\n writeChunkMaxSize of 0 will not send the payload in chunks\n :param port:\n :param baudrate:\n :param writeChunkMaxSize:\n :return:\n ' self.uartManager.config(port, baudrate, writeChunkMaxSize) result = [False] def handleMessage(result, data): result[0] = True event = UartEventBus.subscribe(SystemTopics.connectionEstablished, (lambda data: handleMessage(result, data))) self.uartManager.start() try: while ((not result[0]) and self.running): time.sleep(0.1) except KeyboardInterrupt: print('\nClosing Crownstone Uart.... Thanks for your time!') self.stop() UartEventBus.unsubscribe(event)
writing in chunks solves issues writing to certain JLink chips. A max chunkSize of 64 was found to work well for our case. For normal usage with Crownstones this is not required. writeChunkMaxSize of 0 will not send the payload in chunks :param port: :param baudrate: :param writeChunkMaxSize: :return:
crownstone_uart/core/CrownstoneUart.py
initialize_usb_sync
RicArch97/crownstone-lib-python-uart
0
python
def initialize_usb_sync(self, port=None, baudrate=230400, writeChunkMaxSize=0): '\n writing in chunks solves issues writing to certain JLink chips. A max chunkSize of 64 was found to work well for our case.\n For normal usage with Crownstones this is not required.\n writeChunkMaxSize of 0 will not send the payload in chunks\n :param port:\n :param baudrate:\n :param writeChunkMaxSize:\n :return:\n ' self.uartManager.config(port, baudrate, writeChunkMaxSize) result = [False] def handleMessage(result, data): result[0] = True event = UartEventBus.subscribe(SystemTopics.connectionEstablished, (lambda data: handleMessage(result, data))) self.uartManager.start() try: while ((not result[0]) and self.running): time.sleep(0.1) except KeyboardInterrupt: print('\nClosing Crownstone Uart.... Thanks for your time!') self.stop() UartEventBus.unsubscribe(event)
def initialize_usb_sync(self, port=None, baudrate=230400, writeChunkMaxSize=0): '\n writing in chunks solves issues writing to certain JLink chips. A max chunkSize of 64 was found to work well for our case.\n For normal usage with Crownstones this is not required.\n writeChunkMaxSize of 0 will not send the payload in chunks\n :param port:\n :param baudrate:\n :param writeChunkMaxSize:\n :return:\n ' self.uartManager.config(port, baudrate, writeChunkMaxSize) result = [False] def handleMessage(result, data): result[0] = True event = UartEventBus.subscribe(SystemTopics.connectionEstablished, (lambda data: handleMessage(result, data))) self.uartManager.start() try: while ((not result[0]) and self.running): time.sleep(0.1) except KeyboardInterrupt: print('\nClosing Crownstone Uart.... Thanks for your time!') self.stop() UartEventBus.unsubscribe(event)<|docstring|>writing in chunks solves issues writing to certain JLink chips. A max chunkSize of 64 was found to work well for our case. For normal usage with Crownstones this is not required. writeChunkMaxSize of 0 will not send the payload in chunks :param port: :param baudrate: :param writeChunkMaxSize: :return:<|endoftext|>
b6017f4046284fe320993659a1de14b295a01728125694c4f975c4988491a104
def switch_crownstone(self, crownstoneId: int, on: bool): '\n :param crownstoneId:\n :param on: Boolean\n :return:\n ' if (not on): self.mesh.turn_crownstone_off(crownstoneId) else: self.mesh.turn_crownstone_on(crownstoneId)
:param crownstoneId: :param on: Boolean :return:
crownstone_uart/core/CrownstoneUart.py
switch_crownstone
RicArch97/crownstone-lib-python-uart
0
python
def switch_crownstone(self, crownstoneId: int, on: bool): '\n :param crownstoneId:\n :param on: Boolean\n :return:\n ' if (not on): self.mesh.turn_crownstone_off(crownstoneId) else: self.mesh.turn_crownstone_on(crownstoneId)
def switch_crownstone(self, crownstoneId: int, on: bool): '\n :param crownstoneId:\n :param on: Boolean\n :return:\n ' if (not on): self.mesh.turn_crownstone_off(crownstoneId) else: self.mesh.turn_crownstone_on(crownstoneId)<|docstring|>:param crownstoneId: :param on: Boolean :return:<|endoftext|>
8e9f8258771e3ba2221f3c910c7947b7a520fd07165c234e8c8bf4de2c48e83b
def dim_crownstone(self, crownstoneId: int, switchVal: int): '\n :param crownstoneId:\n :param switchVal: 0% .. 100% or special values (SwitchValSpecial).\n :return:\n ' self.mesh.set_crownstone_switch(crownstoneId, switchVal)
:param crownstoneId: :param switchVal: 0% .. 100% or special values (SwitchValSpecial). :return:
crownstone_uart/core/CrownstoneUart.py
dim_crownstone
RicArch97/crownstone-lib-python-uart
0
python
def dim_crownstone(self, crownstoneId: int, switchVal: int): '\n :param crownstoneId:\n :param switchVal: 0% .. 100% or special values (SwitchValSpecial).\n :return:\n ' self.mesh.set_crownstone_switch(crownstoneId, switchVal)
def dim_crownstone(self, crownstoneId: int, switchVal: int): '\n :param crownstoneId:\n :param switchVal: 0% .. 100% or special values (SwitchValSpecial).\n :return:\n ' self.mesh.set_crownstone_switch(crownstoneId, switchVal)<|docstring|>:param crownstoneId: :param switchVal: 0% .. 100% or special values (SwitchValSpecial). :return:<|endoftext|>
881b8ef4ffa9a6e256344290795197079fd4ffa97d762668c86192c1f2b65f8d
def add_documents(self, matched_files, **kwargs): ' adds new documents to the lingotek cloud and, after prompting user, overwrites changed documents that\n have already been added ' metadata = copy.deepcopy(self.default_metadata) if (('metadata' in kwargs) and kwargs['metadata']): metadata = self.metadata_wizard() elif self.metadata_prompt: if yes_no_prompt('Would you like to launch the metadata wizard?', default_yes=True): metadata = self.metadata_wizard() confirmed = False for file_name in matched_files: try: relative_path = self.norm_path(file_name) title = os.path.basename(relative_path) try: if (os.stat(os.path.join(self.path, relative_path)).st_size == 0): logger.info('This document is empty and was not added: {0}\n'.format(title)) continue except FileNotFoundError: logger.warning('Warning: could not verify that {0} is not empty'.format(relative_path)) except Exception as e: raise e if (not self.doc_manager.is_doc_new(relative_path)): if (self.doc_manager.is_doc_modified(relative_path, self.path) or (len(metadata) > 0)): if (('overwrite' in kwargs) and kwargs['overwrite']): confirmed = True try: if (not confirmed): option = yes_no_prompt("Document '{0}' already exists. Would you like to overwrite it?".format(title), default_yes=False) else: option = True if option: logger.info("Overwriting document '{0}' in Lingotek Cloud...\n".format(title)) self.update_document_action(file_name, title, doc_metadata=metadata, **kwargs) continue else: logger.info("Will not overwrite document '{0}' in Lingotek Cloud\n".format(title)) continue except KeyboardInterrupt: logger.error('Canceled adding the document') return else: logger.error('This document has already been added and no metadata is being sent: {0}\n'.format(title)) continue except json.decoder.JSONDecodeError: logger.error('JSON error on adding document.') except Exception: logger.error('Error adding document') else: self.add_document(file_name, title, doc_metadata=metadata, **kwargs)
adds new documents to the lingotek cloud and, after prompting user, overwrites changed documents that have already been added
python3/ltk/actions/add_action.py
add_documents
Lingotek/filesystem-connector
11
python
def add_documents(self, matched_files, **kwargs): ' adds new documents to the lingotek cloud and, after prompting user, overwrites changed documents that\n have already been added ' metadata = copy.deepcopy(self.default_metadata) if (('metadata' in kwargs) and kwargs['metadata']): metadata = self.metadata_wizard() elif self.metadata_prompt: if yes_no_prompt('Would you like to launch the metadata wizard?', default_yes=True): metadata = self.metadata_wizard() confirmed = False for file_name in matched_files: try: relative_path = self.norm_path(file_name) title = os.path.basename(relative_path) try: if (os.stat(os.path.join(self.path, relative_path)).st_size == 0): logger.info('This document is empty and was not added: {0}\n'.format(title)) continue except FileNotFoundError: logger.warning('Warning: could not verify that {0} is not empty'.format(relative_path)) except Exception as e: raise e if (not self.doc_manager.is_doc_new(relative_path)): if (self.doc_manager.is_doc_modified(relative_path, self.path) or (len(metadata) > 0)): if (('overwrite' in kwargs) and kwargs['overwrite']): confirmed = True try: if (not confirmed): option = yes_no_prompt("Document '{0}' already exists. Would you like to overwrite it?".format(title), default_yes=False) else: option = True if option: logger.info("Overwriting document '{0}' in Lingotek Cloud...\n".format(title)) self.update_document_action(file_name, title, doc_metadata=metadata, **kwargs) continue else: logger.info("Will not overwrite document '{0}' in Lingotek Cloud\n".format(title)) continue except KeyboardInterrupt: logger.error('Canceled adding the document') return else: logger.error('This document has already been added and no metadata is being sent: {0}\n'.format(title)) continue except json.decoder.JSONDecodeError: logger.error('JSON error on adding document.') except Exception: logger.error('Error adding document') else: self.add_document(file_name, title, doc_metadata=metadata, **kwargs)
def add_documents(self, matched_files, **kwargs): ' adds new documents to the lingotek cloud and, after prompting user, overwrites changed documents that\n have already been added ' metadata = copy.deepcopy(self.default_metadata) if (('metadata' in kwargs) and kwargs['metadata']): metadata = self.metadata_wizard() elif self.metadata_prompt: if yes_no_prompt('Would you like to launch the metadata wizard?', default_yes=True): metadata = self.metadata_wizard() confirmed = False for file_name in matched_files: try: relative_path = self.norm_path(file_name) title = os.path.basename(relative_path) try: if (os.stat(os.path.join(self.path, relative_path)).st_size == 0): logger.info('This document is empty and was not added: {0}\n'.format(title)) continue except FileNotFoundError: logger.warning('Warning: could not verify that {0} is not empty'.format(relative_path)) except Exception as e: raise e if (not self.doc_manager.is_doc_new(relative_path)): if (self.doc_manager.is_doc_modified(relative_path, self.path) or (len(metadata) > 0)): if (('overwrite' in kwargs) and kwargs['overwrite']): confirmed = True try: if (not confirmed): option = yes_no_prompt("Document '{0}' already exists. Would you like to overwrite it?".format(title), default_yes=False) else: option = True if option: logger.info("Overwriting document '{0}' in Lingotek Cloud...\n".format(title)) self.update_document_action(file_name, title, doc_metadata=metadata, **kwargs) continue else: logger.info("Will not overwrite document '{0}' in Lingotek Cloud\n".format(title)) continue except KeyboardInterrupt: logger.error('Canceled adding the document') return else: logger.error('This document has already been added and no metadata is being sent: {0}\n'.format(title)) continue except json.decoder.JSONDecodeError: logger.error('JSON error on adding document.') except Exception: logger.error('Error adding document') else: self.add_document(file_name, title, doc_metadata=metadata, **kwargs)<|docstring|>adds new documents to the lingotek cloud and, after prompting user, overwrites changed documents that have already been added<|endoftext|>
d49283c006ee1e3cedf4c37e70f862cf263e8361b52b4d4f870a3c64e4337c23
def add_folders(self, file_patterns): ' checks each file pattern for a directory and adds matching patterns to the db ' ' returns true if folder(s) have been added, otherwise false ' added_folder = False for pattern in file_patterns: if os.path.exists(pattern): if os.path.isdir(pattern): if self.is_hidden_file(pattern): logger.warning('Folder is hidden') elif (not self._is_folder_added(pattern)): self.folder_manager.add_folder(self.norm_path(pattern.rstrip(os.sep))) logger.info(('Added folder ' + str(pattern))) else: logger.warning((('Folder ' + str(pattern)) + ' has already been added.\n')) added_folder = True else: logger.warning((('Path "' + str(pattern)) + '" doesn\'t exist.\n')) return added_folder
checks each file pattern for a directory and adds matching patterns to the db
python3/ltk/actions/add_action.py
add_folders
Lingotek/filesystem-connector
11
python
def add_folders(self, file_patterns): ' ' ' returns true if folder(s) have been added, otherwise false ' added_folder = False for pattern in file_patterns: if os.path.exists(pattern): if os.path.isdir(pattern): if self.is_hidden_file(pattern): logger.warning('Folder is hidden') elif (not self._is_folder_added(pattern)): self.folder_manager.add_folder(self.norm_path(pattern.rstrip(os.sep))) logger.info(('Added folder ' + str(pattern))) else: logger.warning((('Folder ' + str(pattern)) + ' has already been added.\n')) added_folder = True else: logger.warning((('Path "' + str(pattern)) + '" doesn\'t exist.\n')) return added_folder
def add_folders(self, file_patterns): ' ' ' returns true if folder(s) have been added, otherwise false ' added_folder = False for pattern in file_patterns: if os.path.exists(pattern): if os.path.isdir(pattern): if self.is_hidden_file(pattern): logger.warning('Folder is hidden') elif (not self._is_folder_added(pattern)): self.folder_manager.add_folder(self.norm_path(pattern.rstrip(os.sep))) logger.info(('Added folder ' + str(pattern))) else: logger.warning((('Folder ' + str(pattern)) + ' has already been added.\n')) added_folder = True else: logger.warning((('Path "' + str(pattern)) + '" doesn\'t exist.\n')) return added_folder<|docstring|>checks each file pattern for a directory and adds matching patterns to the db<|endoftext|>
6d08f186b389d467aa0d675a3ca532dd7e0c20d2e82e0d65909ee3d3aefb9a24
def _is_folder_added(self, file_name): ' checks if a folder has been added or is a subfolder of an added folder ' folder_names = self.folder_manager.get_file_names() for folder in folder_names: if (os.path.join(self.path, folder) in os.path.abspath(file_name)): return True return False
checks if a folder has been added or is a subfolder of an added folder
python3/ltk/actions/add_action.py
_is_folder_added
Lingotek/filesystem-connector
11
python
def _is_folder_added(self, file_name): ' ' folder_names = self.folder_manager.get_file_names() for folder in folder_names: if (os.path.join(self.path, folder) in os.path.abspath(file_name)): return True return False
def _is_folder_added(self, file_name): ' ' folder_names = self.folder_manager.get_file_names() for folder in folder_names: if (os.path.join(self.path, folder) in os.path.abspath(file_name)): return True return False<|docstring|>checks if a folder has been added or is a subfolder of an added folder<|endoftext|>
80643d07f03c111594e71f55fb228b9bfc4430eda6dea27081218cb6446adfdc
@fill_doc def read_raw(fname, *, preload=False, verbose=None, **kwargs): 'Read raw file.\n\n Parameters\n ----------\n fname : str\n File name to load.\n %(preload)s\n %(verbose)s\n **kwargs\n Keyword arguments to pass to the underlying reader. For details, see\n the arguments of the reader for the underlying file format.\n\n Returns\n -------\n raw : mne.io.Raw\n Raw object.\n\n Notes\n -----\n This function is a wrapper for specific read_raw_xxx readers defined in the\n readers dict. If it does not work with a specific file, try using a\n dedicated reader function (read_raw_xxx) instead.\n ' ext = ''.join(Path(fname).suffixes) if (ext in readers): return readers[ext](fname, preload=preload, verbose=verbose, **kwargs) else: _read_unsupported(fname)
Read raw file. Parameters ---------- fname : str File name to load. %(preload)s %(verbose)s **kwargs Keyword arguments to pass to the underlying reader. For details, see the arguments of the reader for the underlying file format. Returns ------- raw : mne.io.Raw Raw object. Notes ----- This function is a wrapper for specific read_raw_xxx readers defined in the readers dict. If it does not work with a specific file, try using a dedicated reader function (read_raw_xxx) instead.
mne/io/_read_raw.py
read_raw
johnsam7/mne-python
3
python
@fill_doc def read_raw(fname, *, preload=False, verbose=None, **kwargs): 'Read raw file.\n\n Parameters\n ----------\n fname : str\n File name to load.\n %(preload)s\n %(verbose)s\n **kwargs\n Keyword arguments to pass to the underlying reader. For details, see\n the arguments of the reader for the underlying file format.\n\n Returns\n -------\n raw : mne.io.Raw\n Raw object.\n\n Notes\n -----\n This function is a wrapper for specific read_raw_xxx readers defined in the\n readers dict. If it does not work with a specific file, try using a\n dedicated reader function (read_raw_xxx) instead.\n ' ext = .join(Path(fname).suffixes) if (ext in readers): return readers[ext](fname, preload=preload, verbose=verbose, **kwargs) else: _read_unsupported(fname)
@fill_doc def read_raw(fname, *, preload=False, verbose=None, **kwargs): 'Read raw file.\n\n Parameters\n ----------\n fname : str\n File name to load.\n %(preload)s\n %(verbose)s\n **kwargs\n Keyword arguments to pass to the underlying reader. For details, see\n the arguments of the reader for the underlying file format.\n\n Returns\n -------\n raw : mne.io.Raw\n Raw object.\n\n Notes\n -----\n This function is a wrapper for specific read_raw_xxx readers defined in the\n readers dict. If it does not work with a specific file, try using a\n dedicated reader function (read_raw_xxx) instead.\n ' ext = .join(Path(fname).suffixes) if (ext in readers): return readers[ext](fname, preload=preload, verbose=verbose, **kwargs) else: _read_unsupported(fname)<|docstring|>Read raw file. Parameters ---------- fname : str File name to load. %(preload)s %(verbose)s **kwargs Keyword arguments to pass to the underlying reader. For details, see the arguments of the reader for the underlying file format. Returns ------- raw : mne.io.Raw Raw object. Notes ----- This function is a wrapper for specific read_raw_xxx readers defined in the readers dict. If it does not work with a specific file, try using a dedicated reader function (read_raw_xxx) instead.<|endoftext|>
00a377cc62606955e235657eb9618837e2740d38f22b340e16723b0d64eea40d
def mkdir_p(path): '\n Create a directory similar to mkdir -p\n ' try: os.makedirs(path) except OSError as exc: if ((exc.errno == errno.EEXIST) and os.path.isdir(path)): pass else: raise
Create a directory similar to mkdir -p
examples/traductor/traductor/traductor.py
mkdir_p
connectthefuture/docker-hacks
5
python
def mkdir_p(path): '\n \n ' try: os.makedirs(path) except OSError as exc: if ((exc.errno == errno.EEXIST) and os.path.isdir(path)): pass else: raise
def mkdir_p(path): '\n \n ' try: os.makedirs(path) except OSError as exc: if ((exc.errno == errno.EEXIST) and os.path.isdir(path)): pass else: raise<|docstring|>Create a directory similar to mkdir -p<|endoftext|>
0ae3d702773e1eef007e6cc4717922aa4ba373ed95c4453a1ebe8f32a75d4b19
def underscore_to_camelcase(value): '\n Translate a snake_case to CamelCase\n ' def upperfirst(x): return (x[0].upper() + x[1:]) def camelcase(): (yield str.lower) while True: (yield str.capitalize) c = camelcase() return upperfirst(''.join(((c.next()(x) if x else '_') for x in value.split('_'))))
Translate a snake_case to CamelCase
examples/traductor/traductor/traductor.py
underscore_to_camelcase
connectthefuture/docker-hacks
5
python
def underscore_to_camelcase(value): '\n \n ' def upperfirst(x): return (x[0].upper() + x[1:]) def camelcase(): (yield str.lower) while True: (yield str.capitalize) c = camelcase() return upperfirst(.join(((c.next()(x) if x else '_') for x in value.split('_'))))
def underscore_to_camelcase(value): '\n \n ' def upperfirst(x): return (x[0].upper() + x[1:]) def camelcase(): (yield str.lower) while True: (yield str.capitalize) c = camelcase() return upperfirst(.join(((c.next()(x) if x else '_') for x in value.split('_'))))<|docstring|>Translate a snake_case to CamelCase<|endoftext|>
b4b8a2e79ea720ae79fe08022880c92eaf6bf3ea98c3b1cf7c094a1790ded533
def _parse_yaml_from_files(self, files): '\n Convert the given docker-compose files into python objects\n ' docker_services = {} for file in files: with open(file, 'r') as stream: services_set = yaml.load(stream) for (service_name, service_specs) in services_set.iteritems(): docker_services[service_name] = service_specs return docker_services
Convert the given docker-compose files into python objects
examples/traductor/traductor/traductor.py
_parse_yaml_from_files
connectthefuture/docker-hacks
5
python
def _parse_yaml_from_files(self, files): '\n \n ' docker_services = {} for file in files: with open(file, 'r') as stream: services_set = yaml.load(stream) for (service_name, service_specs) in services_set.iteritems(): docker_services[service_name] = service_specs return docker_services
def _parse_yaml_from_files(self, files): '\n \n ' docker_services = {} for file in files: with open(file, 'r') as stream: services_set = yaml.load(stream) for (service_name, service_specs) in services_set.iteritems(): docker_services[service_name] = service_specs return docker_services<|docstring|>Convert the given docker-compose files into python objects<|endoftext|>
be21f37cde3a3e3f7adcf1746b5417950248f87a2e430538ccfad77774e3b2de
def _translate_to_run_template_vars(self, service_name, service_specs): '\n Translate each docker-compose service into docker run cli command\n ' image = '' options = '' command = '' if ('image' in service_specs): image = service_specs['image'] del service_specs['image'] if ('command' in service_specs): command = service_specs['command'] del service_specs['command'] for (attr_name, attr_value) in service_specs.iteritems(): translator = None try: module = importlib.import_module(('traductor.translators.%s' % attr_name)) translator = getattr(module, underscore_to_camelcase(attr_name)) translator = translator() except AttributeError: print(('The docker-compose command "%s" is either not valid or is not ' + ('supported as a run command' % attr_name))) continue options = ('%s %s' % (options, translator.translate(attr_value))) return {'service': {'name': underscore_to_camelcase(service_name), 'description': ('%s service' % service_name), 'image': image, 'options': options, 'command': command}}
Translate each docker-compose service into docker run cli command
examples/traductor/traductor/traductor.py
_translate_to_run_template_vars
connectthefuture/docker-hacks
5
python
def _translate_to_run_template_vars(self, service_name, service_specs): '\n \n ' image = options = command = if ('image' in service_specs): image = service_specs['image'] del service_specs['image'] if ('command' in service_specs): command = service_specs['command'] del service_specs['command'] for (attr_name, attr_value) in service_specs.iteritems(): translator = None try: module = importlib.import_module(('traductor.translators.%s' % attr_name)) translator = getattr(module, underscore_to_camelcase(attr_name)) translator = translator() except AttributeError: print(('The docker-compose command "%s" is either not valid or is not ' + ('supported as a run command' % attr_name))) continue options = ('%s %s' % (options, translator.translate(attr_value))) return {'service': {'name': underscore_to_camelcase(service_name), 'description': ('%s service' % service_name), 'image': image, 'options': options, 'command': command}}
def _translate_to_run_template_vars(self, service_name, service_specs): '\n \n ' image = options = command = if ('image' in service_specs): image = service_specs['image'] del service_specs['image'] if ('command' in service_specs): command = service_specs['command'] del service_specs['command'] for (attr_name, attr_value) in service_specs.iteritems(): translator = None try: module = importlib.import_module(('traductor.translators.%s' % attr_name)) translator = getattr(module, underscore_to_camelcase(attr_name)) translator = translator() except AttributeError: print(('The docker-compose command "%s" is either not valid or is not ' + ('supported as a run command' % attr_name))) continue options = ('%s %s' % (options, translator.translate(attr_value))) return {'service': {'name': underscore_to_camelcase(service_name), 'description': ('%s service' % service_name), 'image': image, 'options': options, 'command': command}}<|docstring|>Translate each docker-compose service into docker run cli command<|endoftext|>
b13243f5a5b64e54e758b2c0e9a4cadcf56ebd9e3055141ad7cc5b9ea68590dc
def _generate_service(self, service_name, template_vars, destination_folder): '\n Create a systemd service file using template vars\n ' template_loader = jinja2.FileSystemLoader(searchpath='/') template_env = jinja2.Environment(loader=template_loader) template_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates/systemd.jinja2.service') template = template_env.get_template(template_file) output_text = template.render(template_vars) mkdir_p(destination_folder) print(output_text, file=open(os.path.join(destination_folder, ('%s.service' % service_name)), 'w')) return output_text
Create a systemd service file using template vars
examples/traductor/traductor/traductor.py
_generate_service
connectthefuture/docker-hacks
5
python
def _generate_service(self, service_name, template_vars, destination_folder): '\n \n ' template_loader = jinja2.FileSystemLoader(searchpath='/') template_env = jinja2.Environment(loader=template_loader) template_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates/systemd.jinja2.service') template = template_env.get_template(template_file) output_text = template.render(template_vars) mkdir_p(destination_folder) print(output_text, file=open(os.path.join(destination_folder, ('%s.service' % service_name)), 'w')) return output_text
def _generate_service(self, service_name, template_vars, destination_folder): '\n \n ' template_loader = jinja2.FileSystemLoader(searchpath='/') template_env = jinja2.Environment(loader=template_loader) template_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates/systemd.jinja2.service') template = template_env.get_template(template_file) output_text = template.render(template_vars) mkdir_p(destination_folder) print(output_text, file=open(os.path.join(destination_folder, ('%s.service' % service_name)), 'w')) return output_text<|docstring|>Create a systemd service file using template vars<|endoftext|>
2e94ee403ea3d088ac310f9ff559a7ac53ab8e95c6fd4e0fa36008831728282a
def __init__(self): '\n Initialise Cli\n ' parser = argparse.ArgumentParser(description=('Translate docker-compose templates to process' + ' manage service files (systemd currently supported).')) parser.add_argument('-d', '--dest', dest='dest', default='./', help='Destination for generated systemd service files (default: ./)') parser.add_argument('-f', '--file', dest='file', action='append', help='Specify docker-compose files (default: docker-compose.yml)') args = parser.parse_args() if (not args.file): args.file = ['docker-compose.yml'] Traductor().translate(files=args.file, destination=args.dest)
Initialise Cli
examples/traductor/traductor/traductor.py
__init__
connectthefuture/docker-hacks
5
python
def __init__(self): '\n \n ' parser = argparse.ArgumentParser(description=('Translate docker-compose templates to process' + ' manage service files (systemd currently supported).')) parser.add_argument('-d', '--dest', dest='dest', default='./', help='Destination for generated systemd service files (default: ./)') parser.add_argument('-f', '--file', dest='file', action='append', help='Specify docker-compose files (default: docker-compose.yml)') args = parser.parse_args() if (not args.file): args.file = ['docker-compose.yml'] Traductor().translate(files=args.file, destination=args.dest)
def __init__(self): '\n \n ' parser = argparse.ArgumentParser(description=('Translate docker-compose templates to process' + ' manage service files (systemd currently supported).')) parser.add_argument('-d', '--dest', dest='dest', default='./', help='Destination for generated systemd service files (default: ./)') parser.add_argument('-f', '--file', dest='file', action='append', help='Specify docker-compose files (default: docker-compose.yml)') args = parser.parse_args() if (not args.file): args.file = ['docker-compose.yml'] Traductor().translate(files=args.file, destination=args.dest)<|docstring|>Initialise Cli<|endoftext|>
81ab2fc1d3b837ebcdcfcf7933e4ecd0e7459cc084e58a4b59c9dc40325f3896
def __init__(self, n_clases=1000): ' init the model with hyper-parameters etc ' self.x = tf.placeholder(tf.float32, shape=[None, None, None, 3]) self.y = tf.placeholder(tf.float32, shape=[]) pass
init the model with hyper-parameters etc
model.py
__init__
slippy0/AppraisalNet
0
python
def __init__(self, n_clases=1000): ' ' self.x = tf.placeholder(tf.float32, shape=[None, None, None, 3]) self.y = tf.placeholder(tf.float32, shape=[]) pass
def __init__(self, n_clases=1000): ' ' self.x = tf.placeholder(tf.float32, shape=[None, None, None, 3]) self.y = tf.placeholder(tf.float32, shape=[]) pass<|docstring|>init the model with hyper-parameters etc<|endoftext|>
5003dbf462c3d1a8925bf81a107ddda804cee63a7cc82ea3410b8043087af849
def inference(self, x): ' This is the forward calculation from x to y ' return some_op(x, name='inference')
This is the forward calculation from x to y
model.py
inference
slippy0/AppraisalNet
0
python
def inference(self, x): ' ' return some_op(x, name='inference')
def inference(self, x): ' ' return some_op(x, name='inference')<|docstring|>This is the forward calculation from x to y<|endoftext|>
fe78924bfe8c99398f0783795c17bbd62939f7693e6385b04cf57dd044ee559e
def test_generate_nonsense_word(self): 'Test case for generate_nonsense_word\n\n Generate Nonsense Word # noqa: E501\n ' pass
Test case for generate_nonsense_word Generate Nonsense Word # noqa: E501
python/test/test_other_api.py
test_generate_nonsense_word
ddsky/humor-api-clients
0
python
def test_generate_nonsense_word(self): 'Test case for generate_nonsense_word\n\n Generate Nonsense Word # noqa: E501\n ' pass
def test_generate_nonsense_word(self): 'Test case for generate_nonsense_word\n\n Generate Nonsense Word # noqa: E501\n ' pass<|docstring|>Test case for generate_nonsense_word Generate Nonsense Word # noqa: E501<|endoftext|>
1c62cb77c5384cd3a3eb0ecb2d258d0a2701203071ed5a297862f448961fef66
def test_insult(self): 'Test case for insult\n\n Insult # noqa: E501\n ' pass
Test case for insult Insult # noqa: E501
python/test/test_other_api.py
test_insult
ddsky/humor-api-clients
0
python
def test_insult(self): 'Test case for insult\n\n Insult # noqa: E501\n ' pass
def test_insult(self): 'Test case for insult\n\n Insult # noqa: E501\n ' pass<|docstring|>Test case for insult Insult # noqa: E501<|endoftext|>
4ad76f929588c3878811788c1713f33c73e9745f377e6980e6f21194f84b816d
def test_praise(self): 'Test case for praise\n\n Praise # noqa: E501\n ' pass
Test case for praise Praise # noqa: E501
python/test/test_other_api.py
test_praise
ddsky/humor-api-clients
0
python
def test_praise(self): 'Test case for praise\n\n Praise # noqa: E501\n ' pass
def test_praise(self): 'Test case for praise\n\n Praise # noqa: E501\n ' pass<|docstring|>Test case for praise Praise # noqa: E501<|endoftext|>
819a076237d5f314afae4a69f25240358a0277bb6e679ea1841cad46b4530679
def test_rate_word(self): 'Test case for rate_word\n\n Rate Word # noqa: E501\n ' pass
Test case for rate_word Rate Word # noqa: E501
python/test/test_other_api.py
test_rate_word
ddsky/humor-api-clients
0
python
def test_rate_word(self): 'Test case for rate_word\n\n Rate Word # noqa: E501\n ' pass
def test_rate_word(self): 'Test case for rate_word\n\n Rate Word # noqa: E501\n ' pass<|docstring|>Test case for rate_word Rate Word # noqa: E501<|endoftext|>
857eeaa3f68b70033036ab409aceeae54b709bf93820a8ba367a513db935d438
def test_search_gifs(self): 'Test case for search_gifs\n\n Search Gifs # noqa: E501\n ' pass
Test case for search_gifs Search Gifs # noqa: E501
python/test/test_other_api.py
test_search_gifs
ddsky/humor-api-clients
0
python
def test_search_gifs(self): 'Test case for search_gifs\n\n Search Gifs # noqa: E501\n ' pass
def test_search_gifs(self): 'Test case for search_gifs\n\n Search Gifs # noqa: E501\n ' pass<|docstring|>Test case for search_gifs Search Gifs # noqa: E501<|endoftext|>
2bbd432ac6e94aff4d0e6b1a53df705b0dbc6fdc708adf53a462c366b7dd03a5
def parse_sgf_coords(s): 'Interprets coords. aa is top left corner; sa is top right corner' if ((s is None) or (s == '')): return None return (SGF_COLUMNS.index(s[1]), SGF_COLUMNS.index(s[0]))
Interprets coords. aa is top left corner; sa is top right corner
utils/utilities.py
parse_sgf_coords
firstlight1/private
325
python
def parse_sgf_coords(s): if ((s is None) or (s == )): return None return (SGF_COLUMNS.index(s[1]), SGF_COLUMNS.index(s[0]))
def parse_sgf_coords(s): if ((s is None) or (s == )): return None return (SGF_COLUMNS.index(s[1]), SGF_COLUMNS.index(s[0]))<|docstring|>Interprets coords. aa is top left corner; sa is top right corner<|endoftext|>
e04d60365a13be735d5f315cd8d32851a785f244ab1b0d0393f3664631ed4009
def parse_kgs_coords(s): 'Interprets coords. A1 is bottom left; A9 is top left.' if (s == 'pass'): return None s = s.upper() col = KGS_COLUMNS.index(s[0]) row_from_bottom = (int(s[1:]) - 1) return (((go.N - row_from_bottom) - 1), col)
Interprets coords. A1 is bottom left; A9 is top left.
utils/utilities.py
parse_kgs_coords
firstlight1/private
325
python
def parse_kgs_coords(s): if (s == 'pass'): return None s = s.upper() col = KGS_COLUMNS.index(s[0]) row_from_bottom = (int(s[1:]) - 1) return (((go.N - row_from_bottom) - 1), col)
def parse_kgs_coords(s): if (s == 'pass'): return None s = s.upper() col = KGS_COLUMNS.index(s[0]) row_from_bottom = (int(s[1:]) - 1) return (((go.N - row_from_bottom) - 1), col)<|docstring|>Interprets coords. A1 is bottom left; A9 is top left.<|endoftext|>
f715a5dcc1e1e771c4290213e51e4fd82e99c3e21ee0dacf989c47e810ada906
def parse_pygtp_coords(vertex): 'Interprets coords. (1, 1) is bottom left; (1, 9) is top left.' if (vertex in (gtp.PASS, gtp.RESIGN)): return None return ((go.N - vertex[1]), (vertex[0] - 1))
Interprets coords. (1, 1) is bottom left; (1, 9) is top left.
utils/utilities.py
parse_pygtp_coords
firstlight1/private
325
python
def parse_pygtp_coords(vertex): if (vertex in (gtp.PASS, gtp.RESIGN)): return None return ((go.N - vertex[1]), (vertex[0] - 1))
def parse_pygtp_coords(vertex): if (vertex in (gtp.PASS, gtp.RESIGN)): return None return ((go.N - vertex[1]), (vertex[0] - 1))<|docstring|>Interprets coords. (1, 1) is bottom left; (1, 9) is top left.<|endoftext|>
7946bb7275c681641e9d772cd0d4f9461d2e204a0e4303831d0f25777d69b5e5
def doublewrap(function): '\n A decorator decorator, allowing to use the decorator to be used without\n parentheses if not arguments are provided. All arguments must be optional.\n ' @functools.wraps(function) def decorator(*args, **kwargs): if ((len(args) == 1) and (len(kwargs) == 0) and callable(args[0])): return function(args[0]) else: return (lambda wrapee: function(wrapee, *args, **kwargs)) return decorator
A decorator decorator, allowing to use the decorator to be used without parentheses if not arguments are provided. All arguments must be optional.
utils/utilities.py
doublewrap
firstlight1/private
325
python
def doublewrap(function): '\n A decorator decorator, allowing to use the decorator to be used without\n parentheses if not arguments are provided. All arguments must be optional.\n ' @functools.wraps(function) def decorator(*args, **kwargs): if ((len(args) == 1) and (len(kwargs) == 0) and callable(args[0])): return function(args[0]) else: return (lambda wrapee: function(wrapee, *args, **kwargs)) return decorator
def doublewrap(function): '\n A decorator decorator, allowing to use the decorator to be used without\n parentheses if not arguments are provided. All arguments must be optional.\n ' @functools.wraps(function) def decorator(*args, **kwargs): if ((len(args) == 1) and (len(kwargs) == 0) and callable(args[0])): return function(args[0]) else: return (lambda wrapee: function(wrapee, *args, **kwargs)) return decorator<|docstring|>A decorator decorator, allowing to use the decorator to be used without parentheses if not arguments are provided. All arguments must be optional.<|endoftext|>
0eafd53a864c835ac7c73c562d56c4feca7c2fd0694061d37ed5e9f7c6d751d6
@doublewrap def define_scope(function, scope=None, *args, **kwargs): '\n A decorator for functions that define TensorFlow operations. The wrapped\n function will only be executed once. Subsequent calls to it will directly\n return the result so that operations are added to the graph only once.\n The operations added by the function live within a tf.variable_scope(). If\n this decorator is used with arguments, they will be forwarded to the\n variable scope. The scope name defaults to the name of the wrapped\n function.\n ' attribute = ('_cache_' + function.__name__) name = (scope or function.__name__) @property @functools.wraps(function) def decorator(self): if (not hasattr(self, attribute)): with tf.variable_scope(name, *args, **kwargs): setattr(self, attribute, function(self)) return getattr(self, attribute) return decorator
A decorator for functions that define TensorFlow operations. The wrapped function will only be executed once. Subsequent calls to it will directly return the result so that operations are added to the graph only once. The operations added by the function live within a tf.variable_scope(). If this decorator is used with arguments, they will be forwarded to the variable scope. The scope name defaults to the name of the wrapped function.
utils/utilities.py
define_scope
firstlight1/private
325
python
@doublewrap def define_scope(function, scope=None, *args, **kwargs): '\n A decorator for functions that define TensorFlow operations. The wrapped\n function will only be executed once. Subsequent calls to it will directly\n return the result so that operations are added to the graph only once.\n The operations added by the function live within a tf.variable_scope(). If\n this decorator is used with arguments, they will be forwarded to the\n variable scope. The scope name defaults to the name of the wrapped\n function.\n ' attribute = ('_cache_' + function.__name__) name = (scope or function.__name__) @property @functools.wraps(function) def decorator(self): if (not hasattr(self, attribute)): with tf.variable_scope(name, *args, **kwargs): setattr(self, attribute, function(self)) return getattr(self, attribute) return decorator
@doublewrap def define_scope(function, scope=None, *args, **kwargs): '\n A decorator for functions that define TensorFlow operations. The wrapped\n function will only be executed once. Subsequent calls to it will directly\n return the result so that operations are added to the graph only once.\n The operations added by the function live within a tf.variable_scope(). If\n this decorator is used with arguments, they will be forwarded to the\n variable scope. The scope name defaults to the name of the wrapped\n function.\n ' attribute = ('_cache_' + function.__name__) name = (scope or function.__name__) @property @functools.wraps(function) def decorator(self): if (not hasattr(self, attribute)): with tf.variable_scope(name, *args, **kwargs): setattr(self, attribute, function(self)) return getattr(self, attribute) return decorator<|docstring|>A decorator for functions that define TensorFlow operations. The wrapped function will only be executed once. Subsequent calls to it will directly return the result so that operations are added to the graph only once. The operations added by the function live within a tf.variable_scope(). If this decorator is used with arguments, they will be forwarded to the variable scope. The scope name defaults to the name of the wrapped function.<|endoftext|>
90ab53b3d671fb918d0376fbb5644b06d8136f234f353f217c6c89d39fdc516c
def stupid_parallel(function, nprocesses=None): '\n Works similar to a decorator to paralelize "stupidly parallel"\n problems. Decorators and multiprocessing don\'t play nicely because\n of naming issues.\n\n Inputs\n ======\n function : the function that will be parallelized. The FIRST\n argument is the one to be iterated on (in parallel). The other\n arguments are the same in all the parallel runs of the function\n (they can be named or unnamedarguments).\n nprocesses : int, the number of processes to run. Default is None.\n It is passed to multiprocessing.Pool (see that for details).\n\n Output\n ======\n A paralelized function. DO NOT NAME IT THE SAME AS THE INPUT\n FUNCTION.\n\n Example\n =======\n def _square_and_offset(value, offset=0):\n return value**2 + offset\n\n parallel_square_and_offset = stupid_parallel(_square_and_offset,\n nprocesses=5)\n print square_and_offset_parallel(range(10), offset=3)\n > [3, 4, 7, 12, 19, 28, 39, 52, 67, 84]\n ' def apply(iterable_values, *args, **kwargs): args = list(args) p = Pool(nprocesses) result = [p.apply_async(function, args=([value] + args), kwds=kwargs) for value in iterable_values] p.close() return [r.get() for r in result] return apply
Works similar to a decorator to paralelize "stupidly parallel" problems. Decorators and multiprocessing don't play nicely because of naming issues. Inputs ====== function : the function that will be parallelized. The FIRST argument is the one to be iterated on (in parallel). The other arguments are the same in all the parallel runs of the function (they can be named or unnamedarguments). nprocesses : int, the number of processes to run. Default is None. It is passed to multiprocessing.Pool (see that for details). Output ====== A paralelized function. DO NOT NAME IT THE SAME AS THE INPUT FUNCTION. Example ======= def _square_and_offset(value, offset=0): return value**2 + offset parallel_square_and_offset = stupid_parallel(_square_and_offset, nprocesses=5) print square_and_offset_parallel(range(10), offset=3) > [3, 4, 7, 12, 19, 28, 39, 52, 67, 84]
utils/utilities.py
stupid_parallel
firstlight1/private
325
python
def stupid_parallel(function, nprocesses=None): '\n Works similar to a decorator to paralelize "stupidly parallel"\n problems. Decorators and multiprocessing don\'t play nicely because\n of naming issues.\n\n Inputs\n ======\n function : the function that will be parallelized. The FIRST\n argument is the one to be iterated on (in parallel). The other\n arguments are the same in all the parallel runs of the function\n (they can be named or unnamedarguments).\n nprocesses : int, the number of processes to run. Default is None.\n It is passed to multiprocessing.Pool (see that for details).\n\n Output\n ======\n A paralelized function. DO NOT NAME IT THE SAME AS THE INPUT\n FUNCTION.\n\n Example\n =======\n def _square_and_offset(value, offset=0):\n return value**2 + offset\n\n parallel_square_and_offset = stupid_parallel(_square_and_offset,\n nprocesses=5)\n print square_and_offset_parallel(range(10), offset=3)\n > [3, 4, 7, 12, 19, 28, 39, 52, 67, 84]\n ' def apply(iterable_values, *args, **kwargs): args = list(args) p = Pool(nprocesses) result = [p.apply_async(function, args=([value] + args), kwds=kwargs) for value in iterable_values] p.close() return [r.get() for r in result] return apply
def stupid_parallel(function, nprocesses=None): '\n Works similar to a decorator to paralelize "stupidly parallel"\n problems. Decorators and multiprocessing don\'t play nicely because\n of naming issues.\n\n Inputs\n ======\n function : the function that will be parallelized. The FIRST\n argument is the one to be iterated on (in parallel). The other\n arguments are the same in all the parallel runs of the function\n (they can be named or unnamedarguments).\n nprocesses : int, the number of processes to run. Default is None.\n It is passed to multiprocessing.Pool (see that for details).\n\n Output\n ======\n A paralelized function. DO NOT NAME IT THE SAME AS THE INPUT\n FUNCTION.\n\n Example\n =======\n def _square_and_offset(value, offset=0):\n return value**2 + offset\n\n parallel_square_and_offset = stupid_parallel(_square_and_offset,\n nprocesses=5)\n print square_and_offset_parallel(range(10), offset=3)\n > [3, 4, 7, 12, 19, 28, 39, 52, 67, 84]\n ' def apply(iterable_values, *args, **kwargs): args = list(args) p = Pool(nprocesses) result = [p.apply_async(function, args=([value] + args), kwds=kwargs) for value in iterable_values] p.close() return [r.get() for r in result] return apply<|docstring|>Works similar to a decorator to paralelize "stupidly parallel" problems. Decorators and multiprocessing don't play nicely because of naming issues. Inputs ====== function : the function that will be parallelized. The FIRST argument is the one to be iterated on (in parallel). The other arguments are the same in all the parallel runs of the function (they can be named or unnamedarguments). nprocesses : int, the number of processes to run. Default is None. It is passed to multiprocessing.Pool (see that for details). Output ====== A paralelized function. DO NOT NAME IT THE SAME AS THE INPUT FUNCTION. Example ======= def _square_and_offset(value, offset=0): return value**2 + offset parallel_square_and_offset = stupid_parallel(_square_and_offset, nprocesses=5) print square_and_offset_parallel(range(10), offset=3) > [3, 4, 7, 12, 19, 28, 39, 52, 67, 84]<|endoftext|>
7819486f7a0b75f8fd32dc3501c36fd568ae897beeb859a2bff1aff3539c6b6b
def merge_microstates_in_tmatrix(transition_matrix, ms1, ms2, keep_size=False): 'Merge two microstates (ms1 and ms2) in the transition matrix, i.e.,\n returns the transition matrix that we would obtain if the microstates where\n merged befored the estimation of the transition matrix. The transition\n matrix is expected to be a square numpy array' check_tmatrix(transition_matrix) p = pops_from_tmatrix(transition_matrix) size = len(transition_matrix) final_tmatrix = np.copy(transition_matrix) for k in range(size): final_tmatrix[(k, ms1)] += final_tmatrix[(k, ms2)] for k in range(size): if ((p[ms1] + p[ms2]) != 0.0): final_tmatrix[(ms1, k)] = (((p[ms1] * final_tmatrix[(ms1, k)]) + (p[ms2] * final_tmatrix[(ms2, k)])) / (p[ms1] + p[ms2])) if keep_size: for i in range(size): final_tmatrix[(ms2, i)] = 0.0 final_tmatrix[(i, ms2)] = 0.0 else: final_tmatrix = np.delete(final_tmatrix, ms2, axis=1) final_tmatrix = np.delete(final_tmatrix, ms2, axis=0) return final_tmatrix
Merge two microstates (ms1 and ms2) in the transition matrix, i.e., returns the transition matrix that we would obtain if the microstates where merged befored the estimation of the transition matrix. The transition matrix is expected to be a square numpy array
nmpath/clustering.py
merge_microstates_in_tmatrix
RobertArbon/NMpathAnalysis
2
python
def merge_microstates_in_tmatrix(transition_matrix, ms1, ms2, keep_size=False): 'Merge two microstates (ms1 and ms2) in the transition matrix, i.e.,\n returns the transition matrix that we would obtain if the microstates where\n merged befored the estimation of the transition matrix. The transition\n matrix is expected to be a square numpy array' check_tmatrix(transition_matrix) p = pops_from_tmatrix(transition_matrix) size = len(transition_matrix) final_tmatrix = np.copy(transition_matrix) for k in range(size): final_tmatrix[(k, ms1)] += final_tmatrix[(k, ms2)] for k in range(size): if ((p[ms1] + p[ms2]) != 0.0): final_tmatrix[(ms1, k)] = (((p[ms1] * final_tmatrix[(ms1, k)]) + (p[ms2] * final_tmatrix[(ms2, k)])) / (p[ms1] + p[ms2])) if keep_size: for i in range(size): final_tmatrix[(ms2, i)] = 0.0 final_tmatrix[(i, ms2)] = 0.0 else: final_tmatrix = np.delete(final_tmatrix, ms2, axis=1) final_tmatrix = np.delete(final_tmatrix, ms2, axis=0) return final_tmatrix
def merge_microstates_in_tmatrix(transition_matrix, ms1, ms2, keep_size=False): 'Merge two microstates (ms1 and ms2) in the transition matrix, i.e.,\n returns the transition matrix that we would obtain if the microstates where\n merged befored the estimation of the transition matrix. The transition\n matrix is expected to be a square numpy array' check_tmatrix(transition_matrix) p = pops_from_tmatrix(transition_matrix) size = len(transition_matrix) final_tmatrix = np.copy(transition_matrix) for k in range(size): final_tmatrix[(k, ms1)] += final_tmatrix[(k, ms2)] for k in range(size): if ((p[ms1] + p[ms2]) != 0.0): final_tmatrix[(ms1, k)] = (((p[ms1] * final_tmatrix[(ms1, k)]) + (p[ms2] * final_tmatrix[(ms2, k)])) / (p[ms1] + p[ms2])) if keep_size: for i in range(size): final_tmatrix[(ms2, i)] = 0.0 final_tmatrix[(i, ms2)] = 0.0 else: final_tmatrix = np.delete(final_tmatrix, ms2, axis=1) final_tmatrix = np.delete(final_tmatrix, ms2, axis=0) return final_tmatrix<|docstring|>Merge two microstates (ms1 and ms2) in the transition matrix, i.e., returns the transition matrix that we would obtain if the microstates where merged befored the estimation of the transition matrix. The transition matrix is expected to be a square numpy array<|endoftext|>
0a10bb48eb17afa42449c0c88987b806df5de6b9865281e3eeafa841fcf15929
def kinetic_clustering_from_tmatrix(transition_matrix, n_clusters=2, t_cut=float('inf'), ini_clusters=None, verbose=False): 'Hierarchical agglomeratice kinetic clustering from the commute matrix\n (MFPTs in both directions). On each step, the matrix is recalculated.\n\n Parameters\n ----------\n transition_matrix: ndarray, shape=(n,n)\n Row-stochastic transiton matrix (each row add to one)\n\n n_clusters: integer.\n A cut-off for the minimum number of clusters after the\n clustering.\n\n t_cut: float or integer,\n A cut-off for the min inter-cluster commute time\n\n ini_clusters: List of lists\n Initial clustering, force initial clusters.\n\n Returns\n -------\n The tuple: clusters, t_min, t_max, new_tmatrix\n ' check_tmatrix(transition_matrix) if (n_clusters < 2): raise ValueError('The final number of clusters should be greater than 2') n_states = len(transition_matrix) new_tmatrix = copy.copy(transition_matrix) if (ini_clusters is None): clusters = [[i] for i in range(n_states)] else: clusters = copy.copy(ini_clusters) mfpt_M = mfpts_matrix(transition_matrix) (t_min, i_min, j_min) = min_commute_time(mfpt_M) (t_max, i_max, j_max) = max_commute_time(mfpt_M) if verbose: print('Number of clusters: ', end=' ') while ((t_min < t_cut) and (len(clusters) > n_clusters)): if (len(clusters[i_min]) > len(clusters[j_min])): clusters[i_min] += clusters[j_min] del clusters[j_min] new_tmatrix = merge_microstates_in_tmatrix(new_tmatrix, i_min, j_min) else: clusters[j_min] += clusters[i_min] del clusters[i_min] new_tmatrix = merge_microstates_in_tmatrix(new_tmatrix, j_min, i_min) if verbose: print(len(clusters), end=' ') mfpt_M = mfpts_matrix(new_tmatrix) (t_min, i_min, j_min) = min_commute_time(mfpt_M) (t_max, i_max, j_max) = max_commute_time(mfpt_M) return (clusters, t_min, t_max, new_tmatrix)
Hierarchical agglomeratice kinetic clustering from the commute matrix (MFPTs in both directions). On each step, the matrix is recalculated. Parameters ---------- transition_matrix: ndarray, shape=(n,n) Row-stochastic transiton matrix (each row add to one) n_clusters: integer. A cut-off for the minimum number of clusters after the clustering. t_cut: float or integer, A cut-off for the min inter-cluster commute time ini_clusters: List of lists Initial clustering, force initial clusters. Returns ------- The tuple: clusters, t_min, t_max, new_tmatrix
nmpath/clustering.py
kinetic_clustering_from_tmatrix
RobertArbon/NMpathAnalysis
2
python
def kinetic_clustering_from_tmatrix(transition_matrix, n_clusters=2, t_cut=float('inf'), ini_clusters=None, verbose=False): 'Hierarchical agglomeratice kinetic clustering from the commute matrix\n (MFPTs in both directions). On each step, the matrix is recalculated.\n\n Parameters\n ----------\n transition_matrix: ndarray, shape=(n,n)\n Row-stochastic transiton matrix (each row add to one)\n\n n_clusters: integer.\n A cut-off for the minimum number of clusters after the\n clustering.\n\n t_cut: float or integer,\n A cut-off for the min inter-cluster commute time\n\n ini_clusters: List of lists\n Initial clustering, force initial clusters.\n\n Returns\n -------\n The tuple: clusters, t_min, t_max, new_tmatrix\n ' check_tmatrix(transition_matrix) if (n_clusters < 2): raise ValueError('The final number of clusters should be greater than 2') n_states = len(transition_matrix) new_tmatrix = copy.copy(transition_matrix) if (ini_clusters is None): clusters = [[i] for i in range(n_states)] else: clusters = copy.copy(ini_clusters) mfpt_M = mfpts_matrix(transition_matrix) (t_min, i_min, j_min) = min_commute_time(mfpt_M) (t_max, i_max, j_max) = max_commute_time(mfpt_M) if verbose: print('Number of clusters: ', end=' ') while ((t_min < t_cut) and (len(clusters) > n_clusters)): if (len(clusters[i_min]) > len(clusters[j_min])): clusters[i_min] += clusters[j_min] del clusters[j_min] new_tmatrix = merge_microstates_in_tmatrix(new_tmatrix, i_min, j_min) else: clusters[j_min] += clusters[i_min] del clusters[i_min] new_tmatrix = merge_microstates_in_tmatrix(new_tmatrix, j_min, i_min) if verbose: print(len(clusters), end=' ') mfpt_M = mfpts_matrix(new_tmatrix) (t_min, i_min, j_min) = min_commute_time(mfpt_M) (t_max, i_max, j_max) = max_commute_time(mfpt_M) return (clusters, t_min, t_max, new_tmatrix)
def kinetic_clustering_from_tmatrix(transition_matrix, n_clusters=2, t_cut=float('inf'), ini_clusters=None, verbose=False): 'Hierarchical agglomeratice kinetic clustering from the commute matrix\n (MFPTs in both directions). On each step, the matrix is recalculated.\n\n Parameters\n ----------\n transition_matrix: ndarray, shape=(n,n)\n Row-stochastic transiton matrix (each row add to one)\n\n n_clusters: integer.\n A cut-off for the minimum number of clusters after the\n clustering.\n\n t_cut: float or integer,\n A cut-off for the min inter-cluster commute time\n\n ini_clusters: List of lists\n Initial clustering, force initial clusters.\n\n Returns\n -------\n The tuple: clusters, t_min, t_max, new_tmatrix\n ' check_tmatrix(transition_matrix) if (n_clusters < 2): raise ValueError('The final number of clusters should be greater than 2') n_states = len(transition_matrix) new_tmatrix = copy.copy(transition_matrix) if (ini_clusters is None): clusters = [[i] for i in range(n_states)] else: clusters = copy.copy(ini_clusters) mfpt_M = mfpts_matrix(transition_matrix) (t_min, i_min, j_min) = min_commute_time(mfpt_M) (t_max, i_max, j_max) = max_commute_time(mfpt_M) if verbose: print('Number of clusters: ', end=' ') while ((t_min < t_cut) and (len(clusters) > n_clusters)): if (len(clusters[i_min]) > len(clusters[j_min])): clusters[i_min] += clusters[j_min] del clusters[j_min] new_tmatrix = merge_microstates_in_tmatrix(new_tmatrix, i_min, j_min) else: clusters[j_min] += clusters[i_min] del clusters[i_min] new_tmatrix = merge_microstates_in_tmatrix(new_tmatrix, j_min, i_min) if verbose: print(len(clusters), end=' ') mfpt_M = mfpts_matrix(new_tmatrix) (t_min, i_min, j_min) = min_commute_time(mfpt_M) (t_max, i_max, j_max) = max_commute_time(mfpt_M) return (clusters, t_min, t_max, new_tmatrix)<|docstring|>Hierarchical agglomeratice kinetic clustering from the commute matrix (MFPTs in both directions). On each step, the matrix is recalculated. Parameters ---------- transition_matrix: ndarray, shape=(n,n) Row-stochastic transiton matrix (each row add to one) n_clusters: integer. A cut-off for the minimum number of clusters after the clustering. t_cut: float or integer, A cut-off for the min inter-cluster commute time ini_clusters: List of lists Initial clustering, force initial clusters. Returns ------- The tuple: clusters, t_min, t_max, new_tmatrix<|endoftext|>
f2e1dd3048ff55f8d31cd8e1e5e60a0e5b99445025d168887315d5ed04a5bd15
def kinetic_clustering2_from_tmatrix(transition_matrix, n_clusters=2, t_cut=float('inf'), ini_clusters=None, verbose=False): 'Hierarchical agglomeratice kinetic clustering from the commute matrix\n (MFPTs in both directions). The microstates are conserved all the time.\n Clusters are formed when al the inter-microstate commute times are bellow\n t_cut\n\n Parameters\n ----------\n transition_matrix: ndarray, shape=(n,n)\n Row-stochastic transiton matrix (each row add to one)\n\n n_clusters: integer.\n A cut-off for the minimum number of clusters after the\n clustering.\n\n t_cut: float or integer,\n A cut-off for the inter-cluster commute time\n\n ini_clusters: List of lists\n Initial clustering, force initial clusters.\n\n Returns\n -------\n The tuple: clusters, t_min, t_max, new_tmatrix\n ' check_tmatrix(transition_matrix) if (n_clusters < 2): raise ValueError('The final number of clusters should be greater than 2') n_states = len(transition_matrix) if (ini_clusters is None): clusters = [[i] for i in range(n_states)] else: clusters = copy.copy(ini_clusters) mfpt_M = mfpts_matrix(transition_matrix) if verbose: print('Number of clusters: ', end=' ') merged = True while (merged and (len(clusters) > n_clusters)): merged = False lenc = len(clusters) t_min = float('inf') t_max = 0 t_min_pair = None for i in range(lenc): for j in range((i + 1), lenc): t_ij = max_inter_cluster_commute_time(mfpt_M, clusters, i, j) if (t_ij > t_max): t_max = t_ij if ((t_ij < t_cut) and (t_ij < t_min)): t_min = t_ij t_min_pair = [i, j] if (t_min_pair is not None): clusters[t_min_pair[0]] += clusters[t_min_pair[1]] del clusters[t_min_pair[1]] merged = True t_min = float('inf') lenc = len(clusters) for i in range(lenc): for j in range((i + 1), lenc): t_ij = max_inter_cluster_commute_time(mfpt_M, clusters, i, j) if (t_ij < t_min): t_min = t_ij return (clusters, t_min, t_max)
Hierarchical agglomeratice kinetic clustering from the commute matrix (MFPTs in both directions). The microstates are conserved all the time. Clusters are formed when al the inter-microstate commute times are bellow t_cut Parameters ---------- transition_matrix: ndarray, shape=(n,n) Row-stochastic transiton matrix (each row add to one) n_clusters: integer. A cut-off for the minimum number of clusters after the clustering. t_cut: float or integer, A cut-off for the inter-cluster commute time ini_clusters: List of lists Initial clustering, force initial clusters. Returns ------- The tuple: clusters, t_min, t_max, new_tmatrix
nmpath/clustering.py
kinetic_clustering2_from_tmatrix
RobertArbon/NMpathAnalysis
2
python
def kinetic_clustering2_from_tmatrix(transition_matrix, n_clusters=2, t_cut=float('inf'), ini_clusters=None, verbose=False): 'Hierarchical agglomeratice kinetic clustering from the commute matrix\n (MFPTs in both directions). The microstates are conserved all the time.\n Clusters are formed when al the inter-microstate commute times are bellow\n t_cut\n\n Parameters\n ----------\n transition_matrix: ndarray, shape=(n,n)\n Row-stochastic transiton matrix (each row add to one)\n\n n_clusters: integer.\n A cut-off for the minimum number of clusters after the\n clustering.\n\n t_cut: float or integer,\n A cut-off for the inter-cluster commute time\n\n ini_clusters: List of lists\n Initial clustering, force initial clusters.\n\n Returns\n -------\n The tuple: clusters, t_min, t_max, new_tmatrix\n ' check_tmatrix(transition_matrix) if (n_clusters < 2): raise ValueError('The final number of clusters should be greater than 2') n_states = len(transition_matrix) if (ini_clusters is None): clusters = [[i] for i in range(n_states)] else: clusters = copy.copy(ini_clusters) mfpt_M = mfpts_matrix(transition_matrix) if verbose: print('Number of clusters: ', end=' ') merged = True while (merged and (len(clusters) > n_clusters)): merged = False lenc = len(clusters) t_min = float('inf') t_max = 0 t_min_pair = None for i in range(lenc): for j in range((i + 1), lenc): t_ij = max_inter_cluster_commute_time(mfpt_M, clusters, i, j) if (t_ij > t_max): t_max = t_ij if ((t_ij < t_cut) and (t_ij < t_min)): t_min = t_ij t_min_pair = [i, j] if (t_min_pair is not None): clusters[t_min_pair[0]] += clusters[t_min_pair[1]] del clusters[t_min_pair[1]] merged = True t_min = float('inf') lenc = len(clusters) for i in range(lenc): for j in range((i + 1), lenc): t_ij = max_inter_cluster_commute_time(mfpt_M, clusters, i, j) if (t_ij < t_min): t_min = t_ij return (clusters, t_min, t_max)
def kinetic_clustering2_from_tmatrix(transition_matrix, n_clusters=2, t_cut=float('inf'), ini_clusters=None, verbose=False): 'Hierarchical agglomeratice kinetic clustering from the commute matrix\n (MFPTs in both directions). The microstates are conserved all the time.\n Clusters are formed when al the inter-microstate commute times are bellow\n t_cut\n\n Parameters\n ----------\n transition_matrix: ndarray, shape=(n,n)\n Row-stochastic transiton matrix (each row add to one)\n\n n_clusters: integer.\n A cut-off for the minimum number of clusters after the\n clustering.\n\n t_cut: float or integer,\n A cut-off for the inter-cluster commute time\n\n ini_clusters: List of lists\n Initial clustering, force initial clusters.\n\n Returns\n -------\n The tuple: clusters, t_min, t_max, new_tmatrix\n ' check_tmatrix(transition_matrix) if (n_clusters < 2): raise ValueError('The final number of clusters should be greater than 2') n_states = len(transition_matrix) if (ini_clusters is None): clusters = [[i] for i in range(n_states)] else: clusters = copy.copy(ini_clusters) mfpt_M = mfpts_matrix(transition_matrix) if verbose: print('Number of clusters: ', end=' ') merged = True while (merged and (len(clusters) > n_clusters)): merged = False lenc = len(clusters) t_min = float('inf') t_max = 0 t_min_pair = None for i in range(lenc): for j in range((i + 1), lenc): t_ij = max_inter_cluster_commute_time(mfpt_M, clusters, i, j) if (t_ij > t_max): t_max = t_ij if ((t_ij < t_cut) and (t_ij < t_min)): t_min = t_ij t_min_pair = [i, j] if (t_min_pair is not None): clusters[t_min_pair[0]] += clusters[t_min_pair[1]] del clusters[t_min_pair[1]] merged = True t_min = float('inf') lenc = len(clusters) for i in range(lenc): for j in range((i + 1), lenc): t_ij = max_inter_cluster_commute_time(mfpt_M, clusters, i, j) if (t_ij < t_min): t_min = t_ij return (clusters, t_min, t_max)<|docstring|>Hierarchical agglomeratice kinetic clustering from the commute matrix (MFPTs in both directions). The microstates are conserved all the time. Clusters are formed when al the inter-microstate commute times are bellow t_cut Parameters ---------- transition_matrix: ndarray, shape=(n,n) Row-stochastic transiton matrix (each row add to one) n_clusters: integer. A cut-off for the minimum number of clusters after the clustering. t_cut: float or integer, A cut-off for the inter-cluster commute time ini_clusters: List of lists Initial clustering, force initial clusters. Returns ------- The tuple: clusters, t_min, t_max, new_tmatrix<|endoftext|>
3906a98dae37963a8f7593ad989f4abc2f464d8414e7be38428f906b5da47daf
def max_inter_cluster_commute_time(mfpt_M, clusters, i, j): 'Computes the all the inter-cluster commute times and returns\n the maximum value found.\n ' t_max = 0 for element_i in clusters[i]: for element_j in clusters[j]: round_trip = (mfpt_M[(element_i, element_j)] + mfpt_M[(element_j, element_i)]) if (round_trip > t_max): t_max = round_trip return t_max
Computes the all the inter-cluster commute times and returns the maximum value found.
nmpath/clustering.py
max_inter_cluster_commute_time
RobertArbon/NMpathAnalysis
2
python
def max_inter_cluster_commute_time(mfpt_M, clusters, i, j): 'Computes the all the inter-cluster commute times and returns\n the maximum value found.\n ' t_max = 0 for element_i in clusters[i]: for element_j in clusters[j]: round_trip = (mfpt_M[(element_i, element_j)] + mfpt_M[(element_j, element_i)]) if (round_trip > t_max): t_max = round_trip return t_max
def max_inter_cluster_commute_time(mfpt_M, clusters, i, j): 'Computes the all the inter-cluster commute times and returns\n the maximum value found.\n ' t_max = 0 for element_i in clusters[i]: for element_j in clusters[j]: round_trip = (mfpt_M[(element_i, element_j)] + mfpt_M[(element_j, element_i)]) if (round_trip > t_max): t_max = round_trip return t_max<|docstring|>Computes the all the inter-cluster commute times and returns the maximum value found.<|endoftext|>
e8261b4f7cd785086392674ee5b19a69739d7fac93d0c6c86ba61fb10dbbebf7
def biggest_clusters_indexes(clusters, n_pick=2): 'Pick the n_pick biggest clusters in a list of lists where the inner\n lists are group of indexes (clusters)\n ' n_clusters = len(clusters) indexes = [i for i in range(n_clusters)] len_cluster = [len(c) for c in clusters] (len_c_sorted, indexes_sorted) = zip(*sorted(zip(len_cluster, indexes), key=operator.itemgetter(0), reverse=True)) return indexes_sorted[0:n_pick]
Pick the n_pick biggest clusters in a list of lists where the inner lists are group of indexes (clusters)
nmpath/clustering.py
biggest_clusters_indexes
RobertArbon/NMpathAnalysis
2
python
def biggest_clusters_indexes(clusters, n_pick=2): 'Pick the n_pick biggest clusters in a list of lists where the inner\n lists are group of indexes (clusters)\n ' n_clusters = len(clusters) indexes = [i for i in range(n_clusters)] len_cluster = [len(c) for c in clusters] (len_c_sorted, indexes_sorted) = zip(*sorted(zip(len_cluster, indexes), key=operator.itemgetter(0), reverse=True)) return indexes_sorted[0:n_pick]
def biggest_clusters_indexes(clusters, n_pick=2): 'Pick the n_pick biggest clusters in a list of lists where the inner\n lists are group of indexes (clusters)\n ' n_clusters = len(clusters) indexes = [i for i in range(n_clusters)] len_cluster = [len(c) for c in clusters] (len_c_sorted, indexes_sorted) = zip(*sorted(zip(len_cluster, indexes), key=operator.itemgetter(0), reverse=True)) return indexes_sorted[0:n_pick]<|docstring|>Pick the n_pick biggest clusters in a list of lists where the inner lists are group of indexes (clusters)<|endoftext|>
4c0f9670d710e2d27a950d67b022cff2c9068f57b63e6eba8b5a6f0912657123
def check_script_prefixes(): "Check that no more than `expected_violation_count` of the\n test scripts don't start with one of the allowed name prefixes." expected_violation_count = 0 leeway = 1 good_prefixes_re = re.compile('(example|feature|interface|mempool|mining|p2p|rpc|wallet)_') bad_script_names = [script for script in ALL_SCRIPTS if (good_prefixes_re.match(script) is None)] if (len(bad_script_names) < expected_violation_count): print('{}HURRAY!{} Number of functional tests violating naming convention reduced!'.format(BOLD[1], BOLD[0])) print(('Consider reducing expected_violation_count from %d to %d' % (expected_violation_count, len(bad_script_names)))) elif (len(bad_script_names) > expected_violation_count): print(('WARNING: %d tests not meeting naming conventions. Please rename with allowed prefix. (expected %d):' % (len(bad_script_names), expected_violation_count))) print((' %s' % '\n '.join(sorted(bad_script_names)))) assert (len(bad_script_names) <= (expected_violation_count + leeway)), ('Too many tests not following naming convention! (%d found, expected: <= %d)' % (len(bad_script_names), expected_violation_count))
Check that no more than `expected_violation_count` of the test scripts don't start with one of the allowed name prefixes.
test/functional/test_runner.py
check_script_prefixes
BruceFenton/financial-Inv-mgmt-blockchain
1,102
python
def check_script_prefixes(): "Check that no more than `expected_violation_count` of the\n test scripts don't start with one of the allowed name prefixes." expected_violation_count = 0 leeway = 1 good_prefixes_re = re.compile('(example|feature|interface|mempool|mining|p2p|rpc|wallet)_') bad_script_names = [script for script in ALL_SCRIPTS if (good_prefixes_re.match(script) is None)] if (len(bad_script_names) < expected_violation_count): print('{}HURRAY!{} Number of functional tests violating naming convention reduced!'.format(BOLD[1], BOLD[0])) print(('Consider reducing expected_violation_count from %d to %d' % (expected_violation_count, len(bad_script_names)))) elif (len(bad_script_names) > expected_violation_count): print(('WARNING: %d tests not meeting naming conventions. Please rename with allowed prefix. (expected %d):' % (len(bad_script_names), expected_violation_count))) print((' %s' % '\n '.join(sorted(bad_script_names)))) assert (len(bad_script_names) <= (expected_violation_count + leeway)), ('Too many tests not following naming convention! (%d found, expected: <= %d)' % (len(bad_script_names), expected_violation_count))
def check_script_prefixes(): "Check that no more than `expected_violation_count` of the\n test scripts don't start with one of the allowed name prefixes." expected_violation_count = 0 leeway = 1 good_prefixes_re = re.compile('(example|feature|interface|mempool|mining|p2p|rpc|wallet)_') bad_script_names = [script for script in ALL_SCRIPTS if (good_prefixes_re.match(script) is None)] if (len(bad_script_names) < expected_violation_count): print('{}HURRAY!{} Number of functional tests violating naming convention reduced!'.format(BOLD[1], BOLD[0])) print(('Consider reducing expected_violation_count from %d to %d' % (expected_violation_count, len(bad_script_names)))) elif (len(bad_script_names) > expected_violation_count): print(('WARNING: %d tests not meeting naming conventions. Please rename with allowed prefix. (expected %d):' % (len(bad_script_names), expected_violation_count))) print((' %s' % '\n '.join(sorted(bad_script_names)))) assert (len(bad_script_names) <= (expected_violation_count + leeway)), ('Too many tests not following naming convention! (%d found, expected: <= %d)' % (len(bad_script_names), expected_violation_count))<|docstring|>Check that no more than `expected_violation_count` of the test scripts don't start with one of the allowed name prefixes.<|endoftext|>
d9ea936b8e5f3a2c7b9920962497cb65b98e6f832592c7194dbf6accec768d3a
def check_script_list(src_dir): 'Check scripts directory.\n\n Check that there are no scripts in the functional tests directory which are\n not being run by pull-tester.py.' script_dir = (src_dir + '/test/functional/') python_files = set([t for t in os.listdir(script_dir) if (t[(- 3):] == '.py')]) missed_tests = list((python_files - set(map((lambda x: x.split()[0]), ((ALL_SCRIPTS + NON_SCRIPTS) + SKIPPED_TESTS))))) if (len(missed_tests) != 0): print(('%sWARNING!%s The following scripts are not being run:\n%s \nCheck the test lists in test_runner.py.' % (BOLD[1], BOLD[0], '\n'.join(missed_tests))))
Check scripts directory. Check that there are no scripts in the functional tests directory which are not being run by pull-tester.py.
test/functional/test_runner.py
check_script_list
BruceFenton/financial-Inv-mgmt-blockchain
1,102
python
def check_script_list(src_dir): 'Check scripts directory.\n\n Check that there are no scripts in the functional tests directory which are\n not being run by pull-tester.py.' script_dir = (src_dir + '/test/functional/') python_files = set([t for t in os.listdir(script_dir) if (t[(- 3):] == '.py')]) missed_tests = list((python_files - set(map((lambda x: x.split()[0]), ((ALL_SCRIPTS + NON_SCRIPTS) + SKIPPED_TESTS))))) if (len(missed_tests) != 0): print(('%sWARNING!%s The following scripts are not being run:\n%s \nCheck the test lists in test_runner.py.' % (BOLD[1], BOLD[0], '\n'.join(missed_tests))))
def check_script_list(src_dir): 'Check scripts directory.\n\n Check that there are no scripts in the functional tests directory which are\n not being run by pull-tester.py.' script_dir = (src_dir + '/test/functional/') python_files = set([t for t in os.listdir(script_dir) if (t[(- 3):] == '.py')]) missed_tests = list((python_files - set(map((lambda x: x.split()[0]), ((ALL_SCRIPTS + NON_SCRIPTS) + SKIPPED_TESTS))))) if (len(missed_tests) != 0): print(('%sWARNING!%s The following scripts are not being run:\n%s \nCheck the test lists in test_runner.py.' % (BOLD[1], BOLD[0], '\n'.join(missed_tests))))<|docstring|>Check scripts directory. Check that there are no scripts in the functional tests directory which are not being run by pull-tester.py.<|endoftext|>
479dc0a906a816da195f731e5148cf5bb19dc5db33e9bc2037774a90d73c3815
def kill_and_join(self): 'Send SIGKILL to all jobs and block until all have ended.' process = [i[2] for i in self.jobs] for p in process: p.kill() for p in process: p.wait()
Send SIGKILL to all jobs and block until all have ended.
test/functional/test_runner.py
kill_and_join
BruceFenton/financial-Inv-mgmt-blockchain
1,102
python
def kill_and_join(self): process = [i[2] for i in self.jobs] for p in process: p.kill() for p in process: p.wait()
def kill_and_join(self): process = [i[2] for i in self.jobs] for p in process: p.kill() for p in process: p.wait()<|docstring|>Send SIGKILL to all jobs and block until all have ended.<|endoftext|>
3ab9b810fcd21de0d9e3ca29a55867b2a0a34802c6eefafbfa3b80ecadc36492
def report_rpc_coverage(self): '\n Print out RPC commands that were unexercised by tests.\n\n ' uncovered = self._get_uncovered_rpc_commands() if uncovered: print('Uncovered RPC commands:') print(''.join(((' - %s\n' % command) for command in sorted(uncovered)))) return False else: print('All RPC commands covered.') return True
Print out RPC commands that were unexercised by tests.
test/functional/test_runner.py
report_rpc_coverage
BruceFenton/financial-Inv-mgmt-blockchain
1,102
python
def report_rpc_coverage(self): '\n \n\n ' uncovered = self._get_uncovered_rpc_commands() if uncovered: print('Uncovered RPC commands:') print(.join(((' - %s\n' % command) for command in sorted(uncovered)))) return False else: print('All RPC commands covered.') return True
def report_rpc_coverage(self): '\n \n\n ' uncovered = self._get_uncovered_rpc_commands() if uncovered: print('Uncovered RPC commands:') print(.join(((' - %s\n' % command) for command in sorted(uncovered)))) return False else: print('All RPC commands covered.') return True<|docstring|>Print out RPC commands that were unexercised by tests.<|endoftext|>
a06df26bc60296348f65c5b5c792d7c1a071d8a7eb00d9eab714a421ee3f1376
def _get_uncovered_rpc_commands(self): '\n Return a set of currently untested RPC commands.\n\n ' reference_filename = 'rpc_interface.txt' coverage_file_prefix = 'coverage.' coverage_ref_filename = os.path.join(self.dir, reference_filename) coverage_filenames = set() all_cmds = set() covered_cmds = set() if (not os.path.isfile(coverage_ref_filename)): raise RuntimeError('No coverage reference found') with open(coverage_ref_filename, 'r', encoding='utf8') as coverage_ref_file: all_cmds.update([line.strip() for line in coverage_ref_file.readlines()]) for (root, _, files) in os.walk(self.dir): for filename in files: if filename.startswith(coverage_file_prefix): coverage_filenames.add(os.path.join(root, filename)) for filename in coverage_filenames: with open(filename, 'r', encoding='utf8') as coverage_file: covered_cmds.update([line.strip() for line in coverage_file.readlines()]) return (all_cmds - covered_cmds)
Return a set of currently untested RPC commands.
test/functional/test_runner.py
_get_uncovered_rpc_commands
BruceFenton/financial-Inv-mgmt-blockchain
1,102
python
def _get_uncovered_rpc_commands(self): '\n \n\n ' reference_filename = 'rpc_interface.txt' coverage_file_prefix = 'coverage.' coverage_ref_filename = os.path.join(self.dir, reference_filename) coverage_filenames = set() all_cmds = set() covered_cmds = set() if (not os.path.isfile(coverage_ref_filename)): raise RuntimeError('No coverage reference found') with open(coverage_ref_filename, 'r', encoding='utf8') as coverage_ref_file: all_cmds.update([line.strip() for line in coverage_ref_file.readlines()]) for (root, _, files) in os.walk(self.dir): for filename in files: if filename.startswith(coverage_file_prefix): coverage_filenames.add(os.path.join(root, filename)) for filename in coverage_filenames: with open(filename, 'r', encoding='utf8') as coverage_file: covered_cmds.update([line.strip() for line in coverage_file.readlines()]) return (all_cmds - covered_cmds)
def _get_uncovered_rpc_commands(self): '\n \n\n ' reference_filename = 'rpc_interface.txt' coverage_file_prefix = 'coverage.' coverage_ref_filename = os.path.join(self.dir, reference_filename) coverage_filenames = set() all_cmds = set() covered_cmds = set() if (not os.path.isfile(coverage_ref_filename)): raise RuntimeError('No coverage reference found') with open(coverage_ref_filename, 'r', encoding='utf8') as coverage_ref_file: all_cmds.update([line.strip() for line in coverage_ref_file.readlines()]) for (root, _, files) in os.walk(self.dir): for filename in files: if filename.startswith(coverage_file_prefix): coverage_filenames.add(os.path.join(root, filename)) for filename in coverage_filenames: with open(filename, 'r', encoding='utf8') as coverage_file: covered_cmds.update([line.strip() for line in coverage_file.readlines()]) return (all_cmds - covered_cmds)<|docstring|>Return a set of currently untested RPC commands.<|endoftext|>
71bd0240d1329894fdafc1db8970af3d6313d40db8d44e2155e5c033a19f4d9e
def test_push(self): 'Test TrackerResource.push(title, text) method' self.resource._request.register_uri('PUT', '/tracker') response = self.resource.push('foo', 'bar') self.assertEqual(response['ok'], 1) self.assertTrue(('server_time' in response))
Test TrackerResource.push(title, text) method
tests/test_tracker.py
test_push
dotzero/habrahabr-api-python
11
python
def test_push(self): self.resource._request.register_uri('PUT', '/tracker') response = self.resource.push('foo', 'bar') self.assertEqual(response['ok'], 1) self.assertTrue(('server_time' in response))
def test_push(self): self.resource._request.register_uri('PUT', '/tracker') response = self.resource.push('foo', 'bar') self.assertEqual(response['ok'], 1) self.assertTrue(('server_time' in response))<|docstring|>Test TrackerResource.push(title, text) method<|endoftext|>
4e745e70e1a3bc050de39e2bd1f4fed2fe19565f118c36c138a3ca68be036d88
def test_push_fail(self): 'Test Fail TrackerResource.push(title, text) method' with self.assertRaises(AssertionError): self.resource.push((- 1)) with self.assertRaises(AssertionError): self.resource.push('foobar', (- 1))
Test Fail TrackerResource.push(title, text) method
tests/test_tracker.py
test_push_fail
dotzero/habrahabr-api-python
11
python
def test_push_fail(self): with self.assertRaises(AssertionError): self.resource.push((- 1)) with self.assertRaises(AssertionError): self.resource.push('foobar', (- 1))
def test_push_fail(self): with self.assertRaises(AssertionError): self.resource.push((- 1)) with self.assertRaises(AssertionError): self.resource.push('foobar', (- 1))<|docstring|>Test Fail TrackerResource.push(title, text) method<|endoftext|>
25878a0ffaef07c6f502d37d8a202afe659abfbe066eb70d5bda6df26de850e7
def test_counters(self): 'Test TrackerResource.counters() method' self.resource._request.register_uri('GET', '/tracker/counters') response = self.resource.counters() self.assertEqual(response['ok'], 1) self.assertTrue(('server_time' in response))
Test TrackerResource.counters() method
tests/test_tracker.py
test_counters
dotzero/habrahabr-api-python
11
python
def test_counters(self): self.resource._request.register_uri('GET', '/tracker/counters') response = self.resource.counters() self.assertEqual(response['ok'], 1) self.assertTrue(('server_time' in response))
def test_counters(self): self.resource._request.register_uri('GET', '/tracker/counters') response = self.resource.counters() self.assertEqual(response['ok'], 1) self.assertTrue(('server_time' in response))<|docstring|>Test TrackerResource.counters() method<|endoftext|>
2694114ced66eed9e6657869fb0cff8cc00a3f99e2a536bfd467a625fd14fae7
def test_posts(self): 'Test TrackerResource.posts(page) method' self.resource._request.register_uri('GET', '/tracker/posts?page=2') response = self.resource.posts(2) self.assertEqual(response['ok'], 1) self.assertTrue(('server_time' in response))
Test TrackerResource.posts(page) method
tests/test_tracker.py
test_posts
dotzero/habrahabr-api-python
11
python
def test_posts(self): self.resource._request.register_uri('GET', '/tracker/posts?page=2') response = self.resource.posts(2) self.assertEqual(response['ok'], 1) self.assertTrue(('server_time' in response))
def test_posts(self): self.resource._request.register_uri('GET', '/tracker/posts?page=2') response = self.resource.posts(2) self.assertEqual(response['ok'], 1) self.assertTrue(('server_time' in response))<|docstring|>Test TrackerResource.posts(page) method<|endoftext|>
b52e8995d7105c5bc5571c7a4aa11629db2ba135cd179ab61f796a10f6bc9a3f
def test_posts_fail(self): 'Test Fail TrackerResource.posts(page) method' with self.assertRaises(AssertionError): self.resource.posts('foobar')
Test Fail TrackerResource.posts(page) method
tests/test_tracker.py
test_posts_fail
dotzero/habrahabr-api-python
11
python
def test_posts_fail(self): with self.assertRaises(AssertionError): self.resource.posts('foobar')
def test_posts_fail(self): with self.assertRaises(AssertionError): self.resource.posts('foobar')<|docstring|>Test Fail TrackerResource.posts(page) method<|endoftext|>
6a94efe4b3e2a3857a6d1e297faa3942879a4809c00e902a57940752152524fc
def test_subscribers(self): 'Test TrackerResource.subscribers(page) method' self.resource._request.register_uri('GET', '/tracker/subscribers?page=2') response = self.resource.subscribers(2) self.assertEqual(response['ok'], 1) self.assertTrue(('server_time' in response))
Test TrackerResource.subscribers(page) method
tests/test_tracker.py
test_subscribers
dotzero/habrahabr-api-python
11
python
def test_subscribers(self): self.resource._request.register_uri('GET', '/tracker/subscribers?page=2') response = self.resource.subscribers(2) self.assertEqual(response['ok'], 1) self.assertTrue(('server_time' in response))
def test_subscribers(self): self.resource._request.register_uri('GET', '/tracker/subscribers?page=2') response = self.resource.subscribers(2) self.assertEqual(response['ok'], 1) self.assertTrue(('server_time' in response))<|docstring|>Test TrackerResource.subscribers(page) method<|endoftext|>
db0e025027d91684afa6b9091f6104715f4382696b5da4bd86812a24d3fd0cb6
def test_subscribers_fail(self): 'Test Fail TrackerResource.subscribers(page) method' with self.assertRaises(AssertionError): self.resource.subscribers('foobar')
Test Fail TrackerResource.subscribers(page) method
tests/test_tracker.py
test_subscribers_fail
dotzero/habrahabr-api-python
11
python
def test_subscribers_fail(self): with self.assertRaises(AssertionError): self.resource.subscribers('foobar')
def test_subscribers_fail(self): with self.assertRaises(AssertionError): self.resource.subscribers('foobar')<|docstring|>Test Fail TrackerResource.subscribers(page) method<|endoftext|>
49c27f4019ce3273f2622036c1e054e9e4acd839df757954fa0be65d57674d5e
def test_mentions(self): 'Test TrackerResource.mentions(page) method' self.resource._request.register_uri('GET', '/tracker/mentions?page=2') response = self.resource.mentions(2) self.assertEqual(response['ok'], 1) self.assertTrue(('server_time' in response))
Test TrackerResource.mentions(page) method
tests/test_tracker.py
test_mentions
dotzero/habrahabr-api-python
11
python
def test_mentions(self): self.resource._request.register_uri('GET', '/tracker/mentions?page=2') response = self.resource.mentions(2) self.assertEqual(response['ok'], 1) self.assertTrue(('server_time' in response))
def test_mentions(self): self.resource._request.register_uri('GET', '/tracker/mentions?page=2') response = self.resource.mentions(2) self.assertEqual(response['ok'], 1) self.assertTrue(('server_time' in response))<|docstring|>Test TrackerResource.mentions(page) method<|endoftext|>
66e1f6b95be8f4be48988cdf4a8c93e262eacc78f3a3bab4c903caabfbb2566f
def test_mentions_fail(self): 'Test Fail TrackerResource.mentions(page) method' with self.assertRaises(AssertionError): self.resource.mentions('foobar')
Test Fail TrackerResource.mentions(page) method
tests/test_tracker.py
test_mentions_fail
dotzero/habrahabr-api-python
11
python
def test_mentions_fail(self): with self.assertRaises(AssertionError): self.resource.mentions('foobar')
def test_mentions_fail(self): with self.assertRaises(AssertionError): self.resource.mentions('foobar')<|docstring|>Test Fail TrackerResource.mentions(page) method<|endoftext|>
c8da3a73c66737f6a420240fbd359719b307faff055e5aaed70f4c298cdf613d
def test_apps(self): 'Test TrackerResource.apps() method' self.resource._request.register_uri('GET', '/tracker/apps') response = self.resource.apps() self.assertEqual(response['ok'], 1) self.assertTrue(('server_time' in response))
Test TrackerResource.apps() method
tests/test_tracker.py
test_apps
dotzero/habrahabr-api-python
11
python
def test_apps(self): self.resource._request.register_uri('GET', '/tracker/apps') response = self.resource.apps() self.assertEqual(response['ok'], 1) self.assertTrue(('server_time' in response))
def test_apps(self): self.resource._request.register_uri('GET', '/tracker/apps') response = self.resource.apps() self.assertEqual(response['ok'], 1) self.assertTrue(('server_time' in response))<|docstring|>Test TrackerResource.apps() method<|endoftext|>
378994292a308570fbfbbda0a06b99518cfdefda8d7f3514417eb9f7c865351a
def get_timeseries_tt(node: TimeSeries, istart=0, istop=None) -> np.ndarray: '\n For any TimeSeries, return timestamps. If the TimeSeries uses starting_time and rate, the timestamps will be\n generated.\n\n Parameters\n ----------\n node: pynwb.TimeSeries\n istart: int, optional\n Optionally sub-select the returned times - lower bound\n istop: int, optional\n Optionally sub-select the returned times - upper bound\n\n Returns\n -------\n numpy.ndarray\n\n ' if (node.timestamps is not None): return node.timestamps[istart:istop] else: if (not np.isfinite(node.starting_time)): starting_time = 0 else: starting_time = node.starting_time if (istop is None): return ((np.arange(istart, len(node.data)) / node.rate) + starting_time) elif (istop > 0): return ((np.arange(istart, istop) / node.rate) + starting_time) else: return ((np.arange(istart, ((len(node.data) + istop) - 1)) / node.rate) + starting_time)
For any TimeSeries, return timestamps. If the TimeSeries uses starting_time and rate, the timestamps will be generated. Parameters ---------- node: pynwb.TimeSeries istart: int, optional Optionally sub-select the returned times - lower bound istop: int, optional Optionally sub-select the returned times - upper bound Returns ------- numpy.ndarray
nwbwidgets/utils/timeseries.py
get_timeseries_tt
lvsltz/nwb-jupyter-widgets
0
python
def get_timeseries_tt(node: TimeSeries, istart=0, istop=None) -> np.ndarray: '\n For any TimeSeries, return timestamps. If the TimeSeries uses starting_time and rate, the timestamps will be\n generated.\n\n Parameters\n ----------\n node: pynwb.TimeSeries\n istart: int, optional\n Optionally sub-select the returned times - lower bound\n istop: int, optional\n Optionally sub-select the returned times - upper bound\n\n Returns\n -------\n numpy.ndarray\n\n ' if (node.timestamps is not None): return node.timestamps[istart:istop] else: if (not np.isfinite(node.starting_time)): starting_time = 0 else: starting_time = node.starting_time if (istop is None): return ((np.arange(istart, len(node.data)) / node.rate) + starting_time) elif (istop > 0): return ((np.arange(istart, istop) / node.rate) + starting_time) else: return ((np.arange(istart, ((len(node.data) + istop) - 1)) / node.rate) + starting_time)
def get_timeseries_tt(node: TimeSeries, istart=0, istop=None) -> np.ndarray: '\n For any TimeSeries, return timestamps. If the TimeSeries uses starting_time and rate, the timestamps will be\n generated.\n\n Parameters\n ----------\n node: pynwb.TimeSeries\n istart: int, optional\n Optionally sub-select the returned times - lower bound\n istop: int, optional\n Optionally sub-select the returned times - upper bound\n\n Returns\n -------\n numpy.ndarray\n\n ' if (node.timestamps is not None): return node.timestamps[istart:istop] else: if (not np.isfinite(node.starting_time)): starting_time = 0 else: starting_time = node.starting_time if (istop is None): return ((np.arange(istart, len(node.data)) / node.rate) + starting_time) elif (istop > 0): return ((np.arange(istart, istop) / node.rate) + starting_time) else: return ((np.arange(istart, ((len(node.data) + istop) - 1)) / node.rate) + starting_time)<|docstring|>For any TimeSeries, return timestamps. If the TimeSeries uses starting_time and rate, the timestamps will be generated. Parameters ---------- node: pynwb.TimeSeries istart: int, optional Optionally sub-select the returned times - lower bound istop: int, optional Optionally sub-select the returned times - upper bound Returns ------- numpy.ndarray<|endoftext|>
32c1d2c3d0c7ed06774f69a471e8403d3c2044f9390bb3d811c717c24d0a0a0c
def get_timeseries_maxt(node: TimeSeries) -> float: '\n Returns the maximum time of any TimeSeries\n\n Parameters\n ----------\n node: pynwb.TimeSeries\n\n Returns\n -------\n float\n\n ' if (node.timestamps is not None): return node.timestamps[(- 1)] else: return ((len(node.data) / node.rate) + node.starting_time)
Returns the maximum time of any TimeSeries Parameters ---------- node: pynwb.TimeSeries Returns ------- float
nwbwidgets/utils/timeseries.py
get_timeseries_maxt
lvsltz/nwb-jupyter-widgets
0
python
def get_timeseries_maxt(node: TimeSeries) -> float: '\n Returns the maximum time of any TimeSeries\n\n Parameters\n ----------\n node: pynwb.TimeSeries\n\n Returns\n -------\n float\n\n ' if (node.timestamps is not None): return node.timestamps[(- 1)] else: return ((len(node.data) / node.rate) + node.starting_time)
def get_timeseries_maxt(node: TimeSeries) -> float: '\n Returns the maximum time of any TimeSeries\n\n Parameters\n ----------\n node: pynwb.TimeSeries\n\n Returns\n -------\n float\n\n ' if (node.timestamps is not None): return node.timestamps[(- 1)] else: return ((len(node.data) / node.rate) + node.starting_time)<|docstring|>Returns the maximum time of any TimeSeries Parameters ---------- node: pynwb.TimeSeries Returns ------- float<|endoftext|>
994b594afa0893ba0cb92a877ce6dc7b34ee13c3e8e47b26e52e22af8a4f75a1
def get_timeseries_mint(node: TimeSeries) -> float: '\n Returns the minimum time of any TimeSeries\n\n Parameters\n ----------\n node: pynwb.TimeSeries\n\n Returns\n -------\n float\n\n ' if (node.timestamps is not None): return node.timestamps[0] else: return node.starting_time
Returns the minimum time of any TimeSeries Parameters ---------- node: pynwb.TimeSeries Returns ------- float
nwbwidgets/utils/timeseries.py
get_timeseries_mint
lvsltz/nwb-jupyter-widgets
0
python
def get_timeseries_mint(node: TimeSeries) -> float: '\n Returns the minimum time of any TimeSeries\n\n Parameters\n ----------\n node: pynwb.TimeSeries\n\n Returns\n -------\n float\n\n ' if (node.timestamps is not None): return node.timestamps[0] else: return node.starting_time
def get_timeseries_mint(node: TimeSeries) -> float: '\n Returns the minimum time of any TimeSeries\n\n Parameters\n ----------\n node: pynwb.TimeSeries\n\n Returns\n -------\n float\n\n ' if (node.timestamps is not None): return node.timestamps[0] else: return node.starting_time<|docstring|>Returns the minimum time of any TimeSeries Parameters ---------- node: pynwb.TimeSeries Returns ------- float<|endoftext|>
204f813a59104689cb706ef8acc324897defbabd37489f0d88eef6ef1b4f61cc
def get_timeseries_in_units(node: TimeSeries, istart=None, istop=None): '\n Convert data into the designated units\n\n Parameters\n ----------\n node: pynwb.TimeSeries\n istart: int\n istop: int\n\n Returns\n -------\n numpy.ndarray, str\n\n ' data = node.data[istart:istop] if (node.conversion and np.isfinite(node.conversion)): data = (data * node.conversion) unit = node.unit else: unit = None return (data, unit)
Convert data into the designated units Parameters ---------- node: pynwb.TimeSeries istart: int istop: int Returns ------- numpy.ndarray, str
nwbwidgets/utils/timeseries.py
get_timeseries_in_units
lvsltz/nwb-jupyter-widgets
0
python
def get_timeseries_in_units(node: TimeSeries, istart=None, istop=None): '\n Convert data into the designated units\n\n Parameters\n ----------\n node: pynwb.TimeSeries\n istart: int\n istop: int\n\n Returns\n -------\n numpy.ndarray, str\n\n ' data = node.data[istart:istop] if (node.conversion and np.isfinite(node.conversion)): data = (data * node.conversion) unit = node.unit else: unit = None return (data, unit)
def get_timeseries_in_units(node: TimeSeries, istart=None, istop=None): '\n Convert data into the designated units\n\n Parameters\n ----------\n node: pynwb.TimeSeries\n istart: int\n istop: int\n\n Returns\n -------\n numpy.ndarray, str\n\n ' data = node.data[istart:istop] if (node.conversion and np.isfinite(node.conversion)): data = (data * node.conversion) unit = node.unit else: unit = None return (data, unit)<|docstring|>Convert data into the designated units Parameters ---------- node: pynwb.TimeSeries istart: int istop: int Returns ------- numpy.ndarray, str<|endoftext|>
d441406894a29043700e064f10f9a73394af04608836efae8dbfc34b433bbc78
def timeseries_time_to_ind(node: TimeSeries, time, ind_min=None, ind_max=None) -> int: '\n Get the index of a certain time for any TimeSeries. For TimeSeries that use timestamps, bisect is used. You can\n optionally provide ind_min and ind_max to constrain the search.\n\n Parameters\n ----------\n node: pynwb.TimeSeries\n time: float\n ind_min: int, optional\n ind_max: int, optional\n\n Returns\n -------\n\n ' if (node.timestamps is not None): kwargs = dict() if (ind_min is not None): kwargs.update(lo=ind_min) if (ind_max is not None): kwargs.update(hi=ind_max) return bisect(node.timestamps, time, **kwargs) else: return int(np.ceil(((time - node.starting_time) * node.rate)))
Get the index of a certain time for any TimeSeries. For TimeSeries that use timestamps, bisect is used. You can optionally provide ind_min and ind_max to constrain the search. Parameters ---------- node: pynwb.TimeSeries time: float ind_min: int, optional ind_max: int, optional Returns -------
nwbwidgets/utils/timeseries.py
timeseries_time_to_ind
lvsltz/nwb-jupyter-widgets
0
python
def timeseries_time_to_ind(node: TimeSeries, time, ind_min=None, ind_max=None) -> int: '\n Get the index of a certain time for any TimeSeries. For TimeSeries that use timestamps, bisect is used. You can\n optionally provide ind_min and ind_max to constrain the search.\n\n Parameters\n ----------\n node: pynwb.TimeSeries\n time: float\n ind_min: int, optional\n ind_max: int, optional\n\n Returns\n -------\n\n ' if (node.timestamps is not None): kwargs = dict() if (ind_min is not None): kwargs.update(lo=ind_min) if (ind_max is not None): kwargs.update(hi=ind_max) return bisect(node.timestamps, time, **kwargs) else: return int(np.ceil(((time - node.starting_time) * node.rate)))
def timeseries_time_to_ind(node: TimeSeries, time, ind_min=None, ind_max=None) -> int: '\n Get the index of a certain time for any TimeSeries. For TimeSeries that use timestamps, bisect is used. You can\n optionally provide ind_min and ind_max to constrain the search.\n\n Parameters\n ----------\n node: pynwb.TimeSeries\n time: float\n ind_min: int, optional\n ind_max: int, optional\n\n Returns\n -------\n\n ' if (node.timestamps is not None): kwargs = dict() if (ind_min is not None): kwargs.update(lo=ind_min) if (ind_max is not None): kwargs.update(hi=ind_max) return bisect(node.timestamps, time, **kwargs) else: return int(np.ceil(((time - node.starting_time) * node.rate)))<|docstring|>Get the index of a certain time for any TimeSeries. For TimeSeries that use timestamps, bisect is used. You can optionally provide ind_min and ind_max to constrain the search. Parameters ---------- node: pynwb.TimeSeries time: float ind_min: int, optional ind_max: int, optional Returns -------<|endoftext|>
abd0e677282dcb07281619d704937eee80e28614427287ba260348a7611fc7af
def align_by_times(timeseries: TimeSeries, starts, stops): '\n Args:\n timeseries: TimeSeries\n starts: array-like\n stops: array-like\n Returns:\n np.array(shape=(n_trials, n_time, ...))\n ' out = [] for (istart, istop) in zip(starts, stops): ind_start = timeseries_time_to_ind(timeseries, istart) ind_stop = timeseries_time_to_ind(timeseries, istop, ind_min=ind_start) out.append(timeseries.data[ind_start:ind_stop]) return np.array(out)
Args: timeseries: TimeSeries starts: array-like stops: array-like Returns: np.array(shape=(n_trials, n_time, ...))
nwbwidgets/utils/timeseries.py
align_by_times
lvsltz/nwb-jupyter-widgets
0
python
def align_by_times(timeseries: TimeSeries, starts, stops): '\n Args:\n timeseries: TimeSeries\n starts: array-like\n stops: array-like\n Returns:\n np.array(shape=(n_trials, n_time, ...))\n ' out = [] for (istart, istop) in zip(starts, stops): ind_start = timeseries_time_to_ind(timeseries, istart) ind_stop = timeseries_time_to_ind(timeseries, istop, ind_min=ind_start) out.append(timeseries.data[ind_start:ind_stop]) return np.array(out)
def align_by_times(timeseries: TimeSeries, starts, stops): '\n Args:\n timeseries: TimeSeries\n starts: array-like\n stops: array-like\n Returns:\n np.array(shape=(n_trials, n_time, ...))\n ' out = [] for (istart, istop) in zip(starts, stops): ind_start = timeseries_time_to_ind(timeseries, istart) ind_stop = timeseries_time_to_ind(timeseries, istop, ind_min=ind_start) out.append(timeseries.data[ind_start:ind_stop]) return np.array(out)<|docstring|>Args: timeseries: TimeSeries starts: array-like stops: array-like Returns: np.array(shape=(n_trials, n_time, ...))<|endoftext|>
8eca16b6e2bd1c97eb859b3bc11d6ea0bfa84063cadfa0e7e97c1039fed76d39
def align_by_trials(timeseries: TimeSeries, start_label='start_time', stop_label=None, before=0.0, after=1.0): "\n Args:\n timeseries: TimeSeries\n start_label: str\n default: 'start_time'\n stop_label: str\n default: None (just align to start_time)\n before: float\n time after start_label in secs (positive goes back in time)\n after: float\n time after stop_label in secs (positive goes forward in time)\n Returns:\n np.array(shape=(n_trials, n_time, ...))\n " trials = timeseries.get_ancestor('NWBFile').trials return align_by_time_intervals(timeseries, trials, start_label, stop_label, before, after)
Args: timeseries: TimeSeries start_label: str default: 'start_time' stop_label: str default: None (just align to start_time) before: float time after start_label in secs (positive goes back in time) after: float time after stop_label in secs (positive goes forward in time) Returns: np.array(shape=(n_trials, n_time, ...))
nwbwidgets/utils/timeseries.py
align_by_trials
lvsltz/nwb-jupyter-widgets
0
python
def align_by_trials(timeseries: TimeSeries, start_label='start_time', stop_label=None, before=0.0, after=1.0): "\n Args:\n timeseries: TimeSeries\n start_label: str\n default: 'start_time'\n stop_label: str\n default: None (just align to start_time)\n before: float\n time after start_label in secs (positive goes back in time)\n after: float\n time after stop_label in secs (positive goes forward in time)\n Returns:\n np.array(shape=(n_trials, n_time, ...))\n " trials = timeseries.get_ancestor('NWBFile').trials return align_by_time_intervals(timeseries, trials, start_label, stop_label, before, after)
def align_by_trials(timeseries: TimeSeries, start_label='start_time', stop_label=None, before=0.0, after=1.0): "\n Args:\n timeseries: TimeSeries\n start_label: str\n default: 'start_time'\n stop_label: str\n default: None (just align to start_time)\n before: float\n time after start_label in secs (positive goes back in time)\n after: float\n time after stop_label in secs (positive goes forward in time)\n Returns:\n np.array(shape=(n_trials, n_time, ...))\n " trials = timeseries.get_ancestor('NWBFile').trials return align_by_time_intervals(timeseries, trials, start_label, stop_label, before, after)<|docstring|>Args: timeseries: TimeSeries start_label: str default: 'start_time' stop_label: str default: None (just align to start_time) before: float time after start_label in secs (positive goes back in time) after: float time after stop_label in secs (positive goes forward in time) Returns: np.array(shape=(n_trials, n_time, ...))<|endoftext|>
5cdbd7ea87913e55f23ba25a3ba350de9baa93eb68e7f6566cda4447dd30a71f
def align_by_time_intervals(timeseries: TimeSeries, intervals, start_label='start_time', stop_label='stop_time', before=0.0, after=0.0): "\n Args:\n timeseries: pynwb.TimeSeries\n intervals: pynwb.epoch.TimeIntervals\n start_label: str\n default: 'start_time'\n stop_label: str\n default: 'stop_time'\n before: float\n time after start_label in secs (positive goes back in time)\n after: float\n time after stop_label in secs (positive goes forward in time)\n Returns:\n np.array(shape=(n_trials, n_time, ...))\n " if (stop_label is None): stop_label = 'start_time' starts = (np.array(intervals[start_label][:]) - before) stops = (np.array(intervals[stop_label][:]) + after) return align_by_times(timeseries, starts, stops)
Args: timeseries: pynwb.TimeSeries intervals: pynwb.epoch.TimeIntervals start_label: str default: 'start_time' stop_label: str default: 'stop_time' before: float time after start_label in secs (positive goes back in time) after: float time after stop_label in secs (positive goes forward in time) Returns: np.array(shape=(n_trials, n_time, ...))
nwbwidgets/utils/timeseries.py
align_by_time_intervals
lvsltz/nwb-jupyter-widgets
0
python
def align_by_time_intervals(timeseries: TimeSeries, intervals, start_label='start_time', stop_label='stop_time', before=0.0, after=0.0): "\n Args:\n timeseries: pynwb.TimeSeries\n intervals: pynwb.epoch.TimeIntervals\n start_label: str\n default: 'start_time'\n stop_label: str\n default: 'stop_time'\n before: float\n time after start_label in secs (positive goes back in time)\n after: float\n time after stop_label in secs (positive goes forward in time)\n Returns:\n np.array(shape=(n_trials, n_time, ...))\n " if (stop_label is None): stop_label = 'start_time' starts = (np.array(intervals[start_label][:]) - before) stops = (np.array(intervals[stop_label][:]) + after) return align_by_times(timeseries, starts, stops)
def align_by_time_intervals(timeseries: TimeSeries, intervals, start_label='start_time', stop_label='stop_time', before=0.0, after=0.0): "\n Args:\n timeseries: pynwb.TimeSeries\n intervals: pynwb.epoch.TimeIntervals\n start_label: str\n default: 'start_time'\n stop_label: str\n default: 'stop_time'\n before: float\n time after start_label in secs (positive goes back in time)\n after: float\n time after stop_label in secs (positive goes forward in time)\n Returns:\n np.array(shape=(n_trials, n_time, ...))\n " if (stop_label is None): stop_label = 'start_time' starts = (np.array(intervals[start_label][:]) - before) stops = (np.array(intervals[stop_label][:]) + after) return align_by_times(timeseries, starts, stops)<|docstring|>Args: timeseries: pynwb.TimeSeries intervals: pynwb.epoch.TimeIntervals start_label: str default: 'start_time' stop_label: str default: 'stop_time' before: float time after start_label in secs (positive goes back in time) after: float time after stop_label in secs (positive goes forward in time) Returns: np.array(shape=(n_trials, n_time, ...))<|endoftext|>
f95d9de19b48129e8608da279a3a299d66fb957402694500c78542e39d19d995
def parse_tags(timeseries, args): 'Returns the tags selectors to set for any uploaded documents' if (not args.tags): return None attachment_tags = {tag['Key']: tag for tag in timeseries.provisioning.get('/tags')['Results'] if tag['AppliesToAttachments']} tag_selectors = [] for pair in [[s.strip() for s in pair.split(':', 1)] for pair in args.tags.split(',')]: key = pair[0] if (key not in attachment_tags): raise NameError(f"'{key}' is not a valid attachment tag key.") tag = attachment_tags[key] tag_selector = {'UniqueId': tag['UniqueId']} if (len(pair) == 2): tag_selector['Value'] = pair[1] tag_selectors.append(tag_selector) return tag_selectors
Returns the tags selectors to set for any uploaded documents
TimeSeries/PublicApis/Python/ApprovalReport/approval_report.py
parse_tags
AquaticInformatics/Examples
12
python
def parse_tags(timeseries, args): if (not args.tags): return None attachment_tags = {tag['Key']: tag for tag in timeseries.provisioning.get('/tags')['Results'] if tag['AppliesToAttachments']} tag_selectors = [] for pair in [[s.strip() for s in pair.split(':', 1)] for pair in args.tags.split(',')]: key = pair[0] if (key not in attachment_tags): raise NameError(f"'{key}' is not a valid attachment tag key.") tag = attachment_tags[key] tag_selector = {'UniqueId': tag['UniqueId']} if (len(pair) == 2): tag_selector['Value'] = pair[1] tag_selectors.append(tag_selector) return tag_selectors
def parse_tags(timeseries, args): if (not args.tags): return None attachment_tags = {tag['Key']: tag for tag in timeseries.provisioning.get('/tags')['Results'] if tag['AppliesToAttachments']} tag_selectors = [] for pair in [[s.strip() for s in pair.split(':', 1)] for pair in args.tags.split(',')]: key = pair[0] if (key not in attachment_tags): raise NameError(f"'{key}' is not a valid attachment tag key.") tag = attachment_tags[key] tag_selector = {'UniqueId': tag['UniqueId']} if (len(pair) == 2): tag_selector['Value'] = pair[1] tag_selectors.append(tag_selector) return tag_selectors<|docstring|>Returns the tags selectors to set for any uploaded documents<|endoftext|>
b974c46fb732ac708b3a022fda04250bcb60de41275e51adf12b53fc9d4a5d6e
def examine_location(timeseries, location, query_from, query_to, tags, report_filename): 'Examine the approvals of one location and upload the report' location_identifier = location['Identifier'] log.info(f'location_identifier={location_identifier!r}: Loading ...') rating_models = timeseries.getRatings(locationIdentifier=location_identifier) log.info(f'{location_identifier}: {len(rating_models)} rating models.') for model in rating_models: model_identifier = model['Identifier'] try: curves = timeseries.publish.get('/GetRatingCurveList', params={'RatingModelIdentifier': model_identifier, 'QueryFrom': query_from, 'QueryTo': query_to})['RatingCurves'] log.info(f'{model_identifier}: {len(curves)} curves.') except HTTPError as e: log.error(f'{model_identifier}: {e}') visits = timeseries.publish.get('/GetFieldVisitDataByLocation', params={'LocationIdentifier': location_identifier})['FieldVisitData'] log.info(f'{location_identifier}: {len(visits)} field visits.') series = timeseries.getTimeSeriesDescriptions(locationIdentifier=location_identifier) log.info(f'{location_identifier}: {len(series)} time-series') for ts in series: ts_identifier = ts['Identifier'] data = timeseries.getTimeSeriesCorrectedData(timeSeriesIdentifier=ts_identifier, queryFrom=query_from, queryTo=query_to, getParts='MetadataOnly') log.info(f"{ts_identifier}: {len(data['Approvals'])} approval regions.") report_content = f'''Approval report =============== Location: {location['Identifier']} ({location['Name']}) Rating Models: {len(rating_models)} Visits:{len(visits)} Time-Series: {len(series)} ''' attachment = timeseries.acquisition.post(f"/locations/{location['UniqueId']}/attachments", params={'Tags': timeseries.acquisition.toJSV(tags)}, files={'file': (report_filename, report_content, 'text/plain')}) log.info(f"""{location_identifier}: Uploaded "{report_filename}" to {attachment['Url']} with tags={tags!r}""")
Examine the approvals of one location and upload the report
TimeSeries/PublicApis/Python/ApprovalReport/approval_report.py
examine_location
AquaticInformatics/Examples
12
python
def examine_location(timeseries, location, query_from, query_to, tags, report_filename): location_identifier = location['Identifier'] log.info(f'location_identifier={location_identifier!r}: Loading ...') rating_models = timeseries.getRatings(locationIdentifier=location_identifier) log.info(f'{location_identifier}: {len(rating_models)} rating models.') for model in rating_models: model_identifier = model['Identifier'] try: curves = timeseries.publish.get('/GetRatingCurveList', params={'RatingModelIdentifier': model_identifier, 'QueryFrom': query_from, 'QueryTo': query_to})['RatingCurves'] log.info(f'{model_identifier}: {len(curves)} curves.') except HTTPError as e: log.error(f'{model_identifier}: {e}') visits = timeseries.publish.get('/GetFieldVisitDataByLocation', params={'LocationIdentifier': location_identifier})['FieldVisitData'] log.info(f'{location_identifier}: {len(visits)} field visits.') series = timeseries.getTimeSeriesDescriptions(locationIdentifier=location_identifier) log.info(f'{location_identifier}: {len(series)} time-series') for ts in series: ts_identifier = ts['Identifier'] data = timeseries.getTimeSeriesCorrectedData(timeSeriesIdentifier=ts_identifier, queryFrom=query_from, queryTo=query_to, getParts='MetadataOnly') log.info(f"{ts_identifier}: {len(data['Approvals'])} approval regions.") report_content = f'Approval report =============== Location: {location['Identifier']} ({location['Name']}) Rating Models: {len(rating_models)} Visits:{len(visits)} Time-Series: {len(series)} ' attachment = timeseries.acquisition.post(f"/locations/{location['UniqueId']}/attachments", params={'Tags': timeseries.acquisition.toJSV(tags)}, files={'file': (report_filename, report_content, 'text/plain')}) log.info(f"{location_identifier}: Uploaded "{report_filename}" to {attachment['Url']} with tags={tags!r}")
def examine_location(timeseries, location, query_from, query_to, tags, report_filename): location_identifier = location['Identifier'] log.info(f'location_identifier={location_identifier!r}: Loading ...') rating_models = timeseries.getRatings(locationIdentifier=location_identifier) log.info(f'{location_identifier}: {len(rating_models)} rating models.') for model in rating_models: model_identifier = model['Identifier'] try: curves = timeseries.publish.get('/GetRatingCurveList', params={'RatingModelIdentifier': model_identifier, 'QueryFrom': query_from, 'QueryTo': query_to})['RatingCurves'] log.info(f'{model_identifier}: {len(curves)} curves.') except HTTPError as e: log.error(f'{model_identifier}: {e}') visits = timeseries.publish.get('/GetFieldVisitDataByLocation', params={'LocationIdentifier': location_identifier})['FieldVisitData'] log.info(f'{location_identifier}: {len(visits)} field visits.') series = timeseries.getTimeSeriesDescriptions(locationIdentifier=location_identifier) log.info(f'{location_identifier}: {len(series)} time-series') for ts in series: ts_identifier = ts['Identifier'] data = timeseries.getTimeSeriesCorrectedData(timeSeriesIdentifier=ts_identifier, queryFrom=query_from, queryTo=query_to, getParts='MetadataOnly') log.info(f"{ts_identifier}: {len(data['Approvals'])} approval regions.") report_content = f'Approval report =============== Location: {location['Identifier']} ({location['Name']}) Rating Models: {len(rating_models)} Visits:{len(visits)} Time-Series: {len(series)} ' attachment = timeseries.acquisition.post(f"/locations/{location['UniqueId']}/attachments", params={'Tags': timeseries.acquisition.toJSV(tags)}, files={'file': (report_filename, report_content, 'text/plain')}) log.info(f"{location_identifier}: Uploaded "{report_filename}" to {attachment['Url']} with tags={tags!r}")<|docstring|>Examine the approvals of one location and upload the report<|endoftext|>
ebf41ed191cad2939e15d7defe6bd521d0ca37cca2cf4a067ec6994c3845e9c2
def rand_rotation_matrix(deflection=1.0, z_only=True, seed=None): 'Creates a random rotation matrix.\n\n deflection: the magnitude of the rotation. For 0, no rotation; for 1, completely random\n rotation. Small deflection => small perturbation.\n\n DOI: http://www.realtimerendering.com/resources/GraphicsGems/gemsiii/rand_rotation.c\n http://blog.lostinmyterminal.com/python/2015/05/12/random-rotation-matrix.html\n ' if (seed is not None): np.random.seed(seed) randnums = np.random.uniform(size=(3,)) (theta, phi, z) = randnums theta = (((theta * 2.0) * deflection) * np.pi) phi = ((phi * 2.0) * np.pi) z = ((z * 2.0) * deflection) st = np.sin(theta) ct = np.cos(theta) R = np.array(((ct, st, 0), ((- st), ct, 0), (0, 0, 1))) if (not z_only): r = np.sqrt(z) V = ((np.sin(phi) * r), (np.cos(phi) * r), np.sqrt((2.0 - z))) M = (np.outer(V, V) - np.eye(3)).dot(R) else: M = R return M
Creates a random rotation matrix. deflection: the magnitude of the rotation. For 0, no rotation; for 1, completely random rotation. Small deflection => small perturbation. DOI: http://www.realtimerendering.com/resources/GraphicsGems/gemsiii/rand_rotation.c http://blog.lostinmyterminal.com/python/2015/05/12/random-rotation-matrix.html
src/general_utils.py
rand_rotation_matrix
itailang/geometric_adv
21
python
def rand_rotation_matrix(deflection=1.0, z_only=True, seed=None): 'Creates a random rotation matrix.\n\n deflection: the magnitude of the rotation. For 0, no rotation; for 1, completely random\n rotation. Small deflection => small perturbation.\n\n DOI: http://www.realtimerendering.com/resources/GraphicsGems/gemsiii/rand_rotation.c\n http://blog.lostinmyterminal.com/python/2015/05/12/random-rotation-matrix.html\n ' if (seed is not None): np.random.seed(seed) randnums = np.random.uniform(size=(3,)) (theta, phi, z) = randnums theta = (((theta * 2.0) * deflection) * np.pi) phi = ((phi * 2.0) * np.pi) z = ((z * 2.0) * deflection) st = np.sin(theta) ct = np.cos(theta) R = np.array(((ct, st, 0), ((- st), ct, 0), (0, 0, 1))) if (not z_only): r = np.sqrt(z) V = ((np.sin(phi) * r), (np.cos(phi) * r), np.sqrt((2.0 - z))) M = (np.outer(V, V) - np.eye(3)).dot(R) else: M = R return M
def rand_rotation_matrix(deflection=1.0, z_only=True, seed=None): 'Creates a random rotation matrix.\n\n deflection: the magnitude of the rotation. For 0, no rotation; for 1, completely random\n rotation. Small deflection => small perturbation.\n\n DOI: http://www.realtimerendering.com/resources/GraphicsGems/gemsiii/rand_rotation.c\n http://blog.lostinmyterminal.com/python/2015/05/12/random-rotation-matrix.html\n ' if (seed is not None): np.random.seed(seed) randnums = np.random.uniform(size=(3,)) (theta, phi, z) = randnums theta = (((theta * 2.0) * deflection) * np.pi) phi = ((phi * 2.0) * np.pi) z = ((z * 2.0) * deflection) st = np.sin(theta) ct = np.cos(theta) R = np.array(((ct, st, 0), ((- st), ct, 0), (0, 0, 1))) if (not z_only): r = np.sqrt(z) V = ((np.sin(phi) * r), (np.cos(phi) * r), np.sqrt((2.0 - z))) M = (np.outer(V, V) - np.eye(3)).dot(R) else: M = R return M<|docstring|>Creates a random rotation matrix. deflection: the magnitude of the rotation. For 0, no rotation; for 1, completely random rotation. Small deflection => small perturbation. DOI: http://www.realtimerendering.com/resources/GraphicsGems/gemsiii/rand_rotation.c http://blog.lostinmyterminal.com/python/2015/05/12/random-rotation-matrix.html<|endoftext|>
2b0d464291df3202d25d9081cf7c56b3ae3fbbccf409b7d25a399ca2a1de3753
def iterate_in_chunks(l, n): "Yield successive 'n'-sized chunks from iterable 'l'.\n Note: last chunk will be smaller than l if n doesn't divide l perfectly.\n " for i in range(0, len(l), n): (yield l[i:(i + n)])
Yield successive 'n'-sized chunks from iterable 'l'. Note: last chunk will be smaller than l if n doesn't divide l perfectly.
src/general_utils.py
iterate_in_chunks
itailang/geometric_adv
21
python
def iterate_in_chunks(l, n): "Yield successive 'n'-sized chunks from iterable 'l'.\n Note: last chunk will be smaller than l if n doesn't divide l perfectly.\n " for i in range(0, len(l), n): (yield l[i:(i + n)])
def iterate_in_chunks(l, n): "Yield successive 'n'-sized chunks from iterable 'l'.\n Note: last chunk will be smaller than l if n doesn't divide l perfectly.\n " for i in range(0, len(l), n): (yield l[i:(i + n)])<|docstring|>Yield successive 'n'-sized chunks from iterable 'l'. Note: last chunk will be smaller than l if n doesn't divide l perfectly.<|endoftext|>
fdfcc7f7f1bd6b74247e3a713f055857c7e389f771f4360301a99ce6a01409af
def unit_cube_grid_point_cloud(resolution, clip_sphere=False): 'Returns the center coordinates of each cell of a 3D grid with resolution^3 cells,\n that is placed in the unit-cube.\n If clip_sphere it True it drops the "corner" cells that lie outside the unit-sphere.\n ' grid = np.ndarray((resolution, resolution, resolution, 3), np.float32) spacing = (1.0 / float((resolution - 1))) for i in range(resolution): for j in range(resolution): for k in range(resolution): grid[(i, j, k, 0)] = ((i * spacing) - 0.5) grid[(i, j, k, 1)] = ((j * spacing) - 0.5) grid[(i, j, k, 2)] = ((k * spacing) - 0.5) if clip_sphere: grid = grid.reshape((- 1), 3) grid = grid[(norm(grid, axis=1) <= 0.5)] return (grid, spacing)
Returns the center coordinates of each cell of a 3D grid with resolution^3 cells, that is placed in the unit-cube. If clip_sphere it True it drops the "corner" cells that lie outside the unit-sphere.
src/general_utils.py
unit_cube_grid_point_cloud
itailang/geometric_adv
21
python
def unit_cube_grid_point_cloud(resolution, clip_sphere=False): 'Returns the center coordinates of each cell of a 3D grid with resolution^3 cells,\n that is placed in the unit-cube.\n If clip_sphere it True it drops the "corner" cells that lie outside the unit-sphere.\n ' grid = np.ndarray((resolution, resolution, resolution, 3), np.float32) spacing = (1.0 / float((resolution - 1))) for i in range(resolution): for j in range(resolution): for k in range(resolution): grid[(i, j, k, 0)] = ((i * spacing) - 0.5) grid[(i, j, k, 1)] = ((j * spacing) - 0.5) grid[(i, j, k, 2)] = ((k * spacing) - 0.5) if clip_sphere: grid = grid.reshape((- 1), 3) grid = grid[(norm(grid, axis=1) <= 0.5)] return (grid, spacing)
def unit_cube_grid_point_cloud(resolution, clip_sphere=False): 'Returns the center coordinates of each cell of a 3D grid with resolution^3 cells,\n that is placed in the unit-cube.\n If clip_sphere it True it drops the "corner" cells that lie outside the unit-sphere.\n ' grid = np.ndarray((resolution, resolution, resolution, 3), np.float32) spacing = (1.0 / float((resolution - 1))) for i in range(resolution): for j in range(resolution): for k in range(resolution): grid[(i, j, k, 0)] = ((i * spacing) - 0.5) grid[(i, j, k, 1)] = ((j * spacing) - 0.5) grid[(i, j, k, 2)] = ((k * spacing) - 0.5) if clip_sphere: grid = grid.reshape((- 1), 3) grid = grid[(norm(grid, axis=1) <= 0.5)] return (grid, spacing)<|docstring|>Returns the center coordinates of each cell of a 3D grid with resolution^3 cells, that is placed in the unit-cube. If clip_sphere it True it drops the "corner" cells that lie outside the unit-sphere.<|endoftext|>
44cb782f6df6a24ff47eb81fd6b5e264323fc8b55ec686998f11bcc6d2dd6d44
def dropout_train(m): '\n Sets dropout modules to train mode, for added noise in the generator\n ' classname = m.__class__.__name__ if (classname.find('Dropout') != (- 1)): m.train()
Sets dropout modules to train mode, for added noise in the generator
src/netreg/utils.py
dropout_train
AWilcke/Dissertation
0
python
def dropout_train(m): '\n \n ' classname = m.__class__.__name__ if (classname.find('Dropout') != (- 1)): m.train()
def dropout_train(m): '\n \n ' classname = m.__class__.__name__ if (classname.find('Dropout') != (- 1)): m.train()<|docstring|>Sets dropout modules to train mode, for added noise in the generator<|endoftext|>
7f8515b3cb8b79b1ce94bad4511da95099332b146aa11acd25eb5f8bdf6a690b
def factory(msgtype, endpoint_context, **kwargs): "\n Factory method that can be used to easily instantiate a class instance\n\n :param msgtype: The name of the class\n :param kwargs: Keyword arguments\n :return: An instance of the class or None if the name doesn't match any\n known class.\n " for (name, obj) in inspect.getmembers(sys.modules[__name__]): if (inspect.isclass(obj) and issubclass(obj, AuthzHandling)): try: if (obj.__name__ == msgtype): return obj(endpoint_context, **kwargs) except AttributeError: pass
Factory method that can be used to easily instantiate a class instance :param msgtype: The name of the class :param kwargs: Keyword arguments :return: An instance of the class or None if the name doesn't match any known class.
src/oidcendpoint/authz/__init__.py
factory
sklemer1/oidcendpoint
0
python
def factory(msgtype, endpoint_context, **kwargs): "\n Factory method that can be used to easily instantiate a class instance\n\n :param msgtype: The name of the class\n :param kwargs: Keyword arguments\n :return: An instance of the class or None if the name doesn't match any\n known class.\n " for (name, obj) in inspect.getmembers(sys.modules[__name__]): if (inspect.isclass(obj) and issubclass(obj, AuthzHandling)): try: if (obj.__name__ == msgtype): return obj(endpoint_context, **kwargs) except AttributeError: pass
def factory(msgtype, endpoint_context, **kwargs): "\n Factory method that can be used to easily instantiate a class instance\n\n :param msgtype: The name of the class\n :param kwargs: Keyword arguments\n :return: An instance of the class or None if the name doesn't match any\n known class.\n " for (name, obj) in inspect.getmembers(sys.modules[__name__]): if (inspect.isclass(obj) and issubclass(obj, AuthzHandling)): try: if (obj.__name__ == msgtype): return obj(endpoint_context, **kwargs) except AttributeError: pass<|docstring|>Factory method that can be used to easily instantiate a class instance :param msgtype: The name of the class :param kwargs: Keyword arguments :return: An instance of the class or None if the name doesn't match any known class.<|endoftext|>
f7b7cf3d84874c1f049323b79a2fced6b5d98aa1b4191e2975629284a1607516
def custom_load_entry_point(group, name): 'Function that mocks `aiida.plugins.entry_point.load_entry_point` that is called by factories.' @calcfunction def calc_function(): pass @workfunction def work_function(): pass entry_points = {'aiida.calculations': {'calc_job': CalcJob, 'calc_function': calc_function, 'work_function': work_function, 'work_chain': WorkChain}, 'aiida.data': {'valid': Data, 'invalid': Node}, 'aiida.tools.dbimporters': {'valid': DbImporter, 'invalid': Node}, 'aiida.tools.data.orbitals': {'valid': Orbital, 'invalid': Node}, 'aiida.parsers': {'valid': Parser, 'invalid': Node}, 'aiida.schedulers': {'valid': Scheduler, 'invalid': Node}, 'aiida.transports': {'valid': Transport, 'invalid': Node}, 'aiida.workflows': {'calc_job': CalcJob, 'calc_function': calc_function, 'work_function': work_function, 'work_chain': WorkChain}} return entry_points[group][name]
Function that mocks `aiida.plugins.entry_point.load_entry_point` that is called by factories.
tests/plugins/test_factories.py
custom_load_entry_point
eimrek/aiida-core
1
python
def custom_load_entry_point(group, name): @calcfunction def calc_function(): pass @workfunction def work_function(): pass entry_points = {'aiida.calculations': {'calc_job': CalcJob, 'calc_function': calc_function, 'work_function': work_function, 'work_chain': WorkChain}, 'aiida.data': {'valid': Data, 'invalid': Node}, 'aiida.tools.dbimporters': {'valid': DbImporter, 'invalid': Node}, 'aiida.tools.data.orbitals': {'valid': Orbital, 'invalid': Node}, 'aiida.parsers': {'valid': Parser, 'invalid': Node}, 'aiida.schedulers': {'valid': Scheduler, 'invalid': Node}, 'aiida.transports': {'valid': Transport, 'invalid': Node}, 'aiida.workflows': {'calc_job': CalcJob, 'calc_function': calc_function, 'work_function': work_function, 'work_chain': WorkChain}} return entry_points[group][name]
def custom_load_entry_point(group, name): @calcfunction def calc_function(): pass @workfunction def work_function(): pass entry_points = {'aiida.calculations': {'calc_job': CalcJob, 'calc_function': calc_function, 'work_function': work_function, 'work_chain': WorkChain}, 'aiida.data': {'valid': Data, 'invalid': Node}, 'aiida.tools.dbimporters': {'valid': DbImporter, 'invalid': Node}, 'aiida.tools.data.orbitals': {'valid': Orbital, 'invalid': Node}, 'aiida.parsers': {'valid': Parser, 'invalid': Node}, 'aiida.schedulers': {'valid': Scheduler, 'invalid': Node}, 'aiida.transports': {'valid': Transport, 'invalid': Node}, 'aiida.workflows': {'calc_job': CalcJob, 'calc_function': calc_function, 'work_function': work_function, 'work_chain': WorkChain}} return entry_points[group][name]<|docstring|>Function that mocks `aiida.plugins.entry_point.load_entry_point` that is called by factories.<|endoftext|>
49197a6b5dc231471f56a91624ec44518bceeb4038c0387d523ad92559c8c78b
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_calculation_factory(self): 'Test the `CalculationFactory`.' plugin = factories.CalculationFactory('calc_function') self.assertEqual(plugin.is_process_function, True) self.assertEqual(plugin.node_class, CalcFunctionNode) plugin = factories.CalculationFactory('calc_job') self.assertEqual(plugin, CalcJob) with self.assertRaises(InvalidEntryPointTypeError): factories.CalculationFactory('work_function') with self.assertRaises(InvalidEntryPointTypeError): factories.CalculationFactory('work_chain')
Test the `CalculationFactory`.
tests/plugins/test_factories.py
test_calculation_factory
eimrek/aiida-core
1
python
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_calculation_factory(self): plugin = factories.CalculationFactory('calc_function') self.assertEqual(plugin.is_process_function, True) self.assertEqual(plugin.node_class, CalcFunctionNode) plugin = factories.CalculationFactory('calc_job') self.assertEqual(plugin, CalcJob) with self.assertRaises(InvalidEntryPointTypeError): factories.CalculationFactory('work_function') with self.assertRaises(InvalidEntryPointTypeError): factories.CalculationFactory('work_chain')
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_calculation_factory(self): plugin = factories.CalculationFactory('calc_function') self.assertEqual(plugin.is_process_function, True) self.assertEqual(plugin.node_class, CalcFunctionNode) plugin = factories.CalculationFactory('calc_job') self.assertEqual(plugin, CalcJob) with self.assertRaises(InvalidEntryPointTypeError): factories.CalculationFactory('work_function') with self.assertRaises(InvalidEntryPointTypeError): factories.CalculationFactory('work_chain')<|docstring|>Test the `CalculationFactory`.<|endoftext|>
1d9cfd81e02e7d8cfd06365422976e54eae3b064911d607c75f267619a196cea
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_workflow_factory(self): 'Test the `WorkflowFactory`.' plugin = factories.WorkflowFactory('work_function') self.assertEqual(plugin.is_process_function, True) self.assertEqual(plugin.node_class, WorkFunctionNode) plugin = factories.WorkflowFactory('work_chain') self.assertEqual(plugin, WorkChain) with self.assertRaises(InvalidEntryPointTypeError): factories.WorkflowFactory('calc_function') with self.assertRaises(InvalidEntryPointTypeError): factories.WorkflowFactory('calc_job')
Test the `WorkflowFactory`.
tests/plugins/test_factories.py
test_workflow_factory
eimrek/aiida-core
1
python
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_workflow_factory(self): plugin = factories.WorkflowFactory('work_function') self.assertEqual(plugin.is_process_function, True) self.assertEqual(plugin.node_class, WorkFunctionNode) plugin = factories.WorkflowFactory('work_chain') self.assertEqual(plugin, WorkChain) with self.assertRaises(InvalidEntryPointTypeError): factories.WorkflowFactory('calc_function') with self.assertRaises(InvalidEntryPointTypeError): factories.WorkflowFactory('calc_job')
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_workflow_factory(self): plugin = factories.WorkflowFactory('work_function') self.assertEqual(plugin.is_process_function, True) self.assertEqual(plugin.node_class, WorkFunctionNode) plugin = factories.WorkflowFactory('work_chain') self.assertEqual(plugin, WorkChain) with self.assertRaises(InvalidEntryPointTypeError): factories.WorkflowFactory('calc_function') with self.assertRaises(InvalidEntryPointTypeError): factories.WorkflowFactory('calc_job')<|docstring|>Test the `WorkflowFactory`.<|endoftext|>
dcc1570abd396974e7dbab1919e7ac970e43987fb32844b44f42e7a67674c183
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_data_factory(self): 'Test the `DataFactory`.' plugin = factories.DataFactory('valid') self.assertEqual(plugin, Data) with self.assertRaises(InvalidEntryPointTypeError): factories.DataFactory('invalid')
Test the `DataFactory`.
tests/plugins/test_factories.py
test_data_factory
eimrek/aiida-core
1
python
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_data_factory(self): plugin = factories.DataFactory('valid') self.assertEqual(plugin, Data) with self.assertRaises(InvalidEntryPointTypeError): factories.DataFactory('invalid')
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_data_factory(self): plugin = factories.DataFactory('valid') self.assertEqual(plugin, Data) with self.assertRaises(InvalidEntryPointTypeError): factories.DataFactory('invalid')<|docstring|>Test the `DataFactory`.<|endoftext|>
7139800563613aff388e627416a930f11dc49efbd6ba9c5f74300b8fa8fd1461
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_db_importer_factory(self): 'Test the `DbImporterFactory`.' plugin = factories.DbImporterFactory('valid') self.assertEqual(plugin, DbImporter) with self.assertRaises(InvalidEntryPointTypeError): factories.DbImporterFactory('invalid')
Test the `DbImporterFactory`.
tests/plugins/test_factories.py
test_db_importer_factory
eimrek/aiida-core
1
python
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_db_importer_factory(self): plugin = factories.DbImporterFactory('valid') self.assertEqual(plugin, DbImporter) with self.assertRaises(InvalidEntryPointTypeError): factories.DbImporterFactory('invalid')
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_db_importer_factory(self): plugin = factories.DbImporterFactory('valid') self.assertEqual(plugin, DbImporter) with self.assertRaises(InvalidEntryPointTypeError): factories.DbImporterFactory('invalid')<|docstring|>Test the `DbImporterFactory`.<|endoftext|>
93d110bb1f7844d42142667d16606959e1f256b35ea1c1fb8c61b5d2e408e870
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_orbital_factory(self): 'Test the `OrbitalFactory`.' plugin = factories.OrbitalFactory('valid') self.assertEqual(plugin, Orbital) with self.assertRaises(InvalidEntryPointTypeError): factories.OrbitalFactory('invalid')
Test the `OrbitalFactory`.
tests/plugins/test_factories.py
test_orbital_factory
eimrek/aiida-core
1
python
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_orbital_factory(self): plugin = factories.OrbitalFactory('valid') self.assertEqual(plugin, Orbital) with self.assertRaises(InvalidEntryPointTypeError): factories.OrbitalFactory('invalid')
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_orbital_factory(self): plugin = factories.OrbitalFactory('valid') self.assertEqual(plugin, Orbital) with self.assertRaises(InvalidEntryPointTypeError): factories.OrbitalFactory('invalid')<|docstring|>Test the `OrbitalFactory`.<|endoftext|>
3ba5a83db1506dcf62d05f0593deff0d97359d697a84fa68e6dfa4d5e9af964e
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_parser_factory(self): 'Test the `ParserFactory`.' plugin = factories.ParserFactory('valid') self.assertEqual(plugin, Parser) with self.assertRaises(InvalidEntryPointTypeError): factories.ParserFactory('invalid')
Test the `ParserFactory`.
tests/plugins/test_factories.py
test_parser_factory
eimrek/aiida-core
1
python
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_parser_factory(self): plugin = factories.ParserFactory('valid') self.assertEqual(plugin, Parser) with self.assertRaises(InvalidEntryPointTypeError): factories.ParserFactory('invalid')
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_parser_factory(self): plugin = factories.ParserFactory('valid') self.assertEqual(plugin, Parser) with self.assertRaises(InvalidEntryPointTypeError): factories.ParserFactory('invalid')<|docstring|>Test the `ParserFactory`.<|endoftext|>
b6efe56aa3a739963b54ee1b36057cc9b175160fa5c4b8d531fa3863f31b4a54
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_scheduler_factory(self): 'Test the `SchedulerFactory`.' plugin = factories.SchedulerFactory('valid') self.assertEqual(plugin, Scheduler) with self.assertRaises(InvalidEntryPointTypeError): factories.SchedulerFactory('invalid')
Test the `SchedulerFactory`.
tests/plugins/test_factories.py
test_scheduler_factory
eimrek/aiida-core
1
python
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_scheduler_factory(self): plugin = factories.SchedulerFactory('valid') self.assertEqual(plugin, Scheduler) with self.assertRaises(InvalidEntryPointTypeError): factories.SchedulerFactory('invalid')
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_scheduler_factory(self): plugin = factories.SchedulerFactory('valid') self.assertEqual(plugin, Scheduler) with self.assertRaises(InvalidEntryPointTypeError): factories.SchedulerFactory('invalid')<|docstring|>Test the `SchedulerFactory`.<|endoftext|>
fda431ae347188799a62240b341f6f2775533530fcdc81d38daad006b56cc236
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_transport_factory(self): 'Test the `TransportFactory`.' plugin = factories.TransportFactory('valid') self.assertEqual(plugin, Transport) with self.assertRaises(InvalidEntryPointTypeError): factories.TransportFactory('invalid')
Test the `TransportFactory`.
tests/plugins/test_factories.py
test_transport_factory
eimrek/aiida-core
1
python
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_transport_factory(self): plugin = factories.TransportFactory('valid') self.assertEqual(plugin, Transport) with self.assertRaises(InvalidEntryPointTypeError): factories.TransportFactory('invalid')
@patch('aiida.plugins.entry_point.load_entry_point', custom_load_entry_point) def test_transport_factory(self): plugin = factories.TransportFactory('valid') self.assertEqual(plugin, Transport) with self.assertRaises(InvalidEntryPointTypeError): factories.TransportFactory('invalid')<|docstring|>Test the `TransportFactory`.<|endoftext|>
54e73611eae4df04a91b7813f57c321d09c8bccd987efabe040e3667d75c7313
def urlencode(query, params): '\n Correctly convert the given query and parameters into a full query+query\n string, ensuring the order of the params.\n ' return ((query + '?') + '&'.join((((key + '=') + quote_plus(str(value))) for (key, value) in params)))
Correctly convert the given query and parameters into a full query+query string, ensuring the order of the params.
python/reddit/reddit.py
urlencode
RealTimeWeb/reddit
2
python
def urlencode(query, params): '\n Correctly convert the given query and parameters into a full query+query\n string, ensuring the order of the params.\n ' return ((query + '?') + '&'.join((((key + '=') + quote_plus(str(value))) for (key, value) in params)))
def urlencode(query, params): '\n Correctly convert the given query and parameters into a full query+query\n string, ensuring the order of the params.\n ' return ((query + '?') + '&'.join((((key + '=') + quote_plus(str(value))) for (key, value) in params)))<|docstring|>Correctly convert the given query and parameters into a full query+query string, ensuring the order of the params.<|endoftext|>
3eeef84928b920689c2f59e9a3bdd4a3f2d083e96d5df5f946c1e86d173656d9
def _parse_int(value, default=0): '\n Attempt to cast *value* into an integer, returning *default* if it fails.\n ' if (value is None): return default try: return int(value) except ValueError: return default
Attempt to cast *value* into an integer, returning *default* if it fails.
python/reddit/reddit.py
_parse_int
RealTimeWeb/reddit
2
python
def _parse_int(value, default=0): '\n \n ' if (value is None): return default try: return int(value) except ValueError: return default
def _parse_int(value, default=0): '\n \n ' if (value is None): return default try: return int(value) except ValueError: return default<|docstring|>Attempt to cast *value* into an integer, returning *default* if it fails.<|endoftext|>
1393196524f589e8281855a9011aca6af3b8034c07993f721d677f8abe269d24
def _parse_float(value, default=0): '\n Attempt to cast *value* into a float, returning *default* if it fails.\n ' if (value is None): return default try: return float(value) except ValueError: return default
Attempt to cast *value* into a float, returning *default* if it fails.
python/reddit/reddit.py
_parse_float
RealTimeWeb/reddit
2
python
def _parse_float(value, default=0): '\n \n ' if (value is None): return default try: return float(value) except ValueError: return default
def _parse_float(value, default=0): '\n \n ' if (value is None): return default try: return float(value) except ValueError: return default<|docstring|>Attempt to cast *value* into a float, returning *default* if it fails.<|endoftext|>
ad3b2527f8f0a4dd9e4ffad991a0f56d87be838f8c788a184f77dfa87352788c
def _parse_boolean(value, default=False): '\n Attempt to cast *value* into a bool, returning *default* if it fails.\n ' if (value is None): return default try: return bool(value) except ValueError: return default
Attempt to cast *value* into a bool, returning *default* if it fails.
python/reddit/reddit.py
_parse_boolean
RealTimeWeb/reddit
2
python
def _parse_boolean(value, default=False): '\n \n ' if (value is None): return default try: return bool(value) except ValueError: return default
def _parse_boolean(value, default=False): '\n \n ' if (value is None): return default try: return bool(value) except ValueError: return default<|docstring|>Attempt to cast *value* into a bool, returning *default* if it fails.<|endoftext|>
8a11e5bfb92b3fabdbca79c76cdd2886081907cf46fd01deec2bbd8315b16659
def _get(url): "\n Convert a URL into it's response (a *str*).\n " if PYTHON_3: req = request.Request(url, headers=HEADER) response = request.urlopen(req) return response.read().decode('utf-8') else: req = urllib2.Request(url, headers=HEADER) response = urllib2.urlopen(req) return response.read()
Convert a URL into it's response (a *str*).
python/reddit/reddit.py
_get
RealTimeWeb/reddit
2
python
def _get(url): "\n \n " if PYTHON_3: req = request.Request(url, headers=HEADER) response = request.urlopen(req) return response.read().decode('utf-8') else: req = urllib2.Request(url, headers=HEADER) response = urllib2.urlopen(req) return response.read()
def _get(url): "\n \n " if PYTHON_3: req = request.Request(url, headers=HEADER) response = request.urlopen(req) return response.read().decode('utf-8') else: req = urllib2.Request(url, headers=HEADER) response = urllib2.urlopen(req) return response.read()<|docstring|>Convert a URL into it's response (a *str*).<|endoftext|>
bc23d8c8377f6ffa4a210f9d21ab4fb318d4b5922eb74f7e12c051c6fdb402e3
def _recursively_convert_unicode_to_str(input): '\n Force the given input to only use `str` instead of `bytes` or `unicode`.\n This works even if the input is a dict, list, \n ' if isinstance(input, dict): return {_recursively_convert_unicode_to_str(key): _recursively_convert_unicode_to_str(value) for (key, value) in input.items()} elif isinstance(input, list): return [_recursively_convert_unicode_to_str(element) for element in input] elif ((not PYTHON_3) and isinstance(input, unicode)): return input.encode('utf-8') else: return input
Force the given input to only use `str` instead of `bytes` or `unicode`. This works even if the input is a dict, list,
python/reddit/reddit.py
_recursively_convert_unicode_to_str
RealTimeWeb/reddit
2
python
def _recursively_convert_unicode_to_str(input): '\n Force the given input to only use `str` instead of `bytes` or `unicode`.\n This works even if the input is a dict, list, \n ' if isinstance(input, dict): return {_recursively_convert_unicode_to_str(key): _recursively_convert_unicode_to_str(value) for (key, value) in input.items()} elif isinstance(input, list): return [_recursively_convert_unicode_to_str(element) for element in input] elif ((not PYTHON_3) and isinstance(input, unicode)): return input.encode('utf-8') else: return input
def _recursively_convert_unicode_to_str(input): '\n Force the given input to only use `str` instead of `bytes` or `unicode`.\n This works even if the input is a dict, list, \n ' if isinstance(input, dict): return {_recursively_convert_unicode_to_str(key): _recursively_convert_unicode_to_str(value) for (key, value) in input.items()} elif isinstance(input, list): return [_recursively_convert_unicode_to_str(element) for element in input] elif ((not PYTHON_3) and isinstance(input, unicode)): return input.encode('utf-8') else: return input<|docstring|>Force the given input to only use `str` instead of `bytes` or `unicode`. This works even if the input is a dict, list,<|endoftext|>
fd1c20b4c5c79fe5d2cf6ec65c23dc544ad90f5b4dc318b4f60b1f18b67a1e54
def _from_json(data): '\n Convert the given string data into a JSON dict/list/primitive, ensuring that\n `str` are used instead of bytes.\n ' return _recursively_convert_unicode_to_str(json.loads(data))
Convert the given string data into a JSON dict/list/primitive, ensuring that `str` are used instead of bytes.
python/reddit/reddit.py
_from_json
RealTimeWeb/reddit
2
python
def _from_json(data): '\n Convert the given string data into a JSON dict/list/primitive, ensuring that\n `str` are used instead of bytes.\n ' return _recursively_convert_unicode_to_str(json.loads(data))
def _from_json(data): '\n Convert the given string data into a JSON dict/list/primitive, ensuring that\n `str` are used instead of bytes.\n ' return _recursively_convert_unicode_to_str(json.loads(data))<|docstring|>Convert the given string data into a JSON dict/list/primitive, ensuring that `str` are used instead of bytes.<|endoftext|>
98d40dc8a4a761007e8428343e145817fb48c11411152100acf8d8e1aa0c8fed
def _start_editing(pattern=_PATTERN): '\n Start adding seen entries to the cache. So, every time that you make a request,\n it will be saved to the cache. You must :ref:`_save_cache` to save the\n newly edited cache to disk, though!\n ' global _EDITABLE, _PATTERN _EDITABLE = True _PATTERN = pattern
Start adding seen entries to the cache. So, every time that you make a request, it will be saved to the cache. You must :ref:`_save_cache` to save the newly edited cache to disk, though!
python/reddit/reddit.py
_start_editing
RealTimeWeb/reddit
2
python
def _start_editing(pattern=_PATTERN): '\n Start adding seen entries to the cache. So, every time that you make a request,\n it will be saved to the cache. You must :ref:`_save_cache` to save the\n newly edited cache to disk, though!\n ' global _EDITABLE, _PATTERN _EDITABLE = True _PATTERN = pattern
def _start_editing(pattern=_PATTERN): '\n Start adding seen entries to the cache. So, every time that you make a request,\n it will be saved to the cache. You must :ref:`_save_cache` to save the\n newly edited cache to disk, though!\n ' global _EDITABLE, _PATTERN _EDITABLE = True _PATTERN = pattern<|docstring|>Start adding seen entries to the cache. So, every time that you make a request, it will be saved to the cache. You must :ref:`_save_cache` to save the newly edited cache to disk, though!<|endoftext|>
657ea61de6cb462a566e46fc9feb6a64e37d1aa7b1ac8725556ddc7c3bad5d53
def _stop_editing(): '\n Stop adding seen entries to the cache.\n ' global _EDITABLE _EDITABLE = False
Stop adding seen entries to the cache.
python/reddit/reddit.py
_stop_editing
RealTimeWeb/reddit
2
python
def _stop_editing(): '\n \n ' global _EDITABLE _EDITABLE = False
def _stop_editing(): '\n \n ' global _EDITABLE _EDITABLE = False<|docstring|>Stop adding seen entries to the cache.<|endoftext|>
adeef58c09652ee403d39a614a1de7a283ccb17e2ca1306d10d075b2eea9ca26
def connect(): '\n Connect to the online data source in order to get up-to-date information.\n :returns: void\n ' global _CONNECTED _CONNECTED = True
Connect to the online data source in order to get up-to-date information. :returns: void
python/reddit/reddit.py
connect
RealTimeWeb/reddit
2
python
def connect(): '\n Connect to the online data source in order to get up-to-date information.\n :returns: void\n ' global _CONNECTED _CONNECTED = True
def connect(): '\n Connect to the online data source in order to get up-to-date information.\n :returns: void\n ' global _CONNECTED _CONNECTED = True<|docstring|>Connect to the online data source in order to get up-to-date information. :returns: void<|endoftext|>