max_stars_repo_path
stringlengths
4
286
max_stars_repo_name
stringlengths
5
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.03M
content_cleaned
stringlengths
6
1.03M
language
stringclasses
111 values
language_score
float64
0.03
1
comments
stringlengths
0
556k
edu_score
float64
0.32
5.03
edu_int_score
int64
0
5
src/aosat/fftx.py
mfeldt/AOSAT
2
6623151
<filename>src/aosat/fftx.py # -*- coding: utf-8 -*- """ This selects the best (i.e. fastest) FFT routine to be used in AOSAT. The module will look first for CUDA, then for OpenCL, and fall back to numpy FFTs if neither is available. """ import logging log = logging.getLogger('aosat_logger') log.addHandler(logging.NullHandler()) ## ## ## Check for GPU support and select FFT function ## ## from pip._internal.utils.misc import get_installed_distributions if any(["cupy" in str(f) for f in get_installed_distributions()]): import cupy as np else: import numpy as np #import numpy as np from packaging import version from aosat import aosat_cfg avl_pkgs = [f.project_name for f in get_installed_distributions()] avl_vrss = [f.version for f in get_installed_distributions()] cuda_vrs = avl_vrss[avl_pkgs.index('pycuda')] if 'pycuda' in avl_pkgs else "0.0" opcl_vrs = avl_vrss[avl_pkgs.index('pyopencl')] if 'pyopencl' in avl_pkgs else "0.0" FORCE_NUMPY = aosat_cfg.CFG_SETTINGS['aosat_fft_forcenumpy'] if (FORCE_NUMPY or (version.parse(opcl_vrs) < version.parse("2018.2.4") and version.parse(cuda_vrs) < version.parse("0.94"))): ## ## use numpy fftx ## log.debug("Neither CUDA nor OpenCL found or not desired!") log.info("Using numpy FFTs!") def FFTmakeplan(samplearr): """Make a plan for FFTs Parameters ---------- arrshape : numpy array the shape of the arrays to be transformed Returns ------- plan FFT plan to be executed upon calls. In the current case where numpy FFTs are used, plan is None! Examples ------- >>> plan = FFTmakeplan(np.zeros((1024,1024)).shape) >>> plan == None True """ return(None) def FFTmakeout(inarr): """Make an output for FFTs Parameters ---------- inarr : numpy array Then input array Returns ------- plan FFT plan to be executed upon calls. In the current case where numpy FFTs are used, plan is None! Examples ------- >>> out = FFTmakeout(np.zeros((1024,1024))) >>> out == None True """ return(None) def FFTprepare(inarr): """Prepare an array for input int FFTforward or FFTinverse Parameters ---------- inarr : numpy array The array to be transformed Returns ------- numpy array In the current case of numpy FFTs, the array itself Examples ------- >>> arr = np.zeros((1024,1024)) >>> iarr = FFTprepare(arr) >>> np.array_equal(arr,iarr) True """ return(inarr) def FFTforward(plan,outarr,inarr): """Perform forward FFT. Parameters ---------- plan : fft plan In this case of numpy FFTs, plan should be None. outarr : device-suitable output array The device-suitable output. Should be None. inarr : numpy array The array to be transformed. Should be square. Returns ------- numpy array The transformed array Examples ------- >>> arr = np.zeros((1024,1024)) >>> oarr = FFTforward(None,None,arr) >>> oarr.dtype dtype('complex128') >>> oarr.shape (1024, 1024) """ return(np.fft.fft2(inarr)) def FFTinverse(plan,outarr, inarr): """Perform inverse FFT. Parameters ---------- plan : fft plan In this case of numpy FFTs, plan should be None. outarr : device-suitable output array The device-suitable output. Should be None. inarr : numpy array The array to be transformed. Should be square. Returns ------- numpy array The transformed array Examples ------- >>> arr = np.random.rand(1024,1024) >>> farr = FFTforward(None,None,arr) >>> oarr = FFTinverse(None,None,farr) >>> np.abs((np.real(oarr)-arr)).sum() < 2e-10 True >>> oarr.dtype dtype('complex128') >>> oarr.shape (1024, 1024) """ return(np.fft.ifft2(inarr)) def FFTshift(inarr): """Shift array transformed by FFT such that the zero component is centered Parameters ---------- inarr : numpy array Output of an FFT transform Returns ------- numpy array Centered array. Examples ------- >>> arr = np.random.rand(1024,1024) >>> farr = np.abs(FFTshift(FFTforward(None,None,arr))) >>> np.unravel_index(np.argmax(farr, axis=None), farr.shape) (512, 512) """ return(np.fft.fftshift(inarr)) else: ## ## use one of the CLUDA FFTs ## if version.parse(cuda_vrs) >= version.parse("0.94"): log.debug("CUDA version %s found" % cuda_vrs) log.info("Using CUDA FFTs!") from reikna.cluda import dtypes, cuda_api FFTapi = cuda_api() else: log.debug("OpenCL version %s found" % opcl_vrs) log.info("Using OpenCL FFTs!") from reikna.cluda import dtypes, ocl_api FFTapi = ocl_api() import reikna.fft as cludaFFT FFTthr = FFTapi.Thread.create() def FFTmakeplan(samplearr): """Make a plan for FFTs Parameters ---------- samplearr : numpy array an array of the same type and size as the ones you're going to transform a lot later on Returns ------- plan FFT plan to be executed upon calls. Examples ------- >>> plan = FFTmakeplan(np.zeros((1024,1024),dtype=np.float64)) >>> plan <reikna.core.computation.ComputationCallable object at ... """ fft = cludaFFT.FFT(samplearr.astype(np.complex128)) return(fft.compile(FFTthr)) def FFTmakeout(inarr): """Make a suitable output object for FFTs Parameters ---------- inarr : numpy array, preferably np.complex64 Sample of input array, same size and type which you are going to transform a lot later on. Returns ------- FFTout object The output object which must be passed to FFTplan later on. Will not be used explicitly Examples ------- >>> inarr = np.zeros((1024,1024)) >>> outobj = FFTmakeout(inarr) >>> type(outobj) <class 'reikna.cluda.ocl.Array'> """ return(FFTthr.array(inarr.shape, dtype=np.complex128)) def FFTprepare(inarr): """Prepare an input array to suit machine/GPU architecture Parameters ---------- inarr : numpy array The input array Returns ------- inarr_dev device dependent input array representation Examples ------- >>> arr = np.random.rand(1024,1024) >>> arr_dev = FFTprepare(arr) >>> type(arr_dev) <class 'reikna.cluda.ocl.Array'> """ return(FFTthr.to_device(inarr.astype(np.complex128))) def FFTforward(plan,outarr,inarr_dev): """Perform forward FFT Parameters ---------- plan : fft plan The plan produced by FFTmakeplan. outarr : reikna.cluda.ocl.Array Output array, produced by FFTmakeout inarr_dev : reikna.cluda.ocl.Array Device-suitable input array representation, produced by FFTprepare Returns ------- numpy array FFT transform of input array Examples ------- >>> arr = np.random.rand(1024,1024) >>> plan = FFTmakeplan(arr) >>> arr_dev = FFTprepare(arr) >>> arr_out = FFTmakeout(arr) >>> arr_fft = FFTforward(plan,arr_out,arr_dev) >>> ref_fft = np.fft.fft2(arr) >>> print(np.testing.assert_almost_equal(arr_fft,ref_fft)) None You can also time the execution to see if it's really faster than the standard numpy FFT: >>> import time >>> start=time.time() >>> for i in range(100): ... arr_fft = FFTforward(plan,arr_out,arr_dev) ... >>> end=time.time() >>> print("100 CLUDA FFTs: ",end-start) 100 CLUDA FFTs: ... >>> start=time.time() >>> for i in range(100): ... ref_fft = np.fft.fft2(arr) ... >>> end=time.time() >>> print("100 numpy FFTs: ",end-start) 100 numpy FFTs: ... If that's not the case, you can force the use of numpy's FFTs by putting the line force_np_fft = True in any configuration or report file! """ plan(outarr, inarr_dev, inverse=0) return(outarr.get()) def FFTinverse(plan,outarr,inarr_dev): """Perform inverse FFT Parameters ---------- plan : fft plan The plan produced by FFTmakeplan. outarr : reikna.cluda.ocl.Array Output array, produced by FFTmakeout inarr_dev : reikna.cluda.ocl.Array Device-suitable input array representation, produced by FFTprepare Returns ------- numpy array FFT inverse transform of input array Examples ------- >>> arr = np.random.rand(1024,1024) >>> plan = FFTmakeplan(arr) >>> arr_dev = FFTprepare(arr) >>> arr_out = FFTmakeout(arr) >>> arr_fft = FFTinverse(plan,arr_out,arr_dev) >>> ref_fft = np.fft.ifft2(arr) >>> print(np.testing.assert_almost_equal(arr_fft,ref_fft)) None """ plan(outarr, inarr_dev, inverse=1) return(outarr.get()) def FFTshift(inarr): """Shift array transformed by FFT such that the zero component is centered Parameters ---------- inarr : numpy array Output of an FFT transform Returns ------- numpy array Centered array. Examples ------- >>> arr = np.random.rand(1024,1024) >>> plan = FFTmakeplan(arr) >>> arr_dev = FFTprepare(arr) >>> arr_out = FFTmakeout(arr) >>> farr = FFTshift(FFTforward(plan,arr_out,arr_dev)) >>> np.unravel_index(np.argmax(farr, axis=None), farr.shape) (512, 512) """ return(np.fft.fftshift(inarr)) def fftSpeedTest(max_res=13): """Test of speed of currently selected FFT vs. numpy. This is intended to verify that the selected OpenCL / CUDA FFTs are indeed faster than numpy. For older GPUs, that may not always be the case. When called, fftSpeedtest will test a series of array sizes and print the ratio of execution times against standardnumpy implementations. If you see a lot of number smaller than one, in particular in the line for the array size of interest, make sure that the golbal aosat_cfg.CFG_SETTINGS contains the entry CFG_SETTINGS['aosat_fft_forcenumpy'] = True . In aosat, this can be achieved by calling aosat.aosat_cfg.configure(setupfile) where the setupfile contains the line aosat_fft_forcenumpy = True The setup (or "report") fiel is also an argument of many helper and convenience functions. After an execution of configure, issue a reload(aosat.fftx) This will redefine the fftx.FFT* functions! Parameters ---------- Returns ------- nothing Examples ------- >>> fftSpeedTest(max_res=4) array size = 4 x 4 : gpu speedup = ... """ from time import time dtype = np.complex128 resolutions = range(2,max_res) Nloops = 20 rtol = 1e-7 atol = 0 for n in resolutions: shape, axes = (2**n,2**n), (0,1) data = np.random.rand(*shape).astype(dtype) plan = FFTmakeplan(data) rtime, ntime = 0., 0. for nloop in range(Nloops): data = np.random.rand(*shape).astype(dtype) # forward t0 = time() data_dev = FFTprepare(data) fwd = FFTforward(plan,data_dev,data_dev) rtime += time() - t0 t0 = time() fwd_ref = np.fft.fft2(data, axes=axes).astype(dtype) ntime += time() - t0 actualf = np.real(fwd * np.conj(fwd)) desiredf = np.real(fwd_ref * np.conj(fwd_ref)) # inverse t0 = time() data_dev = FFTprepare(data) inv = FFTinverse(plan,data_dev,data_dev) rtime += time() - t0 t0 = time() inv_ref = np.fft.ifft2(data, axes=axes).astype(dtype) ntime += time() - t0 actuali = np.real(inv * np.conj(inv)) desiredi = np.real(inv_ref * np.conj(inv_ref)) np.testing.assert_allclose(desiredf, actualf, rtol, atol) np.testing.assert_allclose(desiredi, actuali, rtol, atol) print ('array size = %5d x %5d : gpu speedup = %g' % (2**n, 2**n, ntime / rtime)) if __name__ == "__main__": import doctest doctest.testmod(verbose=True, optionflags=doctest.ELLIPSIS)
<filename>src/aosat/fftx.py # -*- coding: utf-8 -*- """ This selects the best (i.e. fastest) FFT routine to be used in AOSAT. The module will look first for CUDA, then for OpenCL, and fall back to numpy FFTs if neither is available. """ import logging log = logging.getLogger('aosat_logger') log.addHandler(logging.NullHandler()) ## ## ## Check for GPU support and select FFT function ## ## from pip._internal.utils.misc import get_installed_distributions if any(["cupy" in str(f) for f in get_installed_distributions()]): import cupy as np else: import numpy as np #import numpy as np from packaging import version from aosat import aosat_cfg avl_pkgs = [f.project_name for f in get_installed_distributions()] avl_vrss = [f.version for f in get_installed_distributions()] cuda_vrs = avl_vrss[avl_pkgs.index('pycuda')] if 'pycuda' in avl_pkgs else "0.0" opcl_vrs = avl_vrss[avl_pkgs.index('pyopencl')] if 'pyopencl' in avl_pkgs else "0.0" FORCE_NUMPY = aosat_cfg.CFG_SETTINGS['aosat_fft_forcenumpy'] if (FORCE_NUMPY or (version.parse(opcl_vrs) < version.parse("2018.2.4") and version.parse(cuda_vrs) < version.parse("0.94"))): ## ## use numpy fftx ## log.debug("Neither CUDA nor OpenCL found or not desired!") log.info("Using numpy FFTs!") def FFTmakeplan(samplearr): """Make a plan for FFTs Parameters ---------- arrshape : numpy array the shape of the arrays to be transformed Returns ------- plan FFT plan to be executed upon calls. In the current case where numpy FFTs are used, plan is None! Examples ------- >>> plan = FFTmakeplan(np.zeros((1024,1024)).shape) >>> plan == None True """ return(None) def FFTmakeout(inarr): """Make an output for FFTs Parameters ---------- inarr : numpy array Then input array Returns ------- plan FFT plan to be executed upon calls. In the current case where numpy FFTs are used, plan is None! Examples ------- >>> out = FFTmakeout(np.zeros((1024,1024))) >>> out == None True """ return(None) def FFTprepare(inarr): """Prepare an array for input int FFTforward or FFTinverse Parameters ---------- inarr : numpy array The array to be transformed Returns ------- numpy array In the current case of numpy FFTs, the array itself Examples ------- >>> arr = np.zeros((1024,1024)) >>> iarr = FFTprepare(arr) >>> np.array_equal(arr,iarr) True """ return(inarr) def FFTforward(plan,outarr,inarr): """Perform forward FFT. Parameters ---------- plan : fft plan In this case of numpy FFTs, plan should be None. outarr : device-suitable output array The device-suitable output. Should be None. inarr : numpy array The array to be transformed. Should be square. Returns ------- numpy array The transformed array Examples ------- >>> arr = np.zeros((1024,1024)) >>> oarr = FFTforward(None,None,arr) >>> oarr.dtype dtype('complex128') >>> oarr.shape (1024, 1024) """ return(np.fft.fft2(inarr)) def FFTinverse(plan,outarr, inarr): """Perform inverse FFT. Parameters ---------- plan : fft plan In this case of numpy FFTs, plan should be None. outarr : device-suitable output array The device-suitable output. Should be None. inarr : numpy array The array to be transformed. Should be square. Returns ------- numpy array The transformed array Examples ------- >>> arr = np.random.rand(1024,1024) >>> farr = FFTforward(None,None,arr) >>> oarr = FFTinverse(None,None,farr) >>> np.abs((np.real(oarr)-arr)).sum() < 2e-10 True >>> oarr.dtype dtype('complex128') >>> oarr.shape (1024, 1024) """ return(np.fft.ifft2(inarr)) def FFTshift(inarr): """Shift array transformed by FFT such that the zero component is centered Parameters ---------- inarr : numpy array Output of an FFT transform Returns ------- numpy array Centered array. Examples ------- >>> arr = np.random.rand(1024,1024) >>> farr = np.abs(FFTshift(FFTforward(None,None,arr))) >>> np.unravel_index(np.argmax(farr, axis=None), farr.shape) (512, 512) """ return(np.fft.fftshift(inarr)) else: ## ## use one of the CLUDA FFTs ## if version.parse(cuda_vrs) >= version.parse("0.94"): log.debug("CUDA version %s found" % cuda_vrs) log.info("Using CUDA FFTs!") from reikna.cluda import dtypes, cuda_api FFTapi = cuda_api() else: log.debug("OpenCL version %s found" % opcl_vrs) log.info("Using OpenCL FFTs!") from reikna.cluda import dtypes, ocl_api FFTapi = ocl_api() import reikna.fft as cludaFFT FFTthr = FFTapi.Thread.create() def FFTmakeplan(samplearr): """Make a plan for FFTs Parameters ---------- samplearr : numpy array an array of the same type and size as the ones you're going to transform a lot later on Returns ------- plan FFT plan to be executed upon calls. Examples ------- >>> plan = FFTmakeplan(np.zeros((1024,1024),dtype=np.float64)) >>> plan <reikna.core.computation.ComputationCallable object at ... """ fft = cludaFFT.FFT(samplearr.astype(np.complex128)) return(fft.compile(FFTthr)) def FFTmakeout(inarr): """Make a suitable output object for FFTs Parameters ---------- inarr : numpy array, preferably np.complex64 Sample of input array, same size and type which you are going to transform a lot later on. Returns ------- FFTout object The output object which must be passed to FFTplan later on. Will not be used explicitly Examples ------- >>> inarr = np.zeros((1024,1024)) >>> outobj = FFTmakeout(inarr) >>> type(outobj) <class 'reikna.cluda.ocl.Array'> """ return(FFTthr.array(inarr.shape, dtype=np.complex128)) def FFTprepare(inarr): """Prepare an input array to suit machine/GPU architecture Parameters ---------- inarr : numpy array The input array Returns ------- inarr_dev device dependent input array representation Examples ------- >>> arr = np.random.rand(1024,1024) >>> arr_dev = FFTprepare(arr) >>> type(arr_dev) <class 'reikna.cluda.ocl.Array'> """ return(FFTthr.to_device(inarr.astype(np.complex128))) def FFTforward(plan,outarr,inarr_dev): """Perform forward FFT Parameters ---------- plan : fft plan The plan produced by FFTmakeplan. outarr : reikna.cluda.ocl.Array Output array, produced by FFTmakeout inarr_dev : reikna.cluda.ocl.Array Device-suitable input array representation, produced by FFTprepare Returns ------- numpy array FFT transform of input array Examples ------- >>> arr = np.random.rand(1024,1024) >>> plan = FFTmakeplan(arr) >>> arr_dev = FFTprepare(arr) >>> arr_out = FFTmakeout(arr) >>> arr_fft = FFTforward(plan,arr_out,arr_dev) >>> ref_fft = np.fft.fft2(arr) >>> print(np.testing.assert_almost_equal(arr_fft,ref_fft)) None You can also time the execution to see if it's really faster than the standard numpy FFT: >>> import time >>> start=time.time() >>> for i in range(100): ... arr_fft = FFTforward(plan,arr_out,arr_dev) ... >>> end=time.time() >>> print("100 CLUDA FFTs: ",end-start) 100 CLUDA FFTs: ... >>> start=time.time() >>> for i in range(100): ... ref_fft = np.fft.fft2(arr) ... >>> end=time.time() >>> print("100 numpy FFTs: ",end-start) 100 numpy FFTs: ... If that's not the case, you can force the use of numpy's FFTs by putting the line force_np_fft = True in any configuration or report file! """ plan(outarr, inarr_dev, inverse=0) return(outarr.get()) def FFTinverse(plan,outarr,inarr_dev): """Perform inverse FFT Parameters ---------- plan : fft plan The plan produced by FFTmakeplan. outarr : reikna.cluda.ocl.Array Output array, produced by FFTmakeout inarr_dev : reikna.cluda.ocl.Array Device-suitable input array representation, produced by FFTprepare Returns ------- numpy array FFT inverse transform of input array Examples ------- >>> arr = np.random.rand(1024,1024) >>> plan = FFTmakeplan(arr) >>> arr_dev = FFTprepare(arr) >>> arr_out = FFTmakeout(arr) >>> arr_fft = FFTinverse(plan,arr_out,arr_dev) >>> ref_fft = np.fft.ifft2(arr) >>> print(np.testing.assert_almost_equal(arr_fft,ref_fft)) None """ plan(outarr, inarr_dev, inverse=1) return(outarr.get()) def FFTshift(inarr): """Shift array transformed by FFT such that the zero component is centered Parameters ---------- inarr : numpy array Output of an FFT transform Returns ------- numpy array Centered array. Examples ------- >>> arr = np.random.rand(1024,1024) >>> plan = FFTmakeplan(arr) >>> arr_dev = FFTprepare(arr) >>> arr_out = FFTmakeout(arr) >>> farr = FFTshift(FFTforward(plan,arr_out,arr_dev)) >>> np.unravel_index(np.argmax(farr, axis=None), farr.shape) (512, 512) """ return(np.fft.fftshift(inarr)) def fftSpeedTest(max_res=13): """Test of speed of currently selected FFT vs. numpy. This is intended to verify that the selected OpenCL / CUDA FFTs are indeed faster than numpy. For older GPUs, that may not always be the case. When called, fftSpeedtest will test a series of array sizes and print the ratio of execution times against standardnumpy implementations. If you see a lot of number smaller than one, in particular in the line for the array size of interest, make sure that the golbal aosat_cfg.CFG_SETTINGS contains the entry CFG_SETTINGS['aosat_fft_forcenumpy'] = True . In aosat, this can be achieved by calling aosat.aosat_cfg.configure(setupfile) where the setupfile contains the line aosat_fft_forcenumpy = True The setup (or "report") fiel is also an argument of many helper and convenience functions. After an execution of configure, issue a reload(aosat.fftx) This will redefine the fftx.FFT* functions! Parameters ---------- Returns ------- nothing Examples ------- >>> fftSpeedTest(max_res=4) array size = 4 x 4 : gpu speedup = ... """ from time import time dtype = np.complex128 resolutions = range(2,max_res) Nloops = 20 rtol = 1e-7 atol = 0 for n in resolutions: shape, axes = (2**n,2**n), (0,1) data = np.random.rand(*shape).astype(dtype) plan = FFTmakeplan(data) rtime, ntime = 0., 0. for nloop in range(Nloops): data = np.random.rand(*shape).astype(dtype) # forward t0 = time() data_dev = FFTprepare(data) fwd = FFTforward(plan,data_dev,data_dev) rtime += time() - t0 t0 = time() fwd_ref = np.fft.fft2(data, axes=axes).astype(dtype) ntime += time() - t0 actualf = np.real(fwd * np.conj(fwd)) desiredf = np.real(fwd_ref * np.conj(fwd_ref)) # inverse t0 = time() data_dev = FFTprepare(data) inv = FFTinverse(plan,data_dev,data_dev) rtime += time() - t0 t0 = time() inv_ref = np.fft.ifft2(data, axes=axes).astype(dtype) ntime += time() - t0 actuali = np.real(inv * np.conj(inv)) desiredi = np.real(inv_ref * np.conj(inv_ref)) np.testing.assert_allclose(desiredf, actualf, rtol, atol) np.testing.assert_allclose(desiredi, actuali, rtol, atol) print ('array size = %5d x %5d : gpu speedup = %g' % (2**n, 2**n, ntime / rtime)) if __name__ == "__main__": import doctest doctest.testmod(verbose=True, optionflags=doctest.ELLIPSIS)
en
0.586954
# -*- coding: utf-8 -*- This selects the best (i.e. fastest) FFT routine to be used in AOSAT. The module will look first for CUDA, then for OpenCL, and fall back to numpy FFTs if neither is available. ## ## ## Check for GPU support and select FFT function ## ## #import numpy as np ## ## use numpy fftx ## Make a plan for FFTs Parameters ---------- arrshape : numpy array the shape of the arrays to be transformed Returns ------- plan FFT plan to be executed upon calls. In the current case where numpy FFTs are used, plan is None! Examples ------- >>> plan = FFTmakeplan(np.zeros((1024,1024)).shape) >>> plan == None True Make an output for FFTs Parameters ---------- inarr : numpy array Then input array Returns ------- plan FFT plan to be executed upon calls. In the current case where numpy FFTs are used, plan is None! Examples ------- >>> out = FFTmakeout(np.zeros((1024,1024))) >>> out == None True Prepare an array for input int FFTforward or FFTinverse Parameters ---------- inarr : numpy array The array to be transformed Returns ------- numpy array In the current case of numpy FFTs, the array itself Examples ------- >>> arr = np.zeros((1024,1024)) >>> iarr = FFTprepare(arr) >>> np.array_equal(arr,iarr) True Perform forward FFT. Parameters ---------- plan : fft plan In this case of numpy FFTs, plan should be None. outarr : device-suitable output array The device-suitable output. Should be None. inarr : numpy array The array to be transformed. Should be square. Returns ------- numpy array The transformed array Examples ------- >>> arr = np.zeros((1024,1024)) >>> oarr = FFTforward(None,None,arr) >>> oarr.dtype dtype('complex128') >>> oarr.shape (1024, 1024) Perform inverse FFT. Parameters ---------- plan : fft plan In this case of numpy FFTs, plan should be None. outarr : device-suitable output array The device-suitable output. Should be None. inarr : numpy array The array to be transformed. Should be square. Returns ------- numpy array The transformed array Examples ------- >>> arr = np.random.rand(1024,1024) >>> farr = FFTforward(None,None,arr) >>> oarr = FFTinverse(None,None,farr) >>> np.abs((np.real(oarr)-arr)).sum() < 2e-10 True >>> oarr.dtype dtype('complex128') >>> oarr.shape (1024, 1024) Shift array transformed by FFT such that the zero component is centered Parameters ---------- inarr : numpy array Output of an FFT transform Returns ------- numpy array Centered array. Examples ------- >>> arr = np.random.rand(1024,1024) >>> farr = np.abs(FFTshift(FFTforward(None,None,arr))) >>> np.unravel_index(np.argmax(farr, axis=None), farr.shape) (512, 512) ## ## use one of the CLUDA FFTs ## Make a plan for FFTs Parameters ---------- samplearr : numpy array an array of the same type and size as the ones you're going to transform a lot later on Returns ------- plan FFT plan to be executed upon calls. Examples ------- >>> plan = FFTmakeplan(np.zeros((1024,1024),dtype=np.float64)) >>> plan <reikna.core.computation.ComputationCallable object at ... Make a suitable output object for FFTs Parameters ---------- inarr : numpy array, preferably np.complex64 Sample of input array, same size and type which you are going to transform a lot later on. Returns ------- FFTout object The output object which must be passed to FFTplan later on. Will not be used explicitly Examples ------- >>> inarr = np.zeros((1024,1024)) >>> outobj = FFTmakeout(inarr) >>> type(outobj) <class 'reikna.cluda.ocl.Array'> Prepare an input array to suit machine/GPU architecture Parameters ---------- inarr : numpy array The input array Returns ------- inarr_dev device dependent input array representation Examples ------- >>> arr = np.random.rand(1024,1024) >>> arr_dev = FFTprepare(arr) >>> type(arr_dev) <class 'reikna.cluda.ocl.Array'> Perform forward FFT Parameters ---------- plan : fft plan The plan produced by FFTmakeplan. outarr : reikna.cluda.ocl.Array Output array, produced by FFTmakeout inarr_dev : reikna.cluda.ocl.Array Device-suitable input array representation, produced by FFTprepare Returns ------- numpy array FFT transform of input array Examples ------- >>> arr = np.random.rand(1024,1024) >>> plan = FFTmakeplan(arr) >>> arr_dev = FFTprepare(arr) >>> arr_out = FFTmakeout(arr) >>> arr_fft = FFTforward(plan,arr_out,arr_dev) >>> ref_fft = np.fft.fft2(arr) >>> print(np.testing.assert_almost_equal(arr_fft,ref_fft)) None You can also time the execution to see if it's really faster than the standard numpy FFT: >>> import time >>> start=time.time() >>> for i in range(100): ... arr_fft = FFTforward(plan,arr_out,arr_dev) ... >>> end=time.time() >>> print("100 CLUDA FFTs: ",end-start) 100 CLUDA FFTs: ... >>> start=time.time() >>> for i in range(100): ... ref_fft = np.fft.fft2(arr) ... >>> end=time.time() >>> print("100 numpy FFTs: ",end-start) 100 numpy FFTs: ... If that's not the case, you can force the use of numpy's FFTs by putting the line force_np_fft = True in any configuration or report file! Perform inverse FFT Parameters ---------- plan : fft plan The plan produced by FFTmakeplan. outarr : reikna.cluda.ocl.Array Output array, produced by FFTmakeout inarr_dev : reikna.cluda.ocl.Array Device-suitable input array representation, produced by FFTprepare Returns ------- numpy array FFT inverse transform of input array Examples ------- >>> arr = np.random.rand(1024,1024) >>> plan = FFTmakeplan(arr) >>> arr_dev = FFTprepare(arr) >>> arr_out = FFTmakeout(arr) >>> arr_fft = FFTinverse(plan,arr_out,arr_dev) >>> ref_fft = np.fft.ifft2(arr) >>> print(np.testing.assert_almost_equal(arr_fft,ref_fft)) None Shift array transformed by FFT such that the zero component is centered Parameters ---------- inarr : numpy array Output of an FFT transform Returns ------- numpy array Centered array. Examples ------- >>> arr = np.random.rand(1024,1024) >>> plan = FFTmakeplan(arr) >>> arr_dev = FFTprepare(arr) >>> arr_out = FFTmakeout(arr) >>> farr = FFTshift(FFTforward(plan,arr_out,arr_dev)) >>> np.unravel_index(np.argmax(farr, axis=None), farr.shape) (512, 512) Test of speed of currently selected FFT vs. numpy. This is intended to verify that the selected OpenCL / CUDA FFTs are indeed faster than numpy. For older GPUs, that may not always be the case. When called, fftSpeedtest will test a series of array sizes and print the ratio of execution times against standardnumpy implementations. If you see a lot of number smaller than one, in particular in the line for the array size of interest, make sure that the golbal aosat_cfg.CFG_SETTINGS contains the entry CFG_SETTINGS['aosat_fft_forcenumpy'] = True . In aosat, this can be achieved by calling aosat.aosat_cfg.configure(setupfile) where the setupfile contains the line aosat_fft_forcenumpy = True The setup (or "report") fiel is also an argument of many helper and convenience functions. After an execution of configure, issue a reload(aosat.fftx) This will redefine the fftx.FFT* functions! Parameters ---------- Returns ------- nothing Examples ------- >>> fftSpeedTest(max_res=4) array size = 4 x 4 : gpu speedup = ... # forward # inverse
2.235471
2
src/data.py
nikikilbertus/general-iv-models
9
6623152
<filename>src/data.py """Data loading and pre-processing utilities.""" from typing import Tuple, Callable, Sequence, Text, Dict, Union import os from absl import logging import jax.numpy as np from jax import random import numpy as onp import pandas as pd from scipy.stats import norm import utils DataSynth = Tuple[Dict[Text, Union[np.ndarray, float, None]], np.ndarray, np.ndarray] DataReal = Dict[Text, Union[np.ndarray, float, None]] ArrayTup = Tuple[np.ndarray, np.ndarray] Equations = Dict[Text, Callable[..., np.ndarray]] # ============================================================================= # NOISE SOURCES # ============================================================================= def std_normal_1d(key: np.ndarray, num: int) -> np.ndarray: """Generate a Gaussian for the confounder.""" return random.normal(key, (num,)) def std_normal_2d(key: np.ndarray, num: int) -> ArrayTup: """Generate a multivariate Gaussian for the noises e_X, e_Y.""" key1, key2 = random.split(key) return random.normal(key1, (num,)), random.normal(key2, (num,)) # ============================================================================= # SYNTHETIC STRUCTURAL EQUATIONS # ============================================================================= structural_equations = { "lin1": { "noise": std_normal_2d, "confounder": std_normal_1d, "f_z": std_normal_1d, "f_x": lambda z, c, ex: 0.5 * z + 3 * c + ex, "f_y": lambda x, c, ey: x - 6 * c + ey, }, "lin2": { "noise": std_normal_2d, "confounder": std_normal_1d, "f_z": std_normal_1d, "f_x": lambda z, c, ex: 3.0 * z + 0.5 * c + ex, "f_y": lambda x, c, ey: x - 6 * c + ey, }, "quad1": { "noise": std_normal_2d, "confounder": std_normal_1d, "f_z": std_normal_1d, "f_x": lambda z, c, ex: 0.5 * z + 3 * c + ex, "f_y": lambda x, c, ey: 0.3 * x ** 2 - 1.5 * x * c + ey, }, "quad2": { "noise": std_normal_2d, "confounder": std_normal_1d, "f_z": std_normal_1d, "f_x": lambda z, c, ex: 3.0 * z + 0.5 * c + ex, "f_y": lambda x, c, ey: 0.3 * x ** 2 - 1.5 * x * c + ey, }, } # ============================================================================= # DATA GENERATORS # ============================================================================= def whiten( inputs: Dict[Text, np.ndarray] ) -> Dict[Text, Union[float, np.ndarray, None]]: """Whiten each input.""" res = {} for k, v in inputs.items(): if v is not None: mu = np.mean(v, 0) std = np.maximum(np.std(v, 0), 1e-7) res[k + "_mu"] = mu res[k + "_std"] = std res[k] = (v - mu) / std else: res[k] = v return res def whiten_with_mu_std(val: np.ndarray, mu: float, std: float) -> np.ndarray: return (val - mu) / std def get_synth_data( key: np.ndarray, num: int, equations: Text, num_xstar: int = 100, external_equations: Equations = None, disconnect_instrument: bool = False ) -> DataSynth: """Generate some synthetic data. Args: key: A JAX random key. num: The number of examples to generate. equations: Which structural equations to choose for x and y. Default: 1 num_xstar: Size of grid for interventions on x. external_equations: A dictionary that must contain the keys 'f_x' and 'f_y' mapping to callables as values that take two np.ndarrays as arguments and produce another np.ndarray. These are the structural equations for X and Y in the graph Z -> X -> Y. If this argument is not provided, the `equation` argument selects structural equations from the pre-defined dict `structural_equations`. disconnect_instrument: Whether to regenerate random (standard Gaussian) values for the instrument after the data has been generated. This serves for diagnostic purposes, i.e., looking at the same x, y data, Returns: A 3-tuple (values, xstar, ystar) consisting a dictionary `values` containing values for x, y, z, confounder, ex, ey as well as two array xstar, ystar containing values for the true cause-effect. """ if external_equations is not None: eqs = external_equations elif equations == "np": return get_newey_powell(key, num, num_xstar) else: eqs = structural_equations[equations] key, subkey = random.split(key) ex, ey = eqs["noise"](subkey, num) key, subkey = random.split(key) confounder = eqs["confounder"](subkey, num) key, subkey = random.split(key) z = eqs["f_z"](subkey, num) x = eqs["f_x"](z, confounder, ex) y = eqs["f_y"](x, confounder, ey) values = whiten({'x': x, 'y': y, 'z': z, 'confounder': confounder, 'ex': ex, 'ey': ey}) # Evaluate E[ Y | do(x^*)] empirically xmin, xmax = np.min(x), np.max(x) xstar = np.linspace(xmin, xmax, num_xstar) ystar = [] for _ in range(500): key, subkey = random.split(key) tmpey = eqs["noise"](subkey, num_xstar)[1] key, subkey = random.split(key) tmpconf = eqs["confounder"](subkey, num_xstar) tmp_ystar = whiten_with_mu_std( eqs["f_y"](xstar, tmpconf, tmpey), values["y_mu"], values["y_std"]) ystar.append(tmp_ystar) ystar = np.array(ystar) xstar = whiten_with_mu_std(xstar, values["x_mu"], values["x_std"]) if disconnect_instrument: key, subkey = random.split(key) values['z'] = random.normal(subkey, shape=z.shape) return values, xstar, ystar def get_colonial_origins(data_dir: Text = "../data") -> DataReal: """Load data from colonial origins paper of Acemoglu.""" stata_path = os.path.join(data_dir, "colonial_origins", "data.dta") df = pd.read_stata(stata_path) ycol = 'logpgp95' zcol = 'logem4' xcol = 'avexpr' df = df[[zcol, xcol, ycol]].dropna() z, x, y = df[zcol].values, df[xcol].values, df[ycol].values data = {'x': x, 'y': y, 'z': z, 'confounder': None, 'ex': None, 'ey': None} return whiten(data) def get_newey_powell(key: np.ndarray, num: int, num_xstar: int = 100) -> DataSynth: """Get simulated Newey Powell (sigmoid design) data from KIV paper.""" def np_true(vals: np.ndarray): return np.log(np.abs(16. * vals - 8) + 1) * np.sign(vals - 0.5) xstar = np.linspace(0, 1, num_xstar) ystar = np_true(xstar) mu = np.zeros(3) sigma = np.array([[1., 0.5, 0.], [0.5, 1., 0.], [0., 0., 1.]]) r = random.multivariate_normal(key, mu, sigma, shape=(num,)) u, t, w = r[:, 0], r[:, 1], r[:, 2] x = w + t x = norm.cdf(x / np.sqrt(2.)) z = norm.cdf(w) e = u y = np_true(x) + e values = whiten({'x': x, 'y': y, 'z': z, 'ex': e, 'ey': e}) xstar = whiten_with_mu_std(xstar, values['x_mu'], values['x_std']) ystar = whiten_with_mu_std(ystar, values['y_mu'], values['y_std']) values['confounder'] = None return values, xstar, ystar # ============================================================================= # DISCRETIZATION AND CDF HANDLING # ============================================================================= def ecdf(vals: np.ndarray, num_points: int = None) -> ArrayTup: """Evaluate the empirical distribution function on fixed number of points.""" if num_points is None: num_points = len(vals) cdf = np.linspace(0, 1, num_points) t = np.quantile(vals, cdf) return t, cdf def cdf_inv(vals: np.ndarray, num_points: int = None) -> Callable[..., np.ndarray]: """Compute an interpolation function of the (empirical) inverse cdf.""" t, cdf = ecdf(vals, num_points) return lambda x: onp.interp(x, cdf, t) def get_cdf_invs(val: np.ndarray, bin_ids: np.ndarray, num_z: int) -> Sequence[Callable[..., np.ndarray]]: """Compute a list of interpolated inverse CDFs of val at each z in Z grid.""" cdf_invs = [] for i in range(num_z): cdf_invs.append(cdf_inv(val[bin_ids == i])) return cdf_invs def get_z_bin_assigment(z: np.ndarray, z_grid: np.ndarray) -> np.ndarray: """Assignment of values in z to the respective bin in z_grid.""" bins = np.concatenate((np.array([-np.inf]), z_grid[1:-1], np.array([np.inf]))) hist = onp.digitize(z, bins=bins, right=True) - 1 return hist def get_x_samples(x: np.ndarray, bin_ids: np.ndarray, num_z: int, num_sample: int) -> ArrayTup: """Pre-compute samples from p(x | z^{(i)}) for each gridpoint zi.""" x_cdf_invs = get_cdf_invs(x, bin_ids, num_z) tmp = np.linspace(0, 1, num_sample + 2)[1:-1] tmp0 = utils.normal_cdf_inv(tmp, np.array([0]), np.array([0])) return tmp0, np.array([x_cdf_inv(tmp) for x_cdf_inv in x_cdf_invs]) def get_y_pre(y: np.ndarray, bin_ids: np.ndarray, num_z: int, num_points: int) -> np.ndarray: """Compute the grid of y points for constraint approach y.""" y_cdf_invs = get_cdf_invs(y, bin_ids, num_z) grid = np.linspace(0, 1, num_points + 2)[1:-1] return np.array([y_cdf_inv(grid) for y_cdf_inv in y_cdf_invs]) def make_zgrid_and_binids(z: np.ndarray, num_z: int) -> ArrayTup: """Discretize instrument Z and assign all z points to corresponding bins.""" if num_z <= 0: logging.info("Discrete instrument specified, checking for values.") z_grid = np.sort(onp.unique(z)) if len(z_grid) > 50: logging.info("Found more than 50 unique values for z. This is not a " "discrete instrument. Aborting!") raise RuntimeError("Discrete instrument specified, but not found.") logging.info(f"Found {len(z_grid)} unique values for discrete instrument.") bin_ids = - onp.ones_like(z) for i, zpoint in enumerate(z_grid): bin_ids[z == zpoint] = i if onp.any(bin_ids < 0): raise ValueError(f"Found negative value in bin_ids. " "Couldn't discretize instrument.") bin_ids = np.array(bin_ids).astype(int) else: z_grid = ecdf(z, num_z + 1)[0] bin_ids = get_z_bin_assigment(z, z_grid) z_grid = (z_grid[:-1] + z_grid[1:]) / 2 return z_grid, bin_ids
<filename>src/data.py """Data loading and pre-processing utilities.""" from typing import Tuple, Callable, Sequence, Text, Dict, Union import os from absl import logging import jax.numpy as np from jax import random import numpy as onp import pandas as pd from scipy.stats import norm import utils DataSynth = Tuple[Dict[Text, Union[np.ndarray, float, None]], np.ndarray, np.ndarray] DataReal = Dict[Text, Union[np.ndarray, float, None]] ArrayTup = Tuple[np.ndarray, np.ndarray] Equations = Dict[Text, Callable[..., np.ndarray]] # ============================================================================= # NOISE SOURCES # ============================================================================= def std_normal_1d(key: np.ndarray, num: int) -> np.ndarray: """Generate a Gaussian for the confounder.""" return random.normal(key, (num,)) def std_normal_2d(key: np.ndarray, num: int) -> ArrayTup: """Generate a multivariate Gaussian for the noises e_X, e_Y.""" key1, key2 = random.split(key) return random.normal(key1, (num,)), random.normal(key2, (num,)) # ============================================================================= # SYNTHETIC STRUCTURAL EQUATIONS # ============================================================================= structural_equations = { "lin1": { "noise": std_normal_2d, "confounder": std_normal_1d, "f_z": std_normal_1d, "f_x": lambda z, c, ex: 0.5 * z + 3 * c + ex, "f_y": lambda x, c, ey: x - 6 * c + ey, }, "lin2": { "noise": std_normal_2d, "confounder": std_normal_1d, "f_z": std_normal_1d, "f_x": lambda z, c, ex: 3.0 * z + 0.5 * c + ex, "f_y": lambda x, c, ey: x - 6 * c + ey, }, "quad1": { "noise": std_normal_2d, "confounder": std_normal_1d, "f_z": std_normal_1d, "f_x": lambda z, c, ex: 0.5 * z + 3 * c + ex, "f_y": lambda x, c, ey: 0.3 * x ** 2 - 1.5 * x * c + ey, }, "quad2": { "noise": std_normal_2d, "confounder": std_normal_1d, "f_z": std_normal_1d, "f_x": lambda z, c, ex: 3.0 * z + 0.5 * c + ex, "f_y": lambda x, c, ey: 0.3 * x ** 2 - 1.5 * x * c + ey, }, } # ============================================================================= # DATA GENERATORS # ============================================================================= def whiten( inputs: Dict[Text, np.ndarray] ) -> Dict[Text, Union[float, np.ndarray, None]]: """Whiten each input.""" res = {} for k, v in inputs.items(): if v is not None: mu = np.mean(v, 0) std = np.maximum(np.std(v, 0), 1e-7) res[k + "_mu"] = mu res[k + "_std"] = std res[k] = (v - mu) / std else: res[k] = v return res def whiten_with_mu_std(val: np.ndarray, mu: float, std: float) -> np.ndarray: return (val - mu) / std def get_synth_data( key: np.ndarray, num: int, equations: Text, num_xstar: int = 100, external_equations: Equations = None, disconnect_instrument: bool = False ) -> DataSynth: """Generate some synthetic data. Args: key: A JAX random key. num: The number of examples to generate. equations: Which structural equations to choose for x and y. Default: 1 num_xstar: Size of grid for interventions on x. external_equations: A dictionary that must contain the keys 'f_x' and 'f_y' mapping to callables as values that take two np.ndarrays as arguments and produce another np.ndarray. These are the structural equations for X and Y in the graph Z -> X -> Y. If this argument is not provided, the `equation` argument selects structural equations from the pre-defined dict `structural_equations`. disconnect_instrument: Whether to regenerate random (standard Gaussian) values for the instrument after the data has been generated. This serves for diagnostic purposes, i.e., looking at the same x, y data, Returns: A 3-tuple (values, xstar, ystar) consisting a dictionary `values` containing values for x, y, z, confounder, ex, ey as well as two array xstar, ystar containing values for the true cause-effect. """ if external_equations is not None: eqs = external_equations elif equations == "np": return get_newey_powell(key, num, num_xstar) else: eqs = structural_equations[equations] key, subkey = random.split(key) ex, ey = eqs["noise"](subkey, num) key, subkey = random.split(key) confounder = eqs["confounder"](subkey, num) key, subkey = random.split(key) z = eqs["f_z"](subkey, num) x = eqs["f_x"](z, confounder, ex) y = eqs["f_y"](x, confounder, ey) values = whiten({'x': x, 'y': y, 'z': z, 'confounder': confounder, 'ex': ex, 'ey': ey}) # Evaluate E[ Y | do(x^*)] empirically xmin, xmax = np.min(x), np.max(x) xstar = np.linspace(xmin, xmax, num_xstar) ystar = [] for _ in range(500): key, subkey = random.split(key) tmpey = eqs["noise"](subkey, num_xstar)[1] key, subkey = random.split(key) tmpconf = eqs["confounder"](subkey, num_xstar) tmp_ystar = whiten_with_mu_std( eqs["f_y"](xstar, tmpconf, tmpey), values["y_mu"], values["y_std"]) ystar.append(tmp_ystar) ystar = np.array(ystar) xstar = whiten_with_mu_std(xstar, values["x_mu"], values["x_std"]) if disconnect_instrument: key, subkey = random.split(key) values['z'] = random.normal(subkey, shape=z.shape) return values, xstar, ystar def get_colonial_origins(data_dir: Text = "../data") -> DataReal: """Load data from colonial origins paper of Acemoglu.""" stata_path = os.path.join(data_dir, "colonial_origins", "data.dta") df = pd.read_stata(stata_path) ycol = 'logpgp95' zcol = 'logem4' xcol = 'avexpr' df = df[[zcol, xcol, ycol]].dropna() z, x, y = df[zcol].values, df[xcol].values, df[ycol].values data = {'x': x, 'y': y, 'z': z, 'confounder': None, 'ex': None, 'ey': None} return whiten(data) def get_newey_powell(key: np.ndarray, num: int, num_xstar: int = 100) -> DataSynth: """Get simulated Newey Powell (sigmoid design) data from KIV paper.""" def np_true(vals: np.ndarray): return np.log(np.abs(16. * vals - 8) + 1) * np.sign(vals - 0.5) xstar = np.linspace(0, 1, num_xstar) ystar = np_true(xstar) mu = np.zeros(3) sigma = np.array([[1., 0.5, 0.], [0.5, 1., 0.], [0., 0., 1.]]) r = random.multivariate_normal(key, mu, sigma, shape=(num,)) u, t, w = r[:, 0], r[:, 1], r[:, 2] x = w + t x = norm.cdf(x / np.sqrt(2.)) z = norm.cdf(w) e = u y = np_true(x) + e values = whiten({'x': x, 'y': y, 'z': z, 'ex': e, 'ey': e}) xstar = whiten_with_mu_std(xstar, values['x_mu'], values['x_std']) ystar = whiten_with_mu_std(ystar, values['y_mu'], values['y_std']) values['confounder'] = None return values, xstar, ystar # ============================================================================= # DISCRETIZATION AND CDF HANDLING # ============================================================================= def ecdf(vals: np.ndarray, num_points: int = None) -> ArrayTup: """Evaluate the empirical distribution function on fixed number of points.""" if num_points is None: num_points = len(vals) cdf = np.linspace(0, 1, num_points) t = np.quantile(vals, cdf) return t, cdf def cdf_inv(vals: np.ndarray, num_points: int = None) -> Callable[..., np.ndarray]: """Compute an interpolation function of the (empirical) inverse cdf.""" t, cdf = ecdf(vals, num_points) return lambda x: onp.interp(x, cdf, t) def get_cdf_invs(val: np.ndarray, bin_ids: np.ndarray, num_z: int) -> Sequence[Callable[..., np.ndarray]]: """Compute a list of interpolated inverse CDFs of val at each z in Z grid.""" cdf_invs = [] for i in range(num_z): cdf_invs.append(cdf_inv(val[bin_ids == i])) return cdf_invs def get_z_bin_assigment(z: np.ndarray, z_grid: np.ndarray) -> np.ndarray: """Assignment of values in z to the respective bin in z_grid.""" bins = np.concatenate((np.array([-np.inf]), z_grid[1:-1], np.array([np.inf]))) hist = onp.digitize(z, bins=bins, right=True) - 1 return hist def get_x_samples(x: np.ndarray, bin_ids: np.ndarray, num_z: int, num_sample: int) -> ArrayTup: """Pre-compute samples from p(x | z^{(i)}) for each gridpoint zi.""" x_cdf_invs = get_cdf_invs(x, bin_ids, num_z) tmp = np.linspace(0, 1, num_sample + 2)[1:-1] tmp0 = utils.normal_cdf_inv(tmp, np.array([0]), np.array([0])) return tmp0, np.array([x_cdf_inv(tmp) for x_cdf_inv in x_cdf_invs]) def get_y_pre(y: np.ndarray, bin_ids: np.ndarray, num_z: int, num_points: int) -> np.ndarray: """Compute the grid of y points for constraint approach y.""" y_cdf_invs = get_cdf_invs(y, bin_ids, num_z) grid = np.linspace(0, 1, num_points + 2)[1:-1] return np.array([y_cdf_inv(grid) for y_cdf_inv in y_cdf_invs]) def make_zgrid_and_binids(z: np.ndarray, num_z: int) -> ArrayTup: """Discretize instrument Z and assign all z points to corresponding bins.""" if num_z <= 0: logging.info("Discrete instrument specified, checking for values.") z_grid = np.sort(onp.unique(z)) if len(z_grid) > 50: logging.info("Found more than 50 unique values for z. This is not a " "discrete instrument. Aborting!") raise RuntimeError("Discrete instrument specified, but not found.") logging.info(f"Found {len(z_grid)} unique values for discrete instrument.") bin_ids = - onp.ones_like(z) for i, zpoint in enumerate(z_grid): bin_ids[z == zpoint] = i if onp.any(bin_ids < 0): raise ValueError(f"Found negative value in bin_ids. " "Couldn't discretize instrument.") bin_ids = np.array(bin_ids).astype(int) else: z_grid = ecdf(z, num_z + 1)[0] bin_ids = get_z_bin_assigment(z, z_grid) z_grid = (z_grid[:-1] + z_grid[1:]) / 2 return z_grid, bin_ids
en
0.696818
Data loading and pre-processing utilities. # ============================================================================= # NOISE SOURCES # ============================================================================= Generate a Gaussian for the confounder. Generate a multivariate Gaussian for the noises e_X, e_Y. # ============================================================================= # SYNTHETIC STRUCTURAL EQUATIONS # ============================================================================= # ============================================================================= # DATA GENERATORS # ============================================================================= Whiten each input. Generate some synthetic data. Args: key: A JAX random key. num: The number of examples to generate. equations: Which structural equations to choose for x and y. Default: 1 num_xstar: Size of grid for interventions on x. external_equations: A dictionary that must contain the keys 'f_x' and 'f_y' mapping to callables as values that take two np.ndarrays as arguments and produce another np.ndarray. These are the structural equations for X and Y in the graph Z -> X -> Y. If this argument is not provided, the `equation` argument selects structural equations from the pre-defined dict `structural_equations`. disconnect_instrument: Whether to regenerate random (standard Gaussian) values for the instrument after the data has been generated. This serves for diagnostic purposes, i.e., looking at the same x, y data, Returns: A 3-tuple (values, xstar, ystar) consisting a dictionary `values` containing values for x, y, z, confounder, ex, ey as well as two array xstar, ystar containing values for the true cause-effect. # Evaluate E[ Y | do(x^*)] empirically Load data from colonial origins paper of Acemoglu. Get simulated Newey Powell (sigmoid design) data from KIV paper. # ============================================================================= # DISCRETIZATION AND CDF HANDLING # ============================================================================= Evaluate the empirical distribution function on fixed number of points. Compute an interpolation function of the (empirical) inverse cdf. Compute a list of interpolated inverse CDFs of val at each z in Z grid. Assignment of values in z to the respective bin in z_grid. Pre-compute samples from p(x | z^{(i)}) for each gridpoint zi. Compute the grid of y points for constraint approach y. Discretize instrument Z and assign all z points to corresponding bins.
2.752634
3
Interact with the API/get-blobs.py
KevoLoyal/youngrockets
0
6623153
########### Blob Interaction ########### import http.client, urllib.request, urllib.parse, urllib.error, base64, requests, json # Get all modules for the Blob Storage from azure.storage.blob import BlockBlobService from azure.storage.blob import PublicAccess from azure.storage.blob import ContentSettings from os import path # Import OS Path Function # Python Classes Involved # BlobServiceClient: The BlobServiceClient class allows you to manipulate Azure Storage resources and blob containers. # ContainerClient: The ContainerClient class allows you to manipulate Azure Storage containers and their blobs. # BlobClient: The BlobClient class allows you to manipulate Azure Storage blobs. # Info to Blob blob_storage_key = 'Key' connect_str = 'String' storage_account = 'account name' container_name = input("To what container you want to list? ") print("***********************************************") # local_file_name = input("What is the name of the file to upload? ") try: block_blob_service = BlockBlobService(account_name=storage_account, account_key=blob_storage_key) generator = block_blob_service.list_blobs(container_name) except Exception as ex: print('Exception:') print(ex) for blob in generator: print(blob.name)
########### Blob Interaction ########### import http.client, urllib.request, urllib.parse, urllib.error, base64, requests, json # Get all modules for the Blob Storage from azure.storage.blob import BlockBlobService from azure.storage.blob import PublicAccess from azure.storage.blob import ContentSettings from os import path # Import OS Path Function # Python Classes Involved # BlobServiceClient: The BlobServiceClient class allows you to manipulate Azure Storage resources and blob containers. # ContainerClient: The ContainerClient class allows you to manipulate Azure Storage containers and their blobs. # BlobClient: The BlobClient class allows you to manipulate Azure Storage blobs. # Info to Blob blob_storage_key = 'Key' connect_str = 'String' storage_account = 'account name' container_name = input("To what container you want to list? ") print("***********************************************") # local_file_name = input("What is the name of the file to upload? ") try: block_blob_service = BlockBlobService(account_name=storage_account, account_key=blob_storage_key) generator = block_blob_service.list_blobs(container_name) except Exception as ex: print('Exception:') print(ex) for blob in generator: print(blob.name)
en
0.674102
########### Blob Interaction ########### # Get all modules for the Blob Storage # Import OS Path Function # Python Classes Involved # BlobServiceClient: The BlobServiceClient class allows you to manipulate Azure Storage resources and blob containers. # ContainerClient: The ContainerClient class allows you to manipulate Azure Storage containers and their blobs. # BlobClient: The BlobClient class allows you to manipulate Azure Storage blobs. # Info to Blob # local_file_name = input("What is the name of the file to upload? ")
3.033523
3
by-session/ta-921/j3/number2.py
amiraliakbari/sharif-mabani-python
2
6623154
print 'A' x = 3 y = 2 print 'B' if x > 10: print "1" else: print x / y print 'C' print x * 1.0 / y print 2 / (y - 2) print 'D' x = 3.0 y = 2.0 print x / y
print 'A' x = 3 y = 2 print 'B' if x > 10: print "1" else: print x / y print 'C' print x * 1.0 / y print 2 / (y - 2) print 'D' x = 3.0 y = 2.0 print x / y
none
1
3.838209
4
solution/11655(ROT13).py
OMEGA-Y/CodingTest-sol
0
6623155
import sys data = sys.stdin.readline().rstrip() output = "" for i in data: if i.islower(): output += chr(97+int((ord(i)-ord('a')+13)%26)) elif i.isupper(): output += chr(65+int((ord(i)-ord('A')+13)%26)) else: output += i print(output)
import sys data = sys.stdin.readline().rstrip() output = "" for i in data: if i.islower(): output += chr(97+int((ord(i)-ord('a')+13)%26)) elif i.isupper(): output += chr(65+int((ord(i)-ord('A')+13)%26)) else: output += i print(output)
none
1
3.363043
3
problems/OF/auto/problem62_OF.py
sunandita/ICAPS_Summer_School_RAE_2020
5
6623156
<reponame>sunandita/ICAPS_Summer_School_RAE_2020 __author__ = 'mason' from domain_orderFulfillment import * from timer import DURATION from state import state import numpy as np ''' This is a randomly generated problem ''' def GetCostOfMove(id, r, loc1, loc2, dist): return 1 + dist def GetCostOfLookup(id, item): return max(1, np.random.beta(2, 2)) def GetCostOfWrap(id, orderName, m, item): return max(1, np.random.normal(5, .5)) def GetCostOfPickup(id, r, item): return max(1, np.random.normal(4, 1)) def GetCostOfPutdown(id, r, item): return max(1, np.random.normal(4, 1)) def GetCostOfLoad(id, orderName, r, m, item): return max(1, np.random.normal(3, .5)) DURATION.TIME = { 'lookupDB': GetCostOfLookup, 'wrap': GetCostOfWrap, 'pickup': GetCostOfPickup, 'putdown': GetCostOfPutdown, 'loadMachine': GetCostOfLoad, 'moveRobot': GetCostOfMove, 'acquireRobot': 1, 'freeRobot': 1, 'wait': 5 } DURATION.COUNTER = { 'lookupDB': GetCostOfLookup, 'wrap': GetCostOfWrap, 'pickup': GetCostOfPickup, 'putdown': GetCostOfPutdown, 'loadMachine': GetCostOfLoad, 'moveRobot': GetCostOfMove, 'acquireRobot': 1, 'freeRobot': 1, 'wait': 5 } rv.LOCATIONS = [0, 1, 2, 3, 4, 200] rv.FACTORY1 = frozenset({0, 1, 2, 3, 4, 200}) rv.FACTORY_UNION = rv.FACTORY1 rv.SHIPPING_DOC = {rv.FACTORY1: 0} rv.GROUND_EDGES = {0: [1, 2, 4, 200, 3], 1: [2, 4, 0, 3, 200], 2: [4, 0, 1], 3: [0, 1, 4], 4: [3, 0, 1, 2], 200: [1, 0]} rv.GROUND_WEIGHTS = {(0, 1): 8.339734977426263, (0, 2): 12.782471204845653, (0, 4): 1.4573925753056773, (0, 200): 1.9054250683218728, (0, 3): 4.193557905999012, (1, 2): 15.777006308874313, (1, 4): 10.742111749991842, (1, 3): 7.534473584229431, (1, 200): 6.632985362706415, (2, 4): 5.1167109230895, (3, 4): 1.2180650914526048} rv.ROBOTS = { 'r0': rv.FACTORY1, } rv.ROBOT_CAPACITY = {'r0': 4.642981441266107} rv.MACHINES = { 'm0': rv.FACTORY1, 'm1': rv.FACTORY1, 'm2': rv.FACTORY1, } rv.PALLETS = { 'p0', } def ResetState(): state.OBJECTS = { 'o0': True, 'o1': True, 'o2': True, 'o3': True, 'o4': True, 'o5': True, 'o6': True, 'o7': True, 'o8': True, } state.OBJ_WEIGHT = {'o0': 4.642981441266107, 'o1': 4.642981441266107, 'o2': 4.642981441266107, 'o3': 3.978811029733769, 'o4': 4.642981441266107, 'o5': 4.642981441266107, 'o6': 4.642981441266107, 'o7': 3.9377798836061166, 'o8': 4.642981441266107} state.OBJ_CLASS = {'type0': ['o0', 'o1'], 'type1': ['o2', 'o3', 'o4'], 'type2': ['o5'], 'type3': ['o6', 'o7', 'o8']} state.loc = { 'r0': 0, 'm0': 4, 'm1': 1, 'm2': 200, 'p0': 2, 'o0': 4, 'o1': 3, 'o2': 1, 'o3': 200, 'o4': 3, 'o5': 0, 'o6': 2, 'o7': 2, 'o8': 3,} state.load = { 'r0': NIL,} state.busy = {'r0': False, 'm0': False, 'm1': False, 'm2': False} state.numUses = {'m0': 4, 'm1': 9, 'm2': 13} state.var1 = {'temp': 'r0', 'temp1': 'r0', 'temp2': 1, 'redoId': 0} state.shouldRedo = {} tasks = { 15: [['orderStart', ['type0']]], 12: [['orderStart', ['type0']]], } eventsEnv = { }
__author__ = 'mason' from domain_orderFulfillment import * from timer import DURATION from state import state import numpy as np ''' This is a randomly generated problem ''' def GetCostOfMove(id, r, loc1, loc2, dist): return 1 + dist def GetCostOfLookup(id, item): return max(1, np.random.beta(2, 2)) def GetCostOfWrap(id, orderName, m, item): return max(1, np.random.normal(5, .5)) def GetCostOfPickup(id, r, item): return max(1, np.random.normal(4, 1)) def GetCostOfPutdown(id, r, item): return max(1, np.random.normal(4, 1)) def GetCostOfLoad(id, orderName, r, m, item): return max(1, np.random.normal(3, .5)) DURATION.TIME = { 'lookupDB': GetCostOfLookup, 'wrap': GetCostOfWrap, 'pickup': GetCostOfPickup, 'putdown': GetCostOfPutdown, 'loadMachine': GetCostOfLoad, 'moveRobot': GetCostOfMove, 'acquireRobot': 1, 'freeRobot': 1, 'wait': 5 } DURATION.COUNTER = { 'lookupDB': GetCostOfLookup, 'wrap': GetCostOfWrap, 'pickup': GetCostOfPickup, 'putdown': GetCostOfPutdown, 'loadMachine': GetCostOfLoad, 'moveRobot': GetCostOfMove, 'acquireRobot': 1, 'freeRobot': 1, 'wait': 5 } rv.LOCATIONS = [0, 1, 2, 3, 4, 200] rv.FACTORY1 = frozenset({0, 1, 2, 3, 4, 200}) rv.FACTORY_UNION = rv.FACTORY1 rv.SHIPPING_DOC = {rv.FACTORY1: 0} rv.GROUND_EDGES = {0: [1, 2, 4, 200, 3], 1: [2, 4, 0, 3, 200], 2: [4, 0, 1], 3: [0, 1, 4], 4: [3, 0, 1, 2], 200: [1, 0]} rv.GROUND_WEIGHTS = {(0, 1): 8.339734977426263, (0, 2): 12.782471204845653, (0, 4): 1.4573925753056773, (0, 200): 1.9054250683218728, (0, 3): 4.193557905999012, (1, 2): 15.777006308874313, (1, 4): 10.742111749991842, (1, 3): 7.534473584229431, (1, 200): 6.632985362706415, (2, 4): 5.1167109230895, (3, 4): 1.2180650914526048} rv.ROBOTS = { 'r0': rv.FACTORY1, } rv.ROBOT_CAPACITY = {'r0': 4.642981441266107} rv.MACHINES = { 'm0': rv.FACTORY1, 'm1': rv.FACTORY1, 'm2': rv.FACTORY1, } rv.PALLETS = { 'p0', } def ResetState(): state.OBJECTS = { 'o0': True, 'o1': True, 'o2': True, 'o3': True, 'o4': True, 'o5': True, 'o6': True, 'o7': True, 'o8': True, } state.OBJ_WEIGHT = {'o0': 4.642981441266107, 'o1': 4.642981441266107, 'o2': 4.642981441266107, 'o3': 3.978811029733769, 'o4': 4.642981441266107, 'o5': 4.642981441266107, 'o6': 4.642981441266107, 'o7': 3.9377798836061166, 'o8': 4.642981441266107} state.OBJ_CLASS = {'type0': ['o0', 'o1'], 'type1': ['o2', 'o3', 'o4'], 'type2': ['o5'], 'type3': ['o6', 'o7', 'o8']} state.loc = { 'r0': 0, 'm0': 4, 'm1': 1, 'm2': 200, 'p0': 2, 'o0': 4, 'o1': 3, 'o2': 1, 'o3': 200, 'o4': 3, 'o5': 0, 'o6': 2, 'o7': 2, 'o8': 3,} state.load = { 'r0': NIL,} state.busy = {'r0': False, 'm0': False, 'm1': False, 'm2': False} state.numUses = {'m0': 4, 'm1': 9, 'm2': 13} state.var1 = {'temp': 'r0', 'temp1': 'r0', 'temp2': 1, 'redoId': 0} state.shouldRedo = {} tasks = { 15: [['orderStart', ['type0']]], 12: [['orderStart', ['type0']]], } eventsEnv = { }
en
0.887912
This is a randomly generated problem
2.265882
2
2_PG/2-2_A2C/model.py
stella-moon323/Reinforcement_Learning
1
6623157
import torch.nn as nn class Net(nn.Module): def __init__(self, input_nums, output_nums, hidden_nums): super(Net, self).__init__() self.layers = nn.Sequential( nn.Linear(input_nums, hidden_nums), nn.ReLU(inplace=True), nn.Linear(hidden_nums, hidden_nums), nn.ReLU(inplace=True), ) self.fc_actor = nn.Linear(hidden_nums, output_nums) self.fc_critic = nn.Linear(hidden_nums, 1) # 重みの初期化 for m in self.modules(): if isinstance(m, nn.Linear): nn.init.xavier_uniform_(m.weight) m.bias.data.zero_() def forward(self, x): hid = self.layers(x) actor = self.fc_actor(hid) critic = self.fc_critic(hid) return actor, critic
import torch.nn as nn class Net(nn.Module): def __init__(self, input_nums, output_nums, hidden_nums): super(Net, self).__init__() self.layers = nn.Sequential( nn.Linear(input_nums, hidden_nums), nn.ReLU(inplace=True), nn.Linear(hidden_nums, hidden_nums), nn.ReLU(inplace=True), ) self.fc_actor = nn.Linear(hidden_nums, output_nums) self.fc_critic = nn.Linear(hidden_nums, 1) # 重みの初期化 for m in self.modules(): if isinstance(m, nn.Linear): nn.init.xavier_uniform_(m.weight) m.bias.data.zero_() def forward(self, x): hid = self.layers(x) actor = self.fc_actor(hid) critic = self.fc_critic(hid) return actor, critic
none
1
3.224252
3
postcorrection/seq2seq_tester.py
shrutirij/ocr-post-correction
35
6623158
<reponame>shrutirij/ocr-post-correction<gh_stars>10-100 """Module with functions for using a trained post-correction model to produce predictions on unseen input data. The module can be used with a test set in order to get a text output and CER/WER metrics (lines 26). It can also be used without a target prediction to only get the predicted output (line 40). Copyright (c) 2021, <NAME> All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. """ import dynet as dy from utils import DataReader, ErrorMetrics class Seq2SeqTester: def __init__(self, model, output_name): self.model = model self.datareader = DataReader() self.metrics = ErrorMetrics() self.output_name = output_name def test(self, src1, src2, tgt): if tgt: data = self.datareader.read_parallel_data(self.model, src1, src2, tgt) output_name = "{}_{}".format(self.output_name, src1.split("/")[-1]) cer, wer = self.metrics.get_average_cer( self.model, data, output_file=open( "{}.output".format(output_name), "w", encoding="utf-8" ), write_pgens=False, ) with open("{}.metrics".format(output_name), "w") as output_file: output_file.write("TEST CER: %0.4f\n" % (cer)) output_file.write("TEST WER: %0.4f\n" % (wer)) else: output_file = open( "{}_{}.output".format(self.output_name, src1.split("/")[-1]), "w", encoding="utf8", ) data = self.datareader.read_test_data(self.model, src1, src2) for src1, src2 in data: if len(src1) == 0 or len(src2) == 0: output_file.write("\n") continue dy.renew_cg() output, _ = self.model.generate_beam(src1, src2) output_file.write(str(output) + "\n") output_file.close()
"""Module with functions for using a trained post-correction model to produce predictions on unseen input data. The module can be used with a test set in order to get a text output and CER/WER metrics (lines 26). It can also be used without a target prediction to only get the predicted output (line 40). Copyright (c) 2021, <NAME> All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. """ import dynet as dy from utils import DataReader, ErrorMetrics class Seq2SeqTester: def __init__(self, model, output_name): self.model = model self.datareader = DataReader() self.metrics = ErrorMetrics() self.output_name = output_name def test(self, src1, src2, tgt): if tgt: data = self.datareader.read_parallel_data(self.model, src1, src2, tgt) output_name = "{}_{}".format(self.output_name, src1.split("/")[-1]) cer, wer = self.metrics.get_average_cer( self.model, data, output_file=open( "{}.output".format(output_name), "w", encoding="utf-8" ), write_pgens=False, ) with open("{}.metrics".format(output_name), "w") as output_file: output_file.write("TEST CER: %0.4f\n" % (cer)) output_file.write("TEST WER: %0.4f\n" % (wer)) else: output_file = open( "{}_{}.output".format(self.output_name, src1.split("/")[-1]), "w", encoding="utf8", ) data = self.datareader.read_test_data(self.model, src1, src2) for src1, src2 in data: if len(src1) == 0 or len(src2) == 0: output_file.write("\n") continue dy.renew_cg() output, _ = self.model.generate_beam(src1, src2) output_file.write(str(output) + "\n") output_file.close()
en
0.817666
Module with functions for using a trained post-correction model to produce predictions on unseen input data. The module can be used with a test set in order to get a text output and CER/WER metrics (lines 26). It can also be used without a target prediction to only get the predicted output (line 40). Copyright (c) 2021, <NAME> All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree.
2.839709
3
src/pyndf/gui/widgets/control.py
Guillaume-Guardia/ndf-python
0
6623159
<filename>src/pyndf/gui/widgets/control.py # -*- coding: utf-8 -*- from pyndf.qtlib import QtWidgets class ControlButtons(QtWidgets.QWidget): """Widget adding in status bar to control the execution of the thread Args: QtWidgets (QT): """ def __init__(self, windows, *args, **kwargs): super().__init__(*args, **kwargs) self.windows = windows self.buttons = {} # Create vertical layout layout = QtWidgets.QHBoxLayout() # Cancel button icon = "" # TODO find icon pause text = self.tr("&Cancel") # Alt + C self.buttons["cancel"] = QtWidgets.QPushButton(text, parent=self) self.buttons["cancel"].clicked.connect(self.cancel) layout.addWidget(self.buttons["cancel"]) self.setLayout(layout) def cancel(self): """Cancel method which stop the thread execution safely with the set of a flag.""" if self.windows.process is not None: self.windows.process.flags.cancel = True
<filename>src/pyndf/gui/widgets/control.py # -*- coding: utf-8 -*- from pyndf.qtlib import QtWidgets class ControlButtons(QtWidgets.QWidget): """Widget adding in status bar to control the execution of the thread Args: QtWidgets (QT): """ def __init__(self, windows, *args, **kwargs): super().__init__(*args, **kwargs) self.windows = windows self.buttons = {} # Create vertical layout layout = QtWidgets.QHBoxLayout() # Cancel button icon = "" # TODO find icon pause text = self.tr("&Cancel") # Alt + C self.buttons["cancel"] = QtWidgets.QPushButton(text, parent=self) self.buttons["cancel"].clicked.connect(self.cancel) layout.addWidget(self.buttons["cancel"]) self.setLayout(layout) def cancel(self): """Cancel method which stop the thread execution safely with the set of a flag.""" if self.windows.process is not None: self.windows.process.flags.cancel = True
en
0.777384
# -*- coding: utf-8 -*- Widget adding in status bar to control the execution of the thread Args: QtWidgets (QT): # Create vertical layout # Cancel button # TODO find icon pause # Alt + C Cancel method which stop the thread execution safely with the set of a flag.
2.91059
3
bacaml/conftest.py
phetdam/bac-advanced-ml
0
6623160
<reponame>phetdam/bac-advanced-ml<filename>bacaml/conftest.py<gh_stars>0 """pytest fixtures required by all unit test subpackages. .. codeauthor:: <NAME> <<EMAIL>> """ import pytest @pytest.fixture(scope="session") def global_seed(): """Universal seed value to be reused by all test methods. Returns ------- int """ return 7
"""pytest fixtures required by all unit test subpackages. .. codeauthor:: <NAME> <<EMAIL>> """ import pytest @pytest.fixture(scope="session") def global_seed(): """Universal seed value to be reused by all test methods. Returns ------- int """ return 7
en
0.590198
pytest fixtures required by all unit test subpackages. .. codeauthor:: <NAME> <<EMAIL>> Universal seed value to be reused by all test methods. Returns ------- int
1.937557
2
tests/fixtures/q_functions/__init__.py
blacksph3re/garage
1,500
6623161
<filename>tests/fixtures/q_functions/__init__.py from tests.fixtures.q_functions.simple_q_function import SimpleQFunction __all__ = ['SimpleQFunction']
<filename>tests/fixtures/q_functions/__init__.py from tests.fixtures.q_functions.simple_q_function import SimpleQFunction __all__ = ['SimpleQFunction']
none
1
1.24167
1
Walkthru_10/ex_10_01.py
Witziger/Walkthru-Python
0
6623162
name = input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) counts = dict() for line in handle: if not line.startswith("From ") : continue line = line.rstrip() line = line.split() time = line[5] hour, minute, second = time.split(':') counts[hour] = counts.get(hour,0) + 1 #print (counts) t = list(counts.items()) t.sort() for key, val in t: print(key, val)
name = input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) counts = dict() for line in handle: if not line.startswith("From ") : continue line = line.rstrip() line = line.split() time = line[5] hour, minute, second = time.split(':') counts[hour] = counts.get(hour,0) + 1 #print (counts) t = list(counts.items()) t.sort() for key, val in t: print(key, val)
en
0.573618
#print (counts)
3.429411
3
openstack_dashboard/test/integration_tests/pages/admin/system/flavorspage.py
ankur-gupta91/block_storage
3
6623163
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack_dashboard.test.integration_tests.pages import basepage from openstack_dashboard.test.integration_tests.regions import forms from openstack_dashboard.test.integration_tests.regions import tables class FlavorsTable(tables.TableRegion): name = "flavors" CREATE_FLAVOR_FORM_FIELDS = (("name", "flavor_id", "vcpus", "memory_mb", "disk_gb", "eph_gb", "swap_mb"), ("all_projects", "selected_projects")) @tables.bind_table_action('create') def create_flavor(self, create_button): create_button.click() return forms.TabbedFormRegion( self.driver, self.conf, field_mappings=self.CREATE_FLAVOR_FORM_FIELDS) @tables.bind_table_action('delete') def delete_flavor(self, delete_button): delete_button.click() return forms.BaseFormRegion(self.driver, self.conf, None) class FlavorsPage(basepage.BaseNavigationPage): DEFAULT_ID = "auto" FLAVORS_TABLE_NAME_COLUMN = 'name' def __init__(self, driver, conf): super(FlavorsPage, self).__init__(driver, conf) self._page_title = "Flavors" @property def flavors_table(self): return FlavorsTable(self.driver, self.conf) def _get_flavor_row(self, name): return self.flavors_table.get_row(self.FLAVORS_TABLE_NAME_COLUMN, name) def create_flavor(self, name, id_=DEFAULT_ID, vcpus=None, ram=None, root_disk=None, ephemeral_disk=None, swap_disk=None): create_flavor_form = self.flavors_table.create_flavor() create_flavor_form.name.text = name if id_ is not None: create_flavor_form.flavor_id.text = id_ create_flavor_form.vcpus.value = vcpus create_flavor_form.memory_mb.value = ram create_flavor_form.disk_gb.value = root_disk create_flavor_form.eph_gb.value = ephemeral_disk create_flavor_form.swap_mb.value = swap_disk create_flavor_form.submit() def delete_flavor(self, name): row = self._get_flavor_row(name) row.mark() confirm_delete_flavors_form = self.flavors_table.delete_flavor() confirm_delete_flavors_form.submit() def is_flavor_present(self, name): return bool(self._get_flavor_row(name))
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack_dashboard.test.integration_tests.pages import basepage from openstack_dashboard.test.integration_tests.regions import forms from openstack_dashboard.test.integration_tests.regions import tables class FlavorsTable(tables.TableRegion): name = "flavors" CREATE_FLAVOR_FORM_FIELDS = (("name", "flavor_id", "vcpus", "memory_mb", "disk_gb", "eph_gb", "swap_mb"), ("all_projects", "selected_projects")) @tables.bind_table_action('create') def create_flavor(self, create_button): create_button.click() return forms.TabbedFormRegion( self.driver, self.conf, field_mappings=self.CREATE_FLAVOR_FORM_FIELDS) @tables.bind_table_action('delete') def delete_flavor(self, delete_button): delete_button.click() return forms.BaseFormRegion(self.driver, self.conf, None) class FlavorsPage(basepage.BaseNavigationPage): DEFAULT_ID = "auto" FLAVORS_TABLE_NAME_COLUMN = 'name' def __init__(self, driver, conf): super(FlavorsPage, self).__init__(driver, conf) self._page_title = "Flavors" @property def flavors_table(self): return FlavorsTable(self.driver, self.conf) def _get_flavor_row(self, name): return self.flavors_table.get_row(self.FLAVORS_TABLE_NAME_COLUMN, name) def create_flavor(self, name, id_=DEFAULT_ID, vcpus=None, ram=None, root_disk=None, ephemeral_disk=None, swap_disk=None): create_flavor_form = self.flavors_table.create_flavor() create_flavor_form.name.text = name if id_ is not None: create_flavor_form.flavor_id.text = id_ create_flavor_form.vcpus.value = vcpus create_flavor_form.memory_mb.value = ram create_flavor_form.disk_gb.value = root_disk create_flavor_form.eph_gb.value = ephemeral_disk create_flavor_form.swap_mb.value = swap_disk create_flavor_form.submit() def delete_flavor(self, name): row = self._get_flavor_row(name) row.mark() confirm_delete_flavors_form = self.flavors_table.delete_flavor() confirm_delete_flavors_form.submit() def is_flavor_present(self, name): return bool(self._get_flavor_row(name))
en
0.859654
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License.
1.840577
2
setup.py
TylerPflueger/CSCI4900
0
6623164
<gh_stars>0 from setuptools import setup _domaven_version = '0.0.1' ''' 'flake8', 'pyflakes', 'mccabe', 'pep8', 'dosocs2' ''' install_requires = [ 'treelib' ] tests_require = [ 'pytest' ] setup( name='domaven', version=_domaven_version, description='Connector between DoSOCSv2 and Maven for relationships', long_description='', url='https://github.com/tpflueger/CSCI4900', author='<NAME>, <NAME>', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Documentation', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT', 'Programming Language :: Python :: 2.7' 'Environment :: Console' ], keywords='spdx licenses maven dosocs2', packages=['scripts'], install_requires=install_requires, tests_require=tests_require, extras_require={ 'tests': install_requires + tests_require }, entry_points={'console_scripts': ['domaven=scripts.main:main']}, test_suite='py.test', zip_safe=False )
from setuptools import setup _domaven_version = '0.0.1' ''' 'flake8', 'pyflakes', 'mccabe', 'pep8', 'dosocs2' ''' install_requires = [ 'treelib' ] tests_require = [ 'pytest' ] setup( name='domaven', version=_domaven_version, description='Connector between DoSOCSv2 and Maven for relationships', long_description='', url='https://github.com/tpflueger/CSCI4900', author='<NAME>, <NAME>', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Documentation', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT', 'Programming Language :: Python :: 2.7' 'Environment :: Console' ], keywords='spdx licenses maven dosocs2', packages=['scripts'], install_requires=install_requires, tests_require=tests_require, extras_require={ 'tests': install_requires + tests_require }, entry_points={'console_scripts': ['domaven=scripts.main:main']}, test_suite='py.test', zip_safe=False )
en
0.087476
'flake8', 'pyflakes', 'mccabe', 'pep8', 'dosocs2'
1.283001
1
cla_backend/apps/checker/migrations/0001_initial.py
uk-gov-mirror/ministryofjustice.cla_backend
3
6623165
# coding=utf-8 from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone import model_utils.fields import uuidfield.fields class Migration(migrations.Migration): dependencies = [("legalaid", "0003_eod_details")] operations = [ migrations.CreateModel( name="ReasonForContacting", fields=[ ("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)), ( "created", model_utils.fields.AutoCreatedField( default=django.utils.timezone.now, verbose_name="created", editable=False ), ), ( "modified", model_utils.fields.AutoLastModifiedField( default=django.utils.timezone.now, verbose_name="modified", editable=False ), ), ("reference", uuidfield.fields.UUIDField(unique=True, max_length=32, editable=False, blank=True)), ("other_reasons", models.TextField(blank=True)), ("referrer", models.CharField(max_length=255, blank=True)), ("user_agent", models.CharField(max_length=255, blank=True)), ("case", models.ForeignKey(blank=True, to="legalaid.Case", null=True)), ], options={"ordering": ("-created",), "verbose_name_plural": "reasons for contacting"}, bases=(models.Model,), ), migrations.CreateModel( name="ReasonForContactingCategory", fields=[ ("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)), ( "category", models.CharField( max_length=20, choices=[ (b"CANT_ANSWER", "I don\u2019t know how to answer a question"), (b"MISSING_PAPERWORK", "I don\u2019t have the paperwork I need"), (b"PREFER_SPEAKING", "I\u2019d prefer to speak to someone"), (b"DIFFICULTY_ONLINE", "I have trouble using online services"), (b"HOW_SERVICE_HELPS", "I don\u2019t understand how this service can help me"), (b"AREA_NOT_COVERED", "My problem area isn\u2019t covered"), (b"PNS", "I\u2019d prefer not to say"), (b"OTHER", "Another reason"), ], ), ), ("reason_for_contacting", models.ForeignKey(related_name="reasons", to="checker.ReasonForContacting")), ], options={"verbose_name": "category", "verbose_name_plural": "categories"}, bases=(models.Model,), ), ]
# coding=utf-8 from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone import model_utils.fields import uuidfield.fields class Migration(migrations.Migration): dependencies = [("legalaid", "0003_eod_details")] operations = [ migrations.CreateModel( name="ReasonForContacting", fields=[ ("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)), ( "created", model_utils.fields.AutoCreatedField( default=django.utils.timezone.now, verbose_name="created", editable=False ), ), ( "modified", model_utils.fields.AutoLastModifiedField( default=django.utils.timezone.now, verbose_name="modified", editable=False ), ), ("reference", uuidfield.fields.UUIDField(unique=True, max_length=32, editable=False, blank=True)), ("other_reasons", models.TextField(blank=True)), ("referrer", models.CharField(max_length=255, blank=True)), ("user_agent", models.CharField(max_length=255, blank=True)), ("case", models.ForeignKey(blank=True, to="legalaid.Case", null=True)), ], options={"ordering": ("-created",), "verbose_name_plural": "reasons for contacting"}, bases=(models.Model,), ), migrations.CreateModel( name="ReasonForContactingCategory", fields=[ ("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)), ( "category", models.CharField( max_length=20, choices=[ (b"CANT_ANSWER", "I don\u2019t know how to answer a question"), (b"MISSING_PAPERWORK", "I don\u2019t have the paperwork I need"), (b"PREFER_SPEAKING", "I\u2019d prefer to speak to someone"), (b"DIFFICULTY_ONLINE", "I have trouble using online services"), (b"HOW_SERVICE_HELPS", "I don\u2019t understand how this service can help me"), (b"AREA_NOT_COVERED", "My problem area isn\u2019t covered"), (b"PNS", "I\u2019d prefer not to say"), (b"OTHER", "Another reason"), ], ), ), ("reason_for_contacting", models.ForeignKey(related_name="reasons", to="checker.ReasonForContacting")), ], options={"verbose_name": "category", "verbose_name_plural": "categories"}, bases=(models.Model,), ), ]
en
0.644078
# coding=utf-8
1.934536
2
router_change_ip.py
hbvj99/vianet-scripts
2
6623166
<filename>router_change_ip.py # ISCOM HT803-1GE EPON Home Terminal # Generate new public IP through reconnect from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import NoSuchElementException, NoSuchFrameException from requests import get import sys import credentials as c chrome_options = Options() chrome_options.add_argument("--headless") driver = webdriver.Chrome(options=chrome_options) def LoginRouter(): driver.get('http://192.168.1.1/admin/login.asp') driver.find_element(By.ID, 'username').click() driver.find_element(By.ID, 'username').click() element = driver.find_element(By.ID, 'username') actions = ActionChains(driver) actions.double_click(element).perform() driver.find_element(By.ID, 'username').send_keys(c.router_usr) driver.find_element(By.ID, 'psd').send_keys(c.router_psw) driver.find_element(By.CSS_SELECTOR, '.button:nth-child(1)').click() try: driver.find_element(By.CSS_SELECTOR, 'body > blockquote > form > table > tbody > tr:nth-child(1) > td > h4') sys.exit('ERROR! Superadmin login credential incorrect') except NoSuchElementException: pass driver.switch_to.frame(0) def NewIp(): driver.find_element(By.CSS_SELECTOR, 'td:nth-child(2) > p').click() driver.find_element(By.CSS_SELECTOR, 'td:nth-child(2) span').click() element = driver.find_element(By.CSS_SELECTOR, 'td:nth-child(2) span') actions = ActionChains(driver) actions.move_to_element(element).perform() element = driver.find_element(By.CSS_SELECTOR, 'body') actions = ActionChains(driver) driver.switch_to.default_content() driver.switch_to.frame(2) element = driver.find_element(By.CSS_SELECTOR, '.button:nth-child(39)') actions = ActionChains(driver) actions.move_to_element(element).release().perform() driver.find_element(By.CSS_SELECTOR, '.button:nth-child(39)').click() driver.find_element(By.CSS_SELECTOR, 'input').click() geo = get('http://ip-api.com/json').json() print('SUCCESS! New public IP is '+geo['query']+' by '+geo['isp']) if __name__ == '__main__': LoginRouter() NewIp() driver.quit()
<filename>router_change_ip.py # ISCOM HT803-1GE EPON Home Terminal # Generate new public IP through reconnect from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import NoSuchElementException, NoSuchFrameException from requests import get import sys import credentials as c chrome_options = Options() chrome_options.add_argument("--headless") driver = webdriver.Chrome(options=chrome_options) def LoginRouter(): driver.get('http://192.168.1.1/admin/login.asp') driver.find_element(By.ID, 'username').click() driver.find_element(By.ID, 'username').click() element = driver.find_element(By.ID, 'username') actions = ActionChains(driver) actions.double_click(element).perform() driver.find_element(By.ID, 'username').send_keys(c.router_usr) driver.find_element(By.ID, 'psd').send_keys(c.router_psw) driver.find_element(By.CSS_SELECTOR, '.button:nth-child(1)').click() try: driver.find_element(By.CSS_SELECTOR, 'body > blockquote > form > table > tbody > tr:nth-child(1) > td > h4') sys.exit('ERROR! Superadmin login credential incorrect') except NoSuchElementException: pass driver.switch_to.frame(0) def NewIp(): driver.find_element(By.CSS_SELECTOR, 'td:nth-child(2) > p').click() driver.find_element(By.CSS_SELECTOR, 'td:nth-child(2) span').click() element = driver.find_element(By.CSS_SELECTOR, 'td:nth-child(2) span') actions = ActionChains(driver) actions.move_to_element(element).perform() element = driver.find_element(By.CSS_SELECTOR, 'body') actions = ActionChains(driver) driver.switch_to.default_content() driver.switch_to.frame(2) element = driver.find_element(By.CSS_SELECTOR, '.button:nth-child(39)') actions = ActionChains(driver) actions.move_to_element(element).release().perform() driver.find_element(By.CSS_SELECTOR, '.button:nth-child(39)').click() driver.find_element(By.CSS_SELECTOR, 'input').click() geo = get('http://ip-api.com/json').json() print('SUCCESS! New public IP is '+geo['query']+' by '+geo['isp']) if __name__ == '__main__': LoginRouter() NewIp() driver.quit()
en
0.692329
# ISCOM HT803-1GE EPON Home Terminal # Generate new public IP through reconnect
2.478469
2
marlin-firmware/buildroot/share/PlatformIO/scripts/common-cxxflags.py
voicevon/gogame_bot
6
6623167
<reponame>voicevon/gogame_bot # # common-cxxflags.py # Convenience script to apply customizations to CPP flags # Import("env") env.Append(CXXFLAGS=[ "-Wno-register" #"-Wno-incompatible-pointer-types", #"-Wno-unused-const-variable", #"-Wno-maybe-uninitialized", #"-Wno-sign-compare" ])
# # common-cxxflags.py # Convenience script to apply customizations to CPP flags # Import("env") env.Append(CXXFLAGS=[ "-Wno-register" #"-Wno-incompatible-pointer-types", #"-Wno-unused-const-variable", #"-Wno-maybe-uninitialized", #"-Wno-sign-compare" ])
en
0.57934
# # common-cxxflags.py # Convenience script to apply customizations to CPP flags # #"-Wno-incompatible-pointer-types", #"-Wno-unused-const-variable", #"-Wno-maybe-uninitialized", #"-Wno-sign-compare"
1.487318
1
aghlam/migrations/0007_aghlam_external.py
mablue/Specialized-Procurement-and-Sales-Management-System-for-East-Azarbaijan-Gas-Company
30
6623168
<filename>aghlam/migrations/0007_aghlam_external.py # Generated by Django 2.2.2 on 2019-07-21 11:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('aghlam', '0006_auto_20190721_1122'), ] operations = [ migrations.AddField( model_name='aghlam', name='external', field=models.BooleanField(default=1, verbose_name='خارجی'), preserve_default=False, ), ]
<filename>aghlam/migrations/0007_aghlam_external.py # Generated by Django 2.2.2 on 2019-07-21 11:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('aghlam', '0006_auto_20190721_1122'), ] operations = [ migrations.AddField( model_name='aghlam', name='external', field=models.BooleanField(default=1, verbose_name='خارجی'), preserve_default=False, ), ]
en
0.763552
# Generated by Django 2.2.2 on 2019-07-21 11:25
1.272019
1
tests/test_make_dataset.py
Hannemit/data_science_projects
0
6623169
<filename>tests/test_make_dataset.py import pandas as pd CHOROPLETH_FILE = "./tests/data/choropleth_df.csv" CONVENIENT_FILE = "./tests/data/year_country_data.csv" def test_make_df_nicer_format(): """ Perform some checks on whether we didn't change anything weird in making the more convenient dataframe to work with It should contain the same information as the choropleth dataframe, just differently structured. We're here just checking that they're similar """ try: df_choropleth = pd.read_csv(CHOROPLETH_FILE) df_convenient = pd.read_csv(CONVENIENT_FILE) except FileNotFoundError: raise FileNotFoundError("Before running this test, make sure the data files are there.. these are the same ones" "that are created from running the make_dataset.py file") both = df_choropleth.groupby(['year', 'country']).agg(population=pd.NamedAgg(column="population", aggfunc=sum), suicides_no=pd.NamedAgg(column="suicides_no", aggfunc=sum), code=pd.NamedAgg(column="code", aggfunc=lambda x: x[0]), ).reset_index() both["overall_rate"] = both['suicides_no'] / both['population'] * 100000 right = df_convenient[["year", "country", "code", "population", "overall_rate", "suicides_no"]] pd.testing.assert_frame_equal(both.sort_index(axis=1), right.sort_index(axis=1)) # sort_index to get same col order left = df_choropleth.loc[df_choropleth["sex"] == "female"].drop(columns=["sex"], axis=1) right = df_convenient[["year", "country", "code", "female_pop", "female_rate", "suicide_num_f"]] right.index = list(range(len(right))) left.index = list(range(len(left))) right = right.rename(columns={"female_rate": "suicides per 100,000", "suicide_num_f": "suicides_no", "female_pop": "population"}) pd.testing.assert_frame_equal(left.sort_index(axis=1), right.sort_index(axis=1)) left = df_choropleth.loc[df_choropleth["sex"] == "male"].drop(columns=["sex"], axis=1) right = df_convenient[["year", "country", "code", "male_pop", "male_rate", "suicide_num_m"]] right.index = list(range(len(right))) left.index = list(range(len(left))) right = right.rename(columns={"male_rate": "suicides per 100,000", "suicide_num_m": "suicides_no", "male_pop": "population"}) pd.testing.assert_frame_equal(left.sort_index(axis=1), right.sort_index(axis=1)) def test_prepare_data_for_choropleth(): try: df_choropleth = pd.read_csv(CHOROPLETH_FILE) except FileNotFoundError: raise FileNotFoundError("Before running this test, run make_dataset.py to create our processed datafiles") both = df_choropleth.groupby(['year', 'country']).agg(population=pd.NamedAgg(column="population", aggfunc=sum), suicides_no=pd.NamedAgg(column="suicides_no", aggfunc=sum), code=pd.NamedAgg(column="code", aggfunc=lambda x: x[0]), ).reset_index() females = df_choropleth[df_choropleth["sex"] == "female"] males = df_choropleth[df_choropleth["sex"] == "male"] both["suicides per 100,000"] = both['suicides_no'] / both['population'] * 100000 # pick some random countries and check that male and female population add up to total population countries = df_choropleth["country"].unique() for country in countries[:50]: female_pop = females.loc[(females["country"] == country) & (females["year"] == 1992), "population"].values if len(female_pop) == 0: continue # might not have data for this country in the specific year we're looking at male_pop = males.loc[(males["country"] == country) & (males["year"] == 1992), "population"].values combined_pop = both.loc[(both["country"] == country) & (both["year"] == 1992), "population"].values assert combined_pop == female_pop + male_pop
<filename>tests/test_make_dataset.py import pandas as pd CHOROPLETH_FILE = "./tests/data/choropleth_df.csv" CONVENIENT_FILE = "./tests/data/year_country_data.csv" def test_make_df_nicer_format(): """ Perform some checks on whether we didn't change anything weird in making the more convenient dataframe to work with It should contain the same information as the choropleth dataframe, just differently structured. We're here just checking that they're similar """ try: df_choropleth = pd.read_csv(CHOROPLETH_FILE) df_convenient = pd.read_csv(CONVENIENT_FILE) except FileNotFoundError: raise FileNotFoundError("Before running this test, make sure the data files are there.. these are the same ones" "that are created from running the make_dataset.py file") both = df_choropleth.groupby(['year', 'country']).agg(population=pd.NamedAgg(column="population", aggfunc=sum), suicides_no=pd.NamedAgg(column="suicides_no", aggfunc=sum), code=pd.NamedAgg(column="code", aggfunc=lambda x: x[0]), ).reset_index() both["overall_rate"] = both['suicides_no'] / both['population'] * 100000 right = df_convenient[["year", "country", "code", "population", "overall_rate", "suicides_no"]] pd.testing.assert_frame_equal(both.sort_index(axis=1), right.sort_index(axis=1)) # sort_index to get same col order left = df_choropleth.loc[df_choropleth["sex"] == "female"].drop(columns=["sex"], axis=1) right = df_convenient[["year", "country", "code", "female_pop", "female_rate", "suicide_num_f"]] right.index = list(range(len(right))) left.index = list(range(len(left))) right = right.rename(columns={"female_rate": "suicides per 100,000", "suicide_num_f": "suicides_no", "female_pop": "population"}) pd.testing.assert_frame_equal(left.sort_index(axis=1), right.sort_index(axis=1)) left = df_choropleth.loc[df_choropleth["sex"] == "male"].drop(columns=["sex"], axis=1) right = df_convenient[["year", "country", "code", "male_pop", "male_rate", "suicide_num_m"]] right.index = list(range(len(right))) left.index = list(range(len(left))) right = right.rename(columns={"male_rate": "suicides per 100,000", "suicide_num_m": "suicides_no", "male_pop": "population"}) pd.testing.assert_frame_equal(left.sort_index(axis=1), right.sort_index(axis=1)) def test_prepare_data_for_choropleth(): try: df_choropleth = pd.read_csv(CHOROPLETH_FILE) except FileNotFoundError: raise FileNotFoundError("Before running this test, run make_dataset.py to create our processed datafiles") both = df_choropleth.groupby(['year', 'country']).agg(population=pd.NamedAgg(column="population", aggfunc=sum), suicides_no=pd.NamedAgg(column="suicides_no", aggfunc=sum), code=pd.NamedAgg(column="code", aggfunc=lambda x: x[0]), ).reset_index() females = df_choropleth[df_choropleth["sex"] == "female"] males = df_choropleth[df_choropleth["sex"] == "male"] both["suicides per 100,000"] = both['suicides_no'] / both['population'] * 100000 # pick some random countries and check that male and female population add up to total population countries = df_choropleth["country"].unique() for country in countries[:50]: female_pop = females.loc[(females["country"] == country) & (females["year"] == 1992), "population"].values if len(female_pop) == 0: continue # might not have data for this country in the specific year we're looking at male_pop = males.loc[(males["country"] == country) & (males["year"] == 1992), "population"].values combined_pop = both.loc[(both["country"] == country) & (both["year"] == 1992), "population"].values assert combined_pop == female_pop + male_pop
en
0.938221
Perform some checks on whether we didn't change anything weird in making the more convenient dataframe to work with It should contain the same information as the choropleth dataframe, just differently structured. We're here just checking that they're similar # sort_index to get same col order # pick some random countries and check that male and female population add up to total population # might not have data for this country in the specific year we're looking at
3.641819
4
examples/jetson_nano/example_technichub_jetson_nano.py
AlexandrePoisson/pylgbst
0
6623170
<reponame>AlexandrePoisson/pylgbst from pylgbst.hub import TechnicHub from pylgbst import get_connection_gattool from pylgbst.peripherals import Motor,EncodedMotor import time import random def callback(value): print("Voltage: %s" % value) conn = get_connection_gattool(hub_mac='90:84:2B:5F:33:35') #auto connect does not work hub = TechnicHub(conn) for device in hub.peripherals: print(device) direction_motor = Motor(hub, hub.PORT_B) power_motor = Motor(hub, hub.PORT_D) while True: #hub.connection.notification_delayed('050082030a', 0.1) power_motor.start_power(random.uniform(0, 1.0)) #here motor really moves direction_motor.start_power(random.uniform(-0.2, 0.2)) #here motor really moves time.sleep(0.5) #hub.connection.notification_delayed('050082030a', 0.1) power_motor.stop() #here motor really stops print("Goodbye") """ Output 0 50 => 0x32 59 => 0x3B 60 => 0x3C Goodbye """
from pylgbst.hub import TechnicHub from pylgbst import get_connection_gattool from pylgbst.peripherals import Motor,EncodedMotor import time import random def callback(value): print("Voltage: %s" % value) conn = get_connection_gattool(hub_mac='90:84:2B:5F:33:35') #auto connect does not work hub = TechnicHub(conn) for device in hub.peripherals: print(device) direction_motor = Motor(hub, hub.PORT_B) power_motor = Motor(hub, hub.PORT_D) while True: #hub.connection.notification_delayed('050082030a', 0.1) power_motor.start_power(random.uniform(0, 1.0)) #here motor really moves direction_motor.start_power(random.uniform(-0.2, 0.2)) #here motor really moves time.sleep(0.5) #hub.connection.notification_delayed('050082030a', 0.1) power_motor.stop() #here motor really stops print("Goodbye") """ Output 0 50 => 0x32 59 => 0x3B 60 => 0x3C Goodbye """
en
0.697338
#auto connect does not work #hub.connection.notification_delayed('050082030a', 0.1) #here motor really moves #here motor really moves #hub.connection.notification_delayed('050082030a', 0.1) #here motor really stops Output 0 50 => 0x32 59 => 0x3B 60 => 0x3C Goodbye
2.494912
2
servers/bazarr/scripts/findRename.py
beakerflo/nas_synology_docker-compose
3
6623171
<reponame>beakerflo/nas_synology_docker-compose import os from datetime import datetime dateString = (datetime.now()).strftime("%Y%m%d_%H%M%S") os.rename('/volume1/containers/services/bazarr/scripts/rename.sh', '/volume1/containers/services/bazarr/scripts/rename.sh_' + dateString + '.txt') renameSrt = open('/volume1/containers/services/bazarr/scripts/rename.sh','a') movies = '/volume2/movies' for movieLanguage in os.listdir(movies): if movieLanguage != '.DS_Store': for movieFolder in os.listdir(movies + '/' + movieLanguage): if ' (' in movieFolder: for movieFile in os.listdir(movies + '/' + movieLanguage + '/' + movieFolder): if 'srt' in movieFile: if 'synced' in movieFile: srtfile = '"' + movies + '/' + movieLanguage + '/' + movieFolder + '/' + movieFile + '"' syncedSrtFile = srtfile outOfSync = srtfile.replace('synced.','') newNameForOutOfSync = srtfile.replace('synced','downloaded') newNameForSyncedSrtFile = outOfSync renameSrt.write('mv ' + outOfSync + ' ' + newNameForOutOfSync + '\n') renameSrt.write('mv ' + syncedSrtFile + ' ' + newNameForSyncedSrtFile + '\n') series = '/volume2/tvshows' for serieLanguage in os.listdir(series): if serieLanguage != '.DS_Store' and serieLanguage != '@eaDir': for serieFolder in os.listdir(series + '/' + serieLanguage): if serieFolder != '.DS_Store' and serieFolder != '@eaDir': for serieSeason in os.listdir(series + '/' + serieLanguage + '/' + serieFolder): if serieSeason != '.DS_Store' and serieSeason != '@eaDir': for serieFile in os.listdir(series + '/' + serieLanguage + '/' + serieFolder + '/' + serieSeason): if 'synced' in serieFile: srtfile = '"' + series + '/' + serieLanguage + '/' + serieFolder + '/' + serieSeason + '/' + serieFile + '"' syncedSrtFile = srtfile outOfSync = srtfile.replace('synced.','') newNameForOutOfSync = srtfile.replace('synced','downloaded') newNameForSyncedSrtFile = outOfSync renameSrt.write('mv ' + outOfSync + ' ' + newNameForOutOfSync + '\n') renameSrt.write('mv ' + syncedSrtFile + ' ' + newNameForSyncedSrtFile + '\n')
import os from datetime import datetime dateString = (datetime.now()).strftime("%Y%m%d_%H%M%S") os.rename('/volume1/containers/services/bazarr/scripts/rename.sh', '/volume1/containers/services/bazarr/scripts/rename.sh_' + dateString + '.txt') renameSrt = open('/volume1/containers/services/bazarr/scripts/rename.sh','a') movies = '/volume2/movies' for movieLanguage in os.listdir(movies): if movieLanguage != '.DS_Store': for movieFolder in os.listdir(movies + '/' + movieLanguage): if ' (' in movieFolder: for movieFile in os.listdir(movies + '/' + movieLanguage + '/' + movieFolder): if 'srt' in movieFile: if 'synced' in movieFile: srtfile = '"' + movies + '/' + movieLanguage + '/' + movieFolder + '/' + movieFile + '"' syncedSrtFile = srtfile outOfSync = srtfile.replace('synced.','') newNameForOutOfSync = srtfile.replace('synced','downloaded') newNameForSyncedSrtFile = outOfSync renameSrt.write('mv ' + outOfSync + ' ' + newNameForOutOfSync + '\n') renameSrt.write('mv ' + syncedSrtFile + ' ' + newNameForSyncedSrtFile + '\n') series = '/volume2/tvshows' for serieLanguage in os.listdir(series): if serieLanguage != '.DS_Store' and serieLanguage != '@eaDir': for serieFolder in os.listdir(series + '/' + serieLanguage): if serieFolder != '.DS_Store' and serieFolder != '@eaDir': for serieSeason in os.listdir(series + '/' + serieLanguage + '/' + serieFolder): if serieSeason != '.DS_Store' and serieSeason != '@eaDir': for serieFile in os.listdir(series + '/' + serieLanguage + '/' + serieFolder + '/' + serieSeason): if 'synced' in serieFile: srtfile = '"' + series + '/' + serieLanguage + '/' + serieFolder + '/' + serieSeason + '/' + serieFile + '"' syncedSrtFile = srtfile outOfSync = srtfile.replace('synced.','') newNameForOutOfSync = srtfile.replace('synced','downloaded') newNameForSyncedSrtFile = outOfSync renameSrt.write('mv ' + outOfSync + ' ' + newNameForOutOfSync + '\n') renameSrt.write('mv ' + syncedSrtFile + ' ' + newNameForSyncedSrtFile + '\n')
none
1
2.424469
2
src/main.py
loreloc/exoplanet-detection
5
6623172
import numpy as np import sklearn as sk import sklearn.model_selection from rfc_worker import RFCWorker from hb_optimizer import HBOptimizer from metrics import compute_metrics from koi_dataset import load_koi_dataset # Set the LOCALHOST, PROJECT_NAME constants LOCALHOST = '127.0.0.1' PROJECT_NAME = 'exoplanet-detection' # Set the parameters for hyperparameters optimization eta = 3 min_budget = 8 max_budget = 216 n_iterations = 8 n_workers = 4 n_repetitions = 10 # Load the dataset x_data, y_data = load_koi_dataset() (n_samples, n_features) = x_data.shape # Initialize the optimizer optimizer = HBOptimizer( LOCALHOST, PROJECT_NAME, RFCWorker, eta, min_budget, max_budget, n_iterations ) metrics = { 'precision': 0.0, 'recall': 0.0, 'f1': 0.0, 'confusion': [[0, 0], [0, 0]], 'importances': np.zeros(n_features) } # Repeat multiple times the test for _ in range(n_repetitions): # Split the dataset in train set and test set x_train, x_test, y_train, y_test = sk.model_selection.train_test_split( x_data, y_data, test_size=0.20, stratify=y_data ) # Start the optimizer optimizer.start() # Run the optimizer config = optimizer.run(n_workers, x_train, y_train) # Build and train the best model rfc = RFCWorker.build(config, max_budget) rfc.fit(x_train, y_train) # Compute some evaluation metrics scores = compute_metrics(rfc, x_test, y_test) for k in metrics: metrics[k] = metrics[k] + scores[k] # Close the optimizer optimizer.close() # Normalize the metrics for k in metrics: metrics[k] = metrics[k] / n_repetitions # Print the metrics print(metrics)
import numpy as np import sklearn as sk import sklearn.model_selection from rfc_worker import RFCWorker from hb_optimizer import HBOptimizer from metrics import compute_metrics from koi_dataset import load_koi_dataset # Set the LOCALHOST, PROJECT_NAME constants LOCALHOST = '127.0.0.1' PROJECT_NAME = 'exoplanet-detection' # Set the parameters for hyperparameters optimization eta = 3 min_budget = 8 max_budget = 216 n_iterations = 8 n_workers = 4 n_repetitions = 10 # Load the dataset x_data, y_data = load_koi_dataset() (n_samples, n_features) = x_data.shape # Initialize the optimizer optimizer = HBOptimizer( LOCALHOST, PROJECT_NAME, RFCWorker, eta, min_budget, max_budget, n_iterations ) metrics = { 'precision': 0.0, 'recall': 0.0, 'f1': 0.0, 'confusion': [[0, 0], [0, 0]], 'importances': np.zeros(n_features) } # Repeat multiple times the test for _ in range(n_repetitions): # Split the dataset in train set and test set x_train, x_test, y_train, y_test = sk.model_selection.train_test_split( x_data, y_data, test_size=0.20, stratify=y_data ) # Start the optimizer optimizer.start() # Run the optimizer config = optimizer.run(n_workers, x_train, y_train) # Build and train the best model rfc = RFCWorker.build(config, max_budget) rfc.fit(x_train, y_train) # Compute some evaluation metrics scores = compute_metrics(rfc, x_test, y_test) for k in metrics: metrics[k] = metrics[k] + scores[k] # Close the optimizer optimizer.close() # Normalize the metrics for k in metrics: metrics[k] = metrics[k] / n_repetitions # Print the metrics print(metrics)
en
0.544526
# Set the LOCALHOST, PROJECT_NAME constants # Set the parameters for hyperparameters optimization # Load the dataset # Initialize the optimizer # Repeat multiple times the test # Split the dataset in train set and test set # Start the optimizer # Run the optimizer # Build and train the best model # Compute some evaluation metrics # Close the optimizer # Normalize the metrics # Print the metrics
2.546557
3
app/views/display_tasks_view.py
namuan/task-rider
0
6623173
<filename>app/views/display_tasks_view.py import logging from PyQt5 import QtWidgets from PyQt5.QtCore import Qt, QModelIndex from PyQt5.QtWidgets import QMenu, QAction from app.widgets.completed_task_item_widget import CompletedTaskItemWidget from app.widgets.task_item_widget import TaskItemWidget class DisplayTasksView: def __init__(self, main_window): self.main_window = main_window def setup_item_edit_handler(self, on_edit_selected): self.main_window.lst_tasks.itemDoubleClicked.connect(on_edit_selected) def setup_context_menu(self, on_delete_selected): delete_action = QAction("Delete", self.main_window.lst_tasks) delete_action.triggered.connect(on_delete_selected) self.menu = QMenu() self.menu.addAction(delete_action) self.main_window.lst_tasks.setContextMenuPolicy(Qt.CustomContextMenu) self.main_window.lst_tasks.customContextMenuRequested.connect( self.on_display_context_menu ) def on_display_context_menu(self, position): index: QModelIndex = self.main_window.lst_tasks.indexAt(position) if not index.isValid(): return global_position = self.main_window.lst_tasks.viewport().mapToGlobal(position) self.menu.exec_(global_position) def clear(self): self.main_window.lst_tasks.clear() def task_from_widget(self, item_widget): return self.main_window.lst_tasks.itemWidget(item_widget) def selected_task_widget(self): item_widget = self.main_window.lst_tasks.currentItem() if item_widget: t = self.task_from_widget(item_widget) return t.get_task_id() else: return None def widget_iterator(self): for i in range(self.main_window.lst_tasks.count()): task_widget = self.task_from_widget(self.main_window.lst_tasks.item(i)) yield i, task_widget def show_task_editor(self, item_widget): task_widget = self.task_from_widget(item_widget) task_widget.edit_task() def render_task_entity(self, task_entity, on_btn_task_done=None, on_task_save=None): logging.info("Adding a new task widget for {}".format(task_entity)) task_widget = TaskItemWidget( self.main_window, task_entity, on_btn_task_done, on_task_save ) task_widget_item = QtWidgets.QListWidgetItem(self.main_window.lst_tasks) task_widget_item.setSizeHint(task_widget.sizeHint()) self.main_window.lst_tasks.addItem(task_widget_item) self.main_window.lst_tasks.setItemWidget(task_widget_item, task_widget) def render_completed_task_entity(self, task_entity, callback=None): logging.info("Adding a new completed task widget for {}".format(task_entity)) task_widget = CompletedTaskItemWidget(self.main_window, task_entity, callback) task_widget_item = QtWidgets.QListWidgetItem(self.main_window.lst_tasks) task_widget_item.setSizeHint(task_widget.sizeHint()) self.main_window.lst_tasks.addItem(task_widget_item) self.main_window.lst_tasks.setItemWidget(task_widget_item, task_widget)
<filename>app/views/display_tasks_view.py import logging from PyQt5 import QtWidgets from PyQt5.QtCore import Qt, QModelIndex from PyQt5.QtWidgets import QMenu, QAction from app.widgets.completed_task_item_widget import CompletedTaskItemWidget from app.widgets.task_item_widget import TaskItemWidget class DisplayTasksView: def __init__(self, main_window): self.main_window = main_window def setup_item_edit_handler(self, on_edit_selected): self.main_window.lst_tasks.itemDoubleClicked.connect(on_edit_selected) def setup_context_menu(self, on_delete_selected): delete_action = QAction("Delete", self.main_window.lst_tasks) delete_action.triggered.connect(on_delete_selected) self.menu = QMenu() self.menu.addAction(delete_action) self.main_window.lst_tasks.setContextMenuPolicy(Qt.CustomContextMenu) self.main_window.lst_tasks.customContextMenuRequested.connect( self.on_display_context_menu ) def on_display_context_menu(self, position): index: QModelIndex = self.main_window.lst_tasks.indexAt(position) if not index.isValid(): return global_position = self.main_window.lst_tasks.viewport().mapToGlobal(position) self.menu.exec_(global_position) def clear(self): self.main_window.lst_tasks.clear() def task_from_widget(self, item_widget): return self.main_window.lst_tasks.itemWidget(item_widget) def selected_task_widget(self): item_widget = self.main_window.lst_tasks.currentItem() if item_widget: t = self.task_from_widget(item_widget) return t.get_task_id() else: return None def widget_iterator(self): for i in range(self.main_window.lst_tasks.count()): task_widget = self.task_from_widget(self.main_window.lst_tasks.item(i)) yield i, task_widget def show_task_editor(self, item_widget): task_widget = self.task_from_widget(item_widget) task_widget.edit_task() def render_task_entity(self, task_entity, on_btn_task_done=None, on_task_save=None): logging.info("Adding a new task widget for {}".format(task_entity)) task_widget = TaskItemWidget( self.main_window, task_entity, on_btn_task_done, on_task_save ) task_widget_item = QtWidgets.QListWidgetItem(self.main_window.lst_tasks) task_widget_item.setSizeHint(task_widget.sizeHint()) self.main_window.lst_tasks.addItem(task_widget_item) self.main_window.lst_tasks.setItemWidget(task_widget_item, task_widget) def render_completed_task_entity(self, task_entity, callback=None): logging.info("Adding a new completed task widget for {}".format(task_entity)) task_widget = CompletedTaskItemWidget(self.main_window, task_entity, callback) task_widget_item = QtWidgets.QListWidgetItem(self.main_window.lst_tasks) task_widget_item.setSizeHint(task_widget.sizeHint()) self.main_window.lst_tasks.addItem(task_widget_item) self.main_window.lst_tasks.setItemWidget(task_widget_item, task_widget)
none
1
2.184412
2
model.py
Information-Fusion-Lab-Umass/NoisyInjectiveFlows
0
6623174
<filename>model.py import os import glob import jax import jax.numpy as jnp import staxplusplus as spp import normalizing_flows as nf import jax.nn.initializers as jaxinit from jax.tree_util import tree_flatten import util import non_dim_preserving as ndp from functools import partial ###################################################################################################################################################### class Model(): def __init__(self, dataset_name, x_shape): self.x_shape = x_shape self.dataset_name = dataset_name self.init_fun, self.forward, self.inverse = None, None, None self.names, self.z_shape, self.params, self.state = None, None, None, None self.n_params = None def get_architecture(self, init_key=None): assert 0, 'unimplemented' def get_prior(self): assert 0, 'unimplemented' ##################################################################### def build_model(self, quantize_level_bits, init_key=None): architecture = self.get_architecture(init_key=init_key) prior = self.get_prior() # Use uniform dequantization to build our model flow = nf.sequential_flow(nf.Dequantization(scale=2**quantize_level_bits), nf.Logit(), architecture, nf.Flatten(), prior) self.init_fun, self.forward, self.inverse = flow ##################################################################### def initialize_model(self, key): assert self.init_fun is not None, 'Need to call build_model' self.names, self.z_shape, self.params, self.state = self.init_fun(key, self.x_shape, ()) self.n_params = jax.flatten_util.ravel_pytree(self.params)[0].shape[0] print('Total number of parameters:', self.n_params) ##################################################################### def gen_meta_data(self): """ Create a dictionary that will tell us exactly how to create this model """ meta = {'x_shape' : list(self.x_shape), 'dataset_name': self.dataset_name, 'model' : None} return meta @classmethod def initialize_from_meta_data(cls, meta): assert 0, 'unimplemented' ##################################################################### def save_state(self, path): util.save_pytree_to_file(self.state, path) def load_state_from_file(self, path): self.state = util.load_pytree_from_file(self.state, path) ###################################################################################################################################################### class GLOW(Model): def __init__(self, dataset_name, x_shape, n_filters=256, n_blocks=16, n_multiscale=5, data_init_iterations=1000): super().__init__(dataset_name, x_shape) self.n_filters = n_filters self.n_blocks = n_blocks self.n_multiscale = n_multiscale self.data_init_iterations = data_init_iterations ##################################################################### def get_architecture(self, init_key=None): """ Build the architecture from GLOW https://arxiv.org/pdf/1807.03039.pdf """ def GLOWNet(out_shape, n_filters): """ Transformation used inside affine coupling """ _, _, channels = out_shape return spp.sequential(spp.Conv(n_filters, filter_shape=(3, 3), padding=((1, 1), (1, 1)), bias=True, weightnorm=False), spp.Relu(), spp.Conv(n_filters, filter_shape=(1, 1), padding=((0, 0), (0, 0)), bias=True, weightnorm=False), spp.Relu(), spp.Conv(2*channels, filter_shape=(3, 3), padding=((1, 1), (1, 1)), bias=True, weightnorm=False, W_init=jaxinit.zeros, b_init=jaxinit.zeros), spp.Split(2, axis=-1), spp.parallel(spp.Tanh(), spp.Identity())) # log_s, t def GLOWComponent(name_iter, n_filters, n_blocks): """ Compose glow blocks """ layers = [nf.GLOWBlock(partial(GLOWNet, n_filters=n_filters), masked=False, name=next(name_iter), additive_coupling=False)]*n_blocks return nf.sequential_flow(nf.Debug(''), *layers) # To initialize our model, we want a debugger to print out the size of the network at each multiscale debug_kwargs = dict(print_init_shape=True, print_forward_shape=False, print_inverse_shape=False, compare_vals=False) # We want to name the glow blocks so that we can do data dependent initialization name_iter = iter(['glow_%d'%i for i in range(400)]) # The multiscale architecture factors out pixels def multi_scale(i, flow): if(isinstance(self.n_filters, int)): n_filters = self.n_filters else: n_filters = self.n_filters[i] if(isinstance(self.n_blocks, int)): n_blocks = self.n_blocks else: n_blocks = self.n_blocks[i] return nf.sequential_flow(nf.Squeeze(), GLOWComponent(name_iter, n_filters, n_blocks), nf.FactorOut(2), nf.factored_flow(flow, nf.Identity()), nf.FanInConcat(2), nf.UnSqueeze()) flow = nf.Identity() for i in range(self.n_multiscale): flow = multi_scale(i, flow) if(init_key is not None): # Add the ability to ensure that things arae initialized together flow = nf.key_wrap(flow, init_key) return flow def get_prior(self): return nf.UnitGaussianPrior() ##################################################################### def gen_meta_data(self): """ Create a dictionary that will tell us exactly how to create this model """ meta = {'n_filters' : self.n_filters, 'n_blocks' : self.n_blocks, 'n_multiscale' : self.n_multiscale, 'data_init_iterations': self.data_init_iterations, 'model' : 'GLOW'} parent_meta = super().gen_meta_data() parent_meta.update(meta) return parent_meta @classmethod def initialize_from_meta_data(cls, meta): """ Using a meta data, construct an instance of this model """ dataset_name = meta['dataset_name'] x_shape = tuple(meta['x_shape']) n_filters = meta['n_filters'] n_blocks = meta['n_blocks'] n_multiscale = meta['n_multiscale'] data_init_iterations = meta.get('data_init_iterations', 1000) return GLOW(dataset_name, x_shape, n_filters, n_blocks, n_multiscale, data_init_iterations) ##################################################################### def data_dependent_init(self, key, data_loader, batch_size=64): actnorm_names = [name for name in tree_flatten(self.names)[0] if 'act_norm' in name] flow_model = (self.names, self.z_shape, self.params, self.state), self.forward, self.inverse params = nf.multistep_flow_data_dependent_init(None, actnorm_names, flow_model, (), 'actnorm_seed', key, data_loader=data_loader, n_seed_examples=self.data_init_iterations, batch_size=batch_size, notebook=False) self.params = params ###################################################################################################################################################### class SimpleNIF(GLOW): def __init__(self, dataset_name, x_shape, z_dim, n_filters=256, n_blocks=16, n_multiscale=5, data_init_iterations=1000): super().__init__(dataset_name, x_shape, n_filters, n_blocks, n_multiscale, data_init_iterations) self.z_dim = z_dim def get_prior(self): return ndp.AffineGaussianPriorDiagCov(self.z_dim) ##################################################################### def gen_meta_data(self): """ Create a dictionary that will tell us exactly how to create this model """ parent_meta = super().gen_meta_data() meta = {'z_dim': self.z_dim, 'model': 'SimpleNIF'} parent_meta.update(meta) return parent_meta @classmethod def initialize_from_meta_data(cls, meta): """ Using a meta data, construct an instance of this model """ dataset_name = meta['dataset_name'] x_shape = tuple(meta['x_shape']) n_filters = meta['n_filters'] n_blocks = meta['n_blocks'] n_multiscale = meta['n_multiscale'] z_dim = meta['z_dim'] data_init_iterations = meta.get('data_init_iterations', 1000) return SimpleNIF(dataset_name, x_shape, z_dim, n_filters, n_blocks, n_multiscale, data_init_iterations) ###################################################################################################################################################### class NIF(GLOW): def __init__(self, dataset_name, x_shape, z_dim, n_filters=256, n_blocks=16, n_multiscale=5, n_hidden_layers=3, layer_size=1024, n_flat_layers=5, n_importance_samples=16): super().__init__(dataset_name, x_shape, n_filters, n_blocks, n_multiscale) self.z_dim = z_dim self.n_hidden_layers = n_hidden_layers self.layer_size = layer_size self.n_flat_layers = n_flat_layers self.n_importance_samples = n_importance_samples def get_prior(self): an_names = iter(['flat_act_norm_%d'%i for i in range(100)]) def FlatTransform(out_shape): dense_layers = [spp.Dense(self.layer_size), spp.Relu()]*self.n_hidden_layers return spp.sequential(*dense_layers, spp.Dense(out_shape[-1]*2), spp.Split(2, axis=-1), spp.parallel(spp.Tanh(), spp.Identity())) # log_s, t layers = [nf.AffineCoupling(FlatTransform), nf.ActNorm(name=next(an_names)), nf.Reverse()]*self.n_flat_layers prior_flow = nf.sequential_flow(*layers, nf.UnitGaussianPrior()) return ndp.TallAffineDiagCov(prior_flow, self.z_dim, n_training_importance_samples=self.n_importance_samples) ##################################################################### def gen_meta_data(self): """ Create a dictionary that will tell us exactly how to create this model """ parent_meta = super().gen_meta_data() meta = {'z_dim' : self.z_dim, 'n_hidden_layers' : self.n_hidden_layers, 'layer_size' : self.layer_size, 'n_flat_layers' : self.n_flat_layers, 'n_importance_samples': self.n_importance_samples, 'model' : 'NIF'} parent_meta.update(meta) return parent_meta @classmethod def initialize_from_meta_data(cls, meta): """ Using a meta data, construct an instance of this model """ dataset_name = meta['dataset_name'] x_shape = tuple(meta['x_shape']) n_filters = meta['n_filters'] n_blocks = meta['n_blocks'] n_multiscale = meta['n_multiscale'] z_dim = meta['z_dim'] n_hidden_layers = meta['n_hidden_layers'] layer_size = meta['layer_size'] n_flat_layers = meta['n_flat_layers'] n_importance_samples = meta['n_importance_samples'] return NIF(dataset_name, x_shape, z_dim, n_filters, n_blocks, n_multiscale, n_hidden_layers, layer_size, n_flat_layers, n_importance_samples) ###################################################################################################################################################### # Use a global to make loading easy MODEL_LIST = {'GLOW' : GLOW, 'SimpleNIF': SimpleNIF, 'NIF' : NIF}
<filename>model.py import os import glob import jax import jax.numpy as jnp import staxplusplus as spp import normalizing_flows as nf import jax.nn.initializers as jaxinit from jax.tree_util import tree_flatten import util import non_dim_preserving as ndp from functools import partial ###################################################################################################################################################### class Model(): def __init__(self, dataset_name, x_shape): self.x_shape = x_shape self.dataset_name = dataset_name self.init_fun, self.forward, self.inverse = None, None, None self.names, self.z_shape, self.params, self.state = None, None, None, None self.n_params = None def get_architecture(self, init_key=None): assert 0, 'unimplemented' def get_prior(self): assert 0, 'unimplemented' ##################################################################### def build_model(self, quantize_level_bits, init_key=None): architecture = self.get_architecture(init_key=init_key) prior = self.get_prior() # Use uniform dequantization to build our model flow = nf.sequential_flow(nf.Dequantization(scale=2**quantize_level_bits), nf.Logit(), architecture, nf.Flatten(), prior) self.init_fun, self.forward, self.inverse = flow ##################################################################### def initialize_model(self, key): assert self.init_fun is not None, 'Need to call build_model' self.names, self.z_shape, self.params, self.state = self.init_fun(key, self.x_shape, ()) self.n_params = jax.flatten_util.ravel_pytree(self.params)[0].shape[0] print('Total number of parameters:', self.n_params) ##################################################################### def gen_meta_data(self): """ Create a dictionary that will tell us exactly how to create this model """ meta = {'x_shape' : list(self.x_shape), 'dataset_name': self.dataset_name, 'model' : None} return meta @classmethod def initialize_from_meta_data(cls, meta): assert 0, 'unimplemented' ##################################################################### def save_state(self, path): util.save_pytree_to_file(self.state, path) def load_state_from_file(self, path): self.state = util.load_pytree_from_file(self.state, path) ###################################################################################################################################################### class GLOW(Model): def __init__(self, dataset_name, x_shape, n_filters=256, n_blocks=16, n_multiscale=5, data_init_iterations=1000): super().__init__(dataset_name, x_shape) self.n_filters = n_filters self.n_blocks = n_blocks self.n_multiscale = n_multiscale self.data_init_iterations = data_init_iterations ##################################################################### def get_architecture(self, init_key=None): """ Build the architecture from GLOW https://arxiv.org/pdf/1807.03039.pdf """ def GLOWNet(out_shape, n_filters): """ Transformation used inside affine coupling """ _, _, channels = out_shape return spp.sequential(spp.Conv(n_filters, filter_shape=(3, 3), padding=((1, 1), (1, 1)), bias=True, weightnorm=False), spp.Relu(), spp.Conv(n_filters, filter_shape=(1, 1), padding=((0, 0), (0, 0)), bias=True, weightnorm=False), spp.Relu(), spp.Conv(2*channels, filter_shape=(3, 3), padding=((1, 1), (1, 1)), bias=True, weightnorm=False, W_init=jaxinit.zeros, b_init=jaxinit.zeros), spp.Split(2, axis=-1), spp.parallel(spp.Tanh(), spp.Identity())) # log_s, t def GLOWComponent(name_iter, n_filters, n_blocks): """ Compose glow blocks """ layers = [nf.GLOWBlock(partial(GLOWNet, n_filters=n_filters), masked=False, name=next(name_iter), additive_coupling=False)]*n_blocks return nf.sequential_flow(nf.Debug(''), *layers) # To initialize our model, we want a debugger to print out the size of the network at each multiscale debug_kwargs = dict(print_init_shape=True, print_forward_shape=False, print_inverse_shape=False, compare_vals=False) # We want to name the glow blocks so that we can do data dependent initialization name_iter = iter(['glow_%d'%i for i in range(400)]) # The multiscale architecture factors out pixels def multi_scale(i, flow): if(isinstance(self.n_filters, int)): n_filters = self.n_filters else: n_filters = self.n_filters[i] if(isinstance(self.n_blocks, int)): n_blocks = self.n_blocks else: n_blocks = self.n_blocks[i] return nf.sequential_flow(nf.Squeeze(), GLOWComponent(name_iter, n_filters, n_blocks), nf.FactorOut(2), nf.factored_flow(flow, nf.Identity()), nf.FanInConcat(2), nf.UnSqueeze()) flow = nf.Identity() for i in range(self.n_multiscale): flow = multi_scale(i, flow) if(init_key is not None): # Add the ability to ensure that things arae initialized together flow = nf.key_wrap(flow, init_key) return flow def get_prior(self): return nf.UnitGaussianPrior() ##################################################################### def gen_meta_data(self): """ Create a dictionary that will tell us exactly how to create this model """ meta = {'n_filters' : self.n_filters, 'n_blocks' : self.n_blocks, 'n_multiscale' : self.n_multiscale, 'data_init_iterations': self.data_init_iterations, 'model' : 'GLOW'} parent_meta = super().gen_meta_data() parent_meta.update(meta) return parent_meta @classmethod def initialize_from_meta_data(cls, meta): """ Using a meta data, construct an instance of this model """ dataset_name = meta['dataset_name'] x_shape = tuple(meta['x_shape']) n_filters = meta['n_filters'] n_blocks = meta['n_blocks'] n_multiscale = meta['n_multiscale'] data_init_iterations = meta.get('data_init_iterations', 1000) return GLOW(dataset_name, x_shape, n_filters, n_blocks, n_multiscale, data_init_iterations) ##################################################################### def data_dependent_init(self, key, data_loader, batch_size=64): actnorm_names = [name for name in tree_flatten(self.names)[0] if 'act_norm' in name] flow_model = (self.names, self.z_shape, self.params, self.state), self.forward, self.inverse params = nf.multistep_flow_data_dependent_init(None, actnorm_names, flow_model, (), 'actnorm_seed', key, data_loader=data_loader, n_seed_examples=self.data_init_iterations, batch_size=batch_size, notebook=False) self.params = params ###################################################################################################################################################### class SimpleNIF(GLOW): def __init__(self, dataset_name, x_shape, z_dim, n_filters=256, n_blocks=16, n_multiscale=5, data_init_iterations=1000): super().__init__(dataset_name, x_shape, n_filters, n_blocks, n_multiscale, data_init_iterations) self.z_dim = z_dim def get_prior(self): return ndp.AffineGaussianPriorDiagCov(self.z_dim) ##################################################################### def gen_meta_data(self): """ Create a dictionary that will tell us exactly how to create this model """ parent_meta = super().gen_meta_data() meta = {'z_dim': self.z_dim, 'model': 'SimpleNIF'} parent_meta.update(meta) return parent_meta @classmethod def initialize_from_meta_data(cls, meta): """ Using a meta data, construct an instance of this model """ dataset_name = meta['dataset_name'] x_shape = tuple(meta['x_shape']) n_filters = meta['n_filters'] n_blocks = meta['n_blocks'] n_multiscale = meta['n_multiscale'] z_dim = meta['z_dim'] data_init_iterations = meta.get('data_init_iterations', 1000) return SimpleNIF(dataset_name, x_shape, z_dim, n_filters, n_blocks, n_multiscale, data_init_iterations) ###################################################################################################################################################### class NIF(GLOW): def __init__(self, dataset_name, x_shape, z_dim, n_filters=256, n_blocks=16, n_multiscale=5, n_hidden_layers=3, layer_size=1024, n_flat_layers=5, n_importance_samples=16): super().__init__(dataset_name, x_shape, n_filters, n_blocks, n_multiscale) self.z_dim = z_dim self.n_hidden_layers = n_hidden_layers self.layer_size = layer_size self.n_flat_layers = n_flat_layers self.n_importance_samples = n_importance_samples def get_prior(self): an_names = iter(['flat_act_norm_%d'%i for i in range(100)]) def FlatTransform(out_shape): dense_layers = [spp.Dense(self.layer_size), spp.Relu()]*self.n_hidden_layers return spp.sequential(*dense_layers, spp.Dense(out_shape[-1]*2), spp.Split(2, axis=-1), spp.parallel(spp.Tanh(), spp.Identity())) # log_s, t layers = [nf.AffineCoupling(FlatTransform), nf.ActNorm(name=next(an_names)), nf.Reverse()]*self.n_flat_layers prior_flow = nf.sequential_flow(*layers, nf.UnitGaussianPrior()) return ndp.TallAffineDiagCov(prior_flow, self.z_dim, n_training_importance_samples=self.n_importance_samples) ##################################################################### def gen_meta_data(self): """ Create a dictionary that will tell us exactly how to create this model """ parent_meta = super().gen_meta_data() meta = {'z_dim' : self.z_dim, 'n_hidden_layers' : self.n_hidden_layers, 'layer_size' : self.layer_size, 'n_flat_layers' : self.n_flat_layers, 'n_importance_samples': self.n_importance_samples, 'model' : 'NIF'} parent_meta.update(meta) return parent_meta @classmethod def initialize_from_meta_data(cls, meta): """ Using a meta data, construct an instance of this model """ dataset_name = meta['dataset_name'] x_shape = tuple(meta['x_shape']) n_filters = meta['n_filters'] n_blocks = meta['n_blocks'] n_multiscale = meta['n_multiscale'] z_dim = meta['z_dim'] n_hidden_layers = meta['n_hidden_layers'] layer_size = meta['layer_size'] n_flat_layers = meta['n_flat_layers'] n_importance_samples = meta['n_importance_samples'] return NIF(dataset_name, x_shape, z_dim, n_filters, n_blocks, n_multiscale, n_hidden_layers, layer_size, n_flat_layers, n_importance_samples) ###################################################################################################################################################### # Use a global to make loading easy MODEL_LIST = {'GLOW' : GLOW, 'SimpleNIF': SimpleNIF, 'NIF' : NIF}
de
0.650966
###################################################################################################################################################### ##################################################################### # Use uniform dequantization to build our model ##################################################################### ##################################################################### Create a dictionary that will tell us exactly how to create this model ##################################################################### ###################################################################################################################################################### ##################################################################### Build the architecture from GLOW https://arxiv.org/pdf/1807.03039.pdf Transformation used inside affine coupling # log_s, t Compose glow blocks # To initialize our model, we want a debugger to print out the size of the network at each multiscale # We want to name the glow blocks so that we can do data dependent initialization # The multiscale architecture factors out pixels # Add the ability to ensure that things arae initialized together ##################################################################### Create a dictionary that will tell us exactly how to create this model Using a meta data, construct an instance of this model ##################################################################### ###################################################################################################################################################### ##################################################################### Create a dictionary that will tell us exactly how to create this model Using a meta data, construct an instance of this model ###################################################################################################################################################### # log_s, t ##################################################################### Create a dictionary that will tell us exactly how to create this model Using a meta data, construct an instance of this model ###################################################################################################################################################### # Use a global to make loading easy
2.285354
2
Printer.py
dgirzadas/Pulse-of-the-City
2
6623175
def loading_bar(percentage): if percentage < 100: print("[" + "-" * percentage + " " * (100 - percentage) + "] " + str(percentage) + "%", end='\r') else: print("[" + "-" * percentage + " " * (100 - percentage) + "] " + "Done!")
def loading_bar(percentage): if percentage < 100: print("[" + "-" * percentage + " " * (100 - percentage) + "] " + str(percentage) + "%", end='\r') else: print("[" + "-" * percentage + " " * (100 - percentage) + "] " + "Done!")
none
1
3.08356
3
flowgraph/config.py
Bhaskers-Blu-Org1/pyflowgraph
17
6623176
<reponame>Bhaskers-Blu-Org1/pyflowgraph c.RemoteAnnotationDB.api_url = "https://api.datascienceontology.org"
c.RemoteAnnotationDB.api_url = "https://api.datascienceontology.org"
none
1
1.247719
1
bax_insertion/util/error_propagation.py
johnbachman/bax_insertion_paper
0
6623177
<reponame>johnbachman/bax_insertion_paper import numpy as np def calc_ratio_sd(numer_mean, numer_sd, denom_mean, denom_sd, num_samples=10000): """Calculates the variance of a ratio of two normal distributions with the given means and standard deviations.""" numer_samples = numer_mean + (numer_sd * np.random.randn(num_samples)) denom_samples = denom_mean + (denom_sd * np.random.randn(num_samples)) ratio_samples = numer_samples / denom_samples return np.std(ratio_samples) def calc_ratio_mean_sd(numer_mean, numer_sd, denom_mean, denom_sd, num_samples=10000): """Calculates the variance of a ratio of two normal distributions with the given means and standard deviations.""" # If we're dealing with a numpy array: if isinstance(numer_mean, np.ndarray) and \ isinstance(denom_mean, np.ndarray) and \ isinstance(numer_sd, np.ndarray) and \ isinstance(denom_sd, np.ndarray): num_pts = numer_mean.shape[0] numer_samples = numer_mean + (numer_sd * np.random.randn(num_samples, num_pts)) denom_samples = denom_mean + (denom_sd * np.random.randn(num_samples, num_pts)) # Otherwise, assume we're dealing with a number else: numer_samples = numer_mean + (numer_sd * np.random.randn(num_samples)) denom_samples = denom_mean + (denom_sd * np.random.randn(num_samples)) ratio_samples = numer_samples / denom_samples return (np.mean(ratio_samples, axis=0), np.std(ratio_samples, axis=0))
import numpy as np def calc_ratio_sd(numer_mean, numer_sd, denom_mean, denom_sd, num_samples=10000): """Calculates the variance of a ratio of two normal distributions with the given means and standard deviations.""" numer_samples = numer_mean + (numer_sd * np.random.randn(num_samples)) denom_samples = denom_mean + (denom_sd * np.random.randn(num_samples)) ratio_samples = numer_samples / denom_samples return np.std(ratio_samples) def calc_ratio_mean_sd(numer_mean, numer_sd, denom_mean, denom_sd, num_samples=10000): """Calculates the variance of a ratio of two normal distributions with the given means and standard deviations.""" # If we're dealing with a numpy array: if isinstance(numer_mean, np.ndarray) and \ isinstance(denom_mean, np.ndarray) and \ isinstance(numer_sd, np.ndarray) and \ isinstance(denom_sd, np.ndarray): num_pts = numer_mean.shape[0] numer_samples = numer_mean + (numer_sd * np.random.randn(num_samples, num_pts)) denom_samples = denom_mean + (denom_sd * np.random.randn(num_samples, num_pts)) # Otherwise, assume we're dealing with a number else: numer_samples = numer_mean + (numer_sd * np.random.randn(num_samples)) denom_samples = denom_mean + (denom_sd * np.random.randn(num_samples)) ratio_samples = numer_samples / denom_samples return (np.mean(ratio_samples, axis=0), np.std(ratio_samples, axis=0))
en
0.885717
Calculates the variance of a ratio of two normal distributions with the given means and standard deviations. Calculates the variance of a ratio of two normal distributions with the given means and standard deviations. # If we're dealing with a numpy array: # Otherwise, assume we're dealing with a number
3.641943
4
selenium/spider.py
andrewsmedina/scrap-tools-benchmarking
2
6623178
from selenium import webdriver driver = webdriver.Firefox() journal_url = "http://www.rondonopolis.mt.gov.br/diario-oficial/" driver.get(journal_url) pdf_links = driver.find_elements_by_css_selector("table a") for link in pdf_links: print(link.get_attribute("href")) driver.close()
from selenium import webdriver driver = webdriver.Firefox() journal_url = "http://www.rondonopolis.mt.gov.br/diario-oficial/" driver.get(journal_url) pdf_links = driver.find_elements_by_css_selector("table a") for link in pdf_links: print(link.get_attribute("href")) driver.close()
none
1
2.794113
3
train_arguments.py
kun193/ransomware-classification
7
6623179
import argparse import os class Arguments(): def __init__(self): self.initialized = False def initialize(self, parser): parser.add_argument('name', type=str, help='experiment name.') parser.add_argument('--phase', default='train', type=str, choices=['train', 'test'], help='determining whether the model is being trained or used for inference. Since this is the train_arguments file, this needs to set to train!!') parser.add_argument('--data_root', default='../../Data/ransom_ware/train', type=str, help='path to the training data directory.') parser.add_argument('--num_classes', default=50, type=int, help='number of classes in the classification task.') parser.add_argument('--batch_size', default=32, type=int) parser.add_argument('--num_steps', default=24000, type=int, help='number of steps for which the model is trained.') parser.add_argument('--break_count', default=600, type=int, help='how many steps to before training is stopped when the loss value does not change.') parser.add_argument('--arch', type=str, default='AmirNet', help='which architecture is used to create the classifier', choices=['inception', 'resnet34', 'resnet50', 'resnet101', 'resnext50', 'resnext101', 'densenet161', 'densenet169', 'densenet201', 'vgg16_bn', 'vgg19_bn', 'squeezenet', 'shufflenet', 'mobilenet', 'AmirNet', 'AmirNet_DO', 'AmirNet_CDO', 'AmirNet_VDO']) parser.add_argument('--augs', nargs='+', help='which augmentations are used to help in the training process', choices=['rotate', 'vflip', 'hflip', 'contrast', 'brightness', 'noise', 'occlusion', 'regularblur', 'defocusblur', 'motionblur', 'perspective', 'gray', 'colorjitter']) parser.add_argument('--input_size', type=int, default=128, help='size of the input image.') parser.add_argument('--pretrained', action='store_true', help='the model is initialized with weights pre-trained on imagenet.') parser.add_argument('--num_workers', default=2, type=int, help='number of workers used in the dataloader.') parser.add_argument('--lr', type=float, default=5e-4, help='learning rate.') parser.add_argument('--weight_decay', type=float, default=1e-5, help='weight decay.') parser.add_argument('--resume', action='store_true', help='resume from a checkpoint') parser.add_argument('--which_checkpoint', type=str, default='latest', help='the checkpoint to be loaded to resume training. Checkpoints are identified and saved by the number of steps passed during training.') parser.add_argument('--checkpoints_dir', type=str, default='checkpoints', help='the path to where the model is saved.') parser.add_argument('--print_freq', default=50, type=int, help='how many steps before printing the loss values to the standard output for inspection purposes only.') parser.add_argument('--display', action='store_true', help='display the results periodically via visdom') parser.add_argument('--display_winsize', type=int, default=256, help='display window size for visdom.') parser.add_argument('--display_freq', type=int, default=50, help='frequency of showing training results on screen using visdom.') parser.add_argument('--display_ncols', type=int, default=0, help='if positive, display all images in a single visdom web panel with certain number of images per row.') parser.add_argument('--display_id', type=int, default=1, help='window id of the web display.') parser.add_argument('--display_server', type=str, default="http://localhost", help='visdom server of the web display.') parser.add_argument('--display_env', type=str, default='main', help='visdom display environment name (default is "main").') parser.add_argument('--display_port', type=int, default=8097, help='visdom port of the web display.') parser.add_argument('--save_checkpoint_freq', default=5000, type=int, help='how many steps before saving one sequence of images to disk for inspection purposes only.') self.initialized = True return parser def get_args(self): if not self.initialized: parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser = self.initialize(parser) self.parser = parser return parser.parse_args() def print_args(self, args): txt = '\n' txt += '-------------------- Arguments --------------------\n' for k, v in sorted(vars(args).items()): comment = '' default = self.parser.get_default(k) if v != default: comment = '\t[default: %s]' % str(default) txt += '{:>25}: {:<30}{}\n'.format(str(k), str(v), comment) txt += '----------------------- End -----------------------' txt += '\n' print(txt) def parse(self): args = self.get_args() self.print_args(args) self.args = args return self.args
import argparse import os class Arguments(): def __init__(self): self.initialized = False def initialize(self, parser): parser.add_argument('name', type=str, help='experiment name.') parser.add_argument('--phase', default='train', type=str, choices=['train', 'test'], help='determining whether the model is being trained or used for inference. Since this is the train_arguments file, this needs to set to train!!') parser.add_argument('--data_root', default='../../Data/ransom_ware/train', type=str, help='path to the training data directory.') parser.add_argument('--num_classes', default=50, type=int, help='number of classes in the classification task.') parser.add_argument('--batch_size', default=32, type=int) parser.add_argument('--num_steps', default=24000, type=int, help='number of steps for which the model is trained.') parser.add_argument('--break_count', default=600, type=int, help='how many steps to before training is stopped when the loss value does not change.') parser.add_argument('--arch', type=str, default='AmirNet', help='which architecture is used to create the classifier', choices=['inception', 'resnet34', 'resnet50', 'resnet101', 'resnext50', 'resnext101', 'densenet161', 'densenet169', 'densenet201', 'vgg16_bn', 'vgg19_bn', 'squeezenet', 'shufflenet', 'mobilenet', 'AmirNet', 'AmirNet_DO', 'AmirNet_CDO', 'AmirNet_VDO']) parser.add_argument('--augs', nargs='+', help='which augmentations are used to help in the training process', choices=['rotate', 'vflip', 'hflip', 'contrast', 'brightness', 'noise', 'occlusion', 'regularblur', 'defocusblur', 'motionblur', 'perspective', 'gray', 'colorjitter']) parser.add_argument('--input_size', type=int, default=128, help='size of the input image.') parser.add_argument('--pretrained', action='store_true', help='the model is initialized with weights pre-trained on imagenet.') parser.add_argument('--num_workers', default=2, type=int, help='number of workers used in the dataloader.') parser.add_argument('--lr', type=float, default=5e-4, help='learning rate.') parser.add_argument('--weight_decay', type=float, default=1e-5, help='weight decay.') parser.add_argument('--resume', action='store_true', help='resume from a checkpoint') parser.add_argument('--which_checkpoint', type=str, default='latest', help='the checkpoint to be loaded to resume training. Checkpoints are identified and saved by the number of steps passed during training.') parser.add_argument('--checkpoints_dir', type=str, default='checkpoints', help='the path to where the model is saved.') parser.add_argument('--print_freq', default=50, type=int, help='how many steps before printing the loss values to the standard output for inspection purposes only.') parser.add_argument('--display', action='store_true', help='display the results periodically via visdom') parser.add_argument('--display_winsize', type=int, default=256, help='display window size for visdom.') parser.add_argument('--display_freq', type=int, default=50, help='frequency of showing training results on screen using visdom.') parser.add_argument('--display_ncols', type=int, default=0, help='if positive, display all images in a single visdom web panel with certain number of images per row.') parser.add_argument('--display_id', type=int, default=1, help='window id of the web display.') parser.add_argument('--display_server', type=str, default="http://localhost", help='visdom server of the web display.') parser.add_argument('--display_env', type=str, default='main', help='visdom display environment name (default is "main").') parser.add_argument('--display_port', type=int, default=8097, help='visdom port of the web display.') parser.add_argument('--save_checkpoint_freq', default=5000, type=int, help='how many steps before saving one sequence of images to disk for inspection purposes only.') self.initialized = True return parser def get_args(self): if not self.initialized: parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser = self.initialize(parser) self.parser = parser return parser.parse_args() def print_args(self, args): txt = '\n' txt += '-------------------- Arguments --------------------\n' for k, v in sorted(vars(args).items()): comment = '' default = self.parser.get_default(k) if v != default: comment = '\t[default: %s]' % str(default) txt += '{:>25}: {:<30}{}\n'.format(str(k), str(v), comment) txt += '----------------------- End -----------------------' txt += '\n' print(txt) def parse(self): args = self.get_args() self.print_args(args) self.args = args return self.args
none
1
2.903597
3
foundation/press/views.py
pilnujemy/foundation-manager
1
6623180
from braces.views import SelectRelatedMixin from django.views.generic.dates import ArchiveIndexView from django.views.generic.dates import YearArchiveView from django.views.generic.dates import MonthArchiveView from django.views.generic.dates import DayArchiveView from django.views.generic import DetailView from django.shortcuts import get_object_or_404 from .models import Post, Tag class PostArchiveMixin(SelectRelatedMixin): model = Post date_field = "published" select_related = ['user', ] make_object_list = True month_format = '%m' paginate_by = 25 def get_context_data(self, **kwargs): context = super(PostArchiveMixin, self).get_context_data(**kwargs) context['month_list'] = self.model.objects.datetimes('published', 'month') return context class PostArchiveIndexView(PostArchiveMixin, ArchiveIndexView): pass class PostTagIndexView(PostArchiveMixin, ArchiveIndexView): template_name_suffix = '_archive_tag' def get_queryset(self, *args, **kwargs): self.tag = get_object_or_404(Tag, slug=self.kwargs['slug']) qs = super(PostTagIndexView, self).get_queryset(*args, **kwargs) return qs.filter(tags=self.tag) def get_context_data(self, *args, **kwargs): context = super(PostTagIndexView, self).get_context_data(*args, **kwargs) context['tag'] = self.tag return context class PostYearArchiveView(PostArchiveMixin, YearArchiveView): pass class PostMonthArchiveView(PostArchiveMixin, MonthArchiveView): pass class PostDayArchiveView(PostArchiveMixin, DayArchiveView): pass class PostDetailView(PostArchiveMixin, DetailView): def get_queryset(self, *args, **kwargs): qs = super(PostDetailView, self).get_queryset(*args, **kwargs) return qs.published()
from braces.views import SelectRelatedMixin from django.views.generic.dates import ArchiveIndexView from django.views.generic.dates import YearArchiveView from django.views.generic.dates import MonthArchiveView from django.views.generic.dates import DayArchiveView from django.views.generic import DetailView from django.shortcuts import get_object_or_404 from .models import Post, Tag class PostArchiveMixin(SelectRelatedMixin): model = Post date_field = "published" select_related = ['user', ] make_object_list = True month_format = '%m' paginate_by = 25 def get_context_data(self, **kwargs): context = super(PostArchiveMixin, self).get_context_data(**kwargs) context['month_list'] = self.model.objects.datetimes('published', 'month') return context class PostArchiveIndexView(PostArchiveMixin, ArchiveIndexView): pass class PostTagIndexView(PostArchiveMixin, ArchiveIndexView): template_name_suffix = '_archive_tag' def get_queryset(self, *args, **kwargs): self.tag = get_object_or_404(Tag, slug=self.kwargs['slug']) qs = super(PostTagIndexView, self).get_queryset(*args, **kwargs) return qs.filter(tags=self.tag) def get_context_data(self, *args, **kwargs): context = super(PostTagIndexView, self).get_context_data(*args, **kwargs) context['tag'] = self.tag return context class PostYearArchiveView(PostArchiveMixin, YearArchiveView): pass class PostMonthArchiveView(PostArchiveMixin, MonthArchiveView): pass class PostDayArchiveView(PostArchiveMixin, DayArchiveView): pass class PostDetailView(PostArchiveMixin, DetailView): def get_queryset(self, *args, **kwargs): qs = super(PostDetailView, self).get_queryset(*args, **kwargs) return qs.published()
none
1
2.020676
2
server.py
keithnull/ace-power
4
6623181
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware import entry app = FastAPI() origins = [ "http://localhost:8080", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.get("/search/{author_name}") def read_author(author_name: str): return entry.query(author_name)
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware import entry app = FastAPI() origins = [ "http://localhost:8080", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.get("/search/{author_name}") def read_author(author_name: str): return entry.query(author_name)
none
1
2.542464
3
django/bosscore/lookup.py
ArnaudGallardo/boss
20
6623182
<gh_stars>10-100 # Copyright 2016 The Johns Hopkins University Applied Physics Laboratory # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from .serializers import BossLookupSerializer from .models import BossLookup from .error import BossError, ErrorCodes class LookUpKey: """ Bosskey manager """ @staticmethod def add_lookup(lookup_key, boss_key, collection_name, experiment_name=None, channel_name=None): """ Add the lookup key that correspond to a data model object Args: lookup_key: Lookup key for the object that was created boss_key: Bosskey for the objec that we created collection_name: Collection name . Matches the collection in the bosskey experiment_name: Experiment name . Matches the experiment in the bosskey channel_name: Channel name . Matches the channel in the bosskey Returns: None """ # Create the boss lookup key lookup_data = {'lookup_key': lookup_key, 'boss_key': boss_key, 'collection_name': collection_name, 'experiment_name': experiment_name, 'channel_name': channel_name } serializer = BossLookupSerializer(data=lookup_data) if serializer.is_valid(): serializer.save() @staticmethod def get_lookup_key(bkey): """ Get the lookup keys for a request Args: bkey: Bosskey that corresponds to a request Returns: Lookup key """ lookup_obj = BossLookup.objects.get(boss_key=bkey) return lookup_obj @staticmethod def delete_lookup_key(collection, experiment=None, channel=None): """ Delete a lookupkey for a specific bosskey Args: collection: Collection Name experiment : Experiment Name channel : Channel name Returns: None """ try: if channel and experiment and collection: lookup_obj = BossLookup.objects.get(collection_name=collection, experiment_name=experiment, channel_name=channel) lookup_obj.delete() elif experiment and collection: lookup_obj = BossLookup.objects.get(collection_name=collection, experiment_name=experiment) lookup_obj.delete() elif collection: lookup_obj = BossLookup.objects.get(collection_name=collection) lookup_obj.delete() else: raise BossError(404, "Cannot delete lookupkey", 30000) except BossLookup.DoesNotExist: raise BossError(404, "Cannot find a lookup key for bosskey", 30000) @staticmethod def update_lookup(lookup_key, boss_key, collection_name, experiment_name=None, channel_name=None): """ Update the fields that correspond to a lookupkey Args: lookup_key: Lookup key for the object that was created boss_key: Bosskey for the objec that we created collection_name: Collection name . Matches the collection in the bosskey experiment_name: Experiment name . Matches the experiment in the bosskey channel_name: Channel name . Matches the channel in the bosskey Returns: None """ # Create the boss lookup key lookup_data = {'lookup_key': lookup_key, 'boss_key': boss_key, 'collection_name': collection_name, 'experiment_name': experiment_name, 'channel_name': channel_name } lookup_obj = BossLookup.objects.get(lookup_key=lookup_key) serializer = BossLookupSerializer(lookup_obj, data=lookup_data, partial=True) if serializer.is_valid(): serializer.save() @staticmethod def update_lookup_collection(lookup_key, boss_key, collection_name): """ Update the fields that correspond to a lookupkey Args: lookup_key: Lookup key for the object that was created boss_key: Bosskey for the objec that we created collection_name: Collection name . Matches the collection in the bosskey Returns: None """ try: # Create the boss lookup key lookup_data = {'lookup_key': lookup_key, 'boss_key': boss_key, 'collection_name': collection_name, } lookup_obj = BossLookup.objects.get(lookup_key=lookup_key) old_collection_name = lookup_obj.collection_name serializer = BossLookupSerializer(lookup_obj, data=lookup_data, partial=True) if serializer.is_valid(): serializer.save() else: raise BossError("{}. Error updating the collection name in the lookup key" .format(serializer.errors), ErrorCodes.INVALID_POST_ARGUMENT) # update all object that reference this collection all_lookup_objs = BossLookup.objects.filter(collection_name=old_collection_name)\ .exclude(lookup_key=lookup_key) for item in all_lookup_objs: split_key = item.boss_key.split('&') split_key[0] = collection_name boss_key = '&'.join(split_key) lookup_data = {'lookup_key': item.lookup_key, 'boss_key': boss_key, 'collection_name': collection_name } serializer = BossLookupSerializer(item, data=lookup_data, partial=True) if serializer.is_valid(): serializer.save() else: raise BossError("{}. Error updating the collection name in the lookup key". format(serializer.errors), ErrorCodes.INVALID_POST_ARGUMENT) except BossLookup.DoesNotExist: raise BossError("Cannot update the lookup key", ErrorCodes.UNABLE_TO_VALIDATE) @staticmethod def update_lookup_experiment(lookup_key, boss_key, collection_name, experiment_name): """ Update the fields that correspond to a lookupkey Args: lookup_key: Lookup key for the object that was created boss_key: Bosskey for the objec that we created collection_name: Collection name . Matches the collection in the bosskey experiment_name: Collection name . Matches the collection in the bosskey Returns: None """ try: # Create the boss lookup key lookup_data = {'lookup_key': lookup_key, 'boss_key': boss_key, 'collection_name': collection_name, 'experiment_name': experiment_name, } lookup_obj = BossLookup.objects.get(lookup_key=lookup_key) old_experiment_name = lookup_obj.experiment_name serializer = BossLookupSerializer(lookup_obj, data=lookup_data, partial=True) if serializer.is_valid(): serializer.save() else: raise BossError("{}. Error updating the collection name in the lookup key".format(serializer.errors), ErrorCodes.INVALID_POST_ARGUMENT) # update all channels that reference this experiment all_lookup_objs = BossLookup.objects.filter( collection_name=collection_name, experiment_name=old_experiment_name).exclude( lookup_key=lookup_key) for item in all_lookup_objs: split_key = item.boss_key.split('&') split_key[1] = experiment_name boss_key = '&'.join(split_key) #boss_key = re.sub(old_experiment_name, experiment_name, item.boss_key) lookup_data = {'lookup_key': item.lookup_key, 'boss_key': boss_key, 'experiment_name': experiment_name } serializer = BossLookupSerializer(item, data=lookup_data, partial=True) if serializer.is_valid(): serializer.save() else: raise BossError("{}. Error updating the collection name in the lookup key". format(serializer.errors), ErrorCodes.INVALID_POST_ARGUMENT) except BossLookup.DoesNotExist: raise BossError("Cannot update the lookup key", ErrorCodes.UNABLE_TO_VALIDATE)
# Copyright 2016 The Johns Hopkins University Applied Physics Laboratory # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from .serializers import BossLookupSerializer from .models import BossLookup from .error import BossError, ErrorCodes class LookUpKey: """ Bosskey manager """ @staticmethod def add_lookup(lookup_key, boss_key, collection_name, experiment_name=None, channel_name=None): """ Add the lookup key that correspond to a data model object Args: lookup_key: Lookup key for the object that was created boss_key: Bosskey for the objec that we created collection_name: Collection name . Matches the collection in the bosskey experiment_name: Experiment name . Matches the experiment in the bosskey channel_name: Channel name . Matches the channel in the bosskey Returns: None """ # Create the boss lookup key lookup_data = {'lookup_key': lookup_key, 'boss_key': boss_key, 'collection_name': collection_name, 'experiment_name': experiment_name, 'channel_name': channel_name } serializer = BossLookupSerializer(data=lookup_data) if serializer.is_valid(): serializer.save() @staticmethod def get_lookup_key(bkey): """ Get the lookup keys for a request Args: bkey: Bosskey that corresponds to a request Returns: Lookup key """ lookup_obj = BossLookup.objects.get(boss_key=bkey) return lookup_obj @staticmethod def delete_lookup_key(collection, experiment=None, channel=None): """ Delete a lookupkey for a specific bosskey Args: collection: Collection Name experiment : Experiment Name channel : Channel name Returns: None """ try: if channel and experiment and collection: lookup_obj = BossLookup.objects.get(collection_name=collection, experiment_name=experiment, channel_name=channel) lookup_obj.delete() elif experiment and collection: lookup_obj = BossLookup.objects.get(collection_name=collection, experiment_name=experiment) lookup_obj.delete() elif collection: lookup_obj = BossLookup.objects.get(collection_name=collection) lookup_obj.delete() else: raise BossError(404, "Cannot delete lookupkey", 30000) except BossLookup.DoesNotExist: raise BossError(404, "Cannot find a lookup key for bosskey", 30000) @staticmethod def update_lookup(lookup_key, boss_key, collection_name, experiment_name=None, channel_name=None): """ Update the fields that correspond to a lookupkey Args: lookup_key: Lookup key for the object that was created boss_key: Bosskey for the objec that we created collection_name: Collection name . Matches the collection in the bosskey experiment_name: Experiment name . Matches the experiment in the bosskey channel_name: Channel name . Matches the channel in the bosskey Returns: None """ # Create the boss lookup key lookup_data = {'lookup_key': lookup_key, 'boss_key': boss_key, 'collection_name': collection_name, 'experiment_name': experiment_name, 'channel_name': channel_name } lookup_obj = BossLookup.objects.get(lookup_key=lookup_key) serializer = BossLookupSerializer(lookup_obj, data=lookup_data, partial=True) if serializer.is_valid(): serializer.save() @staticmethod def update_lookup_collection(lookup_key, boss_key, collection_name): """ Update the fields that correspond to a lookupkey Args: lookup_key: Lookup key for the object that was created boss_key: Bosskey for the objec that we created collection_name: Collection name . Matches the collection in the bosskey Returns: None """ try: # Create the boss lookup key lookup_data = {'lookup_key': lookup_key, 'boss_key': boss_key, 'collection_name': collection_name, } lookup_obj = BossLookup.objects.get(lookup_key=lookup_key) old_collection_name = lookup_obj.collection_name serializer = BossLookupSerializer(lookup_obj, data=lookup_data, partial=True) if serializer.is_valid(): serializer.save() else: raise BossError("{}. Error updating the collection name in the lookup key" .format(serializer.errors), ErrorCodes.INVALID_POST_ARGUMENT) # update all object that reference this collection all_lookup_objs = BossLookup.objects.filter(collection_name=old_collection_name)\ .exclude(lookup_key=lookup_key) for item in all_lookup_objs: split_key = item.boss_key.split('&') split_key[0] = collection_name boss_key = '&'.join(split_key) lookup_data = {'lookup_key': item.lookup_key, 'boss_key': boss_key, 'collection_name': collection_name } serializer = BossLookupSerializer(item, data=lookup_data, partial=True) if serializer.is_valid(): serializer.save() else: raise BossError("{}. Error updating the collection name in the lookup key". format(serializer.errors), ErrorCodes.INVALID_POST_ARGUMENT) except BossLookup.DoesNotExist: raise BossError("Cannot update the lookup key", ErrorCodes.UNABLE_TO_VALIDATE) @staticmethod def update_lookup_experiment(lookup_key, boss_key, collection_name, experiment_name): """ Update the fields that correspond to a lookupkey Args: lookup_key: Lookup key for the object that was created boss_key: Bosskey for the objec that we created collection_name: Collection name . Matches the collection in the bosskey experiment_name: Collection name . Matches the collection in the bosskey Returns: None """ try: # Create the boss lookup key lookup_data = {'lookup_key': lookup_key, 'boss_key': boss_key, 'collection_name': collection_name, 'experiment_name': experiment_name, } lookup_obj = BossLookup.objects.get(lookup_key=lookup_key) old_experiment_name = lookup_obj.experiment_name serializer = BossLookupSerializer(lookup_obj, data=lookup_data, partial=True) if serializer.is_valid(): serializer.save() else: raise BossError("{}. Error updating the collection name in the lookup key".format(serializer.errors), ErrorCodes.INVALID_POST_ARGUMENT) # update all channels that reference this experiment all_lookup_objs = BossLookup.objects.filter( collection_name=collection_name, experiment_name=old_experiment_name).exclude( lookup_key=lookup_key) for item in all_lookup_objs: split_key = item.boss_key.split('&') split_key[1] = experiment_name boss_key = '&'.join(split_key) #boss_key = re.sub(old_experiment_name, experiment_name, item.boss_key) lookup_data = {'lookup_key': item.lookup_key, 'boss_key': boss_key, 'experiment_name': experiment_name } serializer = BossLookupSerializer(item, data=lookup_data, partial=True) if serializer.is_valid(): serializer.save() else: raise BossError("{}. Error updating the collection name in the lookup key". format(serializer.errors), ErrorCodes.INVALID_POST_ARGUMENT) except BossLookup.DoesNotExist: raise BossError("Cannot update the lookup key", ErrorCodes.UNABLE_TO_VALIDATE)
en
0.793337
# Copyright 2016 The Johns Hopkins University Applied Physics Laboratory # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. Bosskey manager Add the lookup key that correspond to a data model object Args: lookup_key: Lookup key for the object that was created boss_key: Bosskey for the objec that we created collection_name: Collection name . Matches the collection in the bosskey experiment_name: Experiment name . Matches the experiment in the bosskey channel_name: Channel name . Matches the channel in the bosskey Returns: None # Create the boss lookup key Get the lookup keys for a request Args: bkey: Bosskey that corresponds to a request Returns: Lookup key Delete a lookupkey for a specific bosskey Args: collection: Collection Name experiment : Experiment Name channel : Channel name Returns: None Update the fields that correspond to a lookupkey Args: lookup_key: Lookup key for the object that was created boss_key: Bosskey for the objec that we created collection_name: Collection name . Matches the collection in the bosskey experiment_name: Experiment name . Matches the experiment in the bosskey channel_name: Channel name . Matches the channel in the bosskey Returns: None # Create the boss lookup key Update the fields that correspond to a lookupkey Args: lookup_key: Lookup key for the object that was created boss_key: Bosskey for the objec that we created collection_name: Collection name . Matches the collection in the bosskey Returns: None # Create the boss lookup key # update all object that reference this collection Update the fields that correspond to a lookupkey Args: lookup_key: Lookup key for the object that was created boss_key: Bosskey for the objec that we created collection_name: Collection name . Matches the collection in the bosskey experiment_name: Collection name . Matches the collection in the bosskey Returns: None # Create the boss lookup key # update all channels that reference this experiment #boss_key = re.sub(old_experiment_name, experiment_name, item.boss_key)
2.278519
2
process/honda-label/ProjectGPSonVideo.py
sameeptandon/sail-car-log
1
6623183
import pickle import sys, os from GPSReader import * from VideoReader import * from WGS84toENU import * from GPSReprojection import * from transformations import euler_matrix from numpy import array, dot, zeros, around, divide, nonzero, float32, maximum import numpy as np from cv2 import imshow, waitKey, resize, warpPerspective, getPerspectiveTransform, transpose, Canny, namedWindow import cv import cv2 import time from generate_lane_labels import * def on_mouse(event, x, y, flags, params): if event == cv.CV_EVENT_LBUTTONDOWN: print 'click: ', (x,y) print 'color: ', I[y,x,:] if __name__ == '__main__': video_filename = sys.argv[1] path, vfname = os.path.split(video_filename) vidname = vfname.split('.')[0] cam_num = int(vidname[-1]) gps_filename = path + '/' + vidname[0:-1] + '_gps.out' #gps_filename = sys.argv[2] cv2.namedWindow('video') cv.SetMouseCallback('video', on_mouse, 0) num_imgs_fwd = 200; video_reader = VideoReader(video_filename) gps_reader = GPSReader(gps_filename) gps_dat = gps_reader.getNumericData() cam = pickle.load(open('cam_params.pickle'))[cam_num - 1] #framenum = 1926; #framenum = 29000 framenum = 0 lastTime = time.time() lastCols = [None, None] lastLine = [None, None, None, None] video_reader.setFrame(framenum) while True: framenum = framenum + 1; (success, I) = video_reader.getNextFrame() if success == False: break #if framenum % 10 != 0: # continue if framenum % 100 == 0: print framenum M = GPSMask(gps_dat[framenum:framenum+num_imgs_fwd,:], cam, width=1); I = np.minimum(M,I) """ src = array([[0,0],[1280,0],[1280,960],[0,960]], float32) minX = 0 minY = 0 maxX = 1200 maxY = 960 dst = array([[-1000,200],[2280,200],[780,960],[500,960]], float32) #src = array([(567, 759), (896, 756), (919, 791), (555, 793)], float32) src = array([(570, 737), (864, 737), (881, 761), (564, 761)], float32) #src = array([(520, 727), (916, 733), (950, 775), (497, 771)], float32) #src = array([[499,597],[972,597],[1112,661],[448,678]], float32) #good one #src = array([[528,560],[861,557],[1244,759],[271,773]], float32) #src = array([[550,524],[840,523],[1019,613],[496,612]], float32) ##src = array([(378, 604), (742, 601), (967, 802), (79, 784)], float32) ##src = array( [(445, 521), (729, 527), (1159, 819), (27, 747)], float32) ##src = array([(386, 521), (829, 517), (1190, 681), (92, 663)], float32) rx = 38 ry = 24 sx = 150 sy = 100 dst = array([[sx,sy],[sx+rx,sy],[sx+rx,sy+ry],[sx,sy+ry]],float32) #dst = array([[320,320],[960,320],[960,640],[320,640]], float32) #dst[:,0] += 960 imsize = (320,240) I = resize(I, imsize) I[:, :5] = [255, 0, 0] I[:, -5:] = [255, 0, 0] I[-5:, :] = [0, 255, 0] src = src / 4; dst = dst ; #dst = array([[0,0],[1280,0],[1280,960],[0,960]], float32) P = getPerspectiveTransform(src,dst) WARP = warpPerspective(I, P, imsize); #WARP = resize(WARP, imsize) #I[0:480,:,:]=0 I = WARP if lastCols[0] is None: M = 255 - resize(M, imsize) warped_M = np.nonzero(warpPerspective(M, P, imsize)) col_avg = np.mean(warped_M[1]) lastCols[0] = col_avg - 50 lastCols[1] = col_avg + 50 if lastLine[0] is None: lastLine[0] = 0 lastLine[1] = lastCols[0] lastLine[2] = 0 lastLine[3] = lastCols[1] (WARP, lastCols, lastLine) = findLanes(WARP, (imsize[1], imsize[0]), lastCols, lastLine) WARP = warpPerspective(WARP, P, imsize,flags=cv.CV_WARP_INVERSE_MAP); I_t = np.zeros((imsize[1], imsize[0], 3)) I_t[239/2, :, 0] = 255 I_t = warpPerspective(I_t, P, imsize, flags=cv.CV_WARP_INVERSE_MAP) I[WARP[:,:,0] > 0, 0] = 0 I[WARP[:,:,0] > 0, 1] = 0 I[WARP[:,:,0] > 0, 2] = 255 #I[I_t[:, :, 0] > 0, 0] = 255 #I[I_t[:, :, 0] > 0, 1] = 0 #I[I_t[:, :, 0] > 0, 2] = 0 if lastCols[0] is not None and lastCols[1] is not None: I[:,lastCols[0],:] = 0 I[:,lastCols[1],:] = 0 I[:,(lastCols[0]+lastCols[1])/2,:] = 0 """ #I = warpPerspective(I, P, imsize, flags=cv.CV_WARP_INVERSE_MAP) I = resize(I, (640, 480)) imshow('video', I ) key = (waitKey(2) & 255) if key == ord('q'): break; currentTime = time.time(); if (currentTime - lastTime > 1): lastTime = currentTime
import pickle import sys, os from GPSReader import * from VideoReader import * from WGS84toENU import * from GPSReprojection import * from transformations import euler_matrix from numpy import array, dot, zeros, around, divide, nonzero, float32, maximum import numpy as np from cv2 import imshow, waitKey, resize, warpPerspective, getPerspectiveTransform, transpose, Canny, namedWindow import cv import cv2 import time from generate_lane_labels import * def on_mouse(event, x, y, flags, params): if event == cv.CV_EVENT_LBUTTONDOWN: print 'click: ', (x,y) print 'color: ', I[y,x,:] if __name__ == '__main__': video_filename = sys.argv[1] path, vfname = os.path.split(video_filename) vidname = vfname.split('.')[0] cam_num = int(vidname[-1]) gps_filename = path + '/' + vidname[0:-1] + '_gps.out' #gps_filename = sys.argv[2] cv2.namedWindow('video') cv.SetMouseCallback('video', on_mouse, 0) num_imgs_fwd = 200; video_reader = VideoReader(video_filename) gps_reader = GPSReader(gps_filename) gps_dat = gps_reader.getNumericData() cam = pickle.load(open('cam_params.pickle'))[cam_num - 1] #framenum = 1926; #framenum = 29000 framenum = 0 lastTime = time.time() lastCols = [None, None] lastLine = [None, None, None, None] video_reader.setFrame(framenum) while True: framenum = framenum + 1; (success, I) = video_reader.getNextFrame() if success == False: break #if framenum % 10 != 0: # continue if framenum % 100 == 0: print framenum M = GPSMask(gps_dat[framenum:framenum+num_imgs_fwd,:], cam, width=1); I = np.minimum(M,I) """ src = array([[0,0],[1280,0],[1280,960],[0,960]], float32) minX = 0 minY = 0 maxX = 1200 maxY = 960 dst = array([[-1000,200],[2280,200],[780,960],[500,960]], float32) #src = array([(567, 759), (896, 756), (919, 791), (555, 793)], float32) src = array([(570, 737), (864, 737), (881, 761), (564, 761)], float32) #src = array([(520, 727), (916, 733), (950, 775), (497, 771)], float32) #src = array([[499,597],[972,597],[1112,661],[448,678]], float32) #good one #src = array([[528,560],[861,557],[1244,759],[271,773]], float32) #src = array([[550,524],[840,523],[1019,613],[496,612]], float32) ##src = array([(378, 604), (742, 601), (967, 802), (79, 784)], float32) ##src = array( [(445, 521), (729, 527), (1159, 819), (27, 747)], float32) ##src = array([(386, 521), (829, 517), (1190, 681), (92, 663)], float32) rx = 38 ry = 24 sx = 150 sy = 100 dst = array([[sx,sy],[sx+rx,sy],[sx+rx,sy+ry],[sx,sy+ry]],float32) #dst = array([[320,320],[960,320],[960,640],[320,640]], float32) #dst[:,0] += 960 imsize = (320,240) I = resize(I, imsize) I[:, :5] = [255, 0, 0] I[:, -5:] = [255, 0, 0] I[-5:, :] = [0, 255, 0] src = src / 4; dst = dst ; #dst = array([[0,0],[1280,0],[1280,960],[0,960]], float32) P = getPerspectiveTransform(src,dst) WARP = warpPerspective(I, P, imsize); #WARP = resize(WARP, imsize) #I[0:480,:,:]=0 I = WARP if lastCols[0] is None: M = 255 - resize(M, imsize) warped_M = np.nonzero(warpPerspective(M, P, imsize)) col_avg = np.mean(warped_M[1]) lastCols[0] = col_avg - 50 lastCols[1] = col_avg + 50 if lastLine[0] is None: lastLine[0] = 0 lastLine[1] = lastCols[0] lastLine[2] = 0 lastLine[3] = lastCols[1] (WARP, lastCols, lastLine) = findLanes(WARP, (imsize[1], imsize[0]), lastCols, lastLine) WARP = warpPerspective(WARP, P, imsize,flags=cv.CV_WARP_INVERSE_MAP); I_t = np.zeros((imsize[1], imsize[0], 3)) I_t[239/2, :, 0] = 255 I_t = warpPerspective(I_t, P, imsize, flags=cv.CV_WARP_INVERSE_MAP) I[WARP[:,:,0] > 0, 0] = 0 I[WARP[:,:,0] > 0, 1] = 0 I[WARP[:,:,0] > 0, 2] = 255 #I[I_t[:, :, 0] > 0, 0] = 255 #I[I_t[:, :, 0] > 0, 1] = 0 #I[I_t[:, :, 0] > 0, 2] = 0 if lastCols[0] is not None and lastCols[1] is not None: I[:,lastCols[0],:] = 0 I[:,lastCols[1],:] = 0 I[:,(lastCols[0]+lastCols[1])/2,:] = 0 """ #I = warpPerspective(I, P, imsize, flags=cv.CV_WARP_INVERSE_MAP) I = resize(I, (640, 480)) imshow('video', I ) key = (waitKey(2) & 255) if key == ord('q'): break; currentTime = time.time(); if (currentTime - lastTime > 1): lastTime = currentTime
en
0.404959
#gps_filename = sys.argv[2] #framenum = 1926; #framenum = 29000 #if framenum % 10 != 0: # continue src = array([[0,0],[1280,0],[1280,960],[0,960]], float32) minX = 0 minY = 0 maxX = 1200 maxY = 960 dst = array([[-1000,200],[2280,200],[780,960],[500,960]], float32) #src = array([(567, 759), (896, 756), (919, 791), (555, 793)], float32) src = array([(570, 737), (864, 737), (881, 761), (564, 761)], float32) #src = array([(520, 727), (916, 733), (950, 775), (497, 771)], float32) #src = array([[499,597],[972,597],[1112,661],[448,678]], float32) #good one #src = array([[528,560],[861,557],[1244,759],[271,773]], float32) #src = array([[550,524],[840,523],[1019,613],[496,612]], float32) ##src = array([(378, 604), (742, 601), (967, 802), (79, 784)], float32) ##src = array( [(445, 521), (729, 527), (1159, 819), (27, 747)], float32) ##src = array([(386, 521), (829, 517), (1190, 681), (92, 663)], float32) rx = 38 ry = 24 sx = 150 sy = 100 dst = array([[sx,sy],[sx+rx,sy],[sx+rx,sy+ry],[sx,sy+ry]],float32) #dst = array([[320,320],[960,320],[960,640],[320,640]], float32) #dst[:,0] += 960 imsize = (320,240) I = resize(I, imsize) I[:, :5] = [255, 0, 0] I[:, -5:] = [255, 0, 0] I[-5:, :] = [0, 255, 0] src = src / 4; dst = dst ; #dst = array([[0,0],[1280,0],[1280,960],[0,960]], float32) P = getPerspectiveTransform(src,dst) WARP = warpPerspective(I, P, imsize); #WARP = resize(WARP, imsize) #I[0:480,:,:]=0 I = WARP if lastCols[0] is None: M = 255 - resize(M, imsize) warped_M = np.nonzero(warpPerspective(M, P, imsize)) col_avg = np.mean(warped_M[1]) lastCols[0] = col_avg - 50 lastCols[1] = col_avg + 50 if lastLine[0] is None: lastLine[0] = 0 lastLine[1] = lastCols[0] lastLine[2] = 0 lastLine[3] = lastCols[1] (WARP, lastCols, lastLine) = findLanes(WARP, (imsize[1], imsize[0]), lastCols, lastLine) WARP = warpPerspective(WARP, P, imsize,flags=cv.CV_WARP_INVERSE_MAP); I_t = np.zeros((imsize[1], imsize[0], 3)) I_t[239/2, :, 0] = 255 I_t = warpPerspective(I_t, P, imsize, flags=cv.CV_WARP_INVERSE_MAP) I[WARP[:,:,0] > 0, 0] = 0 I[WARP[:,:,0] > 0, 1] = 0 I[WARP[:,:,0] > 0, 2] = 255 #I[I_t[:, :, 0] > 0, 0] = 255 #I[I_t[:, :, 0] > 0, 1] = 0 #I[I_t[:, :, 0] > 0, 2] = 0 if lastCols[0] is not None and lastCols[1] is not None: I[:,lastCols[0],:] = 0 I[:,lastCols[1],:] = 0 I[:,(lastCols[0]+lastCols[1])/2,:] = 0 #I = warpPerspective(I, P, imsize, flags=cv.CV_WARP_INVERSE_MAP)
2.28926
2
memery/core.py
wkrettek/memery
0
6623184
# Builtins import time from pathlib import Path import logging # Dependencies import torch from torch import Tensor, device from torchvision.transforms import Compose from PIL import Image # Local imports from memery import loader, crafter, encoder, indexer, ranker class Memery(): def __init__(self, root: str = '.'): self.index_file = 'memery.ann' self.db_file = 'memery.pt' self.root = root self.index = None self.db = None self.model = None self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def index_flow(self, root: str, num_workers=0) -> tuple[str, str]: '''Indexes images in path, returns the location of save files''' start_time = time.time() if self.root != root: self.root = root self.reset_state() path = Path(root) if not path.is_dir(): logging.error("Invalid path: %s", root) return device = self.device # Check if we should re-index the files print("Checking files...") dbpath = path/self.db_file db = self.get_db(str(dbpath)) treepath = path/self.index_file treemap = self.get_index(str(treepath)) filepaths = loader.get_valid_images(path) db_set = set([o['hash'] for o in db.values()]) fp_set = set([o for _, o in filepaths]) if treemap == None or db_set != fp_set: archive_db = {} archive_db, new_files = loader.archive_loader(filepaths, db) print(f"Loaded {len(archive_db)} encodings") print(f"Encoding {len(new_files)} new images") # Crafting and encoding crafted_files = crafter.crafter(new_files, device, num_workers=num_workers) model = self.get_model() new_embeddings = encoder.image_encoder(crafted_files, device, model) # Reindexing db = indexer.join_all(archive_db, new_files, new_embeddings) print("Building treemap") treemap = indexer.build_treemap(db) print(f"Saving {len(db)} encodings") save_paths = indexer.save_archives(path, treemap, db) else: save_paths = (str(dbpath), str(treepath)) self.reset_state() print(f"Done in {time.time() - start_time} seconds") return(save_paths) def query_flow(self, root: str, query: str=None, image_query: str=None, reindex: bool=False) -> list[str]: ''' Indexes a folder and returns file paths ranked by query. Parameters: path (str): Folder to search query (str): Search query text image_query (Tensor): Search query image(s) reindex (bool): Reindex the folder if True Returns: list of file paths ranked by query ''' start_time = time.time() if self.root != root: self.root = root self.reset_state() path = Path(root) if not path.is_dir(): logging.error("Invalid path: %s", root) return device = self.device dbpath = path/self.db_file treepath = path/self.index_file treemap = self.get_index(treepath) db = self.get_db(dbpath) # Rebuild the tree if it doesn't exist if reindex==True or len(db) == 0 or treemap == None: print('Indexing') dbpath, treepath = self.index_flow(path) self.reset_state() treemap = self.get_index(treepath) db = self.get_db(dbpath) model = self.get_model() # Convert queries to vector print('Converting query') if image_query: image_query = Image.open(image_query).convert('RGB') img = crafter.preproc(image_query) if query and image_query: text_vec = encoder.text_encoder(query, device, model) image_vec = encoder.image_query_encoder(img, device, model) query_vec = text_vec + image_vec elif query: query_vec = encoder.text_encoder(query, device, model) elif image_query: query_vec = encoder.image_query_encoder(img, device, model) else: print('No query!') return "" # Rank db by query print(f"Searching {len(db)} images") indexes = ranker.ranker(query_vec, treemap) ranked_files = ranker.nns_to_files(db, indexes) print(f"Done in {time.time() - start_time} seconds") return(ranked_files) def clean(self, root: str) -> None: ''' Removes all files produced by Memery ''' path = Path(root) if not path.is_dir(): logging.error("Invalid path: %s", root) db_path = path/Path(self.db_file) treemap_path = path/Path(self.index_file) db_path.unlink(missing_ok=True), treemap_path.unlink(missing_ok=True) def get_model(self): ''' Gets a new clip model if not initialized ''' if self.model == None: self.model = encoder.load_model(self.device) return self.model def get_index(self, treepath: str): ''' Gets a new index if not initialized Parameters: path (str): Path to index ''' if self.index == None: self.index = loader.treemap_loader(treepath) return self.index def get_db(self, dbpath: str): ''' Gets a new db if not initialized Parameters: path (str): Path to db ''' if self.db == None: self.db = loader.db_loader(dbpath, self.device) return self.db def reset_state(self) -> None: ''' Resets the index and db ''' self.index = None self.db = None
# Builtins import time from pathlib import Path import logging # Dependencies import torch from torch import Tensor, device from torchvision.transforms import Compose from PIL import Image # Local imports from memery import loader, crafter, encoder, indexer, ranker class Memery(): def __init__(self, root: str = '.'): self.index_file = 'memery.ann' self.db_file = 'memery.pt' self.root = root self.index = None self.db = None self.model = None self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def index_flow(self, root: str, num_workers=0) -> tuple[str, str]: '''Indexes images in path, returns the location of save files''' start_time = time.time() if self.root != root: self.root = root self.reset_state() path = Path(root) if not path.is_dir(): logging.error("Invalid path: %s", root) return device = self.device # Check if we should re-index the files print("Checking files...") dbpath = path/self.db_file db = self.get_db(str(dbpath)) treepath = path/self.index_file treemap = self.get_index(str(treepath)) filepaths = loader.get_valid_images(path) db_set = set([o['hash'] for o in db.values()]) fp_set = set([o for _, o in filepaths]) if treemap == None or db_set != fp_set: archive_db = {} archive_db, new_files = loader.archive_loader(filepaths, db) print(f"Loaded {len(archive_db)} encodings") print(f"Encoding {len(new_files)} new images") # Crafting and encoding crafted_files = crafter.crafter(new_files, device, num_workers=num_workers) model = self.get_model() new_embeddings = encoder.image_encoder(crafted_files, device, model) # Reindexing db = indexer.join_all(archive_db, new_files, new_embeddings) print("Building treemap") treemap = indexer.build_treemap(db) print(f"Saving {len(db)} encodings") save_paths = indexer.save_archives(path, treemap, db) else: save_paths = (str(dbpath), str(treepath)) self.reset_state() print(f"Done in {time.time() - start_time} seconds") return(save_paths) def query_flow(self, root: str, query: str=None, image_query: str=None, reindex: bool=False) -> list[str]: ''' Indexes a folder and returns file paths ranked by query. Parameters: path (str): Folder to search query (str): Search query text image_query (Tensor): Search query image(s) reindex (bool): Reindex the folder if True Returns: list of file paths ranked by query ''' start_time = time.time() if self.root != root: self.root = root self.reset_state() path = Path(root) if not path.is_dir(): logging.error("Invalid path: %s", root) return device = self.device dbpath = path/self.db_file treepath = path/self.index_file treemap = self.get_index(treepath) db = self.get_db(dbpath) # Rebuild the tree if it doesn't exist if reindex==True or len(db) == 0 or treemap == None: print('Indexing') dbpath, treepath = self.index_flow(path) self.reset_state() treemap = self.get_index(treepath) db = self.get_db(dbpath) model = self.get_model() # Convert queries to vector print('Converting query') if image_query: image_query = Image.open(image_query).convert('RGB') img = crafter.preproc(image_query) if query and image_query: text_vec = encoder.text_encoder(query, device, model) image_vec = encoder.image_query_encoder(img, device, model) query_vec = text_vec + image_vec elif query: query_vec = encoder.text_encoder(query, device, model) elif image_query: query_vec = encoder.image_query_encoder(img, device, model) else: print('No query!') return "" # Rank db by query print(f"Searching {len(db)} images") indexes = ranker.ranker(query_vec, treemap) ranked_files = ranker.nns_to_files(db, indexes) print(f"Done in {time.time() - start_time} seconds") return(ranked_files) def clean(self, root: str) -> None: ''' Removes all files produced by Memery ''' path = Path(root) if not path.is_dir(): logging.error("Invalid path: %s", root) db_path = path/Path(self.db_file) treemap_path = path/Path(self.index_file) db_path.unlink(missing_ok=True), treemap_path.unlink(missing_ok=True) def get_model(self): ''' Gets a new clip model if not initialized ''' if self.model == None: self.model = encoder.load_model(self.device) return self.model def get_index(self, treepath: str): ''' Gets a new index if not initialized Parameters: path (str): Path to index ''' if self.index == None: self.index = loader.treemap_loader(treepath) return self.index def get_db(self, dbpath: str): ''' Gets a new db if not initialized Parameters: path (str): Path to db ''' if self.db == None: self.db = loader.db_loader(dbpath, self.device) return self.db def reset_state(self) -> None: ''' Resets the index and db ''' self.index = None self.db = None
en
0.708312
# Builtins # Dependencies # Local imports Indexes images in path, returns the location of save files # Check if we should re-index the files # Crafting and encoding # Reindexing Indexes a folder and returns file paths ranked by query. Parameters: path (str): Folder to search query (str): Search query text image_query (Tensor): Search query image(s) reindex (bool): Reindex the folder if True Returns: list of file paths ranked by query # Rebuild the tree if it doesn't exist # Convert queries to vector # Rank db by query Removes all files produced by Memery Gets a new clip model if not initialized Gets a new index if not initialized Parameters: path (str): Path to index Gets a new db if not initialized Parameters: path (str): Path to db Resets the index and db
2.095909
2
JTScheduler/JTScheduler_main.py
MaciejGGH/JTDataOrchestrator
0
6623185
<filename>JTScheduler/JTScheduler_main.py # -*- coding: utf-8 -* #------------------------------------------------------------------------------- # Name: Informatica Scheduler # Purpose: # # Author: <NAME> # # Created: 22.02.2017 # Copyright: (c) macie 2017 # Licence: <your licence> #------------------------------------------------------------------------------- import cherrypy from jinja2 import Environment, FileSystemLoader from os.path import join, dirname, abspath, sep from os import getcwd import ConfigParser class job(): def __init__(self, jobId, executorName, name, description, groupId, statusId, type, expectedBy, maxRunTime, maxRetryCnt, maxThreads, updatedBy, updatedOn, version): self.jobId = jobId.strip() self.executorName = executorName.strip() self.name = name.strip() self.description = description self.groupId = groupId.strip() self.statusId = statusId.strip() self.type = type.strip() self.expectedBy = expectedBy.strip() self.maxRunTime = maxRunTime.strip() self.maxRetryCnt = maxRetryCnt.strip() self.maxThreads = maxThreads.strip() self.updatedBy = updatedBy.strip() self.updatedOn = updatedOn.strip() self.version = version.strip() def __str__(self): return 'Job: {0}, running on: {1}'.format(self.name, self.executorName) class filematcher(): def __init__(self, filematcherId, jobId, type, value): self.filematcherId = filematcherId.strip() self.jobId = jobId.strip() self.type = type.strip() self.value = value.strip() def __str__(self): return 'jobId: {0}, type: {1}, value: {2}'.format(self.jobId, self.type, self.value) class JTSchedulerWebService(object): @cherrypy.tools.accept(media='text/plain') def __init__(self): self.executors = {} self.affectedFiles = [] #list of files coming from FileMatchers self.jobs = {} self.filematchers = {} # get config self.registerJobs() self.registerFileMatchers() self.registerExecutors() self.filematcherseparator = ';' def registerExecutors(self): dir = dirname(__file__) configFileName = join(dir, r'cfg\scheduler.cfg') config = ConfigParser.RawConfigParser() config.optionxform = lambda option: option config.read(configFileName) ExecutorList = config.get('Common', 'ExecutorList').split(',') for executorName in ExecutorList: executorAddress = config.get('Executors', executorName) self.executors[executorName] = executorAddress registerExecutors.exposed = True def registerJobs(self): dir = dirname(__file__) for jobLine in open(join(dir, r'job_config\jobs.cfg'), 'r').readlines()[1:]: jobId, executorName, name, description, groupId, statusId, type, expectedBy, maxRunTime, maxRetryCnt, maxThreads, updatedBy, updatedOn, version = jobLine.replace('\n', '').split(',') self.jobs[jobId.strip()] = job(jobId, executorName, name, description, groupId, statusId, type, expectedBy, maxRunTime, maxRetryCnt, maxThreads, updatedBy, updatedOn, version) registerJobs.exposed = True def registerFileMatchers(self): dir = dirname(__file__) for fmLine in open(join(dir, r'job_config\filematchers.cfg'), 'r').readlines()[1:]: filematcherId, jobId, type, value = fmLine.replace('\n', '').split(',') newFM = filematcher(filematcherId, jobId, type, value) try: self.filematchers[jobId.strip()] += [newFM] except: self.filematchers[jobId.strip()] = [newFM] registerFileMatchers.exposed = True def listRegistrations(self): return '<ul>' + ''.join('<li>{0}</li>'.format(f) for f in self.affectedFiles) + '</ul>' listRegistrations.exposed = True def viewJobs(self): print self.jobs return '<ul>' + ''.join('<li>{0}</li>'.format(self.jobs[k]) for k in self.jobs) + '</ul>' viewJobs.exposed = True def viewFilematchers(self): fmList = '<ul>' for jobId in self.filematchers: print '>{0}<'.format(jobId.strip()) fmList += '<li>{0}</li>'.format(self.jobs[jobId].name) fmList += '<ul>' + ''.join('<li>{0}</li>'.format(fm) for fm in self.filematchers[jobId]) + '</ul>' fmList += '</ul>' return fmList #return '<ul>' + ''.join('<li>{0}</li>'.format(self.filematchers[jobId]) for jobId in self.filematchers) + '</ul>' viewFilematchers.exposed = True def viewExecutors(self): print self.executors return '<ul>' + ''.join('<li>{0}:{1}</li>'.format(k, self.executors[k]) for k in self.executors) + '</ul>' viewExecutors.exposed = True def status(self): template_dir = join(dirname(__file__), 'templates') jinja_env = Environment(loader=FileSystemLoader(template_dir), autoescape=True) template = jinja_env.get_template('JTSchedulerIndex.html') return template.render(affectedFiles = self.affectedFiles) status.exposed = True def registerFile(self, fileName, testMode = 0): def checkJobsToRun(fileName): jobsToRun = [] for jobId in self.filematchers: activateJob = True for fm in self.filematchers[jobId]: #print fm if fm.type == 'FS': if fileName[:len(fm.value)] != fm.value: activateJob = False elif fm.type == 'FE': if fileName[-1*len(fm.value):] != fm.value: activateJob = False elif fm.type == 'FM': if fileName != fm.value: activateJob = False elif fm.type == 'FSL': matchFound = False for val in fm.value.split(self.filematcherseparator): if fileName[:len(val)] == val: matchFound = True if not matchFound: activateJob = False elif fm.type == 'FEL': matchFound = False for val in fm.value.split(self.filematcherseparator): if fileName[-1*len(val):] == val: matchFound = True if not matchFound: activateJob = False elif fm.type == 'FML': matchFound = False for val in fm.value.split(self.filematcherseparator): if fileName == val: matchFound = True if not matchFound: activateJob = False if activateJob: jobsToRun += [jobId] return jobsToRun self.affectedFiles += [fileName] print cherrypy.request.params['fileName'] jobsToRun = checkJobsToRun(fileName) if testMode: li = ''.join('<li>{0}</li>'.format(self.jobs[jobId]) for jobId in jobsToRun) return '<ul>{0}</ul>'.format(li) else: #TODO: rum the jobs # check filematchers for jobs to be activated # send notification to Executor if FM found return fileName # check filematchers for jobs to be activated # send notification to Executor if FM found return fileName registerFile.exposed = True def requestCheck(self): ## #def PUT(self, fileName): # check filematchers for jobs to be activated # send notification to Executor if FM found s = cherrypy.request.headers print s return ''.join(k + ': ' + s[k] + '<br>' for k in s) requestCheck.exposed = True ## def DELETE(self): ## cherrypy.session.pop('mystring', None) def index(self): return self.affectedFiles index.exposed = True if __name__ == '__main__': # On Startup current_dir = dirname(abspath(__file__)) + sep config = { 'global': { ## 'environment': 'production', 'log.screen': True, 'server.socket_host': '127.0.0.1', 'server.socket_port': 8080, 'engine.autoreload_on': True, 'log.error_file': join(current_dir, 'errors.log'), 'log.access_file': join(current_dir, 'access.log'), }, '/registerFile': { #'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.sessions.on': True, 'tools.response_headers.on': True, #'tools.response_headers.headers': [('Content-Type', 'text/plain')], }, '/css': { 'tools.staticdir.on': True, 'tools.staticdir.dir': '/css' }, '/job_config': { 'tools.staticfile.debug': True, 'tools.staticdir.on': True, 'tools.staticdir.dir': '/job_config' }, '/css/mystyle.css': { 'tools.staticfile.debug': True, 'tools.staticfile.on': True, 'tools.staticfile.filename': join(join(current_dir, 'css'), 'mystyle.css') }, } #cherrypy.quickstart(JTSchedulerWebService(), '/', config) cherrypy.tree.mount(JTSchedulerWebService(), '/', config) cherrypy.engine.start() cherrypy.engine.block()
<filename>JTScheduler/JTScheduler_main.py # -*- coding: utf-8 -* #------------------------------------------------------------------------------- # Name: Informatica Scheduler # Purpose: # # Author: <NAME> # # Created: 22.02.2017 # Copyright: (c) macie 2017 # Licence: <your licence> #------------------------------------------------------------------------------- import cherrypy from jinja2 import Environment, FileSystemLoader from os.path import join, dirname, abspath, sep from os import getcwd import ConfigParser class job(): def __init__(self, jobId, executorName, name, description, groupId, statusId, type, expectedBy, maxRunTime, maxRetryCnt, maxThreads, updatedBy, updatedOn, version): self.jobId = jobId.strip() self.executorName = executorName.strip() self.name = name.strip() self.description = description self.groupId = groupId.strip() self.statusId = statusId.strip() self.type = type.strip() self.expectedBy = expectedBy.strip() self.maxRunTime = maxRunTime.strip() self.maxRetryCnt = maxRetryCnt.strip() self.maxThreads = maxThreads.strip() self.updatedBy = updatedBy.strip() self.updatedOn = updatedOn.strip() self.version = version.strip() def __str__(self): return 'Job: {0}, running on: {1}'.format(self.name, self.executorName) class filematcher(): def __init__(self, filematcherId, jobId, type, value): self.filematcherId = filematcherId.strip() self.jobId = jobId.strip() self.type = type.strip() self.value = value.strip() def __str__(self): return 'jobId: {0}, type: {1}, value: {2}'.format(self.jobId, self.type, self.value) class JTSchedulerWebService(object): @cherrypy.tools.accept(media='text/plain') def __init__(self): self.executors = {} self.affectedFiles = [] #list of files coming from FileMatchers self.jobs = {} self.filematchers = {} # get config self.registerJobs() self.registerFileMatchers() self.registerExecutors() self.filematcherseparator = ';' def registerExecutors(self): dir = dirname(__file__) configFileName = join(dir, r'cfg\scheduler.cfg') config = ConfigParser.RawConfigParser() config.optionxform = lambda option: option config.read(configFileName) ExecutorList = config.get('Common', 'ExecutorList').split(',') for executorName in ExecutorList: executorAddress = config.get('Executors', executorName) self.executors[executorName] = executorAddress registerExecutors.exposed = True def registerJobs(self): dir = dirname(__file__) for jobLine in open(join(dir, r'job_config\jobs.cfg'), 'r').readlines()[1:]: jobId, executorName, name, description, groupId, statusId, type, expectedBy, maxRunTime, maxRetryCnt, maxThreads, updatedBy, updatedOn, version = jobLine.replace('\n', '').split(',') self.jobs[jobId.strip()] = job(jobId, executorName, name, description, groupId, statusId, type, expectedBy, maxRunTime, maxRetryCnt, maxThreads, updatedBy, updatedOn, version) registerJobs.exposed = True def registerFileMatchers(self): dir = dirname(__file__) for fmLine in open(join(dir, r'job_config\filematchers.cfg'), 'r').readlines()[1:]: filematcherId, jobId, type, value = fmLine.replace('\n', '').split(',') newFM = filematcher(filematcherId, jobId, type, value) try: self.filematchers[jobId.strip()] += [newFM] except: self.filematchers[jobId.strip()] = [newFM] registerFileMatchers.exposed = True def listRegistrations(self): return '<ul>' + ''.join('<li>{0}</li>'.format(f) for f in self.affectedFiles) + '</ul>' listRegistrations.exposed = True def viewJobs(self): print self.jobs return '<ul>' + ''.join('<li>{0}</li>'.format(self.jobs[k]) for k in self.jobs) + '</ul>' viewJobs.exposed = True def viewFilematchers(self): fmList = '<ul>' for jobId in self.filematchers: print '>{0}<'.format(jobId.strip()) fmList += '<li>{0}</li>'.format(self.jobs[jobId].name) fmList += '<ul>' + ''.join('<li>{0}</li>'.format(fm) for fm in self.filematchers[jobId]) + '</ul>' fmList += '</ul>' return fmList #return '<ul>' + ''.join('<li>{0}</li>'.format(self.filematchers[jobId]) for jobId in self.filematchers) + '</ul>' viewFilematchers.exposed = True def viewExecutors(self): print self.executors return '<ul>' + ''.join('<li>{0}:{1}</li>'.format(k, self.executors[k]) for k in self.executors) + '</ul>' viewExecutors.exposed = True def status(self): template_dir = join(dirname(__file__), 'templates') jinja_env = Environment(loader=FileSystemLoader(template_dir), autoescape=True) template = jinja_env.get_template('JTSchedulerIndex.html') return template.render(affectedFiles = self.affectedFiles) status.exposed = True def registerFile(self, fileName, testMode = 0): def checkJobsToRun(fileName): jobsToRun = [] for jobId in self.filematchers: activateJob = True for fm in self.filematchers[jobId]: #print fm if fm.type == 'FS': if fileName[:len(fm.value)] != fm.value: activateJob = False elif fm.type == 'FE': if fileName[-1*len(fm.value):] != fm.value: activateJob = False elif fm.type == 'FM': if fileName != fm.value: activateJob = False elif fm.type == 'FSL': matchFound = False for val in fm.value.split(self.filematcherseparator): if fileName[:len(val)] == val: matchFound = True if not matchFound: activateJob = False elif fm.type == 'FEL': matchFound = False for val in fm.value.split(self.filematcherseparator): if fileName[-1*len(val):] == val: matchFound = True if not matchFound: activateJob = False elif fm.type == 'FML': matchFound = False for val in fm.value.split(self.filematcherseparator): if fileName == val: matchFound = True if not matchFound: activateJob = False if activateJob: jobsToRun += [jobId] return jobsToRun self.affectedFiles += [fileName] print cherrypy.request.params['fileName'] jobsToRun = checkJobsToRun(fileName) if testMode: li = ''.join('<li>{0}</li>'.format(self.jobs[jobId]) for jobId in jobsToRun) return '<ul>{0}</ul>'.format(li) else: #TODO: rum the jobs # check filematchers for jobs to be activated # send notification to Executor if FM found return fileName # check filematchers for jobs to be activated # send notification to Executor if FM found return fileName registerFile.exposed = True def requestCheck(self): ## #def PUT(self, fileName): # check filematchers for jobs to be activated # send notification to Executor if FM found s = cherrypy.request.headers print s return ''.join(k + ': ' + s[k] + '<br>' for k in s) requestCheck.exposed = True ## def DELETE(self): ## cherrypy.session.pop('mystring', None) def index(self): return self.affectedFiles index.exposed = True if __name__ == '__main__': # On Startup current_dir = dirname(abspath(__file__)) + sep config = { 'global': { ## 'environment': 'production', 'log.screen': True, 'server.socket_host': '127.0.0.1', 'server.socket_port': 8080, 'engine.autoreload_on': True, 'log.error_file': join(current_dir, 'errors.log'), 'log.access_file': join(current_dir, 'access.log'), }, '/registerFile': { #'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.sessions.on': True, 'tools.response_headers.on': True, #'tools.response_headers.headers': [('Content-Type', 'text/plain')], }, '/css': { 'tools.staticdir.on': True, 'tools.staticdir.dir': '/css' }, '/job_config': { 'tools.staticfile.debug': True, 'tools.staticdir.on': True, 'tools.staticdir.dir': '/job_config' }, '/css/mystyle.css': { 'tools.staticfile.debug': True, 'tools.staticfile.on': True, 'tools.staticfile.filename': join(join(current_dir, 'css'), 'mystyle.css') }, } #cherrypy.quickstart(JTSchedulerWebService(), '/', config) cherrypy.tree.mount(JTSchedulerWebService(), '/', config) cherrypy.engine.start() cherrypy.engine.block()
en
0.361317
# -*- coding: utf-8 -* #------------------------------------------------------------------------------- # Name: Informatica Scheduler # Purpose: # # Author: <NAME> # # Created: 22.02.2017 # Copyright: (c) macie 2017 # Licence: <your licence> #------------------------------------------------------------------------------- #list of files coming from FileMatchers # get config #return '<ul>' + ''.join('<li>{0}</li>'.format(self.filematchers[jobId]) for jobId in self.filematchers) + '</ul>' #print fm #TODO: rum the jobs # check filematchers for jobs to be activated # send notification to Executor if FM found # check filematchers for jobs to be activated # send notification to Executor if FM found ## #def PUT(self, fileName): # check filematchers for jobs to be activated # send notification to Executor if FM found ## def DELETE(self): ## cherrypy.session.pop('mystring', None) # On Startup ## 'environment': 'production', #'request.dispatch': cherrypy.dispatch.MethodDispatcher(), #'tools.response_headers.headers': [('Content-Type', 'text/plain')], #cherrypy.quickstart(JTSchedulerWebService(), '/', config)
2.091833
2
sandbox/ex2/exps/doom.py
sokol1412/rllab_hierarchical_rl
0
6623186
from sandbox.ex2.algos.trpo import TRPO from rllab.envs.normalized_env import normalize from rllab.misc.instrument import stub, run_experiment_lite from rllab.policies.categorical_conv_policy import CategoricalConvPolicy import lasagne.nonlinearities as NL from sandbox.ex2.envs.cropped_gym_env import CroppedGymEnv from sandbox.ex2.models.exemplar import Exemplar from sandbox.ex2.models.siamese import SiameseConv from sandbox.ex2.utils.log_utils import get_time_stamp from sandbox.ex2.parallel_trpo.linear_feature_baseline import ZeroBaseline import os stub(globals()) from rllab.misc.instrument import VariantGenerator, variant class VG(VariantGenerator): @variant def seed(self): return [0, 100, 200, 300, 400] @variant def env(self): return ['doommaze'] @variant def bonus_coeff(self): return [2e-4] @variant def entropy_bonus(self): return [1e-5] @variant def train_itrs(self): return [1000] @variant def n_parallel(self): return [4] @variant def reset_freq(self): return [0] @variant def hidden_sizes(self): return [(32,)] @variant def exemplar_learning_rate(self): return [1e-4] @variant def bonus_form(self): return ["-log(p)"] @variant def use_actions(self): return [False] @variant def kl_weight(self): return [0.001] @variant def eval_first(self): return [False] variants = VG().variants() for v in variants: exp_index = os.path.basename(__file__).split('.')[0] exp_prefix = "trpo/" + exp_index + "-" + v["env"] exp_name = "{exp_index}_{time}_{env}".format( exp_index=exp_index, time=get_time_stamp(), env=v["env"], ) img_width = 32 img_height = 32 env = CroppedGymEnv(env_name='ex2/DoomMyWayHomeCustom-v0', screen_height=img_height, screen_width=img_width , record_video=True, frame_skip=10, conv=True, transpose_output=True, doom_actionspace=None) env = normalize(env) network_args = dict( conv_filters=[16,16], conv_filter_sizes=[4,4], conv_strides=[4,4], conv_pads=[(0,0)]*2, hidden_sizes=[32], hidden_nonlinearity=NL.rectify, output_nonlinearity=NL.softmax, ) policy = CategoricalConvPolicy( env_spec=env.spec, name="policy", **network_args ) batch_size = 4000 max_path_length = batch_size baseline = ZeroBaseline(env_spec=env.spec) channel_size = 3 model_args = dict(input_size=channel_size*img_width * img_height, img_width=img_width, img_height=img_height, channel_size=channel_size, feature_dim=v['hidden_sizes'][-1]//2, hidden_sizes=v['hidden_sizes'], l2_reg=0, learning_rate=v['exemplar_learning_rate'], hidden_act=NL.tanh, kl_weight=v['kl_weight'], set_norm_constant=1, conv_args=dict(filter_sizes=((4, 4), (4, 4)), num_filters=(16, 16), strides=((2, 2), (2, 2)), hidden_act=NL.tanh) # TODO Try Relu ) exemplar_args = dict(state_dim=env.observation_space.flat_dim, #1, replay_state_dim=env.observation_space.flat_dim, n_action=env.action_space.flat_dim, model_cls=SiameseConv, model_args=model_args, replay_size=5000*50, min_replay_size=4000*2, train_itrs=v["train_itrs"], first_train_itrs=2000, bonus_form=v["bonus_form"], use_actions=v["use_actions"], ) algo = TRPO( env=env, policy=policy, baseline=baseline, batch_size=batch_size, #whole_paths=False, n_parallel=v['n_parallel'], n_itr=300, discount=0.99, step_size=0.01, exemplar_cls=Exemplar, exemplar_args=exemplar_args, bonus_coeff=v['bonus_coeff'], entropy_bonus=v['entropy_bonus'], eval_first=v['eval_first'] #sampler_cls=BatchSampler, #sampler_arg=sampler_args, ) run_experiment_lite( algo.train(), #use_gpu=True, exp_prefix=exp_prefix, exp_name=exp_name, seed=v["seed"], variant=v, mode='local', sync_s3_log=True, use_cloudpickle=False, sync_log_on_termination=True, sync_all_data_node_to_s3=True, snapshot_mode='gap', snapshot_gap=50 )
from sandbox.ex2.algos.trpo import TRPO from rllab.envs.normalized_env import normalize from rllab.misc.instrument import stub, run_experiment_lite from rllab.policies.categorical_conv_policy import CategoricalConvPolicy import lasagne.nonlinearities as NL from sandbox.ex2.envs.cropped_gym_env import CroppedGymEnv from sandbox.ex2.models.exemplar import Exemplar from sandbox.ex2.models.siamese import SiameseConv from sandbox.ex2.utils.log_utils import get_time_stamp from sandbox.ex2.parallel_trpo.linear_feature_baseline import ZeroBaseline import os stub(globals()) from rllab.misc.instrument import VariantGenerator, variant class VG(VariantGenerator): @variant def seed(self): return [0, 100, 200, 300, 400] @variant def env(self): return ['doommaze'] @variant def bonus_coeff(self): return [2e-4] @variant def entropy_bonus(self): return [1e-5] @variant def train_itrs(self): return [1000] @variant def n_parallel(self): return [4] @variant def reset_freq(self): return [0] @variant def hidden_sizes(self): return [(32,)] @variant def exemplar_learning_rate(self): return [1e-4] @variant def bonus_form(self): return ["-log(p)"] @variant def use_actions(self): return [False] @variant def kl_weight(self): return [0.001] @variant def eval_first(self): return [False] variants = VG().variants() for v in variants: exp_index = os.path.basename(__file__).split('.')[0] exp_prefix = "trpo/" + exp_index + "-" + v["env"] exp_name = "{exp_index}_{time}_{env}".format( exp_index=exp_index, time=get_time_stamp(), env=v["env"], ) img_width = 32 img_height = 32 env = CroppedGymEnv(env_name='ex2/DoomMyWayHomeCustom-v0', screen_height=img_height, screen_width=img_width , record_video=True, frame_skip=10, conv=True, transpose_output=True, doom_actionspace=None) env = normalize(env) network_args = dict( conv_filters=[16,16], conv_filter_sizes=[4,4], conv_strides=[4,4], conv_pads=[(0,0)]*2, hidden_sizes=[32], hidden_nonlinearity=NL.rectify, output_nonlinearity=NL.softmax, ) policy = CategoricalConvPolicy( env_spec=env.spec, name="policy", **network_args ) batch_size = 4000 max_path_length = batch_size baseline = ZeroBaseline(env_spec=env.spec) channel_size = 3 model_args = dict(input_size=channel_size*img_width * img_height, img_width=img_width, img_height=img_height, channel_size=channel_size, feature_dim=v['hidden_sizes'][-1]//2, hidden_sizes=v['hidden_sizes'], l2_reg=0, learning_rate=v['exemplar_learning_rate'], hidden_act=NL.tanh, kl_weight=v['kl_weight'], set_norm_constant=1, conv_args=dict(filter_sizes=((4, 4), (4, 4)), num_filters=(16, 16), strides=((2, 2), (2, 2)), hidden_act=NL.tanh) # TODO Try Relu ) exemplar_args = dict(state_dim=env.observation_space.flat_dim, #1, replay_state_dim=env.observation_space.flat_dim, n_action=env.action_space.flat_dim, model_cls=SiameseConv, model_args=model_args, replay_size=5000*50, min_replay_size=4000*2, train_itrs=v["train_itrs"], first_train_itrs=2000, bonus_form=v["bonus_form"], use_actions=v["use_actions"], ) algo = TRPO( env=env, policy=policy, baseline=baseline, batch_size=batch_size, #whole_paths=False, n_parallel=v['n_parallel'], n_itr=300, discount=0.99, step_size=0.01, exemplar_cls=Exemplar, exemplar_args=exemplar_args, bonus_coeff=v['bonus_coeff'], entropy_bonus=v['entropy_bonus'], eval_first=v['eval_first'] #sampler_cls=BatchSampler, #sampler_arg=sampler_args, ) run_experiment_lite( algo.train(), #use_gpu=True, exp_prefix=exp_prefix, exp_name=exp_name, seed=v["seed"], variant=v, mode='local', sync_s3_log=True, use_cloudpickle=False, sync_log_on_termination=True, sync_all_data_node_to_s3=True, snapshot_mode='gap', snapshot_gap=50 )
en
0.438431
# TODO Try Relu #1, #whole_paths=False, #sampler_cls=BatchSampler, #sampler_arg=sampler_args, #use_gpu=True,
1.710401
2
generators/examples/hosts.py
davidyshuang/python3
0
6623187
# hosts.py # # Find unique host IP addresses from linesdir import lines_from_dir from apachelog import apache_log lines = lines_from_dir("access-log*","www") log = apache_log(lines) hosts = set(r['host'] for r in log) for h in hosts: print(h)
# hosts.py # # Find unique host IP addresses from linesdir import lines_from_dir from apachelog import apache_log lines = lines_from_dir("access-log*","www") log = apache_log(lines) hosts = set(r['host'] for r in log) for h in hosts: print(h)
en
0.738287
# hosts.py # # Find unique host IP addresses
2.713811
3
finder.py
bckhm/EmailMatcher
1
6623188
import re import pandas as pd # Function that searches data.txt for email/phone numbers before returning a dictionary def find_data(pattern, column_name): with open('data.txt', 'r') as file: contents = file.read() matches = pattern.findall(contents) matches_dict = {column_name: matches} return matches_dict # Function that converts aobve dictionary to excel def save_excel(matches, filename): df = pd.DataFrame(data=matches) df.to_excel(filename) print(f"{filename} has been created.") print("--- Ensure that you have copied the text into data.txt---") # Dictionary that gives varying patterns. column names and file names based on user input choice_dict = {'e': [r'[\w._-]*@[\w._-]*\.\w+', 'Email Addresses', 'emails.xlsx'], 'n': [r'\d{4}\s*\d{4}', 'Numbers', 'numbers.xlsx']} try: # Allows users to select between finding email addresses/phone numbers choice = input("Type N to find phone numbers and E to find emails: ") choice_lower = choice.lower() pattern = re.compile(choice_dict[choice_lower][0]) except KeyError as e: print(f"You typed {e}, that's not 'E' or 'N'!") except Exception: print("Something went wrong") else: matches = find_data(pattern, choice_dict[choice_lower][1]) save_excel(matches, choice_dict[choice_lower][2]) finally: exit = input("Press Enter key to exit...")
import re import pandas as pd # Function that searches data.txt for email/phone numbers before returning a dictionary def find_data(pattern, column_name): with open('data.txt', 'r') as file: contents = file.read() matches = pattern.findall(contents) matches_dict = {column_name: matches} return matches_dict # Function that converts aobve dictionary to excel def save_excel(matches, filename): df = pd.DataFrame(data=matches) df.to_excel(filename) print(f"{filename} has been created.") print("--- Ensure that you have copied the text into data.txt---") # Dictionary that gives varying patterns. column names and file names based on user input choice_dict = {'e': [r'[\w._-]*@[\w._-]*\.\w+', 'Email Addresses', 'emails.xlsx'], 'n': [r'\d{4}\s*\d{4}', 'Numbers', 'numbers.xlsx']} try: # Allows users to select between finding email addresses/phone numbers choice = input("Type N to find phone numbers and E to find emails: ") choice_lower = choice.lower() pattern = re.compile(choice_dict[choice_lower][0]) except KeyError as e: print(f"You typed {e}, that's not 'E' or 'N'!") except Exception: print("Something went wrong") else: matches = find_data(pattern, choice_dict[choice_lower][1]) save_excel(matches, choice_dict[choice_lower][2]) finally: exit = input("Press Enter key to exit...")
en
0.827275
# Function that searches data.txt for email/phone numbers before returning a dictionary # Function that converts aobve dictionary to excel # Dictionary that gives varying patterns. column names and file names based on user input # Allows users to select between finding email addresses/phone numbers
4.136726
4
benchmarks/sample_fsm/Test_Utilities.py
nuprl/retic_performance
3
6623189
import pytest from Untyped.Utilities import relative_average, accumulated_s def test_relative_average(): assert relative_average([1, 2, 3], 1) == 2 assert relative_average([1, 2, 3], 2) == 1 def test_accumulated_s(): assert accumulated_s([1]) == [1] assert accumulated_s([2, 2]) == [.5, 1] assert accumulated_s([2, 8]) == [.2, 1]
import pytest from Untyped.Utilities import relative_average, accumulated_s def test_relative_average(): assert relative_average([1, 2, 3], 1) == 2 assert relative_average([1, 2, 3], 2) == 1 def test_accumulated_s(): assert accumulated_s([1]) == [1] assert accumulated_s([2, 2]) == [.5, 1] assert accumulated_s([2, 8]) == [.2, 1]
none
1
2.678093
3
__init__.py
manahter/tarag
3
6623190
""" Info: module : Tarag description : Ağdaki cihazları bulur author : Manahter Files: getmac : IP adresini kullanarak MAC adresini bulmamıza yardımcı olur. get_mac_address(ip=ip) main source: "https://github.com/GhostofGoes/getmac", getvendor : MAC adresini kullanarak Üretici Markayı bulmamızı sağlar. get_mac_vendor(mac) rapor : Ağı tarama esnasında ekrana çıktı veren modüldür. INPROCESS : Tarag modül dizininde INPROCESS isimli bir dosyanın varlığı, Tarama işleminde olduğunun göstergesidir. Tarama bittiğinde dosya otomatik olarak silinir. Bu yüzden dosya bazen görünür bazen kaybolur. "" -> İçi boş dosya RESULTS : Çıktıların biriktiği dosyadır { IP: { "MAC": MAC, "VENDOR": VENDOR}, ... } Methods: tarag.start() -> None -> Arka planda ağ taraması başlatılır tarag.scan() -> None -> start aynı tarag.inprocess -> bool -> Tarama işleminde olup olmadığı sorgulanır. tarag.result -> dict -> { IP: { "MAC": MAC, "VENDOR": VENDOR}, ... } -> Bulunan cihaz bilgileri tarag.devices( -> list -> [ ("IP", "MAC", "VENDOR"), ... ] -> Bulunan cihaz bilgileri liste şeklinde only_esp -> bool -> Sadece bulunan ESPressif ürünlerini döndür tarag.wait( -> bool -> Tarama bitene kadar bekler. True-> İşlem bitti. False-> Zaman aşımı sonucu döndüm timeout -> float -> Zaman aşımı Example: # İçe aktarma from .Tarag import tarag # Arkaplanda Ağ Taramayı başlat tarag.scan() # Tarama bitene kadar bekle tarag.wait() # Tarama sonuçlarını kullanabilirsin results = tarag.result # Bulunan cihaz bilgilerini yazdır print(*tarag.devices(), sep="\n") """ import subprocess import time import json import sys import os # Sabitler MAC = "MAC" VENDOR = "VENDOR" RESULTS = "RESULTS" INPROCESS = "INPROCESS" dirname = os.path.dirname(__file__) PATH_RESULTS = os.path.join(dirname, RESULTS) PATH_INPROCESS = os.path.join(dirname, INPROCESS) # Ağ tarama işleminde olup olmadığı, INPROCESS isimli dosyanın olup olmadığına bağlanmıştır. # Bu yüzden, modül import edilirken, bu dosya önceden kalmışsa silinir if INPROCESS in os.listdir(dirname): os.remove(PATH_INPROCESS) class TarAg: def __init__(self): self.inprocess = False def start(self): self.scan() def scan(self): """Ağdaki diğer cihazları tarar""" if self.inprocess: return self.inprocess = True @property def inprocess(self): return INPROCESS in os.listdir(dirname) @inprocess.setter def inprocess(self, value): # İşleme başlansın isteniyorsa.. if value: subprocess.Popen([ # Python konumu sys.executable, # Script konumu dirname, # Parametre "-p" ]) # İşlem bitirilsin isteniyorsa elif self.inprocess: os.remove(PATH_INPROCESS) @property def result(self) -> dict: """Sonuçları çağır. :return { IP: { "MAC": MAC, "VENDOR": VENDOR}, ... } """ if RESULTS not in os.listdir(dirname): return {} with open(PATH_RESULTS, "r") as f: result = json.load(f) return result @result.setter def result(self, data): """Sonuçları kaydet""" # Veri girildiyse veriyi dosyaya yaz. if data: with open(PATH_RESULTS, "w") as f: json.dump(data, f) # Veri girilmediyse ve dosyada varsa, dosyayı sil elif self.result: os.remove(PATH_RESULTS) # Tarama işleminin bittiğini kaydet self.inprocess = False @staticmethod def devices(only_esp=False): """Ağda bulunan cihazları döndürür :param only_esp: bool: Sadece ESPressif Cihazlarını Döndür :return list: [ ("IP", "MAC", "VENDOR"), (...) ... ] """ data = tarag.result if only_esp: for i in data.copy(): if not data[i].get(VENDOR, "").lower().startswith("espressif"): data.pop(i) return [(ip, data[ip].get(MAC), data[ip].get(VENDOR)) for ip in data] def wait(self, timeout=20) -> bool: """İşlem bitene kadar bekle. :param timeout: int: Zaman aşımı. Bu kadar bekledikten sonra hala işlem bitmediyse daha bekleme :return bool: True -> İşlem bitti False-> Zaman aşımı """ # 1 sn'lik bekleme süresi ekliyoruz. Böylece __main__.py başlayıp INPROCESS dosyasını oluşturabilir. time.sleep(1) # timeout'u sorgulama için başlangıç zamanı kaydedilir. start_t = time.time() while self.inprocess: # zaman aşımı olduysa işlemi bitir if time.time() - start_t > timeout: return False return True # Diğer modüllerden işlemler bu değişken üzerinden yapılır. tarag = TarAg()
""" Info: module : Tarag description : Ağdaki cihazları bulur author : Manahter Files: getmac : IP adresini kullanarak MAC adresini bulmamıza yardımcı olur. get_mac_address(ip=ip) main source: "https://github.com/GhostofGoes/getmac", getvendor : MAC adresini kullanarak Üretici Markayı bulmamızı sağlar. get_mac_vendor(mac) rapor : Ağı tarama esnasında ekrana çıktı veren modüldür. INPROCESS : Tarag modül dizininde INPROCESS isimli bir dosyanın varlığı, Tarama işleminde olduğunun göstergesidir. Tarama bittiğinde dosya otomatik olarak silinir. Bu yüzden dosya bazen görünür bazen kaybolur. "" -> İçi boş dosya RESULTS : Çıktıların biriktiği dosyadır { IP: { "MAC": MAC, "VENDOR": VENDOR}, ... } Methods: tarag.start() -> None -> Arka planda ağ taraması başlatılır tarag.scan() -> None -> start aynı tarag.inprocess -> bool -> Tarama işleminde olup olmadığı sorgulanır. tarag.result -> dict -> { IP: { "MAC": MAC, "VENDOR": VENDOR}, ... } -> Bulunan cihaz bilgileri tarag.devices( -> list -> [ ("IP", "MAC", "VENDOR"), ... ] -> Bulunan cihaz bilgileri liste şeklinde only_esp -> bool -> Sadece bulunan ESPressif ürünlerini döndür tarag.wait( -> bool -> Tarama bitene kadar bekler. True-> İşlem bitti. False-> Zaman aşımı sonucu döndüm timeout -> float -> Zaman aşımı Example: # İçe aktarma from .Tarag import tarag # Arkaplanda Ağ Taramayı başlat tarag.scan() # Tarama bitene kadar bekle tarag.wait() # Tarama sonuçlarını kullanabilirsin results = tarag.result # Bulunan cihaz bilgilerini yazdır print(*tarag.devices(), sep="\n") """ import subprocess import time import json import sys import os # Sabitler MAC = "MAC" VENDOR = "VENDOR" RESULTS = "RESULTS" INPROCESS = "INPROCESS" dirname = os.path.dirname(__file__) PATH_RESULTS = os.path.join(dirname, RESULTS) PATH_INPROCESS = os.path.join(dirname, INPROCESS) # Ağ tarama işleminde olup olmadığı, INPROCESS isimli dosyanın olup olmadığına bağlanmıştır. # Bu yüzden, modül import edilirken, bu dosya önceden kalmışsa silinir if INPROCESS in os.listdir(dirname): os.remove(PATH_INPROCESS) class TarAg: def __init__(self): self.inprocess = False def start(self): self.scan() def scan(self): """Ağdaki diğer cihazları tarar""" if self.inprocess: return self.inprocess = True @property def inprocess(self): return INPROCESS in os.listdir(dirname) @inprocess.setter def inprocess(self, value): # İşleme başlansın isteniyorsa.. if value: subprocess.Popen([ # Python konumu sys.executable, # Script konumu dirname, # Parametre "-p" ]) # İşlem bitirilsin isteniyorsa elif self.inprocess: os.remove(PATH_INPROCESS) @property def result(self) -> dict: """Sonuçları çağır. :return { IP: { "MAC": MAC, "VENDOR": VENDOR}, ... } """ if RESULTS not in os.listdir(dirname): return {} with open(PATH_RESULTS, "r") as f: result = json.load(f) return result @result.setter def result(self, data): """Sonuçları kaydet""" # Veri girildiyse veriyi dosyaya yaz. if data: with open(PATH_RESULTS, "w") as f: json.dump(data, f) # Veri girilmediyse ve dosyada varsa, dosyayı sil elif self.result: os.remove(PATH_RESULTS) # Tarama işleminin bittiğini kaydet self.inprocess = False @staticmethod def devices(only_esp=False): """Ağda bulunan cihazları döndürür :param only_esp: bool: Sadece ESPressif Cihazlarını Döndür :return list: [ ("IP", "MAC", "VENDOR"), (...) ... ] """ data = tarag.result if only_esp: for i in data.copy(): if not data[i].get(VENDOR, "").lower().startswith("espressif"): data.pop(i) return [(ip, data[ip].get(MAC), data[ip].get(VENDOR)) for ip in data] def wait(self, timeout=20) -> bool: """İşlem bitene kadar bekle. :param timeout: int: Zaman aşımı. Bu kadar bekledikten sonra hala işlem bitmediyse daha bekleme :return bool: True -> İşlem bitti False-> Zaman aşımı """ # 1 sn'lik bekleme süresi ekliyoruz. Böylece __main__.py başlayıp INPROCESS dosyasını oluşturabilir. time.sleep(1) # timeout'u sorgulama için başlangıç zamanı kaydedilir. start_t = time.time() while self.inprocess: # zaman aşımı olduysa işlemi bitir if time.time() - start_t > timeout: return False return True # Diğer modüllerden işlemler bu değişken üzerinden yapılır. tarag = TarAg()
tr
0.980864
Info: module : Tarag description : Ağdaki cihazları bulur author : Manahter Files: getmac : IP adresini kullanarak MAC adresini bulmamıza yardımcı olur. get_mac_address(ip=ip) main source: "https://github.com/GhostofGoes/getmac", getvendor : MAC adresini kullanarak Üretici Markayı bulmamızı sağlar. get_mac_vendor(mac) rapor : Ağı tarama esnasında ekrana çıktı veren modüldür. INPROCESS : Tarag modül dizininde INPROCESS isimli bir dosyanın varlığı, Tarama işleminde olduğunun göstergesidir. Tarama bittiğinde dosya otomatik olarak silinir. Bu yüzden dosya bazen görünür bazen kaybolur. "" -> İçi boş dosya RESULTS : Çıktıların biriktiği dosyadır { IP: { "MAC": MAC, "VENDOR": VENDOR}, ... } Methods: tarag.start() -> None -> Arka planda ağ taraması başlatılır tarag.scan() -> None -> start aynı tarag.inprocess -> bool -> Tarama işleminde olup olmadığı sorgulanır. tarag.result -> dict -> { IP: { "MAC": MAC, "VENDOR": VENDOR}, ... } -> Bulunan cihaz bilgileri tarag.devices( -> list -> [ ("IP", "MAC", "VENDOR"), ... ] -> Bulunan cihaz bilgileri liste şeklinde only_esp -> bool -> Sadece bulunan ESPressif ürünlerini döndür tarag.wait( -> bool -> Tarama bitene kadar bekler. True-> İşlem bitti. False-> Zaman aşımı sonucu döndüm timeout -> float -> Zaman aşımı Example: # İçe aktarma from .Tarag import tarag # Arkaplanda Ağ Taramayı başlat tarag.scan() # Tarama bitene kadar bekle tarag.wait() # Tarama sonuçlarını kullanabilirsin results = tarag.result # Bulunan cihaz bilgilerini yazdır print(*tarag.devices(), sep="\n") # Sabitler # Ağ tarama işleminde olup olmadığı, INPROCESS isimli dosyanın olup olmadığına bağlanmıştır. # Bu yüzden, modül import edilirken, bu dosya önceden kalmışsa silinir Ağdaki diğer cihazları tarar # İşleme başlansın isteniyorsa.. # Python konumu # Script konumu # Parametre # İşlem bitirilsin isteniyorsa Sonuçları çağır. :return { IP: { "MAC": MAC, "VENDOR": VENDOR}, ... } Sonuçları kaydet # Veri girildiyse veriyi dosyaya yaz. # Veri girilmediyse ve dosyada varsa, dosyayı sil # Tarama işleminin bittiğini kaydet Ağda bulunan cihazları döndürür :param only_esp: bool: Sadece ESPressif Cihazlarını Döndür :return list: [ ("IP", "MAC", "VENDOR"), (...) ... ] İşlem bitene kadar bekle. :param timeout: int: Zaman aşımı. Bu kadar bekledikten sonra hala işlem bitmediyse daha bekleme :return bool: True -> İşlem bitti False-> Zaman aşımı # 1 sn'lik bekleme süresi ekliyoruz. Böylece __main__.py başlayıp INPROCESS dosyasını oluşturabilir. # timeout'u sorgulama için başlangıç zamanı kaydedilir. # zaman aşımı olduysa işlemi bitir # Diğer modüllerden işlemler bu değişken üzerinden yapılır.
2.360084
2
sdbms/app/views.py
xSkyripper/simple-fs-dbms
0
6623191
<reponame>xSkyripper/simple-fs-dbms<gh_stars>0 from flask import Blueprint, render_template, request from sdbms.app.service.builder import QueryBuilder from sdbms.core._manager import DbManager from sdbms.core._parser import QueryParser, CommandError """ Web api that builds the query and sends it to the query manager. Each route will represent a different CRUD operation and for each operation you will need to send a form with the certain data, and as result we will receive a html page. 1.'/' we will display the menu that will give you all the hiperlinks for each operation. 2.'/select' page used for building the select query. Some fields of this form ar optional. As a result, you will receive a page witch contains the selected rows. 3.'/insert' page used for building the insert query. For this one you will need to press the '+' button and fill the fields. As a response, you will receive a success message or an exception if something went wrong 4.'/delete' page use for deleting a row. As a response you will receive success or expcetion. 5.'/update' page used for updating a row. You will need to fill the labels, conditions and values. As a response you will receive a successs message or an exception. """ root_path = "/Users/cernescustefan/Documents/Facultate/db" main_api = Blueprint('main', __name__, template_folder='templates') @main_api.route('/', methods=['GET']) def index(): return render_template('index.html') @main_api.route('/select', methods=['GET']) def select(): return render_template('select.html') @main_api.route('/insert', methods=['GET']) def insert(): return render_template('insert.html') @main_api.route('/delete', methods=['GET']) def delete(): return render_template('delete.html') @main_api.route('/update', methods=['GET']) def update(): return render_template('update.html') @main_api.route('/result', methods=['POST', 'GET']) def result(): if request.method == 'POST': result = request.form queryBuilder = QueryBuilder() set_db = queryBuilder.use_db(result) query = queryBuilder.build_select(result) print(result) db_manager = DbManager(root_path) parser = QueryParser() cmd = parser.parse(set_db) rv = cmd.execute(db_manager) cmd = parser.parse(query) rv = cmd.execute(db_manager) context = list(rv) return render_template('result.html', context=context) @main_api.route('/insertResult', methods=['POST', 'GET']) def insertResult(): if request.method == 'POST': result = request.form queryBuilder = QueryBuilder() set_db = queryBuilder.use_db(result) query = queryBuilder.build_insert(result) print(result) assert result db_manager = DbManager(root_path) parser = QueryParser() cmd = parser.parse(set_db) rv = cmd.execute(db_manager) cmd = parser.parse(query) rv = cmd.execute(db_manager) return render_template('insertResutl.html') @main_api.route('/deleteResult', methods=['POST', 'GET']) def deleteResult(): if request.method == 'POST': result = request.form queryBuilder = QueryBuilder() set_db = queryBuilder.use_db(result) query = queryBuilder.build_delete(result) print(result) assert result db_manager = DbManager(root_path) parser = QueryParser() cmd = parser.parse(set_db) rv = cmd.execute(db_manager) cmd = parser.parse(query) rv = cmd.execute(db_manager) return render_template('deleteResult.html') @main_api.route('/updateResult', methods=['POST', 'GET']) def updateResult(): if request.method == 'POST': result = request.form queryBuilder = QueryBuilder() set_db = queryBuilder.use_db(result) print(result) assert result query = queryBuilder.build_update(result) db_manager = DbManager(root_path) parser = QueryParser() cmd = parser.parse(set_db) rv = cmd.execute(db_manager) cmd = parser.parse(query) rv = cmd.execute(db_manager) return render_template('updateResult.html')
from flask import Blueprint, render_template, request from sdbms.app.service.builder import QueryBuilder from sdbms.core._manager import DbManager from sdbms.core._parser import QueryParser, CommandError """ Web api that builds the query and sends it to the query manager. Each route will represent a different CRUD operation and for each operation you will need to send a form with the certain data, and as result we will receive a html page. 1.'/' we will display the menu that will give you all the hiperlinks for each operation. 2.'/select' page used for building the select query. Some fields of this form ar optional. As a result, you will receive a page witch contains the selected rows. 3.'/insert' page used for building the insert query. For this one you will need to press the '+' button and fill the fields. As a response, you will receive a success message or an exception if something went wrong 4.'/delete' page use for deleting a row. As a response you will receive success or expcetion. 5.'/update' page used for updating a row. You will need to fill the labels, conditions and values. As a response you will receive a successs message or an exception. """ root_path = "/Users/cernescustefan/Documents/Facultate/db" main_api = Blueprint('main', __name__, template_folder='templates') @main_api.route('/', methods=['GET']) def index(): return render_template('index.html') @main_api.route('/select', methods=['GET']) def select(): return render_template('select.html') @main_api.route('/insert', methods=['GET']) def insert(): return render_template('insert.html') @main_api.route('/delete', methods=['GET']) def delete(): return render_template('delete.html') @main_api.route('/update', methods=['GET']) def update(): return render_template('update.html') @main_api.route('/result', methods=['POST', 'GET']) def result(): if request.method == 'POST': result = request.form queryBuilder = QueryBuilder() set_db = queryBuilder.use_db(result) query = queryBuilder.build_select(result) print(result) db_manager = DbManager(root_path) parser = QueryParser() cmd = parser.parse(set_db) rv = cmd.execute(db_manager) cmd = parser.parse(query) rv = cmd.execute(db_manager) context = list(rv) return render_template('result.html', context=context) @main_api.route('/insertResult', methods=['POST', 'GET']) def insertResult(): if request.method == 'POST': result = request.form queryBuilder = QueryBuilder() set_db = queryBuilder.use_db(result) query = queryBuilder.build_insert(result) print(result) assert result db_manager = DbManager(root_path) parser = QueryParser() cmd = parser.parse(set_db) rv = cmd.execute(db_manager) cmd = parser.parse(query) rv = cmd.execute(db_manager) return render_template('insertResutl.html') @main_api.route('/deleteResult', methods=['POST', 'GET']) def deleteResult(): if request.method == 'POST': result = request.form queryBuilder = QueryBuilder() set_db = queryBuilder.use_db(result) query = queryBuilder.build_delete(result) print(result) assert result db_manager = DbManager(root_path) parser = QueryParser() cmd = parser.parse(set_db) rv = cmd.execute(db_manager) cmd = parser.parse(query) rv = cmd.execute(db_manager) return render_template('deleteResult.html') @main_api.route('/updateResult', methods=['POST', 'GET']) def updateResult(): if request.method == 'POST': result = request.form queryBuilder = QueryBuilder() set_db = queryBuilder.use_db(result) print(result) assert result query = queryBuilder.build_update(result) db_manager = DbManager(root_path) parser = QueryParser() cmd = parser.parse(set_db) rv = cmd.execute(db_manager) cmd = parser.parse(query) rv = cmd.execute(db_manager) return render_template('updateResult.html')
en
0.870266
Web api that builds the query and sends it to the query manager. Each route will represent a different CRUD operation and for each operation you will need to send a form with the certain data, and as result we will receive a html page. 1.'/' we will display the menu that will give you all the hiperlinks for each operation. 2.'/select' page used for building the select query. Some fields of this form ar optional. As a result, you will receive a page witch contains the selected rows. 3.'/insert' page used for building the insert query. For this one you will need to press the '+' button and fill the fields. As a response, you will receive a success message or an exception if something went wrong 4.'/delete' page use for deleting a row. As a response you will receive success or expcetion. 5.'/update' page used for updating a row. You will need to fill the labels, conditions and values. As a response you will receive a successs message or an exception.
2.844118
3
extraPackages/Pillow-6.0.0/Tests/test_uploader.py
dolboBobo/python3_ios
130
6623192
<filename>extraPackages/Pillow-6.0.0/Tests/test_uploader.py from .helper import PillowTestCase, hopper class TestUploader(PillowTestCase): def check_upload_equal(self): result = hopper('P').convert('RGB') target = hopper('RGB') self.assert_image_equal(result, target) def check_upload_similar(self): result = hopper('P').convert('RGB') target = hopper('RGB') self.assert_image_similar(result, target, 0)
<filename>extraPackages/Pillow-6.0.0/Tests/test_uploader.py from .helper import PillowTestCase, hopper class TestUploader(PillowTestCase): def check_upload_equal(self): result = hopper('P').convert('RGB') target = hopper('RGB') self.assert_image_equal(result, target) def check_upload_similar(self): result = hopper('P').convert('RGB') target = hopper('RGB') self.assert_image_similar(result, target, 0)
none
1
2.27951
2
Behavioral-Patterns/Interpreter/lexing_and_parsing.py
PratikRamdasi/Design-Patterns-in-Python
0
6623193
# Evaluate numerical expression from enum import Enum, auto class Token: # Token can be anything - numeric INT value or brackets class Type(Enum): INTEGER = auto() PLUS = auto() MINUS = auto() LPAREN = auto() # left paranthesis RPAREN = auto() # right paranthesis def __init__(self, type, text): # takes the type of token and associated text with it # (for printing the text mainly) self.type = type self.text = text def __str__(self): return f'`{self.text}`' # see whitespace by using ` ` def lex(input): # input is a string result = [] i = 0 while(i < len(input)): # check every char - 1 char if input[i] == '+': result.append(Token(Token.Type.PLUS, '+')) elif input[i] == '-': result.append(Token(Token.Type.MINUS, '-')) elif input[i] == '(': result.append(Token(Token.Type.LPAREN, '(')) elif input[i] == ')': result.append(Token(Token.Type.RPAREN, ')')) # integer - more than 1 char else: digits = [input[i]] for j in range(i+1, len(input)): if input[j].isdigit(): digits.append(input[j]) i += 1 else: # digit parsing done, generate token for it -> 13, 4, 12, 1 result.append(Token(Token.Type.INTEGER, ''.join(digits))) break i += 1 return result ## Parsing ## # takes tokens and returns objcect oriented structure # integer object class Integer: def __init__(self, value): self.value = value # binary expression -> +, - etc class BinaryExpression: class Type(Enum): ADDITION = 0 SUBTRACTION = 1 def __init__(self): self.type = None self.left = None # left side of expression self.right = None # right side of expression # calculate value of expression @property def value(self): if self.type == self.Type.ADDITION: return self.left.value + self.right.value else: return self.left.value - self.right.value # Assume final expression is always binary expression def parse(tokens): result = BinaryExpression() # flag to put at LHS or RHS have_lhs = False i = 0 while i < len(tokens): token = tokens[i] if token.type == Token.Type.INTEGER: # put integer value into Integer object defined above integer = Integer(int(token.text)) if not have_lhs: result.left = integer have_lhs = True else: result.right = integer elif token.type == Token.Type.PLUS: # modify current binary expression result.type = BinaryExpression.Type.ADDITION elif token.type == Token.Type.MINUS: # modify current binary expression result.type = BinaryExpression.Type.SUBTRACTION # open and close paranthesis # need to get sub expression and assign at proper left/right location elif token.type == Token.Type.LPAREN: # find right paranthesis to get the subex j = i while j < len(tokens): if tokens[j].type == Token.Type.RPAREN: break j += 1 subexpression = tokens[i+1:j] # parse subexpression recursively element = parse(subexpression) if not have_lhs: result.left = element have_lhs = True else: result.right = element i = j # to the starting of next subexpression i += 1 return result def calc(input): # split input into tokens tokens = lex(input) # turn tokens as string print(' '.join(map(str, tokens))) # parse the tokens parsed = parse(tokens) # print final result print(f'{input} = {parsed.value}') if __name__ == "__main__": calc('(13+4)-(12+1)') # 4
# Evaluate numerical expression from enum import Enum, auto class Token: # Token can be anything - numeric INT value or brackets class Type(Enum): INTEGER = auto() PLUS = auto() MINUS = auto() LPAREN = auto() # left paranthesis RPAREN = auto() # right paranthesis def __init__(self, type, text): # takes the type of token and associated text with it # (for printing the text mainly) self.type = type self.text = text def __str__(self): return f'`{self.text}`' # see whitespace by using ` ` def lex(input): # input is a string result = [] i = 0 while(i < len(input)): # check every char - 1 char if input[i] == '+': result.append(Token(Token.Type.PLUS, '+')) elif input[i] == '-': result.append(Token(Token.Type.MINUS, '-')) elif input[i] == '(': result.append(Token(Token.Type.LPAREN, '(')) elif input[i] == ')': result.append(Token(Token.Type.RPAREN, ')')) # integer - more than 1 char else: digits = [input[i]] for j in range(i+1, len(input)): if input[j].isdigit(): digits.append(input[j]) i += 1 else: # digit parsing done, generate token for it -> 13, 4, 12, 1 result.append(Token(Token.Type.INTEGER, ''.join(digits))) break i += 1 return result ## Parsing ## # takes tokens and returns objcect oriented structure # integer object class Integer: def __init__(self, value): self.value = value # binary expression -> +, - etc class BinaryExpression: class Type(Enum): ADDITION = 0 SUBTRACTION = 1 def __init__(self): self.type = None self.left = None # left side of expression self.right = None # right side of expression # calculate value of expression @property def value(self): if self.type == self.Type.ADDITION: return self.left.value + self.right.value else: return self.left.value - self.right.value # Assume final expression is always binary expression def parse(tokens): result = BinaryExpression() # flag to put at LHS or RHS have_lhs = False i = 0 while i < len(tokens): token = tokens[i] if token.type == Token.Type.INTEGER: # put integer value into Integer object defined above integer = Integer(int(token.text)) if not have_lhs: result.left = integer have_lhs = True else: result.right = integer elif token.type == Token.Type.PLUS: # modify current binary expression result.type = BinaryExpression.Type.ADDITION elif token.type == Token.Type.MINUS: # modify current binary expression result.type = BinaryExpression.Type.SUBTRACTION # open and close paranthesis # need to get sub expression and assign at proper left/right location elif token.type == Token.Type.LPAREN: # find right paranthesis to get the subex j = i while j < len(tokens): if tokens[j].type == Token.Type.RPAREN: break j += 1 subexpression = tokens[i+1:j] # parse subexpression recursively element = parse(subexpression) if not have_lhs: result.left = element have_lhs = True else: result.right = element i = j # to the starting of next subexpression i += 1 return result def calc(input): # split input into tokens tokens = lex(input) # turn tokens as string print(' '.join(map(str, tokens))) # parse the tokens parsed = parse(tokens) # print final result print(f'{input} = {parsed.value}') if __name__ == "__main__": calc('(13+4)-(12+1)') # 4
en
0.71128
# Evaluate numerical expression # Token can be anything - numeric INT value or brackets # left paranthesis # right paranthesis # takes the type of token and associated text with it # (for printing the text mainly) # see whitespace by using ` ` # input is a string # check every char - 1 char # integer - more than 1 char # digit parsing done, generate token for it -> 13, 4, 12, 1 ## Parsing ## # takes tokens and returns objcect oriented structure # integer object # binary expression -> +, - etc # left side of expression # right side of expression # calculate value of expression # Assume final expression is always binary expression # flag to put at LHS or RHS # put integer value into Integer object defined above # modify current binary expression # modify current binary expression # open and close paranthesis # need to get sub expression and assign at proper left/right location # find right paranthesis to get the subex # parse subexpression recursively # to the starting of next subexpression # split input into tokens # turn tokens as string # parse the tokens # print final result # 4
3.860278
4
btdata.py
bstitt79/muzero-general
0
6623194
<reponame>bstitt79/muzero-general<filename>btdata.py<gh_stars>0 companies = [ 'OEDV', 'AAPL', 'BAC', 'AMZN', 'T', 'GOOG', 'MO', 'DAL', 'AA', 'AXP', 'DD', 'BABA', 'ABT', 'UA', 'AMAT', 'AMGN', 'AAL', 'AIG', 'ALL', 'ADBE', 'GOOGL', 'ACN', 'ABBV', 'MT', 'LLY', 'AGN', 'APA', 'ADP', 'APC', 'AKAM', 'NLY', 'ABX', 'ATVI', 'ADSK', 'ADM', 'BMH.AX', 'WBA', 'ARNA', 'LUV', 'ACAD', 'PANW', 'AMD', 'AET', 'AEP', 'ALXN', 'CLMS', 'AVGO', 'EA', 'DB', 'RAI', 'AEM', 'APD', 'AMBA', 'NVS', 'APOL', 'ANF', 'LULU', 'RAD', 'BRK.AX', 'ARRY', 'AGNC', 'JBLU', 'A', 'ORLY', 'FOLD', 'AZO', 'ATML', 'AN', 'AZN', 'AES', 'GAS', 'BUD', 'ARR', 'BDX', 'AKS', 'AB', 'ACOR', 'CS', 'AFL', 'ADI', 'AEGR', 'ACIW', 'AMP', 'AVP', 'AMTD', 'AEO', 'AWK', 'NVO', 'ALTR', 'ALK', 'PAA', 'MTU.AX', 'ARCC', 'AAP', 'NAT', 'FNMA', 'FAV', 'AIV', 'AGIO', 'AEE', 'UBS', 'AVXL', 'ARLP', 'ANTM', 'AGU', 'AG', 'AFSI', 'ABC', 'STO', 'ATI', 'ADT', 'AVB', 'ATW', 'ALNY', 'LH', 'AVY', 'AUY', 'ASH', 'ARMH', 'ARIA', 'ANR', 'AINV', 'ACXM', 'ACHN', 'ACET', 'ABMD', 'ABM', 'VA', 'LIFE', 'ATO', 'ARP', 'AON', 'ADXS', 'ADC', 'APU', 'SAVE', 'AV', 'AKRX', 'ADS', 'ABAX', 'AYI', 'AWH', 'ASML', 'AMT', 'ALDR', 'ACM', 'DWA', 'ATRS', 'ARW', 'ARI', 'ARG', 'AR', 'AMCC', 'AMC', 'AL', 'AGEN', 'AAN', 'WTR', 'FCAU', 'BAH', 'AXAS', 'AVT', 'ALB', 'AIZ', 'SAIC', 'CAR', 'AXLL', 'AU', 'ARO', 'APH', 'ANTH', 'AMX', 'AMDA', 'AI', 'ABCO', 'WMC', 'MPX.AX', 'JKHY', 'AVAV', 'AMKR', 'ALJ', 'ACH', 'GPH.AX', 'ERC', 'APPY', 'ANAC', 'AEIS', 'Y', 'MTGE', 'CENX', 'ASPS', 'AMRN', 'AMPE', 'AMAG', 'ALKS', 'AFFX', 'ADES', 'ACAT', 'AAON', 'XLRN', 'VRSK', 'VJET', 'OA', 'ATLS', 'APTS', 'APO', 'ALSK', 'ALG', 'AHC', 'ACTG', 'ACAS', 'RBA', 'MAA', 'BAM', 'ATHN', 'AT', 'ASX', 'ARCO', 'ANET', 'ANCX', 'AIR', 'AF', 'WAB', 'RS', 'PKG', 'CSH', 'AXDX', 'AVHI', 'AVA', 'ATHX', 'ARWR', 'ANGI', 'AMG', 'ALSN', 'ALGN', 'AKBA', 'AGO', 'AEZS', 'ACRX', 'ROK', 'GLPI', 'DNI', 'AZZ', 'ATRC', 'ARRS', 'ARMK', 'AOS', 'ANFI', 'AMID', 'AMCX', 'ALIM', 'ALE', 'AHT', 'ACW', 'ABB', 'AALI.JK', 'SPR', 'SEE', 'RDEN', 'PAAS', 'DLPH', 'ADAC', 'CBL', 'BBVA', 'AYR', 'APOG', 'ANDE', 'AMSC', 'AMRS', 'AMED', 'ALEX', 'ALCO', 'ADUS', 'ACTA', 'ACST', 'AAWW', 'WMS', 'PAG', 'MDRX', 'KLIC', 'ETH', 'AZPN', 'AXE', 'ATNY', 'APRI', 'AMH', 'AME', 'AJG', 'AIQ', 'AHGP', 'AGCO', 'AERI', 'ACRE', 'ABEO', 'WAL', 'SYT', 'SHLM', 'NOG', 'HTA', 'GIII', 'DAVE', 'CVU', 'BSI', 'AWAY', 'ATU', 'ASTI', 'AREX', 'ARE', 'ANSS', 'AMNB', 'AMBS', 'ALR', 'AIXG', 'AIN', 'AHL', 'AGX', 'AEG', 'ADTN', 'ADMS', 'ACLS', 'ABG', 'ZX', 'NXJ', 'KS', 'HOLI', 'GPI', 'ENI', 'BEAV', 'AXTA', 'AWR', 'AWI', 'AVEO', 'AUO', 'ATHM', 'ATAX', 'ASM', 'AROC', 'ANH', 'ALX', 'AHS', 'AGI', 'AER', 'AE', 'RHHBY', 'PETX', 'ODC', 'NAO', 'KAR', 'HUSA', 'HIVE', 'FMS', 'DOX', 'CXW', 'AZUR', 'AXS', 'AXL', 'AWX', 'AVID', 'ASNA', 'ASGN', 'ARDX', 'ARAY', 'AQXP', 'APT', 'APDN', 'AMBC', 'ALGT', 'ALDW', 'AIT', 'AIRM', 'AIMC', 'AEL', 'AEHR', 'ADHD', 'ACUR', 'ACHC', 'ACFC', 'ACCO', 'ABY', 'TA', 'RPAI', 'MANH', 'LAMR', 'KYN', 'AXN', 'ATRO', 'ATNI', 'ARCW', 'APEI', 'AP', 'ANIK', 'ANGO', 'AMTG', 'AMSG', 'AMOT', 'AM', 'ALV', 'ALOG', 'AKR', 'AEGN', 'ADS.DE', 'ZLTQ', 'WRLD', 'UHAL', 'UAMY', 'SAH', 'RJET', 'NAII', 'AQNM', 'CAS', 'CACC', 'ATSG', 'ASEI', 'ASB', 'ARTX', 'AROW', 'ARCB', 'AMRK', 'ALRM', 'AHP', 'AGRX', 'AFAM', 'ADK', 'ACSF', 'ABTL', 'ABGB', 'ABEV', 'ABCD', 'AAOI', 'USAP', 'STFC', 'STAY', 'SEED', 'RGA', 'IDSA', 'HART', 'CH', 'CEA', 'BREW', 'AXR', 'AVG', 'AVD', 'AUDC', 'ATRI', 'ATOS', 'ARC', 'APIC', 'AOSL', 'AOI', 'AMWD', 'ALXA', 'ALLY', 'AIRI', 'AFOP', 'ACGL', 'ACFN', 'ABR', 'ABCB', 'SAMG', 'REXI', 'RAIL', 'NSAM', 'MITT', 'LCM', 'HASI', 'GOL', 'GIL', 'EAD', 'ATTO', 'ATR', 'ATNM', 'ASTC', 'ASR', 'ASC', 'ARTNA', 'ARGS', 'AOD', 'AGNCP', 'ADRO', 'ACNB', 'AAV', 'AAT', 'ZNH', 'UAM', 'NTT', 'NFJ', 'LNT', 'KALU', 'HOMB', 'HIX', 'FAF', 'FAC', 'EGT', 'CAAS', 'BGR', 'BETR', 'AUPH', 'ATV', 'ATLC', 'AST', 'ARIS', 'ARCI', 'APLE', 'ANY', 'ANIP', 'AMSWA', 'AMSF', 'ALLT', 'AKTX', 'AGYS', 'AGTC', 'AFG', 'ADDYY', 'AAVL', 'WAIR', 'RESI', 'LND', 'LFL', 'HRT', 'ESD', 'ECF', 'DGLY', 'CIK', 'CII', 'CHOP', 'CCD', 'CADC', 'AYA', 'AWRE', 'AVV', 'AVNW', 'ATRM', 'APPF', 'AFFMQ', 'AMRI', 'AMCN', 'AMCF', 'ALTI', 'ALLE', 'AJRD', 'AHH', 'AGM', 'AGII', 'AFCB', 'AEPI', 'ADMA', 'ABCW', 'AAME', 'TEO', 'SRAQU', 'SINO', 'OMAB', 'NOA', 'NCZ', 'MTT', 'MHG', 'JAGX', 'ISL', 'HIO', 'GRR', 'FAX', 'ENL', 'DIT', 'CRMT', 'CRESY', 'CGA', 'CAF', 'ATRA', 'ATEN', 'ATEC', 'ARLZ', 'ARII', 'ARDM', 'ARDC', 'ARCX', 'APPS', 'APHB', 'ANW', 'ANAT', 'ANAD', 'AKAO', 'AGHI', 'AETI', 'AEB', 'ADPT', 'ADMP', 'ACRS', 'ACC', 'ABEOW', 'ABDC', 'REX', 'PAC', 'NNA', 'NAUH', 'IGD', 'HMNY', 'GABC', 'ERH', 'EPAX', 'CACQ', 'BTI', 'AXPW', 'AWF', 'AVX', 'ASUR', 'ASMB', 'ASFI', 'ASCMA', 'ASCC', 'ARES', 'ARCP', 'AQMS', 'ANCB', 'AMRC', 'AMOV', 'AKG', 'AFW', 'ACY', 'ACPW', 'ABIO', 'AAC', 'XKE', 'VLRS', 'PRA.AX', 'TEAM', 'SORL', 'NEN', 'NEA', 'LMIA', 'JEQ', 'IGA', 'IDE', 'GBAB', 'FWP', 'EVTC', 'CMGE', 'CHY', 'CADTU', 'BTZ', 'BAYN.DE', 'AXU', 'AWP', 'ATE', 'ATAI', 'ARQL', 'ARKR', 'APP', 'APLP', 'APF', 'APB', 'AMRB', 'AMBR', 'ALU.PA', 'ALQA', 'ALOT', 'AKER', 'AIB', 'AHPI', 'AGRO', 'AFST', 'ADX', 'ADGE', 'ADAT', 'ADAP', 'ACU', 'ACTS', 'WJA.TO', 'VLKAY', 'TKC', 'AQQSQ', 'SCOK', 'RZA', 'PWX', 'PRTS', 'POPE', 'PEO', 'OASM', 'NCV', 'NBB', 'NADL', 'MHY', 'MHF', 'IOTS', 'HYB', 'GAM', 'EOD', 'EAGL', 'DLA', 'CBA', 'BRKS', 'AVK', 'AUMAU', 'AUBN', 'ASYS', 'ASA', 'AMPH', 'AMIC', 'AMFW', 'ALJJ', 'ALDX', 'AGR', 'AGD', 'AFC', 'AFA', 'AEY', 'AEK', 'ADVS', 'ABUS', 'ABLX.BR', 'AAPC', 'TANN', 'SHOS', 'RYAM', 'RJETQ', 'PAHC', 'NAC', 'MZA', 'MGR', 'HYI', 'GNOW', 'FWRD', 'FEN', 'FEI', 'DAI.DE', 'CHLN', 'CALI', 'AXON', 'AXGN', 'AVH', 'AVAL', 'AUMN', 'ATL', 'ASRVP', 'ASRV', 'ASBI', 'ASBB', 'ARTW', 'APWC', 'APAM', 'AMS', 'AMFC', 'ALN', 'AGFS', 'AFGE', 'AEMD', 'ADNC', 'ACV', 'ACG', 'ACBI', 'ABTX', 'AAMC', 'UNAM', 'TVE', 'TVC', 'SGF', 'SCAI', 'HVCW', 'OMAM', 'NSA', 'NKG', 'NAD', 'MTGEP', 'MPAA', 'LDP', 'JRI', 'JAX', 'IF', 'GGM', 'ETF', 'EARS', 'EADSY', 'DMO', 'DEX', 'AZSEY', 'AXX', 'AXTI', 'AVXS', 'AUQ', 'ATTU', 'ATLO', 'ASTE', 'ASND', 'ARL', 'APTO', 'AMTX', 'AKP', 'AI.PA', 'AGIIL', 'AFMD', 'AFFY', 'AFB', 'AEUA', 'ADEP', 'ABIL', 'ABAC', 'WIW', 'WGA', 'TRAN.BA', 'ICG.AX', 'SBI', 'RKDA', 'PSF', 'NAZ', 'MNP', 'MMU', 'DLS.AX', 'JTA', 'IPCC', 'IAF', 'IAE', 'GCP', 'FTAI', 'FNTCU', 'FGB', 'FCO', 'EMD', 'EAA', 'DDAIF', 'QED.L', 'CHI', 'CEE', 'CADTW', 'BUI', 'AXSM', 'ANOS', 'ANCI', 'ALTV', 'ALAN', 'AKZOY', 'AKO-A', 'AJX', 'AGNCB', 'AFSD', 'AFH', 'AEGG', 'ACP', 'ABRN', 'CLA.AX', 'WRN', 'USA', 'OXXCB.AX', 'CBS.AX', 'PHX', 'NZH', 'KYE', 'KLREU', 'JCE', 'JBR', 'JBK', 'IGZ', 'IGI', 'HOPS', 'HDRA', 'GS.TO', 'GRO', 'GPACU', 'GER', 'ELEC', 'EGIF', 'DYSL', 'CNLM', 'CLAC', 'CACG', 'BTA', 'BRSS', 'BLVDW', 'BLVD', 'AYA.TO', 'AVLY', 'AUMAW', 'ATP.TO', 'ASMI', 'ASKH', 'ARUN', 'AREN', 'ARCPP', 'AMSGP', 'AMRH', 'ALTX', 'ALA.TO', 'AKG.TO', 'AIY', 'AIR.PA', 'AIMT', 'AIF', 'AERG', 'AED', 'ADXSW', 'ACLZ', 'ABX.TO', 'ABAT', 'AAAP', '6599.KL', 'WIA', 'WEA', 'VKI', 'VELCP.AX', 'TRTLW', 'TRTL', 'SKAS', 'SCD', 'RUK', 'ROIQ', 'QPACW', 'QPACU', 'AMLH', 'PZE', 'PAI', 'PAA.TO', 'ORG.AX', 'NXZ', 'NORD', 'NMA', 'NKX', 'NBRV', 'MOG-A', 'MAV', 'LDF', 'JSYNU', 'JPI', 'JBN', 'HDRAW', 'HDRAU', 'HCACW', 'GTATQ', 'GPIAW', 'GGZ', 'GGACW', 'GCH', 'GAI', 'FNTC', 'FBGX', 'EXD', 'EHI', 'EAE', 'DRA', 'DFP', 'DDF', 'CVB', 'CS.PA', 'CNLMR', 'CLAD', 'BLVDU', 'BHAC', 'BGY', 'BBD-A.TO', 'BAM-A.TO', 'AVNU', 'AVL', 'AVL.TO', 'ATH.TO', 'ASG', 'ARU', 'AQA.TO', 'ANZ.AX', 'ANTX', 'ANTM.JK', 'ANSU', 'ANRZQ', 'ANDAU', 'ALYI', 'ALO.PA', 'ALLM', 'ALLB', 'AIRT', 'AIC', 'AFFM', 'ADN.L', 'AC', 'AC.PA', 'ABI.BR', 'ZERO', 'XRF.AX', 'WOW.AX', 'WDI.DE', 'WAT.AX', 'VOLVY', 'TRTLU', 'TPZ', 'ABEC', 'SIEGY', 'SDCJF', 'ROIQW', 'ROIQU', 'QPAC', 'QBE.AX', 'ARN.V', 'PAACR', 'ORT.TO', 'NZF', 'NVX', 'NVG', 'NUW', 'NIE', 'MYHI', 'MT.AS', 'MHNB', 'MDG.AX', 'LAQ', 'KED', 'IAG.TO', 'HJV', 'GLV', 'FIEE', 'VTX.AX', 'ELECU', 'EACQU', 'CNLMU', 'CAMBU', 'BXB.AX', 'BHP.AX', 'AXPWW', 'AV.L', 'ATLN.VX', 'ATA.TO', 'ASPN', 'ASII.JK', 'ARWAW', 'ARBV', 'AOXY', 'AOGN', 'ALV.DE', 'ALOD', 'AKRA.JK', 'AKO-B', 'AINC', 'AGU.TO', 'AGFSW', 'AFFW', 'AFCO', 'AERT', 'AEH', 'AEGA', 'AD.TO', 'ACNV', 'ABHD', 'ABCP', 'AAU', '3264.TWO', 'WVL.AX', 'WRR.AX', 'TANP', 'TANO', 'STO.AX', 'SMCG', 'SMACU', 'SBW', 'RGX.TO', 'AXXE', 'PACQF', 'NRBAY', 'NHH.AX', 'NEN.AX', 'NDO.AX', 'MQG.AX', 'MLPB', 'MHNC', 'MHNA', 'MCX.AX', 'KTE.AX', 'KIK.AX', 'AET-UN.TO', 'JDD', 'IPT.AX', 'IMMA', 'IAIC', 'HNNA', 'HCACU', 'GYC', 'GTN-A', 'GPIA', 'GGACU', 'GGAC', 'GFY', 'GDF', 'FSAM', 'FMAO', 'FCAM', 'ECACU', 'EAGLW', 'EAGLU', 'DLYT', 'CRP.TO', 'CAMBW', 'BMP.AX', 'BHACU', 'BBCA.JK', 'AVTH', 'AVOI', 'AVGR', 'AUXO', 'AUNFF', 'AUNB', 'ATOC', 'ATEA', 'ATD-B.TO', 'ASNB', 'ASCCF', 'ARX.TO', 'ARWA', 'ARTH', 'ARGB', 'APIC.JK', 'ANDA', 'ANAS', 'AMPG', 'AMNF', 'AMEH', 'AMBOY', 'ALB.TO', 'AKSO.OL', 'AHT.L', 'AHONY', 'AFSS', 'AFN.TO', 'AFGH', 'AF.PA', 'AEYE', 'AERO', 'ADVC', 'ACIIQ', 'ACDVF', 'ABBB', 'ZYL.AX', 'WTER', 'WPL.AX', 'WNS.AX', 'WIHL.ST', 'WHC.AX', 'WES.AX', 'WDS.AX', 'WCC.AX', 'VWS.CO', 'AAWC', 'VOLV-B.ST', 'VMS.AX', 'VKA.AX', 'UCW.AX', 'TZL.AX', 'TWCF', 'TRZ-B.TO', 'TLS.AX', 'TGRO', 'TFECY', 'SXL.AX', 'SUGO', 'STL.OL', 'CBAI', 'SMACR', 'SIGL', 'SCA-A.ST', 'SAS.TO', 'SAS.ST', 'ROG.VX', 'REZT.ST', 'REA.AX', 'RBA.TO', 'LEAS', 'PRVW', 'VBPS.VI', 'PDL.TO', 'PBD.AX', 'PACT.ST', 'PAAC', 'OPEI', 'NXK', 'NMS.AX', 'NME.AX', 'NHYDY', 'NFE.AX', 'NBD', 'NAEY', 'NAB.AX', 'MDA.TO', 'LUND-B.ST', 'LO3.DE', 'LMFA', 'LGI', 'LER.AX', 'LCT.AX', 'LAU.AX', 'LAME4.SA', 'KOV.AX', 'KME.AX', 'KBC.AX', 'JMLP', 'IVX.DE', 'IRI.AX', 'IREBY', 'IGAP', 'IBO', 'ALME', 'HLDX.ST', 'HIL.AX', 'HDRAR', 'HCAC', 'HADV', 'GPIAU', 'GPACW', 'GIL.TO', 'GGACR', 'GDO', 'GCV', 'FUTU', 'RSTA.DE', 'AWON', 'FNTCW', 'FBAK', 'FABK', 'ESOA', 'ELUXY', 'ECEX.ST', 'ECACR', 'EACQW', 'EAB', 'E5H.SI', 'DTEGY', 'DNSKY', 'DBRM', 'CPU.AX', 'CMW.AX', 'UAHC', 'CLAS-B.ST', 'CLACU', 'CEAI', 'CBA.AX', 'CARL-B.CO', 'CADT', 'BOE.V', 'BILL.ST', 'BHARTIARTL.NS', 'BHACR', 'BBTO-B.ST', 'BBG.AX', 'BAYRY', 'BAC-PL', 'AZN.L', 'AXY.TO', 'AXST', 'AXIH', 'AXFO.ST', 'AXAHY', 'AUSI', 'ATD-A.TO', 'ATAR', 'ASURB.MX', 'ASML.AS', 'ASHOKLEY.NS', 'ASHG', 'ASCS', 'AQN.TO', 'AQ.V', 'APY.TO', 'APDNW', 'APBR.BA', 'AOREF', 'ANPDF', 'ANN.AX', 'ANAV', 'AMUB', 'AMPLQ', 'AMM.TO', 'AMIN', 'AMBZ', 'AMBTQ', 'AMAVF', 'ALYE', 'ALSE', 'ALRT', 'ALNPY', 'ALN.V', 'ALMG', 'ALEHT.PA', 'AKTS', 'AJX.TO', 'AIM.TO', 'AHII', 'AHFP', 'AGL.L', 'AGIN', 'AFSE', 'AFBG', 'AEM.TO', 'ADTM', 'ADMF.JK', 'ADLS', 'ADHI.JK', 'ADES.JK', 'ACQ.TO', 'ACCA', 'ABNK', 'ABKI', '0522.HK', 'PNA.AX', 'ZRL.AX', 'ZGL.AX', 'XDC.TO', 'XANO-B.ST', 'WWRB', 'WWASA.OL', 'WSA.AX', 'WOR.AX', 'WETM', 'WEC.AX', 'WBC.NZ', 'WBC.AX', 'WBA.AX', 'WALMEX.MX', 'VWS.DE', 'SDL.AX', 'VOIL', 'VIP.AX', 'VII.AX', 'VIE.AX', 'VBHLF', 'UGL.AX', 'UBAB', 'TPM.AX', 'TGZ.AX', 'TGR.AX', 'TCN.AX', 'TCL.AX', 'TCL-A.TO', 'SUD.AX', 'STWRY', 'RRS.AX', 'ARCS', 'SKFRY', 'SIPH.PA', 'SAND.ST', 'RWEOY', 'RKET.DE', 'RHC.AX', 'RAFI', 'QUBSF', 'PTPF', 'PRKA', 'PLS.AX', 'PETS.L', 'PAEKY', 'PAACU', 'OZL.AX', 'OTS.OL', 'OSI.PA', 'ORXOY', 'ORK.OL', 'OKU.AX', 'NSX.AX', 'NOEJ.DE', 'NOE.AX', 'NOA.TO', 'NML.AX', 'MYR.AX', 'MTN.MX', 'MT.PA', 'MQ.ST', 'MOC.AX', 'MMR.AX', 'MLPZ', 'MLPQ', 'MKO.AX', 'MHM', 'LUPE.ST', 'LSPN.DE', 'LNR.AX', 'LMFAU', 'LAS.L', 'KRS.AX', 'KNH.AX', 'KMF', 'KLREW', 'KLRE', 'KKT.AX', 'KINV-B.ST', 'KAS.AX', 'JRV.AX', 'JOES', 'ORS.AX', 'IOX.OL', 'INPC.JK', 'IMU.AX', 'ILU.AX', 'IFNNY', 'HWO.TO', 'HVN.AX', 'HISP', 'HGKGF', 'GPAC', 'GOOG.MX', 'GNGBY', 'GNC.AX', 'GML.AX', 'GLUX', 'GID.AX', 'FLY.V', 'FHZN.SW', 'FFMH', 'ELDO', 'EKO.OL', 'SOUL', 'EBKDY', 'DUNI.ST', 'DNO.OL', 'DFF', 'USAE', 'DANSKE.CO', 'CSCO.BA', 'CRZBY', 'COME.BA', 'COH.AX', 'CITY', 'CISAW', 'CIG-C', 'CHOPF', 'SPX.AX', 'ABHI', 'CCLAY', 'CAFO.PA', 'CADTR', 'CACGW', 'BVB.DE', 'BST', 'BPTY.L', 'BLD.AX', 'BHIP.BA', 'BEN.AX', 'BEIJ-B.ST', 'BCS-PD', 'BCAUY', 'BBVA.MC', 'BAOXF', 'BAMXY', 'AZZEF', 'AXS.L', 'AXRX', 'AXIM', 'AXANF', 'AVTS', 'AVMXY', 'AVBH', 'AUTCF', 'AUROPHARMA.NS', 'AUMA', 'AUE.TO', 'AU8U.SI', 'ATTBF', 'ASX.AX', 'ASR.TO', 'ASCK', 'ASAZY', 'ARZGY', 'ARWAU', 'ARWAR', 'ARNI', 'ARNGF', 'ARKAY', 'ARGKF', 'AREXMIS.BO', 'AR.TO', 'AQUA.OL', 'APVS', 'APO.V', 'APNI', 'APLN.JK', 'APEOF', 'ANZFF', 'ANDAW', 'ANDAR', 'ANA.MC', 'AMXL.MX', 'AMTY', 'AMTC', 'AMSE', 'AMSA', 'AMS.MC', 'AMRR', 'AMP.AX', 'AMKBY', 'AMCO', 'AMBK', 'AMAR', 'AMA.L', 'ALXDF', 'ALSMY', 'ALO.L', 'ALIOF', 'ALGI', 'ALALF', 'AKVA', 'AKT-B.TO', 'AKER.OL', 'AIQUY', 'AIII', 'AHRO', 'AHNR', 'AHF.TO', 'AH.AS', 'AGT.TO', 'AGPPY', 'AGM-A', 'AGI.TO', 'AGF-B.TO', 'AGESY', 'AFK.OL', 'AF.TO', 'ADW-A.TO', 'ADV.TO', 'ADRO.JK', 'ADGL', 'ADFT', 'ACUG', 'ACHI', 'ACD.TO', 'ABK-PC.TO', 'ABEV3.SA', 'ABE.MC', 'ABCE', 'AASP', 'AAPL.SW', 'AAPL.MX', 'AAL.L', 'AACAY', 'AAC.V', 'A23.SI', '5099.KL', '3DM.AX', 'IIN.AX', 'ZURVY', 'YAL.AX', 'ADCF', 'XTD.AX', 'WTR.AX', 'WHLKY', 'WFD.AX', 'WDAS', 'WCP.AX', 'WBAPA.AX', 'VLKPY', 'VLKAF', 'VELIN.AX', 'VBG-B.ST', 'UUL.AX', 'USG.AX', 'UOS.AX', 'UCM.AX', 'UBI.AX', 'UATG', 'TZN.AX', 'TWE.AX', 'TUIFF', 'TPI.AX', 'TPDKY', 'TOTRF', 'TMNSF', 'TMC.TO', 'TKGBY', 'TGS.AX', 'TEN.AX', 'TELNY', 'TARSF', 'AMPW', 'SZGPY', 'ARYX', 'SYIEF', 'SWGAY', 'SWGAF', 'SVNLF', 'STB.OL', 'SSHIP.OL', 'SPX.V', 'SOO.AX', 'KRA.AX', 'SMA.L', 'BTFL', 'SKBSY', 'SKA-B.ST', 'SIQ.AX', 'SIP.AX', 'SHV.AX', 'SEN.AX', 'SDF.AX', 'AIB.IR', 'SBM.AX', 'SAZ.DE', 'SAUHF', 'SAPA.DE', 'SANWARIA.NS', 'SAI.AX', 'SAAB-B.ST', 'RBX.AX', 'RUSF.ST', 'RO.SW', 'RMS.PA', 'RMP.L', 'RMLXP', 'RIS.AX', 'RIO.AX', 'RIGO.BA', 'RCMFF', 'RAD.DE', 'PYC.AX', 'PTBA.JK', 'PSSR', 'PSAHF', 'PSA.AX', 'PRDC', 'PPTG', 'PPT.AX', 'PNE3.DE', 'PNDZY', 'PMV.AX', 'AMFE', 'PHM7.DE', 'PGRD', 'PGPHF', 'AHIX', 'PEXNY', 'PEK.AX', 'PDN.AX', 'PBP.AX', 'PBAM', 'PAY.AX', 'PAN.AX', 'PACI', 'OSR.DE', 'ORKLY', 'ORI.AX', 'ORA.TO', 'OPESY', 'OPERA.OL', 'OMVKY', 'OFX.AX', 'O4B.DE', 'NVZMY', 'NVZMF', 'NVSEF', 'NTM.AX', 'NSP.AX', 'NRK', 'NOTE.ST', 'NOMI.ST', 'NOD.OL', 'NOD.AX', 'NLY-PA', 'NIO.AX', 'NIBE-B.ST', 'NHF.AX', 'NDX1.DE', 'NAN', 'NAF-UN.TO', 'NABZY', 'MYX.AX', 'MYN.AX', 'MURGY', 'MQA.AX', 'MOL.AX', 'MOEX.ME', 'MNY.AX', 'MLMAB.PA', 'MIG.AX', 'MGAM.L', 'MEDI.OL', 'MDD.AX', 'MAL.TO', 'MAJJ', 'MABA', 'MAAL', 'M6YA.DE', 'LTR.AX', 'LNNNF', 'LNEGY', 'LMFAW', 'LIC.AX', 'LIAB.ST', 'LEDE.BA', 'LCE.AX', 'LBT.AX', 'LAS-A.TO', 'LALAB.MX', 'AXL.TO', 'LA.V', 'KWA.V', 'KUKAY', 'KSB.DE', 'KPC.AX', 'KGM.AX', 'KGL.AX', 'KD8.DE', 'KBC.L', 'K1R.DE', 'JYC.AX', 'AWGI', 'JM.ST', 'J7X.SI', 'ITAB-B.ST', 'ISXIF', 'ISSJY', 'IPP.AX', 'IPLO', 'IPL.AX', 'IPD.AX', 'VC8.DE', 'ILMCF', 'IGO.AX', 'AM.TO', 'IAM.TO', 'IALB', 'HYDR.ME', 'HXGCF', 'HXGBY', 'HUTN', 'HUSQ-B.ST', 'HOKCY', 'HNB.OL', 'HIPH', 'HGKGY', 'HGHAF', 'HFA.AX', 'HEXA-B.ST', 'HENOY', 'HCIIP', 'HAW.AX', 'GXY.AX', 'GUD.AX', 'GMG.AX', 'TPET.L', 'GEN.CO', 'GEM.AX', 'GELYY', 'GEEK', 'GCS.AX', 'GCLA.BA', 'GBA.AX', 'GAP.AX', 'GAHC', 'G1A.DE', 'FSJ.L', 'FNMFN', 'FNMAL', 'FMG.AX', 'FLYLF', 'FGRPF', 'FEEL.ST', 'FASV', 'EXAD', 'EVTCY', 'ETPHF', 'ERCA.DE', 'ERAO', 'EOG.V', 'EME.AX', 'ELECW', 'ELD.AX', 'EFGXY', 'ECO.AX', 'ECAC', 'DVI.AX', 'DUO.AX', 'DUE.AX', 'DRX.TO', 'APYP', 'DPSGY', 'DMP.AX', 'DD-PB', 'DATI', 'CYAP', 'CVO.AX', 'CTP.AX', 'CSL.AX', 'CRYO', 'CPPCY', 'COP.DE', 'COLAY', 'COIC.ST', 'COGLF', 'CNLMW', 'CMWAY', 'CLC.TO', 'CLACW', 'LOGL', 'CHCR', 'SKYD.DE', 'CDD.AX', 'CDA.PA', 'CCLAF', 'CBAUF', 'CAMB.L', 'AMIEQ', 'CAI.VI', 'CACGU', 'BWL-A', 'BTT.AX', 'BSE.AX', 'BPT.AX', 'BOS.TO', 'BOL.AX', 'BMAX.ST', 'BLY.AX', 'BKW.AX', 'BKN.AX', 'BKL.AX', 'BFG.AX', 'BF-A', 'BEIA-B.ST', 'BBA.L', 'BAYA.DE', 'BATS.L', 'BAMXF', 'BABS.L', 'AZTECACPO.MX', 'AZRH', 'AZM.MI', 'AZ.TO', 'AYTU', 'AXXU', 'AXXTF', 'AXX.TO', 'AXELF', 'AXAHF', 'AWDR.OL', 'AVV.L', 'AVTC', 'AVR.L', 'AVMXF', 'AUV.V', 'AURZ', 'AUMY', 'AUM.TO', 'ATVM', 'ATUSF', 'ATURF', 'ATRS.VI', 'ATOR', 'ATOA', 'ATO.PA', 'ATN.TO', 'ATLCF', 'ATGSY', 'ATGN', 'ATF.MU', 'ATCV', 'ATCEY', 'ATC.V', 'ATBEF', 'ATA.PA', 'DCAC', 'ASZ.AX', 'ASWRF', 'AST.MI', 'ASSA-B.ST', 'ASPW', 'ASPU', 'ASMVF', 'ASLM', 'ASH.L', 'ASETEK.OL', 'ASDOF', 'ASB-PB', 'ARVSF', 'ARREF', 'ARRB.DE', 'AROFF', 'ARMHF', 'ARL.TO', 'ARET', 'ARE.TO', 'APYI', 'APS.TO', 'APLD', 'RY4A.HM', 'APELY', 'APCX', 'APBRA.BA', 'AP2.DE', 'AOT.V', 'AOMFF', 'AOBI', 'ANZ.NZ', 'ANFGY', 'ANDR', 'ANCKF', 'AN.V', 'AMZ.DE', 'AMX.V', 'KKL.AX', 'AMT-PB', 'AMSYF', 'AMSU', 'AMS.SW', 'AMNL', 'AMMX', 'AMMS', 'AMLM', 'AML.L', 'AMIH', 'AMG.F', 'AMFL', 'AMEN', 'AMC.AX', 'AMBCW', 'AMADY', 'ALY.V', 'ALU.AX', 'ALT.PA', 'ALPMY', 'ALPHA.AT', 'ALOCT.PA', 'ALMONDZ.NS', 'ALMMF', 'ALMDG.PA', 'ALLVF', 'ALLN', 'ALL-H.V', 'ALIOY', 'ALIAF', 'ALFVY', 'ALFE', 'ALFAA.MX', 'ALDA', 'ALAWP', 'ALAST.PA', 'AKKVY', 'AJL.AX', 'AJACD', 'AIW', 'AIVI', 'AIRYY', 'AIRW', 'AIPUY', 'AHT-PE', 'AHMS', 'AHLA.DE', 'AHIID', 'AHCHY', 'AHCG.L', 'AHBIF', 'AGTMF', 'AGS.BR', 'SLED.L', 'AGO.V', 'AGN.AS', 'AGN-PA', 'AGM.V', 'AGI.AX', 'AGGZF', 'AGESF', 'AGE.V', 'AFYG', 'AFT', 'AFCMF', 'AFBA', 'AF-B.ST', 'AEZ.TO', 'AEYIF', 'AETUF', 'AEI.TO', 'AE.MI', 'ADW-B.TO', 'ADTR', 'ADSK.MX', 'ADRNF', 'ADP.PA', 'ADINATH.BO', 'ADIA', 'ADHLY', 'ACUS', 'ACSEF', 'ACRB', 'ACOPF', 'ACMUY', 'ACGFF', 'ACAR', 'ABX.BA', 'ABTO', 'ABRW', 'ABR.V', 'ABJ.DE', 'ABGPF', 'ABGLY', 'ABF.L', 'ABE.V', 'ABC.L', 'ABC.AX', 'ABBN.VX', 'AAV.TO', 'AAST', 'AASL', 'AAD.DE', 'AABVF', 'AABB', 'A2A.MI', '7579.KL', '7162.KL', '6AT.BE', '6432.KL', 'REMO', '5IB.SI', '5014.KL', '4162.KL', 'LEON', '0104.HK', ]
companies = [ 'OEDV', 'AAPL', 'BAC', 'AMZN', 'T', 'GOOG', 'MO', 'DAL', 'AA', 'AXP', 'DD', 'BABA', 'ABT', 'UA', 'AMAT', 'AMGN', 'AAL', 'AIG', 'ALL', 'ADBE', 'GOOGL', 'ACN', 'ABBV', 'MT', 'LLY', 'AGN', 'APA', 'ADP', 'APC', 'AKAM', 'NLY', 'ABX', 'ATVI', 'ADSK', 'ADM', 'BMH.AX', 'WBA', 'ARNA', 'LUV', 'ACAD', 'PANW', 'AMD', 'AET', 'AEP', 'ALXN', 'CLMS', 'AVGO', 'EA', 'DB', 'RAI', 'AEM', 'APD', 'AMBA', 'NVS', 'APOL', 'ANF', 'LULU', 'RAD', 'BRK.AX', 'ARRY', 'AGNC', 'JBLU', 'A', 'ORLY', 'FOLD', 'AZO', 'ATML', 'AN', 'AZN', 'AES', 'GAS', 'BUD', 'ARR', 'BDX', 'AKS', 'AB', 'ACOR', 'CS', 'AFL', 'ADI', 'AEGR', 'ACIW', 'AMP', 'AVP', 'AMTD', 'AEO', 'AWK', 'NVO', 'ALTR', 'ALK', 'PAA', 'MTU.AX', 'ARCC', 'AAP', 'NAT', 'FNMA', 'FAV', 'AIV', 'AGIO', 'AEE', 'UBS', 'AVXL', 'ARLP', 'ANTM', 'AGU', 'AG', 'AFSI', 'ABC', 'STO', 'ATI', 'ADT', 'AVB', 'ATW', 'ALNY', 'LH', 'AVY', 'AUY', 'ASH', 'ARMH', 'ARIA', 'ANR', 'AINV', 'ACXM', 'ACHN', 'ACET', 'ABMD', 'ABM', 'VA', 'LIFE', 'ATO', 'ARP', 'AON', 'ADXS', 'ADC', 'APU', 'SAVE', 'AV', 'AKRX', 'ADS', 'ABAX', 'AYI', 'AWH', 'ASML', 'AMT', 'ALDR', 'ACM', 'DWA', 'ATRS', 'ARW', 'ARI', 'ARG', 'AR', 'AMCC', 'AMC', 'AL', 'AGEN', 'AAN', 'WTR', 'FCAU', 'BAH', 'AXAS', 'AVT', 'ALB', 'AIZ', 'SAIC', 'CAR', 'AXLL', 'AU', 'ARO', 'APH', 'ANTH', 'AMX', 'AMDA', 'AI', 'ABCO', 'WMC', 'MPX.AX', 'JKHY', 'AVAV', 'AMKR', 'ALJ', 'ACH', 'GPH.AX', 'ERC', 'APPY', 'ANAC', 'AEIS', 'Y', 'MTGE', 'CENX', 'ASPS', 'AMRN', 'AMPE', 'AMAG', 'ALKS', 'AFFX', 'ADES', 'ACAT', 'AAON', 'XLRN', 'VRSK', 'VJET', 'OA', 'ATLS', 'APTS', 'APO', 'ALSK', 'ALG', 'AHC', 'ACTG', 'ACAS', 'RBA', 'MAA', 'BAM', 'ATHN', 'AT', 'ASX', 'ARCO', 'ANET', 'ANCX', 'AIR', 'AF', 'WAB', 'RS', 'PKG', 'CSH', 'AXDX', 'AVHI', 'AVA', 'ATHX', 'ARWR', 'ANGI', 'AMG', 'ALSN', 'ALGN', 'AKBA', 'AGO', 'AEZS', 'ACRX', 'ROK', 'GLPI', 'DNI', 'AZZ', 'ATRC', 'ARRS', 'ARMK', 'AOS', 'ANFI', 'AMID', 'AMCX', 'ALIM', 'ALE', 'AHT', 'ACW', 'ABB', 'AALI.JK', 'SPR', 'SEE', 'RDEN', 'PAAS', 'DLPH', 'ADAC', 'CBL', 'BBVA', 'AYR', 'APOG', 'ANDE', 'AMSC', 'AMRS', 'AMED', 'ALEX', 'ALCO', 'ADUS', 'ACTA', 'ACST', 'AAWW', 'WMS', 'PAG', 'MDRX', 'KLIC', 'ETH', 'AZPN', 'AXE', 'ATNY', 'APRI', 'AMH', 'AME', 'AJG', 'AIQ', 'AHGP', 'AGCO', 'AERI', 'ACRE', 'ABEO', 'WAL', 'SYT', 'SHLM', 'NOG', 'HTA', 'GIII', 'DAVE', 'CVU', 'BSI', 'AWAY', 'ATU', 'ASTI', 'AREX', 'ARE', 'ANSS', 'AMNB', 'AMBS', 'ALR', 'AIXG', 'AIN', 'AHL', 'AGX', 'AEG', 'ADTN', 'ADMS', 'ACLS', 'ABG', 'ZX', 'NXJ', 'KS', 'HOLI', 'GPI', 'ENI', 'BEAV', 'AXTA', 'AWR', 'AWI', 'AVEO', 'AUO', 'ATHM', 'ATAX', 'ASM', 'AROC', 'ANH', 'ALX', 'AHS', 'AGI', 'AER', 'AE', 'RHHBY', 'PETX', 'ODC', 'NAO', 'KAR', 'HUSA', 'HIVE', 'FMS', 'DOX', 'CXW', 'AZUR', 'AXS', 'AXL', 'AWX', 'AVID', 'ASNA', 'ASGN', 'ARDX', 'ARAY', 'AQXP', 'APT', 'APDN', 'AMBC', 'ALGT', 'ALDW', 'AIT', 'AIRM', 'AIMC', 'AEL', 'AEHR', 'ADHD', 'ACUR', 'ACHC', 'ACFC', 'ACCO', 'ABY', 'TA', 'RPAI', 'MANH', 'LAMR', 'KYN', 'AXN', 'ATRO', 'ATNI', 'ARCW', 'APEI', 'AP', 'ANIK', 'ANGO', 'AMTG', 'AMSG', 'AMOT', 'AM', 'ALV', 'ALOG', 'AKR', 'AEGN', 'ADS.DE', 'ZLTQ', 'WRLD', 'UHAL', 'UAMY', 'SAH', 'RJET', 'NAII', 'AQNM', 'CAS', 'CACC', 'ATSG', 'ASEI', 'ASB', 'ARTX', 'AROW', 'ARCB', 'AMRK', 'ALRM', 'AHP', 'AGRX', 'AFAM', 'ADK', 'ACSF', 'ABTL', 'ABGB', 'ABEV', 'ABCD', 'AAOI', 'USAP', 'STFC', 'STAY', 'SEED', 'RGA', 'IDSA', 'HART', 'CH', 'CEA', 'BREW', 'AXR', 'AVG', 'AVD', 'AUDC', 'ATRI', 'ATOS', 'ARC', 'APIC', 'AOSL', 'AOI', 'AMWD', 'ALXA', 'ALLY', 'AIRI', 'AFOP', 'ACGL', 'ACFN', 'ABR', 'ABCB', 'SAMG', 'REXI', 'RAIL', 'NSAM', 'MITT', 'LCM', 'HASI', 'GOL', 'GIL', 'EAD', 'ATTO', 'ATR', 'ATNM', 'ASTC', 'ASR', 'ASC', 'ARTNA', 'ARGS', 'AOD', 'AGNCP', 'ADRO', 'ACNB', 'AAV', 'AAT', 'ZNH', 'UAM', 'NTT', 'NFJ', 'LNT', 'KALU', 'HOMB', 'HIX', 'FAF', 'FAC', 'EGT', 'CAAS', 'BGR', 'BETR', 'AUPH', 'ATV', 'ATLC', 'AST', 'ARIS', 'ARCI', 'APLE', 'ANY', 'ANIP', 'AMSWA', 'AMSF', 'ALLT', 'AKTX', 'AGYS', 'AGTC', 'AFG', 'ADDYY', 'AAVL', 'WAIR', 'RESI', 'LND', 'LFL', 'HRT', 'ESD', 'ECF', 'DGLY', 'CIK', 'CII', 'CHOP', 'CCD', 'CADC', 'AYA', 'AWRE', 'AVV', 'AVNW', 'ATRM', 'APPF', 'AFFMQ', 'AMRI', 'AMCN', 'AMCF', 'ALTI', 'ALLE', 'AJRD', 'AHH', 'AGM', 'AGII', 'AFCB', 'AEPI', 'ADMA', 'ABCW', 'AAME', 'TEO', 'SRAQU', 'SINO', 'OMAB', 'NOA', 'NCZ', 'MTT', 'MHG', 'JAGX', 'ISL', 'HIO', 'GRR', 'FAX', 'ENL', 'DIT', 'CRMT', 'CRESY', 'CGA', 'CAF', 'ATRA', 'ATEN', 'ATEC', 'ARLZ', 'ARII', 'ARDM', 'ARDC', 'ARCX', 'APPS', 'APHB', 'ANW', 'ANAT', 'ANAD', 'AKAO', 'AGHI', 'AETI', 'AEB', 'ADPT', 'ADMP', 'ACRS', 'ACC', 'ABEOW', 'ABDC', 'REX', 'PAC', 'NNA', 'NAUH', 'IGD', 'HMNY', 'GABC', 'ERH', 'EPAX', 'CACQ', 'BTI', 'AXPW', 'AWF', 'AVX', 'ASUR', 'ASMB', 'ASFI', 'ASCMA', 'ASCC', 'ARES', 'ARCP', 'AQMS', 'ANCB', 'AMRC', 'AMOV', 'AKG', 'AFW', 'ACY', 'ACPW', 'ABIO', 'AAC', 'XKE', 'VLRS', 'PRA.AX', 'TEAM', 'SORL', 'NEN', 'NEA', 'LMIA', 'JEQ', 'IGA', 'IDE', 'GBAB', 'FWP', 'EVTC', 'CMGE', 'CHY', 'CADTU', 'BTZ', 'BAYN.DE', 'AXU', 'AWP', 'ATE', 'ATAI', 'ARQL', 'ARKR', 'APP', 'APLP', 'APF', 'APB', 'AMRB', 'AMBR', 'ALU.PA', 'ALQA', 'ALOT', 'AKER', 'AIB', 'AHPI', 'AGRO', 'AFST', 'ADX', 'ADGE', 'ADAT', 'ADAP', 'ACU', 'ACTS', 'WJA.TO', 'VLKAY', 'TKC', 'AQQSQ', 'SCOK', 'RZA', 'PWX', 'PRTS', 'POPE', 'PEO', 'OASM', 'NCV', 'NBB', 'NADL', 'MHY', 'MHF', 'IOTS', 'HYB', 'GAM', 'EOD', 'EAGL', 'DLA', 'CBA', 'BRKS', 'AVK', 'AUMAU', 'AUBN', 'ASYS', 'ASA', 'AMPH', 'AMIC', 'AMFW', 'ALJJ', 'ALDX', 'AGR', 'AGD', 'AFC', 'AFA', 'AEY', 'AEK', 'ADVS', 'ABUS', 'ABLX.BR', 'AAPC', 'TANN', 'SHOS', 'RYAM', 'RJETQ', 'PAHC', 'NAC', 'MZA', 'MGR', 'HYI', 'GNOW', 'FWRD', 'FEN', 'FEI', 'DAI.DE', 'CHLN', 'CALI', 'AXON', 'AXGN', 'AVH', 'AVAL', 'AUMN', 'ATL', 'ASRVP', 'ASRV', 'ASBI', 'ASBB', 'ARTW', 'APWC', 'APAM', 'AMS', 'AMFC', 'ALN', 'AGFS', 'AFGE', 'AEMD', 'ADNC', 'ACV', 'ACG', 'ACBI', 'ABTX', 'AAMC', 'UNAM', 'TVE', 'TVC', 'SGF', 'SCAI', 'HVCW', 'OMAM', 'NSA', 'NKG', 'NAD', 'MTGEP', 'MPAA', 'LDP', 'JRI', 'JAX', 'IF', 'GGM', 'ETF', 'EARS', 'EADSY', 'DMO', 'DEX', 'AZSEY', 'AXX', 'AXTI', 'AVXS', 'AUQ', 'ATTU', 'ATLO', 'ASTE', 'ASND', 'ARL', 'APTO', 'AMTX', 'AKP', 'AI.PA', 'AGIIL', 'AFMD', 'AFFY', 'AFB', 'AEUA', 'ADEP', 'ABIL', 'ABAC', 'WIW', 'WGA', 'TRAN.BA', 'ICG.AX', 'SBI', 'RKDA', 'PSF', 'NAZ', 'MNP', 'MMU', 'DLS.AX', 'JTA', 'IPCC', 'IAF', 'IAE', 'GCP', 'FTAI', 'FNTCU', 'FGB', 'FCO', 'EMD', 'EAA', 'DDAIF', 'QED.L', 'CHI', 'CEE', 'CADTW', 'BUI', 'AXSM', 'ANOS', 'ANCI', 'ALTV', 'ALAN', 'AKZOY', 'AKO-A', 'AJX', 'AGNCB', 'AFSD', 'AFH', 'AEGG', 'ACP', 'ABRN', 'CLA.AX', 'WRN', 'USA', 'OXXCB.AX', 'CBS.AX', 'PHX', 'NZH', 'KYE', 'KLREU', 'JCE', 'JBR', 'JBK', 'IGZ', 'IGI', 'HOPS', 'HDRA', 'GS.TO', 'GRO', 'GPACU', 'GER', 'ELEC', 'EGIF', 'DYSL', 'CNLM', 'CLAC', 'CACG', 'BTA', 'BRSS', 'BLVDW', 'BLVD', 'AYA.TO', 'AVLY', 'AUMAW', 'ATP.TO', 'ASMI', 'ASKH', 'ARUN', 'AREN', 'ARCPP', 'AMSGP', 'AMRH', 'ALTX', 'ALA.TO', 'AKG.TO', 'AIY', 'AIR.PA', 'AIMT', 'AIF', 'AERG', 'AED', 'ADXSW', 'ACLZ', 'ABX.TO', 'ABAT', 'AAAP', '6599.KL', 'WIA', 'WEA', 'VKI', 'VELCP.AX', 'TRTLW', 'TRTL', 'SKAS', 'SCD', 'RUK', 'ROIQ', 'QPACW', 'QPACU', 'AMLH', 'PZE', 'PAI', 'PAA.TO', 'ORG.AX', 'NXZ', 'NORD', 'NMA', 'NKX', 'NBRV', 'MOG-A', 'MAV', 'LDF', 'JSYNU', 'JPI', 'JBN', 'HDRAW', 'HDRAU', 'HCACW', 'GTATQ', 'GPIAW', 'GGZ', 'GGACW', 'GCH', 'GAI', 'FNTC', 'FBGX', 'EXD', 'EHI', 'EAE', 'DRA', 'DFP', 'DDF', 'CVB', 'CS.PA', 'CNLMR', 'CLAD', 'BLVDU', 'BHAC', 'BGY', 'BBD-A.TO', 'BAM-A.TO', 'AVNU', 'AVL', 'AVL.TO', 'ATH.TO', 'ASG', 'ARU', 'AQA.TO', 'ANZ.AX', 'ANTX', 'ANTM.JK', 'ANSU', 'ANRZQ', 'ANDAU', 'ALYI', 'ALO.PA', 'ALLM', 'ALLB', 'AIRT', 'AIC', 'AFFM', 'ADN.L', 'AC', 'AC.PA', 'ABI.BR', 'ZERO', 'XRF.AX', 'WOW.AX', 'WDI.DE', 'WAT.AX', 'VOLVY', 'TRTLU', 'TPZ', 'ABEC', 'SIEGY', 'SDCJF', 'ROIQW', 'ROIQU', 'QPAC', 'QBE.AX', 'ARN.V', 'PAACR', 'ORT.TO', 'NZF', 'NVX', 'NVG', 'NUW', 'NIE', 'MYHI', 'MT.AS', 'MHNB', 'MDG.AX', 'LAQ', 'KED', 'IAG.TO', 'HJV', 'GLV', 'FIEE', 'VTX.AX', 'ELECU', 'EACQU', 'CNLMU', 'CAMBU', 'BXB.AX', 'BHP.AX', 'AXPWW', 'AV.L', 'ATLN.VX', 'ATA.TO', 'ASPN', 'ASII.JK', 'ARWAW', 'ARBV', 'AOXY', 'AOGN', 'ALV.DE', 'ALOD', 'AKRA.JK', 'AKO-B', 'AINC', 'AGU.TO', 'AGFSW', 'AFFW', 'AFCO', 'AERT', 'AEH', 'AEGA', 'AD.TO', 'ACNV', 'ABHD', 'ABCP', 'AAU', '3264.TWO', 'WVL.AX', 'WRR.AX', 'TANP', 'TANO', 'STO.AX', 'SMCG', 'SMACU', 'SBW', 'RGX.TO', 'AXXE', 'PACQF', 'NRBAY', 'NHH.AX', 'NEN.AX', 'NDO.AX', 'MQG.AX', 'MLPB', 'MHNC', 'MHNA', 'MCX.AX', 'KTE.AX', 'KIK.AX', 'AET-UN.TO', 'JDD', 'IPT.AX', 'IMMA', 'IAIC', 'HNNA', 'HCACU', 'GYC', 'GTN-A', 'GPIA', 'GGACU', 'GGAC', 'GFY', 'GDF', 'FSAM', 'FMAO', 'FCAM', 'ECACU', 'EAGLW', 'EAGLU', 'DLYT', 'CRP.TO', 'CAMBW', 'BMP.AX', 'BHACU', 'BBCA.JK', 'AVTH', 'AVOI', 'AVGR', 'AUXO', 'AUNFF', 'AUNB', 'ATOC', 'ATEA', 'ATD-B.TO', 'ASNB', 'ASCCF', 'ARX.TO', 'ARWA', 'ARTH', 'ARGB', 'APIC.JK', 'ANDA', 'ANAS', 'AMPG', 'AMNF', 'AMEH', 'AMBOY', 'ALB.TO', 'AKSO.OL', 'AHT.L', 'AHONY', 'AFSS', 'AFN.TO', 'AFGH', 'AF.PA', 'AEYE', 'AERO', 'ADVC', 'ACIIQ', 'ACDVF', 'ABBB', 'ZYL.AX', 'WTER', 'WPL.AX', 'WNS.AX', 'WIHL.ST', 'WHC.AX', 'WES.AX', 'WDS.AX', 'WCC.AX', 'VWS.CO', 'AAWC', 'VOLV-B.ST', 'VMS.AX', 'VKA.AX', 'UCW.AX', 'TZL.AX', 'TWCF', 'TRZ-B.TO', 'TLS.AX', 'TGRO', 'TFECY', 'SXL.AX', 'SUGO', 'STL.OL', 'CBAI', 'SMACR', 'SIGL', 'SCA-A.ST', 'SAS.TO', 'SAS.ST', 'ROG.VX', 'REZT.ST', 'REA.AX', 'RBA.TO', 'LEAS', 'PRVW', 'VBPS.VI', 'PDL.TO', 'PBD.AX', 'PACT.ST', 'PAAC', 'OPEI', 'NXK', 'NMS.AX', 'NME.AX', 'NHYDY', 'NFE.AX', 'NBD', 'NAEY', 'NAB.AX', 'MDA.TO', 'LUND-B.ST', 'LO3.DE', 'LMFA', 'LGI', 'LER.AX', 'LCT.AX', 'LAU.AX', 'LAME4.SA', 'KOV.AX', 'KME.AX', 'KBC.AX', 'JMLP', 'IVX.DE', 'IRI.AX', 'IREBY', 'IGAP', 'IBO', 'ALME', 'HLDX.ST', 'HIL.AX', 'HDRAR', 'HCAC', 'HADV', 'GPIAU', 'GPACW', 'GIL.TO', 'GGACR', 'GDO', 'GCV', 'FUTU', 'RSTA.DE', 'AWON', 'FNTCW', 'FBAK', 'FABK', 'ESOA', 'ELUXY', 'ECEX.ST', 'ECACR', 'EACQW', 'EAB', 'E5H.SI', 'DTEGY', 'DNSKY', 'DBRM', 'CPU.AX', 'CMW.AX', 'UAHC', 'CLAS-B.ST', 'CLACU', 'CEAI', 'CBA.AX', 'CARL-B.CO', 'CADT', 'BOE.V', 'BILL.ST', 'BHARTIARTL.NS', 'BHACR', 'BBTO-B.ST', 'BBG.AX', 'BAYRY', 'BAC-PL', 'AZN.L', 'AXY.TO', 'AXST', 'AXIH', 'AXFO.ST', 'AXAHY', 'AUSI', 'ATD-A.TO', 'ATAR', 'ASURB.MX', 'ASML.AS', 'ASHOKLEY.NS', 'ASHG', 'ASCS', 'AQN.TO', 'AQ.V', 'APY.TO', 'APDNW', 'APBR.BA', 'AOREF', 'ANPDF', 'ANN.AX', 'ANAV', 'AMUB', 'AMPLQ', 'AMM.TO', 'AMIN', 'AMBZ', 'AMBTQ', 'AMAVF', 'ALYE', 'ALSE', 'ALRT', 'ALNPY', 'ALN.V', 'ALMG', 'ALEHT.PA', 'AKTS', 'AJX.TO', 'AIM.TO', 'AHII', 'AHFP', 'AGL.L', 'AGIN', 'AFSE', 'AFBG', 'AEM.TO', 'ADTM', 'ADMF.JK', 'ADLS', 'ADHI.JK', 'ADES.JK', 'ACQ.TO', 'ACCA', 'ABNK', 'ABKI', '0522.HK', 'PNA.AX', 'ZRL.AX', 'ZGL.AX', 'XDC.TO', 'XANO-B.ST', 'WWRB', 'WWASA.OL', 'WSA.AX', 'WOR.AX', 'WETM', 'WEC.AX', 'WBC.NZ', 'WBC.AX', 'WBA.AX', 'WALMEX.MX', 'VWS.DE', 'SDL.AX', 'VOIL', 'VIP.AX', 'VII.AX', 'VIE.AX', 'VBHLF', 'UGL.AX', 'UBAB', 'TPM.AX', 'TGZ.AX', 'TGR.AX', 'TCN.AX', 'TCL.AX', 'TCL-A.TO', 'SUD.AX', 'STWRY', 'RRS.AX', 'ARCS', 'SKFRY', 'SIPH.PA', 'SAND.ST', 'RWEOY', 'RKET.DE', 'RHC.AX', 'RAFI', 'QUBSF', 'PTPF', 'PRKA', 'PLS.AX', 'PETS.L', 'PAEKY', 'PAACU', 'OZL.AX', 'OTS.OL', 'OSI.PA', 'ORXOY', 'ORK.OL', 'OKU.AX', 'NSX.AX', 'NOEJ.DE', 'NOE.AX', 'NOA.TO', 'NML.AX', 'MYR.AX', 'MTN.MX', 'MT.PA', 'MQ.ST', 'MOC.AX', 'MMR.AX', 'MLPZ', 'MLPQ', 'MKO.AX', 'MHM', 'LUPE.ST', 'LSPN.DE', 'LNR.AX', 'LMFAU', 'LAS.L', 'KRS.AX', 'KNH.AX', 'KMF', 'KLREW', 'KLRE', 'KKT.AX', 'KINV-B.ST', 'KAS.AX', 'JRV.AX', 'JOES', 'ORS.AX', 'IOX.OL', 'INPC.JK', 'IMU.AX', 'ILU.AX', 'IFNNY', 'HWO.TO', 'HVN.AX', 'HISP', 'HGKGF', 'GPAC', 'GOOG.MX', 'GNGBY', 'GNC.AX', 'GML.AX', 'GLUX', 'GID.AX', 'FLY.V', 'FHZN.SW', 'FFMH', 'ELDO', 'EKO.OL', 'SOUL', 'EBKDY', 'DUNI.ST', 'DNO.OL', 'DFF', 'USAE', 'DANSKE.CO', 'CSCO.BA', 'CRZBY', 'COME.BA', 'COH.AX', 'CITY', 'CISAW', 'CIG-C', 'CHOPF', 'SPX.AX', 'ABHI', 'CCLAY', 'CAFO.PA', 'CADTR', 'CACGW', 'BVB.DE', 'BST', 'BPTY.L', 'BLD.AX', 'BHIP.BA', 'BEN.AX', 'BEIJ-B.ST', 'BCS-PD', 'BCAUY', 'BBVA.MC', 'BAOXF', 'BAMXY', 'AZZEF', 'AXS.L', 'AXRX', 'AXIM', 'AXANF', 'AVTS', 'AVMXY', 'AVBH', 'AUTCF', 'AUROPHARMA.NS', 'AUMA', 'AUE.TO', 'AU8U.SI', 'ATTBF', 'ASX.AX', 'ASR.TO', 'ASCK', 'ASAZY', 'ARZGY', 'ARWAU', 'ARWAR', 'ARNI', 'ARNGF', 'ARKAY', 'ARGKF', 'AREXMIS.BO', 'AR.TO', 'AQUA.OL', 'APVS', 'APO.V', 'APNI', 'APLN.JK', 'APEOF', 'ANZFF', 'ANDAW', 'ANDAR', 'ANA.MC', 'AMXL.MX', 'AMTY', 'AMTC', 'AMSE', 'AMSA', 'AMS.MC', 'AMRR', 'AMP.AX', 'AMKBY', 'AMCO', 'AMBK', 'AMAR', 'AMA.L', 'ALXDF', 'ALSMY', 'ALO.L', 'ALIOF', 'ALGI', 'ALALF', 'AKVA', 'AKT-B.TO', 'AKER.OL', 'AIQUY', 'AIII', 'AHRO', 'AHNR', 'AHF.TO', 'AH.AS', 'AGT.TO', 'AGPPY', 'AGM-A', 'AGI.TO', 'AGF-B.TO', 'AGESY', 'AFK.OL', 'AF.TO', 'ADW-A.TO', 'ADV.TO', 'ADRO.JK', 'ADGL', 'ADFT', 'ACUG', 'ACHI', 'ACD.TO', 'ABK-PC.TO', 'ABEV3.SA', 'ABE.MC', 'ABCE', 'AASP', 'AAPL.SW', 'AAPL.MX', 'AAL.L', 'AACAY', 'AAC.V', 'A23.SI', '5099.KL', '3DM.AX', 'IIN.AX', 'ZURVY', 'YAL.AX', 'ADCF', 'XTD.AX', 'WTR.AX', 'WHLKY', 'WFD.AX', 'WDAS', 'WCP.AX', 'WBAPA.AX', 'VLKPY', 'VLKAF', 'VELIN.AX', 'VBG-B.ST', 'UUL.AX', 'USG.AX', 'UOS.AX', 'UCM.AX', 'UBI.AX', 'UATG', 'TZN.AX', 'TWE.AX', 'TUIFF', 'TPI.AX', 'TPDKY', 'TOTRF', 'TMNSF', 'TMC.TO', 'TKGBY', 'TGS.AX', 'TEN.AX', 'TELNY', 'TARSF', 'AMPW', 'SZGPY', 'ARYX', 'SYIEF', 'SWGAY', 'SWGAF', 'SVNLF', 'STB.OL', 'SSHIP.OL', 'SPX.V', 'SOO.AX', 'KRA.AX', 'SMA.L', 'BTFL', 'SKBSY', 'SKA-B.ST', 'SIQ.AX', 'SIP.AX', 'SHV.AX', 'SEN.AX', 'SDF.AX', 'AIB.IR', 'SBM.AX', 'SAZ.DE', 'SAUHF', 'SAPA.DE', 'SANWARIA.NS', 'SAI.AX', 'SAAB-B.ST', 'RBX.AX', 'RUSF.ST', 'RO.SW', 'RMS.PA', 'RMP.L', 'RMLXP', 'RIS.AX', 'RIO.AX', 'RIGO.BA', 'RCMFF', 'RAD.DE', 'PYC.AX', 'PTBA.JK', 'PSSR', 'PSAHF', 'PSA.AX', 'PRDC', 'PPTG', 'PPT.AX', 'PNE3.DE', 'PNDZY', 'PMV.AX', 'AMFE', 'PHM7.DE', 'PGRD', 'PGPHF', 'AHIX', 'PEXNY', 'PEK.AX', 'PDN.AX', 'PBP.AX', 'PBAM', 'PAY.AX', 'PAN.AX', 'PACI', 'OSR.DE', 'ORKLY', 'ORI.AX', 'ORA.TO', 'OPESY', 'OPERA.OL', 'OMVKY', 'OFX.AX', 'O4B.DE', 'NVZMY', 'NVZMF', 'NVSEF', 'NTM.AX', 'NSP.AX', 'NRK', 'NOTE.ST', 'NOMI.ST', 'NOD.OL', 'NOD.AX', 'NLY-PA', 'NIO.AX', 'NIBE-B.ST', 'NHF.AX', 'NDX1.DE', 'NAN', 'NAF-UN.TO', 'NABZY', 'MYX.AX', 'MYN.AX', 'MURGY', 'MQA.AX', 'MOL.AX', 'MOEX.ME', 'MNY.AX', 'MLMAB.PA', 'MIG.AX', 'MGAM.L', 'MEDI.OL', 'MDD.AX', 'MAL.TO', 'MAJJ', 'MABA', 'MAAL', 'M6YA.DE', 'LTR.AX', 'LNNNF', 'LNEGY', 'LMFAW', 'LIC.AX', 'LIAB.ST', 'LEDE.BA', 'LCE.AX', 'LBT.AX', 'LAS-A.TO', 'LALAB.MX', 'AXL.TO', 'LA.V', 'KWA.V', 'KUKAY', 'KSB.DE', 'KPC.AX', 'KGM.AX', 'KGL.AX', 'KD8.DE', 'KBC.L', 'K1R.DE', 'JYC.AX', 'AWGI', 'JM.ST', 'J7X.SI', 'ITAB-B.ST', 'ISXIF', 'ISSJY', 'IPP.AX', 'IPLO', 'IPL.AX', 'IPD.AX', 'VC8.DE', 'ILMCF', 'IGO.AX', 'AM.TO', 'IAM.TO', 'IALB', 'HYDR.ME', 'HXGCF', 'HXGBY', 'HUTN', 'HUSQ-B.ST', 'HOKCY', 'HNB.OL', 'HIPH', 'HGKGY', 'HGHAF', 'HFA.AX', 'HEXA-B.ST', 'HENOY', 'HCIIP', 'HAW.AX', 'GXY.AX', 'GUD.AX', 'GMG.AX', 'TPET.L', 'GEN.CO', 'GEM.AX', 'GELYY', 'GEEK', 'GCS.AX', 'GCLA.BA', 'GBA.AX', 'GAP.AX', 'GAHC', 'G1A.DE', 'FSJ.L', 'FNMFN', 'FNMAL', 'FMG.AX', 'FLYLF', 'FGRPF', 'FEEL.ST', 'FASV', 'EXAD', 'EVTCY', 'ETPHF', 'ERCA.DE', 'ERAO', 'EOG.V', 'EME.AX', 'ELECW', 'ELD.AX', 'EFGXY', 'ECO.AX', 'ECAC', 'DVI.AX', 'DUO.AX', 'DUE.AX', 'DRX.TO', 'APYP', 'DPSGY', 'DMP.AX', 'DD-PB', 'DATI', 'CYAP', 'CVO.AX', 'CTP.AX', 'CSL.AX', 'CRYO', 'CPPCY', 'COP.DE', 'COLAY', 'COIC.ST', 'COGLF', 'CNLMW', 'CMWAY', 'CLC.TO', 'CLACW', 'LOGL', 'CHCR', 'SKYD.DE', 'CDD.AX', 'CDA.PA', 'CCLAF', 'CBAUF', 'CAMB.L', 'AMIEQ', 'CAI.VI', 'CACGU', 'BWL-A', 'BTT.AX', 'BSE.AX', 'BPT.AX', 'BOS.TO', 'BOL.AX', 'BMAX.ST', 'BLY.AX', 'BKW.AX', 'BKN.AX', 'BKL.AX', 'BFG.AX', 'BF-A', 'BEIA-B.ST', 'BBA.L', 'BAYA.DE', 'BATS.L', 'BAMXF', 'BABS.L', 'AZTECACPO.MX', 'AZRH', 'AZM.MI', 'AZ.TO', 'AYTU', 'AXXU', 'AXXTF', 'AXX.TO', 'AXELF', 'AXAHF', 'AWDR.OL', 'AVV.L', 'AVTC', 'AVR.L', 'AVMXF', 'AUV.V', 'AURZ', 'AUMY', 'AUM.TO', 'ATVM', 'ATUSF', 'ATURF', 'ATRS.VI', 'ATOR', 'ATOA', 'ATO.PA', 'ATN.TO', 'ATLCF', 'ATGSY', 'ATGN', 'ATF.MU', 'ATCV', 'ATCEY', 'ATC.V', 'ATBEF', 'ATA.PA', 'DCAC', 'ASZ.AX', 'ASWRF', 'AST.MI', 'ASSA-B.ST', 'ASPW', 'ASPU', 'ASMVF', 'ASLM', 'ASH.L', 'ASETEK.OL', 'ASDOF', 'ASB-PB', 'ARVSF', 'ARREF', 'ARRB.DE', 'AROFF', 'ARMHF', 'ARL.TO', 'ARET', 'ARE.TO', 'APYI', 'APS.TO', 'APLD', 'RY4A.HM', 'APELY', 'APCX', 'APBRA.BA', 'AP2.DE', 'AOT.V', 'AOMFF', 'AOBI', 'ANZ.NZ', 'ANFGY', 'ANDR', 'ANCKF', 'AN.V', 'AMZ.DE', 'AMX.V', 'KKL.AX', 'AMT-PB', 'AMSYF', 'AMSU', 'AMS.SW', 'AMNL', 'AMMX', 'AMMS', 'AMLM', 'AML.L', 'AMIH', 'AMG.F', 'AMFL', 'AMEN', 'AMC.AX', 'AMBCW', 'AMADY', 'ALY.V', 'ALU.AX', 'ALT.PA', 'ALPMY', 'ALPHA.AT', 'ALOCT.PA', 'ALMONDZ.NS', 'ALMMF', 'ALMDG.PA', 'ALLVF', 'ALLN', 'ALL-H.V', 'ALIOY', 'ALIAF', 'ALFVY', 'ALFE', 'ALFAA.MX', 'ALDA', 'ALAWP', 'ALAST.PA', 'AKKVY', 'AJL.AX', 'AJACD', 'AIW', 'AIVI', 'AIRYY', 'AIRW', 'AIPUY', 'AHT-PE', 'AHMS', 'AHLA.DE', 'AHIID', 'AHCHY', 'AHCG.L', 'AHBIF', 'AGTMF', 'AGS.BR', 'SLED.L', 'AGO.V', 'AGN.AS', 'AGN-PA', 'AGM.V', 'AGI.AX', 'AGGZF', 'AGESF', 'AGE.V', 'AFYG', 'AFT', 'AFCMF', 'AFBA', 'AF-B.ST', 'AEZ.TO', 'AEYIF', 'AETUF', 'AEI.TO', 'AE.MI', 'ADW-B.TO', 'ADTR', 'ADSK.MX', 'ADRNF', 'ADP.PA', 'ADINATH.BO', 'ADIA', 'ADHLY', 'ACUS', 'ACSEF', 'ACRB', 'ACOPF', 'ACMUY', 'ACGFF', 'ACAR', 'ABX.BA', 'ABTO', 'ABRW', 'ABR.V', 'ABJ.DE', 'ABGPF', 'ABGLY', 'ABF.L', 'ABE.V', 'ABC.L', 'ABC.AX', 'ABBN.VX', 'AAV.TO', 'AAST', 'AASL', 'AAD.DE', 'AABVF', 'AABB', 'A2A.MI', '7579.KL', '7162.KL', '6AT.BE', '6432.KL', 'REMO', '5IB.SI', '5014.KL', '4162.KL', 'LEON', '0104.HK', ]
none
1
1.301624
1
scripts/shared/file_utils.py
cric96/scala-native-benchmarks
13
6623195
<reponame>cric96/scala-native-benchmarks import os import errno import subprocess as subp def mkdir(path): try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def touch(path): open(path, 'w+').close() def slurp(path): with open(path) as f: return f.read().strip() def where(cmd): if os.path.isfile(cmd): return cmd else: paths = os.environ['PATH'].split(os.pathsep) for p in paths: f = os.path.join(p, cmd) if os.path.isfile(f): return f else: return None def run(cmd): print(">>> " + str(cmd)) return subp.check_output(cmd) def dict_from_file(settings_file): kv = {} with open(settings_file) as settings: for line in settings.readlines(): key, raw_value = line.split('=') value = raw_value.strip() kv[key] = value return kv def dict_to_file(settings_file, kv): with open(settings_file, 'w+') as settings: for k, v in kv.items(): settings.write('{}={}\n'.format(k, v)) sbt = where('sbt')
import os import errno import subprocess as subp def mkdir(path): try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def touch(path): open(path, 'w+').close() def slurp(path): with open(path) as f: return f.read().strip() def where(cmd): if os.path.isfile(cmd): return cmd else: paths = os.environ['PATH'].split(os.pathsep) for p in paths: f = os.path.join(p, cmd) if os.path.isfile(f): return f else: return None def run(cmd): print(">>> " + str(cmd)) return subp.check_output(cmd) def dict_from_file(settings_file): kv = {} with open(settings_file) as settings: for line in settings.readlines(): key, raw_value = line.split('=') value = raw_value.strip() kv[key] = value return kv def dict_to_file(settings_file, kv): with open(settings_file, 'w+') as settings: for k, v in kv.items(): settings.write('{}={}\n'.format(k, v)) sbt = where('sbt')
en
0.298393
# Python >2.5
2.761861
3
scripts/utils/make_template.py
mozilla-releng/staging-mozilla-vpn-client
0
6623196
<filename>scripts/utils/make_template.py #! /usr/bin/env python3 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import sys import argparse # Parse arguments to determine what to do. parser = argparse.ArgumentParser( description='Generate a file from a template') parser.add_argument('template', metavar='TEMPLATE', type=str, action='store', help='Template file to process') parser.add_argument('-o', '--output', metavar='FILENAME', type=str, action='store', help='Output file to write') parser.add_argument('-k', '--keyword', metavar='KEY=VALUE', type=str, action='append', default=[], help='Keyword to replace, and the value to replace it with') parser.add_argument('-f', '--keyfile', metavar='KEY=FILE', type=str, action='append', default=[], help='Keyword to replace, and the file to source its value from') args = parser.parse_args() # Build up a dictionary of keywords and their replacement values keywords = {} for keyval in args.keyword: kvsplit = keyval.split("=", 1) if len(kvsplit) != 2: print('Unable to parse KEY=VALUE from: ' + keyval) sys.exit(1) keywords[kvsplit[0]] = kvsplit[1] for keyfile in args.keyfile: kfsplit = keyfile.split("=", 1) if len(kfsplit) != 2: print('Unable to parse KEY=FILE from: ' + keyfile) sys.exit(1) with open(kfsplit[1]) as fp: keywords[kfsplit[0]] = fp.read() # Scan through the string for each of the keywords, replacing them # as they are found, while taking care not to apply transformations # to any already-transformed text. def transform(text): start = 0 while start < len(text): # Find the next matching keyword, if any. matchIdx = -1 matchKey = "" for key in keywords: x = text.find(key, start) if (matchIdx < 0) or (x < matchIdx): matchIdx = x matchKey = key # If there are no matches, we can return. if matchIdx < 0: return text # Substitute the keyword and adjust the start. value = keywords[matchKey] start = matchIdx + len(value) text = text[0:matchIdx] + value + text[matchIdx+len(matchKey):] # Open the output file if args.output is None: fout = sys.stdout else: fout = open(args.output, "w") # Read through the input file and apply variable substitutions. with open(args.template) as fin: fout.write(transform(fin.read())) fout.flush() fout.close()
<filename>scripts/utils/make_template.py #! /usr/bin/env python3 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import sys import argparse # Parse arguments to determine what to do. parser = argparse.ArgumentParser( description='Generate a file from a template') parser.add_argument('template', metavar='TEMPLATE', type=str, action='store', help='Template file to process') parser.add_argument('-o', '--output', metavar='FILENAME', type=str, action='store', help='Output file to write') parser.add_argument('-k', '--keyword', metavar='KEY=VALUE', type=str, action='append', default=[], help='Keyword to replace, and the value to replace it with') parser.add_argument('-f', '--keyfile', metavar='KEY=FILE', type=str, action='append', default=[], help='Keyword to replace, and the file to source its value from') args = parser.parse_args() # Build up a dictionary of keywords and their replacement values keywords = {} for keyval in args.keyword: kvsplit = keyval.split("=", 1) if len(kvsplit) != 2: print('Unable to parse KEY=VALUE from: ' + keyval) sys.exit(1) keywords[kvsplit[0]] = kvsplit[1] for keyfile in args.keyfile: kfsplit = keyfile.split("=", 1) if len(kfsplit) != 2: print('Unable to parse KEY=FILE from: ' + keyfile) sys.exit(1) with open(kfsplit[1]) as fp: keywords[kfsplit[0]] = fp.read() # Scan through the string for each of the keywords, replacing them # as they are found, while taking care not to apply transformations # to any already-transformed text. def transform(text): start = 0 while start < len(text): # Find the next matching keyword, if any. matchIdx = -1 matchKey = "" for key in keywords: x = text.find(key, start) if (matchIdx < 0) or (x < matchIdx): matchIdx = x matchKey = key # If there are no matches, we can return. if matchIdx < 0: return text # Substitute the keyword and adjust the start. value = keywords[matchKey] start = matchIdx + len(value) text = text[0:matchIdx] + value + text[matchIdx+len(matchKey):] # Open the output file if args.output is None: fout = sys.stdout else: fout = open(args.output, "w") # Read through the input file and apply variable substitutions. with open(args.template) as fin: fout.write(transform(fin.read())) fout.flush() fout.close()
en
0.843204
#! /usr/bin/env python3 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # Parse arguments to determine what to do. # Build up a dictionary of keywords and their replacement values # Scan through the string for each of the keywords, replacing them # as they are found, while taking care not to apply transformations # to any already-transformed text. # Find the next matching keyword, if any. # If there are no matches, we can return. # Substitute the keyword and adjust the start. # Open the output file # Read through the input file and apply variable substitutions.
2.502912
3
examples/spot/mining/mining_hashrate_resale_request.py
Banging12/binance-connector-python
512
6623197
#!/usr/bin/env python import logging from binance.spot import Spot as Client from binance.lib.utils import config_logging config_logging(logging, logging.DEBUG) key = "" secret = "" params = { "algo": "sha256", "userName": "user_name", "startDate": 1607659086000, "endDate": 1617659086000, "toPoolUser": "pool_user_name", "hashRate": "100000000", } client = Client(key, secret) logging.info(client.mining_hashrate_resale_request(**params))
#!/usr/bin/env python import logging from binance.spot import Spot as Client from binance.lib.utils import config_logging config_logging(logging, logging.DEBUG) key = "" secret = "" params = { "algo": "sha256", "userName": "user_name", "startDate": 1607659086000, "endDate": 1617659086000, "toPoolUser": "pool_user_name", "hashRate": "100000000", } client = Client(key, secret) logging.info(client.mining_hashrate_resale_request(**params))
ru
0.26433
#!/usr/bin/env python
2.050379
2
mapss/static/packages/arches/arches/app/models/concept.py
MPI-MAPSS/MAPSS
0
6623198
""" ARCHES - a program developed to inventory and manage immovable cultural heritage. Copyright (C) 2013 <NAME> and World Monuments Fund This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import re import uuid import copy from operator import itemgetter from operator import methodcaller from django.db import transaction, connection from django.db.models import Q from arches.app.models import models from arches.app.models.system_settings import settings from arches.app.search.search_engine_factory import SearchEngineInstance as se from arches.app.search.elasticsearch_dsl_builder import Term, Query, Bool, Match, Terms from arches.app.search.mappings import CONCEPTS_INDEX from arches.app.utils.betterJSONSerializer import JSONSerializer, JSONDeserializer from django.utils.translation import ugettext as _ from django.utils.translation import get_language from django.db import IntegrityError import logging logger = logging.getLogger(__name__) CORE_CONCEPTS = ( "00000000-0000-0000-0000-000000000001", "00000000-0000-0000-0000-000000000004", "00000000-0000-0000-0000-000000000005", "00000000-0000-0000-0000-000000000006", ) class Concept(object): def __init__(self, *args, **kwargs): self.id = "" self.nodetype = "" self.legacyoid = "" self.relationshiptype = "" self.values = [] self.subconcepts = [] self.parentconcepts = [] self.relatedconcepts = [] self.hassubconcepts = False if len(args) != 0: if isinstance(args[0], str): try: uuid.UUID(args[0]) self.get(args[0]) except (ValueError): self.load(JSONDeserializer().deserialize(args[0])) elif isinstance(args[0], dict): self.load(args[0]) elif isinstance(args[0], object): self.load(args[0]) def __unicode__(self): return ("%s - %s") % (self.get_preflabel().value, self.id) def __hash__(self): return hash(self.id) def __eq__(self, x): return hash(self) == hash(x) def __ne__(self, x): return hash(self) != hash(x) def load(self, value): if isinstance(value, dict): self.id = str(value["id"]) if "id" in value else "" self.nodetype = value["nodetype"] if "nodetype" in value else "" self.legacyoid = value["legacyoid"] if "legacyoid" in value else "" self.relationshiptype = value["relationshiptype"] if "relationshiptype" in value else "" if "values" in value: for val in value["values"]: self.addvalue(val) if "subconcepts" in value: for subconcept in value["subconcepts"]: self.addsubconcept(subconcept) if "parentconcepts" in value: for parentconcept in value["parentconcepts"]: self.addparent(parentconcept) if "relatedconcepts" in value: for relatedconcept in value["relatedconcepts"]: self.addrelatedconcept(relatedconcept) if isinstance(value, models.Concept): self.id = str(value.pk) self.nodetype = value.nodetype_id self.legacyoid = value.legacyoid def get( self, id="", legacyoid="", include_subconcepts=False, include_parentconcepts=False, include_relatedconcepts=False, exclude=[], include=[], depth_limit=None, up_depth_limit=None, lang=settings.LANGUAGE_CODE, semantic=True, pathway_filter=None, **kwargs, ): if id != "": self.load(models.Concept.objects.get(pk=id)) elif legacyoid != "": self.load(models.Concept.objects.get(legacyoid=legacyoid)) _cache = kwargs.pop("_cache", {}) _cache[self.id] = self.__class__( {"id": self.id, "nodetype": self.nodetype, "legacyoid": self.legacyoid, "relationshiptype": self.relationshiptype} ) if semantic == True: pathway_filter = ( pathway_filter if pathway_filter else Q(relationtype__category="Semantic Relations") | Q(relationtype__category="Properties") ) else: pathway_filter = pathway_filter if pathway_filter else Q(relationtype="member") | Q(relationtype="hasCollection") if self.id != "": nodetype = kwargs.pop("nodetype", self.nodetype) uplevel = kwargs.pop("uplevel", 0) downlevel = kwargs.pop("downlevel", 0) depth_limit = depth_limit if depth_limit is None else int(depth_limit) up_depth_limit = up_depth_limit if up_depth_limit is None else int(up_depth_limit) if include is not None: if len(include) > 0 and len(exclude) > 0: raise Exception(_("Only include values for include or exclude, but not both")) include = ( include if len(include) != 0 else models.DValueType.objects.distinct("category").values_list("category", flat=True) ) include = set(include).difference(exclude) exclude = [] if len(include) > 0: values = models.Value.objects.filter(concept=self.id) for value in values: if value.valuetype.category in include: self.values.append(ConceptValue(value)) hassubconcepts = models.Relation.objects.filter(Q(conceptfrom=self.id), pathway_filter, ~Q(relationtype="related"))[0:1] if len(hassubconcepts) > 0: self.hassubconcepts = True if include_subconcepts: conceptrealations = models.Relation.objects.filter(Q(conceptfrom=self.id), pathway_filter, ~Q(relationtype="related")) if depth_limit is None or downlevel < depth_limit: if depth_limit is not None: downlevel = downlevel + 1 for relation in conceptrealations: subconcept = ( _cache[str(relation.conceptto_id)] if str(relation.conceptto_id) in _cache else self.__class__().get( id=relation.conceptto_id, include_subconcepts=include_subconcepts, include_parentconcepts=include_parentconcepts, include_relatedconcepts=include_relatedconcepts, exclude=exclude, include=include, depth_limit=depth_limit, up_depth_limit=up_depth_limit, downlevel=downlevel, uplevel=uplevel, nodetype=nodetype, semantic=semantic, pathway_filter=pathway_filter, _cache=_cache.copy(), lang=lang, ) ) subconcept.relationshiptype = relation.relationtype_id self.subconcepts.append(subconcept) self.subconcepts = sorted( self.subconcepts, key=lambda concept: self.natural_keys(concept.get_sortkey(lang)), reverse=False ) # self.subconcepts = sorted(self.subconcepts, key=methodcaller( # 'get_sortkey', lang=lang), reverse=False) if include_parentconcepts: conceptrealations = models.Relation.objects.filter(Q(conceptto=self.id), pathway_filter, ~Q(relationtype="related")) if up_depth_limit is None or uplevel < up_depth_limit: if up_depth_limit is not None: uplevel = uplevel + 1 for relation in conceptrealations: parentconcept = ( _cache[str(relation.conceptfrom_id)] if str(relation.conceptfrom_id) in _cache else self.__class__().get( id=relation.conceptfrom_id, include_subconcepts=False, include_parentconcepts=include_parentconcepts, include_relatedconcepts=include_relatedconcepts, exclude=exclude, include=include, depth_limit=depth_limit, up_depth_limit=up_depth_limit, downlevel=downlevel, uplevel=uplevel, nodetype=nodetype, semantic=semantic, pathway_filter=pathway_filter, _cache=_cache.copy(), lang=lang, ) ) parentconcept.relationshiptype = relation.relationtype_id self.parentconcepts.append(parentconcept) if include_relatedconcepts: conceptrealations = models.Relation.objects.filter( Q(relationtype="related") | Q(relationtype__category="Mapping Properties"), Q(conceptto=self.id) | Q(conceptfrom=self.id), ) relations = [] for relation in conceptrealations: if str(relation.conceptto_id) != self.id and str(relation.relationid) not in relations: relations.append(str(relation.relationid)) relatedconcept = self.__class__().get(relation.conceptto_id, include=["label"], lang=lang) relatedconcept.relationshiptype = relation.relationtype_id self.relatedconcepts.append(relatedconcept) if str(relation.conceptfrom_id) != self.id and str(relation.relationid) not in relations: relations.append(str(relation.relationid)) relatedconcept = self.__class__().get(relation.conceptfrom_id, include=["label"], lang=lang) relatedconcept.relationshiptype = relation.relationtype_id self.relatedconcepts.append(relatedconcept) return self def save(self): self.id = self.id if (self.id != "" and self.id is not None) else str(uuid.uuid4()) concept, created = models.Concept.objects.get_or_create( pk=self.id, defaults={"legacyoid": self.legacyoid if self.legacyoid != "" else self.id, "nodetype_id": self.nodetype} ) for value in self.values: if not isinstance(value, ConceptValue): value = ConceptValue(value) value.conceptid = self.id value.save() for parentconcept in self.parentconcepts: parentconcept.save() parentconcept.add_relation(self, parentconcept.relationshiptype) for subconcept in self.subconcepts: subconcept.save() self.add_relation(subconcept, subconcept.relationshiptype) # if we're moving a Concept Scheme below another Concept or Concept Scheme if len(self.parentconcepts) > 0 and concept.nodetype_id == "ConceptScheme": concept.nodetype_id = "Concept" concept.save() self.load(concept) for relation in models.Relation.objects.filter(conceptfrom=concept, relationtype_id="hasTopConcept"): relation.relationtype_id = "narrower" relation.save() for relatedconcept in self.relatedconcepts: self.add_relation(relatedconcept, relatedconcept.relationshiptype) if relatedconcept.relationshiptype == "member": child_concepts = relatedconcept.get(include_subconcepts=True) def applyRelationship(concept): for subconcept in concept.subconcepts: concept.add_relation(subconcept, relatedconcept.relationshiptype) child_concepts.traverse(applyRelationship) return concept def delete(self, delete_self=False): """ Deletes any subconcepts associated with this concept and additionally this concept if 'delete_self' is True If any parentconcepts or relatedconcepts are included then it will only delete the relationship to those concepts but not the concepts themselves If any values are passed, then those values as well as the relationship to those values will be deleted Note, django will automatically take care of deleting any db models that have a foreign key relationship to the model being deleted (eg: deleting a concept model will also delete all values and relationships), but because we need to manage deleting parent concepts and related concepts and values we have to do that here too """ for subconcept in self.subconcepts: concepts_to_delete = Concept.gather_concepts_to_delete(subconcept) for key, concept in concepts_to_delete.items(): models.Concept.objects.get(pk=key).delete() for parentconcept in self.parentconcepts: relations_filter = ( (Q(relationtype__category="Semantic Relations") | Q(relationtype="hasTopConcept")) & Q(conceptfrom=parentconcept.id) & Q(conceptto=self.id) ) conceptrelations = models.Relation.objects.filter(relations_filter) for relation in conceptrelations: relation.delete() if models.Relation.objects.filter(relations_filter).count() == 0: # we've removed all parent concepts so now this concept needs to be promoted to a Concept Scheme concept = models.Concept.objects.get(pk=self.id) concept.nodetype_id = "ConceptScheme" concept.save() self.load(concept) for relation in models.Relation.objects.filter(conceptfrom=concept, relationtype_id="narrower"): relation.relationtype_id = "hasTopConcept" relation.save() deletedrelatedconcepts = [] for relatedconcept in self.relatedconcepts: conceptrelations = models.Relation.objects.filter( Q(relationtype="related") | Q(relationtype="member") | Q(relationtype__category="Mapping Properties"), conceptto=relatedconcept.id, conceptfrom=self.id, ) for relation in conceptrelations: relation.delete() deletedrelatedconcepts.append(relatedconcept) conceptrelations = models.Relation.objects.filter( Q(relationtype="related") | Q(relationtype="member") | Q(relationtype__category="Mapping Properties"), conceptfrom=relatedconcept.id, conceptto=self.id, ) for relation in conceptrelations: relation.delete() deletedrelatedconcepts.append(relatedconcept) for deletedrelatedconcept in deletedrelatedconcepts: if deletedrelatedconcept in self.relatedconcepts: self.relatedconcepts.remove(deletedrelatedconcept) for value in self.values: if not isinstance(value, ConceptValue): value = ConceptValue(value) value.delete() if delete_self: concepts_to_delete = Concept.gather_concepts_to_delete(self) for key, concept in concepts_to_delete.items(): # delete only member relationships if the nodetype == Collection if concept.nodetype == "Collection": concept = Concept().get( id=concept.id, include_subconcepts=True, include_parentconcepts=True, include=["label"], up_depth_limit=1, semantic=False, ) def find_concepts(concept): if len(concept.parentconcepts) <= 1: for subconcept in concept.subconcepts: conceptrelation = models.Relation.objects.get( conceptfrom=concept.id, conceptto=subconcept.id, relationtype="member" ) conceptrelation.delete() find_concepts(subconcept) find_concepts(concept) # if the concept is a collection, loop through the nodes and delete their rdmCollection values for node in models.Node.objects.filter(config__rdmCollection=concept.id): node.config["rdmCollection"] = None node.save() models.Concept.objects.get(pk=key).delete() return def add_relation(self, concepttorelate, relationtype): """ Relates this concept to 'concepttorelate' via the relationtype """ relation, created = models.Relation.objects.get_or_create( conceptfrom_id=self.id, conceptto_id=concepttorelate.id, relationtype_id=relationtype ) return relation @staticmethod def gather_concepts_to_delete(concept, lang=settings.LANGUAGE_CODE): """ Gets a dictionary of all the concepts ids to delete The values of the dictionary keys differ somewhat depending on the node type being deleted If the nodetype == 'Concept' then return ConceptValue objects keyed to the concept id If the nodetype == 'ConceptScheme' then return a ConceptValue object with the value set to any ONE prefLabel keyed to the concept id We do this because it takes so long to gather the ids of the concepts when deleting a Scheme or Group """ concepts_to_delete = {} # Here we have to worry about making sure we don't delete nodes that have more than 1 parent if concept.nodetype == "Concept": concept = Concept().get( id=concept.id, include_subconcepts=True, include_parentconcepts=True, include=["label"], up_depth_limit=1 ) def find_concepts(concept): if len(concept.parentconcepts) <= 1: concepts_to_delete[concept.id] = concept for subconcept in concept.subconcepts: find_concepts(subconcept) find_concepts(concept) return concepts_to_delete # here we can just delete everything and so use a recursive CTE to get the concept ids much more quickly if concept.nodetype == "ConceptScheme": concepts_to_delete[concept.id] = concept rows = Concept().get_child_concepts(concept.id) for row in rows: if row[0] not in concepts_to_delete: concepts_to_delete[row[0]] = Concept({"id": row[0]}) concepts_to_delete[row[0]].addvalue({"id": row[2], "conceptid": row[0], "value": row[1]}) if concept.nodetype == "Collection": concepts_to_delete[concept.id] = concept rows = Concept().get_child_collections(concept.id) for row in rows: if row[0] not in concepts_to_delete: concepts_to_delete[row[0]] = Concept({"id": row[0]}) concepts_to_delete[row[0]].addvalue({"id": row[2], "conceptid": row[0], "value": row[1]}) return concepts_to_delete def get_child_collections_hierarchically(self, conceptid, child_valuetypes=None, offset=0, limit=50, query=None): child_valuetypes = child_valuetypes if child_valuetypes else ["prefLabel"] columns = "valueidto::text, conceptidto::text, valueto, valuetypeto, depth, count(*) OVER() AS full_count, collector" return self.get_child_edges( conceptid, ["member"], child_valuetypes, offset=offset, limit=limit, order_hierarchically=True, query=query, columns=columns ) def get_child_collections(self, conceptid, child_valuetypes=None, parent_valuetype="prefLabel", columns=None, depth_limit=""): child_valuetypes = child_valuetypes if child_valuetypes else ["prefLabel"] columns = columns if columns else "conceptidto::text, valueto, valueidto::text" return self.get_child_edges(conceptid, ["member"], child_valuetypes, parent_valuetype, columns, depth_limit) def get_child_concepts(self, conceptid, child_valuetypes=None, parent_valuetype="prefLabel", columns=None, depth_limit=""): columns = columns if columns else "conceptidto::text, valueto, valueidto::text" return self.get_child_edges(conceptid, ["narrower", "hasTopConcept"], child_valuetypes, parent_valuetype, columns, depth_limit) def get_child_concepts_for_indexing(self, conceptid, child_valuetypes=None, parent_valuetype="prefLabel", depth_limit=""): columns = "valueidto::text, conceptidto::text, valuetypeto, categoryto, valueto, languageto" data = self.get_child_edges(conceptid, ["narrower", "hasTopConcept"], child_valuetypes, parent_valuetype, columns, depth_limit) return [dict(list(zip(["id", "conceptid", "type", "category", "value", "language"], d)), top_concept="") for d in data] def get_child_edges( self, conceptid, relationtypes, child_valuetypes=None, parent_valuetype="prefLabel", columns=None, depth_limit=None, offset=None, limit=20, order_hierarchically=False, query=None, languageid=None, ): """ Recursively builds a list of concept relations for a given concept and all it's subconcepts based on its relationship type and valuetypes. """ languageid = get_language() if languageid is None else languageid relationtypes = " or ".join(["r.relationtype = '%s'" % (relationtype) for relationtype in relationtypes]) depth_limit = "and depth < %s" % depth_limit if depth_limit else "" child_valuetypes = ("','").join( child_valuetypes if child_valuetypes else models.DValueType.objects.filter(category="label").values_list("valuetype", flat=True) ) limit_clause = " limit %s offset %s" % (limit, offset) if offset is not None else "" if order_hierarchically: sql = """ WITH RECURSIVE ordered_relationships AS ( ( SELECT r.conceptidfrom, r.conceptidto, r.relationtype, ( SELECT value FROM values WHERE conceptid=r.conceptidto AND valuetype in ('prefLabel') ORDER BY ( CASE WHEN languageid = '{languageid}' THEN 10 WHEN languageid like '{short_languageid}%' THEN 5 WHEN languageid like '{default_languageid}%' THEN 2 ELSE 0 END ) desc limit 1 ) as valuesto, ( SELECT value::int FROM values WHERE conceptid=r.conceptidto AND valuetype in ('sortorder') limit 1 ) as sortorder, ( SELECT value FROM values WHERE conceptid=r.conceptidto AND valuetype in ('collector') limit 1 ) as collector FROM relations r WHERE r.conceptidfrom = '{conceptid}' and ({relationtypes}) ORDER BY sortorder, valuesto ) UNION ( SELECT r.conceptidfrom, r.conceptidto, r.relationtype,( SELECT value FROM values WHERE conceptid=r.conceptidto AND valuetype in ('prefLabel') ORDER BY ( CASE WHEN languageid = '{languageid}' THEN 10 WHEN languageid like '{short_languageid}%' THEN 5 WHEN languageid like '{default_languageid}%' THEN 2 ELSE 0 END ) desc limit 1 ) as valuesto, ( SELECT value::int FROM values WHERE conceptid=r.conceptidto AND valuetype in ('sortorder') limit 1 ) as sortorder, ( SELECT value FROM values WHERE conceptid=r.conceptidto AND valuetype in ('collector') limit 1 ) as collector FROM relations r JOIN ordered_relationships b ON(b.conceptidto = r.conceptidfrom) WHERE ({relationtypes}) ORDER BY sortorder, valuesto ) ), children AS ( SELECT r.conceptidfrom, r.conceptidto, to_char(row_number() OVER (), 'fm000000') as row, r.collector, 1 AS depth ---|NonRecursive Part FROM ordered_relationships r WHERE r.conceptidfrom = '{conceptid}' and ({relationtypes}) UNION SELECT r.conceptidfrom, r.conceptidto, row || '-' || to_char(row_number() OVER (), 'fm000000'), r.collector, depth+1 ---|RecursivePart FROM ordered_relationships r JOIN children b ON(b.conceptidto = r.conceptidfrom) WHERE ({relationtypes}) {depth_limit} ) {subquery} SELECT ( select row_to_json(d) FROM ( SELECT * FROM values WHERE conceptid={recursive_table}.conceptidto AND valuetype in ('prefLabel') ORDER BY ( CASE WHEN languageid = '{languageid}' THEN 10 WHEN languageid like '{short_languageid}%' THEN 5 WHEN languageid like '{default_languageid}%' THEN 2 ELSE 0 END ) desc limit 1 ) d ) as valueto, depth, collector, count(*) OVER() AS full_count FROM {recursive_table} order by row {limit_clause}; """ subquery = ( """, results as ( SELECT c.conceptidfrom, c.conceptidto, c.row, c.depth, c.collector FROM children c JOIN values ON(values.conceptid = c.conceptidto) WHERE LOWER(values.value) like '%%%s%%' AND values.valuetype in ('prefLabel') UNION SELECT c.conceptidfrom, c.conceptidto, c.row, c.depth, c.collector FROM children c JOIN results r on (r.conceptidfrom=c.conceptidto) )""" % query.lower() if query is not None else "" ) recursive_table = "results" if query else "children" sql = sql.format( conceptid=conceptid, relationtypes=relationtypes, child_valuetypes=child_valuetypes, parent_valuetype=parent_valuetype, depth_limit=depth_limit, limit_clause=limit_clause, subquery=subquery, recursive_table=recursive_table, languageid=languageid, short_languageid=languageid.split("-")[0], default_languageid=settings.LANGUAGE_CODE, ) else: sql = """ WITH RECURSIVE children AS ( SELECT r.conceptidfrom, r.conceptidto, r.relationtype, 1 AS depth FROM relations r WHERE r.conceptidfrom = '{conceptid}' AND ({relationtypes}) UNION SELECT r.conceptidfrom, r.conceptidto, r.relationtype, depth+1 FROM relations r JOIN children c ON(c.conceptidto = r.conceptidfrom) WHERE ({relationtypes}) {depth_limit} ), results AS ( SELECT valuefrom.value as valuefrom, valueto.value as valueto, valuefrom.valueid as valueidfrom, valueto.valueid as valueidto, valuefrom.valuetype as valuetypefrom, valueto.valuetype as valuetypeto, valuefrom.languageid as languagefrom, valueto.languageid as languageto, dtypesfrom.category as categoryfrom, dtypesto.category as categoryto, c.conceptidfrom, c.conceptidto FROM values valueto JOIN d_value_types dtypesto ON(dtypesto.valuetype = valueto.valuetype) JOIN children c ON(c.conceptidto = valueto.conceptid) JOIN values valuefrom ON(c.conceptidfrom = valuefrom.conceptid) JOIN d_value_types dtypesfrom ON(dtypesfrom.valuetype = valuefrom.valuetype) WHERE valueto.valuetype in ('{child_valuetypes}') AND valuefrom.valuetype in ('{child_valuetypes}') ) SELECT distinct {columns} FROM results {limit_clause} """ if not columns: columns = """ conceptidfrom::text, conceptidto::text, valuefrom, valueto, valueidfrom::text, valueidto::text, valuetypefrom, valuetypeto, languagefrom, languageto, categoryfrom, categoryto """ sql = sql.format( conceptid=conceptid, relationtypes=relationtypes, child_valuetypes=child_valuetypes, columns=columns, depth_limit=depth_limit, limit_clause=limit_clause, ) cursor = connection.cursor() cursor.execute(sql) rows = cursor.fetchall() return rows def traverse(self, func, direction="down", scope=None, **kwargs): """ Traverses a concept graph from self to leaf (direction='down') or root (direction='up') calling the given function on each node, passes an optional scope to each function Return a value from the function to prematurely end the traversal """ _cache = kwargs.pop("_cache", []) if self.id not in _cache: _cache.append(self.id) if scope is None: ret = func(self, **kwargs) else: ret = func(self, scope, **kwargs) # break out of the traversal if the function returns a value if ret is not None: return ret if direction == "down": for subconcept in self.subconcepts: ret = subconcept.traverse(func, direction, scope, _cache=_cache, **kwargs) if ret is not None: return ret else: for parentconcept in self.parentconcepts: ret = parentconcept.traverse(func, direction, scope, _cache=_cache, **kwargs) if ret is not None: return ret def get_sortkey(self, lang=settings.LANGUAGE_CODE): for value in self.values: if value.type == "sortorder": try: return float(value.value) except: return None return self.get_preflabel(lang=lang).value def natural_keys(self, text): """ alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments) float regex comes from https://stackoverflow.com/a/12643073/190597 """ def atof(text): try: retval = float(text) except ValueError: retval = text return retval return [atof(c) for c in re.split(r"[+-]?([0-9]+(?:[.][0-9]*)?|[.][0-9]+)", str(text))] def get_preflabel(self, lang=settings.LANGUAGE_CODE): score = 0 ranked_labels = [] if self.values == []: concept = Concept().get(id=self.id, include_subconcepts=False, include_parentconcepts=False, include=["label"]) else: concept = self for value in concept.values: ranked_label = {"weight": 1, "value": value} if value.type == "prefLabel": ranked_label["weight"] = ranked_label["weight"] * 10 elif value.type == "altLabel": ranked_label["weight"] = ranked_label["weight"] * 4 if value.language == lang: ranked_label["weight"] = ranked_label["weight"] * 10 elif value.language.split("-")[0] == lang.split("-")[0]: ranked_label["weight"] = ranked_label["weight"] * 5 ranked_labels.append(ranked_label) ranked_labels = sorted(ranked_labels, key=lambda label: label["weight"], reverse=True) if len(ranked_labels) == 0: ranked_labels.append({"weight": 1, "value": ConceptValue()}) return ranked_labels[0]["value"] def flatten(self, ret=None): """ Flattens the graph into a unordered list of concepts """ if ret is None: ret = [] ret.append(self) for subconcept in self.subconcepts: subconcept.flatten(ret) return ret def addparent(self, value): if isinstance(value, dict): self.parentconcepts.append(Concept(value)) elif isinstance(value, Concept): self.parentconcepts.append(value) else: raise Exception("Invalid parent concept definition: %s" % (value)) def addsubconcept(self, value): if isinstance(value, dict): self.subconcepts.append(Concept(value)) elif isinstance(value, Concept): self.subconcepts.append(value) else: raise Exception(_("Invalid subconcept definition: %s") % (value)) def addrelatedconcept(self, value): if isinstance(value, dict): self.relatedconcepts.append(Concept(value)) elif isinstance(value, Concept): self.relatedconcepts.append(value) else: raise Exception(_("Invalid related concept definition: %s") % (value)) def addvalue(self, value): if isinstance(value, dict): value["conceptid"] = self.id self.values.append(ConceptValue(value)) elif isinstance(value, ConceptValue): self.values.append(value) elif isinstance(value, models.Value): self.values.append(ConceptValue(value)) else: raise Exception(_("Invalid value definition: %s") % (value)) def index(self, scheme=None): if scheme is None: scheme = self.get_context() for value in self.values: value.index(scheme=scheme) if self.nodetype == "ConceptScheme": scheme = None for subconcept in self.subconcepts: subconcept.index(scheme=scheme) def bulk_index(self): concept_docs = [] if self.nodetype == "ConceptScheme": concept = Concept().get(id=self.id, values=["label"]) concept.index() for topConcept in self.get_child_concepts_for_indexing(self.id, depth_limit=1): concept = Concept().get(id=topConcept["conceptid"]) scheme = concept.get_context() topConcept["top_concept"] = scheme.id concept_docs.append(se.create_bulk_item(index=CONCEPTS_INDEX, id=topConcept["id"], data=topConcept)) for childConcept in concept.get_child_concepts_for_indexing(topConcept["conceptid"]): childConcept["top_concept"] = scheme.id concept_docs.append(se.create_bulk_item(index=CONCEPTS_INDEX, id=childConcept["id"], data=childConcept)) if self.nodetype == "Concept": concept = Concept().get(id=self.id, values=["label"]) scheme = concept.get_context() concept.index(scheme) for childConcept in concept.get_child_concepts_for_indexing(self.id): childConcept["top_concept"] = scheme.id concept_docs.append(se.create_bulk_item(index=CONCEPTS_INDEX, id=childConcept["id"], data=childConcept)) se.bulk_index(concept_docs) def delete_index(self, delete_self=False): def delete_concept_values_index(concepts_to_delete): for concept in concepts_to_delete.values(): query = Query(se, start=0, limit=10000) term = Term(field="conceptid", term=concept.id) query.add_query(term) query.delete(index=CONCEPTS_INDEX) if delete_self: concepts_to_delete = Concept.gather_concepts_to_delete(self) delete_concept_values_index(concepts_to_delete) else: for subconcept in self.subconcepts: concepts_to_delete = Concept.gather_concepts_to_delete(subconcept) delete_concept_values_index(concepts_to_delete) def concept_tree( self, top_concept="00000000-0000-0000-0000-000000000001", lang=settings.LANGUAGE_CODE, mode="semantic", ): class concept(object): def __init__(self, *args, **kwargs): self.label = "" self.labelid = "" self.id = "" self.sortorder = None self.load_on_demand = False self.children = [] def _findNarrowerConcept(conceptid, depth_limit=None, level=0): labels = models.Value.objects.filter(concept=conceptid) ret = concept() temp = Concept() for label in labels: temp.addvalue(label) if label.valuetype_id == "sortorder": try: ret.sortorder = float(label.value) except: ret.sortorder = None label = temp.get_preflabel(lang=lang) ret.label = label.value ret.id = label.conceptid ret.labelid = label.id if mode == "semantic": conceptrealations = models.Relation.objects.filter( Q(conceptfrom=conceptid), Q(relationtype__category="Semantic Relations") | Q(relationtype__category="Properties") ) if mode == "collections": conceptrealations = models.Relation.objects.filter( Q(conceptfrom=conceptid), Q(relationtype="member") | Q(relationtype="hasCollection") ) if depth_limit is not None and len(conceptrealations) > 0 and level >= depth_limit: ret.load_on_demand = True else: if depth_limit is not None: level = level + 1 for relation in conceptrealations: ret.children.append(_findNarrowerConcept(relation.conceptto_id, depth_limit=depth_limit, level=level)) ret.children = sorted( ret.children, key=lambda concept: self.natural_keys(concept.sortorder if concept.sortorder else concept.label), reverse=False, ) return ret def _findBroaderConcept(conceptid, child_concept, depth_limit=None, level=0): conceptrealations = models.Relation.objects.filter( Q(conceptto=conceptid), ~Q(relationtype="related"), ~Q(relationtype__category="Mapping Properties") ) if len(conceptrealations) > 0 and conceptid != top_concept: labels = models.Value.objects.filter(concept=conceptrealations[0].conceptfrom_id) ret = concept() temp = Concept() for label in labels: temp.addvalue(label) label = temp.get_preflabel(lang=lang) ret.label = label.value ret.id = label.conceptid ret.labelid = label.id ret.children.append(child_concept) return _findBroaderConcept(conceptrealations[0].conceptfrom_id, ret, depth_limit=depth_limit, level=level) else: return child_concept graph = [] if self.id is None or self.id == "" or self.id == "None" or self.id == top_concept: if mode == "semantic": concepts = models.Concept.objects.filter(nodetype="ConceptScheme") for conceptmodel in concepts: graph.append(_findNarrowerConcept(conceptmodel.pk, depth_limit=1)) if mode == "collections": concepts = models.Concept.objects.filter(nodetype="Collection") for conceptmodel in concepts: graph.append(_findNarrowerConcept(conceptmodel.pk, depth_limit=0)) graph = sorted(graph, key=lambda concept: concept.label) # graph = _findNarrowerConcept(concepts[0].pk, depth_limit=1).children else: graph = _findNarrowerConcept(self.id, depth_limit=1).children # concepts = _findNarrowerConcept(self.id, depth_limit=1) # graph = [_findBroaderConcept(self.id, concepts, depth_limit=1)] return graph def get_paths(self, lang=settings.LANGUAGE_CODE): def graph_to_paths(current_concept, path=[], path_list=[], _cache=[]): if len(path) == 0: current_path = [] else: current_path = path[:] current_path.insert( 0, { "label": current_concept.get_preflabel(lang=lang).value, "relationshiptype": current_concept.relationshiptype, "id": current_concept.id, }, ) if len(current_concept.parentconcepts) == 0 or current_concept.id in _cache: path_list.append(current_path[:]) else: _cache.append(current_concept.id) for parent in current_concept.parentconcepts: ret = graph_to_paths(parent, current_path, path_list, _cache) return path_list # def graph_to_paths(current_concept, **kwargs): # path = kwargs.get('path', []) # path_list = kwargs.get('path_list', []) # if len(path) == 0: # current_path = [] # else: # current_path = path[:] # current_path.insert(0, {'label': current_concept.get_preflabel(lang=lang).value, 'relationshiptype': current_concept.relationshiptype, 'id': current_concept.id}) # if len(current_concept.parentconcepts) == 0: # path_list.append(current_path[:]) # # else: # # for parent in current_concept.parentconcepts: # # ret = graph_to_paths(parent, current_path, path_list, _cache) # #return path_list # self.traverse(graph_to_paths, direction='up') return graph_to_paths(self) def get_node_and_links(self, lang=settings.LANGUAGE_CODE): nodes = [{"concept_id": self.id, "name": self.get_preflabel(lang=lang).value, "type": "Current"}] links = [] def get_parent_nodes_and_links(current_concept, _cache=[]): if current_concept.id not in _cache: _cache.append(current_concept.id) parents = current_concept.parentconcepts for parent in parents: nodes.append( { "concept_id": parent.id, "name": parent.get_preflabel(lang=lang).value, "type": "Root" if len(parent.parentconcepts) == 0 else "Ancestor", } ) links.append( {"target": current_concept.id, "source": parent.id, "relationship": "broader", } ) get_parent_nodes_and_links(parent, _cache) get_parent_nodes_and_links(self) # def get_parent_nodes_and_links(current_concept): # parents = current_concept.parentconcepts # for parent in parents: # nodes.append({'concept_id': parent.id, 'name': parent.get_preflabel(lang=lang).value, 'type': 'Root' if len(parent.parentconcepts) == 0 else 'Ancestor'}) # links.append({'target': current_concept.id, 'source': parent.id, 'relationship': 'broader' }) # self.traverse(get_parent_nodes_and_links, direction='up') for child in self.subconcepts: nodes.append( {"concept_id": child.id, "name": child.get_preflabel(lang=lang).value, "type": "Descendant", } ) links.append({"source": self.id, "target": child.id, "relationship": "narrower"}) for related in self.relatedconcepts: nodes.append( {"concept_id": related.id, "name": related.get_preflabel(lang=lang).value, "type": "Related", } ) links.append({"source": self.id, "target": related.id, "relationship": "related"}) # get unique node list and assign unique integer ids for each node (required by d3) nodes = list({node["concept_id"]: node for node in nodes}.values()) for i in range(len(nodes)): nodes[i]["id"] = i for link in links: link["source"] = i if link["source"] == nodes[i]["concept_id"] else link["source"] link["target"] = i if link["target"] == nodes[i]["concept_id"] else link["target"] return {"nodes": nodes, "links": links} def get_context(self): """ get the Top Concept that the Concept particpates in """ if self.nodetype == "Concept" or self.nodetype == "Collection": concept = Concept().get(id=self.id, include_parentconcepts=True, include=None) def get_scheme_id(concept): for parentconcept in concept.parentconcepts: if parentconcept.relationshiptype == "hasTopConcept": return concept if len(concept.parentconcepts) > 0: return concept.traverse(get_scheme_id, direction="up") else: return self else: # like ConceptScheme or EntityType return self def get_scheme(self): """ get the ConceptScheme that the Concept particpates in """ topConcept = self.get_context() if len(topConcept.parentconcepts) == 1: if topConcept.parentconcepts[0].nodetype == "ConceptScheme": return topConcept.parentconcepts[0] return None def check_if_concept_in_use(self): """Checks if a concept or any of its subconcepts is in use by a resource instance""" in_use = False cursor = connection.cursor() for value in self.values: sql = ( """ SELECT count(*) from tiles t, jsonb_each_text(t.tiledata) as json_data WHERE json_data.value = '%s' """ % value.id ) cursor.execute(sql) rows = cursor.fetchall() if rows[0][0] > 0: in_use = True break if in_use is not True: for subconcept in self.subconcepts: in_use = subconcept.check_if_concept_in_use() if in_use == True: return in_use return in_use def get_e55_domain(self, conceptid): """ For a given entitytypeid creates a dictionary representing that entitytypeid's concept graph (member pathway) formatted to support select2 dropdowns """ cursor = connection.cursor() sql = """ WITH RECURSIVE children AS ( SELECT d.conceptidfrom, d.conceptidto, c2.value, c2.valueid as valueid, c.value as valueto, c.valueid as valueidto, c.valuetype as vtype, 1 AS depth, array[d.conceptidto] AS conceptpath, array[c.valueid] AS idpath ---|NonRecursive Part FROM relations d JOIN values c ON(c.conceptid = d.conceptidto) JOIN values c2 ON(c2.conceptid = d.conceptidfrom) WHERE d.conceptidfrom = '{0}' and c2.valuetype = 'prefLabel' and c.valuetype in ('prefLabel', 'sortorder', 'collector') and (d.relationtype = 'member' or d.relationtype = 'hasTopConcept') UNION SELECT d.conceptidfrom, d.conceptidto, v2.value, v2.valueid as valueid, v.value as valueto, v.valueid as valueidto, v.valuetype as vtype, depth+1, (conceptpath || d.conceptidto), (idpath || v.valueid) ---|RecursivePart FROM relations d JOIN children b ON(b.conceptidto = d.conceptidfrom) JOIN values v ON(v.conceptid = d.conceptidto) JOIN values v2 ON(v2.conceptid = d.conceptidfrom) WHERE v2.valuetype = 'prefLabel' and v.valuetype in ('prefLabel','sortorder', 'collector') and (d.relationtype = 'member' or d.relationtype = 'hasTopConcept') ) SELECT conceptidfrom::text, conceptidto::text, value, valueid::text, valueto, valueidto::text, depth, idpath::text, conceptpath::text, vtype FROM children ORDER BY depth, conceptpath; """.format( conceptid ) column_names = [ "conceptidfrom", "conceptidto", "value", "valueid", "valueto", "valueidto", "depth", "idpath", "conceptpath", "vtype", ] cursor.execute(sql) rows = cursor.fetchall() class Val(object): def __init__(self, conceptid): self.text = "" self.conceptid = conceptid self.id = "" self.sortorder = "" self.collector = "" self.children = [] result = Val(conceptid) def _findNarrower(val, path, rec): for conceptid in path: childids = [child.conceptid for child in val.children] if conceptid not in childids: new_val = Val(rec["conceptidto"]) if rec["vtype"] == "sortorder": new_val.sortorder = rec["valueto"] elif rec["vtype"] == "prefLabel": new_val.text = rec["valueto"] new_val.id = rec["valueidto"] elif rec["vtype"] == "collector": new_val.collector = "collector" val.children.append(new_val) else: for child in val.children: if conceptid == child.conceptid: if conceptid == path[-1]: if rec["vtype"] == "sortorder": child.sortorder = rec["valueto"] elif rec["vtype"] == "prefLabel": child.text = rec["valueto"] child.id = rec["valueidto"] elif rec["vtype"] == "collector": child.collector = "collector" path.pop(0) _findNarrower(child, path, rec) val.children.sort(key=lambda x: (x.sortorder, x.text)) for row in rows: rec = dict(list(zip(column_names, row))) path = rec["conceptpath"][1:-1].split(",") _findNarrower(result, path, rec) return JSONSerializer().serializeToPython(result)["children"] def make_collection(self): if len(self.values) == 0: raise Exception(_("Need to include values when creating a collection")) values = JSONSerializer().serializeToPython(self.values) for value in values: value["id"] = "" collection_concept = Concept({"nodetype": "Collection", "values": values}) def create_collection(conceptfrom): for relation in models.Relation.objects.filter( Q(conceptfrom_id=conceptfrom.id), Q(relationtype__category="Semantic Relations") | Q(relationtype__category="Properties"), ~Q(relationtype="related"), ): conceptto = Concept(relation.conceptto) if conceptfrom == self: collection_concept.add_relation(conceptto, "member") else: conceptfrom.add_relation(conceptto, "member") create_collection(conceptto) with transaction.atomic(): collection_concept.save() create_collection(self) return collection_concept class ConceptValue(object): def __init__(self, *args, **kwargs): self.id = "" self.conceptid = "" self.type = "" self.category = "" self.value = "" self.language = "" if len(args) != 0: if isinstance(args[0], str): try: uuid.UUID(args[0]) self.get(args[0]) except (ValueError): self.load(JSONDeserializer().deserialize(args[0])) elif isinstance(args[0], object): self.load(args[0]) def __repr__(self): return ('%s: %s = "%s" in lang %s') % (self.__class__, self.type, self.value, self.language) def get(self, id=""): self.load(models.Value.objects.get(pk=id)) return self def save(self): if self.value.strip() != "": self.id = self.id if (self.id != "" and self.id is not None) else str(uuid.uuid4()) value = models.Value() value.pk = self.id value.value = self.value value.concept_id = self.conceptid # models.Concept.objects.get(pk=self.conceptid) value.valuetype_id = self.type # models.DValueType.objects.get(pk=self.type) if self.language != "": # need to normalize language ids to the form xx-XX lang_parts = self.language.lower().replace("_", "-").split("-") try: lang_parts[1] = lang_parts[1].upper() except: pass self.language = "-".join(lang_parts) value.language_id = self.language # models.DLanguage.objects.get(pk=self.language) else: value.language_id = settings.LANGUAGE_CODE value.save() self.category = value.valuetype.category def delete(self): if self.id != "": newvalue = models.Value.objects.get(pk=self.id) if newvalue.valuetype.valuetype == "image": newvalue = models.FileValue.objects.get(pk=self.id) newvalue.delete() self = ConceptValue() return self def load(self, value): if isinstance(value, models.Value): self.id = str(value.pk) self.conceptid = str(value.concept_id) self.type = value.valuetype_id self.category = value.valuetype.category self.value = value.value self.language = value.language_id if isinstance(value, dict): self.id = str(value["id"]) if "id" in value else "" self.conceptid = str(value["conceptid"]) if "conceptid" in value else "" self.type = value["type"] if "type" in value else "" self.category = value["category"] if "category" in value else "" self.value = value["value"] if "value" in value else "" self.language = value["language"] if "language" in value else "" def index(self, scheme=None): if self.category == "label": data = JSONSerializer().serializeToPython(self) if scheme is None: scheme = self.get_scheme_id() if scheme is None: raise Exception(_("Index of label failed. Index type (scheme id) could not be derived from the label.")) data["top_concept"] = scheme.id se.index_data(index=CONCEPTS_INDEX, body=data, idfield="id") def delete_index(self): query = Query(se, start=0, limit=10000) term = Term(field="id", term=self.id) query.add_query(term) query.delete(index=CONCEPTS_INDEX) def get_scheme_id(self): result = se.search(index=CONCEPTS_INDEX, id=self.id) if result["found"]: return Concept(result["top_concept"]) else: return None def get_preflabel_from_conceptid(conceptid, lang): ret = None default = { "category": "", "conceptid": "", "language": "", "value": "", "type": "", "id": "", } query = Query(se) bool_query = Bool() bool_query.must(Match(field="type", query="prefLabel", type="phrase")) bool_query.filter(Terms(field="conceptid", terms=[conceptid])) query.add_query(bool_query) preflabels = query.search(index=CONCEPTS_INDEX)["hits"]["hits"] for preflabel in preflabels: default = preflabel["_source"] if preflabel["_source"]["language"] is not None and lang is not None: # get the label in the preferred language, otherwise get the label in the default language if preflabel["_source"]["language"] == lang: return preflabel["_source"] if preflabel["_source"]["language"].split("-")[0] == lang.split("-")[0]: ret = preflabel["_source"] if preflabel["_source"]["language"] == settings.LANGUAGE_CODE and ret is None: ret = preflabel["_source"] return default if ret is None else ret def get_valueids_from_concept_label(label, conceptid=None, lang=None): def exact_val_match(val, conceptid=None): # exact term match, don't care about relevance ordering. # due to language formating issues, and with (hopefully) small result sets # easier to have filter logic in python than to craft it in dsl if conceptid is None: return {"query": {"bool": {"filter": {"match_phrase": {"value": val}}}}} else: return { "query": { "bool": {"filter": [{"match_phrase": {"value": val}}, {"term": {"conceptid": conceptid}}, ]} } } concept_label_results = se.search(index=CONCEPTS_INDEX, body=exact_val_match(label, conceptid)) if concept_label_results is None: print("Found no matches for label:'{0}' and concept_id: '{1}'".format(label, conceptid)) return return [ res["_source"] for res in concept_label_results["hits"]["hits"] if lang is None or res["_source"]["language"].lower() == lang.lower() ] def get_preflabel_from_valueid(valueid, lang): concept_label = se.search(index=CONCEPTS_INDEX, id=valueid) if concept_label["found"]: return get_preflabel_from_conceptid(concept_label["_source"]["conceptid"], lang)
""" ARCHES - a program developed to inventory and manage immovable cultural heritage. Copyright (C) 2013 <NAME> and World Monuments Fund This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import re import uuid import copy from operator import itemgetter from operator import methodcaller from django.db import transaction, connection from django.db.models import Q from arches.app.models import models from arches.app.models.system_settings import settings from arches.app.search.search_engine_factory import SearchEngineInstance as se from arches.app.search.elasticsearch_dsl_builder import Term, Query, Bool, Match, Terms from arches.app.search.mappings import CONCEPTS_INDEX from arches.app.utils.betterJSONSerializer import JSONSerializer, JSONDeserializer from django.utils.translation import ugettext as _ from django.utils.translation import get_language from django.db import IntegrityError import logging logger = logging.getLogger(__name__) CORE_CONCEPTS = ( "00000000-0000-0000-0000-000000000001", "00000000-0000-0000-0000-000000000004", "00000000-0000-0000-0000-000000000005", "00000000-0000-0000-0000-000000000006", ) class Concept(object): def __init__(self, *args, **kwargs): self.id = "" self.nodetype = "" self.legacyoid = "" self.relationshiptype = "" self.values = [] self.subconcepts = [] self.parentconcepts = [] self.relatedconcepts = [] self.hassubconcepts = False if len(args) != 0: if isinstance(args[0], str): try: uuid.UUID(args[0]) self.get(args[0]) except (ValueError): self.load(JSONDeserializer().deserialize(args[0])) elif isinstance(args[0], dict): self.load(args[0]) elif isinstance(args[0], object): self.load(args[0]) def __unicode__(self): return ("%s - %s") % (self.get_preflabel().value, self.id) def __hash__(self): return hash(self.id) def __eq__(self, x): return hash(self) == hash(x) def __ne__(self, x): return hash(self) != hash(x) def load(self, value): if isinstance(value, dict): self.id = str(value["id"]) if "id" in value else "" self.nodetype = value["nodetype"] if "nodetype" in value else "" self.legacyoid = value["legacyoid"] if "legacyoid" in value else "" self.relationshiptype = value["relationshiptype"] if "relationshiptype" in value else "" if "values" in value: for val in value["values"]: self.addvalue(val) if "subconcepts" in value: for subconcept in value["subconcepts"]: self.addsubconcept(subconcept) if "parentconcepts" in value: for parentconcept in value["parentconcepts"]: self.addparent(parentconcept) if "relatedconcepts" in value: for relatedconcept in value["relatedconcepts"]: self.addrelatedconcept(relatedconcept) if isinstance(value, models.Concept): self.id = str(value.pk) self.nodetype = value.nodetype_id self.legacyoid = value.legacyoid def get( self, id="", legacyoid="", include_subconcepts=False, include_parentconcepts=False, include_relatedconcepts=False, exclude=[], include=[], depth_limit=None, up_depth_limit=None, lang=settings.LANGUAGE_CODE, semantic=True, pathway_filter=None, **kwargs, ): if id != "": self.load(models.Concept.objects.get(pk=id)) elif legacyoid != "": self.load(models.Concept.objects.get(legacyoid=legacyoid)) _cache = kwargs.pop("_cache", {}) _cache[self.id] = self.__class__( {"id": self.id, "nodetype": self.nodetype, "legacyoid": self.legacyoid, "relationshiptype": self.relationshiptype} ) if semantic == True: pathway_filter = ( pathway_filter if pathway_filter else Q(relationtype__category="Semantic Relations") | Q(relationtype__category="Properties") ) else: pathway_filter = pathway_filter if pathway_filter else Q(relationtype="member") | Q(relationtype="hasCollection") if self.id != "": nodetype = kwargs.pop("nodetype", self.nodetype) uplevel = kwargs.pop("uplevel", 0) downlevel = kwargs.pop("downlevel", 0) depth_limit = depth_limit if depth_limit is None else int(depth_limit) up_depth_limit = up_depth_limit if up_depth_limit is None else int(up_depth_limit) if include is not None: if len(include) > 0 and len(exclude) > 0: raise Exception(_("Only include values for include or exclude, but not both")) include = ( include if len(include) != 0 else models.DValueType.objects.distinct("category").values_list("category", flat=True) ) include = set(include).difference(exclude) exclude = [] if len(include) > 0: values = models.Value.objects.filter(concept=self.id) for value in values: if value.valuetype.category in include: self.values.append(ConceptValue(value)) hassubconcepts = models.Relation.objects.filter(Q(conceptfrom=self.id), pathway_filter, ~Q(relationtype="related"))[0:1] if len(hassubconcepts) > 0: self.hassubconcepts = True if include_subconcepts: conceptrealations = models.Relation.objects.filter(Q(conceptfrom=self.id), pathway_filter, ~Q(relationtype="related")) if depth_limit is None or downlevel < depth_limit: if depth_limit is not None: downlevel = downlevel + 1 for relation in conceptrealations: subconcept = ( _cache[str(relation.conceptto_id)] if str(relation.conceptto_id) in _cache else self.__class__().get( id=relation.conceptto_id, include_subconcepts=include_subconcepts, include_parentconcepts=include_parentconcepts, include_relatedconcepts=include_relatedconcepts, exclude=exclude, include=include, depth_limit=depth_limit, up_depth_limit=up_depth_limit, downlevel=downlevel, uplevel=uplevel, nodetype=nodetype, semantic=semantic, pathway_filter=pathway_filter, _cache=_cache.copy(), lang=lang, ) ) subconcept.relationshiptype = relation.relationtype_id self.subconcepts.append(subconcept) self.subconcepts = sorted( self.subconcepts, key=lambda concept: self.natural_keys(concept.get_sortkey(lang)), reverse=False ) # self.subconcepts = sorted(self.subconcepts, key=methodcaller( # 'get_sortkey', lang=lang), reverse=False) if include_parentconcepts: conceptrealations = models.Relation.objects.filter(Q(conceptto=self.id), pathway_filter, ~Q(relationtype="related")) if up_depth_limit is None or uplevel < up_depth_limit: if up_depth_limit is not None: uplevel = uplevel + 1 for relation in conceptrealations: parentconcept = ( _cache[str(relation.conceptfrom_id)] if str(relation.conceptfrom_id) in _cache else self.__class__().get( id=relation.conceptfrom_id, include_subconcepts=False, include_parentconcepts=include_parentconcepts, include_relatedconcepts=include_relatedconcepts, exclude=exclude, include=include, depth_limit=depth_limit, up_depth_limit=up_depth_limit, downlevel=downlevel, uplevel=uplevel, nodetype=nodetype, semantic=semantic, pathway_filter=pathway_filter, _cache=_cache.copy(), lang=lang, ) ) parentconcept.relationshiptype = relation.relationtype_id self.parentconcepts.append(parentconcept) if include_relatedconcepts: conceptrealations = models.Relation.objects.filter( Q(relationtype="related") | Q(relationtype__category="Mapping Properties"), Q(conceptto=self.id) | Q(conceptfrom=self.id), ) relations = [] for relation in conceptrealations: if str(relation.conceptto_id) != self.id and str(relation.relationid) not in relations: relations.append(str(relation.relationid)) relatedconcept = self.__class__().get(relation.conceptto_id, include=["label"], lang=lang) relatedconcept.relationshiptype = relation.relationtype_id self.relatedconcepts.append(relatedconcept) if str(relation.conceptfrom_id) != self.id and str(relation.relationid) not in relations: relations.append(str(relation.relationid)) relatedconcept = self.__class__().get(relation.conceptfrom_id, include=["label"], lang=lang) relatedconcept.relationshiptype = relation.relationtype_id self.relatedconcepts.append(relatedconcept) return self def save(self): self.id = self.id if (self.id != "" and self.id is not None) else str(uuid.uuid4()) concept, created = models.Concept.objects.get_or_create( pk=self.id, defaults={"legacyoid": self.legacyoid if self.legacyoid != "" else self.id, "nodetype_id": self.nodetype} ) for value in self.values: if not isinstance(value, ConceptValue): value = ConceptValue(value) value.conceptid = self.id value.save() for parentconcept in self.parentconcepts: parentconcept.save() parentconcept.add_relation(self, parentconcept.relationshiptype) for subconcept in self.subconcepts: subconcept.save() self.add_relation(subconcept, subconcept.relationshiptype) # if we're moving a Concept Scheme below another Concept or Concept Scheme if len(self.parentconcepts) > 0 and concept.nodetype_id == "ConceptScheme": concept.nodetype_id = "Concept" concept.save() self.load(concept) for relation in models.Relation.objects.filter(conceptfrom=concept, relationtype_id="hasTopConcept"): relation.relationtype_id = "narrower" relation.save() for relatedconcept in self.relatedconcepts: self.add_relation(relatedconcept, relatedconcept.relationshiptype) if relatedconcept.relationshiptype == "member": child_concepts = relatedconcept.get(include_subconcepts=True) def applyRelationship(concept): for subconcept in concept.subconcepts: concept.add_relation(subconcept, relatedconcept.relationshiptype) child_concepts.traverse(applyRelationship) return concept def delete(self, delete_self=False): """ Deletes any subconcepts associated with this concept and additionally this concept if 'delete_self' is True If any parentconcepts or relatedconcepts are included then it will only delete the relationship to those concepts but not the concepts themselves If any values are passed, then those values as well as the relationship to those values will be deleted Note, django will automatically take care of deleting any db models that have a foreign key relationship to the model being deleted (eg: deleting a concept model will also delete all values and relationships), but because we need to manage deleting parent concepts and related concepts and values we have to do that here too """ for subconcept in self.subconcepts: concepts_to_delete = Concept.gather_concepts_to_delete(subconcept) for key, concept in concepts_to_delete.items(): models.Concept.objects.get(pk=key).delete() for parentconcept in self.parentconcepts: relations_filter = ( (Q(relationtype__category="Semantic Relations") | Q(relationtype="hasTopConcept")) & Q(conceptfrom=parentconcept.id) & Q(conceptto=self.id) ) conceptrelations = models.Relation.objects.filter(relations_filter) for relation in conceptrelations: relation.delete() if models.Relation.objects.filter(relations_filter).count() == 0: # we've removed all parent concepts so now this concept needs to be promoted to a Concept Scheme concept = models.Concept.objects.get(pk=self.id) concept.nodetype_id = "ConceptScheme" concept.save() self.load(concept) for relation in models.Relation.objects.filter(conceptfrom=concept, relationtype_id="narrower"): relation.relationtype_id = "hasTopConcept" relation.save() deletedrelatedconcepts = [] for relatedconcept in self.relatedconcepts: conceptrelations = models.Relation.objects.filter( Q(relationtype="related") | Q(relationtype="member") | Q(relationtype__category="Mapping Properties"), conceptto=relatedconcept.id, conceptfrom=self.id, ) for relation in conceptrelations: relation.delete() deletedrelatedconcepts.append(relatedconcept) conceptrelations = models.Relation.objects.filter( Q(relationtype="related") | Q(relationtype="member") | Q(relationtype__category="Mapping Properties"), conceptfrom=relatedconcept.id, conceptto=self.id, ) for relation in conceptrelations: relation.delete() deletedrelatedconcepts.append(relatedconcept) for deletedrelatedconcept in deletedrelatedconcepts: if deletedrelatedconcept in self.relatedconcepts: self.relatedconcepts.remove(deletedrelatedconcept) for value in self.values: if not isinstance(value, ConceptValue): value = ConceptValue(value) value.delete() if delete_self: concepts_to_delete = Concept.gather_concepts_to_delete(self) for key, concept in concepts_to_delete.items(): # delete only member relationships if the nodetype == Collection if concept.nodetype == "Collection": concept = Concept().get( id=concept.id, include_subconcepts=True, include_parentconcepts=True, include=["label"], up_depth_limit=1, semantic=False, ) def find_concepts(concept): if len(concept.parentconcepts) <= 1: for subconcept in concept.subconcepts: conceptrelation = models.Relation.objects.get( conceptfrom=concept.id, conceptto=subconcept.id, relationtype="member" ) conceptrelation.delete() find_concepts(subconcept) find_concepts(concept) # if the concept is a collection, loop through the nodes and delete their rdmCollection values for node in models.Node.objects.filter(config__rdmCollection=concept.id): node.config["rdmCollection"] = None node.save() models.Concept.objects.get(pk=key).delete() return def add_relation(self, concepttorelate, relationtype): """ Relates this concept to 'concepttorelate' via the relationtype """ relation, created = models.Relation.objects.get_or_create( conceptfrom_id=self.id, conceptto_id=concepttorelate.id, relationtype_id=relationtype ) return relation @staticmethod def gather_concepts_to_delete(concept, lang=settings.LANGUAGE_CODE): """ Gets a dictionary of all the concepts ids to delete The values of the dictionary keys differ somewhat depending on the node type being deleted If the nodetype == 'Concept' then return ConceptValue objects keyed to the concept id If the nodetype == 'ConceptScheme' then return a ConceptValue object with the value set to any ONE prefLabel keyed to the concept id We do this because it takes so long to gather the ids of the concepts when deleting a Scheme or Group """ concepts_to_delete = {} # Here we have to worry about making sure we don't delete nodes that have more than 1 parent if concept.nodetype == "Concept": concept = Concept().get( id=concept.id, include_subconcepts=True, include_parentconcepts=True, include=["label"], up_depth_limit=1 ) def find_concepts(concept): if len(concept.parentconcepts) <= 1: concepts_to_delete[concept.id] = concept for subconcept in concept.subconcepts: find_concepts(subconcept) find_concepts(concept) return concepts_to_delete # here we can just delete everything and so use a recursive CTE to get the concept ids much more quickly if concept.nodetype == "ConceptScheme": concepts_to_delete[concept.id] = concept rows = Concept().get_child_concepts(concept.id) for row in rows: if row[0] not in concepts_to_delete: concepts_to_delete[row[0]] = Concept({"id": row[0]}) concepts_to_delete[row[0]].addvalue({"id": row[2], "conceptid": row[0], "value": row[1]}) if concept.nodetype == "Collection": concepts_to_delete[concept.id] = concept rows = Concept().get_child_collections(concept.id) for row in rows: if row[0] not in concepts_to_delete: concepts_to_delete[row[0]] = Concept({"id": row[0]}) concepts_to_delete[row[0]].addvalue({"id": row[2], "conceptid": row[0], "value": row[1]}) return concepts_to_delete def get_child_collections_hierarchically(self, conceptid, child_valuetypes=None, offset=0, limit=50, query=None): child_valuetypes = child_valuetypes if child_valuetypes else ["prefLabel"] columns = "valueidto::text, conceptidto::text, valueto, valuetypeto, depth, count(*) OVER() AS full_count, collector" return self.get_child_edges( conceptid, ["member"], child_valuetypes, offset=offset, limit=limit, order_hierarchically=True, query=query, columns=columns ) def get_child_collections(self, conceptid, child_valuetypes=None, parent_valuetype="prefLabel", columns=None, depth_limit=""): child_valuetypes = child_valuetypes if child_valuetypes else ["prefLabel"] columns = columns if columns else "conceptidto::text, valueto, valueidto::text" return self.get_child_edges(conceptid, ["member"], child_valuetypes, parent_valuetype, columns, depth_limit) def get_child_concepts(self, conceptid, child_valuetypes=None, parent_valuetype="prefLabel", columns=None, depth_limit=""): columns = columns if columns else "conceptidto::text, valueto, valueidto::text" return self.get_child_edges(conceptid, ["narrower", "hasTopConcept"], child_valuetypes, parent_valuetype, columns, depth_limit) def get_child_concepts_for_indexing(self, conceptid, child_valuetypes=None, parent_valuetype="prefLabel", depth_limit=""): columns = "valueidto::text, conceptidto::text, valuetypeto, categoryto, valueto, languageto" data = self.get_child_edges(conceptid, ["narrower", "hasTopConcept"], child_valuetypes, parent_valuetype, columns, depth_limit) return [dict(list(zip(["id", "conceptid", "type", "category", "value", "language"], d)), top_concept="") for d in data] def get_child_edges( self, conceptid, relationtypes, child_valuetypes=None, parent_valuetype="prefLabel", columns=None, depth_limit=None, offset=None, limit=20, order_hierarchically=False, query=None, languageid=None, ): """ Recursively builds a list of concept relations for a given concept and all it's subconcepts based on its relationship type and valuetypes. """ languageid = get_language() if languageid is None else languageid relationtypes = " or ".join(["r.relationtype = '%s'" % (relationtype) for relationtype in relationtypes]) depth_limit = "and depth < %s" % depth_limit if depth_limit else "" child_valuetypes = ("','").join( child_valuetypes if child_valuetypes else models.DValueType.objects.filter(category="label").values_list("valuetype", flat=True) ) limit_clause = " limit %s offset %s" % (limit, offset) if offset is not None else "" if order_hierarchically: sql = """ WITH RECURSIVE ordered_relationships AS ( ( SELECT r.conceptidfrom, r.conceptidto, r.relationtype, ( SELECT value FROM values WHERE conceptid=r.conceptidto AND valuetype in ('prefLabel') ORDER BY ( CASE WHEN languageid = '{languageid}' THEN 10 WHEN languageid like '{short_languageid}%' THEN 5 WHEN languageid like '{default_languageid}%' THEN 2 ELSE 0 END ) desc limit 1 ) as valuesto, ( SELECT value::int FROM values WHERE conceptid=r.conceptidto AND valuetype in ('sortorder') limit 1 ) as sortorder, ( SELECT value FROM values WHERE conceptid=r.conceptidto AND valuetype in ('collector') limit 1 ) as collector FROM relations r WHERE r.conceptidfrom = '{conceptid}' and ({relationtypes}) ORDER BY sortorder, valuesto ) UNION ( SELECT r.conceptidfrom, r.conceptidto, r.relationtype,( SELECT value FROM values WHERE conceptid=r.conceptidto AND valuetype in ('prefLabel') ORDER BY ( CASE WHEN languageid = '{languageid}' THEN 10 WHEN languageid like '{short_languageid}%' THEN 5 WHEN languageid like '{default_languageid}%' THEN 2 ELSE 0 END ) desc limit 1 ) as valuesto, ( SELECT value::int FROM values WHERE conceptid=r.conceptidto AND valuetype in ('sortorder') limit 1 ) as sortorder, ( SELECT value FROM values WHERE conceptid=r.conceptidto AND valuetype in ('collector') limit 1 ) as collector FROM relations r JOIN ordered_relationships b ON(b.conceptidto = r.conceptidfrom) WHERE ({relationtypes}) ORDER BY sortorder, valuesto ) ), children AS ( SELECT r.conceptidfrom, r.conceptidto, to_char(row_number() OVER (), 'fm000000') as row, r.collector, 1 AS depth ---|NonRecursive Part FROM ordered_relationships r WHERE r.conceptidfrom = '{conceptid}' and ({relationtypes}) UNION SELECT r.conceptidfrom, r.conceptidto, row || '-' || to_char(row_number() OVER (), 'fm000000'), r.collector, depth+1 ---|RecursivePart FROM ordered_relationships r JOIN children b ON(b.conceptidto = r.conceptidfrom) WHERE ({relationtypes}) {depth_limit} ) {subquery} SELECT ( select row_to_json(d) FROM ( SELECT * FROM values WHERE conceptid={recursive_table}.conceptidto AND valuetype in ('prefLabel') ORDER BY ( CASE WHEN languageid = '{languageid}' THEN 10 WHEN languageid like '{short_languageid}%' THEN 5 WHEN languageid like '{default_languageid}%' THEN 2 ELSE 0 END ) desc limit 1 ) d ) as valueto, depth, collector, count(*) OVER() AS full_count FROM {recursive_table} order by row {limit_clause}; """ subquery = ( """, results as ( SELECT c.conceptidfrom, c.conceptidto, c.row, c.depth, c.collector FROM children c JOIN values ON(values.conceptid = c.conceptidto) WHERE LOWER(values.value) like '%%%s%%' AND values.valuetype in ('prefLabel') UNION SELECT c.conceptidfrom, c.conceptidto, c.row, c.depth, c.collector FROM children c JOIN results r on (r.conceptidfrom=c.conceptidto) )""" % query.lower() if query is not None else "" ) recursive_table = "results" if query else "children" sql = sql.format( conceptid=conceptid, relationtypes=relationtypes, child_valuetypes=child_valuetypes, parent_valuetype=parent_valuetype, depth_limit=depth_limit, limit_clause=limit_clause, subquery=subquery, recursive_table=recursive_table, languageid=languageid, short_languageid=languageid.split("-")[0], default_languageid=settings.LANGUAGE_CODE, ) else: sql = """ WITH RECURSIVE children AS ( SELECT r.conceptidfrom, r.conceptidto, r.relationtype, 1 AS depth FROM relations r WHERE r.conceptidfrom = '{conceptid}' AND ({relationtypes}) UNION SELECT r.conceptidfrom, r.conceptidto, r.relationtype, depth+1 FROM relations r JOIN children c ON(c.conceptidto = r.conceptidfrom) WHERE ({relationtypes}) {depth_limit} ), results AS ( SELECT valuefrom.value as valuefrom, valueto.value as valueto, valuefrom.valueid as valueidfrom, valueto.valueid as valueidto, valuefrom.valuetype as valuetypefrom, valueto.valuetype as valuetypeto, valuefrom.languageid as languagefrom, valueto.languageid as languageto, dtypesfrom.category as categoryfrom, dtypesto.category as categoryto, c.conceptidfrom, c.conceptidto FROM values valueto JOIN d_value_types dtypesto ON(dtypesto.valuetype = valueto.valuetype) JOIN children c ON(c.conceptidto = valueto.conceptid) JOIN values valuefrom ON(c.conceptidfrom = valuefrom.conceptid) JOIN d_value_types dtypesfrom ON(dtypesfrom.valuetype = valuefrom.valuetype) WHERE valueto.valuetype in ('{child_valuetypes}') AND valuefrom.valuetype in ('{child_valuetypes}') ) SELECT distinct {columns} FROM results {limit_clause} """ if not columns: columns = """ conceptidfrom::text, conceptidto::text, valuefrom, valueto, valueidfrom::text, valueidto::text, valuetypefrom, valuetypeto, languagefrom, languageto, categoryfrom, categoryto """ sql = sql.format( conceptid=conceptid, relationtypes=relationtypes, child_valuetypes=child_valuetypes, columns=columns, depth_limit=depth_limit, limit_clause=limit_clause, ) cursor = connection.cursor() cursor.execute(sql) rows = cursor.fetchall() return rows def traverse(self, func, direction="down", scope=None, **kwargs): """ Traverses a concept graph from self to leaf (direction='down') or root (direction='up') calling the given function on each node, passes an optional scope to each function Return a value from the function to prematurely end the traversal """ _cache = kwargs.pop("_cache", []) if self.id not in _cache: _cache.append(self.id) if scope is None: ret = func(self, **kwargs) else: ret = func(self, scope, **kwargs) # break out of the traversal if the function returns a value if ret is not None: return ret if direction == "down": for subconcept in self.subconcepts: ret = subconcept.traverse(func, direction, scope, _cache=_cache, **kwargs) if ret is not None: return ret else: for parentconcept in self.parentconcepts: ret = parentconcept.traverse(func, direction, scope, _cache=_cache, **kwargs) if ret is not None: return ret def get_sortkey(self, lang=settings.LANGUAGE_CODE): for value in self.values: if value.type == "sortorder": try: return float(value.value) except: return None return self.get_preflabel(lang=lang).value def natural_keys(self, text): """ alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments) float regex comes from https://stackoverflow.com/a/12643073/190597 """ def atof(text): try: retval = float(text) except ValueError: retval = text return retval return [atof(c) for c in re.split(r"[+-]?([0-9]+(?:[.][0-9]*)?|[.][0-9]+)", str(text))] def get_preflabel(self, lang=settings.LANGUAGE_CODE): score = 0 ranked_labels = [] if self.values == []: concept = Concept().get(id=self.id, include_subconcepts=False, include_parentconcepts=False, include=["label"]) else: concept = self for value in concept.values: ranked_label = {"weight": 1, "value": value} if value.type == "prefLabel": ranked_label["weight"] = ranked_label["weight"] * 10 elif value.type == "altLabel": ranked_label["weight"] = ranked_label["weight"] * 4 if value.language == lang: ranked_label["weight"] = ranked_label["weight"] * 10 elif value.language.split("-")[0] == lang.split("-")[0]: ranked_label["weight"] = ranked_label["weight"] * 5 ranked_labels.append(ranked_label) ranked_labels = sorted(ranked_labels, key=lambda label: label["weight"], reverse=True) if len(ranked_labels) == 0: ranked_labels.append({"weight": 1, "value": ConceptValue()}) return ranked_labels[0]["value"] def flatten(self, ret=None): """ Flattens the graph into a unordered list of concepts """ if ret is None: ret = [] ret.append(self) for subconcept in self.subconcepts: subconcept.flatten(ret) return ret def addparent(self, value): if isinstance(value, dict): self.parentconcepts.append(Concept(value)) elif isinstance(value, Concept): self.parentconcepts.append(value) else: raise Exception("Invalid parent concept definition: %s" % (value)) def addsubconcept(self, value): if isinstance(value, dict): self.subconcepts.append(Concept(value)) elif isinstance(value, Concept): self.subconcepts.append(value) else: raise Exception(_("Invalid subconcept definition: %s") % (value)) def addrelatedconcept(self, value): if isinstance(value, dict): self.relatedconcepts.append(Concept(value)) elif isinstance(value, Concept): self.relatedconcepts.append(value) else: raise Exception(_("Invalid related concept definition: %s") % (value)) def addvalue(self, value): if isinstance(value, dict): value["conceptid"] = self.id self.values.append(ConceptValue(value)) elif isinstance(value, ConceptValue): self.values.append(value) elif isinstance(value, models.Value): self.values.append(ConceptValue(value)) else: raise Exception(_("Invalid value definition: %s") % (value)) def index(self, scheme=None): if scheme is None: scheme = self.get_context() for value in self.values: value.index(scheme=scheme) if self.nodetype == "ConceptScheme": scheme = None for subconcept in self.subconcepts: subconcept.index(scheme=scheme) def bulk_index(self): concept_docs = [] if self.nodetype == "ConceptScheme": concept = Concept().get(id=self.id, values=["label"]) concept.index() for topConcept in self.get_child_concepts_for_indexing(self.id, depth_limit=1): concept = Concept().get(id=topConcept["conceptid"]) scheme = concept.get_context() topConcept["top_concept"] = scheme.id concept_docs.append(se.create_bulk_item(index=CONCEPTS_INDEX, id=topConcept["id"], data=topConcept)) for childConcept in concept.get_child_concepts_for_indexing(topConcept["conceptid"]): childConcept["top_concept"] = scheme.id concept_docs.append(se.create_bulk_item(index=CONCEPTS_INDEX, id=childConcept["id"], data=childConcept)) if self.nodetype == "Concept": concept = Concept().get(id=self.id, values=["label"]) scheme = concept.get_context() concept.index(scheme) for childConcept in concept.get_child_concepts_for_indexing(self.id): childConcept["top_concept"] = scheme.id concept_docs.append(se.create_bulk_item(index=CONCEPTS_INDEX, id=childConcept["id"], data=childConcept)) se.bulk_index(concept_docs) def delete_index(self, delete_self=False): def delete_concept_values_index(concepts_to_delete): for concept in concepts_to_delete.values(): query = Query(se, start=0, limit=10000) term = Term(field="conceptid", term=concept.id) query.add_query(term) query.delete(index=CONCEPTS_INDEX) if delete_self: concepts_to_delete = Concept.gather_concepts_to_delete(self) delete_concept_values_index(concepts_to_delete) else: for subconcept in self.subconcepts: concepts_to_delete = Concept.gather_concepts_to_delete(subconcept) delete_concept_values_index(concepts_to_delete) def concept_tree( self, top_concept="00000000-0000-0000-0000-000000000001", lang=settings.LANGUAGE_CODE, mode="semantic", ): class concept(object): def __init__(self, *args, **kwargs): self.label = "" self.labelid = "" self.id = "" self.sortorder = None self.load_on_demand = False self.children = [] def _findNarrowerConcept(conceptid, depth_limit=None, level=0): labels = models.Value.objects.filter(concept=conceptid) ret = concept() temp = Concept() for label in labels: temp.addvalue(label) if label.valuetype_id == "sortorder": try: ret.sortorder = float(label.value) except: ret.sortorder = None label = temp.get_preflabel(lang=lang) ret.label = label.value ret.id = label.conceptid ret.labelid = label.id if mode == "semantic": conceptrealations = models.Relation.objects.filter( Q(conceptfrom=conceptid), Q(relationtype__category="Semantic Relations") | Q(relationtype__category="Properties") ) if mode == "collections": conceptrealations = models.Relation.objects.filter( Q(conceptfrom=conceptid), Q(relationtype="member") | Q(relationtype="hasCollection") ) if depth_limit is not None and len(conceptrealations) > 0 and level >= depth_limit: ret.load_on_demand = True else: if depth_limit is not None: level = level + 1 for relation in conceptrealations: ret.children.append(_findNarrowerConcept(relation.conceptto_id, depth_limit=depth_limit, level=level)) ret.children = sorted( ret.children, key=lambda concept: self.natural_keys(concept.sortorder if concept.sortorder else concept.label), reverse=False, ) return ret def _findBroaderConcept(conceptid, child_concept, depth_limit=None, level=0): conceptrealations = models.Relation.objects.filter( Q(conceptto=conceptid), ~Q(relationtype="related"), ~Q(relationtype__category="Mapping Properties") ) if len(conceptrealations) > 0 and conceptid != top_concept: labels = models.Value.objects.filter(concept=conceptrealations[0].conceptfrom_id) ret = concept() temp = Concept() for label in labels: temp.addvalue(label) label = temp.get_preflabel(lang=lang) ret.label = label.value ret.id = label.conceptid ret.labelid = label.id ret.children.append(child_concept) return _findBroaderConcept(conceptrealations[0].conceptfrom_id, ret, depth_limit=depth_limit, level=level) else: return child_concept graph = [] if self.id is None or self.id == "" or self.id == "None" or self.id == top_concept: if mode == "semantic": concepts = models.Concept.objects.filter(nodetype="ConceptScheme") for conceptmodel in concepts: graph.append(_findNarrowerConcept(conceptmodel.pk, depth_limit=1)) if mode == "collections": concepts = models.Concept.objects.filter(nodetype="Collection") for conceptmodel in concepts: graph.append(_findNarrowerConcept(conceptmodel.pk, depth_limit=0)) graph = sorted(graph, key=lambda concept: concept.label) # graph = _findNarrowerConcept(concepts[0].pk, depth_limit=1).children else: graph = _findNarrowerConcept(self.id, depth_limit=1).children # concepts = _findNarrowerConcept(self.id, depth_limit=1) # graph = [_findBroaderConcept(self.id, concepts, depth_limit=1)] return graph def get_paths(self, lang=settings.LANGUAGE_CODE): def graph_to_paths(current_concept, path=[], path_list=[], _cache=[]): if len(path) == 0: current_path = [] else: current_path = path[:] current_path.insert( 0, { "label": current_concept.get_preflabel(lang=lang).value, "relationshiptype": current_concept.relationshiptype, "id": current_concept.id, }, ) if len(current_concept.parentconcepts) == 0 or current_concept.id in _cache: path_list.append(current_path[:]) else: _cache.append(current_concept.id) for parent in current_concept.parentconcepts: ret = graph_to_paths(parent, current_path, path_list, _cache) return path_list # def graph_to_paths(current_concept, **kwargs): # path = kwargs.get('path', []) # path_list = kwargs.get('path_list', []) # if len(path) == 0: # current_path = [] # else: # current_path = path[:] # current_path.insert(0, {'label': current_concept.get_preflabel(lang=lang).value, 'relationshiptype': current_concept.relationshiptype, 'id': current_concept.id}) # if len(current_concept.parentconcepts) == 0: # path_list.append(current_path[:]) # # else: # # for parent in current_concept.parentconcepts: # # ret = graph_to_paths(parent, current_path, path_list, _cache) # #return path_list # self.traverse(graph_to_paths, direction='up') return graph_to_paths(self) def get_node_and_links(self, lang=settings.LANGUAGE_CODE): nodes = [{"concept_id": self.id, "name": self.get_preflabel(lang=lang).value, "type": "Current"}] links = [] def get_parent_nodes_and_links(current_concept, _cache=[]): if current_concept.id not in _cache: _cache.append(current_concept.id) parents = current_concept.parentconcepts for parent in parents: nodes.append( { "concept_id": parent.id, "name": parent.get_preflabel(lang=lang).value, "type": "Root" if len(parent.parentconcepts) == 0 else "Ancestor", } ) links.append( {"target": current_concept.id, "source": parent.id, "relationship": "broader", } ) get_parent_nodes_and_links(parent, _cache) get_parent_nodes_and_links(self) # def get_parent_nodes_and_links(current_concept): # parents = current_concept.parentconcepts # for parent in parents: # nodes.append({'concept_id': parent.id, 'name': parent.get_preflabel(lang=lang).value, 'type': 'Root' if len(parent.parentconcepts) == 0 else 'Ancestor'}) # links.append({'target': current_concept.id, 'source': parent.id, 'relationship': 'broader' }) # self.traverse(get_parent_nodes_and_links, direction='up') for child in self.subconcepts: nodes.append( {"concept_id": child.id, "name": child.get_preflabel(lang=lang).value, "type": "Descendant", } ) links.append({"source": self.id, "target": child.id, "relationship": "narrower"}) for related in self.relatedconcepts: nodes.append( {"concept_id": related.id, "name": related.get_preflabel(lang=lang).value, "type": "Related", } ) links.append({"source": self.id, "target": related.id, "relationship": "related"}) # get unique node list and assign unique integer ids for each node (required by d3) nodes = list({node["concept_id"]: node for node in nodes}.values()) for i in range(len(nodes)): nodes[i]["id"] = i for link in links: link["source"] = i if link["source"] == nodes[i]["concept_id"] else link["source"] link["target"] = i if link["target"] == nodes[i]["concept_id"] else link["target"] return {"nodes": nodes, "links": links} def get_context(self): """ get the Top Concept that the Concept particpates in """ if self.nodetype == "Concept" or self.nodetype == "Collection": concept = Concept().get(id=self.id, include_parentconcepts=True, include=None) def get_scheme_id(concept): for parentconcept in concept.parentconcepts: if parentconcept.relationshiptype == "hasTopConcept": return concept if len(concept.parentconcepts) > 0: return concept.traverse(get_scheme_id, direction="up") else: return self else: # like ConceptScheme or EntityType return self def get_scheme(self): """ get the ConceptScheme that the Concept particpates in """ topConcept = self.get_context() if len(topConcept.parentconcepts) == 1: if topConcept.parentconcepts[0].nodetype == "ConceptScheme": return topConcept.parentconcepts[0] return None def check_if_concept_in_use(self): """Checks if a concept or any of its subconcepts is in use by a resource instance""" in_use = False cursor = connection.cursor() for value in self.values: sql = ( """ SELECT count(*) from tiles t, jsonb_each_text(t.tiledata) as json_data WHERE json_data.value = '%s' """ % value.id ) cursor.execute(sql) rows = cursor.fetchall() if rows[0][0] > 0: in_use = True break if in_use is not True: for subconcept in self.subconcepts: in_use = subconcept.check_if_concept_in_use() if in_use == True: return in_use return in_use def get_e55_domain(self, conceptid): """ For a given entitytypeid creates a dictionary representing that entitytypeid's concept graph (member pathway) formatted to support select2 dropdowns """ cursor = connection.cursor() sql = """ WITH RECURSIVE children AS ( SELECT d.conceptidfrom, d.conceptidto, c2.value, c2.valueid as valueid, c.value as valueto, c.valueid as valueidto, c.valuetype as vtype, 1 AS depth, array[d.conceptidto] AS conceptpath, array[c.valueid] AS idpath ---|NonRecursive Part FROM relations d JOIN values c ON(c.conceptid = d.conceptidto) JOIN values c2 ON(c2.conceptid = d.conceptidfrom) WHERE d.conceptidfrom = '{0}' and c2.valuetype = 'prefLabel' and c.valuetype in ('prefLabel', 'sortorder', 'collector') and (d.relationtype = 'member' or d.relationtype = 'hasTopConcept') UNION SELECT d.conceptidfrom, d.conceptidto, v2.value, v2.valueid as valueid, v.value as valueto, v.valueid as valueidto, v.valuetype as vtype, depth+1, (conceptpath || d.conceptidto), (idpath || v.valueid) ---|RecursivePart FROM relations d JOIN children b ON(b.conceptidto = d.conceptidfrom) JOIN values v ON(v.conceptid = d.conceptidto) JOIN values v2 ON(v2.conceptid = d.conceptidfrom) WHERE v2.valuetype = 'prefLabel' and v.valuetype in ('prefLabel','sortorder', 'collector') and (d.relationtype = 'member' or d.relationtype = 'hasTopConcept') ) SELECT conceptidfrom::text, conceptidto::text, value, valueid::text, valueto, valueidto::text, depth, idpath::text, conceptpath::text, vtype FROM children ORDER BY depth, conceptpath; """.format( conceptid ) column_names = [ "conceptidfrom", "conceptidto", "value", "valueid", "valueto", "valueidto", "depth", "idpath", "conceptpath", "vtype", ] cursor.execute(sql) rows = cursor.fetchall() class Val(object): def __init__(self, conceptid): self.text = "" self.conceptid = conceptid self.id = "" self.sortorder = "" self.collector = "" self.children = [] result = Val(conceptid) def _findNarrower(val, path, rec): for conceptid in path: childids = [child.conceptid for child in val.children] if conceptid not in childids: new_val = Val(rec["conceptidto"]) if rec["vtype"] == "sortorder": new_val.sortorder = rec["valueto"] elif rec["vtype"] == "prefLabel": new_val.text = rec["valueto"] new_val.id = rec["valueidto"] elif rec["vtype"] == "collector": new_val.collector = "collector" val.children.append(new_val) else: for child in val.children: if conceptid == child.conceptid: if conceptid == path[-1]: if rec["vtype"] == "sortorder": child.sortorder = rec["valueto"] elif rec["vtype"] == "prefLabel": child.text = rec["valueto"] child.id = rec["valueidto"] elif rec["vtype"] == "collector": child.collector = "collector" path.pop(0) _findNarrower(child, path, rec) val.children.sort(key=lambda x: (x.sortorder, x.text)) for row in rows: rec = dict(list(zip(column_names, row))) path = rec["conceptpath"][1:-1].split(",") _findNarrower(result, path, rec) return JSONSerializer().serializeToPython(result)["children"] def make_collection(self): if len(self.values) == 0: raise Exception(_("Need to include values when creating a collection")) values = JSONSerializer().serializeToPython(self.values) for value in values: value["id"] = "" collection_concept = Concept({"nodetype": "Collection", "values": values}) def create_collection(conceptfrom): for relation in models.Relation.objects.filter( Q(conceptfrom_id=conceptfrom.id), Q(relationtype__category="Semantic Relations") | Q(relationtype__category="Properties"), ~Q(relationtype="related"), ): conceptto = Concept(relation.conceptto) if conceptfrom == self: collection_concept.add_relation(conceptto, "member") else: conceptfrom.add_relation(conceptto, "member") create_collection(conceptto) with transaction.atomic(): collection_concept.save() create_collection(self) return collection_concept class ConceptValue(object): def __init__(self, *args, **kwargs): self.id = "" self.conceptid = "" self.type = "" self.category = "" self.value = "" self.language = "" if len(args) != 0: if isinstance(args[0], str): try: uuid.UUID(args[0]) self.get(args[0]) except (ValueError): self.load(JSONDeserializer().deserialize(args[0])) elif isinstance(args[0], object): self.load(args[0]) def __repr__(self): return ('%s: %s = "%s" in lang %s') % (self.__class__, self.type, self.value, self.language) def get(self, id=""): self.load(models.Value.objects.get(pk=id)) return self def save(self): if self.value.strip() != "": self.id = self.id if (self.id != "" and self.id is not None) else str(uuid.uuid4()) value = models.Value() value.pk = self.id value.value = self.value value.concept_id = self.conceptid # models.Concept.objects.get(pk=self.conceptid) value.valuetype_id = self.type # models.DValueType.objects.get(pk=self.type) if self.language != "": # need to normalize language ids to the form xx-XX lang_parts = self.language.lower().replace("_", "-").split("-") try: lang_parts[1] = lang_parts[1].upper() except: pass self.language = "-".join(lang_parts) value.language_id = self.language # models.DLanguage.objects.get(pk=self.language) else: value.language_id = settings.LANGUAGE_CODE value.save() self.category = value.valuetype.category def delete(self): if self.id != "": newvalue = models.Value.objects.get(pk=self.id) if newvalue.valuetype.valuetype == "image": newvalue = models.FileValue.objects.get(pk=self.id) newvalue.delete() self = ConceptValue() return self def load(self, value): if isinstance(value, models.Value): self.id = str(value.pk) self.conceptid = str(value.concept_id) self.type = value.valuetype_id self.category = value.valuetype.category self.value = value.value self.language = value.language_id if isinstance(value, dict): self.id = str(value["id"]) if "id" in value else "" self.conceptid = str(value["conceptid"]) if "conceptid" in value else "" self.type = value["type"] if "type" in value else "" self.category = value["category"] if "category" in value else "" self.value = value["value"] if "value" in value else "" self.language = value["language"] if "language" in value else "" def index(self, scheme=None): if self.category == "label": data = JSONSerializer().serializeToPython(self) if scheme is None: scheme = self.get_scheme_id() if scheme is None: raise Exception(_("Index of label failed. Index type (scheme id) could not be derived from the label.")) data["top_concept"] = scheme.id se.index_data(index=CONCEPTS_INDEX, body=data, idfield="id") def delete_index(self): query = Query(se, start=0, limit=10000) term = Term(field="id", term=self.id) query.add_query(term) query.delete(index=CONCEPTS_INDEX) def get_scheme_id(self): result = se.search(index=CONCEPTS_INDEX, id=self.id) if result["found"]: return Concept(result["top_concept"]) else: return None def get_preflabel_from_conceptid(conceptid, lang): ret = None default = { "category": "", "conceptid": "", "language": "", "value": "", "type": "", "id": "", } query = Query(se) bool_query = Bool() bool_query.must(Match(field="type", query="prefLabel", type="phrase")) bool_query.filter(Terms(field="conceptid", terms=[conceptid])) query.add_query(bool_query) preflabels = query.search(index=CONCEPTS_INDEX)["hits"]["hits"] for preflabel in preflabels: default = preflabel["_source"] if preflabel["_source"]["language"] is not None and lang is not None: # get the label in the preferred language, otherwise get the label in the default language if preflabel["_source"]["language"] == lang: return preflabel["_source"] if preflabel["_source"]["language"].split("-")[0] == lang.split("-")[0]: ret = preflabel["_source"] if preflabel["_source"]["language"] == settings.LANGUAGE_CODE and ret is None: ret = preflabel["_source"] return default if ret is None else ret def get_valueids_from_concept_label(label, conceptid=None, lang=None): def exact_val_match(val, conceptid=None): # exact term match, don't care about relevance ordering. # due to language formating issues, and with (hopefully) small result sets # easier to have filter logic in python than to craft it in dsl if conceptid is None: return {"query": {"bool": {"filter": {"match_phrase": {"value": val}}}}} else: return { "query": { "bool": {"filter": [{"match_phrase": {"value": val}}, {"term": {"conceptid": conceptid}}, ]} } } concept_label_results = se.search(index=CONCEPTS_INDEX, body=exact_val_match(label, conceptid)) if concept_label_results is None: print("Found no matches for label:'{0}' and concept_id: '{1}'".format(label, conceptid)) return return [ res["_source"] for res in concept_label_results["hits"]["hits"] if lang is None or res["_source"]["language"].lower() == lang.lower() ] def get_preflabel_from_valueid(valueid, lang): concept_label = se.search(index=CONCEPTS_INDEX, id=valueid) if concept_label["found"]: return get_preflabel_from_conceptid(concept_label["_source"]["conceptid"], lang)
en
0.574605
ARCHES - a program developed to inventory and manage immovable cultural heritage. Copyright (C) 2013 <NAME> and World Monuments Fund This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. # self.subconcepts = sorted(self.subconcepts, key=methodcaller( # 'get_sortkey', lang=lang), reverse=False) # if we're moving a Concept Scheme below another Concept or Concept Scheme Deletes any subconcepts associated with this concept and additionally this concept if 'delete_self' is True If any parentconcepts or relatedconcepts are included then it will only delete the relationship to those concepts but not the concepts themselves If any values are passed, then those values as well as the relationship to those values will be deleted Note, django will automatically take care of deleting any db models that have a foreign key relationship to the model being deleted (eg: deleting a concept model will also delete all values and relationships), but because we need to manage deleting parent concepts and related concepts and values we have to do that here too # we've removed all parent concepts so now this concept needs to be promoted to a Concept Scheme # delete only member relationships if the nodetype == Collection # if the concept is a collection, loop through the nodes and delete their rdmCollection values Relates this concept to 'concepttorelate' via the relationtype Gets a dictionary of all the concepts ids to delete The values of the dictionary keys differ somewhat depending on the node type being deleted If the nodetype == 'Concept' then return ConceptValue objects keyed to the concept id If the nodetype == 'ConceptScheme' then return a ConceptValue object with the value set to any ONE prefLabel keyed to the concept id We do this because it takes so long to gather the ids of the concepts when deleting a Scheme or Group # Here we have to worry about making sure we don't delete nodes that have more than 1 parent # here we can just delete everything and so use a recursive CTE to get the concept ids much more quickly Recursively builds a list of concept relations for a given concept and all it's subconcepts based on its relationship type and valuetypes. WITH RECURSIVE ordered_relationships AS ( ( SELECT r.conceptidfrom, r.conceptidto, r.relationtype, ( SELECT value FROM values WHERE conceptid=r.conceptidto AND valuetype in ('prefLabel') ORDER BY ( CASE WHEN languageid = '{languageid}' THEN 10 WHEN languageid like '{short_languageid}%' THEN 5 WHEN languageid like '{default_languageid}%' THEN 2 ELSE 0 END ) desc limit 1 ) as valuesto, ( SELECT value::int FROM values WHERE conceptid=r.conceptidto AND valuetype in ('sortorder') limit 1 ) as sortorder, ( SELECT value FROM values WHERE conceptid=r.conceptidto AND valuetype in ('collector') limit 1 ) as collector FROM relations r WHERE r.conceptidfrom = '{conceptid}' and ({relationtypes}) ORDER BY sortorder, valuesto ) UNION ( SELECT r.conceptidfrom, r.conceptidto, r.relationtype,( SELECT value FROM values WHERE conceptid=r.conceptidto AND valuetype in ('prefLabel') ORDER BY ( CASE WHEN languageid = '{languageid}' THEN 10 WHEN languageid like '{short_languageid}%' THEN 5 WHEN languageid like '{default_languageid}%' THEN 2 ELSE 0 END ) desc limit 1 ) as valuesto, ( SELECT value::int FROM values WHERE conceptid=r.conceptidto AND valuetype in ('sortorder') limit 1 ) as sortorder, ( SELECT value FROM values WHERE conceptid=r.conceptidto AND valuetype in ('collector') limit 1 ) as collector FROM relations r JOIN ordered_relationships b ON(b.conceptidto = r.conceptidfrom) WHERE ({relationtypes}) ORDER BY sortorder, valuesto ) ), children AS ( SELECT r.conceptidfrom, r.conceptidto, to_char(row_number() OVER (), 'fm000000') as row, r.collector, 1 AS depth ---|NonRecursive Part FROM ordered_relationships r WHERE r.conceptidfrom = '{conceptid}' and ({relationtypes}) UNION SELECT r.conceptidfrom, r.conceptidto, row || '-' || to_char(row_number() OVER (), 'fm000000'), r.collector, depth+1 ---|RecursivePart FROM ordered_relationships r JOIN children b ON(b.conceptidto = r.conceptidfrom) WHERE ({relationtypes}) {depth_limit} ) {subquery} SELECT ( select row_to_json(d) FROM ( SELECT * FROM values WHERE conceptid={recursive_table}.conceptidto AND valuetype in ('prefLabel') ORDER BY ( CASE WHEN languageid = '{languageid}' THEN 10 WHEN languageid like '{short_languageid}%' THEN 5 WHEN languageid like '{default_languageid}%' THEN 2 ELSE 0 END ) desc limit 1 ) d ) as valueto, depth, collector, count(*) OVER() AS full_count FROM {recursive_table} order by row {limit_clause}; , results as ( SELECT c.conceptidfrom, c.conceptidto, c.row, c.depth, c.collector FROM children c JOIN values ON(values.conceptid = c.conceptidto) WHERE LOWER(values.value) like '%%%s%%' AND values.valuetype in ('prefLabel') UNION SELECT c.conceptidfrom, c.conceptidto, c.row, c.depth, c.collector FROM children c JOIN results r on (r.conceptidfrom=c.conceptidto) ) WITH RECURSIVE children AS ( SELECT r.conceptidfrom, r.conceptidto, r.relationtype, 1 AS depth FROM relations r WHERE r.conceptidfrom = '{conceptid}' AND ({relationtypes}) UNION SELECT r.conceptidfrom, r.conceptidto, r.relationtype, depth+1 FROM relations r JOIN children c ON(c.conceptidto = r.conceptidfrom) WHERE ({relationtypes}) {depth_limit} ), results AS ( SELECT valuefrom.value as valuefrom, valueto.value as valueto, valuefrom.valueid as valueidfrom, valueto.valueid as valueidto, valuefrom.valuetype as valuetypefrom, valueto.valuetype as valuetypeto, valuefrom.languageid as languagefrom, valueto.languageid as languageto, dtypesfrom.category as categoryfrom, dtypesto.category as categoryto, c.conceptidfrom, c.conceptidto FROM values valueto JOIN d_value_types dtypesto ON(dtypesto.valuetype = valueto.valuetype) JOIN children c ON(c.conceptidto = valueto.conceptid) JOIN values valuefrom ON(c.conceptidfrom = valuefrom.conceptid) JOIN d_value_types dtypesfrom ON(dtypesfrom.valuetype = valuefrom.valuetype) WHERE valueto.valuetype in ('{child_valuetypes}') AND valuefrom.valuetype in ('{child_valuetypes}') ) SELECT distinct {columns} FROM results {limit_clause} conceptidfrom::text, conceptidto::text, valuefrom, valueto, valueidfrom::text, valueidto::text, valuetypefrom, valuetypeto, languagefrom, languageto, categoryfrom, categoryto Traverses a concept graph from self to leaf (direction='down') or root (direction='up') calling the given function on each node, passes an optional scope to each function Return a value from the function to prematurely end the traversal # break out of the traversal if the function returns a value alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments) float regex comes from https://stackoverflow.com/a/12643073/190597 Flattens the graph into a unordered list of concepts # graph = _findNarrowerConcept(concepts[0].pk, depth_limit=1).children # concepts = _findNarrowerConcept(self.id, depth_limit=1) # graph = [_findBroaderConcept(self.id, concepts, depth_limit=1)] # def graph_to_paths(current_concept, **kwargs): # path = kwargs.get('path', []) # path_list = kwargs.get('path_list', []) # if len(path) == 0: # current_path = [] # else: # current_path = path[:] # current_path.insert(0, {'label': current_concept.get_preflabel(lang=lang).value, 'relationshiptype': current_concept.relationshiptype, 'id': current_concept.id}) # if len(current_concept.parentconcepts) == 0: # path_list.append(current_path[:]) # # else: # # for parent in current_concept.parentconcepts: # # ret = graph_to_paths(parent, current_path, path_list, _cache) # #return path_list # self.traverse(graph_to_paths, direction='up') # def get_parent_nodes_and_links(current_concept): # parents = current_concept.parentconcepts # for parent in parents: # nodes.append({'concept_id': parent.id, 'name': parent.get_preflabel(lang=lang).value, 'type': 'Root' if len(parent.parentconcepts) == 0 else 'Ancestor'}) # links.append({'target': current_concept.id, 'source': parent.id, 'relationship': 'broader' }) # self.traverse(get_parent_nodes_and_links, direction='up') # get unique node list and assign unique integer ids for each node (required by d3) get the Top Concept that the Concept particpates in # like ConceptScheme or EntityType get the ConceptScheme that the Concept particpates in Checks if a concept or any of its subconcepts is in use by a resource instance SELECT count(*) from tiles t, jsonb_each_text(t.tiledata) as json_data WHERE json_data.value = '%s' For a given entitytypeid creates a dictionary representing that entitytypeid's concept graph (member pathway) formatted to support select2 dropdowns WITH RECURSIVE children AS ( SELECT d.conceptidfrom, d.conceptidto, c2.value, c2.valueid as valueid, c.value as valueto, c.valueid as valueidto, c.valuetype as vtype, 1 AS depth, array[d.conceptidto] AS conceptpath, array[c.valueid] AS idpath ---|NonRecursive Part FROM relations d JOIN values c ON(c.conceptid = d.conceptidto) JOIN values c2 ON(c2.conceptid = d.conceptidfrom) WHERE d.conceptidfrom = '{0}' and c2.valuetype = 'prefLabel' and c.valuetype in ('prefLabel', 'sortorder', 'collector') and (d.relationtype = 'member' or d.relationtype = 'hasTopConcept') UNION SELECT d.conceptidfrom, d.conceptidto, v2.value, v2.valueid as valueid, v.value as valueto, v.valueid as valueidto, v.valuetype as vtype, depth+1, (conceptpath || d.conceptidto), (idpath || v.valueid) ---|RecursivePart FROM relations d JOIN children b ON(b.conceptidto = d.conceptidfrom) JOIN values v ON(v.conceptid = d.conceptidto) JOIN values v2 ON(v2.conceptid = d.conceptidfrom) WHERE v2.valuetype = 'prefLabel' and v.valuetype in ('prefLabel','sortorder', 'collector') and (d.relationtype = 'member' or d.relationtype = 'hasTopConcept') ) SELECT conceptidfrom::text, conceptidto::text, value, valueid::text, valueto, valueidto::text, depth, idpath::text, conceptpath::text, vtype FROM children ORDER BY depth, conceptpath; # models.Concept.objects.get(pk=self.conceptid) # models.DValueType.objects.get(pk=self.type) # need to normalize language ids to the form xx-XX # models.DLanguage.objects.get(pk=self.language) # get the label in the preferred language, otherwise get the label in the default language # exact term match, don't care about relevance ordering. # due to language formating issues, and with (hopefully) small result sets # easier to have filter logic in python than to craft it in dsl
2.15739
2
Jobs/Propensity_net_NN.py
Shantanu48114860/DPN-SA
2
6623199
""" MIT License Copyright (c) 2020 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import torch.nn as nn import torch.nn.functional as F # phase = ["train", "eval"] class Propensity_net_NN(nn.Module): def __init__(self, phase, input_nodes): super(Propensity_net_NN, self).__init__() self.phase = phase self.fc1 = nn.Linear(in_features=input_nodes, out_features=25) # nn.init.xavier_uniform_(self.fc1.weight) self.fc2 = nn.Linear(in_features=25, out_features=25) # nn.init.xavier_uniform_(self.fc2.weight) self.ps_out = nn.Linear(in_features=25, out_features=2) def forward(self, x): # if torch.cuda.is_available(): # x = x.float().cuda() # else: # x = x.float() x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.ps_out(x) if self.phase == "eval": return F.softmax(x, dim=1) else: return x
""" MIT License Copyright (c) 2020 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import torch.nn as nn import torch.nn.functional as F # phase = ["train", "eval"] class Propensity_net_NN(nn.Module): def __init__(self, phase, input_nodes): super(Propensity_net_NN, self).__init__() self.phase = phase self.fc1 = nn.Linear(in_features=input_nodes, out_features=25) # nn.init.xavier_uniform_(self.fc1.weight) self.fc2 = nn.Linear(in_features=25, out_features=25) # nn.init.xavier_uniform_(self.fc2.weight) self.ps_out = nn.Linear(in_features=25, out_features=2) def forward(self, x): # if torch.cuda.is_available(): # x = x.float().cuda() # else: # x = x.float() x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.ps_out(x) if self.phase == "eval": return F.softmax(x, dim=1) else: return x
en
0.717884
MIT License Copyright (c) 2020 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # phase = ["train", "eval"] # nn.init.xavier_uniform_(self.fc1.weight) # nn.init.xavier_uniform_(self.fc2.weight) # if torch.cuda.is_available(): # x = x.float().cuda() # else: # x = x.float()
1.863243
2
tests/utils.py
riptano/argus
2
6623200
# Copyright 2018 DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import shutil from configparser import ConfigParser from src.utils import TEST_DIR def clean_test_files(): """ Deletes any files that could have been created by running tests """ test_conf_path = os.path.join(TEST_DIR, 'conf') test_data_path = os.path.join(TEST_DIR, 'data') deleted_folders = False if os.path.exists(test_conf_path): print('Removing path {} from previous test'.format(test_conf_path)) deleted_folders = True shutil.rmtree(test_conf_path) if os.path.exists(test_data_path): print('Removing path {} from previous test'.format(test_data_path)) deleted_folders = True shutil.rmtree(test_data_path) if not deleted_folders: print('Test directory, "{}", is clean') print('No files removed') def parser_to_dict(filename): if not os.path.exists(filename): raise Exception('{} does not exist'.format(filename)) cp = ConfigParser() cp.read(filename) data = {} for section in cp.sections(): data[section] = {} for option in cp.options(section): data[section].update({option: cp.get(section, option)}) return data def csv_to_list(row): return sorted(filter(None, [r for r in row.split(',')]))
# Copyright 2018 DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import shutil from configparser import ConfigParser from src.utils import TEST_DIR def clean_test_files(): """ Deletes any files that could have been created by running tests """ test_conf_path = os.path.join(TEST_DIR, 'conf') test_data_path = os.path.join(TEST_DIR, 'data') deleted_folders = False if os.path.exists(test_conf_path): print('Removing path {} from previous test'.format(test_conf_path)) deleted_folders = True shutil.rmtree(test_conf_path) if os.path.exists(test_data_path): print('Removing path {} from previous test'.format(test_data_path)) deleted_folders = True shutil.rmtree(test_data_path) if not deleted_folders: print('Test directory, "{}", is clean') print('No files removed') def parser_to_dict(filename): if not os.path.exists(filename): raise Exception('{} does not exist'.format(filename)) cp = ConfigParser() cp.read(filename) data = {} for section in cp.sections(): data[section] = {} for option in cp.options(section): data[section].update({option: cp.get(section, option)}) return data def csv_to_list(row): return sorted(filter(None, [r for r in row.split(',')]))
en
0.896665
# Copyright 2018 DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. Deletes any files that could have been created by running tests
2.41546
2
Clase_1/snippets/hint_q1.py
uncrayon/python-para-sistemas
0
6623201
# Recuerda que el radio es la mitad del diámetro. # Por otro lado, si nosotros quisieramos saber cuanto es 51 entre 17 lo podemos guardar en una variable # Resultado_Sorprendente = 51 / 17 # Y luego esa podemos usarla para otros calculos como: # Resultado_Sorprendete_2 = (Resultado_Sorprendente ** 2) * 11
# Recuerda que el radio es la mitad del diámetro. # Por otro lado, si nosotros quisieramos saber cuanto es 51 entre 17 lo podemos guardar en una variable # Resultado_Sorprendente = 51 / 17 # Y luego esa podemos usarla para otros calculos como: # Resultado_Sorprendete_2 = (Resultado_Sorprendente ** 2) * 11
es
0.876126
# Recuerda que el radio es la mitad del diámetro. # Por otro lado, si nosotros quisieramos saber cuanto es 51 entre 17 lo podemos guardar en una variable # Resultado_Sorprendente = 51 / 17 # Y luego esa podemos usarla para otros calculos como: # Resultado_Sorprendete_2 = (Resultado_Sorprendente ** 2) * 11
1.94188
2
tests/test_nptorch.py
guitargeek/geeksw
2
6623202
<reponame>guitargeek/geeksw import unittest import numpy as np import torch import geeksw.nptorch as nt class Test(unittest.TestCase): def test_nptorch(self): a = np.random.uniform(size=10) t = torch.tensor(a) def test_f(f, f_ref): np.testing.assert_array_almost_equal(f(a), f(t).numpy()) np.testing.assert_array_almost_equal(f_ref(a), f(a)) test_f(nt.exp, np.exp) test_f(nt.cos, np.cos) test_f(nt.sin, np.sin) test_f(nt.tan, np.tan) test_f(nt.sqrt, np.sqrt) if __name__ == "__main__": unittest.main(verbosity=2)
import unittest import numpy as np import torch import geeksw.nptorch as nt class Test(unittest.TestCase): def test_nptorch(self): a = np.random.uniform(size=10) t = torch.tensor(a) def test_f(f, f_ref): np.testing.assert_array_almost_equal(f(a), f(t).numpy()) np.testing.assert_array_almost_equal(f_ref(a), f(a)) test_f(nt.exp, np.exp) test_f(nt.cos, np.cos) test_f(nt.sin, np.sin) test_f(nt.tan, np.tan) test_f(nt.sqrt, np.sqrt) if __name__ == "__main__": unittest.main(verbosity=2)
none
1
2.66131
3
tests/test_schematic_upload.py
Frumple/mrt-file-server
2
6623203
<reponame>Frumple/mrt-file-server from test_schematic_base import TestSchematicBase from unittest.mock import call, patch from werkzeug.datastructures import OrderedMultiDict from io import BytesIO import os import pytest class TestSchematicUpload(TestSchematicBase): def setup(self): TestSchematicBase.setup(self) self.uploads_dir = self.app.config["SCHEMATIC_UPLOADS_DIR"] self.clean_schematic_uploads_dir() def teardown(self): TestSchematicBase.teardown(self) self.clean_schematic_uploads_dir() # Tests @patch("mrt_file_server.utils.log_utils.log_adapter") @pytest.mark.parametrize("filename", [ ("mrt_v5_final_elevated_centre_station.schem"), ("mrt_v5_final_elevated_centre_station.schematic") ]) def test_upload_single_file_should_be_successful(self, mock_logger, filename): username = "Frumple" uploaded_filename = self.uploaded_filename(username, filename) original_file_content = self.load_test_data_file(filename) message_key = "SCHEMATIC_UPLOAD_SUCCESS" data = OrderedMultiDict() data.add("userName", username) data.add("schematic", (BytesIO(original_file_content), filename)) response = self.perform_upload(data) assert response.status_code == 200 assert response.mimetype == "text/html" self.verify_file_content(self.uploads_dir, uploaded_filename, original_file_content) self.verify_flash_message_by_key(message_key, response.data, uploaded_filename) mock_logger.info.assert_called_with(self.get_log_message(message_key), uploaded_filename, username) @patch("mrt_file_server.utils.log_utils.log_adapter") def test_upload_multiple_files_should_be_successful(self, mock_logger): username = "Frumple" message_key = "SCHEMATIC_UPLOAD_SUCCESS" # Upload 5 files filenames = [ "mrt_v5_final_elevated_centre_station.schem", "mrt_v5_final_elevated_side_station.schematic", "mrt_v5_final_elevated_single_track.schematic", "mrt_v5_final_elevated_double_track.schematic", "mrt_v5_final_elevated_double_curve.schematic"] original_files = self.load_test_data_files(filenames) data = OrderedMultiDict() data.add("userName", username) for filename in original_files: data.add("schematic", (BytesIO(original_files[filename]), filename)) response = self.perform_upload(data) assert response.status_code == 200 assert response.mimetype == "text/html" logger_calls = [] for filename in original_files: uploaded_filename = self.uploaded_filename(username, filename) self.verify_file_content(self.uploads_dir, uploaded_filename, original_files[filename]) self.verify_flash_message_by_key(message_key, response.data, uploaded_filename) logger_calls.append(call(self.get_log_message(message_key), uploaded_filename, username)) mock_logger.info.assert_has_calls(logger_calls, any_order = True) @patch("mrt_file_server.utils.log_utils.log_adapter") @pytest.mark.parametrize("username, message_key", [ ("", "SCHEMATIC_UPLOAD_USERNAME_EMPTY"), ("Eris The Eagle", "SCHEMATIC_UPLOAD_USERNAME_WHITESPACE") ]) def test_upload_with_invalid_username_should_fail(self, mock_logger, username, message_key): filename = "mrt_v5_final_elevated_centre_station.schematic" original_file_content = self.load_test_data_file(filename) data = OrderedMultiDict() data.add("userName", username) data.add("schematic", (BytesIO(original_file_content), filename)) response = self.perform_upload(data) assert response.status_code == 200 assert response.mimetype == "text/html" self.verify_schematic_uploads_dir_is_empty() self.verify_flash_message_by_key(message_key, response.data) if username: mock_logger.warn.assert_called_with(self.get_log_message(message_key), username) else: mock_logger.warn.assert_called_with(self.get_log_message(message_key)) @patch("mrt_file_server.utils.log_utils.log_adapter") @pytest.mark.parametrize("filename, message_key", [ ("admod.schematic", "SCHEMATIC_UPLOAD_FILE_TOO_LARGE"), ("this file has spaces.schematic", "SCHEMATIC_UPLOAD_FILENAME_WHITESPACE"), ("this_file_has_the_wrong_extension.dat", "SCHEMATIC_UPLOAD_FILENAME_EXTENSION") ]) def test_upload_with_invalid_file_should_fail(self, mock_logger, filename, message_key): username = "Frumple" uploaded_filename = self.uploaded_filename(username, filename) original_file_content = self.load_test_data_file(filename) data = OrderedMultiDict() data.add("userName", username) data.add("schematic", (BytesIO(original_file_content), filename)) response = self.perform_upload(data) assert response.status_code == 200 assert response.mimetype == "text/html" self.verify_schematic_uploads_dir_is_empty() self.verify_flash_message_by_key(message_key, response.data, uploaded_filename) mock_logger.warn.assert_called_with(self.get_log_message(message_key), uploaded_filename, username) @patch("mrt_file_server.utils.log_utils.log_adapter") def test_upload_with_no_files_should_fail(self, mock_logger): username = "Frumple" message_key = "SCHEMATIC_UPLOAD_NO_FILES" data = OrderedMultiDict() data.add("userName", username) response = self.perform_upload(data) assert response.status_code == 200 assert response.mimetype == "text/html" self.verify_schematic_uploads_dir_is_empty() self.verify_flash_message_by_key(message_key, response.data) mock_logger.warn.assert_called_with(self.get_log_message(message_key), username) @patch("mrt_file_server.utils.log_utils.log_adapter") def test_upload_with_too_many_files_should_fail(self, mock_logger): username = "Frumple" message_key = "SCHEMATIC_UPLOAD_TOO_MANY_FILES" # Upload 12 files, over the limit of 10. filenames = [ "mrt_v5_final_elevated_centre_station.schematic", "mrt_v5_final_elevated_side_station.schematic", "mrt_v5_final_elevated_single_track.schematic", "mrt_v5_final_elevated_double_track.schematic", "mrt_v5_final_elevated_double_curve.schematic", "mrt_v5_final_ground_centre_station.schematic", "mrt_v5_final_ground_side_station.schematic", "mrt_v5_final_ground_single_track.schematic", "mrt_v5_final_ground_double_track.schematic", "mrt_v5_final_ground_double_curve.schematic", "mrt_v5_final_subground_centre_station.schematic", "mrt_v5_final_subground_side_station.schematic"] original_files = self.load_test_data_files(filenames) data = OrderedMultiDict() data.add("userName", username) for filename in original_files: data.add("schematic", (BytesIO(original_files[filename]), filename)) response = self.perform_upload(data) assert response.status_code == 200 assert response.mimetype == "text/html" self.verify_schematic_uploads_dir_is_empty() self.verify_flash_message_by_key(message_key, response.data) mock_logger.warn.assert_called_with(self.get_log_message(message_key), username) @patch("mrt_file_server.utils.log_utils.log_adapter") def test_upload_file_that_already_exists_should_fail(self, mock_logger): username = "Frumple" filename = "mrt_v5_final_elevated_centre_station.schematic" uploaded_filename = self.uploaded_filename(username, filename) impostor_filename = "mrt_v5_final_underground_single_track.schematic" message_key = "SCHEMATIC_UPLOAD_FILE_EXISTS" # Copy an impostor file with different content to the uploads directory with the same name as the file to upload self.copy_test_data_file(impostor_filename, self.uploads_dir, uploaded_filename) original_file_content = self.load_test_data_file(filename) data = OrderedMultiDict() data.add("userName", username) data.add("schematic", (BytesIO(original_file_content), filename)) response = self.perform_upload(data) assert response.status_code == 200 assert response.mimetype == "text/html" # Verify that the uploads directory has only the impostor file, and the file has not been modified files = os.listdir(self.uploads_dir) assert len(files) == 1 impostor_file_content = self.load_test_data_file(impostor_filename) self.verify_file_content(self.uploads_dir, uploaded_filename, impostor_file_content) self.verify_flash_message_by_key(message_key, response.data, uploaded_filename) mock_logger.warn.assert_called_with(self.get_log_message(message_key), uploaded_filename, username) # Helper Functions def perform_upload(self, data): return self.client.post("/schematic/upload", content_type = "multipart/form-data", data = data) def clean_schematic_uploads_dir(self): self.remove_files(self.uploads_dir, "schematic") self.remove_files(self.uploads_dir, "schem") def uploaded_filename(self, username, filename): return "{}-{}".format(username, filename) def verify_schematic_uploads_dir_is_empty(self): assert os.listdir(self.uploads_dir) == []
from test_schematic_base import TestSchematicBase from unittest.mock import call, patch from werkzeug.datastructures import OrderedMultiDict from io import BytesIO import os import pytest class TestSchematicUpload(TestSchematicBase): def setup(self): TestSchematicBase.setup(self) self.uploads_dir = self.app.config["SCHEMATIC_UPLOADS_DIR"] self.clean_schematic_uploads_dir() def teardown(self): TestSchematicBase.teardown(self) self.clean_schematic_uploads_dir() # Tests @patch("mrt_file_server.utils.log_utils.log_adapter") @pytest.mark.parametrize("filename", [ ("mrt_v5_final_elevated_centre_station.schem"), ("mrt_v5_final_elevated_centre_station.schematic") ]) def test_upload_single_file_should_be_successful(self, mock_logger, filename): username = "Frumple" uploaded_filename = self.uploaded_filename(username, filename) original_file_content = self.load_test_data_file(filename) message_key = "SCHEMATIC_UPLOAD_SUCCESS" data = OrderedMultiDict() data.add("userName", username) data.add("schematic", (BytesIO(original_file_content), filename)) response = self.perform_upload(data) assert response.status_code == 200 assert response.mimetype == "text/html" self.verify_file_content(self.uploads_dir, uploaded_filename, original_file_content) self.verify_flash_message_by_key(message_key, response.data, uploaded_filename) mock_logger.info.assert_called_with(self.get_log_message(message_key), uploaded_filename, username) @patch("mrt_file_server.utils.log_utils.log_adapter") def test_upload_multiple_files_should_be_successful(self, mock_logger): username = "Frumple" message_key = "SCHEMATIC_UPLOAD_SUCCESS" # Upload 5 files filenames = [ "mrt_v5_final_elevated_centre_station.schem", "mrt_v5_final_elevated_side_station.schematic", "mrt_v5_final_elevated_single_track.schematic", "mrt_v5_final_elevated_double_track.schematic", "mrt_v5_final_elevated_double_curve.schematic"] original_files = self.load_test_data_files(filenames) data = OrderedMultiDict() data.add("userName", username) for filename in original_files: data.add("schematic", (BytesIO(original_files[filename]), filename)) response = self.perform_upload(data) assert response.status_code == 200 assert response.mimetype == "text/html" logger_calls = [] for filename in original_files: uploaded_filename = self.uploaded_filename(username, filename) self.verify_file_content(self.uploads_dir, uploaded_filename, original_files[filename]) self.verify_flash_message_by_key(message_key, response.data, uploaded_filename) logger_calls.append(call(self.get_log_message(message_key), uploaded_filename, username)) mock_logger.info.assert_has_calls(logger_calls, any_order = True) @patch("mrt_file_server.utils.log_utils.log_adapter") @pytest.mark.parametrize("username, message_key", [ ("", "SCHEMATIC_UPLOAD_USERNAME_EMPTY"), ("Eris The Eagle", "SCHEMATIC_UPLOAD_USERNAME_WHITESPACE") ]) def test_upload_with_invalid_username_should_fail(self, mock_logger, username, message_key): filename = "mrt_v5_final_elevated_centre_station.schematic" original_file_content = self.load_test_data_file(filename) data = OrderedMultiDict() data.add("userName", username) data.add("schematic", (BytesIO(original_file_content), filename)) response = self.perform_upload(data) assert response.status_code == 200 assert response.mimetype == "text/html" self.verify_schematic_uploads_dir_is_empty() self.verify_flash_message_by_key(message_key, response.data) if username: mock_logger.warn.assert_called_with(self.get_log_message(message_key), username) else: mock_logger.warn.assert_called_with(self.get_log_message(message_key)) @patch("mrt_file_server.utils.log_utils.log_adapter") @pytest.mark.parametrize("filename, message_key", [ ("admod.schematic", "SCHEMATIC_UPLOAD_FILE_TOO_LARGE"), ("this file has spaces.schematic", "SCHEMATIC_UPLOAD_FILENAME_WHITESPACE"), ("this_file_has_the_wrong_extension.dat", "SCHEMATIC_UPLOAD_FILENAME_EXTENSION") ]) def test_upload_with_invalid_file_should_fail(self, mock_logger, filename, message_key): username = "Frumple" uploaded_filename = self.uploaded_filename(username, filename) original_file_content = self.load_test_data_file(filename) data = OrderedMultiDict() data.add("userName", username) data.add("schematic", (BytesIO(original_file_content), filename)) response = self.perform_upload(data) assert response.status_code == 200 assert response.mimetype == "text/html" self.verify_schematic_uploads_dir_is_empty() self.verify_flash_message_by_key(message_key, response.data, uploaded_filename) mock_logger.warn.assert_called_with(self.get_log_message(message_key), uploaded_filename, username) @patch("mrt_file_server.utils.log_utils.log_adapter") def test_upload_with_no_files_should_fail(self, mock_logger): username = "Frumple" message_key = "SCHEMATIC_UPLOAD_NO_FILES" data = OrderedMultiDict() data.add("userName", username) response = self.perform_upload(data) assert response.status_code == 200 assert response.mimetype == "text/html" self.verify_schematic_uploads_dir_is_empty() self.verify_flash_message_by_key(message_key, response.data) mock_logger.warn.assert_called_with(self.get_log_message(message_key), username) @patch("mrt_file_server.utils.log_utils.log_adapter") def test_upload_with_too_many_files_should_fail(self, mock_logger): username = "Frumple" message_key = "SCHEMATIC_UPLOAD_TOO_MANY_FILES" # Upload 12 files, over the limit of 10. filenames = [ "mrt_v5_final_elevated_centre_station.schematic", "mrt_v5_final_elevated_side_station.schematic", "mrt_v5_final_elevated_single_track.schematic", "mrt_v5_final_elevated_double_track.schematic", "mrt_v5_final_elevated_double_curve.schematic", "mrt_v5_final_ground_centre_station.schematic", "mrt_v5_final_ground_side_station.schematic", "mrt_v5_final_ground_single_track.schematic", "mrt_v5_final_ground_double_track.schematic", "mrt_v5_final_ground_double_curve.schematic", "mrt_v5_final_subground_centre_station.schematic", "mrt_v5_final_subground_side_station.schematic"] original_files = self.load_test_data_files(filenames) data = OrderedMultiDict() data.add("userName", username) for filename in original_files: data.add("schematic", (BytesIO(original_files[filename]), filename)) response = self.perform_upload(data) assert response.status_code == 200 assert response.mimetype == "text/html" self.verify_schematic_uploads_dir_is_empty() self.verify_flash_message_by_key(message_key, response.data) mock_logger.warn.assert_called_with(self.get_log_message(message_key), username) @patch("mrt_file_server.utils.log_utils.log_adapter") def test_upload_file_that_already_exists_should_fail(self, mock_logger): username = "Frumple" filename = "mrt_v5_final_elevated_centre_station.schematic" uploaded_filename = self.uploaded_filename(username, filename) impostor_filename = "mrt_v5_final_underground_single_track.schematic" message_key = "SCHEMATIC_UPLOAD_FILE_EXISTS" # Copy an impostor file with different content to the uploads directory with the same name as the file to upload self.copy_test_data_file(impostor_filename, self.uploads_dir, uploaded_filename) original_file_content = self.load_test_data_file(filename) data = OrderedMultiDict() data.add("userName", username) data.add("schematic", (BytesIO(original_file_content), filename)) response = self.perform_upload(data) assert response.status_code == 200 assert response.mimetype == "text/html" # Verify that the uploads directory has only the impostor file, and the file has not been modified files = os.listdir(self.uploads_dir) assert len(files) == 1 impostor_file_content = self.load_test_data_file(impostor_filename) self.verify_file_content(self.uploads_dir, uploaded_filename, impostor_file_content) self.verify_flash_message_by_key(message_key, response.data, uploaded_filename) mock_logger.warn.assert_called_with(self.get_log_message(message_key), uploaded_filename, username) # Helper Functions def perform_upload(self, data): return self.client.post("/schematic/upload", content_type = "multipart/form-data", data = data) def clean_schematic_uploads_dir(self): self.remove_files(self.uploads_dir, "schematic") self.remove_files(self.uploads_dir, "schem") def uploaded_filename(self, username, filename): return "{}-{}".format(username, filename) def verify_schematic_uploads_dir_is_empty(self): assert os.listdir(self.uploads_dir) == []
en
0.941261
# Tests # Upload 5 files # Upload 12 files, over the limit of 10. # Copy an impostor file with different content to the uploads directory with the same name as the file to upload # Verify that the uploads directory has only the impostor file, and the file has not been modified # Helper Functions
2.229117
2
main.py
grimmpp/cloudFoundryServiceBroker
0
6623204
import sys sys.path.append('cfBroker') from cfBroker.app import App App().start()
import sys sys.path.append('cfBroker') from cfBroker.app import App App().start()
none
1
1.225134
1
commonutils.py
troxel/t_mon
0
6623205
import pprint import os import os.path import subprocess import cherrypy class Utils: # Common utils to mostly handle ro/rw issues and other common needs def __init__(self): version = 1.0; self.is_ro = self.is_filesys_ro() # ----------------------- # Write file to a ro filesystem def write_sysfile(self,fspec,contents): # If filesystem is currently ro then umount ro and remount rw # Otherwise leave alone self.rw() with open(fspec, 'w+') as fid: fid.write(contents) self.ro() # ------------------------ def rw(self): rtn = os.system('mount -o rw,remount /') if rtn != 0: raise SystemError("Cannot remount rw root partition") # ------------------------ def ro(self): os.sync() # Forces write from buffer to disk... # If the filesystem was originally in ro mode leave in ro mode # Otherwise leave alone - a development feature... if self.is_ro: rtn = os.system('mount -o ro,remount /') if rtn != 0: raise SystemError("Cannot remount ro root partition") # ------------------------ def is_filesys_ro(self): rtn = os.system('egrep "\sro[\s,]" /proc/mounts | egrep "\s+/\s+"') if rtn == 0: return(True) else: return(False) # ------------------------ # Removes dir contents def rm_dir(self,dspec): cnt = dspec.count("/") if cnt < 2: print("Refusing to remove low level directory {}".format(dspec), file=sys.stderr) return(False) self.rw() rtn = os.system('rm -rf {}'.format(dspec)) self.ro() if rtn == 0: return(True) else: return(False) # ------------------------ def url_gen(self,path,from_page=''): # Cannot do relative url redirects when working with proxy # as cherrpy isn't aware of the protocol host = cherrypy.request.headers.get('Host') proto = cherrypy.request.headers.get('X-Scheme') if proto is None: proto = 'http' if from_page: from_page = "?from_page={}".format(from_page) url = "{}://{}{}{}".format(proto,host,path,from_page) return(url)
import pprint import os import os.path import subprocess import cherrypy class Utils: # Common utils to mostly handle ro/rw issues and other common needs def __init__(self): version = 1.0; self.is_ro = self.is_filesys_ro() # ----------------------- # Write file to a ro filesystem def write_sysfile(self,fspec,contents): # If filesystem is currently ro then umount ro and remount rw # Otherwise leave alone self.rw() with open(fspec, 'w+') as fid: fid.write(contents) self.ro() # ------------------------ def rw(self): rtn = os.system('mount -o rw,remount /') if rtn != 0: raise SystemError("Cannot remount rw root partition") # ------------------------ def ro(self): os.sync() # Forces write from buffer to disk... # If the filesystem was originally in ro mode leave in ro mode # Otherwise leave alone - a development feature... if self.is_ro: rtn = os.system('mount -o ro,remount /') if rtn != 0: raise SystemError("Cannot remount ro root partition") # ------------------------ def is_filesys_ro(self): rtn = os.system('egrep "\sro[\s,]" /proc/mounts | egrep "\s+/\s+"') if rtn == 0: return(True) else: return(False) # ------------------------ # Removes dir contents def rm_dir(self,dspec): cnt = dspec.count("/") if cnt < 2: print("Refusing to remove low level directory {}".format(dspec), file=sys.stderr) return(False) self.rw() rtn = os.system('rm -rf {}'.format(dspec)) self.ro() if rtn == 0: return(True) else: return(False) # ------------------------ def url_gen(self,path,from_page=''): # Cannot do relative url redirects when working with proxy # as cherrpy isn't aware of the protocol host = cherrypy.request.headers.get('Host') proto = cherrypy.request.headers.get('X-Scheme') if proto is None: proto = 'http' if from_page: from_page = "?from_page={}".format(from_page) url = "{}://{}{}{}".format(proto,host,path,from_page) return(url)
en
0.764125
# Common utils to mostly handle ro/rw issues and other common needs # ----------------------- # Write file to a ro filesystem # If filesystem is currently ro then umount ro and remount rw # Otherwise leave alone # ------------------------ # ------------------------ # Forces write from buffer to disk... # If the filesystem was originally in ro mode leave in ro mode # Otherwise leave alone - a development feature... # ------------------------ # ------------------------ # Removes dir contents # ------------------------ # Cannot do relative url redirects when working with proxy # as cherrpy isn't aware of the protocol
2.270466
2
subset.py
andrewgryan/swift-testbed
0
6623206
<filename>subset.py #!/usr/bin/env python ''' Read data from a netCDF file, cut out a sub-region and save to a new file ''' import sys import os import iris import argparse def parse_args(argv=None): parser = argparse.ArgumentParser() parser.add_argument("in_file", help="file to extract region from") parser.add_argument("out_file", help="file to write to") parser.add_argument("--north", default=30, type=int) parser.add_argument("--south", default=-18, type=int) parser.add_argument("--west", default=90, type=int) parser.add_argument("--east", default=154, type=int) return parser.parse_args(args=argv) def main(argv=None): args = parse_args(argv=argv) constraint = iris.Constraint( latitude=lambda cell: args.south < cell < args.north, longitude=lambda cell: args.west < cell < args.east) print("Reading data from {}".format(args.in_file)) cubes = iris.load(args.in_file) print("N, S, E, W: {}".format( (args.north, args.south, args.east, args.west))) # Cut out a domain small_cubes = [] for cube in cubes: print(cube.name()) try: small_cube = cube.intersection( longitude=(args.west, args.east), latitude=(args.south, args.north)) except: small_cube = cube.extract(constraint) if small_cube is not None: print(small_cube) small_cubes.append(small_cube) print("Writing subset to {}".format(args.out_file)) iris.save(small_cubes, args.out_file) if __name__ == '__main__': main()
<filename>subset.py #!/usr/bin/env python ''' Read data from a netCDF file, cut out a sub-region and save to a new file ''' import sys import os import iris import argparse def parse_args(argv=None): parser = argparse.ArgumentParser() parser.add_argument("in_file", help="file to extract region from") parser.add_argument("out_file", help="file to write to") parser.add_argument("--north", default=30, type=int) parser.add_argument("--south", default=-18, type=int) parser.add_argument("--west", default=90, type=int) parser.add_argument("--east", default=154, type=int) return parser.parse_args(args=argv) def main(argv=None): args = parse_args(argv=argv) constraint = iris.Constraint( latitude=lambda cell: args.south < cell < args.north, longitude=lambda cell: args.west < cell < args.east) print("Reading data from {}".format(args.in_file)) cubes = iris.load(args.in_file) print("N, S, E, W: {}".format( (args.north, args.south, args.east, args.west))) # Cut out a domain small_cubes = [] for cube in cubes: print(cube.name()) try: small_cube = cube.intersection( longitude=(args.west, args.east), latitude=(args.south, args.north)) except: small_cube = cube.extract(constraint) if small_cube is not None: print(small_cube) small_cubes.append(small_cube) print("Writing subset to {}".format(args.out_file)) iris.save(small_cubes, args.out_file) if __name__ == '__main__': main()
en
0.727173
#!/usr/bin/env python Read data from a netCDF file, cut out a sub-region and save to a new file # Cut out a domain
3.389354
3
visualization/dashapp/index.py
Lchuang/yews
0
6623207
#!/Users/lindsaychuang/miniconda3/envs/obspy/bin/python import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State from app import app from apps import geomaps, Continuous_WF # ---- 02. Page contents app.layout = html.Div([ dcc.Location(id='url', refresh=False), html.Div(id='page-content')]) @app.callback(Output('page-content', 'children'), [Input('url', 'pathname')]) def display_page(pathname): if pathname == '/apps/Continuous_WF': return Continuous_WF.layout elif pathname == '/': return geomaps.layout if __name__ == '__main__': app.run_server(debug=True)
#!/Users/lindsaychuang/miniconda3/envs/obspy/bin/python import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State from app import app from apps import geomaps, Continuous_WF # ---- 02. Page contents app.layout = html.Div([ dcc.Location(id='url', refresh=False), html.Div(id='page-content')]) @app.callback(Output('page-content', 'children'), [Input('url', 'pathname')]) def display_page(pathname): if pathname == '/apps/Continuous_WF': return Continuous_WF.layout elif pathname == '/': return geomaps.layout if __name__ == '__main__': app.run_server(debug=True)
en
0.445499
#!/Users/lindsaychuang/miniconda3/envs/obspy/bin/python # ---- 02. Page contents
2.073131
2
pop_tools/datasets.py
dcherian/pop-tools
0
6623208
<filename>pop_tools/datasets.py """ Functions to load sample data """ import os import pkg_resources import pooch DATASETS = pooch.create( path=['~', '.pop_tools', 'data'], version_dev='master', base_url='ftp://ftp.cgd.ucar.edu/archive/aletheia-data/cesm-data/ocn/', ) DATASETS.load_registry(pkg_resources.resource_stream('pop_tools', 'data_registry.txt'))
<filename>pop_tools/datasets.py """ Functions to load sample data """ import os import pkg_resources import pooch DATASETS = pooch.create( path=['~', '.pop_tools', 'data'], version_dev='master', base_url='ftp://ftp.cgd.ucar.edu/archive/aletheia-data/cesm-data/ocn/', ) DATASETS.load_registry(pkg_resources.resource_stream('pop_tools', 'data_registry.txt'))
en
0.811216
Functions to load sample data
1.721295
2
xcube_hub/models/user_user_metadata.py
bcdev/xcube-hub
3
6623209
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from xcube_hub.models.base_model_ import Model from xcube_hub import util from xcube_hub.models.subscription import Subscription class UserUserMetadata(Model): """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. """ def __init__(self, client_id=None, client_secret=None, subscriptions=None): """UserUserMetadata - a model defined in OpenAPI :param client_id: The client_id of this UserUserMetadata. # noqa: E501 :type client_id: str :param client_secret: The client_secret of this UserUserMetadata. # noqa: E501 :type client_secret: str """ self.openapi_types = { 'client_id': str, 'client_secret': str, 'subscriptions': Dict[str, Subscription] } self.attribute_map = { 'client_id': 'client_id', 'client_secret': 'client_secret', 'subscriptions': 'subscriptions', } self._client_id = client_id self._client_secret = client_secret self._subscriptions = subscriptions @classmethod def from_dict(cls, dikt) -> 'UserUserMetadata': """Returns the dict as a model :param dikt: A dict. :type: dict :return: The User_user_metadata of this UserUserMetadata. # noqa: E501 :rtype: UserUserMetadata """ return util.deserialize_model(dikt, cls) @property def client_id(self): """Gets the client_id of this UserUserMetadata. :return: The client_id of this UserUserMetadata. :rtype: str """ return self._client_id @client_id.setter def client_id(self, client_id): """Sets the client_id of this UserUserMetadata. :param client_id: The client_id of this UserUserMetadata. :type client_id: str """ self._client_id = client_id @property def client_secret(self): """Gets the client_secret of this UserUserMetadata. :return: The client_secret of this UserUserMetadata. :rtype: str """ return self._client_secret @client_secret.setter def client_secret(self, client_secret): """Sets the client_secret of this UserUserMetadata. :param client_secret: The client_secret of this UserUserMetadata. :type client_secret: str """ self._client_secret = client_secret @property def subscriptions(self): """Gets the subscriptions of this UserUserMetadata. :return: The subscriptions of this UserUserMetadata. :rtype: float """ return self._subscriptions @subscriptions.setter def subscriptions(self, subscriptions): """Sets the subscriptions of this UserUserMetadata. :param subscriptions: The punits of this UserUserMetadata. :type subscriptions: float """ self._subscriptions = subscriptions
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from xcube_hub.models.base_model_ import Model from xcube_hub import util from xcube_hub.models.subscription import Subscription class UserUserMetadata(Model): """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. """ def __init__(self, client_id=None, client_secret=None, subscriptions=None): """UserUserMetadata - a model defined in OpenAPI :param client_id: The client_id of this UserUserMetadata. # noqa: E501 :type client_id: str :param client_secret: The client_secret of this UserUserMetadata. # noqa: E501 :type client_secret: str """ self.openapi_types = { 'client_id': str, 'client_secret': str, 'subscriptions': Dict[str, Subscription] } self.attribute_map = { 'client_id': 'client_id', 'client_secret': 'client_secret', 'subscriptions': 'subscriptions', } self._client_id = client_id self._client_secret = client_secret self._subscriptions = subscriptions @classmethod def from_dict(cls, dikt) -> 'UserUserMetadata': """Returns the dict as a model :param dikt: A dict. :type: dict :return: The User_user_metadata of this UserUserMetadata. # noqa: E501 :rtype: UserUserMetadata """ return util.deserialize_model(dikt, cls) @property def client_id(self): """Gets the client_id of this UserUserMetadata. :return: The client_id of this UserUserMetadata. :rtype: str """ return self._client_id @client_id.setter def client_id(self, client_id): """Sets the client_id of this UserUserMetadata. :param client_id: The client_id of this UserUserMetadata. :type client_id: str """ self._client_id = client_id @property def client_secret(self): """Gets the client_secret of this UserUserMetadata. :return: The client_secret of this UserUserMetadata. :rtype: str """ return self._client_secret @client_secret.setter def client_secret(self, client_secret): """Sets the client_secret of this UserUserMetadata. :param client_secret: The client_secret of this UserUserMetadata. :type client_secret: str """ self._client_secret = client_secret @property def subscriptions(self): """Gets the subscriptions of this UserUserMetadata. :return: The subscriptions of this UserUserMetadata. :rtype: float """ return self._subscriptions @subscriptions.setter def subscriptions(self, subscriptions): """Sets the subscriptions of this UserUserMetadata. :param subscriptions: The punits of this UserUserMetadata. :type subscriptions: float """ self._subscriptions = subscriptions
en
0.501917
# coding: utf-8 # noqa: F401 # noqa: F401 NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. UserUserMetadata - a model defined in OpenAPI :param client_id: The client_id of this UserUserMetadata. # noqa: E501 :type client_id: str :param client_secret: The client_secret of this UserUserMetadata. # noqa: E501 :type client_secret: str Returns the dict as a model :param dikt: A dict. :type: dict :return: The User_user_metadata of this UserUserMetadata. # noqa: E501 :rtype: UserUserMetadata Gets the client_id of this UserUserMetadata. :return: The client_id of this UserUserMetadata. :rtype: str Sets the client_id of this UserUserMetadata. :param client_id: The client_id of this UserUserMetadata. :type client_id: str Gets the client_secret of this UserUserMetadata. :return: The client_secret of this UserUserMetadata. :rtype: str Sets the client_secret of this UserUserMetadata. :param client_secret: The client_secret of this UserUserMetadata. :type client_secret: str Gets the subscriptions of this UserUserMetadata. :return: The subscriptions of this UserUserMetadata. :rtype: float Sets the subscriptions of this UserUserMetadata. :param subscriptions: The punits of this UserUserMetadata. :type subscriptions: float
2.19699
2
bioprocs/scripts/tsv/pTsv2Xlsx.py
pwwang/biopipen
2
6623210
<gh_stars>1-10 import csv from os import path from openpyxl import Workbook infile = {{i.infile | quote}} outfile = {{o.outfile | quote}} fn2sheet = {{args.fn2sheet}} def tsv2sheet(wb, tsvfile): ws = wb.create_sheet('Sheet1') with open(tsvfile) as f: reader = csv.reader(f, delimiter = "\t") for row in reader: ws.append(row) wb = Workbook() wb.remove(wb.active) # remove default sheet tsv2sheet(wb, infile) wb.save(outfile)
import csv from os import path from openpyxl import Workbook infile = {{i.infile | quote}} outfile = {{o.outfile | quote}} fn2sheet = {{args.fn2sheet}} def tsv2sheet(wb, tsvfile): ws = wb.create_sheet('Sheet1') with open(tsvfile) as f: reader = csv.reader(f, delimiter = "\t") for row in reader: ws.append(row) wb = Workbook() wb.remove(wb.active) # remove default sheet tsv2sheet(wb, infile) wb.save(outfile)
uk
0.055452
# remove default sheet
2.966441
3
createManifest.py
Kaseaa/Tera-Manifest-Auto-Updater
0
6623211
import json import os from Crypto.Hash import SHA256 from multiprocessing.pool import ThreadPool as pool DEF_SYNTAXES = [ "dispatch.toServer", "dispatch.toClient", "dispatch.hook" ] IGNORE_FILES = [ 'createManifest.py', 'createManifest.exe', 'manifest.json', 'module.json' ] NUMBER_OF_THREADS = 6 INDENTING = 4 def getFilePathsFor(path, excluded): """ Get all the files for a given filepath :param path: The parent directory :param excluded: An array of excluded file names :return: An array of filepaths """ filePaths = [] for dir, b, files in os.walk(path): if dir.count('.git') != 0: continue for file in files: if file not in excluded: filePaths.append((dir + '/' + file).replace('\\\\', '\\').replace('\\', '/')) return filePaths def sha1(data): """ Get the SHA256 value of a byte string """ s = SHA256.new() s.update(data) return s.hexdigest() def getDefForSyntax(data, syntax): """ Gets the definition version and name using a given syntax :param data: the data to look for this information in :param syntax: for example "dispatch.toServer" :return: A dictionary with the key as the packet name and a list with the number """ ret = {} syntaxLen = len(syntax) s = data.find(syntax) # While we can't find anymore while s != -1 and len(data) > s + 1: s += syntaxLen + 1 # We make sure it's an actual string and not a variable if data[s] in ['"', "'"]: s += 1 e = data.find(data[s-1], s) # We have the packet name packetName = data[s:e] # While s isn't a number we increment it by 1 while len(data) > s + 1 and not data[s].isdigit(): s+= 1 # Make sure we didn't pass a new line, a { or a ( to find that digit if s > data.find('\n', e) or s > data.find('{', e) or s > data.find('(', e): continue e = s # while e is a number we increment it by 1 while data[e].isdigit(): e += 1 # We have the def number -- assuming it's not more than one because of complexity reasons packetVersion = int(data[s:e]) # Make sure we didn't pass a new line aswell as a { and a ( if e > data.find('\n', s) or e > data.find('{', s) or e > data.find('(', s): continue # If the packet name already exist in our dict, we append it if ret.get(packetName, False): ret[packetName].append(packetVersion) else: ret[packetName] = [packetVersion] # Find the next occurrence s = data.find(syntax, s) return ret def getDefsForFile(path): """ Get the definitions for a file path """ defs = {} try: data = open(path, "r").read() except: return {} for syntax in DEF_SYNTAXES: # Get the defintions found using this syntax ret = getDefForSyntax(data, syntax) # Remove duplicates for key, value in ret.items(): # If the key already exist in our defs variable add them together. if defs.get(key, False): defs[key] = defs[key] + value # If it didn't exist, create the entry else: defs[key] = value return defs def getFinalDefs(oldDefs, newDefs): """ Combines old and new defs and returns it """ # make sure we include all manually added defs for k, v in oldDefs.items(): if newDefs.get(k, False) is False: newDefs[k] = v # merge old and new def newDefs[k] = list(set(newDefs[k] + oldDefs[k])) return newDefs def createManifest(newData): oldManifest = {} # Load the old manifest try: oldManifest = json.loads(open('manifest.json', 'r').read()) except: pass newManifest = { "files": newData.get('files', {}), "defs": getFinalDefs(oldManifest.get('defs', {}), newData.get('defs', {})) } for key, value in oldManifest.get('files', {}).items(): # If the file isn't part of the new manifest ignore it if newManifest['files'].get(key, None) is None: continue # If it has settings we want to keep if isinstance(value, dict): value['hash'] = newManifest['files'][key] newManifest['files'][key] = value else: newManifest['files'][key] = newManifest['files'][key] # Write/create the new manifest open('manifest.json', 'w').write(json.dumps(newManifest, indent=INDENTING)) def getFileInfo(path): return { "hash": sha1(open(path, "rb").read()), "path": path, "defs": getDefsForFile(path) } def main(): with pool(NUMBER_OF_THREADS) as p: files = p.map(getFileInfo, getFilePathsFor('.', IGNORE_FILES)) data = { "files": {}, "defs": {} } for file in files: # Get the hash value for the file path data['files'][file['path'][2:]] = file['hash'] # Get the defs from the file for key, value in file['defs'].items(): # If the packet already exists in our data[defs] append them, else create it if data['defs'].get(key, False): data['defs'][key] += value else: data['defs'][key] = value # To assure there are no duplicates we add it into a set, then back into a list data['defs'][key] = list(set(data['defs'][key])) createManifest(data) if __name__ == '__main__': main()
import json import os from Crypto.Hash import SHA256 from multiprocessing.pool import ThreadPool as pool DEF_SYNTAXES = [ "dispatch.toServer", "dispatch.toClient", "dispatch.hook" ] IGNORE_FILES = [ 'createManifest.py', 'createManifest.exe', 'manifest.json', 'module.json' ] NUMBER_OF_THREADS = 6 INDENTING = 4 def getFilePathsFor(path, excluded): """ Get all the files for a given filepath :param path: The parent directory :param excluded: An array of excluded file names :return: An array of filepaths """ filePaths = [] for dir, b, files in os.walk(path): if dir.count('.git') != 0: continue for file in files: if file not in excluded: filePaths.append((dir + '/' + file).replace('\\\\', '\\').replace('\\', '/')) return filePaths def sha1(data): """ Get the SHA256 value of a byte string """ s = SHA256.new() s.update(data) return s.hexdigest() def getDefForSyntax(data, syntax): """ Gets the definition version and name using a given syntax :param data: the data to look for this information in :param syntax: for example "dispatch.toServer" :return: A dictionary with the key as the packet name and a list with the number """ ret = {} syntaxLen = len(syntax) s = data.find(syntax) # While we can't find anymore while s != -1 and len(data) > s + 1: s += syntaxLen + 1 # We make sure it's an actual string and not a variable if data[s] in ['"', "'"]: s += 1 e = data.find(data[s-1], s) # We have the packet name packetName = data[s:e] # While s isn't a number we increment it by 1 while len(data) > s + 1 and not data[s].isdigit(): s+= 1 # Make sure we didn't pass a new line, a { or a ( to find that digit if s > data.find('\n', e) or s > data.find('{', e) or s > data.find('(', e): continue e = s # while e is a number we increment it by 1 while data[e].isdigit(): e += 1 # We have the def number -- assuming it's not more than one because of complexity reasons packetVersion = int(data[s:e]) # Make sure we didn't pass a new line aswell as a { and a ( if e > data.find('\n', s) or e > data.find('{', s) or e > data.find('(', s): continue # If the packet name already exist in our dict, we append it if ret.get(packetName, False): ret[packetName].append(packetVersion) else: ret[packetName] = [packetVersion] # Find the next occurrence s = data.find(syntax, s) return ret def getDefsForFile(path): """ Get the definitions for a file path """ defs = {} try: data = open(path, "r").read() except: return {} for syntax in DEF_SYNTAXES: # Get the defintions found using this syntax ret = getDefForSyntax(data, syntax) # Remove duplicates for key, value in ret.items(): # If the key already exist in our defs variable add them together. if defs.get(key, False): defs[key] = defs[key] + value # If it didn't exist, create the entry else: defs[key] = value return defs def getFinalDefs(oldDefs, newDefs): """ Combines old and new defs and returns it """ # make sure we include all manually added defs for k, v in oldDefs.items(): if newDefs.get(k, False) is False: newDefs[k] = v # merge old and new def newDefs[k] = list(set(newDefs[k] + oldDefs[k])) return newDefs def createManifest(newData): oldManifest = {} # Load the old manifest try: oldManifest = json.loads(open('manifest.json', 'r').read()) except: pass newManifest = { "files": newData.get('files', {}), "defs": getFinalDefs(oldManifest.get('defs', {}), newData.get('defs', {})) } for key, value in oldManifest.get('files', {}).items(): # If the file isn't part of the new manifest ignore it if newManifest['files'].get(key, None) is None: continue # If it has settings we want to keep if isinstance(value, dict): value['hash'] = newManifest['files'][key] newManifest['files'][key] = value else: newManifest['files'][key] = newManifest['files'][key] # Write/create the new manifest open('manifest.json', 'w').write(json.dumps(newManifest, indent=INDENTING)) def getFileInfo(path): return { "hash": sha1(open(path, "rb").read()), "path": path, "defs": getDefsForFile(path) } def main(): with pool(NUMBER_OF_THREADS) as p: files = p.map(getFileInfo, getFilePathsFor('.', IGNORE_FILES)) data = { "files": {}, "defs": {} } for file in files: # Get the hash value for the file path data['files'][file['path'][2:]] = file['hash'] # Get the defs from the file for key, value in file['defs'].items(): # If the packet already exists in our data[defs] append them, else create it if data['defs'].get(key, False): data['defs'][key] += value else: data['defs'][key] = value # To assure there are no duplicates we add it into a set, then back into a list data['defs'][key] = list(set(data['defs'][key])) createManifest(data) if __name__ == '__main__': main()
en
0.886336
Get all the files for a given filepath :param path: The parent directory :param excluded: An array of excluded file names :return: An array of filepaths Get the SHA256 value of a byte string Gets the definition version and name using a given syntax :param data: the data to look for this information in :param syntax: for example "dispatch.toServer" :return: A dictionary with the key as the packet name and a list with the number # While we can't find anymore # We make sure it's an actual string and not a variable # We have the packet name # While s isn't a number we increment it by 1 # Make sure we didn't pass a new line, a { or a ( to find that digit # while e is a number we increment it by 1 # We have the def number -- assuming it's not more than one because of complexity reasons # Make sure we didn't pass a new line aswell as a { and a ( # If the packet name already exist in our dict, we append it # Find the next occurrence Get the definitions for a file path # Get the defintions found using this syntax # Remove duplicates # If the key already exist in our defs variable add them together. # If it didn't exist, create the entry Combines old and new defs and returns it # make sure we include all manually added defs # merge old and new def # Load the old manifest # If the file isn't part of the new manifest ignore it # If it has settings we want to keep # Write/create the new manifest # Get the hash value for the file path # Get the defs from the file # If the packet already exists in our data[defs] append them, else create it # To assure there are no duplicates we add it into a set, then back into a list
2.623403
3
extras/wordlist.py
i1470s/IVRY
3
6623212
words = ['simp', 'SIMP', 'fag', 'FAG', 'faggot', 'FAGGOT', 'nigger', 'NIGGER']
words = ['simp', 'SIMP', 'fag', 'FAG', 'faggot', 'FAGGOT', 'nigger', 'NIGGER']
none
1
2.071484
2
app/models.py
rahulraj6000/E-commerce
0
6623213
from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator STATE_CHOICES = ( ('Andaman & Nicobar Island ', 'Andaman & Nicobar Islands'), ('Andhra Pradesh', 'Andhra Pradesh'), ('Arunachal Pradesh', 'Arunachal Pradesh'), ('Assam', 'Assam'), ('Bihar', 'Bihar'), ('Chandigarh', 'Chandigarh'), ('Chhattisgarh', 'Chhattisgarh') ) class Customer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) locality = models.IntegerField() city = models.CharField(max_length=50) zipcode = models.IntegerField() state = models.CharField(choices=STATE_CHOICES, max_length=50) def __str__(self): return str(self.id) CATEGORY_CHOICES = ( ('M', 'Mobile'), ('L', 'Laptop'), ('TW', 'Top Wear'), ('BW', 'Bottom Wear'), ) class Product(models.Model): title = models.CharField(max_length=100) selling_price = models.FloatField() discounted_price = models.FloatField() description = models.TextField() brand = models.CharField(max_length=100) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) product_image = models.ImageField(upload_to='productimg') def __str__(self): return str(self.id) class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) def __str__(self): return str(self.id) @property def total_cost(self): return self.quantity * self.product.discounted_price STATUS_CHOICES = ( ('Accepted', 'Accepted'), ('Packed', 'Packed'), ('On The Way', 'On The Way'), ('Delivered', 'Delivered'), ('Cancel', 'Cancel') ) class OrderPlaced(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) ordered_date = models.DateField(auto_now_add=True) status = models.CharField( max_length=50, choices=STATUS_CHOICES, default='Pending') @property def total_cost(self): return self.quantity * self.product.discounted_price
from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator STATE_CHOICES = ( ('Andaman & Nicobar Island ', 'Andaman & Nicobar Islands'), ('Andhra Pradesh', 'Andhra Pradesh'), ('Arunachal Pradesh', 'Arunachal Pradesh'), ('Assam', 'Assam'), ('Bihar', 'Bihar'), ('Chandigarh', 'Chandigarh'), ('Chhattisgarh', 'Chhattisgarh') ) class Customer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) locality = models.IntegerField() city = models.CharField(max_length=50) zipcode = models.IntegerField() state = models.CharField(choices=STATE_CHOICES, max_length=50) def __str__(self): return str(self.id) CATEGORY_CHOICES = ( ('M', 'Mobile'), ('L', 'Laptop'), ('TW', 'Top Wear'), ('BW', 'Bottom Wear'), ) class Product(models.Model): title = models.CharField(max_length=100) selling_price = models.FloatField() discounted_price = models.FloatField() description = models.TextField() brand = models.CharField(max_length=100) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) product_image = models.ImageField(upload_to='productimg') def __str__(self): return str(self.id) class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) def __str__(self): return str(self.id) @property def total_cost(self): return self.quantity * self.product.discounted_price STATUS_CHOICES = ( ('Accepted', 'Accepted'), ('Packed', 'Packed'), ('On The Way', 'On The Way'), ('Delivered', 'Delivered'), ('Cancel', 'Cancel') ) class OrderPlaced(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) ordered_date = models.DateField(auto_now_add=True) status = models.CharField( max_length=50, choices=STATUS_CHOICES, default='Pending') @property def total_cost(self): return self.quantity * self.product.discounted_price
none
1
2.412412
2
apps/locations/forms.py
ExpoAshique/ProveBanking__s
0
6623214
from django import forms from django.utils.translation import ugettext_lazy as _ from med_social.forms.base import DeletableFieldsetForm from med_social.utils import slugify from .models import Location from med_social.forms.mixins import FieldsetMixin class LocationCreateForm(forms.ModelForm, FieldsetMixin): fieldsets = ( ('', { 'rows':( ('city',), ), }), ) class Meta: model = Location fields = ('city',) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(LocationCreateForm, self).__init__(*args, **kwargs) self.__setup_fieldsets__() def clean_city(self): city = self.cleaned_data.get("city") slug = slugify(city.strip()) if self._meta.model.objects.filter(slug=slug).exists(): raise forms.ValidationError( _("location '{}' already exists in database").format(city)) return city class LocationEditForm(DeletableFieldsetForm, FieldsetMixin): fieldsets = ( ('', { 'rows':( ('city',), ), }), ) class Meta: model = Location fields = ('city',) deletable = False def __init__(self, *args, **kwargs): super(LocationEditForm, self).__init__(*args, **kwargs)
from django import forms from django.utils.translation import ugettext_lazy as _ from med_social.forms.base import DeletableFieldsetForm from med_social.utils import slugify from .models import Location from med_social.forms.mixins import FieldsetMixin class LocationCreateForm(forms.ModelForm, FieldsetMixin): fieldsets = ( ('', { 'rows':( ('city',), ), }), ) class Meta: model = Location fields = ('city',) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(LocationCreateForm, self).__init__(*args, **kwargs) self.__setup_fieldsets__() def clean_city(self): city = self.cleaned_data.get("city") slug = slugify(city.strip()) if self._meta.model.objects.filter(slug=slug).exists(): raise forms.ValidationError( _("location '{}' already exists in database").format(city)) return city class LocationEditForm(DeletableFieldsetForm, FieldsetMixin): fieldsets = ( ('', { 'rows':( ('city',), ), }), ) class Meta: model = Location fields = ('city',) deletable = False def __init__(self, *args, **kwargs): super(LocationEditForm, self).__init__(*args, **kwargs)
none
1
2.042417
2
cointrol/utils.py
fakegit/cointrol
967
6623215
import json as _json from decimal import Decimal from functools import partial import rest_framework.utils.encoders class JSONEncoder(rest_framework.utils.encoders.JSONEncoder): def default(self, o): if isinstance(o, Decimal): return float(o) return super().default(o) class json: dumps = partial(_json.dumps, cls=JSONEncoder) loads = partial(_json.loads)
import json as _json from decimal import Decimal from functools import partial import rest_framework.utils.encoders class JSONEncoder(rest_framework.utils.encoders.JSONEncoder): def default(self, o): if isinstance(o, Decimal): return float(o) return super().default(o) class json: dumps = partial(_json.dumps, cls=JSONEncoder) loads = partial(_json.loads)
none
1
2.465285
2
zilean/datasets/basics.py
A-Hilaly/zilean
0
6623216
<filename>zilean/datasets/basics.py from greww.data.mysql import MysqlPen as M class BasicTable(object): """ Basic Table Modelisation Sample """ __slots__ = ["_data"] db = "" table = "" fields = [] def __init__(self): """ Initialise class instance with table content as data ==================================================== """ self._data = M.table_content(self.db, self.table) def update(self): """ Call __init__() in order to rewrite _data attribute with the newest table ==================================================== """ self.__init__() @property def data(self): return self._data @classmethod def DATA(cls): obj = object.__new__(cls) obj.__init__() return obj._data @classmethod def _quantify(cls, line=0): """ Return a Dict (Json type) with fields as keys and line as values ===================================================== """ return dict(zip(self.fields, line)) class ZileanCache(BasicTable): """ Zilean Cache Tables """ __slots__ = ["_data"] db = "zileancache" table = "" fields = [] class ZileanSys(BasicTable): """ Zilean System Tables """ __slots__ = ["_data"] db = "zileansys" table = "" fields = []
<filename>zilean/datasets/basics.py from greww.data.mysql import MysqlPen as M class BasicTable(object): """ Basic Table Modelisation Sample """ __slots__ = ["_data"] db = "" table = "" fields = [] def __init__(self): """ Initialise class instance with table content as data ==================================================== """ self._data = M.table_content(self.db, self.table) def update(self): """ Call __init__() in order to rewrite _data attribute with the newest table ==================================================== """ self.__init__() @property def data(self): return self._data @classmethod def DATA(cls): obj = object.__new__(cls) obj.__init__() return obj._data @classmethod def _quantify(cls, line=0): """ Return a Dict (Json type) with fields as keys and line as values ===================================================== """ return dict(zip(self.fields, line)) class ZileanCache(BasicTable): """ Zilean Cache Tables """ __slots__ = ["_data"] db = "zileancache" table = "" fields = [] class ZileanSys(BasicTable): """ Zilean System Tables """ __slots__ = ["_data"] db = "zileansys" table = "" fields = []
en
0.636711
Basic Table Modelisation Sample Initialise class instance with table content as data ==================================================== Call __init__() in order to rewrite _data attribute with the newest table ==================================================== Return a Dict (Json type) with fields as keys and line as values ===================================================== Zilean Cache Tables Zilean System Tables
2.615186
3
setup.py
dani-garcia/multiview_gpu
5
6623217
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="multiview_gpu", version="0.1.0", author="<NAME>", author_email="<EMAIL>", description="GPU-accelerated multiview clustering and dimensionality reduction", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/dani-garcia/multiview_gpu", keywords=["multiview", "clustering", "dimensionality reduction"], packages=setuptools.find_packages(), install_requires=[ 'numpy', ], extras_require={ "tf": ["tensorflow>=1.12.0"], "tf_gpu": ["tensorflow-gpu>=1.12.0"], }, setup_requires=[ "pytest-runner" ], tests_require=[ "pytest", "pytest-benchmark" ], classifiers=[ "Programming Language :: Python", 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', "Development Status :: 3 - Alpha", "Environment :: Other Environment", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Scientific/Engineering :: Artificial Intelligence", ], )
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="multiview_gpu", version="0.1.0", author="<NAME>", author_email="<EMAIL>", description="GPU-accelerated multiview clustering and dimensionality reduction", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/dani-garcia/multiview_gpu", keywords=["multiview", "clustering", "dimensionality reduction"], packages=setuptools.find_packages(), install_requires=[ 'numpy', ], extras_require={ "tf": ["tensorflow>=1.12.0"], "tf_gpu": ["tensorflow-gpu>=1.12.0"], }, setup_requires=[ "pytest-runner" ], tests_require=[ "pytest", "pytest-benchmark" ], classifiers=[ "Programming Language :: Python", 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', "Development Status :: 3 - Alpha", "Environment :: Other Environment", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Scientific/Engineering :: Artificial Intelligence", ], )
none
1
1.402467
1
scripts/ebook_name_fix.py
mcxiaoke/python-labs
7
6623218
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: mcxiaoke # @Date: 2017-05-29 15:01:41 # @Last Modified by: mcxiaoke # @Last Modified time: 2017-06-27 17:09:59 from __future__ import print_function import sys import os import codecs import re import string import shutil from datetime import datetime ISO_DATE_FORMAT = "%Y-%m-%d %H:%M:%S" FORMATS = ('.pdf', '.epub', '.mobi', '.azw3', '.djv', '.txt') INVALID_CHARS = '~!@#$%^&*()+,._[]{}<>?`【】《》:”‘,。?' processed = [] def log(x): print(x) def _replace_invalid(s): for c in INVALID_CHARS: if c in s: s = s.replace(c, " ") s = s.replace(' ', ' ') s = s.replace(' ', ' ') return s.strip() def nomalize_name(old_name): ''' 1. strip (xxx) at name start (Wiley Finance 019)Portfolio Theory and Performance Analysis.pdf 2. strip 20_xxx at name start 10_Novel Sensors for Food Inspection_Modelling,Fabrication and Experimentation 2014.pdf 101 Ready-to-Use Excel Formulas-John Wiley & Sons(2014).pdf 06.Head First Python.PDF 3. strip press company name Addison-Wesley Starting Out with Visual Basic 2012 6th (2014).pdf ADDISON.WESLEY.DATA.JUST.RIGHT.2014.pdf 4. repalce special chars and strip [] 【】 _ 5. capitalize characters 04 - Seven Concurrency Models in Seven Weeks_When Threads (2014).epub ''' # print('original: {}'.format(base)) new_name = old_name # pass 1 p = re.compile(r'(?:\(.+?\))\s*(.+)', re.I) m = p.match(old_name) if m: new_name = m.group(1) # print('pass1: {}'.format(new_base)) # pass 2 p = re.compile(r'\d+[-_\.](.+)', re.I) m = p.match(new_name) if m: new_name = m.group(1) # print('pass2: {}'.format(new_base)) # pass 4 new_name = _replace_invalid(new_name) # print('pass4: {}'.format(new_base)) # pass 5 # new_base = string.capwords(new_base) # print('pass5: {}'.format(new_base)) return (old_name, new_name) def fix_fileanme(old_path, dry_run=False): curdir = os.path.dirname(old_path) # log('file: {}'.format(old_path)) old_name = os.path.basename(old_path) base, ext = os.path.splitext(old_name) if not ext: return old_path if ext.lower() not in FORMATS: return old_path # print(name) old_base, new_base = nomalize_name(base) if old_base == new_base: return old_path new_name = '{}{}'.format(new_base, ext.lower()) new_path = os.path.join(curdir, new_name) # print(type(old_path), type(new_path)) # print(repr(old_path)[1:-1]) if not os.path.exists(old_path): log('Error: {}'.format(old_path)) return old_path if new_path != old_path: if not os.path.exists(new_path): log('Rename: {} -> {}'.format(old_name, new_name)) processed.append((old_path, new_path)) if not dry_run: shutil.move(old_path, new_path) return new_path else: log('Exists: {}'.format(new_path)) else: log('NoNeed: {}'.format(new_path)) return old_path def rename_ebooks(root, dry_run=False): for curdir, subdirs, filenames in os.walk(root, topdown=True): log('-- {} --'.format(curdir)) for name in filenames: filename = os.path.join(curdir, name) fix_fileanme(filename, dry_run) logfile = os.path.join(root, 'logs.txt') log('processed count: {}'.format(len(processed))) with codecs.open(logfile, 'w', 'utf-8') as f: timestamp = datetime.strftime(datetime.now(), ISO_DATE_FORMAT) f.write('--- Time: {} ---\n'.format(timestamp)) f.write('--- Root: {} ---\n'.format(root)) if dry_run: f.write('--- Mode: dry run mode, no files will be renamed. ---\n') for (o, n) in processed: f.write('{} -> {}\n'.format(o, n)) f.flush() def contains_cjk(text): cjk_pattern = re.compile('[\u4e00-\u9fa5]+') return cjk_pattern.search(text) def remove_cjk(root, dry_run=False): for curdir, subdirs, filenames in os.walk(root, topdown=True): log('-- {} --'.format(curdir)) for name in filenames: if contains_cjk(name): log('Delete {}'.format(name)) os.remove(os.path.join(curdir, name)) if __name__ == '__main__': sys.path.insert(1, os.path.dirname( os.path.dirname(os.path.realpath(__file__)))) print(sys.argv) if len(sys.argv) < 2: log('Usage: {} target_dir -n'.format(sys.argv[0])) sys.exit(1) dry_run = False if len(sys.argv) == 3 and sys.argv[2] == '-n': dry_run = True log(u"Mode: dry run mode, no files will be renamed.") root = os.path.abspath(sys.argv[1]) log('Root: {}'.format(root)) rename_ebooks(root, dry_run)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: mcxiaoke # @Date: 2017-05-29 15:01:41 # @Last Modified by: mcxiaoke # @Last Modified time: 2017-06-27 17:09:59 from __future__ import print_function import sys import os import codecs import re import string import shutil from datetime import datetime ISO_DATE_FORMAT = "%Y-%m-%d %H:%M:%S" FORMATS = ('.pdf', '.epub', '.mobi', '.azw3', '.djv', '.txt') INVALID_CHARS = '~!@#$%^&*()+,._[]{}<>?`【】《》:”‘,。?' processed = [] def log(x): print(x) def _replace_invalid(s): for c in INVALID_CHARS: if c in s: s = s.replace(c, " ") s = s.replace(' ', ' ') s = s.replace(' ', ' ') return s.strip() def nomalize_name(old_name): ''' 1. strip (xxx) at name start (Wiley Finance 019)Portfolio Theory and Performance Analysis.pdf 2. strip 20_xxx at name start 10_Novel Sensors for Food Inspection_Modelling,Fabrication and Experimentation 2014.pdf 101 Ready-to-Use Excel Formulas-John Wiley & Sons(2014).pdf 06.Head First Python.PDF 3. strip press company name Addison-Wesley Starting Out with Visual Basic 2012 6th (2014).pdf ADDISON.WESLEY.DATA.JUST.RIGHT.2014.pdf 4. repalce special chars and strip [] 【】 _ 5. capitalize characters 04 - Seven Concurrency Models in Seven Weeks_When Threads (2014).epub ''' # print('original: {}'.format(base)) new_name = old_name # pass 1 p = re.compile(r'(?:\(.+?\))\s*(.+)', re.I) m = p.match(old_name) if m: new_name = m.group(1) # print('pass1: {}'.format(new_base)) # pass 2 p = re.compile(r'\d+[-_\.](.+)', re.I) m = p.match(new_name) if m: new_name = m.group(1) # print('pass2: {}'.format(new_base)) # pass 4 new_name = _replace_invalid(new_name) # print('pass4: {}'.format(new_base)) # pass 5 # new_base = string.capwords(new_base) # print('pass5: {}'.format(new_base)) return (old_name, new_name) def fix_fileanme(old_path, dry_run=False): curdir = os.path.dirname(old_path) # log('file: {}'.format(old_path)) old_name = os.path.basename(old_path) base, ext = os.path.splitext(old_name) if not ext: return old_path if ext.lower() not in FORMATS: return old_path # print(name) old_base, new_base = nomalize_name(base) if old_base == new_base: return old_path new_name = '{}{}'.format(new_base, ext.lower()) new_path = os.path.join(curdir, new_name) # print(type(old_path), type(new_path)) # print(repr(old_path)[1:-1]) if not os.path.exists(old_path): log('Error: {}'.format(old_path)) return old_path if new_path != old_path: if not os.path.exists(new_path): log('Rename: {} -> {}'.format(old_name, new_name)) processed.append((old_path, new_path)) if not dry_run: shutil.move(old_path, new_path) return new_path else: log('Exists: {}'.format(new_path)) else: log('NoNeed: {}'.format(new_path)) return old_path def rename_ebooks(root, dry_run=False): for curdir, subdirs, filenames in os.walk(root, topdown=True): log('-- {} --'.format(curdir)) for name in filenames: filename = os.path.join(curdir, name) fix_fileanme(filename, dry_run) logfile = os.path.join(root, 'logs.txt') log('processed count: {}'.format(len(processed))) with codecs.open(logfile, 'w', 'utf-8') as f: timestamp = datetime.strftime(datetime.now(), ISO_DATE_FORMAT) f.write('--- Time: {} ---\n'.format(timestamp)) f.write('--- Root: {} ---\n'.format(root)) if dry_run: f.write('--- Mode: dry run mode, no files will be renamed. ---\n') for (o, n) in processed: f.write('{} -> {}\n'.format(o, n)) f.flush() def contains_cjk(text): cjk_pattern = re.compile('[\u4e00-\u9fa5]+') return cjk_pattern.search(text) def remove_cjk(root, dry_run=False): for curdir, subdirs, filenames in os.walk(root, topdown=True): log('-- {} --'.format(curdir)) for name in filenames: if contains_cjk(name): log('Delete {}'.format(name)) os.remove(os.path.join(curdir, name)) if __name__ == '__main__': sys.path.insert(1, os.path.dirname( os.path.dirname(os.path.realpath(__file__)))) print(sys.argv) if len(sys.argv) < 2: log('Usage: {} target_dir -n'.format(sys.argv[0])) sys.exit(1) dry_run = False if len(sys.argv) == 3 and sys.argv[2] == '-n': dry_run = True log(u"Mode: dry run mode, no files will be renamed.") root = os.path.abspath(sys.argv[1]) log('Root: {}'.format(root)) rename_ebooks(root, dry_run)
en
0.45803
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: mcxiaoke # @Date: 2017-05-29 15:01:41 # @Last Modified by: mcxiaoke # @Last Modified time: 2017-06-27 17:09:59 #$%^&*()+,._[]{}<>?`【】《》:”‘,。?' 1. strip (xxx) at name start (Wiley Finance 019)Portfolio Theory and Performance Analysis.pdf 2. strip 20_xxx at name start 10_Novel Sensors for Food Inspection_Modelling,Fabrication and Experimentation 2014.pdf 101 Ready-to-Use Excel Formulas-John Wiley & Sons(2014).pdf 06.Head First Python.PDF 3. strip press company name Addison-Wesley Starting Out with Visual Basic 2012 6th (2014).pdf ADDISON.WESLEY.DATA.JUST.RIGHT.2014.pdf 4. repalce special chars and strip [] 【】 _ 5. capitalize characters 04 - Seven Concurrency Models in Seven Weeks_When Threads (2014).epub # print('original: {}'.format(base)) # pass 1 # print('pass1: {}'.format(new_base)) # pass 2 # print('pass2: {}'.format(new_base)) # pass 4 # print('pass4: {}'.format(new_base)) # pass 5 # new_base = string.capwords(new_base) # print('pass5: {}'.format(new_base)) # log('file: {}'.format(old_path)) # print(name) # print(type(old_path), type(new_path)) # print(repr(old_path)[1:-1])
2.763051
3
python/tests/unit/test_ledger_tls.py
DACH-NY/dazl-client
0
6623219
<reponame>DACH-NY/dazl-client<filename>python/tests/unit/test_ledger_tls.py<gh_stars>0 # Copyright (c) 2017-2022 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from asyncio import sleep from dazl import connect, testing import pytest from .config import daml_sdk_versions @pytest.mark.asyncio @pytest.mark.parametrize("daml_sdk_version", daml_sdk_versions()) async def test_tls(daml_sdk_version): with testing.sandbox(version=daml_sdk_version, use_tls=True) as sandbox: async with connect(url=sandbox.url, admin=True, cert=sandbox.public_cert) as conn: # the result of this call is not particularly interesting; # we just need to make sure it doesn't crash await conn.list_package_ids() await sleep(1)
# Copyright (c) 2017-2022 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from asyncio import sleep from dazl import connect, testing import pytest from .config import daml_sdk_versions @pytest.mark.asyncio @pytest.mark.parametrize("daml_sdk_version", daml_sdk_versions()) async def test_tls(daml_sdk_version): with testing.sandbox(version=daml_sdk_version, use_tls=True) as sandbox: async with connect(url=sandbox.url, admin=True, cert=sandbox.public_cert) as conn: # the result of this call is not particularly interesting; # we just need to make sure it doesn't crash await conn.list_package_ids() await sleep(1)
en
0.875815
# Copyright (c) 2017-2022 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # the result of this call is not particularly interesting; # we just need to make sure it doesn't crash
1.851376
2
apps/jobs/migrations/0004_auto_20201028_1104.py
iamjackwachira/wwfh
0
6623220
# Generated by Django 3.1.2 on 2020-10-28 11:04 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('jobs', '0003_auto_20201028_1035'), ] operations = [ migrations.RenameField( model_name='jobpost', old_name='regional_restrictions', new_name='job_category', ), migrations.RemoveField( model_name='jobpost', name='category', ), migrations.DeleteModel( name='Category', ), ]
# Generated by Django 3.1.2 on 2020-10-28 11:04 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('jobs', '0003_auto_20201028_1035'), ] operations = [ migrations.RenameField( model_name='jobpost', old_name='regional_restrictions', new_name='job_category', ), migrations.RemoveField( model_name='jobpost', name='category', ), migrations.DeleteModel( name='Category', ), ]
en
0.824272
# Generated by Django 3.1.2 on 2020-10-28 11:04
1.540819
2
base/autoencoder.py
RichardLeeK/MachineLearning
1
6623221
from keras.layers import Input, Dense from keras.models import Model import numpy as np encoding_dim = 32 input_img = Input(shape=(16384,)) encoded = Dense(encoding_dim, activation='relu')(input_img) decoded = Dense(16384, activation='sigmoid')(encoded) autoencoder = Model(input_img, decoded) encoder = Model(input_img, encoded) encoded_input = Input(shape=(encoding_dim,)) decoder_layer = autoencoder.layers[-1] decoder = Model(encoded_input, decoder_layer(encoded_input)) autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy') file = open('D:/Richard/CBFV/Auto-encoder/001040SE_interpolated.csv') lines = file.readlines() file.close() signals = [] for line in lines: sl = line.split(',') cur_sig = [] for v in sl[1:]: cur_sig.append(float(v)) signals.append(cur_sig) imgs = [] for sig in signals: dim = len(sig) img = np.zeros((dim, dim)) for i in range(dim): idx = round(sig[i] * (dim - 1)) img[dim-idx-1][i] = 255 if idx > 0: img[dim-idx][i] = 125 if idx < dim - 1: img[dim-idx-2][i] = 125 imgs.append(img) x = np.array(imgs).astype('float32')/255 x = x.reshape((len(x), np.prod(x.shape[1:]))) autoencoder.fit(x, x, epochs=200, batch_size=100, shuffle=True) encoded_imgs = encoder.predict(x) decoded_imgs = decoder.predict(encoded_imgs) """ from keras.datasets import mnist import numpy as np (x, _), (x2, _) = mnist.load_data() x = x[:10] x2 = x2[:10] x = x.astype('float32')/255 x2 = x2.astype('float32')/255 x = x.reshape((len(x), np.prod(x.shape[1:]))) x2 = x2.reshape((len(x2), np.prod(x2.shape[1:]))) print (x.shape) print(x2.shape) autoencoder.fit(x, x, epochs=30, batch_size=100, shuffle=True, validation_data=(x2, x2)) encoded_imgs = encoder.predict(x2) decoded_imgs = decoder.predict(encoded_imgs) """ import matplotlib.pyplot as plt n = 8 plt.figure(figsize=(20,4)) for i in range(n): ax = plt.subplot(2, n, i+1) plt.imshow(x[i].reshape(128, 128)) #plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax = plt.subplot(2, n, i + 1 + n) plt.imshow(decoded_imgs[i].reshape(128, 128)) #plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show()
from keras.layers import Input, Dense from keras.models import Model import numpy as np encoding_dim = 32 input_img = Input(shape=(16384,)) encoded = Dense(encoding_dim, activation='relu')(input_img) decoded = Dense(16384, activation='sigmoid')(encoded) autoencoder = Model(input_img, decoded) encoder = Model(input_img, encoded) encoded_input = Input(shape=(encoding_dim,)) decoder_layer = autoencoder.layers[-1] decoder = Model(encoded_input, decoder_layer(encoded_input)) autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy') file = open('D:/Richard/CBFV/Auto-encoder/001040SE_interpolated.csv') lines = file.readlines() file.close() signals = [] for line in lines: sl = line.split(',') cur_sig = [] for v in sl[1:]: cur_sig.append(float(v)) signals.append(cur_sig) imgs = [] for sig in signals: dim = len(sig) img = np.zeros((dim, dim)) for i in range(dim): idx = round(sig[i] * (dim - 1)) img[dim-idx-1][i] = 255 if idx > 0: img[dim-idx][i] = 125 if idx < dim - 1: img[dim-idx-2][i] = 125 imgs.append(img) x = np.array(imgs).astype('float32')/255 x = x.reshape((len(x), np.prod(x.shape[1:]))) autoencoder.fit(x, x, epochs=200, batch_size=100, shuffle=True) encoded_imgs = encoder.predict(x) decoded_imgs = decoder.predict(encoded_imgs) """ from keras.datasets import mnist import numpy as np (x, _), (x2, _) = mnist.load_data() x = x[:10] x2 = x2[:10] x = x.astype('float32')/255 x2 = x2.astype('float32')/255 x = x.reshape((len(x), np.prod(x.shape[1:]))) x2 = x2.reshape((len(x2), np.prod(x2.shape[1:]))) print (x.shape) print(x2.shape) autoencoder.fit(x, x, epochs=30, batch_size=100, shuffle=True, validation_data=(x2, x2)) encoded_imgs = encoder.predict(x2) decoded_imgs = decoder.predict(encoded_imgs) """ import matplotlib.pyplot as plt n = 8 plt.figure(figsize=(20,4)) for i in range(n): ax = plt.subplot(2, n, i+1) plt.imshow(x[i].reshape(128, 128)) #plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax = plt.subplot(2, n, i + 1 + n) plt.imshow(decoded_imgs[i].reshape(128, 128)) #plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show()
en
0.425148
from keras.datasets import mnist import numpy as np (x, _), (x2, _) = mnist.load_data() x = x[:10] x2 = x2[:10] x = x.astype('float32')/255 x2 = x2.astype('float32')/255 x = x.reshape((len(x), np.prod(x.shape[1:]))) x2 = x2.reshape((len(x2), np.prod(x2.shape[1:]))) print (x.shape) print(x2.shape) autoencoder.fit(x, x, epochs=30, batch_size=100, shuffle=True, validation_data=(x2, x2)) encoded_imgs = encoder.predict(x2) decoded_imgs = decoder.predict(encoded_imgs) #plt.gray() #plt.gray()
2.639742
3
utils/download.py
IanDesuyo/AIKyaru
11
6623222
<filename>utils/download.py<gh_stars>10-100 import logging from aiofile import async_open import aiohttp import re import json import os import brotli HEADER = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36" } async def rank() -> dict: async with async_open("db/RecommendedRank.json", "r") as f: data = json.loads(await f.read()) return data async def GSheet(key: str, gid: str, sql: str = "select%20*"): """ Download google sheet and convert to a dict. Args: key (str): Between the slashes after spreadsheets/d. gid (str): The gid value at query. sql (str, optional): Query sql. Defaults to "select%20*". Raises: e: Exceptions caused by ClientSession. Returns: A converted dict. """ url = f"https://docs.google.com/spreadsheets/u/0/d/{key}/gviz/tq?gid={gid}&tqx=out:json&tq={sql}" async with aiohttp.ClientSession() as session: try: fetchData = await session.get(url, headers=HEADER, timeout=aiohttp.ClientTimeout(total=10.0)) data = re.search(r"(\{.*\})", await fetchData.text()) data = json.loads(data.group(1)) rows = data["table"]["rows"] cols = [i["label"].strip() for i in data["table"]["cols"]] result = {} for row in rows: temp = {} for i in range(1, len(cols)): if isinstance(row["c"][i]["v"], float): temp[cols[i]] = int(row["c"][i]["v"]) else: temp[cols[i]] = row["c"][i]["v"] result[int(row["c"][0]["v"])] = temp return result except Exception as e: logging.error(f"Download Google Sheets failed. {key}({gid})") raise e async def gameDB(url: str, filename: str, isBrotli: bool = True): """ Download game database from url. Args: url (str): Url of the file. filename (str): The name that should be saved as. isBrotli (bool, optional): Should it be decompressed by brotli. Defaults to True. Raises: e: Exceptions caused by ClientSession. """ async with aiohttp.ClientSession() as session: try: fetch = await session.get(url, headers=HEADER, timeout=aiohttp.ClientTimeout(total=10.0)) async with async_open(os.path.join("./gameDB", filename), "wb+") as f: if isBrotli: await f.write(brotli.decompress(await fetch.content.read())) else: await f.write(await fetch.content.read()) except Exception as e: logging.error(f"Download gameDB failed. ({filename}, {url})") raise e async def json_(url: str): async with aiohttp.ClientSession() as session: try: f = await session.get(url, headers=HEADER, timeout=aiohttp.ClientTimeout(total=10.0)) return await f.json() except Exception as e: logging.error(f"Download json failed. ({url})") raise e
<filename>utils/download.py<gh_stars>10-100 import logging from aiofile import async_open import aiohttp import re import json import os import brotli HEADER = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36" } async def rank() -> dict: async with async_open("db/RecommendedRank.json", "r") as f: data = json.loads(await f.read()) return data async def GSheet(key: str, gid: str, sql: str = "select%20*"): """ Download google sheet and convert to a dict. Args: key (str): Between the slashes after spreadsheets/d. gid (str): The gid value at query. sql (str, optional): Query sql. Defaults to "select%20*". Raises: e: Exceptions caused by ClientSession. Returns: A converted dict. """ url = f"https://docs.google.com/spreadsheets/u/0/d/{key}/gviz/tq?gid={gid}&tqx=out:json&tq={sql}" async with aiohttp.ClientSession() as session: try: fetchData = await session.get(url, headers=HEADER, timeout=aiohttp.ClientTimeout(total=10.0)) data = re.search(r"(\{.*\})", await fetchData.text()) data = json.loads(data.group(1)) rows = data["table"]["rows"] cols = [i["label"].strip() for i in data["table"]["cols"]] result = {} for row in rows: temp = {} for i in range(1, len(cols)): if isinstance(row["c"][i]["v"], float): temp[cols[i]] = int(row["c"][i]["v"]) else: temp[cols[i]] = row["c"][i]["v"] result[int(row["c"][0]["v"])] = temp return result except Exception as e: logging.error(f"Download Google Sheets failed. {key}({gid})") raise e async def gameDB(url: str, filename: str, isBrotli: bool = True): """ Download game database from url. Args: url (str): Url of the file. filename (str): The name that should be saved as. isBrotli (bool, optional): Should it be decompressed by brotli. Defaults to True. Raises: e: Exceptions caused by ClientSession. """ async with aiohttp.ClientSession() as session: try: fetch = await session.get(url, headers=HEADER, timeout=aiohttp.ClientTimeout(total=10.0)) async with async_open(os.path.join("./gameDB", filename), "wb+") as f: if isBrotli: await f.write(brotli.decompress(await fetch.content.read())) else: await f.write(await fetch.content.read()) except Exception as e: logging.error(f"Download gameDB failed. ({filename}, {url})") raise e async def json_(url: str): async with aiohttp.ClientSession() as session: try: f = await session.get(url, headers=HEADER, timeout=aiohttp.ClientTimeout(total=10.0)) return await f.json() except Exception as e: logging.error(f"Download json failed. ({url})") raise e
en
0.710662
Download google sheet and convert to a dict. Args: key (str): Between the slashes after spreadsheets/d. gid (str): The gid value at query. sql (str, optional): Query sql. Defaults to "select%20*". Raises: e: Exceptions caused by ClientSession. Returns: A converted dict. Download game database from url. Args: url (str): Url of the file. filename (str): The name that should be saved as. isBrotli (bool, optional): Should it be decompressed by brotli. Defaults to True. Raises: e: Exceptions caused by ClientSession.
2.638176
3
QuestionsBidding/bidding/admin.py
Athi223/Questions-Bidding
0
6623223
from django.contrib import admin from .models import Question, Allotment import json import random # Register your models here. admin.site.register(Question) @admin.register(Allotment) class AllotmentAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): allotments = {} for i in range(int(form.cleaned_data.get('allotments'))): allotments[i] = [] obj.allotments = json.dumps(allotments) obj.room_id = random.randint(1, 2147483647) obj.scores = json.dumps({}) return super().save_model(request, obj, form, change)
from django.contrib import admin from .models import Question, Allotment import json import random # Register your models here. admin.site.register(Question) @admin.register(Allotment) class AllotmentAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): allotments = {} for i in range(int(form.cleaned_data.get('allotments'))): allotments[i] = [] obj.allotments = json.dumps(allotments) obj.room_id = random.randint(1, 2147483647) obj.scores = json.dumps({}) return super().save_model(request, obj, form, change)
en
0.968259
# Register your models here.
2.192819
2
rta.py
fact-project/rta_frontend
1
6623224
<reponame>fact-project/rta_frontend from flask import Flask from flask import render_template, Response, request from datetime import datetime import lightcurve from dateutil import parser from dateutil.relativedelta import relativedelta app = Flask(__name__) def _make_response_for_invalid_request(message): return Response( response=message, status=400, mimetype='application/json' ) @app.route('/v1/excess', methods=['GET']) def rta(): args = request.args try: d = args.get('start_date', None) if d: start_date = parser.parse(d, fuzzy=True).isoformat() else: start_date = (datetime.now() - relativedelta(hours=12)).isoformat() except ValueError: return _make_response_for_invalid_request('Could not parse start date') try: latest_date = parser.parse(args.get('latest_date', datetime.now().isoformat()), fuzzy=True) latest_date = latest_date.isoformat() except ValueError: return _make_response_for_invalid_request('Could not parse latest date') try: bin_width = int(args.get('bin_width', 20)) except ValueError: return _make_response_for_invalid_request('Could not parse bin width') source = args.get('source', None) print(start_date) runs, events = lightcurve.fetch_data(start=start_date, end=latest_date, source=source) if len(runs) == 0: return Response( response='[]', status=200, mimetype="application/json" ) excess = lightcurve.excess(runs, events, bin_width_minutes=bin_width) excess = excess.drop(['run_start', 'run_stop', 'night'], axis=1) excess['bin_start'] = excess.time_mean - excess.time_width * 0.5 excess['bin_end'] = excess.time_mean + excess.time_width * 0.5 excess = excess.drop(['time_mean', 'time_width'], axis=1) resp = Response( response=excess.to_json(orient='records', date_format='iso'), status=200, mimetype="application/json" ) return resp @app.route('/') def hello(): title = 'FACT Real Time Analysis' return render_template('index.html', title=title)
from flask import Flask from flask import render_template, Response, request from datetime import datetime import lightcurve from dateutil import parser from dateutil.relativedelta import relativedelta app = Flask(__name__) def _make_response_for_invalid_request(message): return Response( response=message, status=400, mimetype='application/json' ) @app.route('/v1/excess', methods=['GET']) def rta(): args = request.args try: d = args.get('start_date', None) if d: start_date = parser.parse(d, fuzzy=True).isoformat() else: start_date = (datetime.now() - relativedelta(hours=12)).isoformat() except ValueError: return _make_response_for_invalid_request('Could not parse start date') try: latest_date = parser.parse(args.get('latest_date', datetime.now().isoformat()), fuzzy=True) latest_date = latest_date.isoformat() except ValueError: return _make_response_for_invalid_request('Could not parse latest date') try: bin_width = int(args.get('bin_width', 20)) except ValueError: return _make_response_for_invalid_request('Could not parse bin width') source = args.get('source', None) print(start_date) runs, events = lightcurve.fetch_data(start=start_date, end=latest_date, source=source) if len(runs) == 0: return Response( response='[]', status=200, mimetype="application/json" ) excess = lightcurve.excess(runs, events, bin_width_minutes=bin_width) excess = excess.drop(['run_start', 'run_stop', 'night'], axis=1) excess['bin_start'] = excess.time_mean - excess.time_width * 0.5 excess['bin_end'] = excess.time_mean + excess.time_width * 0.5 excess = excess.drop(['time_mean', 'time_width'], axis=1) resp = Response( response=excess.to_json(orient='records', date_format='iso'), status=200, mimetype="application/json" ) return resp @app.route('/') def hello(): title = 'FACT Real Time Analysis' return render_template('index.html', title=title)
none
1
2.409988
2
tsl/datasets/prototypes/mixin.py
TorchSpatiotemporal/tsl
4
6623225
import numpy as np import pandas as pd from tsl.ops.dataframe import to_numpy from . import checks from ...typing import FrameArray from ...utils.python_utils import ensure_list class PandasParsingMixin: def _parse_dataframe(self, df: pd.DataFrame, node_level: bool = True): assert checks.is_datetime_like_index(df.index) if node_level: df = checks.to_nodes_channels_columns(df) else: df = checks.to_channels_columns(df) df = checks.cast_df(df, precision=self.precision) return df def _to_indexed_df(self, array: np.ndarray): if array.ndim == 1: array = array[..., None] # check shape equivalence time, channels = array.shape if time != self.length: raise ValueError("Cannot match temporal dimensions {} and {}" .format(time, self.length)) return pd.DataFrame(array, self.index) def _to_primary_df_schema(self, array: np.ndarray): array = np.asarray(array) while array.ndim < 3: array = array[..., None] # check shape equivalence time, nodes, channels = array.shape if time != self.length: raise ValueError("Cannot match temporal dimensions {} and {}" .format(time, self.length)) if nodes != self.n_nodes: raise ValueError("Cannot match nodes dimensions {} and {}" .format(nodes, self.n_nodes)) array = array.reshape(time, nodes * channels) columns = self.columns(channels=pd.RangeIndex(channels)) return pd.DataFrame(array, self.index, columns) def _synch_with_primary(self, df: pd.DataFrame): assert hasattr(self, 'df'), \ "Cannot call this method before setting primary dataframe." if df.columns.nlevels == 2: nodes = set(df.columns.unique(0)) channels = list(df.columns.unique(1)) assert nodes.issubset(self.nodes), \ "You are trying to add an exogenous dataframe with nodes that" \ " are not in the dataset." columns = self.columns(channels=channels) df = df.reindex(index=self.index, columns=columns) elif df.columns.nlevels == 1: df = df.reindex(index=self.index) else: raise ValueError("Input dataframe must have either 1 ('nodes' or " "'channels') or 2 ('nodes', 'channels') column " "levels.") return df def _check_name(self, name: str, check_type: str): assert check_type in ['exogenous', 'attribute'] invalid_names = set(dir(self)) if check_type == 'exogenous': invalid_names.update(self._attributes) else: invalid_names.update(self._exogenous) if name in invalid_names: raise ValueError(f"Cannot set {check_type} with name '{name}', " f"{self.__class__.__name__} contains already an " f"attribute named '{name}'.") class TemporalFeaturesMixin: def datetime_encoded(self, units): units = ensure_list(units) mapping = {un: pd.to_timedelta('1' + un).delta for un in ['day', 'hour', 'minute', 'second', 'millisecond', 'microsecond', 'nanosecond']} mapping['week'] = pd.to_timedelta('1W').delta mapping['year'] = 365.2425 * 24 * 60 * 60 * 10 ** 9 index_nano = self.index.view(np.int64) datetime = dict() for unit in units: if unit not in mapping: raise ValueError() nano_sec = index_nano * (2 * np.pi / mapping[unit]) datetime[unit + '_sin'] = np.sin(nano_sec) datetime[unit + '_cos'] = np.cos(nano_sec) return pd.DataFrame(datetime, index=self.index, dtype=np.float32) def datetime_onehot(self, units): units = ensure_list(units) datetime = dict() for unit in units: if hasattr(self.index.__dict__, unit): raise ValueError() datetime[unit] = getattr(self.index, unit) dummies = pd.get_dummies(pd.DataFrame(datetime, index=self.index), columns=units) return dummies def holidays_onehot(self, country, subdiv=None): """Returns a DataFrame to indicate if dataset timestamps is holiday. See https://python-holidays.readthedocs.io/en/latest/ Args: country (str): country for which holidays have to be checked, e.g., "CH" for Switzerland. subdiv (dict, optional): optional country sub-division (state, region, province, canton), e.g., "TI" for Ticino, Switzerland. Returns: pandas.DataFrame: DataFrame with one column ("holiday") as one-hot encoding (1 if the timestamp is in a holiday, 0 otherwise). """ try: import holidays except ModuleNotFoundError: raise RuntimeError("You should install optional dependency " "'holidays' to call 'datetime_holidays'.") years = np.unique(self.index.year.values) h = holidays.country_holidays(country, subdiv=subdiv, years=years) # label all the timestamps, whether holiday or not out = pd.DataFrame(0, dtype=np.uint8, index=self.index.normalize(), columns=['holiday']) for date in h.keys(): try: out.loc[[date]] = 1 except KeyError: pass out.index = self.index return out class MissingValuesMixin: eval_mask: np.ndarray def set_eval_mask(self, eval_mask: FrameArray): if isinstance(eval_mask, pd.DataFrame): eval_mask = to_numpy(self._parse_dataframe(eval_mask)) if eval_mask.ndim == 2: eval_mask = eval_mask[..., None] assert eval_mask.shape == self.shape eval_mask = eval_mask.astype(self.mask.dtype) & self.mask self.eval_mask = eval_mask @property def training_mask(self): if hasattr(self, 'eval_mask') and self.eval_mask is not None: return self.mask & (1 - self.eval_mask) return self.mask
import numpy as np import pandas as pd from tsl.ops.dataframe import to_numpy from . import checks from ...typing import FrameArray from ...utils.python_utils import ensure_list class PandasParsingMixin: def _parse_dataframe(self, df: pd.DataFrame, node_level: bool = True): assert checks.is_datetime_like_index(df.index) if node_level: df = checks.to_nodes_channels_columns(df) else: df = checks.to_channels_columns(df) df = checks.cast_df(df, precision=self.precision) return df def _to_indexed_df(self, array: np.ndarray): if array.ndim == 1: array = array[..., None] # check shape equivalence time, channels = array.shape if time != self.length: raise ValueError("Cannot match temporal dimensions {} and {}" .format(time, self.length)) return pd.DataFrame(array, self.index) def _to_primary_df_schema(self, array: np.ndarray): array = np.asarray(array) while array.ndim < 3: array = array[..., None] # check shape equivalence time, nodes, channels = array.shape if time != self.length: raise ValueError("Cannot match temporal dimensions {} and {}" .format(time, self.length)) if nodes != self.n_nodes: raise ValueError("Cannot match nodes dimensions {} and {}" .format(nodes, self.n_nodes)) array = array.reshape(time, nodes * channels) columns = self.columns(channels=pd.RangeIndex(channels)) return pd.DataFrame(array, self.index, columns) def _synch_with_primary(self, df: pd.DataFrame): assert hasattr(self, 'df'), \ "Cannot call this method before setting primary dataframe." if df.columns.nlevels == 2: nodes = set(df.columns.unique(0)) channels = list(df.columns.unique(1)) assert nodes.issubset(self.nodes), \ "You are trying to add an exogenous dataframe with nodes that" \ " are not in the dataset." columns = self.columns(channels=channels) df = df.reindex(index=self.index, columns=columns) elif df.columns.nlevels == 1: df = df.reindex(index=self.index) else: raise ValueError("Input dataframe must have either 1 ('nodes' or " "'channels') or 2 ('nodes', 'channels') column " "levels.") return df def _check_name(self, name: str, check_type: str): assert check_type in ['exogenous', 'attribute'] invalid_names = set(dir(self)) if check_type == 'exogenous': invalid_names.update(self._attributes) else: invalid_names.update(self._exogenous) if name in invalid_names: raise ValueError(f"Cannot set {check_type} with name '{name}', " f"{self.__class__.__name__} contains already an " f"attribute named '{name}'.") class TemporalFeaturesMixin: def datetime_encoded(self, units): units = ensure_list(units) mapping = {un: pd.to_timedelta('1' + un).delta for un in ['day', 'hour', 'minute', 'second', 'millisecond', 'microsecond', 'nanosecond']} mapping['week'] = pd.to_timedelta('1W').delta mapping['year'] = 365.2425 * 24 * 60 * 60 * 10 ** 9 index_nano = self.index.view(np.int64) datetime = dict() for unit in units: if unit not in mapping: raise ValueError() nano_sec = index_nano * (2 * np.pi / mapping[unit]) datetime[unit + '_sin'] = np.sin(nano_sec) datetime[unit + '_cos'] = np.cos(nano_sec) return pd.DataFrame(datetime, index=self.index, dtype=np.float32) def datetime_onehot(self, units): units = ensure_list(units) datetime = dict() for unit in units: if hasattr(self.index.__dict__, unit): raise ValueError() datetime[unit] = getattr(self.index, unit) dummies = pd.get_dummies(pd.DataFrame(datetime, index=self.index), columns=units) return dummies def holidays_onehot(self, country, subdiv=None): """Returns a DataFrame to indicate if dataset timestamps is holiday. See https://python-holidays.readthedocs.io/en/latest/ Args: country (str): country for which holidays have to be checked, e.g., "CH" for Switzerland. subdiv (dict, optional): optional country sub-division (state, region, province, canton), e.g., "TI" for Ticino, Switzerland. Returns: pandas.DataFrame: DataFrame with one column ("holiday") as one-hot encoding (1 if the timestamp is in a holiday, 0 otherwise). """ try: import holidays except ModuleNotFoundError: raise RuntimeError("You should install optional dependency " "'holidays' to call 'datetime_holidays'.") years = np.unique(self.index.year.values) h = holidays.country_holidays(country, subdiv=subdiv, years=years) # label all the timestamps, whether holiday or not out = pd.DataFrame(0, dtype=np.uint8, index=self.index.normalize(), columns=['holiday']) for date in h.keys(): try: out.loc[[date]] = 1 except KeyError: pass out.index = self.index return out class MissingValuesMixin: eval_mask: np.ndarray def set_eval_mask(self, eval_mask: FrameArray): if isinstance(eval_mask, pd.DataFrame): eval_mask = to_numpy(self._parse_dataframe(eval_mask)) if eval_mask.ndim == 2: eval_mask = eval_mask[..., None] assert eval_mask.shape == self.shape eval_mask = eval_mask.astype(self.mask.dtype) & self.mask self.eval_mask = eval_mask @property def training_mask(self): if hasattr(self, 'eval_mask') and self.eval_mask is not None: return self.mask & (1 - self.eval_mask) return self.mask
en
0.737801
# check shape equivalence # check shape equivalence Returns a DataFrame to indicate if dataset timestamps is holiday. See https://python-holidays.readthedocs.io/en/latest/ Args: country (str): country for which holidays have to be checked, e.g., "CH" for Switzerland. subdiv (dict, optional): optional country sub-division (state, region, province, canton), e.g., "TI" for Ticino, Switzerland. Returns: pandas.DataFrame: DataFrame with one column ("holiday") as one-hot encoding (1 if the timestamp is in a holiday, 0 otherwise). # label all the timestamps, whether holiday or not
2.5037
3
testslide/import_profiler.py
Flameeyes/TestSlide
0
6623226
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import time class ImportedModule(object): """ A module that was imported with __import__. """ def __init__(self, name, globals, level, parent=None): self.name = name self.globals = globals self.level = level self.parent = parent self.children = [] self.time = None if parent: parent.children.append(self) def __eq__(self, value): return str(self) == str(value) @property def all_children(self): children = [] for child in self.children: children.append(child) children.extend(child.all_children) return children @property def own_time(self): """ How many seconds it took to import this module, minus all child imports. """ return self.time - sum(child.time for child in self.children) def __str__(self): if self.globals and self.level: if self.level == 1: prefix = self.globals["__package__"] else: end = -1 * (self.level - 1) prefix = ".".join(self.globals["__package__"].split(".")[:end]) + "." else: prefix = "" return "{}{}".format(prefix, self.name) def __enter__(self): self._start_time = time.time() def __exit__(self, exc_type, exc_val, exc_tb): self.time = time.time() - self._start_time class ImportProfiler(object): """ Experimental! Quick'n dirty profiler for module import times. Usage: from testslide.import_profiler import ImportProfiler with ImportProfiler() as import_profiler: import everything.here import_profiler.print_stats(100) This will print the dependency tree for imported modules that took more than 100ms to be imported. """ def __init__(self): self._original_import = __builtins__["__import__"] def __enter__(self): __builtins__["__import__"] = self._profiled_import self._top_imp_modules = [] self._import_stack = [] self.total_time = None self._start_time = time.time() return self def __exit__(self, exc_type, exc_val, exc_tb): self.total_time = time.time() - self._start_time __builtins__["__import__"] = self._original_import # def _profiled_import(self, name, globals=None, locals=None, fromlist=(), level=0): def _profiled_import(self, name, globals=None, locals=None, fromlist=(), level=0): # print('Importing {}'.format(repr(name))) imp_mod = ImportedModule( name=name, globals=globals, level=level, parent=self._import_stack[-1] if self._import_stack else None, ) if not self._import_stack: self._top_imp_modules.append(imp_mod) self._import_stack.append(imp_mod) with imp_mod: try: return self._original_import(name, globals, locals, fromlist, level) finally: self._import_stack.pop() def print_stats(self, threshold_ms=0): def print_imp_mod(imp_mod, indent=0): own_ms = int(imp_mod.own_time * 1000) if own_ms >= threshold_ms or any( child for child in imp_mod.all_children if child.own_time * 1000 >= threshold_ms ): print("{}{}: {}ms".format(" " * indent, imp_mod, own_ms)) for child_imp_mod in imp_mod.children: print_imp_mod(child_imp_mod, indent + 1) for imp_mod in self._top_imp_modules: print_imp_mod(imp_mod) print() print("Total import time: {}ms".format(int(self.total_time * 1000)))
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import time class ImportedModule(object): """ A module that was imported with __import__. """ def __init__(self, name, globals, level, parent=None): self.name = name self.globals = globals self.level = level self.parent = parent self.children = [] self.time = None if parent: parent.children.append(self) def __eq__(self, value): return str(self) == str(value) @property def all_children(self): children = [] for child in self.children: children.append(child) children.extend(child.all_children) return children @property def own_time(self): """ How many seconds it took to import this module, minus all child imports. """ return self.time - sum(child.time for child in self.children) def __str__(self): if self.globals and self.level: if self.level == 1: prefix = self.globals["__package__"] else: end = -1 * (self.level - 1) prefix = ".".join(self.globals["__package__"].split(".")[:end]) + "." else: prefix = "" return "{}{}".format(prefix, self.name) def __enter__(self): self._start_time = time.time() def __exit__(self, exc_type, exc_val, exc_tb): self.time = time.time() - self._start_time class ImportProfiler(object): """ Experimental! Quick'n dirty profiler for module import times. Usage: from testslide.import_profiler import ImportProfiler with ImportProfiler() as import_profiler: import everything.here import_profiler.print_stats(100) This will print the dependency tree for imported modules that took more than 100ms to be imported. """ def __init__(self): self._original_import = __builtins__["__import__"] def __enter__(self): __builtins__["__import__"] = self._profiled_import self._top_imp_modules = [] self._import_stack = [] self.total_time = None self._start_time = time.time() return self def __exit__(self, exc_type, exc_val, exc_tb): self.total_time = time.time() - self._start_time __builtins__["__import__"] = self._original_import # def _profiled_import(self, name, globals=None, locals=None, fromlist=(), level=0): def _profiled_import(self, name, globals=None, locals=None, fromlist=(), level=0): # print('Importing {}'.format(repr(name))) imp_mod = ImportedModule( name=name, globals=globals, level=level, parent=self._import_stack[-1] if self._import_stack else None, ) if not self._import_stack: self._top_imp_modules.append(imp_mod) self._import_stack.append(imp_mod) with imp_mod: try: return self._original_import(name, globals, locals, fromlist, level) finally: self._import_stack.pop() def print_stats(self, threshold_ms=0): def print_imp_mod(imp_mod, indent=0): own_ms = int(imp_mod.own_time * 1000) if own_ms >= threshold_ms or any( child for child in imp_mod.all_children if child.own_time * 1000 >= threshold_ms ): print("{}{}: {}ms".format(" " * indent, imp_mod, own_ms)) for child_imp_mod in imp_mod.children: print_imp_mod(child_imp_mod, indent + 1) for imp_mod in self._top_imp_modules: print_imp_mod(imp_mod) print() print("Total import time: {}ms".format(int(self.total_time * 1000)))
en
0.800996
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. A module that was imported with __import__. How many seconds it took to import this module, minus all child imports. Experimental! Quick'n dirty profiler for module import times. Usage: from testslide.import_profiler import ImportProfiler with ImportProfiler() as import_profiler: import everything.here import_profiler.print_stats(100) This will print the dependency tree for imported modules that took more than 100ms to be imported. # def _profiled_import(self, name, globals=None, locals=None, fromlist=(), level=0): # print('Importing {}'.format(repr(name)))
2.565533
3
companion/src/cycle.py
kreako/soklaki
0
6623227
<filename>companion/src/cycle.py from datetime import date, timedelta YEARS_6 = timedelta(days=6 * 365 + 1) YEARS_9 = timedelta(days=9 * 365 + 2) YEARS_12 = timedelta(days=12 * 365 + 3) def estimate_cycle(birthdate, evaluation_date): # First estimate scholar year of the evaluation if evaluation_date.month > 8: scholar_year = evaluation_date.year else: scholar_year = evaluation_date.year - 1 # the date corresponding to the end of the year in the scholar year end_of_year = date(scholar_year, 12, 31) age = end_of_year - birthdate if age < YEARS_6: return "c1" elif age < YEARS_9: return "c2" elif age < YEARS_12: return "c3" else: return "c4"
<filename>companion/src/cycle.py from datetime import date, timedelta YEARS_6 = timedelta(days=6 * 365 + 1) YEARS_9 = timedelta(days=9 * 365 + 2) YEARS_12 = timedelta(days=12 * 365 + 3) def estimate_cycle(birthdate, evaluation_date): # First estimate scholar year of the evaluation if evaluation_date.month > 8: scholar_year = evaluation_date.year else: scholar_year = evaluation_date.year - 1 # the date corresponding to the end of the year in the scholar year end_of_year = date(scholar_year, 12, 31) age = end_of_year - birthdate if age < YEARS_6: return "c1" elif age < YEARS_9: return "c2" elif age < YEARS_12: return "c3" else: return "c4"
en
0.846065
# First estimate scholar year of the evaluation # the date corresponding to the end of the year in the scholar year
3.684935
4
wizzer/__init__.py
mabolhasani/wizzer
0
6623228
<reponame>mabolhasani/wizzer #module file: __init__.py """This module is a wizard builder for setting up parameters [ e.g. variable(s) / configuration(s) ] to run a service."""
#module file: __init__.py """This module is a wizard builder for setting up parameters [ e.g. variable(s) / configuration(s) ] to run a service."""
en
0.426073
#module file: __init__.py This module is a wizard builder for setting up parameters [ e.g. variable(s) / configuration(s) ] to run a service.
1.665951
2
vlm/param.py
woojeongjin/vokenization
173
6623229
<reponame>woojeongjin/vokenization import argparse def process_args(): parser = argparse.ArgumentParser() # Datasets parser.add_argument( "--train_data_file", default=None, type=str, help="The input training data file (a text file).") parser.add_argument( "--eval_data_file", default=None, type=str, help="An optional input evaluation data file to evaluate the perplexity on (a text file).") parser.add_argument("--do_train", action="store_true", help="Whether to run training.") parser.add_argument("--do_eval", action="store_true", help="Whether to run eval on the dev set.") # Data loader parser.add_argument("--col_data", action="store_true", help="Using the specific dataset object in data.py") parser.add_argument("--split_sent", action="store_true", help="Overwrite the cached training and evaluation sets") parser.add_argument("--shuffle", action="store_true", help="Shuffle the training dataset") parser.add_argument( "--block_size", default=-1, type=int, help="Optional input sequence length after tokenization." "The training dataset will be truncated in block of this size for training." "Default to the model max input length for single sentence inputs (take into account special tokens).", ) # Logging and Saving parser.add_argument("--logging_steps", type=int, default=500, help="Log every X updates steps.") parser.add_argument( "--output_dir", type=str, help="The output directory where the model predictions and checkpoints will be written.",) parser.add_argument( "--overwrite_output_dir", action="store_true", help="Overwrite the content of the output directory") # Model types parser.add_argument( "--model_type", type=str, help="The model architecture to be trained or fine-tuned.",) parser.add_argument( "--should_continue", action="store_true", help="Whether to continue from latest checkpoint in output_dir") parser.add_argument( "--model_name_or_path", default=None, type=str, help="The model checkpoint for weights initialization. Leave None if you want to train a model from scratch.",) parser.add_argument( "--config_name", default=None, type=str, help="Optional pretrained config name or path if not the same as model_name_or_path. If both are None, initialize a new config.",) parser.add_argument( "--tokenizer_name", default=None, type=str, help="Optional pretrained tokenizer name or path if not the same as model_name_or_path. If both are None, initialize a new tokenizer.",) parser.add_argument( "--cache_dir", default=None, type=str, help="Optional directory to store the pre-trained models downloaded from s3 (instead of the default one)",) parser.add_argument( "--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets") # MLM tasks parser.add_argument( "--mlm", action="store_true", help="Train with masked-language modeling loss instead of language modeling.") parser.add_argument( "--mlm_probability", type=float, default=0.15, help="Ratio of tokens to mask for masked language modeling loss") parser.add_argument( "--mlm_ratio", type=float, default=1., help="The ratio of mlm loss in the total loss.") # VLM related params parser.add_argument("--voken_dir", type=str, default='snap1/coco_hinge05_dim64_resxt101_robertal4/vokens', help='Where the vokens are saved') parser.add_argument("--voken_suffix", type=str, default='vg_nococo.10000', help='The suffix after the voken file, e.g., en.train.raw.{suffix} where suffix==vgcoco.1000') parser.add_argument("--voken_labels", type=str, default='all', help='all: Calculate voken loss for all tokens;' 'mask: Calculate voken loss for masked tokens.' 'nonmask: Calculate voken loss for non-masked tokens.') parser.add_argument("--voken_feat_dir", type=str, default=None, help='Where the vokens are saved') parser.add_argument("--do_voken_cls", action='store_true', help='Will do voken classification task') parser.add_argument("--do_voken_reg", action='store_true', help='Will do voken regression task (not used in this paper)') parser.add_argument("--do_voken_ctr", action='store_true', help='Will do voken contrastive task (not used in this paper)') parser.add_argument("--shared_head", action='store_true', help='Share the head if more than one tasks (e.g., cls, reg, ctr) are used (not used in this paper)') # Batch Size and Training Steps parser.add_argument("--seed", type=int, default=95, help="random seed for initialization") parser.add_argument("--per_gpu_train_batch_size", default=4, type=int, help="Batch size per GPU/CPU for training.") parser.add_argument("--per_gpu_eval_batch_size", default=4, type=int, help="Batch size per GPU/CPU for evaluation.") parser.add_argument("--gradient_accumulation_steps", type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.",) parser.add_argument("--num_train_epochs", default=1.0, type=float, help="Total number of training epochs to perform.") parser.add_argument("--max_steps", default=-1, type=int, help="If > 0: set total number of training steps to perform. Override num_train_epochs.",) # Optimizer parser.add_argument("--lamb", action="store_true", help='Use the LAMB optimizer in apex') parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.") parser.add_argument("--warmup_ratio", default=0., type=float, help="Linear warmup over warmup_steps.") parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.") parser.add_argument("--weight_decay", default=0.01, type=float, help="Weight decay if we apply some.") parser.add_argument("--adam_epsilon", default=1e-6, type=float, help="Epsilon for Adam optimizer.") parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.") # Distributed Training parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank") parser.add_argument("--nodes", type=int, default=1) parser.add_argument("--nr", type=int, default=0) # Half Precision parser.add_argument( "--fp16", action="store_true", help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit",) parser.add_argument( "--fp16_opt_level", type=str, default="O1", help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html",) # Ablation Study parser.add_argument("--voken_ablation", default=None, help="random, shuffle, reverse, token") args = parser.parse_args() return args
import argparse def process_args(): parser = argparse.ArgumentParser() # Datasets parser.add_argument( "--train_data_file", default=None, type=str, help="The input training data file (a text file).") parser.add_argument( "--eval_data_file", default=None, type=str, help="An optional input evaluation data file to evaluate the perplexity on (a text file).") parser.add_argument("--do_train", action="store_true", help="Whether to run training.") parser.add_argument("--do_eval", action="store_true", help="Whether to run eval on the dev set.") # Data loader parser.add_argument("--col_data", action="store_true", help="Using the specific dataset object in data.py") parser.add_argument("--split_sent", action="store_true", help="Overwrite the cached training and evaluation sets") parser.add_argument("--shuffle", action="store_true", help="Shuffle the training dataset") parser.add_argument( "--block_size", default=-1, type=int, help="Optional input sequence length after tokenization." "The training dataset will be truncated in block of this size for training." "Default to the model max input length for single sentence inputs (take into account special tokens).", ) # Logging and Saving parser.add_argument("--logging_steps", type=int, default=500, help="Log every X updates steps.") parser.add_argument( "--output_dir", type=str, help="The output directory where the model predictions and checkpoints will be written.",) parser.add_argument( "--overwrite_output_dir", action="store_true", help="Overwrite the content of the output directory") # Model types parser.add_argument( "--model_type", type=str, help="The model architecture to be trained or fine-tuned.",) parser.add_argument( "--should_continue", action="store_true", help="Whether to continue from latest checkpoint in output_dir") parser.add_argument( "--model_name_or_path", default=None, type=str, help="The model checkpoint for weights initialization. Leave None if you want to train a model from scratch.",) parser.add_argument( "--config_name", default=None, type=str, help="Optional pretrained config name or path if not the same as model_name_or_path. If both are None, initialize a new config.",) parser.add_argument( "--tokenizer_name", default=None, type=str, help="Optional pretrained tokenizer name or path if not the same as model_name_or_path. If both are None, initialize a new tokenizer.",) parser.add_argument( "--cache_dir", default=None, type=str, help="Optional directory to store the pre-trained models downloaded from s3 (instead of the default one)",) parser.add_argument( "--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets") # MLM tasks parser.add_argument( "--mlm", action="store_true", help="Train with masked-language modeling loss instead of language modeling.") parser.add_argument( "--mlm_probability", type=float, default=0.15, help="Ratio of tokens to mask for masked language modeling loss") parser.add_argument( "--mlm_ratio", type=float, default=1., help="The ratio of mlm loss in the total loss.") # VLM related params parser.add_argument("--voken_dir", type=str, default='snap1/coco_hinge05_dim64_resxt101_robertal4/vokens', help='Where the vokens are saved') parser.add_argument("--voken_suffix", type=str, default='vg_nococo.10000', help='The suffix after the voken file, e.g., en.train.raw.{suffix} where suffix==vgcoco.1000') parser.add_argument("--voken_labels", type=str, default='all', help='all: Calculate voken loss for all tokens;' 'mask: Calculate voken loss for masked tokens.' 'nonmask: Calculate voken loss for non-masked tokens.') parser.add_argument("--voken_feat_dir", type=str, default=None, help='Where the vokens are saved') parser.add_argument("--do_voken_cls", action='store_true', help='Will do voken classification task') parser.add_argument("--do_voken_reg", action='store_true', help='Will do voken regression task (not used in this paper)') parser.add_argument("--do_voken_ctr", action='store_true', help='Will do voken contrastive task (not used in this paper)') parser.add_argument("--shared_head", action='store_true', help='Share the head if more than one tasks (e.g., cls, reg, ctr) are used (not used in this paper)') # Batch Size and Training Steps parser.add_argument("--seed", type=int, default=95, help="random seed for initialization") parser.add_argument("--per_gpu_train_batch_size", default=4, type=int, help="Batch size per GPU/CPU for training.") parser.add_argument("--per_gpu_eval_batch_size", default=4, type=int, help="Batch size per GPU/CPU for evaluation.") parser.add_argument("--gradient_accumulation_steps", type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.",) parser.add_argument("--num_train_epochs", default=1.0, type=float, help="Total number of training epochs to perform.") parser.add_argument("--max_steps", default=-1, type=int, help="If > 0: set total number of training steps to perform. Override num_train_epochs.",) # Optimizer parser.add_argument("--lamb", action="store_true", help='Use the LAMB optimizer in apex') parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.") parser.add_argument("--warmup_ratio", default=0., type=float, help="Linear warmup over warmup_steps.") parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.") parser.add_argument("--weight_decay", default=0.01, type=float, help="Weight decay if we apply some.") parser.add_argument("--adam_epsilon", default=1e-6, type=float, help="Epsilon for Adam optimizer.") parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.") # Distributed Training parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank") parser.add_argument("--nodes", type=int, default=1) parser.add_argument("--nr", type=int, default=0) # Half Precision parser.add_argument( "--fp16", action="store_true", help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit",) parser.add_argument( "--fp16_opt_level", type=str, default="O1", help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html",) # Ablation Study parser.add_argument("--voken_ablation", default=None, help="random, shuffle, reverse, token") args = parser.parse_args() return args
en
0.798648
# Datasets # Data loader # Logging and Saving # Model types # MLM tasks # VLM related params # Batch Size and Training Steps # Optimizer # Distributed Training # Half Precision # Ablation Study
2.803858
3
rough_work/test.py
ndey96/spiking-actor-critic
1
6623230
<gh_stars>1-10 import numpy as np import matplotlib.pyplot as plt import nengo import nengo_ocl # define the model with nengo.Network() as model: stim = nengo.Node(np.sin) a = nengo.Ensemble(100, 1) b = nengo.Ensemble(100, 1) nengo.Connection(stim, a) nengo.Connection(a, b, function=lambda x: x**2) probe_a = nengo.Probe(a, synapse=0.01) probe_b = nengo.Probe(b, synapse=0.01) # build and run the model with nengo_ocl.Simulator(model) as sim: sim.run(10) # plot the results #plt.plot(sim.trange(), sim.data[probe_a]) #plt.plot(sim.trange(), sim.data[probe_b]) #plt.show()
import numpy as np import matplotlib.pyplot as plt import nengo import nengo_ocl # define the model with nengo.Network() as model: stim = nengo.Node(np.sin) a = nengo.Ensemble(100, 1) b = nengo.Ensemble(100, 1) nengo.Connection(stim, a) nengo.Connection(a, b, function=lambda x: x**2) probe_a = nengo.Probe(a, synapse=0.01) probe_b = nengo.Probe(b, synapse=0.01) # build and run the model with nengo_ocl.Simulator(model) as sim: sim.run(10) # plot the results #plt.plot(sim.trange(), sim.data[probe_a]) #plt.plot(sim.trange(), sim.data[probe_b]) #plt.show()
en
0.101077
# define the model # build and run the model # plot the results #plt.plot(sim.trange(), sim.data[probe_a]) #plt.plot(sim.trange(), sim.data[probe_b]) #plt.show()
2.711178
3
chat/migrations/0002_auto_20190625_1304.py
lokesh1729/chatapp
1
6623231
# Generated by Django 2.0.13 on 2019-06-25 07:34 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('chat', '0001_initial'), ] operations = [ migrations.RenameField( model_name='participant', old_name='room', new_name='rooms', ), ]
# Generated by Django 2.0.13 on 2019-06-25 07:34 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('chat', '0001_initial'), ] operations = [ migrations.RenameField( model_name='participant', old_name='room', new_name='rooms', ), ]
en
0.728945
# Generated by Django 2.0.13 on 2019-06-25 07:34
1.828832
2
2019/day2/2.py
tomhel/AoC_2019
1
6623232
<filename>2019/day2/2.py #!/usr/bin/env python3 def execute(prog): pc = 0 while True: op = prog[pc] if op == 1: r = prog[prog[pc + 1]] + prog[prog[pc + 2]] prog[prog[pc + 3]] = r pc += 4 elif op == 2: r = prog[prog[pc + 1]] * prog[prog[pc + 2]] prog[prog[pc + 3]] = r pc += 4 elif op == 99: break else: raise Exception("unknown op: %d" % op) def find_init_values(prog): for noun in range(100): for verb in range(100): p = prog[:] p[1] = noun p[2] = verb execute(p) if p[0] == 19690720: return noun, verb program = [int(i) for i in open("input").read().split(",")] print("%02d%02d" % find_init_values(program))
<filename>2019/day2/2.py #!/usr/bin/env python3 def execute(prog): pc = 0 while True: op = prog[pc] if op == 1: r = prog[prog[pc + 1]] + prog[prog[pc + 2]] prog[prog[pc + 3]] = r pc += 4 elif op == 2: r = prog[prog[pc + 1]] * prog[prog[pc + 2]] prog[prog[pc + 3]] = r pc += 4 elif op == 99: break else: raise Exception("unknown op: %d" % op) def find_init_values(prog): for noun in range(100): for verb in range(100): p = prog[:] p[1] = noun p[2] = verb execute(p) if p[0] == 19690720: return noun, verb program = [int(i) for i in open("input").read().split(",")] print("%02d%02d" % find_init_values(program))
fr
0.221828
#!/usr/bin/env python3
3.467883
3
config.py
SnewbieChen/YunWeiBlog
1
6623233
# -*- coding: utf-8 -*- # @Author : YunWei.Chen # @Site : https://chen.yunwei.space import os import datetime class Config: DEBUG = False # 是否开启调试模式 SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://yunwei:chen@yunwei#space@localhost/myspace' # 数据库URI SECRET_KEY = 'Chen@YunWei#Space->Blog' # session加密密钥 JSON_AS_ASCII = False # 让JSON字符串显示中文 PERMANENT_SESSION_LIFETIME = datetime.timedelta(days=3) # 设置session过期时间为3天 SQLALCHEMY_COMMIT_ON_TEARDOWN = True SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_RECORD_QUERIES = True UPLOAD_DIR = 'uploads' # 文件保存文件夹名 UPLOAD_FOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), UPLOAD_DIR) # 文件上传目录
# -*- coding: utf-8 -*- # @Author : YunWei.Chen # @Site : https://chen.yunwei.space import os import datetime class Config: DEBUG = False # 是否开启调试模式 SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://yunwei:chen@yunwei#space@localhost/myspace' # 数据库URI SECRET_KEY = 'Chen@YunWei#Space->Blog' # session加密密钥 JSON_AS_ASCII = False # 让JSON字符串显示中文 PERMANENT_SESSION_LIFETIME = datetime.timedelta(days=3) # 设置session过期时间为3天 SQLALCHEMY_COMMIT_ON_TEARDOWN = True SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_RECORD_QUERIES = True UPLOAD_DIR = 'uploads' # 文件保存文件夹名 UPLOAD_FOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), UPLOAD_DIR) # 文件上传目录
zh
0.636533
# -*- coding: utf-8 -*- # @Author : YunWei.Chen # @Site : https://chen.yunwei.space # 是否开启调试模式 #space@localhost/myspace' # 数据库URI #Space->Blog' # session加密密钥 # 让JSON字符串显示中文 # 设置session过期时间为3天 # 文件保存文件夹名 # 文件上传目录
2.07028
2
app.py
rishabh99-rc/Student-Feedback-Sentimental-Analysis
0
6623234
<filename>app.py import pandas as pd import numpy as np import matplotlib.pyplot as plt import json import faculty import drawFigure from flask import Flask , render_template , redirect , request app = Flask(__name__) with open('feedback1.json') as file: json_string = file.read() documents1 = json.loads(json_string) with open('feedback2.json') as file: json_string = file.read() documents2 = json.loads(json_string) with open('feedback3.json') as file: json_string = file.read() documents3 = json.loads(json_string) with open('feedback4.json') as file: json_string = file.read() documents4 = json.loads(json_string) with open('feedback5.json') as file: json_string = file.read() documents5 = json.loads(json_string) with open('feedback6.json') as file: json_string = file.read() documents6 = json.loads(json_string) label2category = {1: 'positive' , 0: 'neutral' , -1: 'negative'} category2label = {cat:label for label , cat in label2category.items()} categories1 = [category2label[category] for doc , category in documents1] categories2 = [category2label[category] for doc , category in documents2] categories3 = [category2label[category] for doc , category in documents3] categories4 = [category2label[category] for doc , category in documents4] categories5 = [category2label[category] for doc , category in documents5] categories6 = [category2label[category] for doc , category in documents6] corpus1 = [' '.join(document) for document , cat in documents1] corpus2 = [' '.join(document) for document , cat in documents2] corpus3 = [' '.join(document) for document , cat in documents3] corpus4 = [' '.join(document) for document , cat in documents4] corpus5 = [' '.join(document) for document , cat in documents5] corpus6 = [' '.join(document) for document , cat in documents6] @app.route('/') def display(): return render_template('index.html') @app.route('/' , methods=['POST']) def caption(): if request.method == 'POST': f = request.files["file_name"] path = "./static/{}".format(f.filename) f.save(path) category_no = int(request.form['Cate']) df = pd.read_csv(path) cols1 = [] cols2 = [] cols3 = [] cols4 = [] cols5 = [] cols6 = [] substring1 = ['teacher' , 'faculty' , 'feedback' , 'effectiveness' , 'teaching' , 'knowledge' , 'delivery' , 'content' , 'quality' , 'lecture' , 'subject' , 'syllabus' , 'review' , 'assessment'] substring2 = ['course' , 'content' , 'syllabus' , 'review' , 'evaluation' , 'curriculum' , 'syllabi' , 'contents' , 'level' , 'difficulty' , 'lecture' , 'outline'] substring3 = ['exam' , 'examination' , 'pattern' , 'conduct' , 'question' , 'paper' , 'level' , 'outline'] substring4 = ['laboratory' , 'laboratories' , 'lab' , 'facility' , 'facilities' , 'review' , 'feedback' , 'rate' , 'learning' ] substring5 = ['library' , 'facilities' , 'books' , 'availability' , 'facility' , 'material' , 'rate' , 'feedback' , 'review'] substring6 = ['extra' , 'curricular' , 'activity' , 'activities'] for i in list(df.columns): for j in substring1: if j.casefold() in i.casefold(): cols1.append(df.columns.get_loc(i)) if cols1 != []: break for i in list(df.columns): for j in substring2: if j.casefold() in i.casefold(): cols2.append(df.columns.get_loc(i)) if cols2 != []: break for i in list(df.columns): for j in substring3: if j.casefold() in i.casefold(): cols3.append(df.columns.get_loc(i)) if cols3 != []: break for i in list(df.columns): for j in substring4: if j.casefold() in i.casefold(): cols4.append(df.columns.get_loc(i)) if cols4 != []: break for i in list(df.columns): for j in substring5: if j.casefold() in i.casefold(): cols5.append(df.columns.get_loc(i)) if cols5 != []: break for i in list(df.columns): for j in substring6: if j.casefold() in i.casefold(): cols6.append(df.columns.get_loc(i)) if cols6 != []: break cols = cols1+cols2+cols3+cols4+cols5+cols6 cols = list(set(cols)) df_form = pd.read_csv(path , usecols = cols) reviews = np.array(df_form) pos1 , n1 , neg1 = faculty.predict(corpus1 , categories1 , reviews[: , 0]) pos2 , n2 , neg2 = faculty.predict(corpus1 , categories1 , reviews[: , 1]) pos3 , n3 , neg3 = faculty.predict(corpus1 , categories1 , reviews[: , 2]) pos4 , n4 , neg4 = faculty.predict(corpus1 , categories1 , reviews[: , 3]) pos5 , n5 , neg5 = faculty.predict(corpus1 , categories1 , reviews[: , 4]) pos6 , n6 , neg6 = faculty.predict(corpus1 , categories1 , reviews[: , 5]) results = { 'f1' : 'Teacher Feedback', 'pos1' : pos1, 'n1' : n1, 'neg1' : neg1, 'f2' : 'Course Content', 'pos2' : pos2, 'n2' : n2, 'neg1' : neg2, 'f3' : 'Examination pattern', 'pos3' : pos3, 'n3' : n3, 'neg3' : neg3, 'f4' : 'Laboratory', 'pos4' : pos4, 'n4' : n4, 'neg4' : neg4, 'f5' : 'Library Facilities', 'pos5' : pos5, 'n5' : n5, 'neg5' : neg5, 'f6' : 'Extra Co-Curricular Activities', 'pos6' : pos6, 'n6' : n6, 'neg6' : neg6, } values = list([[pos1 , n1 , neg1], [pos2 , n2 , neg2], [pos3 , n3 , neg3], [pos4 , n4 , neg4], [pos5 , n5 , neg5], [pos6 , n6 , neg6]]) labels = list(['Teacher Feedback', 'Course Content', 'Examination pattern','Laboratory','Library Facilities', 'Extra Co-Curricular Activities']) print(values[category_no-1] , labels[category_no-1] , category_no , category_no-1) if category_no == 1: results_1 = { 'f1' : 'Teacher Feedback', 'pos1' : pos1, 'n1' : n1, 'neg1' : neg1 } drawFigure.make(values[category_no-1] , labels[category_no-1] , category_no) return render_template('index1.html' , result1 = results_1 , cat = category_no) elif category_no == 2: results_2 = { 'f2' : 'Course Content', 'pos2' : pos2, 'n2' : n2, 'neg2' : neg2 } drawFigure.make(values[category_no-1] , labels[category_no-1] , category_no) return render_template('index1.html' , result2 = results_2 , cat = category_no) elif category_no == 3: results_3 = { 'f3' : 'Examination pattern', 'pos3' : pos3, 'n3' : n3, 'neg3' : neg3 } drawFigure.make(values[category_no-1] , labels[category_no-1] , category_no) return render_template('index1.html' , result3 = results_3 , cat = category_no) elif category_no == 4: results_4 = { 'f4' : 'Laboratory', 'pos4' : pos4, 'n4' : n4, 'neg4' : neg4 } drawFigure.make(values[category_no-1] , labels[category_no-1] , category_no) return render_template('index1.html' , result4 = results_4 , cat = category_no) elif category_no == 5: results_5 = { 'f5' : 'Library Facilities', 'pos5' : pos5, 'n5' : n5, 'neg5' : neg5 } drawFigure.make(values[category_no-1] , labels[category_no-1] , category_no) return render_template('index1.html' , result5 = results_5 , cat = category_no) elif category_no == 6: results_6 = { 'f6' : 'Extra Co-Curricular Activities', 'pos6' : pos6, 'n6' : n6, 'neg6' : neg6 } drawFigure.make(values[category_no-1] , labels[category_no-1] , category_no) return render_template('index1.html' , result6 = results_6 , cat = category_no) else: for i in range(0 , 6): fig = plt.figure(figsize=(8,8) , edgecolor='red' , linewidth=10) plt.bar(x = ['Positive' , 'Neutral' , 'Negative'] , height = values[i] , color=['blue','gold','red']) plt.title(labels[i], fontsize = 24, weight = 'demibold', pad = 15, fontstyle = 'italic' , family = 'cursive') plt.xticks(rotation=0 , fontsize=16) plt.yticks([]) plt.xlabel('Feedback Type',fontsize = 18, labelpad=17, weight= 550 , family = 'cursive') plt.ylabel('') fig.subplots_adjust(bottom = 0.14) ax = plt.gca() ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['left'].set_visible(False) for p in ax.patches: ax.annotate("%.1f%%" % (100*float(p.get_height()/sum(values[i]))), (p.get_x() + p.get_width() / 2., abs(p.get_height())), ha='center', va='bottom', color='black', xytext=(0, 5),rotation = 'horizontal', textcoords='offset points', fontsize = 16 , fontweight = 'medium') plt.savefig(f'./static/plot{i+10}.jpg') return render_template('index1.html' , result = results) else: return render_template('error.html') if __name__ == '__main__': app.run(debug=True)
<filename>app.py import pandas as pd import numpy as np import matplotlib.pyplot as plt import json import faculty import drawFigure from flask import Flask , render_template , redirect , request app = Flask(__name__) with open('feedback1.json') as file: json_string = file.read() documents1 = json.loads(json_string) with open('feedback2.json') as file: json_string = file.read() documents2 = json.loads(json_string) with open('feedback3.json') as file: json_string = file.read() documents3 = json.loads(json_string) with open('feedback4.json') as file: json_string = file.read() documents4 = json.loads(json_string) with open('feedback5.json') as file: json_string = file.read() documents5 = json.loads(json_string) with open('feedback6.json') as file: json_string = file.read() documents6 = json.loads(json_string) label2category = {1: 'positive' , 0: 'neutral' , -1: 'negative'} category2label = {cat:label for label , cat in label2category.items()} categories1 = [category2label[category] for doc , category in documents1] categories2 = [category2label[category] for doc , category in documents2] categories3 = [category2label[category] for doc , category in documents3] categories4 = [category2label[category] for doc , category in documents4] categories5 = [category2label[category] for doc , category in documents5] categories6 = [category2label[category] for doc , category in documents6] corpus1 = [' '.join(document) for document , cat in documents1] corpus2 = [' '.join(document) for document , cat in documents2] corpus3 = [' '.join(document) for document , cat in documents3] corpus4 = [' '.join(document) for document , cat in documents4] corpus5 = [' '.join(document) for document , cat in documents5] corpus6 = [' '.join(document) for document , cat in documents6] @app.route('/') def display(): return render_template('index.html') @app.route('/' , methods=['POST']) def caption(): if request.method == 'POST': f = request.files["file_name"] path = "./static/{}".format(f.filename) f.save(path) category_no = int(request.form['Cate']) df = pd.read_csv(path) cols1 = [] cols2 = [] cols3 = [] cols4 = [] cols5 = [] cols6 = [] substring1 = ['teacher' , 'faculty' , 'feedback' , 'effectiveness' , 'teaching' , 'knowledge' , 'delivery' , 'content' , 'quality' , 'lecture' , 'subject' , 'syllabus' , 'review' , 'assessment'] substring2 = ['course' , 'content' , 'syllabus' , 'review' , 'evaluation' , 'curriculum' , 'syllabi' , 'contents' , 'level' , 'difficulty' , 'lecture' , 'outline'] substring3 = ['exam' , 'examination' , 'pattern' , 'conduct' , 'question' , 'paper' , 'level' , 'outline'] substring4 = ['laboratory' , 'laboratories' , 'lab' , 'facility' , 'facilities' , 'review' , 'feedback' , 'rate' , 'learning' ] substring5 = ['library' , 'facilities' , 'books' , 'availability' , 'facility' , 'material' , 'rate' , 'feedback' , 'review'] substring6 = ['extra' , 'curricular' , 'activity' , 'activities'] for i in list(df.columns): for j in substring1: if j.casefold() in i.casefold(): cols1.append(df.columns.get_loc(i)) if cols1 != []: break for i in list(df.columns): for j in substring2: if j.casefold() in i.casefold(): cols2.append(df.columns.get_loc(i)) if cols2 != []: break for i in list(df.columns): for j in substring3: if j.casefold() in i.casefold(): cols3.append(df.columns.get_loc(i)) if cols3 != []: break for i in list(df.columns): for j in substring4: if j.casefold() in i.casefold(): cols4.append(df.columns.get_loc(i)) if cols4 != []: break for i in list(df.columns): for j in substring5: if j.casefold() in i.casefold(): cols5.append(df.columns.get_loc(i)) if cols5 != []: break for i in list(df.columns): for j in substring6: if j.casefold() in i.casefold(): cols6.append(df.columns.get_loc(i)) if cols6 != []: break cols = cols1+cols2+cols3+cols4+cols5+cols6 cols = list(set(cols)) df_form = pd.read_csv(path , usecols = cols) reviews = np.array(df_form) pos1 , n1 , neg1 = faculty.predict(corpus1 , categories1 , reviews[: , 0]) pos2 , n2 , neg2 = faculty.predict(corpus1 , categories1 , reviews[: , 1]) pos3 , n3 , neg3 = faculty.predict(corpus1 , categories1 , reviews[: , 2]) pos4 , n4 , neg4 = faculty.predict(corpus1 , categories1 , reviews[: , 3]) pos5 , n5 , neg5 = faculty.predict(corpus1 , categories1 , reviews[: , 4]) pos6 , n6 , neg6 = faculty.predict(corpus1 , categories1 , reviews[: , 5]) results = { 'f1' : 'Teacher Feedback', 'pos1' : pos1, 'n1' : n1, 'neg1' : neg1, 'f2' : 'Course Content', 'pos2' : pos2, 'n2' : n2, 'neg1' : neg2, 'f3' : 'Examination pattern', 'pos3' : pos3, 'n3' : n3, 'neg3' : neg3, 'f4' : 'Laboratory', 'pos4' : pos4, 'n4' : n4, 'neg4' : neg4, 'f5' : 'Library Facilities', 'pos5' : pos5, 'n5' : n5, 'neg5' : neg5, 'f6' : 'Extra Co-Curricular Activities', 'pos6' : pos6, 'n6' : n6, 'neg6' : neg6, } values = list([[pos1 , n1 , neg1], [pos2 , n2 , neg2], [pos3 , n3 , neg3], [pos4 , n4 , neg4], [pos5 , n5 , neg5], [pos6 , n6 , neg6]]) labels = list(['Teacher Feedback', 'Course Content', 'Examination pattern','Laboratory','Library Facilities', 'Extra Co-Curricular Activities']) print(values[category_no-1] , labels[category_no-1] , category_no , category_no-1) if category_no == 1: results_1 = { 'f1' : 'Teacher Feedback', 'pos1' : pos1, 'n1' : n1, 'neg1' : neg1 } drawFigure.make(values[category_no-1] , labels[category_no-1] , category_no) return render_template('index1.html' , result1 = results_1 , cat = category_no) elif category_no == 2: results_2 = { 'f2' : 'Course Content', 'pos2' : pos2, 'n2' : n2, 'neg2' : neg2 } drawFigure.make(values[category_no-1] , labels[category_no-1] , category_no) return render_template('index1.html' , result2 = results_2 , cat = category_no) elif category_no == 3: results_3 = { 'f3' : 'Examination pattern', 'pos3' : pos3, 'n3' : n3, 'neg3' : neg3 } drawFigure.make(values[category_no-1] , labels[category_no-1] , category_no) return render_template('index1.html' , result3 = results_3 , cat = category_no) elif category_no == 4: results_4 = { 'f4' : 'Laboratory', 'pos4' : pos4, 'n4' : n4, 'neg4' : neg4 } drawFigure.make(values[category_no-1] , labels[category_no-1] , category_no) return render_template('index1.html' , result4 = results_4 , cat = category_no) elif category_no == 5: results_5 = { 'f5' : 'Library Facilities', 'pos5' : pos5, 'n5' : n5, 'neg5' : neg5 } drawFigure.make(values[category_no-1] , labels[category_no-1] , category_no) return render_template('index1.html' , result5 = results_5 , cat = category_no) elif category_no == 6: results_6 = { 'f6' : 'Extra Co-Curricular Activities', 'pos6' : pos6, 'n6' : n6, 'neg6' : neg6 } drawFigure.make(values[category_no-1] , labels[category_no-1] , category_no) return render_template('index1.html' , result6 = results_6 , cat = category_no) else: for i in range(0 , 6): fig = plt.figure(figsize=(8,8) , edgecolor='red' , linewidth=10) plt.bar(x = ['Positive' , 'Neutral' , 'Negative'] , height = values[i] , color=['blue','gold','red']) plt.title(labels[i], fontsize = 24, weight = 'demibold', pad = 15, fontstyle = 'italic' , family = 'cursive') plt.xticks(rotation=0 , fontsize=16) plt.yticks([]) plt.xlabel('Feedback Type',fontsize = 18, labelpad=17, weight= 550 , family = 'cursive') plt.ylabel('') fig.subplots_adjust(bottom = 0.14) ax = plt.gca() ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['left'].set_visible(False) for p in ax.patches: ax.annotate("%.1f%%" % (100*float(p.get_height()/sum(values[i]))), (p.get_x() + p.get_width() / 2., abs(p.get_height())), ha='center', va='bottom', color='black', xytext=(0, 5),rotation = 'horizontal', textcoords='offset points', fontsize = 16 , fontweight = 'medium') plt.savefig(f'./static/plot{i+10}.jpg') return render_template('index1.html' , result = results) else: return render_template('error.html') if __name__ == '__main__': app.run(debug=True)
none
1
2.617895
3
RASPI-stuff/python-codeline/Nokia5110/rpiMonitor.py
siliconchris1973/fairytale
3
6623235
<filename>RASPI-stuff/python-codeline/Nokia5110/rpiMonitor.py #!/usr/bin/env python import httplib, time, os, sys, json import pcd8544.lcd as lcd # class Process dedicated to process data get from Client # and send information to LCD and console class Process: # Process constructor def __init__(self): # Initialize LCD lcd.init() # Turn the backlight on lcd.backlight(1) def run(self, jsonString): # Parse data as json data = json.loads( jsonString ) # Try to get data from json or return default value try: rpi_temperature = data['living_room_temp'] except: rpi_temperature="--.---" try: rpi_humidity = data['humidity'] except: rpi_humidity = "--" # Construct string to be displayed on screens temperature = "Temp: %s C" % rpi_temperature humidity = "Humidity: %s %%" % rpi_humidity lcd.gotorc(0,1) lcd.text("RPi-Monitor") lcd.gotorc(2,0) lcd.text(temperature) lcd.gotorc(3,0) lcd.text(humidity) # Also print string in console os.system("clear") print " RPi-Monitor " print print temperature print humidity print time.sleep(1) # Class client design to work as web client and get information # from RPi-Monitor embedded web server class Client: # Client constructor def __init__(self): # Create a Process object self.process = Process() def run(self): # Infinite loop while True: try: # Initiate a connection to RPi-Monitor embedded server connection = httplib.HTTPConnection("localhost", 8888) # Get the file dynamic.json connection.request("GET","/dynamic.json") # Get the server response response = connection.getresponse() if ( response.status == 200 ): # If response is OK, read data data = response.read() # Run process object on extracted data self.process.run(data) # Close the connection to RPi-Monitor embedded server connection.close() finally: # Wait 5 secondes before restarting the loop time.sleep(5) # Main function def main(): try: # Create a Client object client = Client() # Run it client.run() except KeyboardInterrupt: # if Ctrl+C has been pressed # turn off the lcd backlight lcd.backlight(0); # exit from the program sys.exit(0) # Execute main if the script is directly called if __name__ == "__main__": main()
<filename>RASPI-stuff/python-codeline/Nokia5110/rpiMonitor.py #!/usr/bin/env python import httplib, time, os, sys, json import pcd8544.lcd as lcd # class Process dedicated to process data get from Client # and send information to LCD and console class Process: # Process constructor def __init__(self): # Initialize LCD lcd.init() # Turn the backlight on lcd.backlight(1) def run(self, jsonString): # Parse data as json data = json.loads( jsonString ) # Try to get data from json or return default value try: rpi_temperature = data['living_room_temp'] except: rpi_temperature="--.---" try: rpi_humidity = data['humidity'] except: rpi_humidity = "--" # Construct string to be displayed on screens temperature = "Temp: %s C" % rpi_temperature humidity = "Humidity: %s %%" % rpi_humidity lcd.gotorc(0,1) lcd.text("RPi-Monitor") lcd.gotorc(2,0) lcd.text(temperature) lcd.gotorc(3,0) lcd.text(humidity) # Also print string in console os.system("clear") print " RPi-Monitor " print print temperature print humidity print time.sleep(1) # Class client design to work as web client and get information # from RPi-Monitor embedded web server class Client: # Client constructor def __init__(self): # Create a Process object self.process = Process() def run(self): # Infinite loop while True: try: # Initiate a connection to RPi-Monitor embedded server connection = httplib.HTTPConnection("localhost", 8888) # Get the file dynamic.json connection.request("GET","/dynamic.json") # Get the server response response = connection.getresponse() if ( response.status == 200 ): # If response is OK, read data data = response.read() # Run process object on extracted data self.process.run(data) # Close the connection to RPi-Monitor embedded server connection.close() finally: # Wait 5 secondes before restarting the loop time.sleep(5) # Main function def main(): try: # Create a Client object client = Client() # Run it client.run() except KeyboardInterrupt: # if Ctrl+C has been pressed # turn off the lcd backlight lcd.backlight(0); # exit from the program sys.exit(0) # Execute main if the script is directly called if __name__ == "__main__": main()
en
0.787954
#!/usr/bin/env python # class Process dedicated to process data get from Client # and send information to LCD and console # Process constructor # Initialize LCD # Turn the backlight on # Parse data as json # Try to get data from json or return default value # Construct string to be displayed on screens # Also print string in console # Class client design to work as web client and get information # from RPi-Monitor embedded web server # Client constructor # Create a Process object # Infinite loop # Initiate a connection to RPi-Monitor embedded server # Get the file dynamic.json # Get the server response # If response is OK, read data # Run process object on extracted data # Close the connection to RPi-Monitor embedded server # Wait 5 secondes before restarting the loop # Main function # Create a Client object # Run it # if Ctrl+C has been pressed # turn off the lcd backlight # exit from the program # Execute main if the script is directly called
3.168679
3
demo.py
sseemayer/msacounts
1
6623236
#!/usr/bin/env python """msacounts demo Compile the C extensions using `python setup.py build_ext --inplace` before running this! """ import msacounts import sys import numpy as np def main(): aln = msacounts.read_msa('data/1atzA.aln') counts = msacounts.pair_counts(aln) pwm = msacounts.pwm(counts) np.savetxt('pwm.txt', pwm) if __name__ == '__main__': main()
#!/usr/bin/env python """msacounts demo Compile the C extensions using `python setup.py build_ext --inplace` before running this! """ import msacounts import sys import numpy as np def main(): aln = msacounts.read_msa('data/1atzA.aln') counts = msacounts.pair_counts(aln) pwm = msacounts.pwm(counts) np.savetxt('pwm.txt', pwm) if __name__ == '__main__': main()
en
0.443132
#!/usr/bin/env python msacounts demo Compile the C extensions using `python setup.py build_ext --inplace` before running this!
2.000182
2
scripts/shared_options.py
shaypal5/hollywood_crawler
7
6623237
<filename>scripts/shared_options.py """Shared holcrawl cli options.""" import click _SHARED_OPTIONS = [ click.option('--verbose/--silent', default=True, help="Turn printing progress to screen on or off.") ] def _shared_options(func): for option in reversed(_SHARED_OPTIONS): func = option(func) return func
<filename>scripts/shared_options.py """Shared holcrawl cli options.""" import click _SHARED_OPTIONS = [ click.option('--verbose/--silent', default=True, help="Turn printing progress to screen on or off.") ] def _shared_options(func): for option in reversed(_SHARED_OPTIONS): func = option(func) return func
en
0.402392
Shared holcrawl cli options.
2.54079
3
Python/homework/hw03/my_gray_scaler.py
LucasChangcoding/USTC-2018-Smester-1
32
6623238
from graphics import * class MyGrayScaler(object): # 构造函数, 注意 graphics 只支持 gif 和 ppm 格式的图片, 默认的图像文件名为 'color.gif' def __init__(self, filename='color.gif'): # 图像中心位于(200, 200) self.img = Image(Point(200, 200), filename) width = self.img.getWidth() height = self.img.getHeight() # 新建一个背景窗口, 长款分别为彩色图像的 2 倍 self.winImage = GraphWin('Color Image', width*2, height*2) # 显示图像 def showImg(self): # 先撤掉(可能)已经画过的图像 self.img.undraw() # 然后在背景窗口中画出 img self.img.draw(self.winImage) # 进行灰度转换 def convert(self): text = self.setHint('在窗口内单击鼠标进行灰度转换') self.winImage.getMouse() text.undraw() text = self.setHint('转换中...') img = self.img # 根据公式进行灰度转换 for x in range(img.getHeight()): for y in range(img.getWidth()): r, g, b = img.getPixel(x, y) grayscale = int(round(0.299*r + 0.587*g + 0.114*b)) img.setPixel(x, y, color_rgb(grayscale, grayscale, grayscale)) text.undraw() text = self.setHint('转换完成, 单击鼠标进入保存窗口') self.winImage.getMouse() # 设置提示 def setHint(self, hint=''): text = Text(Point(200, 50), hint) text.draw(self.winImage) return text # 保存图像 def saveImg(self): win2 = GraphWin('另存为', 400, 400) Text(Point(200, 150), '请输入文件名').draw(win2) Text(Point(200, 250), '然后单击空白处退出').draw(win2) inputText = Entry(Point(200, 200), 10) Text(Point(250, 200), '.gif').draw(win2) inputText.setText("gray image") inputText.draw(win2) win2.getMouse() filename = inputText.getText() self.img.save(filename+'.gif') if __name__ == '__main__': # 创建对象 mgs = MyGrayScaler() # 显示彩色图像 mgs.showImg() # 转换为灰度图 mgs.convert() # 保存图像 mgs.saveImg()
from graphics import * class MyGrayScaler(object): # 构造函数, 注意 graphics 只支持 gif 和 ppm 格式的图片, 默认的图像文件名为 'color.gif' def __init__(self, filename='color.gif'): # 图像中心位于(200, 200) self.img = Image(Point(200, 200), filename) width = self.img.getWidth() height = self.img.getHeight() # 新建一个背景窗口, 长款分别为彩色图像的 2 倍 self.winImage = GraphWin('Color Image', width*2, height*2) # 显示图像 def showImg(self): # 先撤掉(可能)已经画过的图像 self.img.undraw() # 然后在背景窗口中画出 img self.img.draw(self.winImage) # 进行灰度转换 def convert(self): text = self.setHint('在窗口内单击鼠标进行灰度转换') self.winImage.getMouse() text.undraw() text = self.setHint('转换中...') img = self.img # 根据公式进行灰度转换 for x in range(img.getHeight()): for y in range(img.getWidth()): r, g, b = img.getPixel(x, y) grayscale = int(round(0.299*r + 0.587*g + 0.114*b)) img.setPixel(x, y, color_rgb(grayscale, grayscale, grayscale)) text.undraw() text = self.setHint('转换完成, 单击鼠标进入保存窗口') self.winImage.getMouse() # 设置提示 def setHint(self, hint=''): text = Text(Point(200, 50), hint) text.draw(self.winImage) return text # 保存图像 def saveImg(self): win2 = GraphWin('另存为', 400, 400) Text(Point(200, 150), '请输入文件名').draw(win2) Text(Point(200, 250), '然后单击空白处退出').draw(win2) inputText = Entry(Point(200, 200), 10) Text(Point(250, 200), '.gif').draw(win2) inputText.setText("gray image") inputText.draw(win2) win2.getMouse() filename = inputText.getText() self.img.save(filename+'.gif') if __name__ == '__main__': # 创建对象 mgs = MyGrayScaler() # 显示彩色图像 mgs.showImg() # 转换为灰度图 mgs.convert() # 保存图像 mgs.saveImg()
zh
0.995467
# 构造函数, 注意 graphics 只支持 gif 和 ppm 格式的图片, 默认的图像文件名为 'color.gif' # 图像中心位于(200, 200) # 新建一个背景窗口, 长款分别为彩色图像的 2 倍 # 显示图像 # 先撤掉(可能)已经画过的图像 # 然后在背景窗口中画出 img # 进行灰度转换 # 根据公式进行灰度转换 # 设置提示 # 保存图像 # 创建对象 # 显示彩色图像 # 转换为灰度图 # 保存图像
3.299703
3
Rozdzial_1/r1_06.py
xinulsw/helion-python
1
6623239
<filename>Rozdzial_1/r1_06.py # program r1_06.py # Test modyfikacji obiektu typu list list_object = [11, 22, 33, "A", "B", "C"] print(f"Dla ID = {id(list_object)} wartość: {list_object}") # Do obiektu możemy dodać wartość list_object.append("Nowa") print(f"Dla ID = {id(list_object)} wartość: {list_object}") # lub zmienić wartość w środku list_object[2] = "Inna wartość" print(f"Dla ID = {id(list_object)} wartość: {list_object}") # Test modyfikacji obiektu typu dict dict_object = {1: "Pierwszy element"} print(f"Dla ID = {id(dict_object)} wartość: {dict_object}") # Do obiektu możemy dodać wartość dict_object[2] = "Drugi element" dict_object[3] = "Trzeci element" print(f"Dla ID = {id(dict_object)} wartość: {dict_object}") # lub zmienić wartość w środku dict_object[2] = "Inna wartość" print(f"Dla ID = {id(dict_object)} wartość: {dict_object}")
<filename>Rozdzial_1/r1_06.py # program r1_06.py # Test modyfikacji obiektu typu list list_object = [11, 22, 33, "A", "B", "C"] print(f"Dla ID = {id(list_object)} wartość: {list_object}") # Do obiektu możemy dodać wartość list_object.append("Nowa") print(f"Dla ID = {id(list_object)} wartość: {list_object}") # lub zmienić wartość w środku list_object[2] = "Inna wartość" print(f"Dla ID = {id(list_object)} wartość: {list_object}") # Test modyfikacji obiektu typu dict dict_object = {1: "Pierwszy element"} print(f"Dla ID = {id(dict_object)} wartość: {dict_object}") # Do obiektu możemy dodać wartość dict_object[2] = "Drugi element" dict_object[3] = "Trzeci element" print(f"Dla ID = {id(dict_object)} wartość: {dict_object}") # lub zmienić wartość w środku dict_object[2] = "Inna wartość" print(f"Dla ID = {id(dict_object)} wartość: {dict_object}")
pl
0.999329
# program r1_06.py # Test modyfikacji obiektu typu list # Do obiektu możemy dodać wartość # lub zmienić wartość w środku # Test modyfikacji obiektu typu dict # Do obiektu możemy dodać wartość # lub zmienić wartość w środku
3.169746
3
python/vast/voidfinder/viz/load_results.py
DESI-UR/VoidFinder
5
6623240
<filename>python/vast/voidfinder/viz/load_results.py import numpy import h5py from astropy.table import Table import matplotlib import matplotlib.pyplot as plt #from vast.voidfinder.absmag_comovingdist_functions import Distance from vast.voidfinder.distance import z_to_comoving_dist from vast.voidfinder.preprocessing import load_data_to_Table # Constants c = 3e5 DtoR = numpy.pi/180. RtoD = 180./numpy.pi distance_metric = 'comoving' #distance_metric = 'redshift' Omega_M = 0.3 h = 1.0 if __name__ == "__main__": infilename1 = "vollim_dr7_cbp_102709_holes.txt" infilename2 = "vollim_dr7_cbp_102709_maximal.txt" infilename3 = "vollim_dr7_cbp_102709.dat" ############################################################################ # load hole locations # keys are 'x' 'y' 'z' 'radius' 'flag' #--------------------------------------------------------------------------- holes_data = Table.read(infilename1, format='ascii.commented_header') ############################################################################ ############################################################################ # Load galaxy data and convert coordinates to xyz #--------------------------------------------------------------------------- galaxy_data = Table.read(infilename3, format='ascii.commented_header') if distance_metric == 'comoving': r_gal = galaxy_data['Rgal'] else: if 'redshift' in galaxy_data.colnames: z_column = 'redshift' elif 'REDSHIFT' in galaxy_data.colnames: z_column = 'REDSHIFT' elif 'z' in galaxy_data.colnames: z_column = 'z' else: print('Redshift column not known. Please rename column to "redshift".') r_gal = c*galaxy_data[z_column]/(100*h) xin = r_gal*numpy.cos(galaxy_data['ra']*DtoR)*numpy.cos(galaxy_data['dec']*DtoR) yin = r_gal*numpy.sin(galaxy_data['ra']*DtoR)*numpy.cos(galaxy_data['dec']*DtoR) zin = r_gal*numpy.sin(galaxy_data['dec']*DtoR) xyz_galaxy_data = Table([xin, yin, zin], names=('x','y','z')) ############################################################################ print(xyz_galaxy_data) print(holes_data) def load_void_data(infilename): ''' Load voids as formatted for VoidFinder Parameters ========== infilename : string path to desired data file Returns ======= holes_xyz : numpy.ndarray shape (N,3) the xyz centers of the holes holes_radii : numpy.ndarray shape (N,) the radii of the holes hole_flags : numpy.ndarray shape (N,) the VoidFinder 'flag' output representing which void group a hole belongs to ''' holes_data = load_data_to_Table(infilename) num_rows = len(holes_data) holes_xyz = numpy.empty((num_rows, 3), dtype=numpy.float64) hole_radii = numpy.empty(num_rows, dtype=numpy.float64) hole_flags = numpy.empty(num_rows, dtype=numpy.int32) holes_xyz[:,0] = holes_data['x'] holes_xyz[:,1] = holes_data['y'] holes_xyz[:,2] = holes_data['z'] hole_radii[:] = holes_data["radius"] hole_flags[:] = holes_data["flag"] return holes_xyz, hole_radii, hole_flags def load_galaxy_data(infilename): """ Load a table of galaxies for use in VoidRender Parameters ========== infilename : string path to desired data file intended to be an astropy table output from VoidFinder with columns 'ra', 'dec', 'redshift', and possibly 'Rgal' Returns ======= galaxy_data_xyz : numpy.ndarray shape (N,3) xyz coordinates of galaxies from the data table """ galaxy_data = load_data_to_Table(infilename) if all([name in galaxy_data.colnames for name in ['x', 'y', 'z']]): num_rows = len(galaxy_data) galaxy_data_xyz = numpy.empty((num_rows, 3), dtype=numpy.float64) galaxy_data_xyz[:,0] = galaxy_data['x'] galaxy_data_xyz[:,1] = galaxy_data['y'] galaxy_data_xyz[:,2] = galaxy_data['z'] else: ############################################################################ # Identify the redshift column label #--------------------------------------------------------------------------- if 'redshift' in galaxy_data.colnames: z_column = 'redshift' elif 'REDSHIFT' in galaxy_data.colnames: z_column = 'REDSHIFT' elif 'z' in galaxy_data.colnames: z_column = 'z' else: print('Redshift column not known. Please rename column to "redshift".') ############################################################################ ############################################################################ # Calculate the distance to the galaxies #--------------------------------------------------------------------------- if distance_metric == 'comoving' and 'Rgal' not in galaxy_data.columns: r_gal = z_to_comoving_dist(galaxy_data[z_column].data.astype(numpy.float32), Omega_M, h) elif distance_metric == 'comoving': r_gal = galaxy_data['Rgal'] else: r_gal = c*galaxy_data[z_column]/(100*h) ############################################################################ ############################################################################ # Convert sky coordinates to Cartesian coordinates #--------------------------------------------------------------------------- xin = r_gal*numpy.cos(galaxy_data['ra']*DtoR)*numpy.cos(galaxy_data['dec']*DtoR) yin = r_gal*numpy.sin(galaxy_data['ra']*DtoR)*numpy.cos(galaxy_data['dec']*DtoR) zin = r_gal*numpy.sin(galaxy_data['dec']*DtoR) ############################################################################ ############################################################################ # Create output array #--------------------------------------------------------------------------- #xyz_galaxy_table = Table([xin, yin, zin], names=('x','y','z')) num_rows = len(galaxy_data) galaxy_data_xyz = numpy.empty((num_rows, 3), dtype=numpy.float64) galaxy_data_xyz[:,0] = xin galaxy_data_xyz[:,1] = yin galaxy_data_xyz[:,2] = zin ############################################################################ return galaxy_data_xyz
<filename>python/vast/voidfinder/viz/load_results.py import numpy import h5py from astropy.table import Table import matplotlib import matplotlib.pyplot as plt #from vast.voidfinder.absmag_comovingdist_functions import Distance from vast.voidfinder.distance import z_to_comoving_dist from vast.voidfinder.preprocessing import load_data_to_Table # Constants c = 3e5 DtoR = numpy.pi/180. RtoD = 180./numpy.pi distance_metric = 'comoving' #distance_metric = 'redshift' Omega_M = 0.3 h = 1.0 if __name__ == "__main__": infilename1 = "vollim_dr7_cbp_102709_holes.txt" infilename2 = "vollim_dr7_cbp_102709_maximal.txt" infilename3 = "vollim_dr7_cbp_102709.dat" ############################################################################ # load hole locations # keys are 'x' 'y' 'z' 'radius' 'flag' #--------------------------------------------------------------------------- holes_data = Table.read(infilename1, format='ascii.commented_header') ############################################################################ ############################################################################ # Load galaxy data and convert coordinates to xyz #--------------------------------------------------------------------------- galaxy_data = Table.read(infilename3, format='ascii.commented_header') if distance_metric == 'comoving': r_gal = galaxy_data['Rgal'] else: if 'redshift' in galaxy_data.colnames: z_column = 'redshift' elif 'REDSHIFT' in galaxy_data.colnames: z_column = 'REDSHIFT' elif 'z' in galaxy_data.colnames: z_column = 'z' else: print('Redshift column not known. Please rename column to "redshift".') r_gal = c*galaxy_data[z_column]/(100*h) xin = r_gal*numpy.cos(galaxy_data['ra']*DtoR)*numpy.cos(galaxy_data['dec']*DtoR) yin = r_gal*numpy.sin(galaxy_data['ra']*DtoR)*numpy.cos(galaxy_data['dec']*DtoR) zin = r_gal*numpy.sin(galaxy_data['dec']*DtoR) xyz_galaxy_data = Table([xin, yin, zin], names=('x','y','z')) ############################################################################ print(xyz_galaxy_data) print(holes_data) def load_void_data(infilename): ''' Load voids as formatted for VoidFinder Parameters ========== infilename : string path to desired data file Returns ======= holes_xyz : numpy.ndarray shape (N,3) the xyz centers of the holes holes_radii : numpy.ndarray shape (N,) the radii of the holes hole_flags : numpy.ndarray shape (N,) the VoidFinder 'flag' output representing which void group a hole belongs to ''' holes_data = load_data_to_Table(infilename) num_rows = len(holes_data) holes_xyz = numpy.empty((num_rows, 3), dtype=numpy.float64) hole_radii = numpy.empty(num_rows, dtype=numpy.float64) hole_flags = numpy.empty(num_rows, dtype=numpy.int32) holes_xyz[:,0] = holes_data['x'] holes_xyz[:,1] = holes_data['y'] holes_xyz[:,2] = holes_data['z'] hole_radii[:] = holes_data["radius"] hole_flags[:] = holes_data["flag"] return holes_xyz, hole_radii, hole_flags def load_galaxy_data(infilename): """ Load a table of galaxies for use in VoidRender Parameters ========== infilename : string path to desired data file intended to be an astropy table output from VoidFinder with columns 'ra', 'dec', 'redshift', and possibly 'Rgal' Returns ======= galaxy_data_xyz : numpy.ndarray shape (N,3) xyz coordinates of galaxies from the data table """ galaxy_data = load_data_to_Table(infilename) if all([name in galaxy_data.colnames for name in ['x', 'y', 'z']]): num_rows = len(galaxy_data) galaxy_data_xyz = numpy.empty((num_rows, 3), dtype=numpy.float64) galaxy_data_xyz[:,0] = galaxy_data['x'] galaxy_data_xyz[:,1] = galaxy_data['y'] galaxy_data_xyz[:,2] = galaxy_data['z'] else: ############################################################################ # Identify the redshift column label #--------------------------------------------------------------------------- if 'redshift' in galaxy_data.colnames: z_column = 'redshift' elif 'REDSHIFT' in galaxy_data.colnames: z_column = 'REDSHIFT' elif 'z' in galaxy_data.colnames: z_column = 'z' else: print('Redshift column not known. Please rename column to "redshift".') ############################################################################ ############################################################################ # Calculate the distance to the galaxies #--------------------------------------------------------------------------- if distance_metric == 'comoving' and 'Rgal' not in galaxy_data.columns: r_gal = z_to_comoving_dist(galaxy_data[z_column].data.astype(numpy.float32), Omega_M, h) elif distance_metric == 'comoving': r_gal = galaxy_data['Rgal'] else: r_gal = c*galaxy_data[z_column]/(100*h) ############################################################################ ############################################################################ # Convert sky coordinates to Cartesian coordinates #--------------------------------------------------------------------------- xin = r_gal*numpy.cos(galaxy_data['ra']*DtoR)*numpy.cos(galaxy_data['dec']*DtoR) yin = r_gal*numpy.sin(galaxy_data['ra']*DtoR)*numpy.cos(galaxy_data['dec']*DtoR) zin = r_gal*numpy.sin(galaxy_data['dec']*DtoR) ############################################################################ ############################################################################ # Create output array #--------------------------------------------------------------------------- #xyz_galaxy_table = Table([xin, yin, zin], names=('x','y','z')) num_rows = len(galaxy_data) galaxy_data_xyz = numpy.empty((num_rows, 3), dtype=numpy.float64) galaxy_data_xyz[:,0] = xin galaxy_data_xyz[:,1] = yin galaxy_data_xyz[:,2] = zin ############################################################################ return galaxy_data_xyz
de
0.331728
#from vast.voidfinder.absmag_comovingdist_functions import Distance # Constants #distance_metric = 'redshift' ############################################################################ # load hole locations # keys are 'x' 'y' 'z' 'radius' 'flag' #--------------------------------------------------------------------------- ############################################################################ ############################################################################ # Load galaxy data and convert coordinates to xyz #--------------------------------------------------------------------------- ############################################################################ Load voids as formatted for VoidFinder Parameters ========== infilename : string path to desired data file Returns ======= holes_xyz : numpy.ndarray shape (N,3) the xyz centers of the holes holes_radii : numpy.ndarray shape (N,) the radii of the holes hole_flags : numpy.ndarray shape (N,) the VoidFinder 'flag' output representing which void group a hole belongs to Load a table of galaxies for use in VoidRender Parameters ========== infilename : string path to desired data file intended to be an astropy table output from VoidFinder with columns 'ra', 'dec', 'redshift', and possibly 'Rgal' Returns ======= galaxy_data_xyz : numpy.ndarray shape (N,3) xyz coordinates of galaxies from the data table ############################################################################ # Identify the redshift column label #--------------------------------------------------------------------------- ############################################################################ ############################################################################ # Calculate the distance to the galaxies #--------------------------------------------------------------------------- ############################################################################ ############################################################################ # Convert sky coordinates to Cartesian coordinates #--------------------------------------------------------------------------- ############################################################################ ############################################################################ # Create output array #--------------------------------------------------------------------------- #xyz_galaxy_table = Table([xin, yin, zin], names=('x','y','z')) ############################################################################
2.224967
2
Backend/Pozyx/pypozyx/structures/generic.py
osoc21/Safe-Crossing
2
6623241
<filename>Backend/Pozyx/pypozyx/structures/generic.py #!/usr/bin/env python # TODO move this in the RST files. """ pypozyx.structures.generic - introduces generic data structures derived from ByteStructure Generic Structures As the name implies, contains generic structures whose specific use is up to the user. You should use SingleRegister where applicable when reading/writing a single register, and use Data for larger data structures. Structures contained: Data THE generic data structure, a powerful way of constructing arbitrarily formed packed data structures XYZ A generic XYZ data structure that is used in much 3D sensor data SingleRegister Data resembling a single register. Can choose size and whether signed. UniformData A variation on Data with all data being a uniform format. Questionably useful. The use of Data: Data creates a packed data structure with size and format that is entirely the user's choice. The format follows the one used in struct, where b is a byte, h is a 2-byte int, and i is a default-sized integer, and f is a float. In capitals, these are signed. So, to create a custom construct consisting of 4 uint16 and a single int, the following code can be used. >>> d = Data([0] * 5, 'HHHHi') or >>> data_format = 'HHHHi' >>> d = Data([0] * len(data_format), data_format) """ from pypozyx.structures.byte_structure import ByteStructure def is_reg_readable(reg): """Returns whether a Pozyx register is readable.""" if (0x00 <= reg < 0x07) or (0x10 <= reg < 0x12) or (0x14 <= reg < 0x22) or (0x22 <= reg <= 0x24) or ( 0x26 <= reg < 0x2B) or (0x30 <= reg < 0x48) or (0x4E <= reg < 0x89): return True return False def is_reg_writable(reg): """Returns whether a Pozyx register is writeable.""" if (0x10 <= reg < 0x12) or (0x14 <= reg < 0x22) or (0x22 <= reg <= 0x24) or (0x26 <= reg < 0x2B) or ( 0x30 <= reg < 0x3C) or (0x85 <= reg < 0x89): return True return False def is_functioncall(reg): """Returns whether a Pozyx register is a Pozyx function.""" if (0xB0 <= reg <= 0xBC) or (0xC0 <= reg < 0xC9): return True return False def dataCheck(data): """Returns whether an object is part of the ByteStructure-derived classes or not. The function checks the base classes of the passed data object. This function enables many library functions to be passed along its data as either an int/list or the properly intended data structure. For example, the following code will result in the same behaviour:: >>> p.setCoordinates([0, 0, 0]) >>> # or >>> coords = Coordinates() >>> p.setCoordinates(coords) AND >>> p.setNetworkId(0x6000) >>> # or >>> n = NetworkID(0x6000) >>> p.setNetworkId(n) Note that this only works for functions where you change one of the Pozyx's settings. When reading data from the Pozyx, you have to pass along the correct data structure. Using dataCheck: You might want to use this in your own function, as it makes it more robust to whether an int or list gets sent as a parameter to your function, or a ByteStructure-like object. If so, you can perform:: >>> if not dataCheck(sample): # assume a is an int but you want it to be a SingleRegister >>> sample = SingleRegister(sample) """ if not(Data in type(data).__bases__ or ByteStructure in type(data).__bases__ or Data is type(data) or XYZ in type(data).__bases__ or SingleRegister in type(data).__bases__): return False return True class XYZ(ByteStructure): """ Generic XYZ data structure consisting of 3 integers x, y, and z. Not recommended to use in practice, as relevant sensor data classes are derived from this. """ physical_convert = 1 byte_size = 12 data_format = 'iii' def __init__(self, x=0, y=0, z=0): """Initializes the XYZ or XYZ-derived object.""" self.data = [x, y, z] def load(self, data, convert=True): self.data = data def __str__(self): return 'X: {}, Y: {}, Z: {}'.format(self.x, self.y, self.z) @property def x(self): return self.data[0] / self.physical_convert @x.setter def x(self, value): self.data[0] = value * self.physical_convert @property def y(self): return self.data[1] / self.physical_convert @y.setter def y(self, value): self.data[1] = value * self.physical_convert @property def z(self): return self.data[2] / self.physical_convert @z.setter def z(self, value): self.data[2] = value * self.physical_convert # TODO maybe use asdict()? Move to dataclasses? def to_dict(self): return { "x": self.x, "y": self.y, "z": self.z, } class Data(ByteStructure): """Data allows the user to define arbitrary data structures to use with Pozyx. The Leatherman of ByteStructure-derived classes, Data allows you to create your own library-compatible packed data structures. Also for empty data, this is used. The use of Data: Data creates a packed data structure with size and format that is entirely the user's choice. The format follows the one used in struct, where b is a byte, h is a 2-byte int, and i is a default-sized integer, and f is a float. In capitals, these are unsigned. So, to create a custom construct consisting of 4 uint16 and a single int, the following code can be used. >>> d = Data([0] * 5, 'HHHHi') or >>> data_format = 'HHHHi' >>> d = Data([0] * len(data_format), data_format) Args: data (optional): Data contained in the data structure. When no data_format is passed, these are assumed UInt8 values. data_format (optional): Custom data format for the data passed. """ def __init__(self, data=None, data_format=None): if data is None: data = [] self.data = data if data_format is None: data_format = 'B' * len(data) self.data_format = data_format self.set_packed_size() self.byte_data = '00' * self.byte_size def load(self, data, convert=True): self.data = data class SingleRegister(Data): """ SingleRegister is container for the data from a single Pozyx register. By default, this represents a UInt8 register. Used for both reading and writing. The size and whether the data is a 'signed' integer are both changeable by the user using the size and signed keyword arguments. Args: value (optional): Value of the register. size (optional): Size of the register. 1, 2, or 4. Default 1. signed (optional): Whether the data is signed. unsigned by default. print_hex (optional): How to print the register output. Hex by default. Special options are 'hex' and 'bin' other things, such as 'dec', will return decimal output. """ byte_size = 1 data_format = 'B' def __init__(self, value=0, size=1, signed=False, print_style='hex'): self.print_style = print_style if size == 1: data_format = 'b' elif size == 2: data_format = 'h' elif size == 4: data_format = 'i' else: raise ValueError("Size should be 1, 2, or 4") if not signed: data_format = data_format.capitalize() Data.__init__(self, [value], data_format) def load(self, data, convert=True): self.data = data @property def value(self): return self.data[0] @value.setter def value(self, new_value): self.data[0] = new_value def __str__(self): if self.print_style is 'hex': return hex(self.value).capitalize() elif self.print_style is 'bin': return bin(self.value) else: return str(self.value) def __eq__(self, other): if type(other) == SingleRegister: return self.value == other.value elif type(other) == int: return self.value == other else: raise ValueError("Can't compare SingleRegister value with non-integer values or registers") def __le__(self, other): if type(other) == SingleRegister: return self.value <= other.value elif type(other) == int: return self.value <= other else: raise ValueError("Can't compare SingleRegister value with non-integer values or registers") def __lt__(self, other): if type(other) == SingleRegister: return self.value < other.value elif type(other) == int: return self.value < other else: raise ValueError("Can't compare SingleRegister value with non-integer values or registers") def __gt__(self, other): return not self.__le__(other) def __ge__(self, other): return not self.__lt__(other) class SingleSensorValue(ByteStructure): """ Generic Single Sensor Value data structure. Not recommended to use in practice, as relevant sensor data classes are derived from this. """ physical_convert = 1 byte_size = 4 data_format = 'i' def __init__(self, value=0): """Initializes the XYZ or XYZ-derived object.""" self.data = [0] self.load([value]) @property def value(self): return self.data[0] @value.setter def value(self, new_value): self.data[0] = new_value def load(self, data=None, convert=True): self.data = [0] if data is None else data if convert: self.data[0] = float(self.data[0]) / self.physical_convert def __str__(self): return 'Value: {}'.format(self.value)
<filename>Backend/Pozyx/pypozyx/structures/generic.py #!/usr/bin/env python # TODO move this in the RST files. """ pypozyx.structures.generic - introduces generic data structures derived from ByteStructure Generic Structures As the name implies, contains generic structures whose specific use is up to the user. You should use SingleRegister where applicable when reading/writing a single register, and use Data for larger data structures. Structures contained: Data THE generic data structure, a powerful way of constructing arbitrarily formed packed data structures XYZ A generic XYZ data structure that is used in much 3D sensor data SingleRegister Data resembling a single register. Can choose size and whether signed. UniformData A variation on Data with all data being a uniform format. Questionably useful. The use of Data: Data creates a packed data structure with size and format that is entirely the user's choice. The format follows the one used in struct, where b is a byte, h is a 2-byte int, and i is a default-sized integer, and f is a float. In capitals, these are signed. So, to create a custom construct consisting of 4 uint16 and a single int, the following code can be used. >>> d = Data([0] * 5, 'HHHHi') or >>> data_format = 'HHHHi' >>> d = Data([0] * len(data_format), data_format) """ from pypozyx.structures.byte_structure import ByteStructure def is_reg_readable(reg): """Returns whether a Pozyx register is readable.""" if (0x00 <= reg < 0x07) or (0x10 <= reg < 0x12) or (0x14 <= reg < 0x22) or (0x22 <= reg <= 0x24) or ( 0x26 <= reg < 0x2B) or (0x30 <= reg < 0x48) or (0x4E <= reg < 0x89): return True return False def is_reg_writable(reg): """Returns whether a Pozyx register is writeable.""" if (0x10 <= reg < 0x12) or (0x14 <= reg < 0x22) or (0x22 <= reg <= 0x24) or (0x26 <= reg < 0x2B) or ( 0x30 <= reg < 0x3C) or (0x85 <= reg < 0x89): return True return False def is_functioncall(reg): """Returns whether a Pozyx register is a Pozyx function.""" if (0xB0 <= reg <= 0xBC) or (0xC0 <= reg < 0xC9): return True return False def dataCheck(data): """Returns whether an object is part of the ByteStructure-derived classes or not. The function checks the base classes of the passed data object. This function enables many library functions to be passed along its data as either an int/list or the properly intended data structure. For example, the following code will result in the same behaviour:: >>> p.setCoordinates([0, 0, 0]) >>> # or >>> coords = Coordinates() >>> p.setCoordinates(coords) AND >>> p.setNetworkId(0x6000) >>> # or >>> n = NetworkID(0x6000) >>> p.setNetworkId(n) Note that this only works for functions where you change one of the Pozyx's settings. When reading data from the Pozyx, you have to pass along the correct data structure. Using dataCheck: You might want to use this in your own function, as it makes it more robust to whether an int or list gets sent as a parameter to your function, or a ByteStructure-like object. If so, you can perform:: >>> if not dataCheck(sample): # assume a is an int but you want it to be a SingleRegister >>> sample = SingleRegister(sample) """ if not(Data in type(data).__bases__ or ByteStructure in type(data).__bases__ or Data is type(data) or XYZ in type(data).__bases__ or SingleRegister in type(data).__bases__): return False return True class XYZ(ByteStructure): """ Generic XYZ data structure consisting of 3 integers x, y, and z. Not recommended to use in practice, as relevant sensor data classes are derived from this. """ physical_convert = 1 byte_size = 12 data_format = 'iii' def __init__(self, x=0, y=0, z=0): """Initializes the XYZ or XYZ-derived object.""" self.data = [x, y, z] def load(self, data, convert=True): self.data = data def __str__(self): return 'X: {}, Y: {}, Z: {}'.format(self.x, self.y, self.z) @property def x(self): return self.data[0] / self.physical_convert @x.setter def x(self, value): self.data[0] = value * self.physical_convert @property def y(self): return self.data[1] / self.physical_convert @y.setter def y(self, value): self.data[1] = value * self.physical_convert @property def z(self): return self.data[2] / self.physical_convert @z.setter def z(self, value): self.data[2] = value * self.physical_convert # TODO maybe use asdict()? Move to dataclasses? def to_dict(self): return { "x": self.x, "y": self.y, "z": self.z, } class Data(ByteStructure): """Data allows the user to define arbitrary data structures to use with Pozyx. The Leatherman of ByteStructure-derived classes, Data allows you to create your own library-compatible packed data structures. Also for empty data, this is used. The use of Data: Data creates a packed data structure with size and format that is entirely the user's choice. The format follows the one used in struct, where b is a byte, h is a 2-byte int, and i is a default-sized integer, and f is a float. In capitals, these are unsigned. So, to create a custom construct consisting of 4 uint16 and a single int, the following code can be used. >>> d = Data([0] * 5, 'HHHHi') or >>> data_format = 'HHHHi' >>> d = Data([0] * len(data_format), data_format) Args: data (optional): Data contained in the data structure. When no data_format is passed, these are assumed UInt8 values. data_format (optional): Custom data format for the data passed. """ def __init__(self, data=None, data_format=None): if data is None: data = [] self.data = data if data_format is None: data_format = 'B' * len(data) self.data_format = data_format self.set_packed_size() self.byte_data = '00' * self.byte_size def load(self, data, convert=True): self.data = data class SingleRegister(Data): """ SingleRegister is container for the data from a single Pozyx register. By default, this represents a UInt8 register. Used for both reading and writing. The size and whether the data is a 'signed' integer are both changeable by the user using the size and signed keyword arguments. Args: value (optional): Value of the register. size (optional): Size of the register. 1, 2, or 4. Default 1. signed (optional): Whether the data is signed. unsigned by default. print_hex (optional): How to print the register output. Hex by default. Special options are 'hex' and 'bin' other things, such as 'dec', will return decimal output. """ byte_size = 1 data_format = 'B' def __init__(self, value=0, size=1, signed=False, print_style='hex'): self.print_style = print_style if size == 1: data_format = 'b' elif size == 2: data_format = 'h' elif size == 4: data_format = 'i' else: raise ValueError("Size should be 1, 2, or 4") if not signed: data_format = data_format.capitalize() Data.__init__(self, [value], data_format) def load(self, data, convert=True): self.data = data @property def value(self): return self.data[0] @value.setter def value(self, new_value): self.data[0] = new_value def __str__(self): if self.print_style is 'hex': return hex(self.value).capitalize() elif self.print_style is 'bin': return bin(self.value) else: return str(self.value) def __eq__(self, other): if type(other) == SingleRegister: return self.value == other.value elif type(other) == int: return self.value == other else: raise ValueError("Can't compare SingleRegister value with non-integer values or registers") def __le__(self, other): if type(other) == SingleRegister: return self.value <= other.value elif type(other) == int: return self.value <= other else: raise ValueError("Can't compare SingleRegister value with non-integer values or registers") def __lt__(self, other): if type(other) == SingleRegister: return self.value < other.value elif type(other) == int: return self.value < other else: raise ValueError("Can't compare SingleRegister value with non-integer values or registers") def __gt__(self, other): return not self.__le__(other) def __ge__(self, other): return not self.__lt__(other) class SingleSensorValue(ByteStructure): """ Generic Single Sensor Value data structure. Not recommended to use in practice, as relevant sensor data classes are derived from this. """ physical_convert = 1 byte_size = 4 data_format = 'i' def __init__(self, value=0): """Initializes the XYZ or XYZ-derived object.""" self.data = [0] self.load([value]) @property def value(self): return self.data[0] @value.setter def value(self, new_value): self.data[0] = new_value def load(self, data=None, convert=True): self.data = [0] if data is None else data if convert: self.data[0] = float(self.data[0]) / self.physical_convert def __str__(self): return 'Value: {}'.format(self.value)
en
0.81027
#!/usr/bin/env python # TODO move this in the RST files. pypozyx.structures.generic - introduces generic data structures derived from ByteStructure Generic Structures As the name implies, contains generic structures whose specific use is up to the user. You should use SingleRegister where applicable when reading/writing a single register, and use Data for larger data structures. Structures contained: Data THE generic data structure, a powerful way of constructing arbitrarily formed packed data structures XYZ A generic XYZ data structure that is used in much 3D sensor data SingleRegister Data resembling a single register. Can choose size and whether signed. UniformData A variation on Data with all data being a uniform format. Questionably useful. The use of Data: Data creates a packed data structure with size and format that is entirely the user's choice. The format follows the one used in struct, where b is a byte, h is a 2-byte int, and i is a default-sized integer, and f is a float. In capitals, these are signed. So, to create a custom construct consisting of 4 uint16 and a single int, the following code can be used. >>> d = Data([0] * 5, 'HHHHi') or >>> data_format = 'HHHHi' >>> d = Data([0] * len(data_format), data_format) Returns whether a Pozyx register is readable. Returns whether a Pozyx register is writeable. Returns whether a Pozyx register is a Pozyx function. Returns whether an object is part of the ByteStructure-derived classes or not. The function checks the base classes of the passed data object. This function enables many library functions to be passed along its data as either an int/list or the properly intended data structure. For example, the following code will result in the same behaviour:: >>> p.setCoordinates([0, 0, 0]) >>> # or >>> coords = Coordinates() >>> p.setCoordinates(coords) AND >>> p.setNetworkId(0x6000) >>> # or >>> n = NetworkID(0x6000) >>> p.setNetworkId(n) Note that this only works for functions where you change one of the Pozyx's settings. When reading data from the Pozyx, you have to pass along the correct data structure. Using dataCheck: You might want to use this in your own function, as it makes it more robust to whether an int or list gets sent as a parameter to your function, or a ByteStructure-like object. If so, you can perform:: >>> if not dataCheck(sample): # assume a is an int but you want it to be a SingleRegister >>> sample = SingleRegister(sample) Generic XYZ data structure consisting of 3 integers x, y, and z. Not recommended to use in practice, as relevant sensor data classes are derived from this. Initializes the XYZ or XYZ-derived object. # TODO maybe use asdict()? Move to dataclasses? Data allows the user to define arbitrary data structures to use with Pozyx. The Leatherman of ByteStructure-derived classes, Data allows you to create your own library-compatible packed data structures. Also for empty data, this is used. The use of Data: Data creates a packed data structure with size and format that is entirely the user's choice. The format follows the one used in struct, where b is a byte, h is a 2-byte int, and i is a default-sized integer, and f is a float. In capitals, these are unsigned. So, to create a custom construct consisting of 4 uint16 and a single int, the following code can be used. >>> d = Data([0] * 5, 'HHHHi') or >>> data_format = 'HHHHi' >>> d = Data([0] * len(data_format), data_format) Args: data (optional): Data contained in the data structure. When no data_format is passed, these are assumed UInt8 values. data_format (optional): Custom data format for the data passed. SingleRegister is container for the data from a single Pozyx register. By default, this represents a UInt8 register. Used for both reading and writing. The size and whether the data is a 'signed' integer are both changeable by the user using the size and signed keyword arguments. Args: value (optional): Value of the register. size (optional): Size of the register. 1, 2, or 4. Default 1. signed (optional): Whether the data is signed. unsigned by default. print_hex (optional): How to print the register output. Hex by default. Special options are 'hex' and 'bin' other things, such as 'dec', will return decimal output. Generic Single Sensor Value data structure. Not recommended to use in practice, as relevant sensor data classes are derived from this. Initializes the XYZ or XYZ-derived object.
2.331866
2
Protheus_WebApp/Modules/SIGAGTP/GTPA042TestCase.py
98llm/tir-script-samples
17
6623242
from tir import Webapp import unittest class GTPA042(unittest.TestCase): @classmethod def setUpClass(inst): inst.oHelper = Webapp() inst.oHelper.Setup('SIGAGTP', '14/08/2020', 'T1', 'D MG 01 ') inst.oHelper.Program('GTPA042') # Efetua o cadastro de evento para envio de e-mail print('CT001 - inclui evento para Envio de e-mails') def test_GTPA042_CT001(self): self.oHelper.SetButton('Sim') self.oHelper.SetButton('Incluir') self.oHelper.SetValue('GZ8_DESEVE', 'AUTOMACAO ENVIO DE EMAIL') self.oHelper.SetValue('GZ8_TEXTO', 'AUTOMACAO ENVIO DE EMAIL TEXTO E-MAIL') self.oHelper.SetValue('GZ8_STATUS', '1') self.oHelper.SetValue('GZ8_TITULO', 'AUTOMACAO ENVIO DE EMAIL TITULO') self.oHelper.SetValue('GZ8_RECOR', '2') self.oHelper.SetValue('GZ6_CODIGO', '000002') self.oHelper.SetButton('Outras Ações','Automação') self.oHelper.SetValue('GY5_ENTIDA', 'G57') self.oHelper.SetButton('Confirmar') self.oHelper.SetButton('Fechar') self.oHelper.SetValue('GY6_CAMPO1', 'G57_AGENCI') self.oHelper.SetValue('GY6_CONTEU', '000050') self.oHelper.SetButton('Confirmar') self.oHelper.SetButton('Fechar') self.oHelper.SetButton('Confirmar') self.oHelper.SetButton('Fechar') self.oHelper.SetButton('Visualizar') self.oHelper.SetButton('Fechar') self.oHelper.SetButton('Outras Ações','Excluir') self.oHelper.SetButton('Confirmar') self.oHelper.SetButton('Fechar') self.oHelper.AssertTrue() @classmethod def tearDownClass(inst): inst.oHelper.TearDown() if __name__ == '__main__': unittest.main()
from tir import Webapp import unittest class GTPA042(unittest.TestCase): @classmethod def setUpClass(inst): inst.oHelper = Webapp() inst.oHelper.Setup('SIGAGTP', '14/08/2020', 'T1', 'D MG 01 ') inst.oHelper.Program('GTPA042') # Efetua o cadastro de evento para envio de e-mail print('CT001 - inclui evento para Envio de e-mails') def test_GTPA042_CT001(self): self.oHelper.SetButton('Sim') self.oHelper.SetButton('Incluir') self.oHelper.SetValue('GZ8_DESEVE', 'AUTOMACAO ENVIO DE EMAIL') self.oHelper.SetValue('GZ8_TEXTO', 'AUTOMACAO ENVIO DE EMAIL TEXTO E-MAIL') self.oHelper.SetValue('GZ8_STATUS', '1') self.oHelper.SetValue('GZ8_TITULO', 'AUTOMACAO ENVIO DE EMAIL TITULO') self.oHelper.SetValue('GZ8_RECOR', '2') self.oHelper.SetValue('GZ6_CODIGO', '000002') self.oHelper.SetButton('Outras Ações','Automação') self.oHelper.SetValue('GY5_ENTIDA', 'G57') self.oHelper.SetButton('Confirmar') self.oHelper.SetButton('Fechar') self.oHelper.SetValue('GY6_CAMPO1', 'G57_AGENCI') self.oHelper.SetValue('GY6_CONTEU', '000050') self.oHelper.SetButton('Confirmar') self.oHelper.SetButton('Fechar') self.oHelper.SetButton('Confirmar') self.oHelper.SetButton('Fechar') self.oHelper.SetButton('Visualizar') self.oHelper.SetButton('Fechar') self.oHelper.SetButton('Outras Ações','Excluir') self.oHelper.SetButton('Confirmar') self.oHelper.SetButton('Fechar') self.oHelper.AssertTrue() @classmethod def tearDownClass(inst): inst.oHelper.TearDown() if __name__ == '__main__': unittest.main()
es
0.553952
# Efetua o cadastro de evento para envio de e-mail
2.524049
3
src/support/__init__.py
TauferLab/UrbanTrafficFramework_20
0
6623243
from . import roadnet, simsio, utm, mappings, linkvolio, heatmap, emissions
from . import roadnet, simsio, utm, mappings, linkvolio, heatmap, emissions
none
1
0.925337
1
server/tests/base.py
ZoiksScoob/SimpleEvents
1
6623244
import json from flask_testing import TestCase from simple_events.app import app from simple_events.models import db class BaseTestCase(TestCase): """ Base Tests """ def create_app(self): app.config.from_object('simple_events.config.TestingConfig') return app def setUp(self): db.create_all() db.session.commit() def tearDown(self): db.session.remove() db.drop_all() def register_user(self, username, password): return self.client.post( 'auth/register', data=json.dumps(dict( username=username, password=password )), content_type='application/json', ) def login_user(self, username, password): return self.client.post( 'auth/login', data=json.dumps(dict( username=username, password=password )), content_type='application/json', )
import json from flask_testing import TestCase from simple_events.app import app from simple_events.models import db class BaseTestCase(TestCase): """ Base Tests """ def create_app(self): app.config.from_object('simple_events.config.TestingConfig') return app def setUp(self): db.create_all() db.session.commit() def tearDown(self): db.session.remove() db.drop_all() def register_user(self, username, password): return self.client.post( 'auth/register', data=json.dumps(dict( username=username, password=password )), content_type='application/json', ) def login_user(self, username, password): return self.client.post( 'auth/login', data=json.dumps(dict( username=username, password=password )), content_type='application/json', )
en
0.806644
Base Tests
2.429068
2
fjord/settings/base.py
joshua-s/fjord
0
6623245
# This is your project's main settings file that can be committed to # your repo. If you need to override a setting locally, use # settings_local.py from funfactory.settings_base import * # Name of the top-level module where you put all your apps. If you # did not install Playdoh with the funfactory installer script you may # need to edit this value. See the docs about installing from a clone. PROJECT_MODULE = 'fjord' # Defines the views served for root URLs. ROOT_URLCONF = '%s.urls' % PROJECT_MODULE # This is the list of languages that are active for non-DEV # environments. Add languages here to allow users to see the site in # that locale and additionally submit feedback in that locale. PROD_LANGUAGES = [ 'ach', 'af', 'ak', 'am-et', 'an', 'ar', 'as', 'ast', 'az', 'be', 'bg', 'bn-BD', 'bn-IN', 'br', 'bs', 'ca', 'cs', 'csb', 'cy', 'da', 'dbg', 'de', 'de-AT', 'de-CH', 'de-DE', 'dsb', 'el', 'en-AU', 'en-CA', 'en-GB', 'en-NZ', 'en-US', 'en-ZA', 'eo', 'es', 'es-AR', 'es-CL', 'es-ES', 'es-MX', 'et', 'eu', 'fa', 'ff', 'fi', 'fj-FJ', 'fr', 'fur-IT', 'fy', 'fy-NL', 'ga', 'ga-IE', 'gd', 'gl', 'gu-IN', 'he', 'hi', 'hi-IN', 'hr', 'hsb', 'hu', 'hy-AM', 'id', 'is', 'it', 'ja', 'ka', 'kk', 'km', 'kn', 'ko', 'ku', 'la', 'lg', 'lij', 'lt', 'lv', 'mai', 'mg', 'mi', 'mk', 'ml', 'mn', 'mr', 'ms', 'my', 'nb-NO', 'ne-NP', 'nl', 'nn-NO', 'nr', 'nso', 'oc', 'or', 'pa-IN', 'pl', 'pt', 'pt-BR', 'pt-PT', 'rm', 'ro', 'ru', 'rw', 'sa', 'sah', 'si', 'sk', 'sl', 'son', 'sq', 'sr', 'sr-Latn', 'ss', 'st', 'sv-SE', 'sw', 'ta', 'ta-IN', 'ta-LK', 'te', 'th', 'tn', 'tr', 'ts', 'tt-RU', 'uk', 'ur', 've', 'vi', 'wo', 'xh', 'zh-CN', 'zh-TW', 'zu' ] DEV_LANGUAGES = PROD_LANGUAGES INSTALLED_APPS = get_apps( exclude=( 'compressor', ), append=( # south has to come early, otherwise tests fail. 'south', 'django_browserid', 'adminplus', 'django.contrib.admin', 'django_extensions', 'django_nose', 'djcelery', 'eadred', 'jingo_minify', 'dennis.django_dennis', 'fjord.analytics', 'fjord.base', 'fjord.feedback', 'fjord.search', 'fjord.translations', )) MIDDLEWARE_CLASSES = get_middleware( exclude=( # We do mobile detection ourselves. 'mobility.middleware.DetectMobileMiddleware', 'mobility.middleware.XMobileMiddleware', ), append=( 'fjord.base.middleware.UserAgentMiddleware', 'fjord.base.middleware.MobileQueryStringMiddleware', 'fjord.base.middleware.MobileMiddleware', 'django_statsd.middleware.GraphiteMiddleware', 'django_statsd.middleware.GraphiteRequestTimingMiddleware', )) LOCALE_PATHS = ( os.path.join(ROOT, PROJECT_MODULE, 'locale'), ) SUPPORTED_NONLOCALES += ( 'robots.txt', 'services', 'api', ) # Because Jinja2 is the default template loader, add any non-Jinja # templated apps here: JINGO_EXCLUDE_APPS = [ 'admin', 'adminplus', 'registration', 'browserid', ] MINIFY_BUNDLES = { 'css': { 'base': ( 'css/lib/normalize.css', 'css/fjord.less', ), 'generic_feedback': ( 'css/lib/normalize.css', 'css/lib/brick-1.0.0.byob.min.css', # FIXME - This should become feedback.less and move out of # mobile/. 'css/mobile/base.less', 'css/generic_feedback.less', ), 'dashboard': ( 'css/ui-lightness/jquery-ui.css', 'css/lib/normalize.css', 'css/fjord.less', 'css/dashboard.less', ), 'stage': ( 'css/stage.less', ), 'thanks': ( 'css/lib/normalize.css', 'css/thanks.less', ), 'mobile/base': ( 'css/lib/normalize.css', 'css/mobile/base.less', ), 'mobile/fxos_feedback': ( 'css/lib/normalize.css', 'css/lib/brick-1.0.0.byob.min.css', 'css/mobile/base.less', 'css/mobile/fxos_feedback.less', ), 'mobile/thanks': ( 'css/lib/normalize.css', 'css/mobile/base.less', 'css/mobile/thanks.less', ) }, 'js': { 'base': ( 'js/lib/jquery.min.js', 'browserid/browserid.js', 'js/init.js', 'js/ga.js', ), 'singlecard': ( 'js/lib/jquery.min.js', 'js/ga.js', ), 'generic_feedback': ( 'js/lib/jquery.min.js', 'js/common_feedback.js', 'js/generic_feedback.js', 'js/ga.js', ), 'dashboard': ( 'js/lib/jquery.min.js', 'js/lib/jquery-ui.min.js', 'js/init.js', 'js/lib/excanvas.js', 'js/lib/jquery.flot.js', 'js/lib/jquery.flot.time.js', 'js/lib/jquery.flot.resize.js', 'js/dashboard.js', 'browserid/browserid.js', 'js/ga.js', ), 'thanks': ( 'js/lib/jquery.min.js', 'js/init.js', 'js/ga.js', ), 'mobile/base': ( 'js/lib/jquery.min.js', 'js/ga.js', ), 'mobile/fxos_feedback': ( 'js/lib/jquery.min.js', 'js/common_feedback.js', 'js/mobile/fxos_feedback.js', 'js/ga.js', ), } } LESS_PREPROCESS = True JINGO_MINIFY_USE_STATIC = True LESS_BIN = 'lessc' JAVA_BIN = 'java' AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'django_browserid.auth.BrowserIDBackend', ] BROWSERID_VERIFY_CLASS = 'fjord.base.browserid.FjordVerify' BROWSERID_AUDIENCES = ['http://127.0.0.1:8000', 'http://localhost:8000'] LOGIN_URL = '/' LOGIN_REDIRECT_URL = '/' LOGIN_REDIRECT_URL_FAILURE = '/login-failure' TEMPLATE_CONTEXT_PROCESSORS = get_template_context_processors( exclude=(), append=( 'django_browserid.context_processors.browserid', )) # Should robots.txt deny everything or disallow a calculated list of # URLs we don't want to be crawled? Default is false, disallow # everything. Also see # http://www.google.com/support/webmasters/bin/answer.py?answer=93710 ENGAGE_ROBOTS = False # Always generate a CSRF token for anonymous users. ANON_ALWAYS = True # CSRF error page CSRF_FAILURE_VIEW = 'fjord.base.views.csrf_failure' # Tells the extract script what files to look for L10n in and what # function handles the extraction. The Tower library expects this. DOMAIN_METHODS['messages'] = [ ('%s/**.py' % PROJECT_MODULE, 'tower.management.commands.extract.extract_tower_python'), ('%s/**/templates/**.html' % PROJECT_MODULE, 'tower.management.commands.extract.extract_tower_template'), ('templates/**.html', 'tower.management.commands.extract.extract_tower_template'), ] # # Use this if you have localizable HTML files: # DOMAIN_METHODS['lhtml'] = [ # ('**/templates/**.lhtml', # 'tower.management.commands.extract.extract_tower_template'), # ] # # Use this if you have localizable JS files: # DOMAIN_METHODS['javascript'] = [ # # Make sure that this won't pull in strings from external # # libraries you may use. # ('media/js/**.js', 'javascript'), # ] # When set to True, this will cause a message to be displayed on all # pages that this is not production. SHOW_STAGE_NOTICE = False # Explicitly set this because the one from funfactory includes # django-compressor which we don't use. # STATICFILES_FINDERS = ( # 'django.contrib.staticfiles.finders.FileSystemFinder', # 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # ) # ElasticSearch settings. # List of host urls for the ES hosts we should connect to. ES_URLS = ['http://localhost:9200'] # Dict of mapping-type-name -> index-name to use. Input pretty much # uses one index, so this should be some variation of: # {'default': 'inputindex'}. ES_INDEXES = {'default': 'inputindex'} # Prefix for the index. This allows -dev and -stage to share the same # ES cluster, but not bump into each other. ES_INDEX_PREFIX = 'input' # When True, objects that belong in the index will get automatically # indexed and deindexed when created and destroyed. ES_LIVE_INDEX = True ES_TIMEOUT = 10 # Time in seconds before celery.exceptions.SoftTimeLimitExceeded is raised. # The task can catch that and recover but should exit ASAP. CELERYD_TASK_SOFT_TIME_LIMIT = 60 * 10 # Configuration for API views. REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': ( 'fjord.base.util.MeasuredAnonRateThrottle', ), 'DEFAULT_THROTTLE_RATES': { 'anon': '100/hour', }, 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) }
# This is your project's main settings file that can be committed to # your repo. If you need to override a setting locally, use # settings_local.py from funfactory.settings_base import * # Name of the top-level module where you put all your apps. If you # did not install Playdoh with the funfactory installer script you may # need to edit this value. See the docs about installing from a clone. PROJECT_MODULE = 'fjord' # Defines the views served for root URLs. ROOT_URLCONF = '%s.urls' % PROJECT_MODULE # This is the list of languages that are active for non-DEV # environments. Add languages here to allow users to see the site in # that locale and additionally submit feedback in that locale. PROD_LANGUAGES = [ 'ach', 'af', 'ak', 'am-et', 'an', 'ar', 'as', 'ast', 'az', 'be', 'bg', 'bn-BD', 'bn-IN', 'br', 'bs', 'ca', 'cs', 'csb', 'cy', 'da', 'dbg', 'de', 'de-AT', 'de-CH', 'de-DE', 'dsb', 'el', 'en-AU', 'en-CA', 'en-GB', 'en-NZ', 'en-US', 'en-ZA', 'eo', 'es', 'es-AR', 'es-CL', 'es-ES', 'es-MX', 'et', 'eu', 'fa', 'ff', 'fi', 'fj-FJ', 'fr', 'fur-IT', 'fy', 'fy-NL', 'ga', 'ga-IE', 'gd', 'gl', 'gu-IN', 'he', 'hi', 'hi-IN', 'hr', 'hsb', 'hu', 'hy-AM', 'id', 'is', 'it', 'ja', 'ka', 'kk', 'km', 'kn', 'ko', 'ku', 'la', 'lg', 'lij', 'lt', 'lv', 'mai', 'mg', 'mi', 'mk', 'ml', 'mn', 'mr', 'ms', 'my', 'nb-NO', 'ne-NP', 'nl', 'nn-NO', 'nr', 'nso', 'oc', 'or', 'pa-IN', 'pl', 'pt', 'pt-BR', 'pt-PT', 'rm', 'ro', 'ru', 'rw', 'sa', 'sah', 'si', 'sk', 'sl', 'son', 'sq', 'sr', 'sr-Latn', 'ss', 'st', 'sv-SE', 'sw', 'ta', 'ta-IN', 'ta-LK', 'te', 'th', 'tn', 'tr', 'ts', 'tt-RU', 'uk', 'ur', 've', 'vi', 'wo', 'xh', 'zh-CN', 'zh-TW', 'zu' ] DEV_LANGUAGES = PROD_LANGUAGES INSTALLED_APPS = get_apps( exclude=( 'compressor', ), append=( # south has to come early, otherwise tests fail. 'south', 'django_browserid', 'adminplus', 'django.contrib.admin', 'django_extensions', 'django_nose', 'djcelery', 'eadred', 'jingo_minify', 'dennis.django_dennis', 'fjord.analytics', 'fjord.base', 'fjord.feedback', 'fjord.search', 'fjord.translations', )) MIDDLEWARE_CLASSES = get_middleware( exclude=( # We do mobile detection ourselves. 'mobility.middleware.DetectMobileMiddleware', 'mobility.middleware.XMobileMiddleware', ), append=( 'fjord.base.middleware.UserAgentMiddleware', 'fjord.base.middleware.MobileQueryStringMiddleware', 'fjord.base.middleware.MobileMiddleware', 'django_statsd.middleware.GraphiteMiddleware', 'django_statsd.middleware.GraphiteRequestTimingMiddleware', )) LOCALE_PATHS = ( os.path.join(ROOT, PROJECT_MODULE, 'locale'), ) SUPPORTED_NONLOCALES += ( 'robots.txt', 'services', 'api', ) # Because Jinja2 is the default template loader, add any non-Jinja # templated apps here: JINGO_EXCLUDE_APPS = [ 'admin', 'adminplus', 'registration', 'browserid', ] MINIFY_BUNDLES = { 'css': { 'base': ( 'css/lib/normalize.css', 'css/fjord.less', ), 'generic_feedback': ( 'css/lib/normalize.css', 'css/lib/brick-1.0.0.byob.min.css', # FIXME - This should become feedback.less and move out of # mobile/. 'css/mobile/base.less', 'css/generic_feedback.less', ), 'dashboard': ( 'css/ui-lightness/jquery-ui.css', 'css/lib/normalize.css', 'css/fjord.less', 'css/dashboard.less', ), 'stage': ( 'css/stage.less', ), 'thanks': ( 'css/lib/normalize.css', 'css/thanks.less', ), 'mobile/base': ( 'css/lib/normalize.css', 'css/mobile/base.less', ), 'mobile/fxos_feedback': ( 'css/lib/normalize.css', 'css/lib/brick-1.0.0.byob.min.css', 'css/mobile/base.less', 'css/mobile/fxos_feedback.less', ), 'mobile/thanks': ( 'css/lib/normalize.css', 'css/mobile/base.less', 'css/mobile/thanks.less', ) }, 'js': { 'base': ( 'js/lib/jquery.min.js', 'browserid/browserid.js', 'js/init.js', 'js/ga.js', ), 'singlecard': ( 'js/lib/jquery.min.js', 'js/ga.js', ), 'generic_feedback': ( 'js/lib/jquery.min.js', 'js/common_feedback.js', 'js/generic_feedback.js', 'js/ga.js', ), 'dashboard': ( 'js/lib/jquery.min.js', 'js/lib/jquery-ui.min.js', 'js/init.js', 'js/lib/excanvas.js', 'js/lib/jquery.flot.js', 'js/lib/jquery.flot.time.js', 'js/lib/jquery.flot.resize.js', 'js/dashboard.js', 'browserid/browserid.js', 'js/ga.js', ), 'thanks': ( 'js/lib/jquery.min.js', 'js/init.js', 'js/ga.js', ), 'mobile/base': ( 'js/lib/jquery.min.js', 'js/ga.js', ), 'mobile/fxos_feedback': ( 'js/lib/jquery.min.js', 'js/common_feedback.js', 'js/mobile/fxos_feedback.js', 'js/ga.js', ), } } LESS_PREPROCESS = True JINGO_MINIFY_USE_STATIC = True LESS_BIN = 'lessc' JAVA_BIN = 'java' AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'django_browserid.auth.BrowserIDBackend', ] BROWSERID_VERIFY_CLASS = 'fjord.base.browserid.FjordVerify' BROWSERID_AUDIENCES = ['http://127.0.0.1:8000', 'http://localhost:8000'] LOGIN_URL = '/' LOGIN_REDIRECT_URL = '/' LOGIN_REDIRECT_URL_FAILURE = '/login-failure' TEMPLATE_CONTEXT_PROCESSORS = get_template_context_processors( exclude=(), append=( 'django_browserid.context_processors.browserid', )) # Should robots.txt deny everything or disallow a calculated list of # URLs we don't want to be crawled? Default is false, disallow # everything. Also see # http://www.google.com/support/webmasters/bin/answer.py?answer=93710 ENGAGE_ROBOTS = False # Always generate a CSRF token for anonymous users. ANON_ALWAYS = True # CSRF error page CSRF_FAILURE_VIEW = 'fjord.base.views.csrf_failure' # Tells the extract script what files to look for L10n in and what # function handles the extraction. The Tower library expects this. DOMAIN_METHODS['messages'] = [ ('%s/**.py' % PROJECT_MODULE, 'tower.management.commands.extract.extract_tower_python'), ('%s/**/templates/**.html' % PROJECT_MODULE, 'tower.management.commands.extract.extract_tower_template'), ('templates/**.html', 'tower.management.commands.extract.extract_tower_template'), ] # # Use this if you have localizable HTML files: # DOMAIN_METHODS['lhtml'] = [ # ('**/templates/**.lhtml', # 'tower.management.commands.extract.extract_tower_template'), # ] # # Use this if you have localizable JS files: # DOMAIN_METHODS['javascript'] = [ # # Make sure that this won't pull in strings from external # # libraries you may use. # ('media/js/**.js', 'javascript'), # ] # When set to True, this will cause a message to be displayed on all # pages that this is not production. SHOW_STAGE_NOTICE = False # Explicitly set this because the one from funfactory includes # django-compressor which we don't use. # STATICFILES_FINDERS = ( # 'django.contrib.staticfiles.finders.FileSystemFinder', # 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # ) # ElasticSearch settings. # List of host urls for the ES hosts we should connect to. ES_URLS = ['http://localhost:9200'] # Dict of mapping-type-name -> index-name to use. Input pretty much # uses one index, so this should be some variation of: # {'default': 'inputindex'}. ES_INDEXES = {'default': 'inputindex'} # Prefix for the index. This allows -dev and -stage to share the same # ES cluster, but not bump into each other. ES_INDEX_PREFIX = 'input' # When True, objects that belong in the index will get automatically # indexed and deindexed when created and destroyed. ES_LIVE_INDEX = True ES_TIMEOUT = 10 # Time in seconds before celery.exceptions.SoftTimeLimitExceeded is raised. # The task can catch that and recover but should exit ASAP. CELERYD_TASK_SOFT_TIME_LIMIT = 60 * 10 # Configuration for API views. REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': ( 'fjord.base.util.MeasuredAnonRateThrottle', ), 'DEFAULT_THROTTLE_RATES': { 'anon': '100/hour', }, 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) }
en
0.823802
# This is your project's main settings file that can be committed to # your repo. If you need to override a setting locally, use # settings_local.py # Name of the top-level module where you put all your apps. If you # did not install Playdoh with the funfactory installer script you may # need to edit this value. See the docs about installing from a clone. # Defines the views served for root URLs. # This is the list of languages that are active for non-DEV # environments. Add languages here to allow users to see the site in # that locale and additionally submit feedback in that locale. # south has to come early, otherwise tests fail. # We do mobile detection ourselves. # Because Jinja2 is the default template loader, add any non-Jinja # templated apps here: # FIXME - This should become feedback.less and move out of # mobile/. # Should robots.txt deny everything or disallow a calculated list of # URLs we don't want to be crawled? Default is false, disallow # everything. Also see # http://www.google.com/support/webmasters/bin/answer.py?answer=93710 # Always generate a CSRF token for anonymous users. # CSRF error page # Tells the extract script what files to look for L10n in and what # function handles the extraction. The Tower library expects this. # # Use this if you have localizable HTML files: # DOMAIN_METHODS['lhtml'] = [ # ('**/templates/**.lhtml', # 'tower.management.commands.extract.extract_tower_template'), # ] # # Use this if you have localizable JS files: # DOMAIN_METHODS['javascript'] = [ # # Make sure that this won't pull in strings from external # # libraries you may use. # ('media/js/**.js', 'javascript'), # ] # When set to True, this will cause a message to be displayed on all # pages that this is not production. # Explicitly set this because the one from funfactory includes # django-compressor which we don't use. # STATICFILES_FINDERS = ( # 'django.contrib.staticfiles.finders.FileSystemFinder', # 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # ) # ElasticSearch settings. # List of host urls for the ES hosts we should connect to. # Dict of mapping-type-name -> index-name to use. Input pretty much # uses one index, so this should be some variation of: # {'default': 'inputindex'}. # Prefix for the index. This allows -dev and -stage to share the same # ES cluster, but not bump into each other. # When True, objects that belong in the index will get automatically # indexed and deindexed when created and destroyed. # Time in seconds before celery.exceptions.SoftTimeLimitExceeded is raised. # The task can catch that and recover but should exit ASAP. # Configuration for API views.
1.598789
2
tests/test_utils.py
pauleveritt/wired_injector
1
6623246
from wired_injector.utils import caller_package, caller_module def test_caller_package(): result = caller_package() assert '_pytest' == result.__name__ def test_caller_module(): result = caller_module() assert '_pytest.python' == result.__name__
from wired_injector.utils import caller_package, caller_module def test_caller_package(): result = caller_package() assert '_pytest' == result.__name__ def test_caller_module(): result = caller_module() assert '_pytest.python' == result.__name__
none
1
2.066433
2
pca_utils.py
akashpalrecha/computational-linear-algebra
1
6623247
import torch import torchvision from sklearn.decomposition import PCA import matplotlib.pyplot as plt import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D, proj3d from matplotlib.patches import FancyArrowPatch from datetime import datetime from pdb import set_trace MIN_16, MAX_16 = torch.finfo(torch.float16).min, torch.finfo(torch.float16).max MIN_32, MAX_32 = torch.finfo(torch.float32).min, torch.finfo(torch.float32).max def stats(*args): for x in args: print("Type : ", type(x)) print("Shape: ", x.shape) print("Sum : ", x.sum()) print("Mean : ", x.mean()) print("STD : ", x.std()) print() def torchCov(matrix:torch.Tensor, transposed=False, debug=False): "Transposed = True if individual samples are columns and not rows" if not isinstance(matrix, torch.Tensor): matrix = torch.tensor(matrix) if torch.cuda.is_available(): matrix = matrix.cuda() m = matrix.T if transposed else matrix if debug: set_trace() n = m.shape[0] MAX = torch.finfo(m.dtype).max mean = m.mean(axis=0, keepdim=True) m.sub_(mean) product = (m.T @ m).clamp(0, MAX) product[torch.isnan(product)] = 0 product[torch.isinf(product)] = MAX return product / (n-1) def torchPCA(matrix:torch.Tensor, k=2, transposed=False, fp16=True, debug=False): # Convert to tensor, cuda, half precision if debug: set_trace() dtype = torch.float16 if (fp16 and torch.cuda.is_available()) else torch.float32 if not isinstance(matrix, torch.Tensor): matrix = torch.tensor(matrix).type(dtype) if torch.cuda.is_available(): torch.cuda.set_device(0) matrix = matrix.cuda() # Make sure samples are rows and not columns m = matrix.T.type(dtype) if transposed else matrix.type(dtype) # PCA Computations now = datetime.now() cov_mat = torchCov(m, False, debug=debug).type(torch.float32) eig_vals, eig_vecs = cov_mat.eig(eigenvectors=True) eig_vals = eig_vals[:, 0] # Ignoring the complex part [:, 1] # Getting the top k eigen vectors order = eig_vals.argsort(descending=True) top_k = eig_vecs[:, order[:k]].type_as(m) # Reducing the matrix res = m @ top_k, top_k total_time = datetime.now() - now return res, total_time.microseconds / 1e6 # def torchCov(x, rowvar=False, bias=False, ddof=None, aweights=None): # """Estimates covariance matrix like numpy.cov""" # # ensure at least 2D # if x.dim() == 1: x = x.view(-1, 1) # # treat each column as a data point, each row as a variable # if rowvar and x.shape[0] != 1: # x = x.t() # if ddof is None: # if bias == 0: ddof = 1 # else: ddof = 0 # w = aweights # if w is not None: # if not torch.is_tensor(w): w = torch.tensor(w, dtype=torch.float) # w_sum = torch.sum(w) # avg = torch.sum(x * (w/w_sum)[:,None], 0) # else: # avg = torch.mean(x, 0) # # Determine the normalization # if w is None: fact = x.shape[0] - ddof # elif ddof == 0: fact = w_sum # elif aweights is None: fact = w_sum - ddof # else: fact = w_sum - ddof * torch.sum(w * w) / w_sum # xm = x.sub(avg.expand_as(x)) # if w is None: X_T = xm.t() # else: X_T = torch.mm(torch.diag(w), xm).t() # c = torch.mm(X_T, xm) # c = c / fact # return c.squeeze() class Arrow3D(FancyArrowPatch): def __init__(self, xs, ys, zs, *args, **kwargs): FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs) self._verts3d = xs, ys, zs def draw(self, renderer): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) self.set_positions((xs[0], ys[0]), (xs[1], ys[1])) FancyArrowPatch.draw(self, renderer) def visualize3dData(matrix:torch.Tensor, labels=None, transposed=False): if not isinstance(matrix, torch.Tensor): matrix = torch.tensor(matrix) m = matrix.clone().T if not transposed else matrix.clone() assert m.shape[0] == 3 if labels is None: labels = torch.zeros(m.shape[1]) else: if not isinstance(labels, torch.Tensor): labels = torch.tensor(labels) fig = plt.figure(figsize=(16,16)) ax = fig.add_subplot(111, projection='3d') plt.rcParams['legend.fontsize'] = 10 classes = torch.unique(labels) for label in classes: data = m[:, labels == label] ax.plot(data[0, :], data[1, :], data[2, :], 'o', markersize=8, alpha=0.4, label="Class 1") mean_vector = m.mean(dim=1, keepdim=True) cov_mat = torchCov(m, True) eig_vals, eig_vecs = cov_mat.eig(eigenvectors=True) eig_vals = eig_vals[:, 0] # Ignoring the complex part [:, 1] scaled_eig_vecs = (eig_vecs * eig_vals).cpu() means = mean_vector.cpu() for v in scaled_eig_vecs.T: a = Arrow3D([means[0].item(), v[0]], [means[1].item(), v[1]], [means[2].item(), v[2]], mutation_scale=20, lw=3, arrowstyle="-|>", color="black") ax.add_artist(a) ax.set_xlabel('x_values') ax.set_ylabel('y_values') ax.set_zlabel('z_values') plt.title('Eigenvectors') plt.show() return fig
import torch import torchvision from sklearn.decomposition import PCA import matplotlib.pyplot as plt import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D, proj3d from matplotlib.patches import FancyArrowPatch from datetime import datetime from pdb import set_trace MIN_16, MAX_16 = torch.finfo(torch.float16).min, torch.finfo(torch.float16).max MIN_32, MAX_32 = torch.finfo(torch.float32).min, torch.finfo(torch.float32).max def stats(*args): for x in args: print("Type : ", type(x)) print("Shape: ", x.shape) print("Sum : ", x.sum()) print("Mean : ", x.mean()) print("STD : ", x.std()) print() def torchCov(matrix:torch.Tensor, transposed=False, debug=False): "Transposed = True if individual samples are columns and not rows" if not isinstance(matrix, torch.Tensor): matrix = torch.tensor(matrix) if torch.cuda.is_available(): matrix = matrix.cuda() m = matrix.T if transposed else matrix if debug: set_trace() n = m.shape[0] MAX = torch.finfo(m.dtype).max mean = m.mean(axis=0, keepdim=True) m.sub_(mean) product = (m.T @ m).clamp(0, MAX) product[torch.isnan(product)] = 0 product[torch.isinf(product)] = MAX return product / (n-1) def torchPCA(matrix:torch.Tensor, k=2, transposed=False, fp16=True, debug=False): # Convert to tensor, cuda, half precision if debug: set_trace() dtype = torch.float16 if (fp16 and torch.cuda.is_available()) else torch.float32 if not isinstance(matrix, torch.Tensor): matrix = torch.tensor(matrix).type(dtype) if torch.cuda.is_available(): torch.cuda.set_device(0) matrix = matrix.cuda() # Make sure samples are rows and not columns m = matrix.T.type(dtype) if transposed else matrix.type(dtype) # PCA Computations now = datetime.now() cov_mat = torchCov(m, False, debug=debug).type(torch.float32) eig_vals, eig_vecs = cov_mat.eig(eigenvectors=True) eig_vals = eig_vals[:, 0] # Ignoring the complex part [:, 1] # Getting the top k eigen vectors order = eig_vals.argsort(descending=True) top_k = eig_vecs[:, order[:k]].type_as(m) # Reducing the matrix res = m @ top_k, top_k total_time = datetime.now() - now return res, total_time.microseconds / 1e6 # def torchCov(x, rowvar=False, bias=False, ddof=None, aweights=None): # """Estimates covariance matrix like numpy.cov""" # # ensure at least 2D # if x.dim() == 1: x = x.view(-1, 1) # # treat each column as a data point, each row as a variable # if rowvar and x.shape[0] != 1: # x = x.t() # if ddof is None: # if bias == 0: ddof = 1 # else: ddof = 0 # w = aweights # if w is not None: # if not torch.is_tensor(w): w = torch.tensor(w, dtype=torch.float) # w_sum = torch.sum(w) # avg = torch.sum(x * (w/w_sum)[:,None], 0) # else: # avg = torch.mean(x, 0) # # Determine the normalization # if w is None: fact = x.shape[0] - ddof # elif ddof == 0: fact = w_sum # elif aweights is None: fact = w_sum - ddof # else: fact = w_sum - ddof * torch.sum(w * w) / w_sum # xm = x.sub(avg.expand_as(x)) # if w is None: X_T = xm.t() # else: X_T = torch.mm(torch.diag(w), xm).t() # c = torch.mm(X_T, xm) # c = c / fact # return c.squeeze() class Arrow3D(FancyArrowPatch): def __init__(self, xs, ys, zs, *args, **kwargs): FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs) self._verts3d = xs, ys, zs def draw(self, renderer): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) self.set_positions((xs[0], ys[0]), (xs[1], ys[1])) FancyArrowPatch.draw(self, renderer) def visualize3dData(matrix:torch.Tensor, labels=None, transposed=False): if not isinstance(matrix, torch.Tensor): matrix = torch.tensor(matrix) m = matrix.clone().T if not transposed else matrix.clone() assert m.shape[0] == 3 if labels is None: labels = torch.zeros(m.shape[1]) else: if not isinstance(labels, torch.Tensor): labels = torch.tensor(labels) fig = plt.figure(figsize=(16,16)) ax = fig.add_subplot(111, projection='3d') plt.rcParams['legend.fontsize'] = 10 classes = torch.unique(labels) for label in classes: data = m[:, labels == label] ax.plot(data[0, :], data[1, :], data[2, :], 'o', markersize=8, alpha=0.4, label="Class 1") mean_vector = m.mean(dim=1, keepdim=True) cov_mat = torchCov(m, True) eig_vals, eig_vecs = cov_mat.eig(eigenvectors=True) eig_vals = eig_vals[:, 0] # Ignoring the complex part [:, 1] scaled_eig_vecs = (eig_vecs * eig_vals).cpu() means = mean_vector.cpu() for v in scaled_eig_vecs.T: a = Arrow3D([means[0].item(), v[0]], [means[1].item(), v[1]], [means[2].item(), v[2]], mutation_scale=20, lw=3, arrowstyle="-|>", color="black") ax.add_artist(a) ax.set_xlabel('x_values') ax.set_ylabel('y_values') ax.set_zlabel('z_values') plt.title('Eigenvectors') plt.show() return fig
en
0.696656
# Convert to tensor, cuda, half precision # Make sure samples are rows and not columns # PCA Computations # Ignoring the complex part [:, 1] # Getting the top k eigen vectors # Reducing the matrix # def torchCov(x, rowvar=False, bias=False, ddof=None, aweights=None): # """Estimates covariance matrix like numpy.cov""" # # ensure at least 2D # if x.dim() == 1: x = x.view(-1, 1) # # treat each column as a data point, each row as a variable # if rowvar and x.shape[0] != 1: # x = x.t() # if ddof is None: # if bias == 0: ddof = 1 # else: ddof = 0 # w = aweights # if w is not None: # if not torch.is_tensor(w): w = torch.tensor(w, dtype=torch.float) # w_sum = torch.sum(w) # avg = torch.sum(x * (w/w_sum)[:,None], 0) # else: # avg = torch.mean(x, 0) # # Determine the normalization # if w is None: fact = x.shape[0] - ddof # elif ddof == 0: fact = w_sum # elif aweights is None: fact = w_sum - ddof # else: fact = w_sum - ddof * torch.sum(w * w) / w_sum # xm = x.sub(avg.expand_as(x)) # if w is None: X_T = xm.t() # else: X_T = torch.mm(torch.diag(w), xm).t() # c = torch.mm(X_T, xm) # c = c / fact # return c.squeeze() # Ignoring the complex part [:, 1]
2.297537
2
kdbtest/__main__.py
SiMylo/kmel_db
0
6623248
<gh_stars>0 """Python's unittest main entry point, extended to include coverage""" import os import sys import unittest try: import coverage HAVE_COVERAGE = True except ImportError: HAVE_COVERAGE = False if sys.argv[0].endswith("__main__.py"): # We change sys.argv[0] to make help message more useful # use executable without path, unquoted # (it's just a hint anyway) # (if you have spaces in your executable you get what you deserve!) executable = os.path.basename(sys.executable) sys.argv[0] = executable + " -m unittest" __unittest = True html_dir = 'test_coverage' cov = None if HAVE_COVERAGE: cov = coverage.Coverage(branch=True) cov._warn_no_data = False cov.exclude(r'\@abc\.abstract', 'partial') cov.start() try: loader = unittest.TestLoader() _current_dir = os.path.dirname(__file__) suite = loader.discover(_current_dir + '/../tests') runner = unittest.TextTestRunner() runner.run(suite) finally: if cov is not None: cov.stop() cov.save() cov.html_report(directory=html_dir, title='DapGen test coverage')
"""Python's unittest main entry point, extended to include coverage""" import os import sys import unittest try: import coverage HAVE_COVERAGE = True except ImportError: HAVE_COVERAGE = False if sys.argv[0].endswith("__main__.py"): # We change sys.argv[0] to make help message more useful # use executable without path, unquoted # (it's just a hint anyway) # (if you have spaces in your executable you get what you deserve!) executable = os.path.basename(sys.executable) sys.argv[0] = executable + " -m unittest" __unittest = True html_dir = 'test_coverage' cov = None if HAVE_COVERAGE: cov = coverage.Coverage(branch=True) cov._warn_no_data = False cov.exclude(r'\@abc\.abstract', 'partial') cov.start() try: loader = unittest.TestLoader() _current_dir = os.path.dirname(__file__) suite = loader.discover(_current_dir + '/../tests') runner = unittest.TextTestRunner() runner.run(suite) finally: if cov is not None: cov.stop() cov.save() cov.html_report(directory=html_dir, title='DapGen test coverage')
en
0.887393
Python's unittest main entry point, extended to include coverage # We change sys.argv[0] to make help message more useful # use executable without path, unquoted # (it's just a hint anyway) # (if you have spaces in your executable you get what you deserve!)
2.448614
2
app/views/product.py
LP-Dev-Web/LeBonRecoin
0
6623249
<gh_stars>0 from django.contrib import messages from django.contrib.messages.views import SuccessMessageMixin from django.http import HttpResponseRedirect from django.urls import reverse_lazy from django.views.generic import ( DetailView, RedirectView, CreateView, UpdateView, DeleteView, ListView, ) from django.utils.translation import gettext_lazy as _ from app.forms.product import AdForm, PictureForm, EditPictureForm from app.models import Product, Picture, Address, Favorite class NewAdView(CreateView): template_name = "account/form.html" model = Product form_class = AdForm def get(self, request, *args, **kwargs): if Address.objects.filter(user_id=self.request.user.pk).exists(): return super().get(request) else: return HttpResponseRedirect(reverse_lazy("new-address")) def get_context_data(self, **kwargs): data = super(NewAdView, self).get_context_data(**kwargs) data["title"] = _("Add your ad") data["link"] = "index" data["button"] = _("Next") return data def form_valid(self, form): new_ad = form.save(commit=False) new_ad.user_id = self.request.user.pk new_ad.save() return super().form_valid(form) def get_success_url(self): product = Product.objects.filter(user_id=self.request.user.pk).latest("pk") return reverse_lazy("new-ad-picture", kwargs={"pk": product.pk}) class NewPictureView(SuccessMessageMixin, CreateView): success_url = reverse_lazy("profil-ads") template_name = "account/form.html" model = Picture form_class = PictureForm success_message = _("Your ad has been published.") def get_context_data(self, **kwargs): data = super(NewPictureView, self).get_context_data(**kwargs) data["title"] = _("Add your pictures") data["back"] = "index" return data def form_valid(self, form): new_picture = form.save(commit=False) new_picture.product_id = self.kwargs["pk"] new_picture.save() return super().form_valid(form) class ListAdView(ListView): template_name = "account/list.html" model = Product def get_context_data(self, **kwargs): data = super(ListAdView, self).get_context_data(**kwargs) data["title"] = _("Your ads") data["message"] = _("You have not yet published any ads.") data["view"] = "view-ad" data["edit"] = "edit-ad" data["delete"] = "delete-ad" return data def get_queryset(self): return Picture.objects.filter(product__user_id=self.request.user.pk).all() class ViewAdView(DetailView): template_name = "product/ad.html" model = Product def get(self, request, *args, **kwargs): if Product.objects.filter( user_id=self.request.user.pk, id=self.kwargs["pk"] ).exists(): return super().get(request) else: lastest = Product.objects.filter(user_id=self.request.user.pk).first() return HttpResponseRedirect( reverse_lazy("view-ad", kwargs={"pk": lastest.pk}) ) def get_context_data(self, **kwargs): data = super(ViewAdView, self).get_context_data(**kwargs) data["pictures"] = Picture.objects.filter(product_id=self.kwargs["pk"]).first() return data class EditAdView(SuccessMessageMixin, UpdateView): template_name = "account/form.html" model = Product form_class = AdForm success_message = _("The ad has been modified.") def get(self, request, *args, **kwargs): if Product.objects.filter( user_id=self.request.user.pk, id=self.kwargs["pk"] ).exists(): return super().get(request) else: lastest = Product.objects.filter(user_id=self.request.user.pk).first() return HttpResponseRedirect( reverse_lazy("edit-ad", kwargs={"pk": lastest.pk}) ) def get_context_data(self, **kwargs): data = super(EditAdView, self).get_context_data(**kwargs) data["pictures"] = Picture.objects.filter(product_id=self.kwargs["pk"]).first() data["extra"] = True data["title"] = _("Edit your ad") data["link"] = "profil-ads" data["button"] = _("Edit") return data def get_success_url(self): pk = self.kwargs["pk"] return reverse_lazy("view-ad", kwargs={"pk": pk}) class EditPictureView(SuccessMessageMixin, UpdateView): template_name = "account/form.html" model = Picture form_class = EditPictureForm success_message = _("The image(s) have been modified.") def get(self, request, *args, **kwargs): product = Product.objects.filter( picture=self.kwargs["pk"], user_id=self.request.user.pk ).first() if Picture.objects.filter(product_id=product, id=self.kwargs["pk"]).exists(): return super().get(request) else: product = Product.objects.filter(user_id=self.request.user.pk).first() lastest = Picture.objects.get(product_id=product) return HttpResponseRedirect( reverse_lazy("edit-ad-picture", kwargs={"pk": lastest.pk}) ) def get_context_data(self, **kwargs): data = super(EditPictureView, self).get_context_data(**kwargs) data["product"] = Product.objects.filter(picture=self.kwargs["pk"]).first() data["title"] = _("Edit your ad") data["link"] = "edit-ad" data["value"] = data["product"].id data["button"] = _("Edit") return data def get_success_url(self): product = Product.objects.get(picture=self.kwargs["pk"]) return reverse_lazy("view-ad", kwargs={"pk": product.pk}) class DeleteAdView(DeleteView): success_url = reverse_lazy("profil-ads") template_name = "account/delete.html" model = Product def get(self, request, *args, **kwargs): if Product.objects.filter( user_id=self.request.user.pk, id=self.kwargs["pk"] ).exists(): return super().get(request) else: lastest = Product.objects.filter(user_id=self.request.user.pk).first() return HttpResponseRedirect( reverse_lazy("delete-ad", kwargs={"pk": lastest.pk}) ) def delete(self, request, *args, **kwargs): messages.success(request, _("The ad has been removed.")) return super().delete(request) class AdView(DetailView): template_name = "product/ad.html" model = Product def get_context_data(self, **kwargs): data = super(AdView, self).get_context_data(**kwargs) data["pictures"] = Picture.objects.filter(product_id=self.kwargs["pk"]).first() user_id = Product.objects.get(id=self.kwargs["pk"]).user.pk data["address"] = Address.objects.filter(user_id=user_id).first() data["products"] = ( Picture.objects.filter(product__categorie_id=data["product"].categorie.id) .all() .exclude(product_id=self.kwargs["pk"])[:4] ) if ( not Picture.objects.filter( product__categorie_id=data["product"].categorie.id ) .all() .exclude(product_id=self.kwargs["pk"]) .exists() ): data["others"] = Picture.objects.all().exclude( product_id=self.kwargs["pk"] )[:4] data["favorite"] = Favorite.objects.filter( product_id=self.kwargs["pk"], user_id=self.request.user.pk ).exists() data["edit"] = Product.objects.filter( pk=self.kwargs["pk"], user_id=self.request.user.pk ).exists() return data class OfferAdView(DetailView): template_name = "product/offer.html" model = Product def get_context_data(self, **kwargs): data = super(OfferAdView, self).get_context_data(**kwargs) user_id = Product.objects.get(id=self.kwargs["pk"]).user.pk data["address"] = Address.objects.filter(user_id=user_id).first() return data class FavoriteView(RedirectView): def get(self, request, *args, **kwargs): if Favorite.objects.filter( product_id=self.kwargs["pk"], user_id=self.request.user.pk ).exists(): Favorite.objects.get( product_id=self.kwargs["pk"], user_id=self.request.user.pk ).delete() else: Favorite.objects.create( product_id=self.kwargs["pk"], user_id=self.request.user.pk ) return HttpResponseRedirect( reverse_lazy("ad", kwargs={"pk": self.kwargs["pk"]}) )
from django.contrib import messages from django.contrib.messages.views import SuccessMessageMixin from django.http import HttpResponseRedirect from django.urls import reverse_lazy from django.views.generic import ( DetailView, RedirectView, CreateView, UpdateView, DeleteView, ListView, ) from django.utils.translation import gettext_lazy as _ from app.forms.product import AdForm, PictureForm, EditPictureForm from app.models import Product, Picture, Address, Favorite class NewAdView(CreateView): template_name = "account/form.html" model = Product form_class = AdForm def get(self, request, *args, **kwargs): if Address.objects.filter(user_id=self.request.user.pk).exists(): return super().get(request) else: return HttpResponseRedirect(reverse_lazy("new-address")) def get_context_data(self, **kwargs): data = super(NewAdView, self).get_context_data(**kwargs) data["title"] = _("Add your ad") data["link"] = "index" data["button"] = _("Next") return data def form_valid(self, form): new_ad = form.save(commit=False) new_ad.user_id = self.request.user.pk new_ad.save() return super().form_valid(form) def get_success_url(self): product = Product.objects.filter(user_id=self.request.user.pk).latest("pk") return reverse_lazy("new-ad-picture", kwargs={"pk": product.pk}) class NewPictureView(SuccessMessageMixin, CreateView): success_url = reverse_lazy("profil-ads") template_name = "account/form.html" model = Picture form_class = PictureForm success_message = _("Your ad has been published.") def get_context_data(self, **kwargs): data = super(NewPictureView, self).get_context_data(**kwargs) data["title"] = _("Add your pictures") data["back"] = "index" return data def form_valid(self, form): new_picture = form.save(commit=False) new_picture.product_id = self.kwargs["pk"] new_picture.save() return super().form_valid(form) class ListAdView(ListView): template_name = "account/list.html" model = Product def get_context_data(self, **kwargs): data = super(ListAdView, self).get_context_data(**kwargs) data["title"] = _("Your ads") data["message"] = _("You have not yet published any ads.") data["view"] = "view-ad" data["edit"] = "edit-ad" data["delete"] = "delete-ad" return data def get_queryset(self): return Picture.objects.filter(product__user_id=self.request.user.pk).all() class ViewAdView(DetailView): template_name = "product/ad.html" model = Product def get(self, request, *args, **kwargs): if Product.objects.filter( user_id=self.request.user.pk, id=self.kwargs["pk"] ).exists(): return super().get(request) else: lastest = Product.objects.filter(user_id=self.request.user.pk).first() return HttpResponseRedirect( reverse_lazy("view-ad", kwargs={"pk": lastest.pk}) ) def get_context_data(self, **kwargs): data = super(ViewAdView, self).get_context_data(**kwargs) data["pictures"] = Picture.objects.filter(product_id=self.kwargs["pk"]).first() return data class EditAdView(SuccessMessageMixin, UpdateView): template_name = "account/form.html" model = Product form_class = AdForm success_message = _("The ad has been modified.") def get(self, request, *args, **kwargs): if Product.objects.filter( user_id=self.request.user.pk, id=self.kwargs["pk"] ).exists(): return super().get(request) else: lastest = Product.objects.filter(user_id=self.request.user.pk).first() return HttpResponseRedirect( reverse_lazy("edit-ad", kwargs={"pk": lastest.pk}) ) def get_context_data(self, **kwargs): data = super(EditAdView, self).get_context_data(**kwargs) data["pictures"] = Picture.objects.filter(product_id=self.kwargs["pk"]).first() data["extra"] = True data["title"] = _("Edit your ad") data["link"] = "profil-ads" data["button"] = _("Edit") return data def get_success_url(self): pk = self.kwargs["pk"] return reverse_lazy("view-ad", kwargs={"pk": pk}) class EditPictureView(SuccessMessageMixin, UpdateView): template_name = "account/form.html" model = Picture form_class = EditPictureForm success_message = _("The image(s) have been modified.") def get(self, request, *args, **kwargs): product = Product.objects.filter( picture=self.kwargs["pk"], user_id=self.request.user.pk ).first() if Picture.objects.filter(product_id=product, id=self.kwargs["pk"]).exists(): return super().get(request) else: product = Product.objects.filter(user_id=self.request.user.pk).first() lastest = Picture.objects.get(product_id=product) return HttpResponseRedirect( reverse_lazy("edit-ad-picture", kwargs={"pk": lastest.pk}) ) def get_context_data(self, **kwargs): data = super(EditPictureView, self).get_context_data(**kwargs) data["product"] = Product.objects.filter(picture=self.kwargs["pk"]).first() data["title"] = _("Edit your ad") data["link"] = "edit-ad" data["value"] = data["product"].id data["button"] = _("Edit") return data def get_success_url(self): product = Product.objects.get(picture=self.kwargs["pk"]) return reverse_lazy("view-ad", kwargs={"pk": product.pk}) class DeleteAdView(DeleteView): success_url = reverse_lazy("profil-ads") template_name = "account/delete.html" model = Product def get(self, request, *args, **kwargs): if Product.objects.filter( user_id=self.request.user.pk, id=self.kwargs["pk"] ).exists(): return super().get(request) else: lastest = Product.objects.filter(user_id=self.request.user.pk).first() return HttpResponseRedirect( reverse_lazy("delete-ad", kwargs={"pk": lastest.pk}) ) def delete(self, request, *args, **kwargs): messages.success(request, _("The ad has been removed.")) return super().delete(request) class AdView(DetailView): template_name = "product/ad.html" model = Product def get_context_data(self, **kwargs): data = super(AdView, self).get_context_data(**kwargs) data["pictures"] = Picture.objects.filter(product_id=self.kwargs["pk"]).first() user_id = Product.objects.get(id=self.kwargs["pk"]).user.pk data["address"] = Address.objects.filter(user_id=user_id).first() data["products"] = ( Picture.objects.filter(product__categorie_id=data["product"].categorie.id) .all() .exclude(product_id=self.kwargs["pk"])[:4] ) if ( not Picture.objects.filter( product__categorie_id=data["product"].categorie.id ) .all() .exclude(product_id=self.kwargs["pk"]) .exists() ): data["others"] = Picture.objects.all().exclude( product_id=self.kwargs["pk"] )[:4] data["favorite"] = Favorite.objects.filter( product_id=self.kwargs["pk"], user_id=self.request.user.pk ).exists() data["edit"] = Product.objects.filter( pk=self.kwargs["pk"], user_id=self.request.user.pk ).exists() return data class OfferAdView(DetailView): template_name = "product/offer.html" model = Product def get_context_data(self, **kwargs): data = super(OfferAdView, self).get_context_data(**kwargs) user_id = Product.objects.get(id=self.kwargs["pk"]).user.pk data["address"] = Address.objects.filter(user_id=user_id).first() return data class FavoriteView(RedirectView): def get(self, request, *args, **kwargs): if Favorite.objects.filter( product_id=self.kwargs["pk"], user_id=self.request.user.pk ).exists(): Favorite.objects.get( product_id=self.kwargs["pk"], user_id=self.request.user.pk ).delete() else: Favorite.objects.create( product_id=self.kwargs["pk"], user_id=self.request.user.pk ) return HttpResponseRedirect( reverse_lazy("ad", kwargs={"pk": self.kwargs["pk"]}) )
none
1
2.136909
2
AutoRegression.py
sercangul/AutoMachineLearning
0
6623250
<reponame>sercangul/AutoMachineLearning<gh_stars>0 #!/usr/bin/env python # coding: utf-8 # This notebook explains the steps to develop an Automated Supervised Machine Learning Regression program, which automatically tunes the hyperparameters and prints out the final accuracy results as a tables together with feature importance results. # Let's import all libraries. # In[1]: import pandas as pd import numpy as np from xgboost import XGBRegressor from sklearn.model_selection import GridSearchCV from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LinearRegression from sklearn.linear_model import Ridge from sklearn.ensemble import RandomForestRegressor from sklearn.linear_model import Lasso from sklearn.svm import SVR from sklearn.neural_network import MLPRegressor from sklearn.model_selection import train_test_split from sklearn.metrics import explained_variance_score from sklearn.metrics import max_error from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_error from sklearn.metrics import mean_squared_log_error from sklearn.metrics import median_absolute_error from sklearn.metrics import r2_score from sklearn.metrics import mean_poisson_deviance from sklearn.metrics import mean_gamma_deviance from sklearn.metrics import mean_absolute_percentage_error from itertools import repeat import matplotlib.pyplot as plt # Lets import our dataset from the csv files as a dataframe. # In[2]: df = pd.read_csv('data.csv') # Let's take a look at dataset. I like using df.describe() function to have some statistics about each column. # In[3]: df.describe().T # Let's define the features as X and the column we want to predict (column F) as y. # In[4]: n = len(df.columns) X = df.iloc[:,0:n-1].to_numpy() y = df.iloc[:,n-1].to_numpy() # This defines X as all the values except the last column (columns A,B,C,D,E), and y as the last column (column numbers start from zero, hence: 0 - A, 1 - B, 2 - C, 3 - D,4 - E, 5 -F). # Some algorithms provide better accuracies with the standard scaling of the input features (i.e. normalization). Let's normalize the data. # In[5]: scaler = StandardScaler() scaler.fit(X) X= scaler.transform(X) # We have to split our dataset as train and test data. For this we can use train_test_split by sklearn.model_selection. Test size of 0.20 means that 20% of the data will be used as test data and 80% of the data will be used for training. # In[6]: X_train, X_test, y_train, y_test= train_test_split(X,y,test_size = 0.20) # We might not always want to tune the parameters of models, or only tune for some models. For this I have defined a basic input. When it is set to "True", the program will perform the tuning for all the models. # In[7]: Perform_tuning = True Lassotuning, Ridgetuning, randomforestparametertuning, XGboostparametertuning, SVMparametertuning, MLPparametertuning = repeat(Perform_tuning,6) # Let's define the grid search function to be used with our models. The values of grid might need to be changed regarding the problem (i.e., some problems might require higher values of n_estimators, while some might require lower ranges). # In[8]: def grid_search(model,grid): # Instantiate the grid search model print ("Performing gridsearch for {}".format(model)) grid_search = GridSearchCV(estimator = model(), param_grid=grid, cv = 3, n_jobs = -1, verbose = 2) # Fit the grid search to the data grid_search.fit(X_train, y_train) print("Grid Search Best Parameters for {}".format(model)) print (grid_search.best_params_) return grid_search.best_params_ # Performing Lasso parameter tuning. # In[9]: if Lassotuning: # Create the parameter grid based on the results of random search grid = { 'alpha': [1,0.9,0.75,0.5,0.1,0.01,0.001,0.0001] , "fit_intercept": [True, False] } Lasso_bestparam = grid_search(Lasso,grid) # Performing Ridge parameter tuning. # In[10]: if Ridgetuning: # Create the parameter grid based on the results of random search grid = { 'alpha': [1,0.9,0.75,0.5,0.1,0.01,0.001,0.0001] , "fit_intercept": [True, False] } Ridge_bestparam = grid_search(Ridge,grid) # Performing Random Forest parameter tuning. # In[11]: if randomforestparametertuning: # Create the parameter grid based on the results of random search grid = { 'bootstrap': [True,False], 'max_depth': [40, 50, 60, 70], 'max_features': ['auto', 'sqrt'], 'min_samples_leaf': [1,2,3,], 'min_samples_split': [3, 4, 5,6,7], 'n_estimators': [5,10,15] } RF_bestparam = grid_search(RandomForestRegressor,grid) # Performing XGBoost parameter tuning. # In[12]: if XGboostparametertuning: # Create the parameter grid based on the results of random search grid = {'colsample_bytree': [0.9,0.7], 'gamma': [2,5], 'learning_rate': [0.1,0.2,0.3], 'max_depth': [8,10,12], 'n_estimators': [5,10], 'subsample': [0.8,1], 'reg_alpha': [15,20], 'min_child_weight':[3,5]} XGB_bestparam = grid_search(XGBRegressor,grid) # Performing SVM parameter tuning. # In[13]: #SVM Parameter Tuning---------------------------------------------------------- if SVMparametertuning: grid = {'gamma': 10. ** np.arange(-5, 3), 'C': 10. ** np.arange(-3, 3)} SVR_bestparam = grid_search(SVR,grid) # Performing MLP parameter tuning. # In[14]: if MLPparametertuning: grid = { 'hidden_layer_sizes': [2,5,8,10], 'activation': ['identity','logistic','tanh','relu'], 'solver': ['lbfgs', 'sgd','adam'], 'learning_rate': ['constant','invscaling','adaptive']} MLP_bestparam = grid_search(MLPRegressor,grid) # Now we obtained the best parameters for all the models using the training data. Let's define the error metrics that will be used in analyzing the accuracy of each model. # In[15]: error_metrics = ( explained_variance_score, max_error, mean_absolute_error, mean_squared_error, mean_squared_log_error, median_absolute_error, r2_score, mean_poisson_deviance, mean_gamma_deviance, mean_absolute_percentage_error ) # Let's define fit_model function to predict the results, and analyze the error metrics for each model. # In[16]: def fit_model(model,X_train, X_test, y_train, y_test,error_metrics): fitted_model = model.fit(X_train,y_train) y_predicted = fitted_model.predict(X_test) calculations = [] for metric in error_metrics: calc = metric(y_test, y_predicted) calculations.append(calc) return calculations # Provide a summary of each model and their GridSearch best parameter results. If tuning is not performed, the script will use the default values as best parameters. # In[17]: try: trainingmodels = ( LinearRegression(), Ridge(**Ridge_bestparam), RandomForestRegressor(**RF_bestparam), XGBRegressor(**XGB_bestparam), Lasso(**Lasso_bestparam), SVR(**SVR_bestparam), MLPRegressor(**MLP_bestparam) ) except: trainingmodels = ( LinearRegression(), Ridge(), RandomForestRegressor(), XGBRegressor(), Lasso(), SVR(), MLPRegressor() ) calculations = [] # Below loop performes training, testing and error metrics calculations for each model. # In[18]: for trainmodel in trainingmodels: errors = fit_model(trainmodel,X_train, X_test, y_train, y_test,error_metrics) calculations.append(errors) # Let's organize these results, and summarize them all in a dataframe. # In[19]: errors = ( 'Explained variance score', 'Max error', 'Mean absolute error', 'Mean squared error', 'Mean squared log error', 'Median absolute error', 'r2 score', 'Mean poisson deviance', 'Mean gamma deviance', 'Mean absolute percentage error' ) model_names = ( 'LinearRegression', 'Ridge', 'RandomForestRegressor', 'XGBRegressor', 'Lasso', 'SVR', 'MLPRegressor' ) df_error = pd.DataFrame(calculations, columns=errors) df_error["Model"] = model_names cols = df_error.columns.tolist() cols = cols[-1:] + cols[:-1] df_error = df_error[cols] df_error = df_error.sort_values(by=['Mean squared error'],ascending=True) df_error = (df_error.set_index('Model') .astype(float) .applymap('{:,.3f}'.format)) df_error.to_csv("errors.csv") df_error # Moreover, we can analyze the feature importance results using the Random Forest regressor. # In[20]: #Principal Component Analysis features = df.columns[:-1] try: randreg = RandomForestRegressor(**RF_bestparam).fit(X,y) except: randreg = RandomForestRegressor().fit(X,y) importances = randreg.feature_importances_ indices = np.argsort(importances) plt.figure(3) #the axis number plt.title('Feature Importance') plt.barh(range(len(indices)), importances[indices], color='b', align='center') plt.yticks(range(len(indices)), features[indices]) plt.xlabel('Relative Importance') plt.savefig('Feature Importance.png', bbox_inches='tight', dpi = 500) # In[ ]:
#!/usr/bin/env python # coding: utf-8 # This notebook explains the steps to develop an Automated Supervised Machine Learning Regression program, which automatically tunes the hyperparameters and prints out the final accuracy results as a tables together with feature importance results. # Let's import all libraries. # In[1]: import pandas as pd import numpy as np from xgboost import XGBRegressor from sklearn.model_selection import GridSearchCV from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LinearRegression from sklearn.linear_model import Ridge from sklearn.ensemble import RandomForestRegressor from sklearn.linear_model import Lasso from sklearn.svm import SVR from sklearn.neural_network import MLPRegressor from sklearn.model_selection import train_test_split from sklearn.metrics import explained_variance_score from sklearn.metrics import max_error from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_error from sklearn.metrics import mean_squared_log_error from sklearn.metrics import median_absolute_error from sklearn.metrics import r2_score from sklearn.metrics import mean_poisson_deviance from sklearn.metrics import mean_gamma_deviance from sklearn.metrics import mean_absolute_percentage_error from itertools import repeat import matplotlib.pyplot as plt # Lets import our dataset from the csv files as a dataframe. # In[2]: df = pd.read_csv('data.csv') # Let's take a look at dataset. I like using df.describe() function to have some statistics about each column. # In[3]: df.describe().T # Let's define the features as X and the column we want to predict (column F) as y. # In[4]: n = len(df.columns) X = df.iloc[:,0:n-1].to_numpy() y = df.iloc[:,n-1].to_numpy() # This defines X as all the values except the last column (columns A,B,C,D,E), and y as the last column (column numbers start from zero, hence: 0 - A, 1 - B, 2 - C, 3 - D,4 - E, 5 -F). # Some algorithms provide better accuracies with the standard scaling of the input features (i.e. normalization). Let's normalize the data. # In[5]: scaler = StandardScaler() scaler.fit(X) X= scaler.transform(X) # We have to split our dataset as train and test data. For this we can use train_test_split by sklearn.model_selection. Test size of 0.20 means that 20% of the data will be used as test data and 80% of the data will be used for training. # In[6]: X_train, X_test, y_train, y_test= train_test_split(X,y,test_size = 0.20) # We might not always want to tune the parameters of models, or only tune for some models. For this I have defined a basic input. When it is set to "True", the program will perform the tuning for all the models. # In[7]: Perform_tuning = True Lassotuning, Ridgetuning, randomforestparametertuning, XGboostparametertuning, SVMparametertuning, MLPparametertuning = repeat(Perform_tuning,6) # Let's define the grid search function to be used with our models. The values of grid might need to be changed regarding the problem (i.e., some problems might require higher values of n_estimators, while some might require lower ranges). # In[8]: def grid_search(model,grid): # Instantiate the grid search model print ("Performing gridsearch for {}".format(model)) grid_search = GridSearchCV(estimator = model(), param_grid=grid, cv = 3, n_jobs = -1, verbose = 2) # Fit the grid search to the data grid_search.fit(X_train, y_train) print("Grid Search Best Parameters for {}".format(model)) print (grid_search.best_params_) return grid_search.best_params_ # Performing Lasso parameter tuning. # In[9]: if Lassotuning: # Create the parameter grid based on the results of random search grid = { 'alpha': [1,0.9,0.75,0.5,0.1,0.01,0.001,0.0001] , "fit_intercept": [True, False] } Lasso_bestparam = grid_search(Lasso,grid) # Performing Ridge parameter tuning. # In[10]: if Ridgetuning: # Create the parameter grid based on the results of random search grid = { 'alpha': [1,0.9,0.75,0.5,0.1,0.01,0.001,0.0001] , "fit_intercept": [True, False] } Ridge_bestparam = grid_search(Ridge,grid) # Performing Random Forest parameter tuning. # In[11]: if randomforestparametertuning: # Create the parameter grid based on the results of random search grid = { 'bootstrap': [True,False], 'max_depth': [40, 50, 60, 70], 'max_features': ['auto', 'sqrt'], 'min_samples_leaf': [1,2,3,], 'min_samples_split': [3, 4, 5,6,7], 'n_estimators': [5,10,15] } RF_bestparam = grid_search(RandomForestRegressor,grid) # Performing XGBoost parameter tuning. # In[12]: if XGboostparametertuning: # Create the parameter grid based on the results of random search grid = {'colsample_bytree': [0.9,0.7], 'gamma': [2,5], 'learning_rate': [0.1,0.2,0.3], 'max_depth': [8,10,12], 'n_estimators': [5,10], 'subsample': [0.8,1], 'reg_alpha': [15,20], 'min_child_weight':[3,5]} XGB_bestparam = grid_search(XGBRegressor,grid) # Performing SVM parameter tuning. # In[13]: #SVM Parameter Tuning---------------------------------------------------------- if SVMparametertuning: grid = {'gamma': 10. ** np.arange(-5, 3), 'C': 10. ** np.arange(-3, 3)} SVR_bestparam = grid_search(SVR,grid) # Performing MLP parameter tuning. # In[14]: if MLPparametertuning: grid = { 'hidden_layer_sizes': [2,5,8,10], 'activation': ['identity','logistic','tanh','relu'], 'solver': ['lbfgs', 'sgd','adam'], 'learning_rate': ['constant','invscaling','adaptive']} MLP_bestparam = grid_search(MLPRegressor,grid) # Now we obtained the best parameters for all the models using the training data. Let's define the error metrics that will be used in analyzing the accuracy of each model. # In[15]: error_metrics = ( explained_variance_score, max_error, mean_absolute_error, mean_squared_error, mean_squared_log_error, median_absolute_error, r2_score, mean_poisson_deviance, mean_gamma_deviance, mean_absolute_percentage_error ) # Let's define fit_model function to predict the results, and analyze the error metrics for each model. # In[16]: def fit_model(model,X_train, X_test, y_train, y_test,error_metrics): fitted_model = model.fit(X_train,y_train) y_predicted = fitted_model.predict(X_test) calculations = [] for metric in error_metrics: calc = metric(y_test, y_predicted) calculations.append(calc) return calculations # Provide a summary of each model and their GridSearch best parameter results. If tuning is not performed, the script will use the default values as best parameters. # In[17]: try: trainingmodels = ( LinearRegression(), Ridge(**Ridge_bestparam), RandomForestRegressor(**RF_bestparam), XGBRegressor(**XGB_bestparam), Lasso(**Lasso_bestparam), SVR(**SVR_bestparam), MLPRegressor(**MLP_bestparam) ) except: trainingmodels = ( LinearRegression(), Ridge(), RandomForestRegressor(), XGBRegressor(), Lasso(), SVR(), MLPRegressor() ) calculations = [] # Below loop performes training, testing and error metrics calculations for each model. # In[18]: for trainmodel in trainingmodels: errors = fit_model(trainmodel,X_train, X_test, y_train, y_test,error_metrics) calculations.append(errors) # Let's organize these results, and summarize them all in a dataframe. # In[19]: errors = ( 'Explained variance score', 'Max error', 'Mean absolute error', 'Mean squared error', 'Mean squared log error', 'Median absolute error', 'r2 score', 'Mean poisson deviance', 'Mean gamma deviance', 'Mean absolute percentage error' ) model_names = ( 'LinearRegression', 'Ridge', 'RandomForestRegressor', 'XGBRegressor', 'Lasso', 'SVR', 'MLPRegressor' ) df_error = pd.DataFrame(calculations, columns=errors) df_error["Model"] = model_names cols = df_error.columns.tolist() cols = cols[-1:] + cols[:-1] df_error = df_error[cols] df_error = df_error.sort_values(by=['Mean squared error'],ascending=True) df_error = (df_error.set_index('Model') .astype(float) .applymap('{:,.3f}'.format)) df_error.to_csv("errors.csv") df_error # Moreover, we can analyze the feature importance results using the Random Forest regressor. # In[20]: #Principal Component Analysis features = df.columns[:-1] try: randreg = RandomForestRegressor(**RF_bestparam).fit(X,y) except: randreg = RandomForestRegressor().fit(X,y) importances = randreg.feature_importances_ indices = np.argsort(importances) plt.figure(3) #the axis number plt.title('Feature Importance') plt.barh(range(len(indices)), importances[indices], color='b', align='center') plt.yticks(range(len(indices)), features[indices]) plt.xlabel('Relative Importance') plt.savefig('Feature Importance.png', bbox_inches='tight', dpi = 500) # In[ ]:
en
0.739494
#!/usr/bin/env python # coding: utf-8 # This notebook explains the steps to develop an Automated Supervised Machine Learning Regression program, which automatically tunes the hyperparameters and prints out the final accuracy results as a tables together with feature importance results. # Let's import all libraries. # In[1]: # Lets import our dataset from the csv files as a dataframe. # In[2]: # Let's take a look at dataset. I like using df.describe() function to have some statistics about each column. # In[3]: # Let's define the features as X and the column we want to predict (column F) as y. # In[4]: # This defines X as all the values except the last column (columns A,B,C,D,E), and y as the last column (column numbers start from zero, hence: 0 - A, 1 - B, 2 - C, 3 - D,4 - E, 5 -F). # Some algorithms provide better accuracies with the standard scaling of the input features (i.e. normalization). Let's normalize the data. # In[5]: # We have to split our dataset as train and test data. For this we can use train_test_split by sklearn.model_selection. Test size of 0.20 means that 20% of the data will be used as test data and 80% of the data will be used for training. # In[6]: # We might not always want to tune the parameters of models, or only tune for some models. For this I have defined a basic input. When it is set to "True", the program will perform the tuning for all the models. # In[7]: # Let's define the grid search function to be used with our models. The values of grid might need to be changed regarding the problem (i.e., some problems might require higher values of n_estimators, while some might require lower ranges). # In[8]: # Instantiate the grid search model # Fit the grid search to the data # Performing Lasso parameter tuning. # In[9]: # Create the parameter grid based on the results of random search # Performing Ridge parameter tuning. # In[10]: # Create the parameter grid based on the results of random search # Performing Random Forest parameter tuning. # In[11]: # Create the parameter grid based on the results of random search # Performing XGBoost parameter tuning. # In[12]: # Create the parameter grid based on the results of random search # Performing SVM parameter tuning. # In[13]: #SVM Parameter Tuning---------------------------------------------------------- # Performing MLP parameter tuning. # In[14]: # Now we obtained the best parameters for all the models using the training data. Let's define the error metrics that will be used in analyzing the accuracy of each model. # In[15]: # Let's define fit_model function to predict the results, and analyze the error metrics for each model. # In[16]: # Provide a summary of each model and their GridSearch best parameter results. If tuning is not performed, the script will use the default values as best parameters. # In[17]: # Below loop performes training, testing and error metrics calculations for each model. # In[18]: # Let's organize these results, and summarize them all in a dataframe. # In[19]: # Moreover, we can analyze the feature importance results using the Random Forest regressor. # In[20]: #Principal Component Analysis #the axis number # In[ ]:
3.557041
4