body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
e0fe1d0c73f014e021904eab73fa62cd9b2689a2ffaae993104ea6d8742b6b0b
def f(self, val, unit=None): '\n Convert string or value/unit pair to float\n ' return self.__convert(val, unit)
Convert string or value/unit pair to float
spec2nii/fileiobase.py
f
NeutralKaon/spec2nii
5
python
def f(self, val, unit=None): '\n \n ' return self.__convert(val, unit)
def f(self, val, unit=None): '\n \n ' return self.__convert(val, unit)<|docstring|>Convert string or value/unit pair to float<|endoftext|>
b138b6b2a5d3a26e2f4b8043277c6f6e2cffe9fd4a76e9a47e5296759fdf029a
def i(self, val, unit=None): '\n Convert string or value/unit pair to integer\n ' return int(round(self.__convert(val, unit)))
Convert string or value/unit pair to integer
spec2nii/fileiobase.py
i
NeutralKaon/spec2nii
5
python
def i(self, val, unit=None): '\n \n ' return int(round(self.__convert(val, unit)))
def i(self, val, unit=None): '\n \n ' return int(round(self.__convert(val, unit)))<|docstring|>Convert string or value/unit pair to integer<|endoftext|>
7dc49851170735b4b913f4c82e24e132850f65ac6bb1bb0c9745c76a1010b1e2
def ppm(self, val): '\n Convert to ppm\n ' return self.__pnt2unit(val, 'PPM')
Convert to ppm
spec2nii/fileiobase.py
ppm
NeutralKaon/spec2nii
5
python
def ppm(self, val): '\n \n ' return self.__pnt2unit(val, 'PPM')
def ppm(self, val): '\n \n ' return self.__pnt2unit(val, 'PPM')<|docstring|>Convert to ppm<|endoftext|>
d14c15fe67e364c57d88fbe96d4493e85d64003559a11ed7d995c6e4b1d05d9f
def hz(self, val): '\n Convert to Hz\n ' return self.__pnt2unit(val, 'HZ')
Convert to Hz
spec2nii/fileiobase.py
hz
NeutralKaon/spec2nii
5
python
def hz(self, val): '\n \n ' return self.__pnt2unit(val, 'HZ')
def hz(self, val): '\n \n ' return self.__pnt2unit(val, 'HZ')<|docstring|>Convert to Hz<|endoftext|>
2dc7b34042b28998df204280d919d71f801245e081c91f0e2f6b02909b1cd7ba
def percent(self, val): '\n Convert to percent\n ' return self.__pnt2unit(val, 'PERCENT')
Convert to percent
spec2nii/fileiobase.py
percent
NeutralKaon/spec2nii
5
python
def percent(self, val): '\n \n ' return self.__pnt2unit(val, 'PERCENT')
def percent(self, val): '\n \n ' return self.__pnt2unit(val, 'PERCENT')<|docstring|>Convert to percent<|endoftext|>
9dca6dc09705699c698d9d3225e1ad9bbf7c191d2b34b9a0ad3ece20d4d88bd6
def seconds(self, val): '\n Convert to seconds\n ' return self.__pnt2unit(val, 'SEC')
Convert to seconds
spec2nii/fileiobase.py
seconds
NeutralKaon/spec2nii
5
python
def seconds(self, val): '\n \n ' return self.__pnt2unit(val, 'SEC')
def seconds(self, val): '\n \n ' return self.__pnt2unit(val, 'SEC')<|docstring|>Convert to seconds<|endoftext|>
ce65f2f253ed7f59ba220c3f00168e7b641183ebcceabb8c569c2da6293db3da
def sec(self, val): '\n Convert to seconds\n ' return self.__pnt2unit(val, 'SEC')
Convert to seconds
spec2nii/fileiobase.py
sec
NeutralKaon/spec2nii
5
python
def sec(self, val): '\n \n ' return self.__pnt2unit(val, 'SEC')
def sec(self, val): '\n \n ' return self.__pnt2unit(val, 'SEC')<|docstring|>Convert to seconds<|endoftext|>
8926436b5a7f4f52f4a73a6c81f6d8d1654b48cd803243fe061c043252782053
def ms(self, val): '\n Convert to milliseconds (ms)\n ' return self.__pnt2unit(val, 'MS')
Convert to milliseconds (ms)
spec2nii/fileiobase.py
ms
NeutralKaon/spec2nii
5
python
def ms(self, val): '\n \n ' return self.__pnt2unit(val, 'MS')
def ms(self, val): '\n \n ' return self.__pnt2unit(val, 'MS')<|docstring|>Convert to milliseconds (ms)<|endoftext|>
53fd610a40ddddc63154d1e97d024eab5fee14db9fb0e6b85399610601614912
def us(self, val): '\n Convert to microseconds (us)\n ' return self.__pnt2unit(val, 'US')
Convert to microseconds (us)
spec2nii/fileiobase.py
us
NeutralKaon/spec2nii
5
python
def us(self, val): '\n \n ' return self.__pnt2unit(val, 'US')
def us(self, val): '\n \n ' return self.__pnt2unit(val, 'US')<|docstring|>Convert to microseconds (us)<|endoftext|>
62b0b48f25eec4ebae30f51a031b7c4e4e6356b934c565a56749e9ed14aa8068
def unit(self, val, unit): '\n Convert val points to unit\n ' return self.__pnt2unit(val, unit)
Convert val points to unit
spec2nii/fileiobase.py
unit
NeutralKaon/spec2nii
5
python
def unit(self, val, unit): '\n \n ' return self.__pnt2unit(val, unit)
def unit(self, val, unit): '\n \n ' return self.__pnt2unit(val, unit)<|docstring|>Convert val points to unit<|endoftext|>
2db7d97ba196f2c4d91f2e168bc240017a71f53f4e68f5f31671dec06d0c3480
def percent_limits(self): '\n Return tuple of left and right edges in percent\n ' return (0.0, 100.0)
Return tuple of left and right edges in percent
spec2nii/fileiobase.py
percent_limits
NeutralKaon/spec2nii
5
python
def percent_limits(self): '\n \n ' return (0.0, 100.0)
def percent_limits(self): '\n \n ' return (0.0, 100.0)<|docstring|>Return tuple of left and right edges in percent<|endoftext|>
7ed2e64c07280cd50baa1232d3ff18dc0174aefe83a7a40d16a11a705713cd26
def percent_scale(self): '\n Return array of percent values\n ' return np.linspace(0.0, 100.0, self._size)
Return array of percent values
spec2nii/fileiobase.py
percent_scale
NeutralKaon/spec2nii
5
python
def percent_scale(self): '\n \n ' return np.linspace(0.0, 100.0, self._size)
def percent_scale(self): '\n \n ' return np.linspace(0.0, 100.0, self._size)<|docstring|>Return array of percent values<|endoftext|>
e381058f928fd15a4a81c6cac80010e492e338a42fa71be09d08be90371e929e
def ppm_limits(self): '\n Return tuple of left and right edges in ppm\n ' return (self.ppm(0), self.ppm((self._size - 1)))
Return tuple of left and right edges in ppm
spec2nii/fileiobase.py
ppm_limits
NeutralKaon/spec2nii
5
python
def ppm_limits(self): '\n \n ' return (self.ppm(0), self.ppm((self._size - 1)))
def ppm_limits(self): '\n \n ' return (self.ppm(0), self.ppm((self._size - 1)))<|docstring|>Return tuple of left and right edges in ppm<|endoftext|>
ffdc3fec4c3e3f7a1200d21e5922f56ffd1d6bf338d988d88fe3e92d77068bc3
def ppm_scale(self): '\n Return array of ppm values\n ' (x0, x1) = self.ppm_limits() return np.linspace(x0, x1, self._size)
Return array of ppm values
spec2nii/fileiobase.py
ppm_scale
NeutralKaon/spec2nii
5
python
def ppm_scale(self): '\n \n ' (x0, x1) = self.ppm_limits() return np.linspace(x0, x1, self._size)
def ppm_scale(self): '\n \n ' (x0, x1) = self.ppm_limits() return np.linspace(x0, x1, self._size)<|docstring|>Return array of ppm values<|endoftext|>
05cb707567ff638a76e2bc342f09a4e7b67669c308cfd7c5f656f9dac8fa8732
def hz_limits(self): '\n Return tuple of left and right edges in Hz\n ' return (self.hz(0), self.hz((self._size - 1)))
Return tuple of left and right edges in Hz
spec2nii/fileiobase.py
hz_limits
NeutralKaon/spec2nii
5
python
def hz_limits(self): '\n \n ' return (self.hz(0), self.hz((self._size - 1)))
def hz_limits(self): '\n \n ' return (self.hz(0), self.hz((self._size - 1)))<|docstring|>Return tuple of left and right edges in Hz<|endoftext|>
9e6814dc8121831d52bb95927f9ff4cd909ec2d54bb90ea0b2ec52348f043f1a
def hz_scale(self): '\n Return array of Hz values\n ' (x0, x1) = self.hz_limits() return np.linspace(x0, x1, self._size)
Return array of Hz values
spec2nii/fileiobase.py
hz_scale
NeutralKaon/spec2nii
5
python
def hz_scale(self): '\n \n ' (x0, x1) = self.hz_limits() return np.linspace(x0, x1, self._size)
def hz_scale(self): '\n \n ' (x0, x1) = self.hz_limits() return np.linspace(x0, x1, self._size)<|docstring|>Return array of Hz values<|endoftext|>
4f6e8a834316ae1d59b71717fce802706200e4808f3858d90664225f5e38c16a
def sec_limits(self): '\n Return tuple of left and right edges in seconds\n ' return (self.sec(0), self.sec((self._size - 1)))
Return tuple of left and right edges in seconds
spec2nii/fileiobase.py
sec_limits
NeutralKaon/spec2nii
5
python
def sec_limits(self): '\n \n ' return (self.sec(0), self.sec((self._size - 1)))
def sec_limits(self): '\n \n ' return (self.sec(0), self.sec((self._size - 1)))<|docstring|>Return tuple of left and right edges in seconds<|endoftext|>
c9ad3992152bfe67b5df8f2c77f55b6561394e53ac979e48fa60ea44cac4c69b
def sec_scale(self): '\n Return array of seconds values\n ' (x0, x1) = self.sec_limits() return np.linspace(x0, x1, self._size)
Return array of seconds values
spec2nii/fileiobase.py
sec_scale
NeutralKaon/spec2nii
5
python
def sec_scale(self): '\n \n ' (x0, x1) = self.sec_limits() return np.linspace(x0, x1, self._size)
def sec_scale(self): '\n \n ' (x0, x1) = self.sec_limits() return np.linspace(x0, x1, self._size)<|docstring|>Return array of seconds values<|endoftext|>
b4a5acb976432dffc58cda372117c94b37152607337ee08c547209a29df5d4ad
def ms_limits(self): '\n Return tuple of left and right edges in milliseconds\n ' return (self.ms(0), self.ms((self._size - 1)))
Return tuple of left and right edges in milliseconds
spec2nii/fileiobase.py
ms_limits
NeutralKaon/spec2nii
5
python
def ms_limits(self): '\n \n ' return (self.ms(0), self.ms((self._size - 1)))
def ms_limits(self): '\n \n ' return (self.ms(0), self.ms((self._size - 1)))<|docstring|>Return tuple of left and right edges in milliseconds<|endoftext|>
a1063d009d18a255a37df887f29e415b193ba2bff97d2900932de9feeb038e3e
def ms_scale(self): '\n Return array of seconds values\n ' (x0, x1) = self.ms_limits() return np.linspace(x0, x1, self._size)
Return array of seconds values
spec2nii/fileiobase.py
ms_scale
NeutralKaon/spec2nii
5
python
def ms_scale(self): '\n \n ' (x0, x1) = self.ms_limits() return np.linspace(x0, x1, self._size)
def ms_scale(self): '\n \n ' (x0, x1) = self.ms_limits() return np.linspace(x0, x1, self._size)<|docstring|>Return array of seconds values<|endoftext|>
713e90cc0d7d79eff532f8cfe5bdfe3cac72c97dfafda9b7f3fc99b574331447
def us_limits(self): '\n Return tuple of left and right edges in milliseconds\n ' return (self.us(0), self.us((self._size - 1)))
Return tuple of left and right edges in milliseconds
spec2nii/fileiobase.py
us_limits
NeutralKaon/spec2nii
5
python
def us_limits(self): '\n \n ' return (self.us(0), self.us((self._size - 1)))
def us_limits(self): '\n \n ' return (self.us(0), self.us((self._size - 1)))<|docstring|>Return tuple of left and right edges in milliseconds<|endoftext|>
156e62df062e0faf951a06b0c579ab1fa38fcd7f7f357506313962cf3b46f0a6
def us_scale(self): '\n Return array of seconds values\n ' (x0, x1) = self.us_limits() return np.linspace(x0, x1, self._size)
Return array of seconds values
spec2nii/fileiobase.py
us_scale
NeutralKaon/spec2nii
5
python
def us_scale(self): '\n \n ' (x0, x1) = self.us_limits() return np.linspace(x0, x1, self._size)
def us_scale(self): '\n \n ' (x0, x1) = self.us_limits() return np.linspace(x0, x1, self._size)<|docstring|>Return array of seconds values<|endoftext|>
31e6e1dc5db78d994e940378a687b8dec48211c241b6ba28f0ee68c9e88772aa
def __setdimandshape__(self): ' Set the the ndim and shape attributes from fshape ' self.ndim = len(self.fshape) self.shape = tuple([self.fshape[i] for i in self.order])
Set the the ndim and shape attributes from fshape
spec2nii/fileiobase.py
__setdimandshape__
NeutralKaon/spec2nii
5
python
def __setdimandshape__(self): ' ' self.ndim = len(self.fshape) self.shape = tuple([self.fshape[i] for i in self.order])
def __setdimandshape__(self): ' ' self.ndim = len(self.fshape) self.shape = tuple([self.fshape[i] for i in self.order])<|docstring|>Set the the ndim and shape attributes from fshape<|endoftext|>
029ea59ed308ce3848fd1938ba8bd7befbb6d3163bd7e5c0f9d89d7a13af1c2d
def __copy__(self): '\n create a copy\n ' return self.__fcopy__(self, self.order)
create a copy
spec2nii/fileiobase.py
__copy__
NeutralKaon/spec2nii
5
python
def __copy__(self): '\n \n ' return self.__fcopy__(self, self.order)
def __copy__(self): '\n \n ' return self.__fcopy__(self, self.order)<|docstring|>create a copy<|endoftext|>
0193bef117998990d59fef98339cca205bf6123b1e9a287cc33845b6066dedc0
def __getitem__(self, key): '\n x.__getitem__(y) <==> x[y]\n ' if (not isinstance(key, tuple)): rlist = [key] else: rlist = list(key) while (Ellipsis in rlist): i = rlist.index(Ellipsis) rlist.pop(i) for j in range((self.ndim - len(rlist))): rlist.insert(i, slice(None)) if (len(rlist) > self.ndim): raise IndexError('invalid index') for (i, v) in enumerate(rlist): if (not isinstance(v, slice)): if (v >= self.shape[i]): raise IndexError(('index(%s) out of range(0 <= index < %s) in dimension %s' % (v, (self.shape[i] - 1), i))) if (v <= (((- 1) * self.shape[i]) - 1)): raise IndexError(('index(%s) out of range(0 <= index < %s) in dimension %s' % (v, (self.shape[i] - 1), i))) if (v < 0): w = (self.shape[i] + v) rlist[i] = slice(w, (w + 1), 1) else: rlist[i] = slice(v, (v + 1), 1) for i in range(len(rlist), self.ndim): rlist.append(slice(None)) frlist = [rlist[self.order.index(i)] for i in range(self.ndim)] data = self.__fgetitem__(tuple(frlist)) if (data.shape != (0,)): return np.squeeze(data.transpose(self.order)) else: return data
x.__getitem__(y) <==> x[y]
spec2nii/fileiobase.py
__getitem__
NeutralKaon/spec2nii
5
python
def __getitem__(self, key): '\n \n ' if (not isinstance(key, tuple)): rlist = [key] else: rlist = list(key) while (Ellipsis in rlist): i = rlist.index(Ellipsis) rlist.pop(i) for j in range((self.ndim - len(rlist))): rlist.insert(i, slice(None)) if (len(rlist) > self.ndim): raise IndexError('invalid index') for (i, v) in enumerate(rlist): if (not isinstance(v, slice)): if (v >= self.shape[i]): raise IndexError(('index(%s) out of range(0 <= index < %s) in dimension %s' % (v, (self.shape[i] - 1), i))) if (v <= (((- 1) * self.shape[i]) - 1)): raise IndexError(('index(%s) out of range(0 <= index < %s) in dimension %s' % (v, (self.shape[i] - 1), i))) if (v < 0): w = (self.shape[i] + v) rlist[i] = slice(w, (w + 1), 1) else: rlist[i] = slice(v, (v + 1), 1) for i in range(len(rlist), self.ndim): rlist.append(slice(None)) frlist = [rlist[self.order.index(i)] for i in range(self.ndim)] data = self.__fgetitem__(tuple(frlist)) if (data.shape != (0,)): return np.squeeze(data.transpose(self.order)) else: return data
def __getitem__(self, key): '\n \n ' if (not isinstance(key, tuple)): rlist = [key] else: rlist = list(key) while (Ellipsis in rlist): i = rlist.index(Ellipsis) rlist.pop(i) for j in range((self.ndim - len(rlist))): rlist.insert(i, slice(None)) if (len(rlist) > self.ndim): raise IndexError('invalid index') for (i, v) in enumerate(rlist): if (not isinstance(v, slice)): if (v >= self.shape[i]): raise IndexError(('index(%s) out of range(0 <= index < %s) in dimension %s' % (v, (self.shape[i] - 1), i))) if (v <= (((- 1) * self.shape[i]) - 1)): raise IndexError(('index(%s) out of range(0 <= index < %s) in dimension %s' % (v, (self.shape[i] - 1), i))) if (v < 0): w = (self.shape[i] + v) rlist[i] = slice(w, (w + 1), 1) else: rlist[i] = slice(v, (v + 1), 1) for i in range(len(rlist), self.ndim): rlist.append(slice(None)) frlist = [rlist[self.order.index(i)] for i in range(self.ndim)] data = self.__fgetitem__(tuple(frlist)) if (data.shape != (0,)): return np.squeeze(data.transpose(self.order)) else: return data<|docstring|>x.__getitem__(y) <==> x[y]<|endoftext|>
afbbc775c37550a39501750aa139a57dd6f79ce97fc7225cb21657c4204e5c29
def __len__(self): '\n x._len__ <==> len(x)\n ' return self.shape[0]
x._len__ <==> len(x)
spec2nii/fileiobase.py
__len__
NeutralKaon/spec2nii
5
python
def __len__(self): '\n \n ' return self.shape[0]
def __len__(self): '\n \n ' return self.shape[0]<|docstring|>x._len__ <==> len(x)<|endoftext|>
0cf7b2a4c54cc34ca2348cb7207e3a28fa05f47cc4c4569dc17bf82e321f0e01
def __iter__(self): ' x.__iter__() <==> iter(x) ' for index in range(0, self.shape[0]): (yield self[index])
x.__iter__() <==> iter(x)
spec2nii/fileiobase.py
__iter__
NeutralKaon/spec2nii
5
python
def __iter__(self): ' ' for index in range(0, self.shape[0]): (yield self[index])
def __iter__(self): ' ' for index in range(0, self.shape[0]): (yield self[index])<|docstring|>x.__iter__() <==> iter(x)<|endoftext|>
df304deb9fd910a6c72df2882a0d8ea531e26ac965e8c964a84639b599131d4c
def swapaxes(self, axis1, axis2): '\n Return object with `axis1` and `axis2` interchanged.\n ' (axis1, axis2) = (int(axis1), int(axis2)) if (axis1 < 0): axis1 = (self.ndim - axis1) if (axis2 < 0): axis2 = (self.ndim - axis2) if (axis1 >= self.ndim): raise ValueError('bad axis1 argument to swapaxes') if (axis2 >= self.ndim): raise ValueError('bad axis2 argument to swapaxes') order = list(self.order) (order[axis1], order[axis2]) = (order[axis2], order[axis1]) n = self.__fcopy__(order=order) return n
Return object with `axis1` and `axis2` interchanged.
spec2nii/fileiobase.py
swapaxes
NeutralKaon/spec2nii
5
python
def swapaxes(self, axis1, axis2): '\n \n ' (axis1, axis2) = (int(axis1), int(axis2)) if (axis1 < 0): axis1 = (self.ndim - axis1) if (axis2 < 0): axis2 = (self.ndim - axis2) if (axis1 >= self.ndim): raise ValueError('bad axis1 argument to swapaxes') if (axis2 >= self.ndim): raise ValueError('bad axis2 argument to swapaxes') order = list(self.order) (order[axis1], order[axis2]) = (order[axis2], order[axis1]) n = self.__fcopy__(order=order) return n
def swapaxes(self, axis1, axis2): '\n \n ' (axis1, axis2) = (int(axis1), int(axis2)) if (axis1 < 0): axis1 = (self.ndim - axis1) if (axis2 < 0): axis2 = (self.ndim - axis2) if (axis1 >= self.ndim): raise ValueError('bad axis1 argument to swapaxes') if (axis2 >= self.ndim): raise ValueError('bad axis2 argument to swapaxes') order = list(self.order) (order[axis1], order[axis2]) = (order[axis2], order[axis1]) n = self.__fcopy__(order=order) return n<|docstring|>Return object with `axis1` and `axis2` interchanged.<|endoftext|>
8e0e6f386f36d4a423b4618f0ede4b90c1fc97e422c7218175088b4e0d59b47f
def transpose(self, *axes): "\n Return object with axes transposed.\n\n Parameters\n ----------\n axes : None, tuple or ints, or `n` ints\n * None or no arguments: reverse order of the axes\n\n * tuple of ints: `i` in the `j`-th place in the tuples means the\n 'i'-th axis becomes the new objects `j`-th axis.\n\n * `n` ints: same as an n-tuple.\n\n Returns\n -------\n out : data_nd object\n Object whose axes are permuted.\n\n " if (axes == ()): axes = range(self.ndim)[::(- 1)] if (len(axes) == 1): axes = axes[0] try: axes = [int(i) for i in axes] except Exception: raise TypeError('an integer is required') if (len(axes) != self.ndim): raise ValueError("axes don't match array") for (i, v) in enumerate(axes): if (v < 0): axes[i] = (self.ndim + v) for v in axes: if (v >= self.ndim): raise ValueError('invalid axis for this array') if (len(set(axes)) != self.ndim): raise ValueError('repeated axis in tranpose') return self.__fcopy__(order=tuple([self.order[i] for i in axes]))
Return object with axes transposed. Parameters ---------- axes : None, tuple or ints, or `n` ints * None or no arguments: reverse order of the axes * tuple of ints: `i` in the `j`-th place in the tuples means the 'i'-th axis becomes the new objects `j`-th axis. * `n` ints: same as an n-tuple. Returns ------- out : data_nd object Object whose axes are permuted.
spec2nii/fileiobase.py
transpose
NeutralKaon/spec2nii
5
python
def transpose(self, *axes): "\n Return object with axes transposed.\n\n Parameters\n ----------\n axes : None, tuple or ints, or `n` ints\n * None or no arguments: reverse order of the axes\n\n * tuple of ints: `i` in the `j`-th place in the tuples means the\n 'i'-th axis becomes the new objects `j`-th axis.\n\n * `n` ints: same as an n-tuple.\n\n Returns\n -------\n out : data_nd object\n Object whose axes are permuted.\n\n " if (axes == ()): axes = range(self.ndim)[::(- 1)] if (len(axes) == 1): axes = axes[0] try: axes = [int(i) for i in axes] except Exception: raise TypeError('an integer is required') if (len(axes) != self.ndim): raise ValueError("axes don't match array") for (i, v) in enumerate(axes): if (v < 0): axes[i] = (self.ndim + v) for v in axes: if (v >= self.ndim): raise ValueError('invalid axis for this array') if (len(set(axes)) != self.ndim): raise ValueError('repeated axis in tranpose') return self.__fcopy__(order=tuple([self.order[i] for i in axes]))
def transpose(self, *axes): "\n Return object with axes transposed.\n\n Parameters\n ----------\n axes : None, tuple or ints, or `n` ints\n * None or no arguments: reverse order of the axes\n\n * tuple of ints: `i` in the `j`-th place in the tuples means the\n 'i'-th axis becomes the new objects `j`-th axis.\n\n * `n` ints: same as an n-tuple.\n\n Returns\n -------\n out : data_nd object\n Object whose axes are permuted.\n\n " if (axes == ()): axes = range(self.ndim)[::(- 1)] if (len(axes) == 1): axes = axes[0] try: axes = [int(i) for i in axes] except Exception: raise TypeError('an integer is required') if (len(axes) != self.ndim): raise ValueError("axes don't match array") for (i, v) in enumerate(axes): if (v < 0): axes[i] = (self.ndim + v) for v in axes: if (v >= self.ndim): raise ValueError('invalid axis for this array') if (len(set(axes)) != self.ndim): raise ValueError('repeated axis in tranpose') return self.__fcopy__(order=tuple([self.order[i] for i in axes]))<|docstring|>Return object with axes transposed. Parameters ---------- axes : None, tuple or ints, or `n` ints * None or no arguments: reverse order of the axes * tuple of ints: `i` in the `j`-th place in the tuples means the 'i'-th axis becomes the new objects `j`-th axis. * `n` ints: same as an n-tuple. Returns ------- out : data_nd object Object whose axes are permuted.<|endoftext|>
8829f34e32a5fbf4929a37cc5ccc70e74214c7d915a50ddbbdda58f0422d5331
def tearDown(self): ' Be a good person and always clean up unit test data ' if exists(self.filename): unlink(self.filename)
Be a good person and always clean up unit test data
py23/tests/base.py
tearDown
cooperlees/py23
1
python
def tearDown(self): ' ' if exists(self.filename): unlink(self.filename)
def tearDown(self): ' ' if exists(self.filename): unlink(self.filename)<|docstring|>Be a good person and always clean up unit test data<|endoftext|>
06a38400f17d768935325123d960adc2188d2cf3081b989f94a783276a5497e2
def get_pecan_config(): 'Returns the pecan config.' filename = app_config.__file__.replace('.pyc', '.py') return pecan.configuration.conf_from_file(filename)
Returns the pecan config.
starfish/frame_api/app.py
get_pecan_config
JayLiu7319/Starfish
0
python
def get_pecan_config(): filename = app_config.__file__.replace('.pyc', '.py') return pecan.configuration.conf_from_file(filename)
def get_pecan_config(): filename = app_config.__file__.replace('.pyc', '.py') return pecan.configuration.conf_from_file(filename)<|docstring|>Returns the pecan config.<|endoftext|>
26aeef060412e89f8de41eb0a9209ea31226004b1d7b44da94dddc63a5743a8e
def setup_app(pecan_config=None, debug=True, argv=None): 'Creates and returns a pecan wsgi app.' if (argv is None): argv = sys.argv octavia_service.prepare_service(argv) cfg.CONF.log_opt_values(LOG, logging.DEBUG) if (not pecan_config): pecan_config = get_pecan_config() pecan.configuration.set_config(dict(pecan_config), overwrite=True) return pecan.make_app(pecan_config.app.root, debug=debug, hooks=pecan_config.app.hooks, wsme=pecan_config.wsme)
Creates and returns a pecan wsgi app.
starfish/frame_api/app.py
setup_app
JayLiu7319/Starfish
0
python
def setup_app(pecan_config=None, debug=True, argv=None): if (argv is None): argv = sys.argv octavia_service.prepare_service(argv) cfg.CONF.log_opt_values(LOG, logging.DEBUG) if (not pecan_config): pecan_config = get_pecan_config() pecan.configuration.set_config(dict(pecan_config), overwrite=True) return pecan.make_app(pecan_config.app.root, debug=debug, hooks=pecan_config.app.hooks, wsme=pecan_config.wsme)
def setup_app(pecan_config=None, debug=True, argv=None): if (argv is None): argv = sys.argv octavia_service.prepare_service(argv) cfg.CONF.log_opt_values(LOG, logging.DEBUG) if (not pecan_config): pecan_config = get_pecan_config() pecan.configuration.set_config(dict(pecan_config), overwrite=True) return pecan.make_app(pecan_config.app.root, debug=debug, hooks=pecan_config.app.hooks, wsme=pecan_config.wsme)<|docstring|>Creates and returns a pecan wsgi app.<|endoftext|>
571f4c0ae6a05a8d2c3a732a559b7892ba60f492bf40be1b1441362a418033ae
def header(fn): '\n Custom header for isomiR-SEA importer.\n\n Args:\n *fn (str)*: file name with isomiR-SEA GFF output\n\n Returns:\n *(str)*: isomiR-SEA header string.\n ' h = '' return h
Custom header for isomiR-SEA importer. Args: *fn (str)*: file name with isomiR-SEA GFF output Returns: *(str)*: isomiR-SEA header string.
mirtop/importer/isomirsea.py
header
srinivas32/mirtop
0
python
def header(fn): '\n Custom header for isomiR-SEA importer.\n\n Args:\n *fn (str)*: file name with isomiR-SEA GFF output\n\n Returns:\n *(str)*: isomiR-SEA header string.\n ' h = return h
def header(fn): '\n Custom header for isomiR-SEA importer.\n\n Args:\n *fn (str)*: file name with isomiR-SEA GFF output\n\n Returns:\n *(str)*: isomiR-SEA header string.\n ' h = return h<|docstring|>Custom header for isomiR-SEA importer. Args: *fn (str)*: file name with isomiR-SEA GFF output Returns: *(str)*: isomiR-SEA header string.<|endoftext|>
50e335e5b6ed1ffa722a220a7ae21d04a82582269f188be54ac1e25dd07efb5d
def read_file(fn, args): '\n Read isomiR-SEA file and convert to mirtop GFF format.\n\n Args:\n *fn(str)*: file name with isomiR-SEA output information.\n\n *database(str)*: database name.\n\n *args(namedtuple)*: arguments from command line.\n See *mirtop.libs.parse.add_subparser_gff()*.\n\n Returns:\n *reads (nested dicts)*:gff_list has the format as\n defined in *mirtop.gff.body.read()*.\n\n ' database = args.database gtf = args.gtf sep = (' ' if (args.out_format == 'gtf') else '=') map_mir = mapper.read_gtf_to_mirna(gtf) reads = defaultdict(dict) reads_in = 0 sample = os.path.splitext(os.path.basename(fn))[0] hits = _get_hits(fn) logger.debug(('ISOMIRSEA::SAMPLE::%s' % sample)) with open(fn) as handle: for line in handle: cols = line.strip().split('\t') attr = read_attributes(line, '=') query_name = attr['TS'] query_sequence = attr['TS'].replace('U', 'T') start = int(cols[3]) end = int(cols[4]) isomirseq_iso = attr['ISO'] if ((query_name not in reads) and (query_sequence == None)): continue if (query_sequence and (query_sequence.find('N') > (- 1))): continue counts = attr['TC'] chrom = cols[0] cigar = attr['CI'].replace('U', 'T') idu = make_id(query_sequence) isoformat = cigar2variants(cigar, query_sequence, attr['ISO']) logger.debug('\nISOMIRSEA::NEW::query: {query_sequence}\n precursor {chrom}\n name: {query_name}\n idu: {idu}\n start: {start}\n cigar: {cigar}\n iso: {isoformat}\n variant: {isoformat}'.format(**locals())) source = ('isomiR' if (isoformat != 'NA') else 'ref_miRNA') strand = '+' database = cols[1] mirName = attr['MIN'].split()[0] preName = attr['PIN'].split()[0] score = '.' Filter = attr['FILTER'] isotag = attr['ISO'] (tchrom, tstart) = _genomic2transcript(map_mir[mirName], chrom, start) start = (start if (not tstart) else tstart) chrom = (chrom if (not tstart) else tchrom) end = (start + len(query_sequence)) hit = hits[idu] fields = {'seq_name': query_sequence, 'idseq': idu, 'name': mirName, 'parent': preName, 'variant': isoformat, 'cigar': cigar, 'counts': counts, 'filter': Filter, 'hits': hit, 'chrom': chrom, 'start': start, 'end': end, 'database': database, 'source': source, 'score': score, 'strand': strand} line = feature(fields).line if args.add_extra: extra = variant_with_nt(line, args.precursors, args.matures) line = ('%s Changes %s;' % (line, extra)) line = paste_columns(feature(line), sep=sep) if (start not in reads[chrom]): reads[chrom][start] = [] if (Filter == 'Pass'): reads_in += 1 reads[chrom][start].append([idu, chrom, counts, sample, line]) logger.info(('Hits: %s' % reads_in)) return reads
Read isomiR-SEA file and convert to mirtop GFF format. Args: *fn(str)*: file name with isomiR-SEA output information. *database(str)*: database name. *args(namedtuple)*: arguments from command line. See *mirtop.libs.parse.add_subparser_gff()*. Returns: *reads (nested dicts)*:gff_list has the format as defined in *mirtop.gff.body.read()*.
mirtop/importer/isomirsea.py
read_file
srinivas32/mirtop
0
python
def read_file(fn, args): '\n Read isomiR-SEA file and convert to mirtop GFF format.\n\n Args:\n *fn(str)*: file name with isomiR-SEA output information.\n\n *database(str)*: database name.\n\n *args(namedtuple)*: arguments from command line.\n See *mirtop.libs.parse.add_subparser_gff()*.\n\n Returns:\n *reads (nested dicts)*:gff_list has the format as\n defined in *mirtop.gff.body.read()*.\n\n ' database = args.database gtf = args.gtf sep = (' ' if (args.out_format == 'gtf') else '=') map_mir = mapper.read_gtf_to_mirna(gtf) reads = defaultdict(dict) reads_in = 0 sample = os.path.splitext(os.path.basename(fn))[0] hits = _get_hits(fn) logger.debug(('ISOMIRSEA::SAMPLE::%s' % sample)) with open(fn) as handle: for line in handle: cols = line.strip().split('\t') attr = read_attributes(line, '=') query_name = attr['TS'] query_sequence = attr['TS'].replace('U', 'T') start = int(cols[3]) end = int(cols[4]) isomirseq_iso = attr['ISO'] if ((query_name not in reads) and (query_sequence == None)): continue if (query_sequence and (query_sequence.find('N') > (- 1))): continue counts = attr['TC'] chrom = cols[0] cigar = attr['CI'].replace('U', 'T') idu = make_id(query_sequence) isoformat = cigar2variants(cigar, query_sequence, attr['ISO']) logger.debug('\nISOMIRSEA::NEW::query: {query_sequence}\n precursor {chrom}\n name: {query_name}\n idu: {idu}\n start: {start}\n cigar: {cigar}\n iso: {isoformat}\n variant: {isoformat}'.format(**locals())) source = ('isomiR' if (isoformat != 'NA') else 'ref_miRNA') strand = '+' database = cols[1] mirName = attr['MIN'].split()[0] preName = attr['PIN'].split()[0] score = '.' Filter = attr['FILTER'] isotag = attr['ISO'] (tchrom, tstart) = _genomic2transcript(map_mir[mirName], chrom, start) start = (start if (not tstart) else tstart) chrom = (chrom if (not tstart) else tchrom) end = (start + len(query_sequence)) hit = hits[idu] fields = {'seq_name': query_sequence, 'idseq': idu, 'name': mirName, 'parent': preName, 'variant': isoformat, 'cigar': cigar, 'counts': counts, 'filter': Filter, 'hits': hit, 'chrom': chrom, 'start': start, 'end': end, 'database': database, 'source': source, 'score': score, 'strand': strand} line = feature(fields).line if args.add_extra: extra = variant_with_nt(line, args.precursors, args.matures) line = ('%s Changes %s;' % (line, extra)) line = paste_columns(feature(line), sep=sep) if (start not in reads[chrom]): reads[chrom][start] = [] if (Filter == 'Pass'): reads_in += 1 reads[chrom][start].append([idu, chrom, counts, sample, line]) logger.info(('Hits: %s' % reads_in)) return reads
def read_file(fn, args): '\n Read isomiR-SEA file and convert to mirtop GFF format.\n\n Args:\n *fn(str)*: file name with isomiR-SEA output information.\n\n *database(str)*: database name.\n\n *args(namedtuple)*: arguments from command line.\n See *mirtop.libs.parse.add_subparser_gff()*.\n\n Returns:\n *reads (nested dicts)*:gff_list has the format as\n defined in *mirtop.gff.body.read()*.\n\n ' database = args.database gtf = args.gtf sep = (' ' if (args.out_format == 'gtf') else '=') map_mir = mapper.read_gtf_to_mirna(gtf) reads = defaultdict(dict) reads_in = 0 sample = os.path.splitext(os.path.basename(fn))[0] hits = _get_hits(fn) logger.debug(('ISOMIRSEA::SAMPLE::%s' % sample)) with open(fn) as handle: for line in handle: cols = line.strip().split('\t') attr = read_attributes(line, '=') query_name = attr['TS'] query_sequence = attr['TS'].replace('U', 'T') start = int(cols[3]) end = int(cols[4]) isomirseq_iso = attr['ISO'] if ((query_name not in reads) and (query_sequence == None)): continue if (query_sequence and (query_sequence.find('N') > (- 1))): continue counts = attr['TC'] chrom = cols[0] cigar = attr['CI'].replace('U', 'T') idu = make_id(query_sequence) isoformat = cigar2variants(cigar, query_sequence, attr['ISO']) logger.debug('\nISOMIRSEA::NEW::query: {query_sequence}\n precursor {chrom}\n name: {query_name}\n idu: {idu}\n start: {start}\n cigar: {cigar}\n iso: {isoformat}\n variant: {isoformat}'.format(**locals())) source = ('isomiR' if (isoformat != 'NA') else 'ref_miRNA') strand = '+' database = cols[1] mirName = attr['MIN'].split()[0] preName = attr['PIN'].split()[0] score = '.' Filter = attr['FILTER'] isotag = attr['ISO'] (tchrom, tstart) = _genomic2transcript(map_mir[mirName], chrom, start) start = (start if (not tstart) else tstart) chrom = (chrom if (not tstart) else tchrom) end = (start + len(query_sequence)) hit = hits[idu] fields = {'seq_name': query_sequence, 'idseq': idu, 'name': mirName, 'parent': preName, 'variant': isoformat, 'cigar': cigar, 'counts': counts, 'filter': Filter, 'hits': hit, 'chrom': chrom, 'start': start, 'end': end, 'database': database, 'source': source, 'score': score, 'strand': strand} line = feature(fields).line if args.add_extra: extra = variant_with_nt(line, args.precursors, args.matures) line = ('%s Changes %s;' % (line, extra)) line = paste_columns(feature(line), sep=sep) if (start not in reads[chrom]): reads[chrom][start] = [] if (Filter == 'Pass'): reads_in += 1 reads[chrom][start].append([idu, chrom, counts, sample, line]) logger.info(('Hits: %s' % reads_in)) return reads<|docstring|>Read isomiR-SEA file and convert to mirtop GFF format. Args: *fn(str)*: file name with isomiR-SEA output information. *database(str)*: database name. *args(namedtuple)*: arguments from command line. See *mirtop.libs.parse.add_subparser_gff()*. Returns: *reads (nested dicts)*:gff_list has the format as defined in *mirtop.gff.body.read()*.<|endoftext|>
3090e5ab3702cf2e720dc560908716d31d6c358b51eca8a8a62c4aad16c90fd2
def cigar2variants(cigar, sequence, tag): 'From cigar to Variants in GFF format' pos = 0 iso5p = 0 logger.debug(('\nISOMIRSEA:: expanded: %s' % expand_cigar(cigar))) for l in expand_cigar(cigar): if (l == 'I'): iso5p -= 1 elif (l == 'D'): iso5p += 1 else: break iso3p = 0 for l in reversed(expand_cigar(cigar)): if (l == 'I'): iso3p += 1 elif (l == 'D'): iso3p -= 1 else: break isosnp = [] for l in expand_cigar(cigar): if (l in ['A', 'T', 'C', 'G']): isosnp.append([pos, sequence[pos], l]) if (l in ['D']): continue pos += 1 iso5p = (('iso_5p:%s' % _fix(iso5p)) if iso5p else '') if ((tag[(- 1)] == 'T') or (iso3p < 0)): iso3p = (('iso_3p:%s' % _fix(iso3p)) if iso3p else '') else: iso3p = (('iso_add3p:%s' % iso3p) if iso3p else '') variant = '' for iso in [iso5p, iso3p, _define_snp(isosnp)]: if iso: variant += ('%s,' % iso) variant = ('NA;' if (not variant) else variant) return variant[:(- 1)]
From cigar to Variants in GFF format
mirtop/importer/isomirsea.py
cigar2variants
srinivas32/mirtop
0
python
def cigar2variants(cigar, sequence, tag): pos = 0 iso5p = 0 logger.debug(('\nISOMIRSEA:: expanded: %s' % expand_cigar(cigar))) for l in expand_cigar(cigar): if (l == 'I'): iso5p -= 1 elif (l == 'D'): iso5p += 1 else: break iso3p = 0 for l in reversed(expand_cigar(cigar)): if (l == 'I'): iso3p += 1 elif (l == 'D'): iso3p -= 1 else: break isosnp = [] for l in expand_cigar(cigar): if (l in ['A', 'T', 'C', 'G']): isosnp.append([pos, sequence[pos], l]) if (l in ['D']): continue pos += 1 iso5p = (('iso_5p:%s' % _fix(iso5p)) if iso5p else ) if ((tag[(- 1)] == 'T') or (iso3p < 0)): iso3p = (('iso_3p:%s' % _fix(iso3p)) if iso3p else ) else: iso3p = (('iso_add3p:%s' % iso3p) if iso3p else ) variant = for iso in [iso5p, iso3p, _define_snp(isosnp)]: if iso: variant += ('%s,' % iso) variant = ('NA;' if (not variant) else variant) return variant[:(- 1)]
def cigar2variants(cigar, sequence, tag): pos = 0 iso5p = 0 logger.debug(('\nISOMIRSEA:: expanded: %s' % expand_cigar(cigar))) for l in expand_cigar(cigar): if (l == 'I'): iso5p -= 1 elif (l == 'D'): iso5p += 1 else: break iso3p = 0 for l in reversed(expand_cigar(cigar)): if (l == 'I'): iso3p += 1 elif (l == 'D'): iso3p -= 1 else: break isosnp = [] for l in expand_cigar(cigar): if (l in ['A', 'T', 'C', 'G']): isosnp.append([pos, sequence[pos], l]) if (l in ['D']): continue pos += 1 iso5p = (('iso_5p:%s' % _fix(iso5p)) if iso5p else ) if ((tag[(- 1)] == 'T') or (iso3p < 0)): iso3p = (('iso_3p:%s' % _fix(iso3p)) if iso3p else ) else: iso3p = (('iso_add3p:%s' % iso3p) if iso3p else ) variant = for iso in [iso5p, iso3p, _define_snp(isosnp)]: if iso: variant += ('%s,' % iso) variant = ('NA;' if (not variant) else variant) return variant[:(- 1)]<|docstring|>From cigar to Variants in GFF format<|endoftext|>
44f163bbd35312ea967687a16089a2832567b632d1a8256b6f2049e606a46afa
def __init__(self, kube_client: client.CoreV1Api=None, in_cluster: bool=True, cluster_context: Optional[str]=None, extract_xcom: bool=False): '\n Deprecated class for launching pods. please use\n airflow.providers.cncf.kubernetes.utils.pod_launcher.PodLauncher instead\n Creates the launcher.\n\n :param kube_client: kubernetes client\n :param in_cluster: whether we are in cluster\n :param cluster_context: context of the cluster\n :param extract_xcom: whether we should extract xcom\n ' super().__init__() self._client = (kube_client or get_kube_client(in_cluster=in_cluster, cluster_context=cluster_context)) self._watch = watch.Watch() self.extract_xcom = extract_xcom
Deprecated class for launching pods. please use airflow.providers.cncf.kubernetes.utils.pod_launcher.PodLauncher instead Creates the launcher. :param kube_client: kubernetes client :param in_cluster: whether we are in cluster :param cluster_context: context of the cluster :param extract_xcom: whether we should extract xcom
airflow/kubernetes/pod_launcher_deprecated.py
__init__
legau/airflow
27
python
def __init__(self, kube_client: client.CoreV1Api=None, in_cluster: bool=True, cluster_context: Optional[str]=None, extract_xcom: bool=False): '\n Deprecated class for launching pods. please use\n airflow.providers.cncf.kubernetes.utils.pod_launcher.PodLauncher instead\n Creates the launcher.\n\n :param kube_client: kubernetes client\n :param in_cluster: whether we are in cluster\n :param cluster_context: context of the cluster\n :param extract_xcom: whether we should extract xcom\n ' super().__init__() self._client = (kube_client or get_kube_client(in_cluster=in_cluster, cluster_context=cluster_context)) self._watch = watch.Watch() self.extract_xcom = extract_xcom
def __init__(self, kube_client: client.CoreV1Api=None, in_cluster: bool=True, cluster_context: Optional[str]=None, extract_xcom: bool=False): '\n Deprecated class for launching pods. please use\n airflow.providers.cncf.kubernetes.utils.pod_launcher.PodLauncher instead\n Creates the launcher.\n\n :param kube_client: kubernetes client\n :param in_cluster: whether we are in cluster\n :param cluster_context: context of the cluster\n :param extract_xcom: whether we should extract xcom\n ' super().__init__() self._client = (kube_client or get_kube_client(in_cluster=in_cluster, cluster_context=cluster_context)) self._watch = watch.Watch() self.extract_xcom = extract_xcom<|docstring|>Deprecated class for launching pods. please use airflow.providers.cncf.kubernetes.utils.pod_launcher.PodLauncher instead Creates the launcher. :param kube_client: kubernetes client :param in_cluster: whether we are in cluster :param cluster_context: context of the cluster :param extract_xcom: whether we should extract xcom<|endoftext|>
dc7f2f60f4028251f55e16285294b7fd2f772e0432002e7665ac378692d95f50
def run_pod_async(self, pod: V1Pod, **kwargs): 'Runs POD asynchronously' pod_mutation_hook(pod) sanitized_pod = self._client.api_client.sanitize_for_serialization(pod) json_pod = json.dumps(sanitized_pod, indent=2) self.log.debug('Pod Creation Request: \n%s', json_pod) try: resp = self._client.create_namespaced_pod(body=sanitized_pod, namespace=pod.metadata.namespace, **kwargs) self.log.debug('Pod Creation Response: %s', resp) except Exception as e: self.log.exception('Exception when attempting to create Namespaced Pod: %s', json_pod) raise e return resp
Runs POD asynchronously
airflow/kubernetes/pod_launcher_deprecated.py
run_pod_async
legau/airflow
27
python
def run_pod_async(self, pod: V1Pod, **kwargs): pod_mutation_hook(pod) sanitized_pod = self._client.api_client.sanitize_for_serialization(pod) json_pod = json.dumps(sanitized_pod, indent=2) self.log.debug('Pod Creation Request: \n%s', json_pod) try: resp = self._client.create_namespaced_pod(body=sanitized_pod, namespace=pod.metadata.namespace, **kwargs) self.log.debug('Pod Creation Response: %s', resp) except Exception as e: self.log.exception('Exception when attempting to create Namespaced Pod: %s', json_pod) raise e return resp
def run_pod_async(self, pod: V1Pod, **kwargs): pod_mutation_hook(pod) sanitized_pod = self._client.api_client.sanitize_for_serialization(pod) json_pod = json.dumps(sanitized_pod, indent=2) self.log.debug('Pod Creation Request: \n%s', json_pod) try: resp = self._client.create_namespaced_pod(body=sanitized_pod, namespace=pod.metadata.namespace, **kwargs) self.log.debug('Pod Creation Response: %s', resp) except Exception as e: self.log.exception('Exception when attempting to create Namespaced Pod: %s', json_pod) raise e return resp<|docstring|>Runs POD asynchronously<|endoftext|>
48f47bc37088cd587a64d6968639bf23a941d5f3be4d74bdd99d6ab5dbbf0a06
def delete_pod(self, pod: V1Pod): 'Deletes POD' try: self._client.delete_namespaced_pod(pod.metadata.name, pod.metadata.namespace, body=client.V1DeleteOptions()) except ApiException as e: if (e.status != 404): raise
Deletes POD
airflow/kubernetes/pod_launcher_deprecated.py
delete_pod
legau/airflow
27
python
def delete_pod(self, pod: V1Pod): try: self._client.delete_namespaced_pod(pod.metadata.name, pod.metadata.namespace, body=client.V1DeleteOptions()) except ApiException as e: if (e.status != 404): raise
def delete_pod(self, pod: V1Pod): try: self._client.delete_namespaced_pod(pod.metadata.name, pod.metadata.namespace, body=client.V1DeleteOptions()) except ApiException as e: if (e.status != 404): raise<|docstring|>Deletes POD<|endoftext|>
c45cd2a9882b3418fe094bfff32791d1bddbd7d75101ad4194a108502d7be575
def start_pod(self, pod: V1Pod, startup_timeout: int=120): '\n Launches the pod synchronously and waits for completion.\n\n :param pod:\n :param startup_timeout: Timeout for startup of the pod (if pod is pending for too long, fails task)\n :return:\n ' resp = self.run_pod_async(pod) curr_time = dt.now() if (resp.status.start_time is None): while self.pod_not_started(pod): self.log.warning('Pod not yet started: %s', pod.metadata.name) delta = (dt.now() - curr_time) if (delta.total_seconds() >= startup_timeout): raise AirflowException('Pod took too long to start') time.sleep(1)
Launches the pod synchronously and waits for completion. :param pod: :param startup_timeout: Timeout for startup of the pod (if pod is pending for too long, fails task) :return:
airflow/kubernetes/pod_launcher_deprecated.py
start_pod
legau/airflow
27
python
def start_pod(self, pod: V1Pod, startup_timeout: int=120): '\n Launches the pod synchronously and waits for completion.\n\n :param pod:\n :param startup_timeout: Timeout for startup of the pod (if pod is pending for too long, fails task)\n :return:\n ' resp = self.run_pod_async(pod) curr_time = dt.now() if (resp.status.start_time is None): while self.pod_not_started(pod): self.log.warning('Pod not yet started: %s', pod.metadata.name) delta = (dt.now() - curr_time) if (delta.total_seconds() >= startup_timeout): raise AirflowException('Pod took too long to start') time.sleep(1)
def start_pod(self, pod: V1Pod, startup_timeout: int=120): '\n Launches the pod synchronously and waits for completion.\n\n :param pod:\n :param startup_timeout: Timeout for startup of the pod (if pod is pending for too long, fails task)\n :return:\n ' resp = self.run_pod_async(pod) curr_time = dt.now() if (resp.status.start_time is None): while self.pod_not_started(pod): self.log.warning('Pod not yet started: %s', pod.metadata.name) delta = (dt.now() - curr_time) if (delta.total_seconds() >= startup_timeout): raise AirflowException('Pod took too long to start') time.sleep(1)<|docstring|>Launches the pod synchronously and waits for completion. :param pod: :param startup_timeout: Timeout for startup of the pod (if pod is pending for too long, fails task) :return:<|endoftext|>
b8a2f21bb83941fcbd12850348b0cdf49a88419b636d8c240b6c2be463e1ad81
def monitor_pod(self, pod: V1Pod, get_logs: bool) -> Tuple[(State, Optional[str])]: '\n Monitors a pod and returns the final state\n\n :param pod: pod spec that will be monitored\n :type pod : V1Pod\n :param get_logs: whether to read the logs locally\n :return: Tuple[State, Optional[str]]\n ' if get_logs: read_logs_since_sec = None last_log_time = None while True: logs = self.read_pod_logs(pod, timestamps=True, since_seconds=read_logs_since_sec) for line in logs: (timestamp, message) = self.parse_log_line(line.decode('utf-8')) last_log_time = pendulum.parse(timestamp) self.log.info(message) time.sleep(1) if (not self.base_container_is_running(pod)): break self.log.warning('Pod %s log read interrupted', pod.metadata.name) if last_log_time: delta = (pendulum.now() - last_log_time) read_logs_since_sec = math.ceil(delta.total_seconds()) result = None if self.extract_xcom: while self.base_container_is_running(pod): self.log.info('Container %s has state %s', pod.metadata.name, State.RUNNING) time.sleep(2) result = self._extract_xcom(pod) self.log.info(result) result = json.loads(result) while self.pod_is_running(pod): self.log.info('Pod %s has state %s', pod.metadata.name, State.RUNNING) time.sleep(2) return (self._task_status(self.read_pod(pod)), result)
Monitors a pod and returns the final state :param pod: pod spec that will be monitored :type pod : V1Pod :param get_logs: whether to read the logs locally :return: Tuple[State, Optional[str]]
airflow/kubernetes/pod_launcher_deprecated.py
monitor_pod
legau/airflow
27
python
def monitor_pod(self, pod: V1Pod, get_logs: bool) -> Tuple[(State, Optional[str])]: '\n Monitors a pod and returns the final state\n\n :param pod: pod spec that will be monitored\n :type pod : V1Pod\n :param get_logs: whether to read the logs locally\n :return: Tuple[State, Optional[str]]\n ' if get_logs: read_logs_since_sec = None last_log_time = None while True: logs = self.read_pod_logs(pod, timestamps=True, since_seconds=read_logs_since_sec) for line in logs: (timestamp, message) = self.parse_log_line(line.decode('utf-8')) last_log_time = pendulum.parse(timestamp) self.log.info(message) time.sleep(1) if (not self.base_container_is_running(pod)): break self.log.warning('Pod %s log read interrupted', pod.metadata.name) if last_log_time: delta = (pendulum.now() - last_log_time) read_logs_since_sec = math.ceil(delta.total_seconds()) result = None if self.extract_xcom: while self.base_container_is_running(pod): self.log.info('Container %s has state %s', pod.metadata.name, State.RUNNING) time.sleep(2) result = self._extract_xcom(pod) self.log.info(result) result = json.loads(result) while self.pod_is_running(pod): self.log.info('Pod %s has state %s', pod.metadata.name, State.RUNNING) time.sleep(2) return (self._task_status(self.read_pod(pod)), result)
def monitor_pod(self, pod: V1Pod, get_logs: bool) -> Tuple[(State, Optional[str])]: '\n Monitors a pod and returns the final state\n\n :param pod: pod spec that will be monitored\n :type pod : V1Pod\n :param get_logs: whether to read the logs locally\n :return: Tuple[State, Optional[str]]\n ' if get_logs: read_logs_since_sec = None last_log_time = None while True: logs = self.read_pod_logs(pod, timestamps=True, since_seconds=read_logs_since_sec) for line in logs: (timestamp, message) = self.parse_log_line(line.decode('utf-8')) last_log_time = pendulum.parse(timestamp) self.log.info(message) time.sleep(1) if (not self.base_container_is_running(pod)): break self.log.warning('Pod %s log read interrupted', pod.metadata.name) if last_log_time: delta = (pendulum.now() - last_log_time) read_logs_since_sec = math.ceil(delta.total_seconds()) result = None if self.extract_xcom: while self.base_container_is_running(pod): self.log.info('Container %s has state %s', pod.metadata.name, State.RUNNING) time.sleep(2) result = self._extract_xcom(pod) self.log.info(result) result = json.loads(result) while self.pod_is_running(pod): self.log.info('Pod %s has state %s', pod.metadata.name, State.RUNNING) time.sleep(2) return (self._task_status(self.read_pod(pod)), result)<|docstring|>Monitors a pod and returns the final state :param pod: pod spec that will be monitored :type pod : V1Pod :param get_logs: whether to read the logs locally :return: Tuple[State, Optional[str]]<|endoftext|>
9372944828f824f16d55538662ddc27be788581feda66a7795c7ab046f88ffc9
def parse_log_line(self, line: str) -> Tuple[(str, str)]: '\n Parse K8s log line and returns the final state\n\n :param line: k8s log line\n :type line: str\n :return: timestamp and log message\n :rtype: Tuple[str, str]\n ' split_at = line.find(' ') if (split_at == (- 1)): raise Exception(f'Log not in "{{timestamp}} {{log}}" format. Got: {line}') timestamp = line[:split_at] message = line[(split_at + 1):].rstrip() return (timestamp, message)
Parse K8s log line and returns the final state :param line: k8s log line :type line: str :return: timestamp and log message :rtype: Tuple[str, str]
airflow/kubernetes/pod_launcher_deprecated.py
parse_log_line
legau/airflow
27
python
def parse_log_line(self, line: str) -> Tuple[(str, str)]: '\n Parse K8s log line and returns the final state\n\n :param line: k8s log line\n :type line: str\n :return: timestamp and log message\n :rtype: Tuple[str, str]\n ' split_at = line.find(' ') if (split_at == (- 1)): raise Exception(f'Log not in "{{timestamp}} {{log}}" format. Got: {line}') timestamp = line[:split_at] message = line[(split_at + 1):].rstrip() return (timestamp, message)
def parse_log_line(self, line: str) -> Tuple[(str, str)]: '\n Parse K8s log line and returns the final state\n\n :param line: k8s log line\n :type line: str\n :return: timestamp and log message\n :rtype: Tuple[str, str]\n ' split_at = line.find(' ') if (split_at == (- 1)): raise Exception(f'Log not in "{{timestamp}} {{log}}" format. Got: {line}') timestamp = line[:split_at] message = line[(split_at + 1):].rstrip() return (timestamp, message)<|docstring|>Parse K8s log line and returns the final state :param line: k8s log line :type line: str :return: timestamp and log message :rtype: Tuple[str, str]<|endoftext|>
855e2dd8223495ab9286b9d9bcf004fcc527fa9411294a4c113878d395130d56
def pod_not_started(self, pod: V1Pod): 'Tests if pod has not started' state = self._task_status(self.read_pod(pod)) return (state == State.QUEUED)
Tests if pod has not started
airflow/kubernetes/pod_launcher_deprecated.py
pod_not_started
legau/airflow
27
python
def pod_not_started(self, pod: V1Pod): state = self._task_status(self.read_pod(pod)) return (state == State.QUEUED)
def pod_not_started(self, pod: V1Pod): state = self._task_status(self.read_pod(pod)) return (state == State.QUEUED)<|docstring|>Tests if pod has not started<|endoftext|>
ef5af0cf1b0c5c6a1a8ac0753cb995dcddcc5125c8c783d29e873c2430480586
def pod_is_running(self, pod: V1Pod): 'Tests if pod is running' state = self._task_status(self.read_pod(pod)) return (state not in (State.SUCCESS, State.FAILED))
Tests if pod is running
airflow/kubernetes/pod_launcher_deprecated.py
pod_is_running
legau/airflow
27
python
def pod_is_running(self, pod: V1Pod): state = self._task_status(self.read_pod(pod)) return (state not in (State.SUCCESS, State.FAILED))
def pod_is_running(self, pod: V1Pod): state = self._task_status(self.read_pod(pod)) return (state not in (State.SUCCESS, State.FAILED))<|docstring|>Tests if pod is running<|endoftext|>
7926278dfb6997e92eb61d6420141a7e1130ef4aa411f2d8b04e82448de60e4a
def base_container_is_running(self, pod: V1Pod): 'Tests if base container is running' event = self.read_pod(pod) status = next(iter(filter((lambda s: (s.name == 'base')), event.status.container_statuses)), None) if (not status): return False return (status.state.running is not None)
Tests if base container is running
airflow/kubernetes/pod_launcher_deprecated.py
base_container_is_running
legau/airflow
27
python
def base_container_is_running(self, pod: V1Pod): event = self.read_pod(pod) status = next(iter(filter((lambda s: (s.name == 'base')), event.status.container_statuses)), None) if (not status): return False return (status.state.running is not None)
def base_container_is_running(self, pod: V1Pod): event = self.read_pod(pod) status = next(iter(filter((lambda s: (s.name == 'base')), event.status.container_statuses)), None) if (not status): return False return (status.state.running is not None)<|docstring|>Tests if base container is running<|endoftext|>
3227837018ec7af43ac9c2d360755e3c1002e33d35ed1bd7c66286b22853f58b
@tenacity.retry(stop=tenacity.stop_after_attempt(3), wait=tenacity.wait_exponential(), reraise=True) def read_pod_logs(self, pod: V1Pod, tail_lines: Optional[int]=None, timestamps: bool=False, since_seconds: Optional[int]=None): 'Reads log from the POD' additional_kwargs = {} if since_seconds: additional_kwargs['since_seconds'] = since_seconds if tail_lines: additional_kwargs['tail_lines'] = tail_lines try: return self._client.read_namespaced_pod_log(name=pod.metadata.name, namespace=pod.metadata.namespace, container='base', follow=True, timestamps=timestamps, _preload_content=False, **additional_kwargs) except HTTPError as e: raise AirflowException(f'There was an error reading the kubernetes API: {e}')
Reads log from the POD
airflow/kubernetes/pod_launcher_deprecated.py
read_pod_logs
legau/airflow
27
python
@tenacity.retry(stop=tenacity.stop_after_attempt(3), wait=tenacity.wait_exponential(), reraise=True) def read_pod_logs(self, pod: V1Pod, tail_lines: Optional[int]=None, timestamps: bool=False, since_seconds: Optional[int]=None): additional_kwargs = {} if since_seconds: additional_kwargs['since_seconds'] = since_seconds if tail_lines: additional_kwargs['tail_lines'] = tail_lines try: return self._client.read_namespaced_pod_log(name=pod.metadata.name, namespace=pod.metadata.namespace, container='base', follow=True, timestamps=timestamps, _preload_content=False, **additional_kwargs) except HTTPError as e: raise AirflowException(f'There was an error reading the kubernetes API: {e}')
@tenacity.retry(stop=tenacity.stop_after_attempt(3), wait=tenacity.wait_exponential(), reraise=True) def read_pod_logs(self, pod: V1Pod, tail_lines: Optional[int]=None, timestamps: bool=False, since_seconds: Optional[int]=None): additional_kwargs = {} if since_seconds: additional_kwargs['since_seconds'] = since_seconds if tail_lines: additional_kwargs['tail_lines'] = tail_lines try: return self._client.read_namespaced_pod_log(name=pod.metadata.name, namespace=pod.metadata.namespace, container='base', follow=True, timestamps=timestamps, _preload_content=False, **additional_kwargs) except HTTPError as e: raise AirflowException(f'There was an error reading the kubernetes API: {e}')<|docstring|>Reads log from the POD<|endoftext|>
9cb9df5638f5be83093bd8b03bb9af084eeec4d280515dbed22c78e4efd4f7cd
@tenacity.retry(stop=tenacity.stop_after_attempt(3), wait=tenacity.wait_exponential(), reraise=True) def read_pod_events(self, pod): 'Reads events from the POD' try: return self._client.list_namespaced_event(namespace=pod.metadata.namespace, field_selector=f'involvedObject.name={pod.metadata.name}') except HTTPError as e: raise AirflowException(f'There was an error reading the kubernetes API: {e}')
Reads events from the POD
airflow/kubernetes/pod_launcher_deprecated.py
read_pod_events
legau/airflow
27
python
@tenacity.retry(stop=tenacity.stop_after_attempt(3), wait=tenacity.wait_exponential(), reraise=True) def read_pod_events(self, pod): try: return self._client.list_namespaced_event(namespace=pod.metadata.namespace, field_selector=f'involvedObject.name={pod.metadata.name}') except HTTPError as e: raise AirflowException(f'There was an error reading the kubernetes API: {e}')
@tenacity.retry(stop=tenacity.stop_after_attempt(3), wait=tenacity.wait_exponential(), reraise=True) def read_pod_events(self, pod): try: return self._client.list_namespaced_event(namespace=pod.metadata.namespace, field_selector=f'involvedObject.name={pod.metadata.name}') except HTTPError as e: raise AirflowException(f'There was an error reading the kubernetes API: {e}')<|docstring|>Reads events from the POD<|endoftext|>
013575fa3e1863ad1f3b494e903b75e7bd33dceec389413c8a9c0071743b8cbd
@tenacity.retry(stop=tenacity.stop_after_attempt(3), wait=tenacity.wait_exponential(), reraise=True) def read_pod(self, pod: V1Pod): 'Read POD information' try: return self._client.read_namespaced_pod(pod.metadata.name, pod.metadata.namespace) except HTTPError as e: raise AirflowException(f'There was an error reading the kubernetes API: {e}')
Read POD information
airflow/kubernetes/pod_launcher_deprecated.py
read_pod
legau/airflow
27
python
@tenacity.retry(stop=tenacity.stop_after_attempt(3), wait=tenacity.wait_exponential(), reraise=True) def read_pod(self, pod: V1Pod): try: return self._client.read_namespaced_pod(pod.metadata.name, pod.metadata.namespace) except HTTPError as e: raise AirflowException(f'There was an error reading the kubernetes API: {e}')
@tenacity.retry(stop=tenacity.stop_after_attempt(3), wait=tenacity.wait_exponential(), reraise=True) def read_pod(self, pod: V1Pod): try: return self._client.read_namespaced_pod(pod.metadata.name, pod.metadata.namespace) except HTTPError as e: raise AirflowException(f'There was an error reading the kubernetes API: {e}')<|docstring|>Read POD information<|endoftext|>
571aa2ebf1efd0a3816871c7f2c6eea81bf7d36e9a398b2a51bd857d037e88aa
def process_status(self, job_id, status): 'Process status information for the JOB' status = status.lower() if (status == PodStatus.PENDING): return State.QUEUED elif (status == PodStatus.FAILED): self.log.error('Event with job id %s Failed', job_id) return State.FAILED elif (status == PodStatus.SUCCEEDED): self.log.info('Event with job id %s Succeeded', job_id) return State.SUCCESS elif (status == PodStatus.RUNNING): return State.RUNNING else: self.log.error('Event: Invalid state %s on job %s', status, job_id) return State.FAILED
Process status information for the JOB
airflow/kubernetes/pod_launcher_deprecated.py
process_status
legau/airflow
27
python
def process_status(self, job_id, status): status = status.lower() if (status == PodStatus.PENDING): return State.QUEUED elif (status == PodStatus.FAILED): self.log.error('Event with job id %s Failed', job_id) return State.FAILED elif (status == PodStatus.SUCCEEDED): self.log.info('Event with job id %s Succeeded', job_id) return State.SUCCESS elif (status == PodStatus.RUNNING): return State.RUNNING else: self.log.error('Event: Invalid state %s on job %s', status, job_id) return State.FAILED
def process_status(self, job_id, status): status = status.lower() if (status == PodStatus.PENDING): return State.QUEUED elif (status == PodStatus.FAILED): self.log.error('Event with job id %s Failed', job_id) return State.FAILED elif (status == PodStatus.SUCCEEDED): self.log.info('Event with job id %s Succeeded', job_id) return State.SUCCESS elif (status == PodStatus.RUNNING): return State.RUNNING else: self.log.error('Event: Invalid state %s on job %s', status, job_id) return State.FAILED<|docstring|>Process status information for the JOB<|endoftext|>
e08cefe02a3e3ade0787dad64c7ffcbfda2f6183454997606fa3a945aa038326
@staticmethod def status(s): 'Prints things in bold.' print('\x1b[1m{0}\x1b[0m'.format(s))
Prints things in bold.
setup.py
status
zed/leap-second-client
4
python
@staticmethod def status(s): print('\x1b[1m{0}\x1b[0m'.format(s))
@staticmethod def status(s): print('\x1b[1m{0}\x1b[0m'.format(s))<|docstring|>Prints things in bold.<|endoftext|>
0c8ae1acc7cf5292540756f023922e9701446a0641aa9e78475e8b9c83ad2890
def show(name, resource_group): '\n Get the details of a domain.\n\n Required Parameters:\n - name -- Name of the domain.\n - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`\n ' return _call_az('az eventgrid domain show', locals())
Get the details of a domain. Required Parameters: - name -- Name of the domain. - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
pyaz/eventgrid/domain/__init__.py
show
py-az-cli/py-az-cli
0
python
def show(name, resource_group): '\n Get the details of a domain.\n\n Required Parameters:\n - name -- Name of the domain.\n - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`\n ' return _call_az('az eventgrid domain show', locals())
def show(name, resource_group): '\n Get the details of a domain.\n\n Required Parameters:\n - name -- Name of the domain.\n - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`\n ' return _call_az('az eventgrid domain show', locals())<|docstring|>Get the details of a domain. Required Parameters: - name -- Name of the domain. - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`<|endoftext|>
eff4ef6d9029ef5a265392612ed3300d522debcdb8084c02d88407cb439b664e
def list(odata_query=None, resource_group=None): '\n List available domains.\n\n Optional Parameters:\n - odata_query -- The OData query used for filtering the list results. Filtering is currently allowed on the Name property only. The supported operations include: CONTAINS, eq (for equal), ne (for not equal), AND, OR and NOT.\n - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`\n ' return _call_az('az eventgrid domain list', locals())
List available domains. Optional Parameters: - odata_query -- The OData query used for filtering the list results. Filtering is currently allowed on the Name property only. The supported operations include: CONTAINS, eq (for equal), ne (for not equal), AND, OR and NOT. - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
pyaz/eventgrid/domain/__init__.py
list
py-az-cli/py-az-cli
0
python
def list(odata_query=None, resource_group=None): '\n List available domains.\n\n Optional Parameters:\n - odata_query -- The OData query used for filtering the list results. Filtering is currently allowed on the Name property only. The supported operations include: CONTAINS, eq (for equal), ne (for not equal), AND, OR and NOT.\n - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`\n ' return _call_az('az eventgrid domain list', locals())
def list(odata_query=None, resource_group=None): '\n List available domains.\n\n Optional Parameters:\n - odata_query -- The OData query used for filtering the list results. Filtering is currently allowed on the Name property only. The supported operations include: CONTAINS, eq (for equal), ne (for not equal), AND, OR and NOT.\n - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`\n ' return _call_az('az eventgrid domain list', locals())<|docstring|>List available domains. Optional Parameters: - odata_query -- The OData query used for filtering the list results. Filtering is currently allowed on the Name property only. The supported operations include: CONTAINS, eq (for equal), ne (for not equal), AND, OR and NOT. - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`<|endoftext|>
8ce16ff17b9c28f7d9bf5c10d17539b442278c7a6ff836424622bff163de0c0a
def create(name, resource_group, identity=None, inbound_ip_rules=None, input_mapping_default_values=None, input_mapping_fields=None, input_schema=None, location=None, public_network_access=None, sku=None, tags=None): "\n Create a domain.\n\n Required Parameters:\n - name -- Name of the domain.\n - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`\n\n Optional Parameters:\n - identity -- The managed identity type for the resource.\n - inbound_ip_rules -- None\n - input_mapping_default_values -- When input-schema is specified as customeventschema, this parameter can be used to specify input mappings based on default values. You can use this parameter when your custom schema does not include a field that corresponds to one of the three fields supported by this parameter. Specify space separated mappings in 'key=value' format. Allowed key names are 'subject', 'eventtype', 'dataversion'. The corresponding value names should specify the default values to be used for the mapping and they will be used only when the published event doesn't have a valid mapping for a particular field.\n - input_mapping_fields -- When input-schema is specified as customeventschema, this parameter is used to specify input mappings based on field names. Specify space separated mappings in 'key=value' format. Allowed key names are 'id', 'topic', 'eventtime', 'subject', 'eventtype', 'dataversion'. The corresponding value names should specify the names of the fields in the custom input schema. If a mapping for either 'id' or 'eventtime' is not provided, Event Grid will auto-generate a default value for these two fields.\n - input_schema -- Schema in which incoming events will be published to this topic/domain. If you specify customeventschema as the value for this parameter, you must also provide values for at least one of --input_mapping_default_values / --input_mapping_fields.\n - location -- Location. Values from: `az account list-locations`. You can configure the default location using `az configure --defaults location=<location>`.\n - public_network_access -- This determines if traffic is allowed over public network. By default it is enabled. You can further restrict to specific IPs by configuring.\n - sku -- The Sku name of the resource.\n - tags -- space-separated tags: key[=value] [key[=value] ...]. Use '' to clear existing tags.\n " return _call_az('az eventgrid domain create', locals())
Create a domain. Required Parameters: - name -- Name of the domain. - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>` Optional Parameters: - identity -- The managed identity type for the resource. - inbound_ip_rules -- None - input_mapping_default_values -- When input-schema is specified as customeventschema, this parameter can be used to specify input mappings based on default values. You can use this parameter when your custom schema does not include a field that corresponds to one of the three fields supported by this parameter. Specify space separated mappings in 'key=value' format. Allowed key names are 'subject', 'eventtype', 'dataversion'. The corresponding value names should specify the default values to be used for the mapping and they will be used only when the published event doesn't have a valid mapping for a particular field. - input_mapping_fields -- When input-schema is specified as customeventschema, this parameter is used to specify input mappings based on field names. Specify space separated mappings in 'key=value' format. Allowed key names are 'id', 'topic', 'eventtime', 'subject', 'eventtype', 'dataversion'. The corresponding value names should specify the names of the fields in the custom input schema. If a mapping for either 'id' or 'eventtime' is not provided, Event Grid will auto-generate a default value for these two fields. - input_schema -- Schema in which incoming events will be published to this topic/domain. If you specify customeventschema as the value for this parameter, you must also provide values for at least one of --input_mapping_default_values / --input_mapping_fields. - location -- Location. Values from: `az account list-locations`. You can configure the default location using `az configure --defaults location=<location>`. - public_network_access -- This determines if traffic is allowed over public network. By default it is enabled. You can further restrict to specific IPs by configuring. - sku -- The Sku name of the resource. - tags -- space-separated tags: key[=value] [key[=value] ...]. Use '' to clear existing tags.
pyaz/eventgrid/domain/__init__.py
create
py-az-cli/py-az-cli
0
python
def create(name, resource_group, identity=None, inbound_ip_rules=None, input_mapping_default_values=None, input_mapping_fields=None, input_schema=None, location=None, public_network_access=None, sku=None, tags=None): "\n Create a domain.\n\n Required Parameters:\n - name -- Name of the domain.\n - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`\n\n Optional Parameters:\n - identity -- The managed identity type for the resource.\n - inbound_ip_rules -- None\n - input_mapping_default_values -- When input-schema is specified as customeventschema, this parameter can be used to specify input mappings based on default values. You can use this parameter when your custom schema does not include a field that corresponds to one of the three fields supported by this parameter. Specify space separated mappings in 'key=value' format. Allowed key names are 'subject', 'eventtype', 'dataversion'. The corresponding value names should specify the default values to be used for the mapping and they will be used only when the published event doesn't have a valid mapping for a particular field.\n - input_mapping_fields -- When input-schema is specified as customeventschema, this parameter is used to specify input mappings based on field names. Specify space separated mappings in 'key=value' format. Allowed key names are 'id', 'topic', 'eventtime', 'subject', 'eventtype', 'dataversion'. The corresponding value names should specify the names of the fields in the custom input schema. If a mapping for either 'id' or 'eventtime' is not provided, Event Grid will auto-generate a default value for these two fields.\n - input_schema -- Schema in which incoming events will be published to this topic/domain. If you specify customeventschema as the value for this parameter, you must also provide values for at least one of --input_mapping_default_values / --input_mapping_fields.\n - location -- Location. Values from: `az account list-locations`. You can configure the default location using `az configure --defaults location=<location>`.\n - public_network_access -- This determines if traffic is allowed over public network. By default it is enabled. You can further restrict to specific IPs by configuring.\n - sku -- The Sku name of the resource.\n - tags -- space-separated tags: key[=value] [key[=value] ...]. Use to clear existing tags.\n " return _call_az('az eventgrid domain create', locals())
def create(name, resource_group, identity=None, inbound_ip_rules=None, input_mapping_default_values=None, input_mapping_fields=None, input_schema=None, location=None, public_network_access=None, sku=None, tags=None): "\n Create a domain.\n\n Required Parameters:\n - name -- Name of the domain.\n - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`\n\n Optional Parameters:\n - identity -- The managed identity type for the resource.\n - inbound_ip_rules -- None\n - input_mapping_default_values -- When input-schema is specified as customeventschema, this parameter can be used to specify input mappings based on default values. You can use this parameter when your custom schema does not include a field that corresponds to one of the three fields supported by this parameter. Specify space separated mappings in 'key=value' format. Allowed key names are 'subject', 'eventtype', 'dataversion'. The corresponding value names should specify the default values to be used for the mapping and they will be used only when the published event doesn't have a valid mapping for a particular field.\n - input_mapping_fields -- When input-schema is specified as customeventschema, this parameter is used to specify input mappings based on field names. Specify space separated mappings in 'key=value' format. Allowed key names are 'id', 'topic', 'eventtime', 'subject', 'eventtype', 'dataversion'. The corresponding value names should specify the names of the fields in the custom input schema. If a mapping for either 'id' or 'eventtime' is not provided, Event Grid will auto-generate a default value for these two fields.\n - input_schema -- Schema in which incoming events will be published to this topic/domain. If you specify customeventschema as the value for this parameter, you must also provide values for at least one of --input_mapping_default_values / --input_mapping_fields.\n - location -- Location. Values from: `az account list-locations`. You can configure the default location using `az configure --defaults location=<location>`.\n - public_network_access -- This determines if traffic is allowed over public network. By default it is enabled. You can further restrict to specific IPs by configuring.\n - sku -- The Sku name of the resource.\n - tags -- space-separated tags: key[=value] [key[=value] ...]. Use to clear existing tags.\n " return _call_az('az eventgrid domain create', locals())<|docstring|>Create a domain. Required Parameters: - name -- Name of the domain. - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>` Optional Parameters: - identity -- The managed identity type for the resource. - inbound_ip_rules -- None - input_mapping_default_values -- When input-schema is specified as customeventschema, this parameter can be used to specify input mappings based on default values. You can use this parameter when your custom schema does not include a field that corresponds to one of the three fields supported by this parameter. Specify space separated mappings in 'key=value' format. Allowed key names are 'subject', 'eventtype', 'dataversion'. The corresponding value names should specify the default values to be used for the mapping and they will be used only when the published event doesn't have a valid mapping for a particular field. - input_mapping_fields -- When input-schema is specified as customeventschema, this parameter is used to specify input mappings based on field names. Specify space separated mappings in 'key=value' format. Allowed key names are 'id', 'topic', 'eventtime', 'subject', 'eventtype', 'dataversion'. The corresponding value names should specify the names of the fields in the custom input schema. If a mapping for either 'id' or 'eventtime' is not provided, Event Grid will auto-generate a default value for these two fields. - input_schema -- Schema in which incoming events will be published to this topic/domain. If you specify customeventschema as the value for this parameter, you must also provide values for at least one of --input_mapping_default_values / --input_mapping_fields. - location -- Location. Values from: `az account list-locations`. You can configure the default location using `az configure --defaults location=<location>`. - public_network_access -- This determines if traffic is allowed over public network. By default it is enabled. You can further restrict to specific IPs by configuring. - sku -- The Sku name of the resource. - tags -- space-separated tags: key[=value] [key[=value] ...]. Use '' to clear existing tags.<|endoftext|>
71b26323a2d3bf3426aa0e559a6f5242ba6b09829715a4c8cb945647a49538a2
def delete(name, resource_group): '\n Delete a domain.\n\n Required Parameters:\n - name -- Name of the domain.\n - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`\n ' return _call_az('az eventgrid domain delete', locals())
Delete a domain. Required Parameters: - name -- Name of the domain. - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
pyaz/eventgrid/domain/__init__.py
delete
py-az-cli/py-az-cli
0
python
def delete(name, resource_group): '\n Delete a domain.\n\n Required Parameters:\n - name -- Name of the domain.\n - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`\n ' return _call_az('az eventgrid domain delete', locals())
def delete(name, resource_group): '\n Delete a domain.\n\n Required Parameters:\n - name -- Name of the domain.\n - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`\n ' return _call_az('az eventgrid domain delete', locals())<|docstring|>Delete a domain. Required Parameters: - name -- Name of the domain. - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`<|endoftext|>
eb7a945e984b26cc8dbc57e1d8d48fe9a90cc134088464f74176d1fed9567574
def update(name, resource_group, identity=None, inbound_ip_rules=None, public_network_access=None, sku=None, tags=None): "\n Update a domain.\n\n Required Parameters:\n - name -- Name of the domain.\n - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`\n\n Optional Parameters:\n - identity -- The managed identity type for the resource.\n - inbound_ip_rules -- None\n - public_network_access -- This determines if traffic is allowed over public network. By default it is enabled. You can further restrict to specific IPs by configuring.\n - sku -- The Sku name of the resource.\n - tags -- space-separated tags: key[=value] [key[=value] ...]. Use '' to clear existing tags.\n " return _call_az('az eventgrid domain update', locals())
Update a domain. Required Parameters: - name -- Name of the domain. - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>` Optional Parameters: - identity -- The managed identity type for the resource. - inbound_ip_rules -- None - public_network_access -- This determines if traffic is allowed over public network. By default it is enabled. You can further restrict to specific IPs by configuring. - sku -- The Sku name of the resource. - tags -- space-separated tags: key[=value] [key[=value] ...]. Use '' to clear existing tags.
pyaz/eventgrid/domain/__init__.py
update
py-az-cli/py-az-cli
0
python
def update(name, resource_group, identity=None, inbound_ip_rules=None, public_network_access=None, sku=None, tags=None): "\n Update a domain.\n\n Required Parameters:\n - name -- Name of the domain.\n - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`\n\n Optional Parameters:\n - identity -- The managed identity type for the resource.\n - inbound_ip_rules -- None\n - public_network_access -- This determines if traffic is allowed over public network. By default it is enabled. You can further restrict to specific IPs by configuring.\n - sku -- The Sku name of the resource.\n - tags -- space-separated tags: key[=value] [key[=value] ...]. Use to clear existing tags.\n " return _call_az('az eventgrid domain update', locals())
def update(name, resource_group, identity=None, inbound_ip_rules=None, public_network_access=None, sku=None, tags=None): "\n Update a domain.\n\n Required Parameters:\n - name -- Name of the domain.\n - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`\n\n Optional Parameters:\n - identity -- The managed identity type for the resource.\n - inbound_ip_rules -- None\n - public_network_access -- This determines if traffic is allowed over public network. By default it is enabled. You can further restrict to specific IPs by configuring.\n - sku -- The Sku name of the resource.\n - tags -- space-separated tags: key[=value] [key[=value] ...]. Use to clear existing tags.\n " return _call_az('az eventgrid domain update', locals())<|docstring|>Update a domain. Required Parameters: - name -- Name of the domain. - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>` Optional Parameters: - identity -- The managed identity type for the resource. - inbound_ip_rules -- None - public_network_access -- This determines if traffic is allowed over public network. By default it is enabled. You can further restrict to specific IPs by configuring. - sku -- The Sku name of the resource. - tags -- space-separated tags: key[=value] [key[=value] ...]. Use '' to clear existing tags.<|endoftext|>
644f49043831488e9c999677c83d89668559e0db71a6a231056326c0bdfee89f
def std_mad(x): 'Robust estimation of the standard deviation, based on the Corrected Median\n Absolute Deviation (MAD) of x.\n This computes the MAD of x, and applies the Gaussian distribution\n correction, making it a consistent estimator of the standard-deviation\n (when the sample looks Gaussian with outliers).\n\n Parameters\n ----------\n x : `np.ndarray`\n Input vector\n\n Returns\n -------\n output : `float`\n A robust estimation of the standard deviation\n ' from scipy.stats import norm correction = (1 / norm.ppf((3 / 4))) return (correction * np.median(np.abs((x - np.median(x)))))
Robust estimation of the standard deviation, based on the Corrected Median Absolute Deviation (MAD) of x. This computes the MAD of x, and applies the Gaussian distribution correction, making it a consistent estimator of the standard-deviation (when the sample looks Gaussian with outliers). Parameters ---------- x : `np.ndarray` Input vector Returns ------- output : `float` A robust estimation of the standard deviation
tick/robust/robust.py
std_mad
andro2157/tick
411
python
def std_mad(x): 'Robust estimation of the standard deviation, based on the Corrected Median\n Absolute Deviation (MAD) of x.\n This computes the MAD of x, and applies the Gaussian distribution\n correction, making it a consistent estimator of the standard-deviation\n (when the sample looks Gaussian with outliers).\n\n Parameters\n ----------\n x : `np.ndarray`\n Input vector\n\n Returns\n -------\n output : `float`\n A robust estimation of the standard deviation\n ' from scipy.stats import norm correction = (1 / norm.ppf((3 / 4))) return (correction * np.median(np.abs((x - np.median(x)))))
def std_mad(x): 'Robust estimation of the standard deviation, based on the Corrected Median\n Absolute Deviation (MAD) of x.\n This computes the MAD of x, and applies the Gaussian distribution\n correction, making it a consistent estimator of the standard-deviation\n (when the sample looks Gaussian with outliers).\n\n Parameters\n ----------\n x : `np.ndarray`\n Input vector\n\n Returns\n -------\n output : `float`\n A robust estimation of the standard deviation\n ' from scipy.stats import norm correction = (1 / norm.ppf((3 / 4))) return (correction * np.median(np.abs((x - np.median(x)))))<|docstring|>Robust estimation of the standard deviation, based on the Corrected Median Absolute Deviation (MAD) of x. This computes the MAD of x, and applies the Gaussian distribution correction, making it a consistent estimator of the standard-deviation (when the sample looks Gaussian with outliers). Parameters ---------- x : `np.ndarray` Input vector Returns ------- output : `float` A robust estimation of the standard deviation<|endoftext|>
ec6611a6ac76322f974c41464022af1ff2a3cc42bdf4ce7e9e6eada6a5cba3df
def std_iqr(x): 'Robust estimation of the standard deviation, based on the inter-quartile\n (IQR) distance of x.\n This computes the IQR of x, and applies the Gaussian distribution\n correction, making it a consistent estimator of the standard-deviation\n (when the sample looks Gaussian with outliers).\n\n Parameters\n ----------\n x : `np.ndarray`\n Input vector\n\n Returns\n -------\n output : `float`\n A robust estimation of the standard deviation\n ' from scipy.stats import iqr from scipy.special import erfinv correction = ((2 ** 0.5) * erfinv(0.5)) return (correction * iqr(x))
Robust estimation of the standard deviation, based on the inter-quartile (IQR) distance of x. This computes the IQR of x, and applies the Gaussian distribution correction, making it a consistent estimator of the standard-deviation (when the sample looks Gaussian with outliers). Parameters ---------- x : `np.ndarray` Input vector Returns ------- output : `float` A robust estimation of the standard deviation
tick/robust/robust.py
std_iqr
andro2157/tick
411
python
def std_iqr(x): 'Robust estimation of the standard deviation, based on the inter-quartile\n (IQR) distance of x.\n This computes the IQR of x, and applies the Gaussian distribution\n correction, making it a consistent estimator of the standard-deviation\n (when the sample looks Gaussian with outliers).\n\n Parameters\n ----------\n x : `np.ndarray`\n Input vector\n\n Returns\n -------\n output : `float`\n A robust estimation of the standard deviation\n ' from scipy.stats import iqr from scipy.special import erfinv correction = ((2 ** 0.5) * erfinv(0.5)) return (correction * iqr(x))
def std_iqr(x): 'Robust estimation of the standard deviation, based on the inter-quartile\n (IQR) distance of x.\n This computes the IQR of x, and applies the Gaussian distribution\n correction, making it a consistent estimator of the standard-deviation\n (when the sample looks Gaussian with outliers).\n\n Parameters\n ----------\n x : `np.ndarray`\n Input vector\n\n Returns\n -------\n output : `float`\n A robust estimation of the standard deviation\n ' from scipy.stats import iqr from scipy.special import erfinv correction = ((2 ** 0.5) * erfinv(0.5)) return (correction * iqr(x))<|docstring|>Robust estimation of the standard deviation, based on the inter-quartile (IQR) distance of x. This computes the IQR of x, and applies the Gaussian distribution correction, making it a consistent estimator of the standard-deviation (when the sample looks Gaussian with outliers). Parameters ---------- x : `np.ndarray` Input vector Returns ------- output : `float` A robust estimation of the standard deviation<|endoftext|>
36cd95d5616dbb686603ad26e4c1c002257fd1f0de16cd7ada01dce0d140a9a8
def __init__(self, arr=None, already_heap=False): '\n\t\tCreates an empty heap when passed with no parameters.\n\t\tInitializes self.arr when passed with a list that is already a heap.\n\t\tCalls build_heap when given list is not a heap.\n\t\t' if (not arr): self.arr = [] elif already_heap: self.arr = arr else: self.build_heap(arr)
Creates an empty heap when passed with no parameters. Initializes self.arr when passed with a list that is already a heap. Calls build_heap when given list is not a heap.
BinaryHeap.py
__init__
arunkumaraqm/Prims-Algorithm-Using-Fibonacci-Heap
1
python
def __init__(self, arr=None, already_heap=False): '\n\t\tCreates an empty heap when passed with no parameters.\n\t\tInitializes self.arr when passed with a list that is already a heap.\n\t\tCalls build_heap when given list is not a heap.\n\t\t' if (not arr): self.arr = [] elif already_heap: self.arr = arr else: self.build_heap(arr)
def __init__(self, arr=None, already_heap=False): '\n\t\tCreates an empty heap when passed with no parameters.\n\t\tInitializes self.arr when passed with a list that is already a heap.\n\t\tCalls build_heap when given list is not a heap.\n\t\t' if (not arr): self.arr = [] elif already_heap: self.arr = arr else: self.build_heap(arr)<|docstring|>Creates an empty heap when passed with no parameters. Initializes self.arr when passed with a list that is already a heap. Calls build_heap when given list is not a heap.<|endoftext|>
f189c3fc3dd56faa8e07139f813640ed81d3d7fcbc8e7480e415b7edf7c79aea
def find_min_child(self, ind): '\n\t\tReturns the index of the smaller child of a node.\n\t\tReturns -1 if node is a leaf.\n\t\t' left = ((ind * 2) + 1) right = (left + 1) if (left >= len(self)): return (- 1) if (right >= len(self)): return left if (self.arr[left] < self.arr[right]): return left else: return right
Returns the index of the smaller child of a node. Returns -1 if node is a leaf.
BinaryHeap.py
find_min_child
arunkumaraqm/Prims-Algorithm-Using-Fibonacci-Heap
1
python
def find_min_child(self, ind): '\n\t\tReturns the index of the smaller child of a node.\n\t\tReturns -1 if node is a leaf.\n\t\t' left = ((ind * 2) + 1) right = (left + 1) if (left >= len(self)): return (- 1) if (right >= len(self)): return left if (self.arr[left] < self.arr[right]): return left else: return right
def find_min_child(self, ind): '\n\t\tReturns the index of the smaller child of a node.\n\t\tReturns -1 if node is a leaf.\n\t\t' left = ((ind * 2) + 1) right = (left + 1) if (left >= len(self)): return (- 1) if (right >= len(self)): return left if (self.arr[left] < self.arr[right]): return left else: return right<|docstring|>Returns the index of the smaller child of a node. Returns -1 if node is a leaf.<|endoftext|>
be646da3ab9de835530f2acb63442bb423afc1f230cfee72bc269d4bfe29478f
def sift_down(self, ind): '\n\t\tSwaps node with the smaller child repeatedly \n\t\tuntil the node is smaller than both its children.\n\t\t' while True: desired_child = self.find_min_child(ind) if (desired_child == (- 1)): break if (self.arr[ind] > self.arr[desired_child]): self.swap(ind, desired_child) ind = desired_child else: break
Swaps node with the smaller child repeatedly until the node is smaller than both its children.
BinaryHeap.py
sift_down
arunkumaraqm/Prims-Algorithm-Using-Fibonacci-Heap
1
python
def sift_down(self, ind): '\n\t\tSwaps node with the smaller child repeatedly \n\t\tuntil the node is smaller than both its children.\n\t\t' while True: desired_child = self.find_min_child(ind) if (desired_child == (- 1)): break if (self.arr[ind] > self.arr[desired_child]): self.swap(ind, desired_child) ind = desired_child else: break
def sift_down(self, ind): '\n\t\tSwaps node with the smaller child repeatedly \n\t\tuntil the node is smaller than both its children.\n\t\t' while True: desired_child = self.find_min_child(ind) if (desired_child == (- 1)): break if (self.arr[ind] > self.arr[desired_child]): self.swap(ind, desired_child) ind = desired_child else: break<|docstring|>Swaps node with the smaller child repeatedly until the node is smaller than both its children.<|endoftext|>
76c6d27f3618a4f4839c545455aec33ae81b67d9d6304c07bddaf41b6011abe4
def sift_up(self, ind): '\n\t\tSwaps node with its parent repeatedly\n\t\tuntil the node is larger than its parent.\n\t\t' while True: if (ind == 0): break parent = ((ind - 1) // 2) if (self.arr[ind] < self.arr[parent]): self.swap(ind, parent) ind = parent else: break
Swaps node with its parent repeatedly until the node is larger than its parent.
BinaryHeap.py
sift_up
arunkumaraqm/Prims-Algorithm-Using-Fibonacci-Heap
1
python
def sift_up(self, ind): '\n\t\tSwaps node with its parent repeatedly\n\t\tuntil the node is larger than its parent.\n\t\t' while True: if (ind == 0): break parent = ((ind - 1) // 2) if (self.arr[ind] < self.arr[parent]): self.swap(ind, parent) ind = parent else: break
def sift_up(self, ind): '\n\t\tSwaps node with its parent repeatedly\n\t\tuntil the node is larger than its parent.\n\t\t' while True: if (ind == 0): break parent = ((ind - 1) // 2) if (self.arr[ind] < self.arr[parent]): self.swap(ind, parent) ind = parent else: break<|docstring|>Swaps node with its parent repeatedly until the node is larger than its parent.<|endoftext|>
060aa5765a0343d7388c70981622d9c5305ef031d579c9741dc495bde75c2649
def extract_min(self): 'Removes and returns the minimum key from heap.' if (len(self) == 0): return None minn = self.arr[0] self.arr[0] = self.arr[(- 1)] del self.arr[(- 1)] self.sift_down(0) return minn
Removes and returns the minimum key from heap.
BinaryHeap.py
extract_min
arunkumaraqm/Prims-Algorithm-Using-Fibonacci-Heap
1
python
def extract_min(self): if (len(self) == 0): return None minn = self.arr[0] self.arr[0] = self.arr[(- 1)] del self.arr[(- 1)] self.sift_down(0) return minn
def extract_min(self): if (len(self) == 0): return None minn = self.arr[0] self.arr[0] = self.arr[(- 1)] del self.arr[(- 1)] self.sift_down(0) return minn<|docstring|>Removes and returns the minimum key from heap.<|endoftext|>
fca8935c9900a58de4c967836e30ee1af77821058e9ac36412f6bb4fa1340949
def merge(self, other): 'Builds a new MinHeap after combining the two existing ones.' return MinHeap((self.arr + other.arr))
Builds a new MinHeap after combining the two existing ones.
BinaryHeap.py
merge
arunkumaraqm/Prims-Algorithm-Using-Fibonacci-Heap
1
python
def merge(self, other): return MinHeap((self.arr + other.arr))
def merge(self, other): return MinHeap((self.arr + other.arr))<|docstring|>Builds a new MinHeap after combining the two existing ones.<|endoftext|>
5997cc5ef2e4ac79b8a1c836894bf71c5c36365171882456fb4bcb2b2885885f
@staticmethod def vstack(matrices, require_equal_columnlabels=True): 'Returns a new matrix equal to the row-wise\n concatenation of the given matrices' assert (len(matrices) > 0) if (len(matrices) == 1): return matrices[0].copy() for matrix in matrices: assert isinstance(matrix, Matrix) assert (matrix.columnlabels.shape == matrices[0].columnlabels.shape) assert (matrix.data.shape[1] == matrices[0].data.shape[1]) if require_equal_columnlabels: assert np.array_equal(matrix.columnlabels, matrices[0].columnlabels) data = np.vstack([mtx.data for mtx in matrices]) rowlabels = np.hstack([mtx.rowlabels for mtx in matrices]) return Matrix(data, rowlabels, matrices[0].columnlabels.copy())
Returns a new matrix equal to the row-wise concatenation of the given matrices
server/analysis/matrix.py
vstack
newopscn/ottertune
0
python
@staticmethod def vstack(matrices, require_equal_columnlabels=True): 'Returns a new matrix equal to the row-wise\n concatenation of the given matrices' assert (len(matrices) > 0) if (len(matrices) == 1): return matrices[0].copy() for matrix in matrices: assert isinstance(matrix, Matrix) assert (matrix.columnlabels.shape == matrices[0].columnlabels.shape) assert (matrix.data.shape[1] == matrices[0].data.shape[1]) if require_equal_columnlabels: assert np.array_equal(matrix.columnlabels, matrices[0].columnlabels) data = np.vstack([mtx.data for mtx in matrices]) rowlabels = np.hstack([mtx.rowlabels for mtx in matrices]) return Matrix(data, rowlabels, matrices[0].columnlabels.copy())
@staticmethod def vstack(matrices, require_equal_columnlabels=True): 'Returns a new matrix equal to the row-wise\n concatenation of the given matrices' assert (len(matrices) > 0) if (len(matrices) == 1): return matrices[0].copy() for matrix in matrices: assert isinstance(matrix, Matrix) assert (matrix.columnlabels.shape == matrices[0].columnlabels.shape) assert (matrix.data.shape[1] == matrices[0].data.shape[1]) if require_equal_columnlabels: assert np.array_equal(matrix.columnlabels, matrices[0].columnlabels) data = np.vstack([mtx.data for mtx in matrices]) rowlabels = np.hstack([mtx.rowlabels for mtx in matrices]) return Matrix(data, rowlabels, matrices[0].columnlabels.copy())<|docstring|>Returns a new matrix equal to the row-wise concatenation of the given matrices<|endoftext|>
06a5f49a0580ad3507e8daf74c92e9ee66c563dba7a39b1f371008574f5aeb89
@staticmethod def hstack(matrices, require_equal_rowlabels=True): 'Returns a new matrix equal to the column-wise\n concatenation of the given matrices' assert (len(matrices) > 0) if (len(matrices) == 1): return matrices[0].copy() for matrix in matrices: assert isinstance(matrix, Matrix) assert (matrix.data.shape[0] == matrices[0].data.shape[0]) assert (matrix.rowlabels.shape == matrices[0].rowlabels.shape) if require_equal_rowlabels: assert np.array_equal(matrix.rowlabels, matrices[0].rowlabels) data = np.hstack([mtx.data for mtx in matrices]) columnlabels = np.hstack([mtx.columnlabels for mtx in matrices]) return Matrix(data, matrices[0].rowlabels.copy(), columnlabels)
Returns a new matrix equal to the column-wise concatenation of the given matrices
server/analysis/matrix.py
hstack
newopscn/ottertune
0
python
@staticmethod def hstack(matrices, require_equal_rowlabels=True): 'Returns a new matrix equal to the column-wise\n concatenation of the given matrices' assert (len(matrices) > 0) if (len(matrices) == 1): return matrices[0].copy() for matrix in matrices: assert isinstance(matrix, Matrix) assert (matrix.data.shape[0] == matrices[0].data.shape[0]) assert (matrix.rowlabels.shape == matrices[0].rowlabels.shape) if require_equal_rowlabels: assert np.array_equal(matrix.rowlabels, matrices[0].rowlabels) data = np.hstack([mtx.data for mtx in matrices]) columnlabels = np.hstack([mtx.columnlabels for mtx in matrices]) return Matrix(data, matrices[0].rowlabels.copy(), columnlabels)
@staticmethod def hstack(matrices, require_equal_rowlabels=True): 'Returns a new matrix equal to the column-wise\n concatenation of the given matrices' assert (len(matrices) > 0) if (len(matrices) == 1): return matrices[0].copy() for matrix in matrices: assert isinstance(matrix, Matrix) assert (matrix.data.shape[0] == matrices[0].data.shape[0]) assert (matrix.rowlabels.shape == matrices[0].rowlabels.shape) if require_equal_rowlabels: assert np.array_equal(matrix.rowlabels, matrices[0].rowlabels) data = np.hstack([mtx.data for mtx in matrices]) columnlabels = np.hstack([mtx.columnlabels for mtx in matrices]) return Matrix(data, matrices[0].rowlabels.copy(), columnlabels)<|docstring|>Returns a new matrix equal to the column-wise concatenation of the given matrices<|endoftext|>
3a360b79a7de6bf1dcd495f9722774c3c6102305bd93bf0b71637be6c8953c5f
def unique_rows(self, return_index=False): 'Returns a new matrix containing the unique rows\n in this matrix' unique_indices = Matrix._unique_helper(self.__data) if (unique_indices.size == self.__data.shape[0]): newmatrix = self.copy() else: newmatrix = Matrix(self.__data[unique_indices], self.__rowlabels[unique_indices], self.__columnlabels.copy()) if return_index: return (newmatrix, unique_indices) else: return newmatrix
Returns a new matrix containing the unique rows in this matrix
server/analysis/matrix.py
unique_rows
newopscn/ottertune
0
python
def unique_rows(self, return_index=False): 'Returns a new matrix containing the unique rows\n in this matrix' unique_indices = Matrix._unique_helper(self.__data) if (unique_indices.size == self.__data.shape[0]): newmatrix = self.copy() else: newmatrix = Matrix(self.__data[unique_indices], self.__rowlabels[unique_indices], self.__columnlabels.copy()) if return_index: return (newmatrix, unique_indices) else: return newmatrix
def unique_rows(self, return_index=False): 'Returns a new matrix containing the unique rows\n in this matrix' unique_indices = Matrix._unique_helper(self.__data) if (unique_indices.size == self.__data.shape[0]): newmatrix = self.copy() else: newmatrix = Matrix(self.__data[unique_indices], self.__rowlabels[unique_indices], self.__columnlabels.copy()) if return_index: return (newmatrix, unique_indices) else: return newmatrix<|docstring|>Returns a new matrix containing the unique rows in this matrix<|endoftext|>
71e2ff58b4f1415c50628234131e00e6c2c1e3a87336834ca7dc7002a3ee3971
def unique_columns(self, return_index=False): 'Returns a new matrix containing the unique columns\n in this matrix' unique_indices = Matrix._unique_helper(self.__data.T) if (unique_indices.size == self.__data.shape[1]): newmatrix = self.copy() else: newmatrix = Matrix(self.__data[(:, unique_indices)], self.__rowlabels.copy(), self.__columnlabels[unique_indices]) if return_index: return (newmatrix, unique_indices) else: return newmatrix
Returns a new matrix containing the unique columns in this matrix
server/analysis/matrix.py
unique_columns
newopscn/ottertune
0
python
def unique_columns(self, return_index=False): 'Returns a new matrix containing the unique columns\n in this matrix' unique_indices = Matrix._unique_helper(self.__data.T) if (unique_indices.size == self.__data.shape[1]): newmatrix = self.copy() else: newmatrix = Matrix(self.__data[(:, unique_indices)], self.__rowlabels.copy(), self.__columnlabels[unique_indices]) if return_index: return (newmatrix, unique_indices) else: return newmatrix
def unique_columns(self, return_index=False): 'Returns a new matrix containing the unique columns\n in this matrix' unique_indices = Matrix._unique_helper(self.__data.T) if (unique_indices.size == self.__data.shape[1]): newmatrix = self.copy() else: newmatrix = Matrix(self.__data[(:, unique_indices)], self.__rowlabels.copy(), self.__columnlabels[unique_indices]) if return_index: return (newmatrix, unique_indices) else: return newmatrix<|docstring|>Returns a new matrix containing the unique columns in this matrix<|endoftext|>
403d0aafc439353bd1c51b60c30d95662024b1925213a6445f9ab0cb2cda824c
def copy(self): 'Returns a copy of this matrix' return Matrix(self.__data.copy(), self.__rowlabels.copy(), self.__columnlabels.copy())
Returns a copy of this matrix
server/analysis/matrix.py
copy
newopscn/ottertune
0
python
def copy(self): return Matrix(self.__data.copy(), self.__rowlabels.copy(), self.__columnlabels.copy())
def copy(self): return Matrix(self.__data.copy(), self.__rowlabels.copy(), self.__columnlabels.copy())<|docstring|>Returns a copy of this matrix<|endoftext|>
07f7972b5115dbd0863d39fa79c2f6784d4fbfe037d320b66ea2dd38f303057e
def filter(self, labels, rows_or_columns): "Returns a new matrix filtered by either the rows or\n columns given in 'labels'" assert (rows_or_columns in ['rows', 'columns']) logical_filter = self.get_membership_mask(labels, rows_or_columns) if (rows_or_columns == 'rows'): return Matrix(self.__data[logical_filter], self.__rowlabels[logical_filter], self.__columnlabels) else: return Matrix(self.__data[(:, logical_filter)], self.__rowlabels, self.__columnlabels[logical_filter])
Returns a new matrix filtered by either the rows or columns given in 'labels'
server/analysis/matrix.py
filter
newopscn/ottertune
0
python
def filter(self, labels, rows_or_columns): "Returns a new matrix filtered by either the rows or\n columns given in 'labels'" assert (rows_or_columns in ['rows', 'columns']) logical_filter = self.get_membership_mask(labels, rows_or_columns) if (rows_or_columns == 'rows'): return Matrix(self.__data[logical_filter], self.__rowlabels[logical_filter], self.__columnlabels) else: return Matrix(self.__data[(:, logical_filter)], self.__rowlabels, self.__columnlabels[logical_filter])
def filter(self, labels, rows_or_columns): "Returns a new matrix filtered by either the rows or\n columns given in 'labels'" assert (rows_or_columns in ['rows', 'columns']) logical_filter = self.get_membership_mask(labels, rows_or_columns) if (rows_or_columns == 'rows'): return Matrix(self.__data[logical_filter], self.__rowlabels[logical_filter], self.__columnlabels) else: return Matrix(self.__data[(:, logical_filter)], self.__rowlabels, self.__columnlabels[logical_filter])<|docstring|>Returns a new matrix filtered by either the rows or columns given in 'labels'<|endoftext|>
c18b8bdb8388401d987a98861e4d3b017cc535675fdefdafff71a558997dc33e
def load_model_checkpoint(self): '\n This function loads a model checkpoint if there is a checkpoint with the models configuration name\n :return:\n ' checkpoint_abs_path = os.path.join(self.checkpoint_folder_path, self.checkpoint_filename) if os.path.exists(checkpoint_abs_path): checkpoint = torch.load(checkpoint_abs_path) self.model.load_state_dict(checkpoint['model_state_dict']) self.optimizer.load_state_dict(checkpoint['optimizer_state_dict']) self.start_epoch = checkpoint['epoch'] self.log.info('Loaded {} model. Starting from the epoch number {}. Checkpoint path: {}'.format(self.model_configuration_name, self.start_epoch, checkpoint_abs_path)) self.model.train() else: self.log.info('No checkpoint found at {}. Training will start from scratch.'.format(checkpoint_abs_path))
This function loads a model checkpoint if there is a checkpoint with the models configuration name :return:
trainer/trainer.py
load_model_checkpoint
sarodriguez/audio-source-separation
0
python
def load_model_checkpoint(self): '\n This function loads a model checkpoint if there is a checkpoint with the models configuration name\n :return:\n ' checkpoint_abs_path = os.path.join(self.checkpoint_folder_path, self.checkpoint_filename) if os.path.exists(checkpoint_abs_path): checkpoint = torch.load(checkpoint_abs_path) self.model.load_state_dict(checkpoint['model_state_dict']) self.optimizer.load_state_dict(checkpoint['optimizer_state_dict']) self.start_epoch = checkpoint['epoch'] self.log.info('Loaded {} model. Starting from the epoch number {}. Checkpoint path: {}'.format(self.model_configuration_name, self.start_epoch, checkpoint_abs_path)) self.model.train() else: self.log.info('No checkpoint found at {}. Training will start from scratch.'.format(checkpoint_abs_path))
def load_model_checkpoint(self): '\n This function loads a model checkpoint if there is a checkpoint with the models configuration name\n :return:\n ' checkpoint_abs_path = os.path.join(self.checkpoint_folder_path, self.checkpoint_filename) if os.path.exists(checkpoint_abs_path): checkpoint = torch.load(checkpoint_abs_path) self.model.load_state_dict(checkpoint['model_state_dict']) self.optimizer.load_state_dict(checkpoint['optimizer_state_dict']) self.start_epoch = checkpoint['epoch'] self.log.info('Loaded {} model. Starting from the epoch number {}. Checkpoint path: {}'.format(self.model_configuration_name, self.start_epoch, checkpoint_abs_path)) self.model.train() else: self.log.info('No checkpoint found at {}. Training will start from scratch.'.format(checkpoint_abs_path))<|docstring|>This function loads a model checkpoint if there is a checkpoint with the models configuration name :return:<|endoftext|>
4e0c3adb8481e15e418174717958631ae6bb5bab890e488f7ecc3a581f281588
def pull_nytimes() -> int: 'Adds new nytimes stuff to database and returns status code' print('Getting newslets..') search = f'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=coronavirus&begindate=20200301&api-key={config.NYTIMES_KEY}' resp = requests.get(search) if (resp.status_code != 200): return resp.status_code for newslet in resp.json()['response']['docs']: if (Newslet.query.filter_by(id=newslet['web_url']).first() is None): new_newslet = Newslet(newslet['web_url'], newslet['snippet'], newslet['lead_paragraph']) db.session.add(new_newslet) db.session.commit() return resp.status_code
Adds new nytimes stuff to database and returns status code
covidmap.py
pull_nytimes
sneakykiwi/CovidMap
2
python
def pull_nytimes() -> int: print('Getting newslets..') search = f'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=coronavirus&begindate=20200301&api-key={config.NYTIMES_KEY}' resp = requests.get(search) if (resp.status_code != 200): return resp.status_code for newslet in resp.json()['response']['docs']: if (Newslet.query.filter_by(id=newslet['web_url']).first() is None): new_newslet = Newslet(newslet['web_url'], newslet['snippet'], newslet['lead_paragraph']) db.session.add(new_newslet) db.session.commit() return resp.status_code
def pull_nytimes() -> int: print('Getting newslets..') search = f'https://api.nytimes.com/svc/search/v2/articlesearch.json?q=coronavirus&begindate=20200301&api-key={config.NYTIMES_KEY}' resp = requests.get(search) if (resp.status_code != 200): return resp.status_code for newslet in resp.json()['response']['docs']: if (Newslet.query.filter_by(id=newslet['web_url']).first() is None): new_newslet = Newslet(newslet['web_url'], newslet['snippet'], newslet['lead_paragraph']) db.session.add(new_newslet) db.session.commit() return resp.status_code<|docstring|>Adds new nytimes stuff to database and returns status code<|endoftext|>
ac056637b548e6f7c316621fd7691ef82e97218d6e750b2a49b4354fa30cce81
def populate_db(): 'Top-level function for getting all csv data from github' dbpath = 'covidmap.db' if os.path.exists(dbpath): os.remove(dbpath) print('Adding stats..') db.create_all() print('Adding newslets..') nytimes_respcode = pull_nytimes() if (nytimes_respcode != 200): print(f"Failed to add newslets, error code: '{nytimes_respcode}'!") print('Adding provinces..') province_to_db() csv_data = json.loads(csvtojson()) for country_name in csv_data: new_country = Country(country_name, csv_data[country_name]) db.session.add(new_country) db.session.commit()
Top-level function for getting all csv data from github
covidmap.py
populate_db
sneakykiwi/CovidMap
2
python
def populate_db(): dbpath = 'covidmap.db' if os.path.exists(dbpath): os.remove(dbpath) print('Adding stats..') db.create_all() print('Adding newslets..') nytimes_respcode = pull_nytimes() if (nytimes_respcode != 200): print(f"Failed to add newslets, error code: '{nytimes_respcode}'!") print('Adding provinces..') province_to_db() csv_data = json.loads(csvtojson()) for country_name in csv_data: new_country = Country(country_name, csv_data[country_name]) db.session.add(new_country) db.session.commit()
def populate_db(): dbpath = 'covidmap.db' if os.path.exists(dbpath): os.remove(dbpath) print('Adding stats..') db.create_all() print('Adding newslets..') nytimes_respcode = pull_nytimes() if (nytimes_respcode != 200): print(f"Failed to add newslets, error code: '{nytimes_respcode}'!") print('Adding provinces..') province_to_db() csv_data = json.loads(csvtojson()) for country_name in csv_data: new_country = Country(country_name, csv_data[country_name]) db.session.add(new_country) db.session.commit()<|docstring|>Top-level function for getting all csv data from github<|endoftext|>
af089a6e5a7983c08a39d6f6b5b40b3f6b95c425bb93c9c879f5bad4b7c52541
def _get_env(self, env: str, fallback: str=None) -> str: 'Gets env var (boilerplate interchangable)' if fallback: try: return os.environ[env] except: return fallback return os.environ[env]
Gets env var (boilerplate interchangable)
covidmap.py
_get_env
sneakykiwi/CovidMap
2
python
def _get_env(self, env: str, fallback: str=None) -> str: if fallback: try: return os.environ[env] except: return fallback return os.environ[env]
def _get_env(self, env: str, fallback: str=None) -> str: if fallback: try: return os.environ[env] except: return fallback return os.environ[env]<|docstring|>Gets env var (boilerplate interchangable)<|endoftext|>
3b37056e14a526989e1ccfb435d228fa29f71bb1376d02aecc5bb09da9cf3d5e
@commands('weather', 'wea') @example('.weather') @example('.weather London') @example('.weather Seattle, US') @example('.weather 90210') def weather_command(bot, trigger): '.weather location - Show the weather at the given location.' if ((bot.config.weather.weather_api_key is None) or (bot.config.weather.weather_api_key == '')): return bot.reply('Weather API key missing. Please configure this module.') if ((bot.config.weather.geocoords_api_key is None) or (bot.config.weather.geocoords_api_key == '')): return bot.reply('GeoCoords API key missing. Please configure this module.') location = trigger.group(2) if (not location): latitude = bot.db.get_nick_value(trigger.nick, 'latitude') longitude = bot.db.get_nick_value(trigger.nick, 'longitude') if ((not latitude) or (not longitude)): return bot.say("I don't know where you live. Give me a location, like {pfx}{command} London, or tell me where you live by saying {pfx}setlocation London, for example.".format(command=trigger.group(1), pfx=bot.config.core.help_prefix)) try: data = get_weather(bot, trigger) except Exception as err: bot.reply(('Could not get weather: ' + str(err))) return weather = u'{location}: {temp}, {condition}, {humidity}'.format(location=data['location'], temp=get_temp(data['temp']), condition=data['condition'], humidity=get_humidity(data['humidity'])) if ('uvindex' in data.keys()): weather += ', UV Index: {uvindex}'.format(uvindex=data['uvindex']) if bot.config.weather.sunrise_sunset: tz = data['timezone'] sr = convert_timestamp(data['sunrise'], tz) ss = convert_timestamp(data['sunset'], tz) weather += ', Sunrise: {sunrise} Sunset: {sunset}'.format(sunrise=sr, sunset=ss) weather += ', {wind}'.format(wind=get_wind(data['wind']['speed'], data['wind']['bearing'])) return bot.say(weather)
.weather location - Show the weather at the given location.
sopel_modules/weather/weather.py
weather_command
RustyBower/sopel-weather
3
python
@commands('weather', 'wea') @example('.weather') @example('.weather London') @example('.weather Seattle, US') @example('.weather 90210') def weather_command(bot, trigger): if ((bot.config.weather.weather_api_key is None) or (bot.config.weather.weather_api_key == )): return bot.reply('Weather API key missing. Please configure this module.') if ((bot.config.weather.geocoords_api_key is None) or (bot.config.weather.geocoords_api_key == )): return bot.reply('GeoCoords API key missing. Please configure this module.') location = trigger.group(2) if (not location): latitude = bot.db.get_nick_value(trigger.nick, 'latitude') longitude = bot.db.get_nick_value(trigger.nick, 'longitude') if ((not latitude) or (not longitude)): return bot.say("I don't know where you live. Give me a location, like {pfx}{command} London, or tell me where you live by saying {pfx}setlocation London, for example.".format(command=trigger.group(1), pfx=bot.config.core.help_prefix)) try: data = get_weather(bot, trigger) except Exception as err: bot.reply(('Could not get weather: ' + str(err))) return weather = u'{location}: {temp}, {condition}, {humidity}'.format(location=data['location'], temp=get_temp(data['temp']), condition=data['condition'], humidity=get_humidity(data['humidity'])) if ('uvindex' in data.keys()): weather += ', UV Index: {uvindex}'.format(uvindex=data['uvindex']) if bot.config.weather.sunrise_sunset: tz = data['timezone'] sr = convert_timestamp(data['sunrise'], tz) ss = convert_timestamp(data['sunset'], tz) weather += ', Sunrise: {sunrise} Sunset: {sunset}'.format(sunrise=sr, sunset=ss) weather += ', {wind}'.format(wind=get_wind(data['wind']['speed'], data['wind']['bearing'])) return bot.say(weather)
@commands('weather', 'wea') @example('.weather') @example('.weather London') @example('.weather Seattle, US') @example('.weather 90210') def weather_command(bot, trigger): if ((bot.config.weather.weather_api_key is None) or (bot.config.weather.weather_api_key == )): return bot.reply('Weather API key missing. Please configure this module.') if ((bot.config.weather.geocoords_api_key is None) or (bot.config.weather.geocoords_api_key == )): return bot.reply('GeoCoords API key missing. Please configure this module.') location = trigger.group(2) if (not location): latitude = bot.db.get_nick_value(trigger.nick, 'latitude') longitude = bot.db.get_nick_value(trigger.nick, 'longitude') if ((not latitude) or (not longitude)): return bot.say("I don't know where you live. Give me a location, like {pfx}{command} London, or tell me where you live by saying {pfx}setlocation London, for example.".format(command=trigger.group(1), pfx=bot.config.core.help_prefix)) try: data = get_weather(bot, trigger) except Exception as err: bot.reply(('Could not get weather: ' + str(err))) return weather = u'{location}: {temp}, {condition}, {humidity}'.format(location=data['location'], temp=get_temp(data['temp']), condition=data['condition'], humidity=get_humidity(data['humidity'])) if ('uvindex' in data.keys()): weather += ', UV Index: {uvindex}'.format(uvindex=data['uvindex']) if bot.config.weather.sunrise_sunset: tz = data['timezone'] sr = convert_timestamp(data['sunrise'], tz) ss = convert_timestamp(data['sunset'], tz) weather += ', Sunrise: {sunrise} Sunset: {sunset}'.format(sunrise=sr, sunset=ss) weather += ', {wind}'.format(wind=get_wind(data['wind']['speed'], data['wind']['bearing'])) return bot.say(weather)<|docstring|>.weather location - Show the weather at the given location.<|endoftext|>
d3a3baff2020c9adf51e902d2542d594dd272dde0780296b770c22f1db83ae4f
@commands('forecast', 'fc') @example('.forecast') @example('.forecast London') @example('.forecast Seattle, US') @example('.forecast 90210') def forecast_command(bot, trigger): '.forecast location - Show the weather forecast for tomorrow at the given location.' if ((bot.config.weather.weather_api_key is None) or (bot.config.weather.weather_api_key == '')): return bot.reply('Weather API key missing. Please configure this module.') if ((bot.config.weather.geocoords_api_key is None) or (bot.config.weather.geocoords_api_key == '')): return bot.reply('GeoCoords API key missing. Please configure this module.') location = trigger.group(2) if (not location): latitude = bot.db.get_nick_value(trigger.nick, 'latitude') longitude = bot.db.get_nick_value(trigger.nick, 'longitude') if ((not latitude) or (not longitude)): return bot.say("I don't know where you live. Give me a location, like {pfx}{command} London, or tell me where you live by saying {pfx}setlocation London, for example.".format(command=trigger.group(1), pfx=bot.config.core.help_prefix)) try: data = get_forecast(bot, trigger) except Exception as err: bot.reply(('Could not get forecast: ' + str(err))) return forecast = '{location}'.format(location=data['location']) for day in data['data']: forecast += ' :: {dow} - {summary} - {high_temp} / {low_temp}'.format(dow=day.get('dow'), summary=day.get('summary'), high_temp=get_temp(day.get('high_temp')), low_temp=get_temp(day.get('low_temp'))) return bot.say(forecast)
.forecast location - Show the weather forecast for tomorrow at the given location.
sopel_modules/weather/weather.py
forecast_command
RustyBower/sopel-weather
3
python
@commands('forecast', 'fc') @example('.forecast') @example('.forecast London') @example('.forecast Seattle, US') @example('.forecast 90210') def forecast_command(bot, trigger): if ((bot.config.weather.weather_api_key is None) or (bot.config.weather.weather_api_key == )): return bot.reply('Weather API key missing. Please configure this module.') if ((bot.config.weather.geocoords_api_key is None) or (bot.config.weather.geocoords_api_key == )): return bot.reply('GeoCoords API key missing. Please configure this module.') location = trigger.group(2) if (not location): latitude = bot.db.get_nick_value(trigger.nick, 'latitude') longitude = bot.db.get_nick_value(trigger.nick, 'longitude') if ((not latitude) or (not longitude)): return bot.say("I don't know where you live. Give me a location, like {pfx}{command} London, or tell me where you live by saying {pfx}setlocation London, for example.".format(command=trigger.group(1), pfx=bot.config.core.help_prefix)) try: data = get_forecast(bot, trigger) except Exception as err: bot.reply(('Could not get forecast: ' + str(err))) return forecast = '{location}'.format(location=data['location']) for day in data['data']: forecast += ' :: {dow} - {summary} - {high_temp} / {low_temp}'.format(dow=day.get('dow'), summary=day.get('summary'), high_temp=get_temp(day.get('high_temp')), low_temp=get_temp(day.get('low_temp'))) return bot.say(forecast)
@commands('forecast', 'fc') @example('.forecast') @example('.forecast London') @example('.forecast Seattle, US') @example('.forecast 90210') def forecast_command(bot, trigger): if ((bot.config.weather.weather_api_key is None) or (bot.config.weather.weather_api_key == )): return bot.reply('Weather API key missing. Please configure this module.') if ((bot.config.weather.geocoords_api_key is None) or (bot.config.weather.geocoords_api_key == )): return bot.reply('GeoCoords API key missing. Please configure this module.') location = trigger.group(2) if (not location): latitude = bot.db.get_nick_value(trigger.nick, 'latitude') longitude = bot.db.get_nick_value(trigger.nick, 'longitude') if ((not latitude) or (not longitude)): return bot.say("I don't know where you live. Give me a location, like {pfx}{command} London, or tell me where you live by saying {pfx}setlocation London, for example.".format(command=trigger.group(1), pfx=bot.config.core.help_prefix)) try: data = get_forecast(bot, trigger) except Exception as err: bot.reply(('Could not get forecast: ' + str(err))) return forecast = '{location}'.format(location=data['location']) for day in data['data']: forecast += ' :: {dow} - {summary} - {high_temp} / {low_temp}'.format(dow=day.get('dow'), summary=day.get('summary'), high_temp=get_temp(day.get('high_temp')), low_temp=get_temp(day.get('low_temp'))) return bot.say(forecast)<|docstring|>.forecast location - Show the weather forecast for tomorrow at the given location.<|endoftext|>
293a1d999a4676ff35f62add98a8d6158607732e6aad66265677a23ecd752b9e
@commands('setlocation') @example('.setlocation London') @example('.setlocation Seattle, US') @example('.setlocation 90210') @example('.setlocation w7174408') def update_location(bot, trigger): 'Set your location for fetching weather.' if ((bot.config.weather.geocoords_api_key is None) or (bot.config.weather.geocoords_api_key == '')): return bot.reply('GeoCoords API key missing. Please configure this module.') if (not trigger.group(2)): bot.reply('Give me a location, like "London" or "90210".') return NOLIMIT try: (latitude, longitude, location) = get_geocoords(bot, trigger) except Exception as err: bot.reply(('Could not find location details: ' + str(err))) return bot.db.set_nick_value(trigger.nick, 'latitude', latitude) bot.db.set_nick_value(trigger.nick, 'longitude', longitude) bot.db.set_nick_value(trigger.nick, 'location', location) return bot.reply('I now have you at {}'.format(location))
Set your location for fetching weather.
sopel_modules/weather/weather.py
update_location
RustyBower/sopel-weather
3
python
@commands('setlocation') @example('.setlocation London') @example('.setlocation Seattle, US') @example('.setlocation 90210') @example('.setlocation w7174408') def update_location(bot, trigger): if ((bot.config.weather.geocoords_api_key is None) or (bot.config.weather.geocoords_api_key == )): return bot.reply('GeoCoords API key missing. Please configure this module.') if (not trigger.group(2)): bot.reply('Give me a location, like "London" or "90210".') return NOLIMIT try: (latitude, longitude, location) = get_geocoords(bot, trigger) except Exception as err: bot.reply(('Could not find location details: ' + str(err))) return bot.db.set_nick_value(trigger.nick, 'latitude', latitude) bot.db.set_nick_value(trigger.nick, 'longitude', longitude) bot.db.set_nick_value(trigger.nick, 'location', location) return bot.reply('I now have you at {}'.format(location))
@commands('setlocation') @example('.setlocation London') @example('.setlocation Seattle, US') @example('.setlocation 90210') @example('.setlocation w7174408') def update_location(bot, trigger): if ((bot.config.weather.geocoords_api_key is None) or (bot.config.weather.geocoords_api_key == )): return bot.reply('GeoCoords API key missing. Please configure this module.') if (not trigger.group(2)): bot.reply('Give me a location, like "London" or "90210".') return NOLIMIT try: (latitude, longitude, location) = get_geocoords(bot, trigger) except Exception as err: bot.reply(('Could not find location details: ' + str(err))) return bot.db.set_nick_value(trigger.nick, 'latitude', latitude) bot.db.set_nick_value(trigger.nick, 'longitude', longitude) bot.db.set_nick_value(trigger.nick, 'location', location) return bot.reply('I now have you at {}'.format(location))<|docstring|>Set your location for fetching weather.<|endoftext|>
5af94be2db4f8bb23993360789e9923994ddae4e85a18bae91ea426e3e85c56c
def tearDown(self): 'Clean up the rache:* redis keys' keys = r.keys('{0}*'.format(REDIS_PREFIX)) for key in keys: r.delete(key)
Clean up the rache:* redis keys
tests.py
tearDown
brutasse/rache
3
python
def tearDown(self): keys = r.keys('{0}*'.format(REDIS_PREFIX)) for key in keys: r.delete(key)
def tearDown(self): keys = r.keys('{0}*'.format(REDIS_PREFIX)) for key in keys: r.delete(key)<|docstring|>Clean up the rache:* redis keys<|endoftext|>
4710d72c6edeca6bf77403f9d17a6f1b2c8aa507fa0fad7b5b3abc1f9c89ff96
def fix_ang(ang: float) -> float: '\n Transforms the given angle into the range -pi...pi\n ' return (((ang + math.pi) % math.tau) - math.pi)
Transforms the given angle into the range -pi...pi
RLBotPack/Sniper/rlmath.py
fix_ang
lucas-emery/RLBotPack
13
python
def fix_ang(ang: float) -> float: '\n \n ' return (((ang + math.pi) % math.tau) - math.pi)
def fix_ang(ang: float) -> float: '\n \n ' return (((ang + math.pi) % math.tau) - math.pi)<|docstring|>Transforms the given angle into the range -pi...pi<|endoftext|>
5edfc5c53e8572a98b96d4ea6b7bbbd06b91fce8fd505b1608e98c643226b112
def proj_onto(src: Vec3, dir: Vec3) -> Vec3: '\n Returns the vector component of src that is parallel with dir, i.e. the projection of src onto dir.\n ' try: return ((dot(src, dir) / dot(dir, dir)) * dir) except ZeroDivisionError: return Vec3()
Returns the vector component of src that is parallel with dir, i.e. the projection of src onto dir.
RLBotPack/Sniper/rlmath.py
proj_onto
lucas-emery/RLBotPack
13
python
def proj_onto(src: Vec3, dir: Vec3) -> Vec3: '\n \n ' try: return ((dot(src, dir) / dot(dir, dir)) * dir) except ZeroDivisionError: return Vec3()
def proj_onto(src: Vec3, dir: Vec3) -> Vec3: '\n \n ' try: return ((dot(src, dir) / dot(dir, dir)) * dir) except ZeroDivisionError: return Vec3()<|docstring|>Returns the vector component of src that is parallel with dir, i.e. the projection of src onto dir.<|endoftext|>
c22170e9b335eb4bfa4b0e0a231eaaf92435d426a3afcfabb03a7c5817b37c63
def proj_onto_size(src: Vec3, dir: Vec3) -> float: '\n Returns the size of the vector that is the project of src onto dir\n ' try: dir_n = normalize(dir) return (dot(src, dir_n) / dot(dir_n, dir_n)) except ZeroDivisionError: return norm(src)
Returns the size of the vector that is the project of src onto dir
RLBotPack/Sniper/rlmath.py
proj_onto_size
lucas-emery/RLBotPack
13
python
def proj_onto_size(src: Vec3, dir: Vec3) -> float: '\n \n ' try: dir_n = normalize(dir) return (dot(src, dir_n) / dot(dir_n, dir_n)) except ZeroDivisionError: return norm(src)
def proj_onto_size(src: Vec3, dir: Vec3) -> float: '\n \n ' try: dir_n = normalize(dir) return (dot(src, dir_n) / dot(dir_n, dir_n)) except ZeroDivisionError: return norm(src)<|docstring|>Returns the size of the vector that is the project of src onto dir<|endoftext|>
af2562f88c8562bda6e04c4927e436291886ca456baa2e67e9e17076dd169450
def curve_from_arrival_dir(src, target, arrival_direction, w=1): '\n Returns a point that is equally far from src and target on the line going through target with the given direction\n ' dir = normalize(arrival_direction) tx = target.x ty = target.y sx = src.x sy = src.y dx = dir.x dy = dir.y t = ((- ((((((tx * tx) - ((2 * tx) * sx)) + (ty * ty)) - ((2 * ty) * sy)) + (sx * sx)) + (sy * sy))) / (2 * ((((tx * dx) + (ty * dy)) - (sx * dx)) - (sy * dy)))) t = clip(t, (- 1700), 1700) return (target + ((w * t) * dir))
Returns a point that is equally far from src and target on the line going through target with the given direction
RLBotPack/Sniper/rlmath.py
curve_from_arrival_dir
lucas-emery/RLBotPack
13
python
def curve_from_arrival_dir(src, target, arrival_direction, w=1): '\n \n ' dir = normalize(arrival_direction) tx = target.x ty = target.y sx = src.x sy = src.y dx = dir.x dy = dir.y t = ((- ((((((tx * tx) - ((2 * tx) * sx)) + (ty * ty)) - ((2 * ty) * sy)) + (sx * sx)) + (sy * sy))) / (2 * ((((tx * dx) + (ty * dy)) - (sx * dx)) - (sy * dy)))) t = clip(t, (- 1700), 1700) return (target + ((w * t) * dir))
def curve_from_arrival_dir(src, target, arrival_direction, w=1): '\n \n ' dir = normalize(arrival_direction) tx = target.x ty = target.y sx = src.x sy = src.y dx = dir.x dy = dir.y t = ((- ((((((tx * tx) - ((2 * tx) * sx)) + (ty * ty)) - ((2 * ty) * sy)) + (sx * sx)) + (sy * sy))) / (2 * ((((tx * dx) + (ty * dy)) - (sx * dx)) - (sy * dy)))) t = clip(t, (- 1700), 1700) return (target + ((w * t) * dir))<|docstring|>Returns a point that is equally far from src and target on the line going through target with the given direction<|endoftext|>
5e6e806c7d1540e87d81e998eff900b4709e5e3e4230a0320e1bd6992d167d1f
def bezier(t: float, points: list) -> Vec3: '\n Returns a point on a bezier curve made from the given controls points\n ' n = len(points) if (n == 1): return points[0] else: return (((1 - t) * bezier(t, points[0:(- 1)])) + (t * bezier(t, points[1:n])))
Returns a point on a bezier curve made from the given controls points
RLBotPack/Sniper/rlmath.py
bezier
lucas-emery/RLBotPack
13
python
def bezier(t: float, points: list) -> Vec3: '\n \n ' n = len(points) if (n == 1): return points[0] else: return (((1 - t) * bezier(t, points[0:(- 1)])) + (t * bezier(t, points[1:n])))
def bezier(t: float, points: list) -> Vec3: '\n \n ' n = len(points) if (n == 1): return points[0] else: return (((1 - t) * bezier(t, points[0:(- 1)])) + (t * bezier(t, points[1:n])))<|docstring|>Returns a point on a bezier curve made from the given controls points<|endoftext|>
de04819004183c3347de77c77379be986d7f682285b39ffc7343b7644211011c
def is_closer_to_goal_than(a: Vec3, b: Vec3, team_index): ' Returns true if a is closer than b to goal owned by the given team ' return ((a.y < b.y), (a.y > b.y))[team_index]
Returns true if a is closer than b to goal owned by the given team
RLBotPack/Sniper/rlmath.py
is_closer_to_goal_than
lucas-emery/RLBotPack
13
python
def is_closer_to_goal_than(a: Vec3, b: Vec3, team_index): ' ' return ((a.y < b.y), (a.y > b.y))[team_index]
def is_closer_to_goal_than(a: Vec3, b: Vec3, team_index): ' ' return ((a.y < b.y), (a.y > b.y))[team_index]<|docstring|>Returns true if a is closer than b to goal owned by the given team<|endoftext|>
b737f0ffadc519f841417334c6429b0d6ad79e8b75c8a21a5dba66d74f27720c
def __init__(self, replay_downloader, download_validator): '\n Parameters\n ----------\n replay_downloader : clare.application.download_bot.interfaces.IReplayDownloader\n download_validator : clare.application.download_bot.interfaces.DownloadValidator\n ' self._replay_downloader = replay_downloader self._download_validator = download_validator
Parameters ---------- replay_downloader : clare.application.download_bot.interfaces.IReplayDownloader download_validator : clare.application.download_bot.interfaces.DownloadValidator
clare/clare/application/download_bot/download_bots.py
__init__
dnguyen0304/room-list-watcher
0
python
def __init__(self, replay_downloader, download_validator): '\n Parameters\n ----------\n replay_downloader : clare.application.download_bot.interfaces.IReplayDownloader\n download_validator : clare.application.download_bot.interfaces.DownloadValidator\n ' self._replay_downloader = replay_downloader self._download_validator = download_validator
def __init__(self, replay_downloader, download_validator): '\n Parameters\n ----------\n replay_downloader : clare.application.download_bot.interfaces.IReplayDownloader\n download_validator : clare.application.download_bot.interfaces.DownloadValidator\n ' self._replay_downloader = replay_downloader self._download_validator = download_validator<|docstring|>Parameters ---------- replay_downloader : clare.application.download_bot.interfaces.IReplayDownloader download_validator : clare.application.download_bot.interfaces.DownloadValidator<|endoftext|>
8a87690c0621ef8ebd87af68764dac1cd2750b24c31b741918bfa337b4533197
def run(self, url): '\n Parameters\n ----------\n url : str\n\n Returns\n -------\n str\n Path to the downloaded file.\n ' self._replay_downloader.run(url=url) file_path = self._download_validator.run() return file_path
Parameters ---------- url : str Returns ------- str Path to the downloaded file.
clare/clare/application/download_bot/download_bots.py
run
dnguyen0304/room-list-watcher
0
python
def run(self, url): '\n Parameters\n ----------\n url : str\n\n Returns\n -------\n str\n Path to the downloaded file.\n ' self._replay_downloader.run(url=url) file_path = self._download_validator.run() return file_path
def run(self, url): '\n Parameters\n ----------\n url : str\n\n Returns\n -------\n str\n Path to the downloaded file.\n ' self._replay_downloader.run(url=url) file_path = self._download_validator.run() return file_path<|docstring|>Parameters ---------- url : str Returns ------- str Path to the downloaded file.<|endoftext|>
9fd5d7be5d7643218a8839afdd9db2aaae8314dec376463136c93fced7abeb90
def __init__(self, download_bot, logger): '\n Parameters\n ----------\n download_bot : clare.application.download_bot.download_bots.DownloadBot\n logger : logging.Logger\n ' self._download_bot = download_bot self._logger = logger
Parameters ---------- download_bot : clare.application.download_bot.download_bots.DownloadBot logger : logging.Logger
clare/clare/application/download_bot/download_bots.py
__init__
dnguyen0304/room-list-watcher
0
python
def __init__(self, download_bot, logger): '\n Parameters\n ----------\n download_bot : clare.application.download_bot.download_bots.DownloadBot\n logger : logging.Logger\n ' self._download_bot = download_bot self._logger = logger
def __init__(self, download_bot, logger): '\n Parameters\n ----------\n download_bot : clare.application.download_bot.download_bots.DownloadBot\n logger : logging.Logger\n ' self._download_bot = download_bot self._logger = logger<|docstring|>Parameters ---------- download_bot : clare.application.download_bot.download_bots.DownloadBot logger : logging.Logger<|endoftext|>
1b8c76ccbb09f29af68078c08cdbfedcb58a7f78d053f388698c4d6d471340f5
def __init__(self, download_bot): '\n Parameters\n ----------\n download_bot : clare.application.download_bot.download_bots.DownloadBot\n ' self._download_bot = download_bot
Parameters ---------- download_bot : clare.application.download_bot.download_bots.DownloadBot
clare/clare/application/download_bot/download_bots.py
__init__
dnguyen0304/room-list-watcher
0
python
def __init__(self, download_bot): '\n Parameters\n ----------\n download_bot : clare.application.download_bot.download_bots.DownloadBot\n ' self._download_bot = download_bot
def __init__(self, download_bot): '\n Parameters\n ----------\n download_bot : clare.application.download_bot.download_bots.DownloadBot\n ' self._download_bot = download_bot<|docstring|>Parameters ---------- download_bot : clare.application.download_bot.download_bots.DownloadBot<|endoftext|>
afc091db1c15a0480c90389b0e37f27bdcbc237bef6a909e67a494cb84afa3f4
def __init__(self, download_bot, root_url): '\n Parameters\n ----------\n download_bot : clare.application.download_bot.download_bots.DownloadBot\n root_url : str\n ' self._download_bot = download_bot self._root_url = root_url
Parameters ---------- download_bot : clare.application.download_bot.download_bots.DownloadBot root_url : str
clare/clare/application/download_bot/download_bots.py
__init__
dnguyen0304/room-list-watcher
0
python
def __init__(self, download_bot, root_url): '\n Parameters\n ----------\n download_bot : clare.application.download_bot.download_bots.DownloadBot\n root_url : str\n ' self._download_bot = download_bot self._root_url = root_url
def __init__(self, download_bot, root_url): '\n Parameters\n ----------\n download_bot : clare.application.download_bot.download_bots.DownloadBot\n root_url : str\n ' self._download_bot = download_bot self._root_url = root_url<|docstring|>Parameters ---------- download_bot : clare.application.download_bot.download_bots.DownloadBot root_url : str<|endoftext|>
c967a88ee85132beee0a4fe26f427f1bdecffda76493900636d5a494d60a8388
def setup_platform(hass, config, add_devices, discovery_info=None): 'Find and return Vera covers.' add_devices((VeraCover(device, VERA_CONTROLLER) for device in VERA_DEVICES['cover']))
Find and return Vera covers.
homeassistant/components/cover/vera.py
setup_platform
rubund/debian-home-assistant
13
python
def setup_platform(hass, config, add_devices, discovery_info=None): add_devices((VeraCover(device, VERA_CONTROLLER) for device in VERA_DEVICES['cover']))
def setup_platform(hass, config, add_devices, discovery_info=None): add_devices((VeraCover(device, VERA_CONTROLLER) for device in VERA_DEVICES['cover']))<|docstring|>Find and return Vera covers.<|endoftext|>
0abcb844f0e7d29c6ec1e2d58b79bb0bce5d50072516162de88f26e0dc1cfb4f
def __init__(self, vera_device, controller): 'Initialize the Vera device.' VeraDevice.__init__(self, vera_device, controller)
Initialize the Vera device.
homeassistant/components/cover/vera.py
__init__
rubund/debian-home-assistant
13
python
def __init__(self, vera_device, controller): VeraDevice.__init__(self, vera_device, controller)
def __init__(self, vera_device, controller): VeraDevice.__init__(self, vera_device, controller)<|docstring|>Initialize the Vera device.<|endoftext|>
ba43772e990a6be4208e3d36886447fb0cdc241a99ace433c3c756f5df0b3259
@property def current_cover_position(self): '\n Return current position of cover.\n\n 0 is closed, 100 is fully open.\n ' position = self.vera_device.get_level() if (position <= 5): return 0 if (position >= 95): return 100 return position
Return current position of cover. 0 is closed, 100 is fully open.
homeassistant/components/cover/vera.py
current_cover_position
rubund/debian-home-assistant
13
python
@property def current_cover_position(self): '\n Return current position of cover.\n\n 0 is closed, 100 is fully open.\n ' position = self.vera_device.get_level() if (position <= 5): return 0 if (position >= 95): return 100 return position
@property def current_cover_position(self): '\n Return current position of cover.\n\n 0 is closed, 100 is fully open.\n ' position = self.vera_device.get_level() if (position <= 5): return 0 if (position >= 95): return 100 return position<|docstring|>Return current position of cover. 0 is closed, 100 is fully open.<|endoftext|>
0ec56e07920a720f5c9e383a71e5ff0d6c2092349169f06f2152ac9db9cd2292
def set_cover_position(self, position, **kwargs): 'Move the cover to a specific position.' self.vera_device.set_level(position)
Move the cover to a specific position.
homeassistant/components/cover/vera.py
set_cover_position
rubund/debian-home-assistant
13
python
def set_cover_position(self, position, **kwargs): self.vera_device.set_level(position)
def set_cover_position(self, position, **kwargs): self.vera_device.set_level(position)<|docstring|>Move the cover to a specific position.<|endoftext|>
278b7bcecd10e4ca04aa7bdf593a982efe1c35ae579e37b8e0481baefc6014c3
@property def is_closed(self): 'Return if the cover is closed.' if (self.current_cover_position is not None): if (self.current_cover_position > 0): return False else: return True
Return if the cover is closed.
homeassistant/components/cover/vera.py
is_closed
rubund/debian-home-assistant
13
python
@property def is_closed(self): if (self.current_cover_position is not None): if (self.current_cover_position > 0): return False else: return True
@property def is_closed(self): if (self.current_cover_position is not None): if (self.current_cover_position > 0): return False else: return True<|docstring|>Return if the cover is closed.<|endoftext|>
49b9f2f46f1c812d27458a0c64cd907fef61680d7fbfa61f59e85089a749d4bc
def open_cover(self, **kwargs): 'Open the cover.' self.vera_device.open()
Open the cover.
homeassistant/components/cover/vera.py
open_cover
rubund/debian-home-assistant
13
python
def open_cover(self, **kwargs): self.vera_device.open()
def open_cover(self, **kwargs): self.vera_device.open()<|docstring|>Open the cover.<|endoftext|>
64ba672013de1b9eed9de5130b4e832a5fd6ee69e7e54fda701212ad689632ca
def close_cover(self, **kwargs): 'Close the cover.' self.vera_device.close()
Close the cover.
homeassistant/components/cover/vera.py
close_cover
rubund/debian-home-assistant
13
python
def close_cover(self, **kwargs): self.vera_device.close()
def close_cover(self, **kwargs): self.vera_device.close()<|docstring|>Close the cover.<|endoftext|>
f392ff03dcf05524de0ba808bb576d16ac0e1309af25e34533c6b23bfa051f47
def stop_cover(self, **kwargs): 'Stop the cover.' self.vera_device.stop()
Stop the cover.
homeassistant/components/cover/vera.py
stop_cover
rubund/debian-home-assistant
13
python
def stop_cover(self, **kwargs): self.vera_device.stop()
def stop_cover(self, **kwargs): self.vera_device.stop()<|docstring|>Stop the cover.<|endoftext|>
87c04b08babb26177fcf38bbeee64a15a23e63a78909653ac3365c9651100c7a
def validate_instantiation(**kwargs): 'Checks if a driver is instantiated other than by the unified driver.\n\n Helps check direct instantiation of netapp drivers.\n Call this function in every netapp block driver constructor.\n ' if (kwargs and (kwargs.get('netapp_mode') == 'proxy')): return LOG.warning(_LW('It is not the recommended way to use drivers by NetApp. Please use NetAppDriver to achieve the functionality.'))
Checks if a driver is instantiated other than by the unified driver. Helps check direct instantiation of netapp drivers. Call this function in every netapp block driver constructor.
cinder/volume/drivers/netapp/utils.py
validate_instantiation
bswartz/cinder
11
python
def validate_instantiation(**kwargs): 'Checks if a driver is instantiated other than by the unified driver.\n\n Helps check direct instantiation of netapp drivers.\n Call this function in every netapp block driver constructor.\n ' if (kwargs and (kwargs.get('netapp_mode') == 'proxy')): return LOG.warning(_LW('It is not the recommended way to use drivers by NetApp. Please use NetAppDriver to achieve the functionality.'))
def validate_instantiation(**kwargs): 'Checks if a driver is instantiated other than by the unified driver.\n\n Helps check direct instantiation of netapp drivers.\n Call this function in every netapp block driver constructor.\n ' if (kwargs and (kwargs.get('netapp_mode') == 'proxy')): return LOG.warning(_LW('It is not the recommended way to use drivers by NetApp. Please use NetAppDriver to achieve the functionality.'))<|docstring|>Checks if a driver is instantiated other than by the unified driver. Helps check direct instantiation of netapp drivers. Call this function in every netapp block driver constructor.<|endoftext|>
6adb1bac209555f84b70b7a69e2271b67ac1e36655ebc56f4e906cfc29b7a44e
def check_flags(required_flags, configuration): 'Ensure that the flags we care about are set.' for flag in required_flags: if (not getattr(configuration, flag, None)): msg = (_('Configuration value %s is not set.') % flag) raise exception.InvalidInput(reason=msg)
Ensure that the flags we care about are set.
cinder/volume/drivers/netapp/utils.py
check_flags
bswartz/cinder
11
python
def check_flags(required_flags, configuration): for flag in required_flags: if (not getattr(configuration, flag, None)): msg = (_('Configuration value %s is not set.') % flag) raise exception.InvalidInput(reason=msg)
def check_flags(required_flags, configuration): for flag in required_flags: if (not getattr(configuration, flag, None)): msg = (_('Configuration value %s is not set.') % flag) raise exception.InvalidInput(reason=msg)<|docstring|>Ensure that the flags we care about are set.<|endoftext|>
62e730c52d3af48cfcd00f86cb001dd3739a0c29f9bb0b116101127c150df550
def to_bool(val): 'Converts true, yes, y, 1 to True, False otherwise.' if val: strg = six.text_type(val).lower() if ((strg == 'true') or (strg == 'y') or (strg == 'yes') or (strg == 'enabled') or (strg == '1')): return True else: return False else: return False
Converts true, yes, y, 1 to True, False otherwise.
cinder/volume/drivers/netapp/utils.py
to_bool
bswartz/cinder
11
python
def to_bool(val): if val: strg = six.text_type(val).lower() if ((strg == 'true') or (strg == 'y') or (strg == 'yes') or (strg == 'enabled') or (strg == '1')): return True else: return False else: return False
def to_bool(val): if val: strg = six.text_type(val).lower() if ((strg == 'true') or (strg == 'y') or (strg == 'yes') or (strg == 'enabled') or (strg == '1')): return True else: return False else: return False<|docstring|>Converts true, yes, y, 1 to True, False otherwise.<|endoftext|>
455e945d15d7dd8896c9d8a3e5fb26d9a7a7e30a89c97ab93f5bd5227799bb85
@utils.synchronized('safe_set_attr') def set_safe_attr(instance, attr, val): 'Sets the attribute in a thread safe manner.\n\n Returns if new val was set on attribute.\n If attr already had the value then False.\n ' if ((not instance) or (not attr)): return False old_val = getattr(instance, attr, None) if ((val is None) and (old_val is None)): return False elif (val == old_val): return False else: setattr(instance, attr, val) return True
Sets the attribute in a thread safe manner. Returns if new val was set on attribute. If attr already had the value then False.
cinder/volume/drivers/netapp/utils.py
set_safe_attr
bswartz/cinder
11
python
@utils.synchronized('safe_set_attr') def set_safe_attr(instance, attr, val): 'Sets the attribute in a thread safe manner.\n\n Returns if new val was set on attribute.\n If attr already had the value then False.\n ' if ((not instance) or (not attr)): return False old_val = getattr(instance, attr, None) if ((val is None) and (old_val is None)): return False elif (val == old_val): return False else: setattr(instance, attr, val) return True
@utils.synchronized('safe_set_attr') def set_safe_attr(instance, attr, val): 'Sets the attribute in a thread safe manner.\n\n Returns if new val was set on attribute.\n If attr already had the value then False.\n ' if ((not instance) or (not attr)): return False old_val = getattr(instance, attr, None) if ((val is None) and (old_val is None)): return False elif (val == old_val): return False else: setattr(instance, attr, val) return True<|docstring|>Sets the attribute in a thread safe manner. Returns if new val was set on attribute. If attr already had the value then False.<|endoftext|>
3fd7939c242667c3981c510e48f647c59b9d1d430c6e416b7ae0105e1401b86d
def get_volume_extra_specs(volume): 'Provides extra specs associated with volume.' ctxt = context.get_admin_context() type_id = volume.get('volume_type_id') if (type_id is None): return {} volume_type = volume_types.get_volume_type(ctxt, type_id) if (volume_type is None): return {} extra_specs = volume_type.get('extra_specs', {}) log_extra_spec_warnings(extra_specs) return extra_specs
Provides extra specs associated with volume.
cinder/volume/drivers/netapp/utils.py
get_volume_extra_specs
bswartz/cinder
11
python
def get_volume_extra_specs(volume): ctxt = context.get_admin_context() type_id = volume.get('volume_type_id') if (type_id is None): return {} volume_type = volume_types.get_volume_type(ctxt, type_id) if (volume_type is None): return {} extra_specs = volume_type.get('extra_specs', {}) log_extra_spec_warnings(extra_specs) return extra_specs
def get_volume_extra_specs(volume): ctxt = context.get_admin_context() type_id = volume.get('volume_type_id') if (type_id is None): return {} volume_type = volume_types.get_volume_type(ctxt, type_id) if (volume_type is None): return {} extra_specs = volume_type.get('extra_specs', {}) log_extra_spec_warnings(extra_specs) return extra_specs<|docstring|>Provides extra specs associated with volume.<|endoftext|>