repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
Josef-Friedrich/phrydy | phrydy/mediafile.py | MediaFile.bitdepth | def bitdepth(self):
"""The number of bits per sample in the audio encoding (an int).
Only available for certain file formats (zero where
unavailable).
"""
if hasattr(self.mgfile.info, 'bits_per_sample'):
return self.mgfile.info.bits_per_sample
return 0 | python | def bitdepth(self):
"""The number of bits per sample in the audio encoding (an int).
Only available for certain file formats (zero where
unavailable).
"""
if hasattr(self.mgfile.info, 'bits_per_sample'):
return self.mgfile.info.bits_per_sample
return 0 | [
"def",
"bitdepth",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"mgfile",
".",
"info",
",",
"'bits_per_sample'",
")",
":",
"return",
"self",
".",
"mgfile",
".",
"info",
".",
"bits_per_sample",
"return",
"0"
] | The number of bits per sample in the audio encoding (an int).
Only available for certain file formats (zero where
unavailable). | [
"The",
"number",
"of",
"bits",
"per",
"sample",
"in",
"the",
"audio",
"encoding",
"(",
"an",
"int",
")",
".",
"Only",
"available",
"for",
"certain",
"file",
"formats",
"(",
"zero",
"where",
"unavailable",
")",
"."
] | train | https://github.com/Josef-Friedrich/phrydy/blob/aa13755155977b4776e49f79984f9968ac1d74dc/phrydy/mediafile.py#L2172-L2179 |
Josef-Friedrich/phrydy | phrydy/mediafile.py | MediaFile.channels | def channels(self):
"""The number of channels in the audio (an int)."""
if hasattr(self.mgfile.info, 'channels'):
return self.mgfile.info.channels
return 0 | python | def channels(self):
"""The number of channels in the audio (an int)."""
if hasattr(self.mgfile.info, 'channels'):
return self.mgfile.info.channels
return 0 | [
"def",
"channels",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"mgfile",
".",
"info",
",",
"'channels'",
")",
":",
"return",
"self",
".",
"mgfile",
".",
"info",
".",
"channels",
"return",
"0"
] | The number of channels in the audio (an int). | [
"The",
"number",
"of",
"channels",
"in",
"the",
"audio",
"(",
"an",
"int",
")",
"."
] | train | https://github.com/Josef-Friedrich/phrydy/blob/aa13755155977b4776e49f79984f9968ac1d74dc/phrydy/mediafile.py#L2182-L2186 |
Josef-Friedrich/phrydy | phrydy/mediafile.py | MediaFile.bitrate | def bitrate(self):
"""The number of bits per seconds used in the audio coding (an
int). If this is provided explicitly by the compressed file
format, this is a precise reflection of the encoding. Otherwise,
it is estimated from the on-disk file size. In this case, some
imprecisio... | python | def bitrate(self):
"""The number of bits per seconds used in the audio coding (an
int). If this is provided explicitly by the compressed file
format, this is a precise reflection of the encoding. Otherwise,
it is estimated from the on-disk file size. In this case, some
imprecisio... | [
"def",
"bitrate",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"mgfile",
".",
"info",
",",
"'bitrate'",
")",
"and",
"self",
".",
"mgfile",
".",
"info",
".",
"bitrate",
":",
"# Many formats provide it explicitly.",
"return",
"self",
".",
"mgfil... | The number of bits per seconds used in the audio coding (an
int). If this is provided explicitly by the compressed file
format, this is a precise reflection of the encoding. Otherwise,
it is estimated from the on-disk file size. In this case, some
imprecision is possible because the file... | [
"The",
"number",
"of",
"bits",
"per",
"seconds",
"used",
"in",
"the",
"audio",
"coding",
"(",
"an",
"int",
")",
".",
"If",
"this",
"is",
"provided",
"explicitly",
"by",
"the",
"compressed",
"file",
"format",
"this",
"is",
"a",
"precise",
"reflection",
"o... | train | https://github.com/Josef-Friedrich/phrydy/blob/aa13755155977b4776e49f79984f9968ac1d74dc/phrydy/mediafile.py#L2189-L2207 |
Vital-Fernandez/dazer | bin/lib/Astro_Libraries/cosmics.py | fromfits | def fromfits(infilename, hdu = 0, verbose = True):
"""
Reads a FITS file and returns a 2D numpy array of the data.
Use hdu to specify which HDU you want (default = primary = 0)
"""
pixelarray, hdr = pyfits.getdata(infilename, hdu, header=True)
pixelarray = np.asarray(pixelarray).transpose()... | python | def fromfits(infilename, hdu = 0, verbose = True):
"""
Reads a FITS file and returns a 2D numpy array of the data.
Use hdu to specify which HDU you want (default = primary = 0)
"""
pixelarray, hdr = pyfits.getdata(infilename, hdu, header=True)
pixelarray = np.asarray(pixelarray).transpose()... | [
"def",
"fromfits",
"(",
"infilename",
",",
"hdu",
"=",
"0",
",",
"verbose",
"=",
"True",
")",
":",
"pixelarray",
",",
"hdr",
"=",
"pyfits",
".",
"getdata",
"(",
"infilename",
",",
"hdu",
",",
"header",
"=",
"True",
")",
"pixelarray",
"=",
"np",
".",
... | Reads a FITS file and returns a 2D numpy array of the data.
Use hdu to specify which HDU you want (default = primary = 0) | [
"Reads",
"a",
"FITS",
"file",
"and",
"returns",
"a",
"2D",
"numpy",
"array",
"of",
"the",
"data",
".",
"Use",
"hdu",
"to",
"specify",
"which",
"HDU",
"you",
"want",
"(",
"default",
"=",
"primary",
"=",
"0",
")"
] | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/cosmics.py#L639-L654 |
Vital-Fernandez/dazer | bin/lib/Astro_Libraries/cosmics.py | tofits | def tofits(outfilename, pixelarray, hdr = None, verbose = True):
"""
Takes a 2D numpy array and write it into a FITS file.
If you specify a header (pyfits format, as returned by fromfits()) it will be used for the image.
You can give me boolean numpy arrays, I will convert them into 8 bit integers.
... | python | def tofits(outfilename, pixelarray, hdr = None, verbose = True):
"""
Takes a 2D numpy array and write it into a FITS file.
If you specify a header (pyfits format, as returned by fromfits()) it will be used for the image.
You can give me boolean numpy arrays, I will convert them into 8 bit integers.
... | [
"def",
"tofits",
"(",
"outfilename",
",",
"pixelarray",
",",
"hdr",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"pixelarrayshape",
"=",
"pixelarray",
".",
"shape",
"if",
"verbose",
":",
"print",
"\"FITS export shape : (%i, %i)\"",
"%",
"(",
"pixelarray... | Takes a 2D numpy array and write it into a FITS file.
If you specify a header (pyfits format, as returned by fromfits()) it will be used for the image.
You can give me boolean numpy arrays, I will convert them into 8 bit integers. | [
"Takes",
"a",
"2D",
"numpy",
"array",
"and",
"write",
"it",
"into",
"a",
"FITS",
"file",
".",
"If",
"you",
"specify",
"a",
"header",
"(",
"pyfits",
"format",
"as",
"returned",
"by",
"fromfits",
"()",
")",
"it",
"will",
"be",
"used",
"for",
"the",
"im... | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/cosmics.py#L656-L680 |
Vital-Fernandez/dazer | bin/lib/Astro_Libraries/cosmics.py | subsample | def subsample(a): # this is more a generic function then a method ...
"""
Returns a 2x2-subsampled version of array a (no interpolation, just cutting pixels in 4).
The version below is directly from the scipy cookbook on rebinning :
U{http://www.scipy.org/Cookbook/Rebinning}
There is ndimage.zoom(cu... | python | def subsample(a): # this is more a generic function then a method ...
"""
Returns a 2x2-subsampled version of array a (no interpolation, just cutting pixels in 4).
The version below is directly from the scipy cookbook on rebinning :
U{http://www.scipy.org/Cookbook/Rebinning}
There is ndimage.zoom(cu... | [
"def",
"subsample",
"(",
"a",
")",
":",
"# this is more a generic function then a method ...",
"\"\"\"\n # Ouuwww this is slow ...\n outarray = np.zeros((a.shape[0]*2, a.shape[1]*2), dtype=np.float64)\n for i in range(a.shape[0]):\n for j in range(a.shape[1]): \n outarray... | Returns a 2x2-subsampled version of array a (no interpolation, just cutting pixels in 4).
The version below is directly from the scipy cookbook on rebinning :
U{http://www.scipy.org/Cookbook/Rebinning}
There is ndimage.zoom(cutout.array, 2, order=0, prefilter=False), but it makes funny borders. | [
"Returns",
"a",
"2x2",
"-",
"subsampled",
"version",
"of",
"array",
"a",
"(",
"no",
"interpolation",
"just",
"cutting",
"pixels",
"in",
"4",
")",
".",
"The",
"version",
"below",
"is",
"directly",
"from",
"the",
"scipy",
"cookbook",
"on",
"rebinning",
":",
... | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/cosmics.py#L685-L709 |
Vital-Fernandez/dazer | bin/lib/Astro_Libraries/cosmics.py | rebin2x2 | def rebin2x2(a):
"""
Wrapper around rebin that actually rebins 2 by 2
"""
inshape = np.array(a.shape)
if not (inshape % 2 == np.zeros(2)).all(): # Modulo check to see if size is even
raise RuntimeError, "I want even image shapes !"
return rebin(a, inshape/2) | python | def rebin2x2(a):
"""
Wrapper around rebin that actually rebins 2 by 2
"""
inshape = np.array(a.shape)
if not (inshape % 2 == np.zeros(2)).all(): # Modulo check to see if size is even
raise RuntimeError, "I want even image shapes !"
return rebin(a, inshape/2) | [
"def",
"rebin2x2",
"(",
"a",
")",
":",
"inshape",
"=",
"np",
".",
"array",
"(",
"a",
".",
"shape",
")",
"if",
"not",
"(",
"inshape",
"%",
"2",
"==",
"np",
".",
"zeros",
"(",
"2",
")",
")",
".",
"all",
"(",
")",
":",
"# Modulo check to see if size... | Wrapper around rebin that actually rebins 2 by 2 | [
"Wrapper",
"around",
"rebin",
"that",
"actually",
"rebins",
"2",
"by",
"2"
] | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/cosmics.py#L734-L742 |
Vital-Fernandez/dazer | bin/lib/Astro_Libraries/cosmics.py | cosmicsimage.labelmask | def labelmask(self, verbose = None):
"""
Finds and labels the cosmic "islands" and returns a list of dicts containing their positions.
This is made on purpose for visualizations a la f2n.drawstarslist, but could be useful anyway.
"""
if verbose == None:
verbose = self... | python | def labelmask(self, verbose = None):
"""
Finds and labels the cosmic "islands" and returns a list of dicts containing their positions.
This is made on purpose for visualizations a la f2n.drawstarslist, but could be useful anyway.
"""
if verbose == None:
verbose = self... | [
"def",
"labelmask",
"(",
"self",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"verbose",
"==",
"None",
":",
"verbose",
"=",
"self",
".",
"verbose",
"if",
"verbose",
":",
"print",
"\"Labeling mask pixels ...\"",
"# We morphologicaly dilate the mask to generously conn... | Finds and labels the cosmic "islands" and returns a list of dicts containing their positions.
This is made on purpose for visualizations a la f2n.drawstarslist, but could be useful anyway. | [
"Finds",
"and",
"labels",
"the",
"cosmic",
"islands",
"and",
"returns",
"a",
"list",
"of",
"dicts",
"containing",
"their",
"positions",
".",
"This",
"is",
"made",
"on",
"purpose",
"for",
"visualizations",
"a",
"la",
"f2n",
".",
"drawstarslist",
"but",
"could... | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/cosmics.py#L154-L185 |
Vital-Fernandez/dazer | bin/lib/Astro_Libraries/cosmics.py | cosmicsimage.getdilatedmask | def getdilatedmask(self, size=3):
"""
Returns a morphologically dilated copy of the current mask.
size = 3 or 5 decides how to dilate.
"""
if size == 3:
dilmask = ndimage.morphology.binary_dilation(self.mask, structure=growkernel, iterations=1, mask=None, output=None,... | python | def getdilatedmask(self, size=3):
"""
Returns a morphologically dilated copy of the current mask.
size = 3 or 5 decides how to dilate.
"""
if size == 3:
dilmask = ndimage.morphology.binary_dilation(self.mask, structure=growkernel, iterations=1, mask=None, output=None,... | [
"def",
"getdilatedmask",
"(",
"self",
",",
"size",
"=",
"3",
")",
":",
"if",
"size",
"==",
"3",
":",
"dilmask",
"=",
"ndimage",
".",
"morphology",
".",
"binary_dilation",
"(",
"self",
".",
"mask",
",",
"structure",
"=",
"growkernel",
",",
"iterations",
... | Returns a morphologically dilated copy of the current mask.
size = 3 or 5 decides how to dilate. | [
"Returns",
"a",
"morphologically",
"dilated",
"copy",
"of",
"the",
"current",
"mask",
".",
"size",
"=",
"3",
"or",
"5",
"decides",
"how",
"to",
"dilate",
"."
] | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/cosmics.py#L188-L200 |
Vital-Fernandez/dazer | bin/lib/Astro_Libraries/cosmics.py | cosmicsimage.clean | def clean(self, mask = None, verbose = None):
"""
Given the mask, we replace the actual problematic pixels with the masked 5x5 median value.
This mimics what is done in L.A.Cosmic, but it's a bit harder to do in python, as there is no
readymade masked median. So for now we do a loop...
... | python | def clean(self, mask = None, verbose = None):
"""
Given the mask, we replace the actual problematic pixels with the masked 5x5 median value.
This mimics what is done in L.A.Cosmic, but it's a bit harder to do in python, as there is no
readymade masked median. So for now we do a loop...
... | [
"def",
"clean",
"(",
"self",
",",
"mask",
"=",
"None",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"verbose",
"==",
"None",
":",
"verbose",
"=",
"self",
".",
"verbose",
"if",
"mask",
"==",
"None",
":",
"mask",
"=",
"self",
".",
"mask",
"if",
"ve... | Given the mask, we replace the actual problematic pixels with the masked 5x5 median value.
This mimics what is done in L.A.Cosmic, but it's a bit harder to do in python, as there is no
readymade masked median. So for now we do a loop...
Saturated stars, if calculated, are also masked : they are ... | [
"Given",
"the",
"mask",
"we",
"replace",
"the",
"actual",
"problematic",
"pixels",
"with",
"the",
"masked",
"5x5",
"median",
"value",
".",
"This",
"mimics",
"what",
"is",
"done",
"in",
"L",
".",
"A",
".",
"Cosmic",
"but",
"it",
"s",
"a",
"bit",
"harder... | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/cosmics.py#L203-L294 |
Vital-Fernandez/dazer | bin/lib/Astro_Libraries/cosmics.py | cosmicsimage.findsatstars | def findsatstars(self, verbose = None):
"""
Uses the satlevel to find saturated stars (not cosmics !), and puts the result as a mask in self.satstars.
This can then be used to avoid these regions in cosmic detection and cleaning procedures.
Slow ...
"""
if verbose == None... | python | def findsatstars(self, verbose = None):
"""
Uses the satlevel to find saturated stars (not cosmics !), and puts the result as a mask in self.satstars.
This can then be used to avoid these regions in cosmic detection and cleaning procedures.
Slow ...
"""
if verbose == None... | [
"def",
"findsatstars",
"(",
"self",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"verbose",
"==",
"None",
":",
"verbose",
"=",
"self",
".",
"verbose",
"if",
"verbose",
":",
"print",
"\"Detecting saturated stars ...\"",
"# DETECTION",
"satpixels",
"=",
"self",
... | Uses the satlevel to find saturated stars (not cosmics !), and puts the result as a mask in self.satstars.
This can then be used to avoid these regions in cosmic detection and cleaning procedures.
Slow ... | [
"Uses",
"the",
"satlevel",
"to",
"find",
"saturated",
"stars",
"(",
"not",
"cosmics",
"!",
")",
"and",
"puts",
"the",
"result",
"as",
"a",
"mask",
"in",
"self",
".",
"satstars",
".",
"This",
"can",
"then",
"be",
"used",
"to",
"avoid",
"these",
"regions... | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/cosmics.py#L296-L351 |
Vital-Fernandez/dazer | bin/lib/Astro_Libraries/cosmics.py | cosmicsimage.getsatstars | def getsatstars(self, verbose = None):
"""
Returns the mask of saturated stars after finding them if not yet done.
Intended mainly for external use.
"""
if verbose == None:
verbose = self.verbose
if not self.satlevel > 0:
raise RuntimeError, "Canno... | python | def getsatstars(self, verbose = None):
"""
Returns the mask of saturated stars after finding them if not yet done.
Intended mainly for external use.
"""
if verbose == None:
verbose = self.verbose
if not self.satlevel > 0:
raise RuntimeError, "Canno... | [
"def",
"getsatstars",
"(",
"self",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"verbose",
"==",
"None",
":",
"verbose",
"=",
"self",
".",
"verbose",
"if",
"not",
"self",
".",
"satlevel",
">",
"0",
":",
"raise",
"RuntimeError",
",",
"\"Cannot determine s... | Returns the mask of saturated stars after finding them if not yet done.
Intended mainly for external use. | [
"Returns",
"the",
"mask",
"of",
"saturated",
"stars",
"after",
"finding",
"them",
"if",
"not",
"yet",
"done",
".",
"Intended",
"mainly",
"for",
"external",
"use",
"."
] | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/cosmics.py#L353-L364 |
Vital-Fernandez/dazer | bin/lib/Astro_Libraries/cosmics.py | cosmicsimage.guessbackgroundlevel | def guessbackgroundlevel(self):
"""
Estimates the background level. This could be used to fill pixels in large cosmics.
"""
if self.backgroundlevel == None:
self.backgroundlevel = np.median(self.rawarray.ravel())
return self.backgroundlevel | python | def guessbackgroundlevel(self):
"""
Estimates the background level. This could be used to fill pixels in large cosmics.
"""
if self.backgroundlevel == None:
self.backgroundlevel = np.median(self.rawarray.ravel())
return self.backgroundlevel | [
"def",
"guessbackgroundlevel",
"(",
"self",
")",
":",
"if",
"self",
".",
"backgroundlevel",
"==",
"None",
":",
"self",
".",
"backgroundlevel",
"=",
"np",
".",
"median",
"(",
"self",
".",
"rawarray",
".",
"ravel",
"(",
")",
")",
"return",
"self",
".",
"... | Estimates the background level. This could be used to fill pixels in large cosmics. | [
"Estimates",
"the",
"background",
"level",
".",
"This",
"could",
"be",
"used",
"to",
"fill",
"pixels",
"in",
"large",
"cosmics",
"."
] | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/cosmics.py#L382-L388 |
Vital-Fernandez/dazer | bin/lib/Astro_Libraries/cosmics.py | cosmicsimage.lacosmiciteration | def lacosmiciteration(self, verbose = None):
"""
Performs one iteration of the L.A.Cosmic algorithm.
It operates on self.cleanarray, and afterwards updates self.mask by adding the newly detected
cosmics to the existing self.mask. Cleaning is not made automatically ! You have to call
... | python | def lacosmiciteration(self, verbose = None):
"""
Performs one iteration of the L.A.Cosmic algorithm.
It operates on self.cleanarray, and afterwards updates self.mask by adding the newly detected
cosmics to the existing self.mask. Cleaning is not made automatically ! You have to call
... | [
"def",
"lacosmiciteration",
"(",
"self",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"verbose",
"==",
"None",
":",
"verbose",
"=",
"self",
".",
"verbose",
"if",
"verbose",
":",
"print",
"\"Convolving image with Laplacian kernel ...\"",
"# We subsample, convolve, cl... | Performs one iteration of the L.A.Cosmic algorithm.
It operates on self.cleanarray, and afterwards updates self.mask by adding the newly detected
cosmics to the existing self.mask. Cleaning is not made automatically ! You have to call
clean() after each iteration.
This way you can run it... | [
"Performs",
"one",
"iteration",
"of",
"the",
"L",
".",
"A",
".",
"Cosmic",
"algorithm",
".",
"It",
"operates",
"on",
"self",
".",
"cleanarray",
"and",
"afterwards",
"updates",
"self",
".",
"mask",
"by",
"adding",
"the",
"newly",
"detected",
"cosmics",
"to"... | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/cosmics.py#L391-L531 |
Vital-Fernandez/dazer | bin/lib/Astro_Libraries/cosmics.py | cosmicsimage.run | def run(self, maxiter = 4, verbose = False):
"""
Full artillery :-)
- Find saturated stars
- Run maxiter L.A.Cosmic iterations (stops if no more cosmics are found)
Stops if no cosmics are found or if maxiter is reached.
"""
if self.satlev... | python | def run(self, maxiter = 4, verbose = False):
"""
Full artillery :-)
- Find saturated stars
- Run maxiter L.A.Cosmic iterations (stops if no more cosmics are found)
Stops if no cosmics are found or if maxiter is reached.
"""
if self.satlev... | [
"def",
"run",
"(",
"self",
",",
"maxiter",
"=",
"4",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"self",
".",
"satlevel",
">",
"0",
"and",
"self",
".",
"satstars",
"==",
"None",
":",
"self",
".",
"findsatstars",
"(",
"verbose",
"=",
"True",
")",
... | Full artillery :-)
- Find saturated stars
- Run maxiter L.A.Cosmic iterations (stops if no more cosmics are found)
Stops if no cosmics are found or if maxiter is reached. | [
"Full",
"artillery",
":",
"-",
")",
"-",
"Find",
"saturated",
"stars",
"-",
"Run",
"maxiter",
"L",
".",
"A",
".",
"Cosmic",
"iterations",
"(",
"stops",
"if",
"no",
"more",
"cosmics",
"are",
"found",
")",
"Stops",
"if",
"no",
"cosmics",
"are",
"found",
... | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/cosmics.py#L591-L617 |
shotastage/mirage-django-lts | mirage/proj/environ.py | MirageEnvironment.search_project_root | def search_project_root():
"""
Search your Django project root.
returns:
- path:string Django project root path
"""
while True:
current = os.getcwd()
if pathlib.Path("Miragefile.py").is_file() or pathlib.Path("Miragefile").is_file():
... | python | def search_project_root():
"""
Search your Django project root.
returns:
- path:string Django project root path
"""
while True:
current = os.getcwd()
if pathlib.Path("Miragefile.py").is_file() or pathlib.Path("Miragefile").is_file():
... | [
"def",
"search_project_root",
"(",
")",
":",
"while",
"True",
":",
"current",
"=",
"os",
".",
"getcwd",
"(",
")",
"if",
"pathlib",
".",
"Path",
"(",
"\"Miragefile.py\"",
")",
".",
"is_file",
"(",
")",
"or",
"pathlib",
".",
"Path",
"(",
"\"Miragefile\"",
... | Search your Django project root.
returns:
- path:string Django project root path | [
"Search",
"your",
"Django",
"project",
"root",
"."
] | train | https://github.com/shotastage/mirage-django-lts/blob/4e32dd48fff4b191abb90813ce3cc5ef0654a2ab/mirage/proj/environ.py#L61-L78 |
shotastage/mirage-django-lts | mirage/proj/environ.py | MirageEnvironment.search_app_root | def search_app_root():
"""
Search your Django application root
returns:
- (String) Django application root path
"""
while True:
current = os.getcwd()
if pathlib.Path("apps.py").is_file():
return current
elif pathl... | python | def search_app_root():
"""
Search your Django application root
returns:
- (String) Django application root path
"""
while True:
current = os.getcwd()
if pathlib.Path("apps.py").is_file():
return current
elif pathl... | [
"def",
"search_app_root",
"(",
")",
":",
"while",
"True",
":",
"current",
"=",
"os",
".",
"getcwd",
"(",
")",
"if",
"pathlib",
".",
"Path",
"(",
"\"apps.py\"",
")",
".",
"is_file",
"(",
")",
":",
"return",
"current",
"elif",
"pathlib",
".",
"Path",
"... | Search your Django application root
returns:
- (String) Django application root path | [
"Search",
"your",
"Django",
"application",
"root"
] | train | https://github.com/shotastage/mirage-django-lts/blob/4e32dd48fff4b191abb90813ce3cc5ef0654a2ab/mirage/proj/environ.py#L81-L97 |
shotastage/mirage-django-lts | mirage/proj/environ.py | MirageEnvironment.in_app | def in_app() -> bool:
"""
Judge where current working directory is in Django application or not.
returns:
- (Bool) cwd is in app dir returns True
"""
try:
MirageEnvironment.set_import_root()
import apps
if os.path.isfile("apps.py")... | python | def in_app() -> bool:
"""
Judge where current working directory is in Django application or not.
returns:
- (Bool) cwd is in app dir returns True
"""
try:
MirageEnvironment.set_import_root()
import apps
if os.path.isfile("apps.py")... | [
"def",
"in_app",
"(",
")",
"->",
"bool",
":",
"try",
":",
"MirageEnvironment",
".",
"set_import_root",
"(",
")",
"import",
"apps",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"\"apps.py\"",
")",
":",
"return",
"True",
"else",
":",
"return",
"False",
"... | Judge where current working directory is in Django application or not.
returns:
- (Bool) cwd is in app dir returns True | [
"Judge",
"where",
"current",
"working",
"directory",
"is",
"in",
"Django",
"application",
"or",
"not",
"."
] | train | https://github.com/shotastage/mirage-django-lts/blob/4e32dd48fff4b191abb90813ce3cc5ef0654a2ab/mirage/proj/environ.py#L137-L154 |
kajala/django-jutil | jutil/cache.py | update_cached_fields | def update_cached_fields(*args):
"""
Calls update_cached_fields() for each object passed in as argument.
Supports also iterable objects by checking __iter__ attribute.
:param args: List of objects
:return: None
"""
for a in args:
if a is not None:
if hasattr(a, '__iter__'... | python | def update_cached_fields(*args):
"""
Calls update_cached_fields() for each object passed in as argument.
Supports also iterable objects by checking __iter__ attribute.
:param args: List of objects
:return: None
"""
for a in args:
if a is not None:
if hasattr(a, '__iter__'... | [
"def",
"update_cached_fields",
"(",
"*",
"args",
")",
":",
"for",
"a",
"in",
"args",
":",
"if",
"a",
"is",
"not",
"None",
":",
"if",
"hasattr",
"(",
"a",
",",
"'__iter__'",
")",
":",
"for",
"e",
"in",
"a",
":",
"e",
".",
"update_cached_fields",
"("... | Calls update_cached_fields() for each object passed in as argument.
Supports also iterable objects by checking __iter__ attribute.
:param args: List of objects
:return: None | [
"Calls",
"update_cached_fields",
"()",
"for",
"each",
"object",
"passed",
"in",
"as",
"argument",
".",
"Supports",
"also",
"iterable",
"objects",
"by",
"checking",
"__iter__",
"attribute",
".",
":",
"param",
"args",
":",
"List",
"of",
"objects",
":",
"return",... | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/cache.py#L49-L62 |
kajala/django-jutil | jutil/cache.py | CachedFieldsMixin.update_cached_fields_pre_save | def update_cached_fields_pre_save(self, update_fields: list):
"""
Call on pre_save signal for objects (to automatically refresh on save).
:param update_fields: list of fields to update
"""
if self.id and update_fields is None:
self.update_cached_fields(commit=False, e... | python | def update_cached_fields_pre_save(self, update_fields: list):
"""
Call on pre_save signal for objects (to automatically refresh on save).
:param update_fields: list of fields to update
"""
if self.id and update_fields is None:
self.update_cached_fields(commit=False, e... | [
"def",
"update_cached_fields_pre_save",
"(",
"self",
",",
"update_fields",
":",
"list",
")",
":",
"if",
"self",
".",
"id",
"and",
"update_fields",
"is",
"None",
":",
"self",
".",
"update_cached_fields",
"(",
"commit",
"=",
"False",
",",
"exceptions",
"=",
"F... | Call on pre_save signal for objects (to automatically refresh on save).
:param update_fields: list of fields to update | [
"Call",
"on",
"pre_save",
"signal",
"for",
"objects",
"(",
"to",
"automatically",
"refresh",
"on",
"save",
")",
".",
":",
"param",
"update_fields",
":",
"list",
"of",
"fields",
"to",
"update"
] | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/cache.py#L40-L46 |
novopl/peltak | src/peltak/extra/gitflow/logic/hotfix.py | start | def start(name):
# type: (str) -> None
""" Start working on a new hotfix.
This will create a new branch off master called hotfix/<name>.
Args:
name (str):
The name of the new feature.
"""
hotfix_branch = 'hotfix/' + common.to_branch_name(name)
master = conf.get('git.mas... | python | def start(name):
# type: (str) -> None
""" Start working on a new hotfix.
This will create a new branch off master called hotfix/<name>.
Args:
name (str):
The name of the new feature.
"""
hotfix_branch = 'hotfix/' + common.to_branch_name(name)
master = conf.get('git.mas... | [
"def",
"start",
"(",
"name",
")",
":",
"# type: (str) -> None",
"hotfix_branch",
"=",
"'hotfix/'",
"+",
"common",
".",
"to_branch_name",
"(",
"name",
")",
"master",
"=",
"conf",
".",
"get",
"(",
"'git.master_branch'",
",",
"'master'",
")",
"common",
".",
"as... | Start working on a new hotfix.
This will create a new branch off master called hotfix/<name>.
Args:
name (str):
The name of the new feature. | [
"Start",
"working",
"on",
"a",
"new",
"hotfix",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/hotfix.py#L30-L44 |
novopl/peltak | src/peltak/extra/gitflow/logic/hotfix.py | finish | def finish():
# type: () -> None
""" Merge current feature into develop. """
pretend = context.get('pretend', False)
if not pretend and (git.staged() or git.unstaged()):
log.err(
"You have uncommitted changes in your repo!\n"
"You need to stash them before you merge the ... | python | def finish():
# type: () -> None
""" Merge current feature into develop. """
pretend = context.get('pretend', False)
if not pretend and (git.staged() or git.unstaged()):
log.err(
"You have uncommitted changes in your repo!\n"
"You need to stash them before you merge the ... | [
"def",
"finish",
"(",
")",
":",
"# type: () -> None",
"pretend",
"=",
"context",
".",
"get",
"(",
"'pretend'",
",",
"False",
")",
"if",
"not",
"pretend",
"and",
"(",
"git",
".",
"staged",
"(",
")",
"or",
"git",
".",
"unstaged",
"(",
")",
")",
":",
... | Merge current feature into develop. | [
"Merge",
"current",
"feature",
"into",
"develop",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/hotfix.py#L76-L108 |
novopl/peltak | src/peltak/extra/gitflow/logic/hotfix.py | merged | def merged():
# type: () -> None
""" Cleanup a remotely merged branch. """
develop = conf.get('git.devel_branch', 'develop')
master = conf.get('git.master_branch', 'master')
branch = git.current_branch(refresh=True)
common.assert_branch_type('hotfix')
# Pull master with the merged hotfix
... | python | def merged():
# type: () -> None
""" Cleanup a remotely merged branch. """
develop = conf.get('git.devel_branch', 'develop')
master = conf.get('git.master_branch', 'master')
branch = git.current_branch(refresh=True)
common.assert_branch_type('hotfix')
# Pull master with the merged hotfix
... | [
"def",
"merged",
"(",
")",
":",
"# type: () -> None",
"develop",
"=",
"conf",
".",
"get",
"(",
"'git.devel_branch'",
",",
"'develop'",
")",
"master",
"=",
"conf",
".",
"get",
"(",
"'git.master_branch'",
",",
"'master'",
")",
"branch",
"=",
"git",
".",
"cur... | Cleanup a remotely merged branch. | [
"Cleanup",
"a",
"remotely",
"merged",
"branch",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/logic/hotfix.py#L111-L133 |
Varkal/chuda | chuda/shell.py | ShellCommand.run | def run(self):
"""
Run the shell command
Returns:
ShellCommand: return this ShellCommand instance for chaining
"""
if not self.block:
self.output = []
self.error = []
self.thread = threading.Thread(target=self.run_non_blocking)
... | python | def run(self):
"""
Run the shell command
Returns:
ShellCommand: return this ShellCommand instance for chaining
"""
if not self.block:
self.output = []
self.error = []
self.thread = threading.Thread(target=self.run_non_blocking)
... | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"block",
":",
"self",
".",
"output",
"=",
"[",
"]",
"self",
".",
"error",
"=",
"[",
"]",
"self",
".",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"ru... | Run the shell command
Returns:
ShellCommand: return this ShellCommand instance for chaining | [
"Run",
"the",
"shell",
"command"
] | train | https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/shell.py#L51-L72 |
Varkal/chuda | chuda/shell.py | ShellCommand.send | def send(self, value):
"""
Send text to stdin. Can only be used on non blocking commands
Args:
value (str): the text to write on stdin
Raises:
TypeError: If command is blocking
Returns:
ShellCommand: return this ShellCommand instance for chain... | python | def send(self, value):
"""
Send text to stdin. Can only be used on non blocking commands
Args:
value (str): the text to write on stdin
Raises:
TypeError: If command is blocking
Returns:
ShellCommand: return this ShellCommand instance for chain... | [
"def",
"send",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"block",
"and",
"self",
".",
"_stdin",
"is",
"not",
"None",
":",
"self",
".",
"writer",
".",
"write",
"(",
"\"{}\\n\"",
".",
"format",
"(",
"value",
")",
")",
"return",
... | Send text to stdin. Can only be used on non blocking commands
Args:
value (str): the text to write on stdin
Raises:
TypeError: If command is blocking
Returns:
ShellCommand: return this ShellCommand instance for chaining | [
"Send",
"text",
"to",
"stdin",
".",
"Can",
"only",
"be",
"used",
"on",
"non",
"blocking",
"commands"
] | train | https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/shell.py#L114-L129 |
Varkal/chuda | chuda/shell.py | ShellCommand.poll_output | def poll_output(self):
"""
Append lines from stdout to self.output.
Returns:
list: The lines added since last call
"""
if self.block:
return self.output
new_list = self.output[self.old_output_size:]
self.old_output_size += len(new_list)
... | python | def poll_output(self):
"""
Append lines from stdout to self.output.
Returns:
list: The lines added since last call
"""
if self.block:
return self.output
new_list = self.output[self.old_output_size:]
self.old_output_size += len(new_list)
... | [
"def",
"poll_output",
"(",
"self",
")",
":",
"if",
"self",
".",
"block",
":",
"return",
"self",
".",
"output",
"new_list",
"=",
"self",
".",
"output",
"[",
"self",
".",
"old_output_size",
":",
"]",
"self",
".",
"old_output_size",
"+=",
"len",
"(",
"new... | Append lines from stdout to self.output.
Returns:
list: The lines added since last call | [
"Append",
"lines",
"from",
"stdout",
"to",
"self",
".",
"output",
"."
] | train | https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/shell.py#L131-L143 |
Varkal/chuda | chuda/shell.py | ShellCommand.poll_error | def poll_error(self):
"""
Append lines from stderr to self.errors.
Returns:
list: The lines added since last call
"""
if self.block:
return self.error
new_list = self.error[self.old_error_size:]
self.old_error_size += len(new_list)
... | python | def poll_error(self):
"""
Append lines from stderr to self.errors.
Returns:
list: The lines added since last call
"""
if self.block:
return self.error
new_list = self.error[self.old_error_size:]
self.old_error_size += len(new_list)
... | [
"def",
"poll_error",
"(",
"self",
")",
":",
"if",
"self",
".",
"block",
":",
"return",
"self",
".",
"error",
"new_list",
"=",
"self",
".",
"error",
"[",
"self",
".",
"old_error_size",
":",
"]",
"self",
".",
"old_error_size",
"+=",
"len",
"(",
"new_list... | Append lines from stderr to self.errors.
Returns:
list: The lines added since last call | [
"Append",
"lines",
"from",
"stderr",
"to",
"self",
".",
"errors",
"."
] | train | https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/shell.py#L145-L157 |
Varkal/chuda | chuda/shell.py | ShellCommand.kill | def kill(self):
"""
Kill the current non blocking command
Raises:
TypeError: If command is blocking
"""
if self.block:
raise TypeError(NON_BLOCKING_ERROR_MESSAGE)
try:
self.process.kill()
except ProcessLookupError as exc:
... | python | def kill(self):
"""
Kill the current non blocking command
Raises:
TypeError: If command is blocking
"""
if self.block:
raise TypeError(NON_BLOCKING_ERROR_MESSAGE)
try:
self.process.kill()
except ProcessLookupError as exc:
... | [
"def",
"kill",
"(",
"self",
")",
":",
"if",
"self",
".",
"block",
":",
"raise",
"TypeError",
"(",
"NON_BLOCKING_ERROR_MESSAGE",
")",
"try",
":",
"self",
".",
"process",
".",
"kill",
"(",
")",
"except",
"ProcessLookupError",
"as",
"exc",
":",
"self",
".",... | Kill the current non blocking command
Raises:
TypeError: If command is blocking | [
"Kill",
"the",
"current",
"non",
"blocking",
"command"
] | train | https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/shell.py#L159-L172 |
Varkal/chuda | chuda/shell.py | ShellCommand.wait_for | def wait_for(self, pattern, timeout=None):
"""
Block until a pattern have been found in stdout and stderr
Args:
pattern(:class:`~re.Pattern`): The pattern to search
timeout(int): Maximum number of second to wait. If None, wait infinitely
Raises:
Tim... | python | def wait_for(self, pattern, timeout=None):
"""
Block until a pattern have been found in stdout and stderr
Args:
pattern(:class:`~re.Pattern`): The pattern to search
timeout(int): Maximum number of second to wait. If None, wait infinitely
Raises:
Tim... | [
"def",
"wait_for",
"(",
"self",
",",
"pattern",
",",
"timeout",
"=",
"None",
")",
":",
"should_continue",
"=",
"True",
"if",
"self",
".",
"block",
":",
"raise",
"TypeError",
"(",
"NON_BLOCKING_ERROR_MESSAGE",
")",
"def",
"stop",
"(",
"signum",
",",
"frame"... | Block until a pattern have been found in stdout and stderr
Args:
pattern(:class:`~re.Pattern`): The pattern to search
timeout(int): Maximum number of second to wait. If None, wait infinitely
Raises:
TimeoutError: When timeout is reach | [
"Block",
"until",
"a",
"pattern",
"have",
"been",
"found",
"in",
"stdout",
"and",
"stderr"
] | train | https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/shell.py#L174-L203 |
Varkal/chuda | chuda/shell.py | ShellCommand.is_running | def is_running(self):
"""
Check if the command is currently running
Returns:
bool: True if running, else False
"""
if self.block:
return False
return self.thread.is_alive() or self.process.poll() is None | python | def is_running(self):
"""
Check if the command is currently running
Returns:
bool: True if running, else False
"""
if self.block:
return False
return self.thread.is_alive() or self.process.poll() is None | [
"def",
"is_running",
"(",
"self",
")",
":",
"if",
"self",
".",
"block",
":",
"return",
"False",
"return",
"self",
".",
"thread",
".",
"is_alive",
"(",
")",
"or",
"self",
".",
"process",
".",
"poll",
"(",
")",
"is",
"None"
] | Check if the command is currently running
Returns:
bool: True if running, else False | [
"Check",
"if",
"the",
"command",
"is",
"currently",
"running"
] | train | https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/shell.py#L205-L215 |
Varkal/chuda | chuda/shell.py | ShellCommand.print_live_output | def print_live_output(self):
'''
Block and print the output of the command
Raises:
TypeError: If command is blocking
'''
if self.block:
raise TypeError(NON_BLOCKING_ERROR_MESSAGE)
else:
while self.thread.is_alive() or self.old_output_s... | python | def print_live_output(self):
'''
Block and print the output of the command
Raises:
TypeError: If command is blocking
'''
if self.block:
raise TypeError(NON_BLOCKING_ERROR_MESSAGE)
else:
while self.thread.is_alive() or self.old_output_s... | [
"def",
"print_live_output",
"(",
"self",
")",
":",
"if",
"self",
".",
"block",
":",
"raise",
"TypeError",
"(",
"NON_BLOCKING_ERROR_MESSAGE",
")",
"else",
":",
"while",
"self",
".",
"thread",
".",
"is_alive",
"(",
")",
"or",
"self",
".",
"old_output_size",
... | Block and print the output of the command
Raises:
TypeError: If command is blocking | [
"Block",
"and",
"print",
"the",
"output",
"of",
"the",
"command"
] | train | https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/shell.py#L224-L243 |
Varkal/chuda | chuda/shell.py | Runner.run | def run(self, command, block=True, cwd=None, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE):
"""
Create an instance of :class:`~ShellCommand` and run it
Args:
command (str): :class:`~ShellCommand`
block (bool): See :class:`~ShellCommand`
... | python | def run(self, command, block=True, cwd=None, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE):
"""
Create an instance of :class:`~ShellCommand` and run it
Args:
command (str): :class:`~ShellCommand`
block (bool): See :class:`~ShellCommand`
... | [
"def",
"run",
"(",
"self",
",",
"command",
",",
"block",
"=",
"True",
",",
"cwd",
"=",
"None",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
":",
"if... | Create an instance of :class:`~ShellCommand` and run it
Args:
command (str): :class:`~ShellCommand`
block (bool): See :class:`~ShellCommand`
cwd (str): Override the runner cwd. Useb by the :class:`~ShellCommand` instance | [
"Create",
"an",
"instance",
"of",
":",
"class",
":",
"~ShellCommand",
"and",
"run",
"it"
] | train | https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/shell.py#L259-L271 |
Vital-Fernandez/dazer | bin/lib/Math_Libraries/lnr_script.py | bces | def bces(x1, x2, x1err=[], x2err=[], cerr=[], logify=True, model='yx', \
bootstrap=5000, verbose='normal', full_output=True):
"""
Bivariate, Correlated Errors and intrinsic Scatter (BCES)
translated from the FORTRAN code by Christina Bird and Matthew Bershady
(Akritas & Bershady, 1996)
Lin... | python | def bces(x1, x2, x1err=[], x2err=[], cerr=[], logify=True, model='yx', \
bootstrap=5000, verbose='normal', full_output=True):
"""
Bivariate, Correlated Errors and intrinsic Scatter (BCES)
translated from the FORTRAN code by Christina Bird and Matthew Bershady
(Akritas & Bershady, 1996)
Lin... | [
"def",
"bces",
"(",
"x1",
",",
"x2",
",",
"x1err",
"=",
"[",
"]",
",",
"x2err",
"=",
"[",
"]",
",",
"cerr",
"=",
"[",
"]",
",",
"logify",
"=",
"True",
",",
"model",
"=",
"'yx'",
",",
"bootstrap",
"=",
"5000",
",",
"verbose",
"=",
"'normal'",
... | Bivariate, Correlated Errors and intrinsic Scatter (BCES)
translated from the FORTRAN code by Christina Bird and Matthew Bershady
(Akritas & Bershady, 1996)
Linear regression in the presence of heteroscedastic errors on both
variables and intrinsic scatter
Parameters
----------
x1 ... | [
"Bivariate",
"Correlated",
"Errors",
"and",
"intrinsic",
"Scatter",
"(",
"BCES",
")",
"translated",
"from",
"the",
"FORTRAN",
"code",
"by",
"Christina",
"Bird",
"and",
"Matthew",
"Bershady",
"(",
"Akritas",
"&",
"Bershady",
"1996",
")"
] | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Math_Libraries/lnr_script.py#L12-L309 |
Vital-Fernandez/dazer | bin/lib/Math_Libraries/lnr_script.py | scatter | def scatter(slope, zero, x1, x2, x1err=[], x2err=[]):
"""
Used mainly to measure scatter for the BCES best-fit
"""
n = len(x1)
x2pred = zero + slope * x1
s = sum((x2 - x2pred) ** 2) / (n - 1)
if len(x2err) == n:
s_obs = sum((x2err / x2) ** 2) / n
s0 = s - s_obs
print num... | python | def scatter(slope, zero, x1, x2, x1err=[], x2err=[]):
"""
Used mainly to measure scatter for the BCES best-fit
"""
n = len(x1)
x2pred = zero + slope * x1
s = sum((x2 - x2pred) ** 2) / (n - 1)
if len(x2err) == n:
s_obs = sum((x2err / x2) ** 2) / n
s0 = s - s_obs
print num... | [
"def",
"scatter",
"(",
"slope",
",",
"zero",
",",
"x1",
",",
"x2",
",",
"x1err",
"=",
"[",
"]",
",",
"x2err",
"=",
"[",
"]",
")",
":",
"n",
"=",
"len",
"(",
"x1",
")",
"x2pred",
"=",
"zero",
"+",
"slope",
"*",
"x1",
"s",
"=",
"sum",
"(",
... | Used mainly to measure scatter for the BCES best-fit | [
"Used",
"mainly",
"to",
"measure",
"scatter",
"for",
"the",
"BCES",
"best",
"-",
"fit"
] | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Math_Libraries/lnr_script.py#L311-L323 |
Vital-Fernandez/dazer | bin/lib/Math_Libraries/lnr_script.py | kelly | def kelly(x1, x2, x1err=[], x2err=[], cerr=[], logify=True,
miniter=5000, maxiter=1e5, metro=True,
silent=True):
"""
Python wrapper for the linear regression MCMC of Kelly (2007).
Requires pidly (http://astronomy.sussex.ac.uk/~anthonys/pidly/) and
an IDL license.
Parameters
... | python | def kelly(x1, x2, x1err=[], x2err=[], cerr=[], logify=True,
miniter=5000, maxiter=1e5, metro=True,
silent=True):
"""
Python wrapper for the linear regression MCMC of Kelly (2007).
Requires pidly (http://astronomy.sussex.ac.uk/~anthonys/pidly/) and
an IDL license.
Parameters
... | [
"def",
"kelly",
"(",
"x1",
",",
"x2",
",",
"x1err",
"=",
"[",
"]",
",",
"x2err",
"=",
"[",
"]",
",",
"cerr",
"=",
"[",
"]",
",",
"logify",
"=",
"True",
",",
"miniter",
"=",
"5000",
",",
"maxiter",
"=",
"1e5",
",",
"metro",
"=",
"True",
",",
... | Python wrapper for the linear regression MCMC of Kelly (2007).
Requires pidly (http://astronomy.sussex.ac.uk/~anthonys/pidly/) and
an IDL license.
Parameters
----------
x1 : array of floats
Independent variable, or observable
x2 : array of floats
... | [
"Python",
"wrapper",
"for",
"the",
"linear",
"regression",
"MCMC",
"of",
"Kelly",
"(",
"2007",
")",
".",
"Requires",
"pidly",
"(",
"http",
":",
"//",
"astronomy",
".",
"sussex",
".",
"ac",
".",
"uk",
"/",
"~anthonys",
"/",
"pidly",
"/",
")",
"and",
"... | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Math_Libraries/lnr_script.py#L325-L380 |
Vital-Fernandez/dazer | bin/lib/Math_Libraries/lnr_script.py | mcmc | def mcmc(x1, x2, x1err=[], x2err=[], po=(1,1,0.5), logify=True,
nsteps=5000, nwalkers=100, nburn=500, output='full'):
"""
Use emcee to find the best-fit linear relation or power law
accounting for measurement uncertainties and intrinsic scatter
Parameters
----------
x1 : array... | python | def mcmc(x1, x2, x1err=[], x2err=[], po=(1,1,0.5), logify=True,
nsteps=5000, nwalkers=100, nburn=500, output='full'):
"""
Use emcee to find the best-fit linear relation or power law
accounting for measurement uncertainties and intrinsic scatter
Parameters
----------
x1 : array... | [
"def",
"mcmc",
"(",
"x1",
",",
"x2",
",",
"x1err",
"=",
"[",
"]",
",",
"x2err",
"=",
"[",
"]",
",",
"po",
"=",
"(",
"1",
",",
"1",
",",
"0.5",
")",
",",
"logify",
"=",
"True",
",",
"nsteps",
"=",
"5000",
",",
"nwalkers",
"=",
"100",
",",
... | Use emcee to find the best-fit linear relation or power law
accounting for measurement uncertainties and intrinsic scatter
Parameters
----------
x1 : array of floats
Independent variable, or observable
x2 : array of floats
Dependent variable
... | [
"Use",
"emcee",
"to",
"find",
"the",
"best",
"-",
"fit",
"linear",
"relation",
"or",
"power",
"law",
"accounting",
"for",
"measurement",
"uncertainties",
"and",
"intrinsic",
"scatter"
] | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Math_Libraries/lnr_script.py#L382-L468 |
Vital-Fernandez/dazer | bin/lib/Math_Libraries/lnr_script.py | mle | def mle(x1, x2, x1err=[], x2err=[], cerr=[], s_int=True,
po=(1,0,0.1), verbose=False, logify=True, full_output=False):
"""
Maximum Likelihood Estimation of best-fit parameters
Parameters
----------
x1, x2 : float arrays
the independent and dependent variables.
x... | python | def mle(x1, x2, x1err=[], x2err=[], cerr=[], s_int=True,
po=(1,0,0.1), verbose=False, logify=True, full_output=False):
"""
Maximum Likelihood Estimation of best-fit parameters
Parameters
----------
x1, x2 : float arrays
the independent and dependent variables.
x... | [
"def",
"mle",
"(",
"x1",
",",
"x2",
",",
"x1err",
"=",
"[",
"]",
",",
"x2err",
"=",
"[",
"]",
",",
"cerr",
"=",
"[",
"]",
",",
"s_int",
"=",
"True",
",",
"po",
"=",
"(",
"1",
",",
"0",
",",
"0.1",
")",
",",
"verbose",
"=",
"False",
",",
... | Maximum Likelihood Estimation of best-fit parameters
Parameters
----------
x1, x2 : float arrays
the independent and dependent variables.
x1err, x2err : float arrays (optional)
measurement uncertainties on independent and dependent
variables.... | [
"Maximum",
"Likelihood",
"Estimation",
"of",
"best",
"-",
"fit",
"parameters"
] | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Math_Libraries/lnr_script.py#L470-L535 |
Vital-Fernandez/dazer | bin/lib/Math_Libraries/lnr_script.py | to_log | def to_log(x1, x2, x1err, x2err):
"""
Take linear measurements and uncertainties and transform to log values.
"""
logx1 = numpy.log10(numpy.array(x1))
logx2 = numpy.log10(numpy.array(x2))
x1err = numpy.log10(numpy.array(x1)+numpy.array(x1err)) - logx1
x2err = numpy.log10(numpy.array(x2)+num... | python | def to_log(x1, x2, x1err, x2err):
"""
Take linear measurements and uncertainties and transform to log values.
"""
logx1 = numpy.log10(numpy.array(x1))
logx2 = numpy.log10(numpy.array(x2))
x1err = numpy.log10(numpy.array(x1)+numpy.array(x1err)) - logx1
x2err = numpy.log10(numpy.array(x2)+num... | [
"def",
"to_log",
"(",
"x1",
",",
"x2",
",",
"x1err",
",",
"x2err",
")",
":",
"logx1",
"=",
"numpy",
".",
"log10",
"(",
"numpy",
".",
"array",
"(",
"x1",
")",
")",
"logx2",
"=",
"numpy",
".",
"log10",
"(",
"numpy",
".",
"array",
"(",
"x2",
")",
... | Take linear measurements and uncertainties and transform to log values. | [
"Take",
"linear",
"measurements",
"and",
"uncertainties",
"and",
"transform",
"to",
"log",
"values",
"."
] | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Math_Libraries/lnr_script.py#L537-L546 |
novopl/peltak | src/peltak/core/fs.py | wrap_paths | def wrap_paths(paths):
# type: (list[str]) -> str
""" Put quotes around all paths and join them with space in-between. """
if isinstance(paths, string_types):
raise ValueError(
"paths cannot be a string. "
"Use array with one element instead."
)
return ' '.join('"... | python | def wrap_paths(paths):
# type: (list[str]) -> str
""" Put quotes around all paths and join them with space in-between. """
if isinstance(paths, string_types):
raise ValueError(
"paths cannot be a string. "
"Use array with one element instead."
)
return ' '.join('"... | [
"def",
"wrap_paths",
"(",
"paths",
")",
":",
"# type: (list[str]) -> str",
"if",
"isinstance",
"(",
"paths",
",",
"string_types",
")",
":",
"raise",
"ValueError",
"(",
"\"paths cannot be a string. \"",
"\"Use array with one element instead.\"",
")",
"return",
"' '",
"."... | Put quotes around all paths and join them with space in-between. | [
"Put",
"quotes",
"around",
"all",
"paths",
"and",
"join",
"them",
"with",
"space",
"in",
"-",
"between",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/fs.py#L32-L40 |
novopl/peltak | src/peltak/core/fs.py | filtered_walk | def filtered_walk(path, include=None, exclude=None):
# type: (str, List[str], List[str]) -> Generator[str]
""" Walk recursively starting at *path* excluding files matching *exclude*
Args:
path (str):
A starting path. This has to be an existing directory.
include (list[str]):
... | python | def filtered_walk(path, include=None, exclude=None):
# type: (str, List[str], List[str]) -> Generator[str]
""" Walk recursively starting at *path* excluding files matching *exclude*
Args:
path (str):
A starting path. This has to be an existing directory.
include (list[str]):
... | [
"def",
"filtered_walk",
"(",
"path",
",",
"include",
"=",
"None",
",",
"exclude",
"=",
"None",
")",
":",
"# type: (str, List[str], List[str]) -> Generator[str]",
"exclude",
"=",
"exclude",
"or",
"[",
"]",
"if",
"not",
"isdir",
"(",
"path",
")",
":",
"raise",
... | Walk recursively starting at *path* excluding files matching *exclude*
Args:
path (str):
A starting path. This has to be an existing directory.
include (list[str]):
A white list of glob patterns. If given, only files that match those
globs will be yielded (filter... | [
"Walk",
"recursively",
"starting",
"at",
"*",
"path",
"*",
"excluding",
"files",
"matching",
"*",
"exclude",
"*"
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/fs.py#L43-L82 |
novopl/peltak | src/peltak/core/fs.py | match_globs | def match_globs(path, patterns):
# type: (str, List[str]) -> bool
""" Test whether the given *path* matches any patterns in *patterns*
Args:
path (str):
A file path to test for matches.
patterns (list[str]):
A list of glob string patterns to test against. If *path* m... | python | def match_globs(path, patterns):
# type: (str, List[str]) -> bool
""" Test whether the given *path* matches any patterns in *patterns*
Args:
path (str):
A file path to test for matches.
patterns (list[str]):
A list of glob string patterns to test against. If *path* m... | [
"def",
"match_globs",
"(",
"path",
",",
"patterns",
")",
":",
"# type: (str, List[str]) -> bool",
"for",
"pattern",
"in",
"(",
"p",
"for",
"p",
"in",
"patterns",
"if",
"p",
")",
":",
"if",
"pattern",
".",
"startswith",
"(",
"'/'",
")",
":",
"regex",
"=",... | Test whether the given *path* matches any patterns in *patterns*
Args:
path (str):
A file path to test for matches.
patterns (list[str]):
A list of glob string patterns to test against. If *path* matches
any of those patters, it will return True.
Returns:
... | [
"Test",
"whether",
"the",
"given",
"*",
"path",
"*",
"matches",
"any",
"patterns",
"in",
"*",
"patterns",
"*"
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/fs.py#L85-L113 |
novopl/peltak | src/peltak/core/fs.py | search_globs | def search_globs(path, patterns):
# type: (str, List[str]) -> bool
""" Test whether the given *path* contains any patterns in *patterns*
Args:
path (str):
A file path to test for matches.
patterns (list[str]):
A list of glob string patterns to test against. If *path*... | python | def search_globs(path, patterns):
# type: (str, List[str]) -> bool
""" Test whether the given *path* contains any patterns in *patterns*
Args:
path (str):
A file path to test for matches.
patterns (list[str]):
A list of glob string patterns to test against. If *path*... | [
"def",
"search_globs",
"(",
"path",
",",
"patterns",
")",
":",
"# type: (str, List[str]) -> bool",
"for",
"pattern",
"in",
"(",
"p",
"for",
"p",
"in",
"patterns",
"if",
"p",
")",
":",
"if",
"pattern",
".",
"startswith",
"(",
"'/'",
")",
":",
"# If pattern ... | Test whether the given *path* contains any patterns in *patterns*
Args:
path (str):
A file path to test for matches.
patterns (list[str]):
A list of glob string patterns to test against. If *path* matches
any of those patters, it will return True.
Returns:
... | [
"Test",
"whether",
"the",
"given",
"*",
"path",
"*",
"contains",
"any",
"patterns",
"in",
"*",
"patterns",
"*"
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/fs.py#L116-L149 |
novopl/peltak | src/peltak/core/fs.py | write_file | def write_file(path, content, mode='w'):
# type: (Text, Union[Text,bytes], Text) -> None
""" --pretend aware file writing.
You can always write files manually but you should always handle the
--pretend case.
Args:
path (str):
content (str):
mode (str):
"""
from pelt... | python | def write_file(path, content, mode='w'):
# type: (Text, Union[Text,bytes], Text) -> None
""" --pretend aware file writing.
You can always write files manually but you should always handle the
--pretend case.
Args:
path (str):
content (str):
mode (str):
"""
from pelt... | [
"def",
"write_file",
"(",
"path",
",",
"content",
",",
"mode",
"=",
"'w'",
")",
":",
"# type: (Text, Union[Text,bytes], Text) -> None",
"from",
"peltak",
".",
"core",
"import",
"context",
"from",
"peltak",
".",
"core",
"import",
"log",
"if",
"context",
".",
"g... | --pretend aware file writing.
You can always write files manually but you should always handle the
--pretend case.
Args:
path (str):
content (str):
mode (str): | [
"--",
"pretend",
"aware",
"file",
"writing",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/fs.py#L152-L173 |
novopl/peltak | src/peltak/commands/lint.py | lint_cli | def lint_cli(ctx, exclude, skip_untracked, commit_only):
# type: (click.Context, List[str], bool, bool) -> None
""" Run pep8 and pylint on all project files.
You can configure the linting paths using the lint.paths config variable.
This should be a list of paths that will be linted. If a path to a dire... | python | def lint_cli(ctx, exclude, skip_untracked, commit_only):
# type: (click.Context, List[str], bool, bool) -> None
""" Run pep8 and pylint on all project files.
You can configure the linting paths using the lint.paths config variable.
This should be a list of paths that will be linted. If a path to a dire... | [
"def",
"lint_cli",
"(",
"ctx",
",",
"exclude",
",",
"skip_untracked",
",",
"commit_only",
")",
":",
"# type: (click.Context, List[str], bool, bool) -> None",
"if",
"ctx",
".",
"invoked_subcommand",
":",
"return",
"from",
"peltak",
".",
"logic",
"import",
"lint",
"li... | Run pep8 and pylint on all project files.
You can configure the linting paths using the lint.paths config variable.
This should be a list of paths that will be linted. If a path to a directory
is given, all files in that directory and it's subdirectories will be
used.
The pep8 and pylint config pa... | [
"Run",
"pep8",
"and",
"pylint",
"on",
"all",
"project",
"files",
"."
] | train | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/commands/lint.py#L54-L90 |
cons3rt/pycons3rt | pycons3rt/bash.py | run_command | def run_command(command, timeout_sec=3600.0, output=True):
"""Runs a command using the subprocess module
:param command: List containing the command and all args
:param timeout_sec (float) seconds to wait before killing
the command.
:param output (bool) True collects output, False ignores outpu... | python | def run_command(command, timeout_sec=3600.0, output=True):
"""Runs a command using the subprocess module
:param command: List containing the command and all args
:param timeout_sec (float) seconds to wait before killing
the command.
:param output (bool) True collects output, False ignores outpu... | [
"def",
"run_command",
"(",
"command",
",",
"timeout_sec",
"=",
"3600.0",
",",
"output",
"=",
"True",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.run_command'",
")",
"if",
"not",
"isinstance",
"(",
"command",
",",
"list",
... | Runs a command using the subprocess module
:param command: List containing the command and all args
:param timeout_sec (float) seconds to wait before killing
the command.
:param output (bool) True collects output, False ignores output
:return: Dict containing the command output and return code
... | [
"Runs",
"a",
"command",
"using",
"the",
"subprocess",
"module"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L67-L158 |
cons3rt/pycons3rt | pycons3rt/bash.py | get_ip_addresses | def get_ip_addresses():
"""Gets the ip addresses from ifconfig
:return: (dict) of devices and aliases with the IPv4 address
"""
log = logging.getLogger(mod_logger + '.get_ip_addresses')
command = ['/sbin/ifconfig']
try:
result = run_command(command)
except CommandError:
rai... | python | def get_ip_addresses():
"""Gets the ip addresses from ifconfig
:return: (dict) of devices and aliases with the IPv4 address
"""
log = logging.getLogger(mod_logger + '.get_ip_addresses')
command = ['/sbin/ifconfig']
try:
result = run_command(command)
except CommandError:
rai... | [
"def",
"get_ip_addresses",
"(",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.get_ip_addresses'",
")",
"command",
"=",
"[",
"'/sbin/ifconfig'",
"]",
"try",
":",
"result",
"=",
"run_command",
"(",
"command",
")",
"except",
"Com... | Gets the ip addresses from ifconfig
:return: (dict) of devices and aliases with the IPv4 address | [
"Gets",
"the",
"ip",
"addresses",
"from",
"ifconfig"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L235-L267 |
cons3rt/pycons3rt | pycons3rt/bash.py | get_mac_address | def get_mac_address(device_index=0):
"""Returns the Mac Address given a device index
:param device_index: (int) Device index
:return: (str) Mac address or None
"""
log = logging.getLogger(mod_logger + '.get_mac_address')
command = ['ip', 'addr', 'show', 'eth{d}'.format(d=device_index)]
log.... | python | def get_mac_address(device_index=0):
"""Returns the Mac Address given a device index
:param device_index: (int) Device index
:return: (str) Mac address or None
"""
log = logging.getLogger(mod_logger + '.get_mac_address')
command = ['ip', 'addr', 'show', 'eth{d}'.format(d=device_index)]
log.... | [
"def",
"get_mac_address",
"(",
"device_index",
"=",
"0",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.get_mac_address'",
")",
"command",
"=",
"[",
"'ip'",
",",
"'addr'",
",",
"'show'",
",",
"'eth{d}'",
".",
"format",
"(",
... | Returns the Mac Address given a device index
:param device_index: (int) Device index
:return: (str) Mac address or None | [
"Returns",
"the",
"Mac",
"Address",
"given",
"a",
"device",
"index"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L270-L298 |
cons3rt/pycons3rt | pycons3rt/bash.py | chmod | def chmod(path, mode, recursive=False):
"""Emulates bash chmod command
This method sets the file permissions to the specified mode.
:param path: (str) Full path to the file or directory
:param mode: (str) Mode to be set (e.g. 0755)
:param recursive: (bool) Set True to make a recursive call
:re... | python | def chmod(path, mode, recursive=False):
"""Emulates bash chmod command
This method sets the file permissions to the specified mode.
:param path: (str) Full path to the file or directory
:param mode: (str) Mode to be set (e.g. 0755)
:param recursive: (bool) Set True to make a recursive call
:re... | [
"def",
"chmod",
"(",
"path",
",",
"mode",
",",
"recursive",
"=",
"False",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.chmod'",
")",
"# Validate args",
"if",
"not",
"isinstance",
"(",
"path",
",",
"basestring",
")",
":",
... | Emulates bash chmod command
This method sets the file permissions to the specified mode.
:param path: (str) Full path to the file or directory
:param mode: (str) Mode to be set (e.g. 0755)
:param recursive: (bool) Set True to make a recursive call
:return: int exit code of the chmod command
:r... | [
"Emulates",
"bash",
"chmod",
"command"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L301-L342 |
cons3rt/pycons3rt | pycons3rt/bash.py | mkdir_p | def mkdir_p(path):
"""Emulates 'mkdir -p' in bash
:param path: (str) Path to create
:return: None
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.mkdir_p')
if not isinstance(path, basestring):
msg = 'path argument is not a string'
log.error(msg)
raise... | python | def mkdir_p(path):
"""Emulates 'mkdir -p' in bash
:param path: (str) Path to create
:return: None
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.mkdir_p')
if not isinstance(path, basestring):
msg = 'path argument is not a string'
log.error(msg)
raise... | [
"def",
"mkdir_p",
"(",
"path",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.mkdir_p'",
")",
"if",
"not",
"isinstance",
"(",
"path",
",",
"basestring",
")",
":",
"msg",
"=",
"'path argument is not a string'",
"log",
".",
"er... | Emulates 'mkdir -p' in bash
:param path: (str) Path to create
:return: None
:raises CommandError | [
"Emulates",
"mkdir",
"-",
"p",
"in",
"bash"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L345-L366 |
cons3rt/pycons3rt | pycons3rt/bash.py | source | def source(script):
"""Emulates 'source' command in bash
:param script: (str) Full path to the script to source
:return: Updated environment
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.source')
if not isinstance(script, basestring):
msg = 'script argument must be... | python | def source(script):
"""Emulates 'source' command in bash
:param script: (str) Full path to the script to source
:return: Updated environment
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.source')
if not isinstance(script, basestring):
msg = 'script argument must be... | [
"def",
"source",
"(",
"script",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.source'",
")",
"if",
"not",
"isinstance",
"(",
"script",
",",
"basestring",
")",
":",
"msg",
"=",
"'script argument must be a string'",
"log",
".",
... | Emulates 'source' command in bash
:param script: (str) Full path to the script to source
:return: Updated environment
:raises CommandError | [
"Emulates",
"source",
"command",
"in",
"bash"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L369-L417 |
cons3rt/pycons3rt | pycons3rt/bash.py | yum_update | def yum_update(downloadonly=False, dest_dir='/tmp'):
"""Run a yum update on this system
This public method runs the yum -y update command to update
packages from yum. If downloadonly is set to true, the yum
updates will be downloaded to the specified dest_dir.
:param dest_dir: (str) Full path to t... | python | def yum_update(downloadonly=False, dest_dir='/tmp'):
"""Run a yum update on this system
This public method runs the yum -y update command to update
packages from yum. If downloadonly is set to true, the yum
updates will be downloaded to the specified dest_dir.
:param dest_dir: (str) Full path to t... | [
"def",
"yum_update",
"(",
"downloadonly",
"=",
"False",
",",
"dest_dir",
"=",
"'/tmp'",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.yum_update'",
")",
"# Type checks on the args",
"if",
"not",
"isinstance",
"(",
"dest_dir",
",... | Run a yum update on this system
This public method runs the yum -y update command to update
packages from yum. If downloadonly is set to true, the yum
updates will be downloaded to the specified dest_dir.
:param dest_dir: (str) Full path to the download directory
:param downloadonly: Boolean
:... | [
"Run",
"a",
"yum",
"update",
"on",
"this",
"system"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L420-L473 |
cons3rt/pycons3rt | pycons3rt/bash.py | yum_install | def yum_install(packages, downloadonly=False, dest_dir='/tmp'):
"""Installs (or downloads) a list of packages from yum
This public method installs a list of packages from yum or
downloads the packages to the specified destination directory using
the yum-downloadonly yum plugin.
:param downloadonly... | python | def yum_install(packages, downloadonly=False, dest_dir='/tmp'):
"""Installs (or downloads) a list of packages from yum
This public method installs a list of packages from yum or
downloads the packages to the specified destination directory using
the yum-downloadonly yum plugin.
:param downloadonly... | [
"def",
"yum_install",
"(",
"packages",
",",
"downloadonly",
"=",
"False",
",",
"dest_dir",
"=",
"'/tmp'",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.yum_install'",
")",
"# Type checks on the args",
"if",
"not",
"isinstance",
... | Installs (or downloads) a list of packages from yum
This public method installs a list of packages from yum or
downloads the packages to the specified destination directory using
the yum-downloadonly yum plugin.
:param downloadonly: Boolean, set to only download the package and
not install it
... | [
"Installs",
"(",
"or",
"downloads",
")",
"a",
"list",
"of",
"packages",
"from",
"yum"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L476-L546 |
cons3rt/pycons3rt | pycons3rt/bash.py | rpm_install | def rpm_install(install_dir):
"""This method installs all RPM files in a specific dir
:param install_dir: (str) Full path to the directory
:return int exit code form the rpm command
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.rpm_install')
# Type checks on the args
... | python | def rpm_install(install_dir):
"""This method installs all RPM files in a specific dir
:param install_dir: (str) Full path to the directory
:return int exit code form the rpm command
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.rpm_install')
# Type checks on the args
... | [
"def",
"rpm_install",
"(",
"install_dir",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.rpm_install'",
")",
"# Type checks on the args",
"if",
"not",
"isinstance",
"(",
"install_dir",
",",
"basestring",
")",
":",
"msg",
"=",
"'i... | This method installs all RPM files in a specific dir
:param install_dir: (str) Full path to the directory
:return int exit code form the rpm command
:raises CommandError | [
"This",
"method",
"installs",
"all",
"RPM",
"files",
"in",
"a",
"specific",
"dir"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L549-L580 |
cons3rt/pycons3rt | pycons3rt/bash.py | sed | def sed(file_path, pattern, replace_str, g=0):
"""Python impl of the bash sed command
This method emulates the functionality of a bash sed command.
:param file_path: (str) Full path to the file to be edited
:param pattern: (str) Search pattern to replace as a regex
:param replace_str: (str) String... | python | def sed(file_path, pattern, replace_str, g=0):
"""Python impl of the bash sed command
This method emulates the functionality of a bash sed command.
:param file_path: (str) Full path to the file to be edited
:param pattern: (str) Search pattern to replace as a regex
:param replace_str: (str) String... | [
"def",
"sed",
"(",
"file_path",
",",
"pattern",
",",
"replace_str",
",",
"g",
"=",
"0",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.sed'",
")",
"# Type checks on the args",
"if",
"not",
"isinstance",
"(",
"file_path",
",",... | Python impl of the bash sed command
This method emulates the functionality of a bash sed command.
:param file_path: (str) Full path to the file to be edited
:param pattern: (str) Search pattern to replace as a regex
:param replace_str: (str) String to replace the pattern
:param g: (int) Whether to... | [
"Python",
"impl",
"of",
"the",
"bash",
"sed",
"command"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L583-L627 |
cons3rt/pycons3rt | pycons3rt/bash.py | zip_dir | def zip_dir(dir_path, zip_file):
"""Creates a zip file of a directory tree
This method creates a zip archive using the directory tree dir_path
and adds to zip_file output.
:param dir_path: (str) Full path to directory to be zipped
:param zip_file: (str) Full path to the output zip file
:return... | python | def zip_dir(dir_path, zip_file):
"""Creates a zip file of a directory tree
This method creates a zip archive using the directory tree dir_path
and adds to zip_file output.
:param dir_path: (str) Full path to directory to be zipped
:param zip_file: (str) Full path to the output zip file
:return... | [
"def",
"zip_dir",
"(",
"dir_path",
",",
"zip_file",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.zip_dir'",
")",
"# Validate args",
"if",
"not",
"isinstance",
"(",
"dir_path",
",",
"basestring",
")",
":",
"msg",
"=",
"'dir_... | Creates a zip file of a directory tree
This method creates a zip archive using the directory tree dir_path
and adds to zip_file output.
:param dir_path: (str) Full path to directory to be zipped
:param zip_file: (str) Full path to the output zip file
:return: None
:raises CommandError | [
"Creates",
"a",
"zip",
"file",
"of",
"a",
"directory",
"tree"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L630-L674 |
cons3rt/pycons3rt | pycons3rt/bash.py | get_ip | def get_ip(interface=0):
"""This method return the IP address
:param interface: (int) Interface number (e.g. 0 for eth0)
:return: (str) IP address or None
"""
log = logging.getLogger(mod_logger + '.get_ip')
log.info('Getting the IP address for this system...')
ip_address = None
try:
... | python | def get_ip(interface=0):
"""This method return the IP address
:param interface: (int) Interface number (e.g. 0 for eth0)
:return: (str) IP address or None
"""
log = logging.getLogger(mod_logger + '.get_ip')
log.info('Getting the IP address for this system...')
ip_address = None
try:
... | [
"def",
"get_ip",
"(",
"interface",
"=",
"0",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.get_ip'",
")",
"log",
".",
"info",
"(",
"'Getting the IP address for this system...'",
")",
"ip_address",
"=",
"None",
"try",
":",
"log... | This method return the IP address
:param interface: (int) Interface number (e.g. 0 for eth0)
:return: (str) IP address or None | [
"This",
"method",
"return",
"the",
"IP",
"address"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L677-L719 |
cons3rt/pycons3rt | pycons3rt/bash.py | update_hosts_file | def update_hosts_file(ip, entry):
"""Updates the /etc/hosts file for the specified ip
This method updates the /etc/hosts file for the specified IP
address with the specified entry.
:param ip: (str) IP address to be added or updated
:param entry: (str) Hosts file entry to be added
:return: None... | python | def update_hosts_file(ip, entry):
"""Updates the /etc/hosts file for the specified ip
This method updates the /etc/hosts file for the specified IP
address with the specified entry.
:param ip: (str) IP address to be added or updated
:param entry: (str) Hosts file entry to be added
:return: None... | [
"def",
"update_hosts_file",
"(",
"ip",
",",
"entry",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.update_hosts_file'",
")",
"# Validate args",
"if",
"not",
"isinstance",
"(",
"ip",
",",
"basestring",
")",
":",
"msg",
"=",
"... | Updates the /etc/hosts file for the specified ip
This method updates the /etc/hosts file for the specified IP
address with the specified entry.
:param ip: (str) IP address to be added or updated
:param entry: (str) Hosts file entry to be added
:return: None
:raises CommandError | [
"Updates",
"the",
"/",
"etc",
"/",
"hosts",
"file",
"for",
"the",
"specified",
"ip"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L722-L776 |
cons3rt/pycons3rt | pycons3rt/bash.py | set_hostname | def set_hostname(new_hostname, pretty_hostname=None):
"""Sets this hosts hostname
This method updates /etc/sysconfig/network and calls the hostname
command to set a hostname on a Linux system.
:param new_hostname: (str) New hostname
:param pretty_hostname: (str) new pretty hostname, set to the sam... | python | def set_hostname(new_hostname, pretty_hostname=None):
"""Sets this hosts hostname
This method updates /etc/sysconfig/network and calls the hostname
command to set a hostname on a Linux system.
:param new_hostname: (str) New hostname
:param pretty_hostname: (str) new pretty hostname, set to the sam... | [
"def",
"set_hostname",
"(",
"new_hostname",
",",
"pretty_hostname",
"=",
"None",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.set_hostname'",
")",
"# Ensure the hostname is a str",
"if",
"not",
"isinstance",
"(",
"new_hostname",
",... | Sets this hosts hostname
This method updates /etc/sysconfig/network and calls the hostname
command to set a hostname on a Linux system.
:param new_hostname: (str) New hostname
:param pretty_hostname: (str) new pretty hostname, set to the same as
new_hostname if not provided
:return (int) e... | [
"Sets",
"this",
"hosts",
"hostname"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L779-L847 |
cons3rt/pycons3rt | pycons3rt/bash.py | set_ntp_server | def set_ntp_server(server):
"""Sets the NTP server on Linux
:param server: (str) NTP server IP or hostname
:return: None
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.set_ntp_server')
# Ensure the hostname is a str
if not isinstance(server, basestring):
msg = ... | python | def set_ntp_server(server):
"""Sets the NTP server on Linux
:param server: (str) NTP server IP or hostname
:return: None
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.set_ntp_server')
# Ensure the hostname is a str
if not isinstance(server, basestring):
msg = ... | [
"def",
"set_ntp_server",
"(",
"server",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.set_ntp_server'",
")",
"# Ensure the hostname is a str",
"if",
"not",
"isinstance",
"(",
"server",
",",
"basestring",
")",
":",
"msg",
"=",
"'... | Sets the NTP server on Linux
:param server: (str) NTP server IP or hostname
:return: None
:raises CommandError | [
"Sets",
"the",
"NTP",
"server",
"on",
"Linux"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L850-L882 |
cons3rt/pycons3rt | pycons3rt/bash.py | copy_ifcfg_file | def copy_ifcfg_file(source_interface, dest_interface):
"""Copies an existing ifcfg network script to another
:param source_interface: String (e.g. 1)
:param dest_interface: String (e.g. 0:0)
:return: None
:raises TypeError, OSError
"""
log = logging.getLogger(mod_logger + '.copy_ifcfg_file'... | python | def copy_ifcfg_file(source_interface, dest_interface):
"""Copies an existing ifcfg network script to another
:param source_interface: String (e.g. 1)
:param dest_interface: String (e.g. 0:0)
:return: None
:raises TypeError, OSError
"""
log = logging.getLogger(mod_logger + '.copy_ifcfg_file'... | [
"def",
"copy_ifcfg_file",
"(",
"source_interface",
",",
"dest_interface",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.copy_ifcfg_file'",
")",
"# Validate args",
"if",
"not",
"isinstance",
"(",
"source_interface",
",",
"basestring",
... | Copies an existing ifcfg network script to another
:param source_interface: String (e.g. 1)
:param dest_interface: String (e.g. 0:0)
:return: None
:raises TypeError, OSError | [
"Copies",
"an",
"existing",
"ifcfg",
"network",
"script",
"to",
"another"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L885-L955 |
cons3rt/pycons3rt | pycons3rt/bash.py | remove_ifcfg_file | def remove_ifcfg_file(device_index='0'):
"""Removes the ifcfg file at the specified device index
and restarts the network service
:param device_index: (int) Device Index
:return: None
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.remove_ifcfg_file')
if not isinstance(d... | python | def remove_ifcfg_file(device_index='0'):
"""Removes the ifcfg file at the specified device index
and restarts the network service
:param device_index: (int) Device Index
:return: None
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.remove_ifcfg_file')
if not isinstance(d... | [
"def",
"remove_ifcfg_file",
"(",
"device_index",
"=",
"'0'",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.remove_ifcfg_file'",
")",
"if",
"not",
"isinstance",
"(",
"device_index",
",",
"basestring",
")",
":",
"msg",
"=",
"'de... | Removes the ifcfg file at the specified device index
and restarts the network service
:param device_index: (int) Device Index
:return: None
:raises CommandError | [
"Removes",
"the",
"ifcfg",
"file",
"at",
"the",
"specified",
"device",
"index",
"and",
"restarts",
"the",
"network",
"service"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L958-L998 |
cons3rt/pycons3rt | pycons3rt/bash.py | add_nat_rule | def add_nat_rule(port, source_interface, dest_interface):
"""Adds a NAT rule to iptables
:param port: String or int port number
:param source_interface: String (e.g. 1)
:param dest_interface: String (e.g. 0:0)
:return: None
:raises: TypeError, OSError
"""
log = logging.getLogger(mod_log... | python | def add_nat_rule(port, source_interface, dest_interface):
"""Adds a NAT rule to iptables
:param port: String or int port number
:param source_interface: String (e.g. 1)
:param dest_interface: String (e.g. 0:0)
:return: None
:raises: TypeError, OSError
"""
log = logging.getLogger(mod_log... | [
"def",
"add_nat_rule",
"(",
"port",
",",
"source_interface",
",",
"dest_interface",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.add_nat_rule'",
")",
"# Validate args",
"if",
"not",
"isinstance",
"(",
"source_interface",
",",
"ba... | Adds a NAT rule to iptables
:param port: String or int port number
:param source_interface: String (e.g. 1)
:param dest_interface: String (e.g. 0:0)
:return: None
:raises: TypeError, OSError | [
"Adds",
"a",
"NAT",
"rule",
"to",
"iptables"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L1001-L1052 |
cons3rt/pycons3rt | pycons3rt/bash.py | service_network_restart | def service_network_restart():
"""Restarts the network service on linux
:return: None
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.service_network_restart')
command = ['service', 'network', 'restart']
time.sleep(5)
try:
result = run_command(command)
tim... | python | def service_network_restart():
"""Restarts the network service on linux
:return: None
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.service_network_restart')
command = ['service', 'network', 'restart']
time.sleep(5)
try:
result = run_command(command)
tim... | [
"def",
"service_network_restart",
"(",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.service_network_restart'",
")",
"command",
"=",
"[",
"'service'",
",",
"'network'",
",",
"'restart'",
"]",
"time",
".",
"sleep",
"(",
"5",
")... | Restarts the network service on linux
:return: None
:raises CommandError | [
"Restarts",
"the",
"network",
"service",
"on",
"linux",
":",
"return",
":",
"None",
":",
"raises",
"CommandError"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L1055-L1076 |
cons3rt/pycons3rt | pycons3rt/bash.py | save_iptables | def save_iptables(rules_file='/etc/sysconfig/iptables'):
"""Saves iptables rules to the provided rules file
:return: None
:raises OSError
"""
log = logging.getLogger(mod_logger + '.save_iptables')
# Run iptables-save to get the output
command = ['iptables-save']
log.debug('Running comm... | python | def save_iptables(rules_file='/etc/sysconfig/iptables'):
"""Saves iptables rules to the provided rules file
:return: None
:raises OSError
"""
log = logging.getLogger(mod_logger + '.save_iptables')
# Run iptables-save to get the output
command = ['iptables-save']
log.debug('Running comm... | [
"def",
"save_iptables",
"(",
"rules_file",
"=",
"'/etc/sysconfig/iptables'",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.save_iptables'",
")",
"# Run iptables-save to get the output",
"command",
"=",
"[",
"'iptables-save'",
"]",
"log"... | Saves iptables rules to the provided rules file
:return: None
:raises OSError | [
"Saves",
"iptables",
"rules",
"to",
"the",
"provided",
"rules",
"file"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L1079-L1112 |
cons3rt/pycons3rt | pycons3rt/bash.py | get_remote_host_environment_variable | def get_remote_host_environment_variable(host, environment_variable):
"""Retrieves the value of an environment variable of a
remote host over SSH
:param host: (str) host to query
:param environment_variable: (str) variable to query
:return: (str) value of the environment variable
:raises: TypeE... | python | def get_remote_host_environment_variable(host, environment_variable):
"""Retrieves the value of an environment variable of a
remote host over SSH
:param host: (str) host to query
:param environment_variable: (str) variable to query
:return: (str) value of the environment variable
:raises: TypeE... | [
"def",
"get_remote_host_environment_variable",
"(",
"host",
",",
"environment_variable",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.get_remote_host_environment_variable'",
")",
"if",
"not",
"isinstance",
"(",
"host",
",",
"basestring... | Retrieves the value of an environment variable of a
remote host over SSH
:param host: (str) host to query
:param environment_variable: (str) variable to query
:return: (str) value of the environment variable
:raises: TypeError, CommandError | [
"Retrieves",
"the",
"value",
"of",
"an",
"environment",
"variable",
"of",
"a",
"remote",
"host",
"over",
"SSH"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L1115-L1149 |
cons3rt/pycons3rt | pycons3rt/bash.py | set_remote_host_environment_variable | def set_remote_host_environment_variable(host, variable_name, variable_value, env_file='/etc/bashrc'):
"""Sets an environment variable on the remote host in the
specified environment file
:param host: (str) host to set environment variable on
:param variable_name: (str) name of the variable
:param ... | python | def set_remote_host_environment_variable(host, variable_name, variable_value, env_file='/etc/bashrc'):
"""Sets an environment variable on the remote host in the
specified environment file
:param host: (str) host to set environment variable on
:param variable_name: (str) name of the variable
:param ... | [
"def",
"set_remote_host_environment_variable",
"(",
"host",
",",
"variable_name",
",",
"variable_value",
",",
"env_file",
"=",
"'/etc/bashrc'",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.set_remote_host_environment_variable'",
")",
"... | Sets an environment variable on the remote host in the
specified environment file
:param host: (str) host to set environment variable on
:param variable_name: (str) name of the variable
:param variable_value: (str) value of the variable
:param env_file: (str) full path to the environment file to se... | [
"Sets",
"an",
"environment",
"variable",
"on",
"the",
"remote",
"host",
"in",
"the",
"specified",
"environment",
"file"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L1152-L1223 |
cons3rt/pycons3rt | pycons3rt/bash.py | run_remote_command | def run_remote_command(host, command, timeout_sec=5.0):
"""Retrieves the value of an environment variable of a
remote host over SSH
:param host: (str) host to query
:param command: (str) command
:param timeout_sec (float) seconds to wait before killing the command.
:return: (str) command output... | python | def run_remote_command(host, command, timeout_sec=5.0):
"""Retrieves the value of an environment variable of a
remote host over SSH
:param host: (str) host to query
:param command: (str) command
:param timeout_sec (float) seconds to wait before killing the command.
:return: (str) command output... | [
"def",
"run_remote_command",
"(",
"host",
",",
"command",
",",
"timeout_sec",
"=",
"5.0",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.run_remote_command'",
")",
"if",
"not",
"isinstance",
"(",
"host",
",",
"basestring",
")",... | Retrieves the value of an environment variable of a
remote host over SSH
:param host: (str) host to query
:param command: (str) command
:param timeout_sec (float) seconds to wait before killing the command.
:return: (str) command output
:raises: TypeError, CommandError | [
"Retrieves",
"the",
"value",
"of",
"an",
"environment",
"variable",
"of",
"a",
"remote",
"host",
"over",
"SSH"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L1226-L1262 |
cons3rt/pycons3rt | pycons3rt/bash.py | check_remote_host_marker_file | def check_remote_host_marker_file(host, file_path):
"""Queries a remote host over SSH to check for existence
of a marker file
:param host: (str) host to query
:param file_path: (str) path to the marker file
:return: (bool) True if the marker file exists
:raises: TypeError, CommandError
"""
... | python | def check_remote_host_marker_file(host, file_path):
"""Queries a remote host over SSH to check for existence
of a marker file
:param host: (str) host to query
:param file_path: (str) path to the marker file
:return: (bool) True if the marker file exists
:raises: TypeError, CommandError
"""
... | [
"def",
"check_remote_host_marker_file",
"(",
"host",
",",
"file_path",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.check_remote_host_marker_file'",
")",
"if",
"not",
"isinstance",
"(",
"host",
",",
"basestring",
")",
":",
"msg",... | Queries a remote host over SSH to check for existence
of a marker file
:param host: (str) host to query
:param file_path: (str) path to the marker file
:return: (bool) True if the marker file exists
:raises: TypeError, CommandError | [
"Queries",
"a",
"remote",
"host",
"over",
"SSH",
"to",
"check",
"for",
"existence",
"of",
"a",
"marker",
"file"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L1265-L1302 |
cons3rt/pycons3rt | pycons3rt/bash.py | restore_iptables | def restore_iptables(firewall_rules):
"""Restores and saves firewall rules from the firewall_rules file
:param firewall_rules: (str) Full path to the firewall rules file
:return: None
:raises OSError
"""
log = logging.getLogger(mod_logger + '.restore_iptables')
log.info('Restoring firewall ... | python | def restore_iptables(firewall_rules):
"""Restores and saves firewall rules from the firewall_rules file
:param firewall_rules: (str) Full path to the firewall rules file
:return: None
:raises OSError
"""
log = logging.getLogger(mod_logger + '.restore_iptables')
log.info('Restoring firewall ... | [
"def",
"restore_iptables",
"(",
"firewall_rules",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.restore_iptables'",
")",
"log",
".",
"info",
"(",
"'Restoring firewall rules from file: {f}'",
".",
"format",
"(",
"f",
"=",
"firewall_r... | Restores and saves firewall rules from the firewall_rules file
:param firewall_rules: (str) Full path to the firewall rules file
:return: None
:raises OSError | [
"Restores",
"and",
"saves",
"firewall",
"rules",
"from",
"the",
"firewall_rules",
"file"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L1339-L1377 |
cons3rt/pycons3rt | pycons3rt/bash.py | remove_default_gateway | def remove_default_gateway():
"""Removes Default Gateway configuration from /etc/sysconfig/network
and restarts networking
:return: None
:raises: OSError
"""
log = logging.getLogger(mod_logger + '.remove_default_gateway')
# Ensure the network script exists
network_script = '/etc/sy... | python | def remove_default_gateway():
"""Removes Default Gateway configuration from /etc/sysconfig/network
and restarts networking
:return: None
:raises: OSError
"""
log = logging.getLogger(mod_logger + '.remove_default_gateway')
# Ensure the network script exists
network_script = '/etc/sy... | [
"def",
"remove_default_gateway",
"(",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.remove_default_gateway'",
")",
"# Ensure the network script exists",
"network_script",
"=",
"'/etc/sysconfig/network'",
"if",
"not",
"os",
".",
"path",
... | Removes Default Gateway configuration from /etc/sysconfig/network
and restarts networking
:return: None
:raises: OSError | [
"Removes",
"Default",
"Gateway",
"configuration",
"from",
"/",
"etc",
"/",
"sysconfig",
"/",
"network",
"and",
"restarts",
"networking",
":",
"return",
":",
"None",
":",
"raises",
":",
"OSError"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L1380-L1416 |
cons3rt/pycons3rt | pycons3rt/bash.py | is_systemd | def is_systemd():
"""Determines whether this system uses systemd
:return: (bool) True if this distro has systemd
"""
os_family = platform.system()
if os_family != 'Linux':
raise OSError('This method is only supported on Linux, found OS: {o}'.format(o=os_family))
linux_distro, linux_vers... | python | def is_systemd():
"""Determines whether this system uses systemd
:return: (bool) True if this distro has systemd
"""
os_family = platform.system()
if os_family != 'Linux':
raise OSError('This method is only supported on Linux, found OS: {o}'.format(o=os_family))
linux_distro, linux_vers... | [
"def",
"is_systemd",
"(",
")",
":",
"os_family",
"=",
"platform",
".",
"system",
"(",
")",
"if",
"os_family",
"!=",
"'Linux'",
":",
"raise",
"OSError",
"(",
"'This method is only supported on Linux, found OS: {o}'",
".",
"format",
"(",
"o",
"=",
"os_family",
")"... | Determines whether this system uses systemd
:return: (bool) True if this distro has systemd | [
"Determines",
"whether",
"this",
"system",
"uses",
"systemd"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L1419-L1437 |
cons3rt/pycons3rt | pycons3rt/bash.py | manage_service | def manage_service(service_name, service_action='status', systemd=None, output=True):
"""Use to run Linux sysv or systemd service commands
:param service_name (str) name of the service to start
:param service_action (str) action to perform on the service
:param systemd (bool) True if the command should... | python | def manage_service(service_name, service_action='status', systemd=None, output=True):
"""Use to run Linux sysv or systemd service commands
:param service_name (str) name of the service to start
:param service_action (str) action to perform on the service
:param systemd (bool) True if the command should... | [
"def",
"manage_service",
"(",
"service_name",
",",
"service_action",
"=",
"'status'",
",",
"systemd",
"=",
"None",
",",
"output",
"=",
"True",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.manage_service'",
")",
"# Ensure the se... | Use to run Linux sysv or systemd service commands
:param service_name (str) name of the service to start
:param service_action (str) action to perform on the service
:param systemd (bool) True if the command should use systemd
:param output (bool) True to print output
:return: None
:raises: OSE... | [
"Use",
"to",
"run",
"Linux",
"sysv",
"or",
"systemd",
"service",
"commands"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L1440-L1511 |
cons3rt/pycons3rt | pycons3rt/bash.py | system_reboot | def system_reboot(wait_time_sec=20):
"""Reboots the system after a specified wait time. Must be run as root
:param wait_time_sec: (int) number of sec to wait before performing the reboot
:return: None
:raises: SystemRebootError, SystemRebootTimeoutError
"""
log = logging.getLogger(mod_logger +... | python | def system_reboot(wait_time_sec=20):
"""Reboots the system after a specified wait time. Must be run as root
:param wait_time_sec: (int) number of sec to wait before performing the reboot
:return: None
:raises: SystemRebootError, SystemRebootTimeoutError
"""
log = logging.getLogger(mod_logger +... | [
"def",
"system_reboot",
"(",
"wait_time_sec",
"=",
"20",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.system_reboot'",
")",
"try",
":",
"wait_time_sec",
"=",
"int",
"(",
"wait_time_sec",
")",
"except",
"ValueError",
":",
"rai... | Reboots the system after a specified wait time. Must be run as root
:param wait_time_sec: (int) number of sec to wait before performing the reboot
:return: None
:raises: SystemRebootError, SystemRebootTimeoutError | [
"Reboots",
"the",
"system",
"after",
"a",
"specified",
"wait",
"time",
".",
"Must",
"be",
"run",
"as",
"root"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L1514-L1548 |
cons3rt/pycons3rt | pycons3rt/bash.py | main | def main():
"""Sample usage for this python module
This main method simply illustrates sample usage for this python
module.
:return: None
"""
mkdir_p('/tmp/test/test')
source('/root/.bash_profile')
yum_install(['httpd', 'git'])
yum_install(['httpd', 'git'], dest_dir='/tmp/test/test... | python | def main():
"""Sample usage for this python module
This main method simply illustrates sample usage for this python
module.
:return: None
"""
mkdir_p('/tmp/test/test')
source('/root/.bash_profile')
yum_install(['httpd', 'git'])
yum_install(['httpd', 'git'], dest_dir='/tmp/test/test... | [
"def",
"main",
"(",
")",
":",
"mkdir_p",
"(",
"'/tmp/test/test'",
")",
"source",
"(",
"'/root/.bash_profile'",
")",
"yum_install",
"(",
"[",
"'httpd'",
",",
"'git'",
"]",
")",
"yum_install",
"(",
"[",
"'httpd'",
",",
"'git'",
"]",
",",
"dest_dir",
"=",
"... | Sample usage for this python module
This main method simply illustrates sample usage for this python
module.
:return: None | [
"Sample",
"usage",
"for",
"this",
"python",
"module"
] | train | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L1551-L1567 |
kajala/django-jutil | jutil/logs.py | log_event | def log_event(name: str, request: Request=None, data=None, ip=None):
"""
Logs consistent event for easy parsing/analysis.
:param name: Name of the event. Will be logged as EVENT_XXX with XXX in capitals.
:param request: Django REST framework Request (optional)
:param data: Even data (optional)
:... | python | def log_event(name: str, request: Request=None, data=None, ip=None):
"""
Logs consistent event for easy parsing/analysis.
:param name: Name of the event. Will be logged as EVENT_XXX with XXX in capitals.
:param request: Django REST framework Request (optional)
:param data: Even data (optional)
:... | [
"def",
"log_event",
"(",
"name",
":",
"str",
",",
"request",
":",
"Request",
"=",
"None",
",",
"data",
"=",
"None",
",",
"ip",
"=",
"None",
")",
":",
"log_data",
"=",
"{",
"}",
"if",
"not",
"ip",
"and",
"request",
":",
"ip",
"=",
"get_real_ip",
"... | Logs consistent event for easy parsing/analysis.
:param name: Name of the event. Will be logged as EVENT_XXX with XXX in capitals.
:param request: Django REST framework Request (optional)
:param data: Even data (optional)
:param ip: Even IP (optional) | [
"Logs",
"consistent",
"event",
"for",
"easy",
"parsing",
"/",
"analysis",
".",
":",
"param",
"name",
":",
"Name",
"of",
"the",
"event",
".",
"Will",
"be",
"logged",
"as",
"EVENT_XXX",
"with",
"XXX",
"in",
"capitals",
".",
":",
"param",
"request",
":",
... | train | https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/logs.py#L10-L27 |
jaredLunde/vital-tools | vital/security/__init__.py | aes_b64_encrypt | def aes_b64_encrypt(value, secret, block_size=AES.block_size):
""" AES encrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES encrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
... | python | def aes_b64_encrypt(value, secret, block_size=AES.block_size):
""" AES encrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES encrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
... | [
"def",
"aes_b64_encrypt",
"(",
"value",
",",
"secret",
",",
"block_size",
"=",
"AES",
".",
"block_size",
")",
":",
"# iv = randstr(block_size * 2, rng=random)",
"iv",
"=",
"randstr",
"(",
"block_size",
"*",
"2",
")",
"cipher",
"=",
"AES",
".",
"new",
"(",
"s... | AES encrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES encrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
aes_encrypt("Hello, world",
"aLWEFlwgwlreWELF... | [
"AES",
"encrypt",
"@value",
"with",
"@secret",
"using",
"the",
"|CFB|",
"mode",
"of",
"AES",
"with",
"a",
"cryptographically",
"secure",
"initialization",
"vector",
"."
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L31-L52 |
jaredLunde/vital-tools | vital/security/__init__.py | aes_b64_decrypt | def aes_b64_decrypt(value, secret, block_size=AES.block_size):
""" AES decrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES decrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
... | python | def aes_b64_decrypt(value, secret, block_size=AES.block_size):
""" AES decrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES decrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
... | [
"def",
"aes_b64_decrypt",
"(",
"value",
",",
"secret",
",",
"block_size",
"=",
"AES",
".",
"block_size",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"iv",
"=",
"value",
"[",
":",
"block_size",
"]",
"cipher",
"=",
"AES",
".",
"new",
"(",
"secre... | AES decrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES decrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
aes_encrypt("Hello, world",
"aLWEFlwgwlreWELF... | [
"AES",
"decrypt",
"@value",
"with",
"@secret",
"using",
"the",
"|CFB|",
"mode",
"of",
"AES",
"with",
"a",
"cryptographically",
"secure",
"initialization",
"vector",
"."
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L55-L76 |
jaredLunde/vital-tools | vital/security/__init__.py | aes_encrypt | def aes_encrypt(value, secret, block_size=AES.block_size):
""" AES encrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#bytes) AES encrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
... | python | def aes_encrypt(value, secret, block_size=AES.block_size):
""" AES encrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#bytes) AES encrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
... | [
"def",
"aes_encrypt",
"(",
"value",
",",
"secret",
",",
"block_size",
"=",
"AES",
".",
"block_size",
")",
":",
"iv",
"=",
"os",
".",
"urandom",
"(",
"block_size",
"*",
"2",
")",
"cipher",
"=",
"AES",
".",
"new",
"(",
"secret",
"[",
":",
"32",
"]",
... | AES encrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#bytes) AES encrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
aes_encrypt("Hello, world",
"aLWEFlwgwlreWE... | [
"AES",
"encrypt",
"@value",
"with",
"@secret",
"using",
"the",
"|CFB|",
"mode",
"of",
"AES",
"with",
"a",
"cryptographically",
"secure",
"initialization",
"vector",
"."
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L79-L98 |
jaredLunde/vital-tools | vital/security/__init__.py | aes_decrypt | def aes_decrypt(value, secret, block_size=AES.block_size):
""" AES decrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES decrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
ae... | python | def aes_decrypt(value, secret, block_size=AES.block_size):
""" AES decrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES decrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
ae... | [
"def",
"aes_decrypt",
"(",
"value",
",",
"secret",
",",
"block_size",
"=",
"AES",
".",
"block_size",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"cipher",
"=",
"AES",
".",
"new",
"(",
"secret",
"[",
":",
"32",
"]",
",",
"AES",
".",
"MODE_CFB... | AES decrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES decrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
aes_encrypt("Hello, world",
"aLWEFlwgwlreWELF... | [
"AES",
"decrypt",
"@value",
"with",
"@secret",
"using",
"the",
"|CFB|",
"mode",
"of",
"AES",
"with",
"a",
"cryptographically",
"secure",
"initialization",
"vector",
"."
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L101-L120 |
jaredLunde/vital-tools | vital/security/__init__.py | aes_pad | def aes_pad(s, block_size=32, padding='{'):
""" Adds padding to get the correct block sizes for AES encryption
@s: #str being AES encrypted or decrypted
@block_size: the AES block size
@padding: character to pad with
-> padded #str
..
from vital.security import... | python | def aes_pad(s, block_size=32, padding='{'):
""" Adds padding to get the correct block sizes for AES encryption
@s: #str being AES encrypted or decrypted
@block_size: the AES block size
@padding: character to pad with
-> padded #str
..
from vital.security import... | [
"def",
"aes_pad",
"(",
"s",
",",
"block_size",
"=",
"32",
",",
"padding",
"=",
"'{'",
")",
":",
"return",
"s",
"+",
"(",
"block_size",
"-",
"len",
"(",
"s",
")",
"%",
"block_size",
")",
"*",
"padding"
] | Adds padding to get the correct block sizes for AES encryption
@s: #str being AES encrypted or decrypted
@block_size: the AES block size
@padding: character to pad with
-> padded #str
..
from vital.security import aes_pad
aes_pad("swing")
# ... | [
"Adds",
"padding",
"to",
"get",
"the",
"correct",
"block",
"sizes",
"for",
"AES",
"encryption"
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L123-L138 |
jaredLunde/vital-tools | vital/security/__init__.py | lscmp | def lscmp(a, b):
""" Compares two strings in a cryptographically safe way:
Runtime is not affected by length of common prefix, so this
is helpful against timing attacks.
..
from vital.security import lscmp
lscmp("ringo", "starr")
# -> False
ls... | python | def lscmp(a, b):
""" Compares two strings in a cryptographically safe way:
Runtime is not affected by length of common prefix, so this
is helpful against timing attacks.
..
from vital.security import lscmp
lscmp("ringo", "starr")
# -> False
ls... | [
"def",
"lscmp",
"(",
"a",
",",
"b",
")",
":",
"l",
"=",
"len",
"return",
"not",
"sum",
"(",
"0",
"if",
"x",
"==",
"y",
"else",
"1",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"a",
",",
"b",
")",
")",
"and",
"l",
"(",
"a",
")",
"==",
"l",
... | Compares two strings in a cryptographically safe way:
Runtime is not affected by length of common prefix, so this
is helpful against timing attacks.
..
from vital.security import lscmp
lscmp("ringo", "starr")
# -> False
lscmp("ringo", "ringo")
... | [
"Compares",
"two",
"strings",
"in",
"a",
"cryptographically",
"safe",
"way",
":",
"Runtime",
"is",
"not",
"affected",
"by",
"length",
"of",
"common",
"prefix",
"so",
"this",
"is",
"helpful",
"against",
"timing",
"attacks",
"."
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L159-L173 |
jaredLunde/vital-tools | vital/security/__init__.py | cookie | def cookie(data, key_salt='', secret=None, digestmod=None):
""" Encodes or decodes a signed cookie.
@data: cookie data
@key_salt: HMAC key signing salt
@secret: HMAC signing secret key
@digestmod: hashing algorithm to sign with, recommended >=sha256
-> HMAC signed or unsigne... | python | def cookie(data, key_salt='', secret=None, digestmod=None):
""" Encodes or decodes a signed cookie.
@data: cookie data
@key_salt: HMAC key signing salt
@secret: HMAC signing secret key
@digestmod: hashing algorithm to sign with, recommended >=sha256
-> HMAC signed or unsigne... | [
"def",
"cookie",
"(",
"data",
",",
"key_salt",
"=",
"''",
",",
"secret",
"=",
"None",
",",
"digestmod",
"=",
"None",
")",
":",
"digestmod",
"=",
"digestmod",
"or",
"sha256",
"if",
"not",
"data",
":",
"return",
"None",
"try",
":",
"# Decode signed cookie"... | Encodes or decodes a signed cookie.
@data: cookie data
@key_salt: HMAC key signing salt
@secret: HMAC signing secret key
@digestmod: hashing algorithm to sign with, recommended >=sha256
-> HMAC signed or unsigned cookie data
..
from vital.security import coo... | [
"Encodes",
"or",
"decodes",
"a",
"signed",
"cookie",
".",
"@data",
":",
"cookie",
"data",
"@key_salt",
":",
"HMAC",
"key",
"signing",
"salt",
"@secret",
":",
"HMAC",
"signing",
"secret",
"key",
"@digestmod",
":",
"hashing",
"algorithm",
"to",
"sign",
"with",... | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L179-L222 |
jaredLunde/vital-tools | vital/security/__init__.py | strkey | def strkey(val, chaffify=1, keyspace=string.ascii_letters + string.digits):
""" Converts integers to a sequence of strings, and reverse.
This is not intended to obfuscate numbers in any kind of
cryptographically secure way, in fact it's the opposite. It's
for predictable, reversable, obfusca... | python | def strkey(val, chaffify=1, keyspace=string.ascii_letters + string.digits):
""" Converts integers to a sequence of strings, and reverse.
This is not intended to obfuscate numbers in any kind of
cryptographically secure way, in fact it's the opposite. It's
for predictable, reversable, obfusca... | [
"def",
"strkey",
"(",
"val",
",",
"chaffify",
"=",
"1",
",",
"keyspace",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
")",
":",
"chaffify",
"=",
"chaffify",
"or",
"1",
"keylen",
"=",
"len",
"(",
"keyspace",
")",
"try",
":",
"# I... | Converts integers to a sequence of strings, and reverse.
This is not intended to obfuscate numbers in any kind of
cryptographically secure way, in fact it's the opposite. It's
for predictable, reversable, obfuscation. It can also be used to
transform a random bit integer to a string of t... | [
"Converts",
"integers",
"to",
"a",
"sequence",
"of",
"strings",
"and",
"reverse",
".",
"This",
"is",
"not",
"intended",
"to",
"obfuscate",
"numbers",
"in",
"any",
"kind",
"of",
"cryptographically",
"secure",
"way",
"in",
"fact",
"it",
"s",
"the",
"opposite",... | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L241-L302 |
jaredLunde/vital-tools | vital/security/__init__.py | chars_in | def chars_in(bits, keyspace):
""" ..
log2(keyspace^x_chars) = bits
log(keyspace^x_chars) = log(2) * bits
exp(log(keyspace^x_chars)) = exp(log(2) * bits)
x_chars = log(exp(log(2) * bits)) / log(keyspace)
..
-> (#int) number of characters in @bits of entropy given the @... | python | def chars_in(bits, keyspace):
""" ..
log2(keyspace^x_chars) = bits
log(keyspace^x_chars) = log(2) * bits
exp(log(keyspace^x_chars)) = exp(log(2) * bits)
x_chars = log(exp(log(2) * bits)) / log(keyspace)
..
-> (#int) number of characters in @bits of entropy given the @... | [
"def",
"chars_in",
"(",
"bits",
",",
"keyspace",
")",
":",
"keyspace",
"=",
"len",
"(",
"keyspace",
")",
"if",
"keyspace",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"\"Keyspace size must be >1\"",
")",
"bits_per_cycle",
"=",
"512",
"if",
"bits",
">",
"bit... | ..
log2(keyspace^x_chars) = bits
log(keyspace^x_chars) = log(2) * bits
exp(log(keyspace^x_chars)) = exp(log(2) * bits)
x_chars = log(exp(log(2) * bits)) / log(keyspace)
..
-> (#int) number of characters in @bits of entropy given the @keyspace | [
"..",
"log2",
"(",
"keyspace^x_chars",
")",
"=",
"bits",
"log",
"(",
"keyspace^x_chars",
")",
"=",
"log",
"(",
"2",
")",
"*",
"bits",
"exp",
"(",
"log",
"(",
"keyspace^x_chars",
"))",
"=",
"exp",
"(",
"log",
"(",
"2",
")",
"*",
"bits",
")",
"x_char... | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L327-L351 |
jaredLunde/vital-tools | vital/security/__init__.py | bits_in | def bits_in(length, keyspace):
""" |log2(keyspace^length) = bits|
-> (#float) number of bits of entropy in @length of characters for
a given a @keyspace
"""
keyspace = len(keyspace)
length_per_cycle = 64
if length > length_per_cycle:
bits = 0
length_processed = 0
... | python | def bits_in(length, keyspace):
""" |log2(keyspace^length) = bits|
-> (#float) number of bits of entropy in @length of characters for
a given a @keyspace
"""
keyspace = len(keyspace)
length_per_cycle = 64
if length > length_per_cycle:
bits = 0
length_processed = 0
... | [
"def",
"bits_in",
"(",
"length",
",",
"keyspace",
")",
":",
"keyspace",
"=",
"len",
"(",
"keyspace",
")",
"length_per_cycle",
"=",
"64",
"if",
"length",
">",
"length_per_cycle",
":",
"bits",
"=",
"0",
"length_processed",
"=",
"0",
"cycles",
"=",
"ceil",
... | |log2(keyspace^length) = bits|
-> (#float) number of bits of entropy in @length of characters for
a given a @keyspace | [
"|log2",
"(",
"keyspace^length",
")",
"=",
"bits|",
"-",
">",
"(",
"#float",
")",
"number",
"of",
"bits",
"of",
"entropy",
"in"
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L360-L378 |
jaredLunde/vital-tools | vital/security/__init__.py | iter_random_chars | def iter_random_chars(bits,
keyspace=string.ascii_letters + string.digits + '#/.',
rng=None):
""" Yields a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entr... | python | def iter_random_chars(bits,
keyspace=string.ascii_letters + string.digits + '#/.',
rng=None):
""" Yields a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entr... | [
"def",
"iter_random_chars",
"(",
"bits",
",",
"keyspace",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"+",
"'#/.'",
",",
"rng",
"=",
"None",
")",
":",
"if",
"bits",
"<",
"8",
":",
"raise",
"ValueError",
"(",
"'Bits cannot be <8'",
... | Yields a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entropy
@keyspace: (#str) or iterable allowed output chars
..
from vital.security import iter_rand
for char ... | [
"Yields",
"a",
"cryptographically",
"secure",
"random",
"key",
"of",
"desired",
"@bits",
"of",
"entropy",
"within",
"@keyspace",
"using",
":",
"class",
":",
"random",
".",
"SystemRandom"
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L381-L402 |
jaredLunde/vital-tools | vital/security/__init__.py | randkey | def randkey(bits, keyspace=string.ascii_letters + string.digits + '#/.',
rng=None):
""" Returns a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entropy
@keyspace: (#str) or iterable... | python | def randkey(bits, keyspace=string.ascii_letters + string.digits + '#/.',
rng=None):
""" Returns a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entropy
@keyspace: (#str) or iterable... | [
"def",
"randkey",
"(",
"bits",
",",
"keyspace",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"+",
"'#/.'",
",",
"rng",
"=",
"None",
")",
":",
"return",
"\"\"",
".",
"join",
"(",
"char",
"for",
"char",
"in",
"iter_random_chars",
"(... | Returns a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entropy
@keyspace: (#str) or iterable allowed output chars
@rng: the random number generator to use. Defaults to
:class:r... | [
"Returns",
"a",
"cryptographically",
"secure",
"random",
"key",
"of",
"desired",
"@bits",
"of",
"entropy",
"within",
"@keyspace",
"using",
":",
"class",
":",
"random",
".",
"SystemRandom"
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L405-L430 |
jaredLunde/vital-tools | vital/security/__init__.py | randstr | def randstr(size, keyspace=string.ascii_letters + string.digits, rng=None):
""" Returns a cryptographically secure random string of desired @size
(in character length) within @keyspace using :class:random.SystemRandom
@size: (#int) number of random characters to generate
@keyspace: (#str) o... | python | def randstr(size, keyspace=string.ascii_letters + string.digits, rng=None):
""" Returns a cryptographically secure random string of desired @size
(in character length) within @keyspace using :class:random.SystemRandom
@size: (#int) number of random characters to generate
@keyspace: (#str) o... | [
"def",
"randstr",
"(",
"size",
",",
"keyspace",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
",",
"rng",
"=",
"None",
")",
":",
"rng",
"=",
"rng",
"or",
"random",
".",
"SystemRandom",
"(",
")",
"return",
"\"\"",
".",
"join",
"("... | Returns a cryptographically secure random string of desired @size
(in character length) within @keyspace using :class:random.SystemRandom
@size: (#int) number of random characters to generate
@keyspace: (#str) or iterable allowed output chars
@rng: the random number generator to use. De... | [
"Returns",
"a",
"cryptographically",
"secure",
"random",
"string",
"of",
"desired",
"@size",
"(",
"in",
"character",
"length",
")",
"within",
"@keyspace",
"using",
":",
"class",
":",
"random",
".",
"SystemRandom"
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L433-L452 |
jaredLunde/vital-tools | setup.py | parse_requirements | def parse_requirements(filename):
""" load requirements from a pip requirements file """
lineiter = (line.strip() for line in open(filename))
return (line for line in lineiter if line and not line.startswith("#")) | python | def parse_requirements(filename):
""" load requirements from a pip requirements file """
lineiter = (line.strip() for line in open(filename))
return (line for line in lineiter if line and not line.startswith("#")) | [
"def",
"parse_requirements",
"(",
"filename",
")",
":",
"lineiter",
"=",
"(",
"line",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"open",
"(",
"filename",
")",
")",
"return",
"(",
"line",
"for",
"line",
"in",
"lineiter",
"if",
"line",
"and",
"not",
... | load requirements from a pip requirements file | [
"load",
"requirements",
"from",
"a",
"pip",
"requirements",
"file"
] | train | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/setup.py#L24-L27 |
Vital-Fernandez/dazer | bin/lib/Plotting_Libraries/sigfig.py | round_sig | def round_sig(x, n, scien_notation = False):
if x < 0:
x = x * -1
symbol = '-'
else:
symbol = ''
'''round floating point x to n significant figures'''
if type(n) is not types.IntType:
raise TypeError, "n must be an integer"
try:
x = float(x)
exce... | python | def round_sig(x, n, scien_notation = False):
if x < 0:
x = x * -1
symbol = '-'
else:
symbol = ''
'''round floating point x to n significant figures'''
if type(n) is not types.IntType:
raise TypeError, "n must be an integer"
try:
x = float(x)
exce... | [
"def",
"round_sig",
"(",
"x",
",",
"n",
",",
"scien_notation",
"=",
"False",
")",
":",
"if",
"x",
"<",
"0",
":",
"x",
"=",
"x",
"*",
"-",
"1",
"symbol",
"=",
"'-'",
"else",
":",
"symbol",
"=",
"''",
"if",
"type",
"(",
"n",
")",
"is",
"not",
... | round floating point x to n significant figures | [
"round",
"floating",
"point",
"x",
"to",
"n",
"significant",
"figures"
] | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Plotting_Libraries/sigfig.py#L7-L60 |
Vital-Fernandez/dazer | bin/lib/Plotting_Libraries/sigfig.py | round_sig_error | def round_sig_error(x, ex, n, paren=False):
'''Find ex rounded to n sig-figs and make the floating point x
match the number of decimals. If [paren], the string is
returned as quantity(error) format'''
stex = round_sig(ex,n)
if stex.find('.') < 0:
extra_zeros = len(stex) - n
sigfigs ... | python | def round_sig_error(x, ex, n, paren=False):
'''Find ex rounded to n sig-figs and make the floating point x
match the number of decimals. If [paren], the string is
returned as quantity(error) format'''
stex = round_sig(ex,n)
if stex.find('.') < 0:
extra_zeros = len(stex) - n
sigfigs ... | [
"def",
"round_sig_error",
"(",
"x",
",",
"ex",
",",
"n",
",",
"paren",
"=",
"False",
")",
":",
"stex",
"=",
"round_sig",
"(",
"ex",
",",
"n",
")",
"if",
"stex",
".",
"find",
"(",
"'.'",
")",
"<",
"0",
":",
"extra_zeros",
"=",
"len",
"(",
"stex"... | Find ex rounded to n sig-figs and make the floating point x
match the number of decimals. If [paren], the string is
returned as quantity(error) format | [
"Find",
"ex",
"rounded",
"to",
"n",
"sig",
"-",
"figs",
"and",
"make",
"the",
"floating",
"point",
"x",
"match",
"the",
"number",
"of",
"decimals",
".",
"If",
"[",
"paren",
"]",
"the",
"string",
"is",
"returned",
"as",
"quantity",
"(",
"error",
")",
... | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Plotting_Libraries/sigfig.py#L62-L78 |
Vital-Fernandez/dazer | bin/lib/Plotting_Libraries/sigfig.py | format_table | def format_table(cols, errors, n, labels=None, headers=None, latex=False):
'''Format a table such that the errors have n significant
figures. [cols] and [errors] should be a list of 1D arrays
that correspond to data and errors in columns. [n] is the number of
significant figures to keep in the errors.... | python | def format_table(cols, errors, n, labels=None, headers=None, latex=False):
'''Format a table such that the errors have n significant
figures. [cols] and [errors] should be a list of 1D arrays
that correspond to data and errors in columns. [n] is the number of
significant figures to keep in the errors.... | [
"def",
"format_table",
"(",
"cols",
",",
"errors",
",",
"n",
",",
"labels",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"latex",
"=",
"False",
")",
":",
"if",
"len",
"(",
"cols",
")",
"!=",
"len",
"(",
"errors",
")",
":",
"raise",
"ValueError",
... | Format a table such that the errors have n significant
figures. [cols] and [errors] should be a list of 1D arrays
that correspond to data and errors in columns. [n] is the number of
significant figures to keep in the errors. [labels] is an optional
column of strings that will be in the first column. ... | [
"Format",
"a",
"table",
"such",
"that",
"the",
"errors",
"have",
"n",
"significant",
"figures",
".",
"[",
"cols",
"]",
"and",
"[",
"errors",
"]",
"should",
"be",
"a",
"list",
"of",
"1D",
"arrays",
"that",
"correspond",
"to",
"data",
"and",
"errors",
"i... | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Plotting_Libraries/sigfig.py#L80-L149 |
Vital-Fernandez/dazer | bin/lib/Plotting_Libraries/sigfig.py | round_sig_error2 | def round_sig_error2(x, ex1, ex2, n):
'''Find min(ex1,ex2) rounded to n sig-figs and make the floating point x
and max(ex,ex2) match the number of decimals.'''
minerr = min(ex1,ex2)
minstex = round_sig(minerr,n)
if minstex.find('.') < 0:
extra_zeros = len(minstex) - n
sigfigs = len(s... | python | def round_sig_error2(x, ex1, ex2, n):
'''Find min(ex1,ex2) rounded to n sig-figs and make the floating point x
and max(ex,ex2) match the number of decimals.'''
minerr = min(ex1,ex2)
minstex = round_sig(minerr,n)
if minstex.find('.') < 0:
extra_zeros = len(minstex) - n
sigfigs = len(s... | [
"def",
"round_sig_error2",
"(",
"x",
",",
"ex1",
",",
"ex2",
",",
"n",
")",
":",
"minerr",
"=",
"min",
"(",
"ex1",
",",
"ex2",
")",
"minstex",
"=",
"round_sig",
"(",
"minerr",
",",
"n",
")",
"if",
"minstex",
".",
"find",
"(",
"'.'",
")",
"<",
"... | Find min(ex1,ex2) rounded to n sig-figs and make the floating point x
and max(ex,ex2) match the number of decimals. | [
"Find",
"min",
"(",
"ex1",
"ex2",
")",
"rounded",
"to",
"n",
"sig",
"-",
"figs",
"and",
"make",
"the",
"floating",
"point",
"x",
"and",
"max",
"(",
"ex",
"ex2",
")",
"match",
"the",
"number",
"of",
"decimals",
"."
] | train | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Plotting_Libraries/sigfig.py#L151-L168 |
dacker-team/pyzure | pyzure/send/send_multi_threads.py | send_to_azure_multi_threads | def send_to_azure_multi_threads(instance, data, nb_threads=4, replace=True, types=None, primary_key=(),
sub_commit=False):
"""
data = {
"table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist,
"columns_name" : [first_colum... | python | def send_to_azure_multi_threads(instance, data, nb_threads=4, replace=True, types=None, primary_key=(),
sub_commit=False):
"""
data = {
"table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist,
"columns_name" : [first_colum... | [
"def",
"send_to_azure_multi_threads",
"(",
"instance",
",",
"data",
",",
"nb_threads",
"=",
"4",
",",
"replace",
"=",
"True",
",",
"types",
"=",
"None",
",",
"primary_key",
"=",
"(",
")",
",",
"sub_commit",
"=",
"False",
")",
":",
"# Time initialization",
... | data = {
"table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist,
"columns_name" : [first_column_name,second_column_name,...,last_column_name],
"rows" : [[first_raw_value,second_raw_value,...,last_raw_value],...]
} | [
"data",
"=",
"{",
"table_name",
":",
"name_of_the_azure_schema",
"+",
".",
"+",
"name_of_the_azure_table",
"#Must",
"already",
"exist",
"columns_name",
":",
"[",
"first_column_name",
"second_column_name",
"...",
"last_column_name",
"]",
"rows",
":",
"[[",
"first_raw_v... | train | https://github.com/dacker-team/pyzure/blob/1e6d202f91ca0f080635adc470d9d18585056d53/pyzure/send/send_multi_threads.py#L26-L113 |
dacker-team/pyzure | pyzure/send/send_multi_threads.py | send_to_azure | def send_to_azure(instance, data, thread_number, sub_commit, table_info, nb_threads):
"""
data = {
"table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist,
"columns_name" : [first_column_name,second_column_name,...,last_column_name],
"rows" : [[... | python | def send_to_azure(instance, data, thread_number, sub_commit, table_info, nb_threads):
"""
data = {
"table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist,
"columns_name" : [first_column_name,second_column_name,...,last_column_name],
"rows" : [[... | [
"def",
"send_to_azure",
"(",
"instance",
",",
"data",
",",
"thread_number",
",",
"sub_commit",
",",
"table_info",
",",
"nb_threads",
")",
":",
"rows",
"=",
"data",
"[",
"\"rows\"",
"]",
"if",
"not",
"rows",
":",
"return",
"0",
"columns_name",
"=",
"data",
... | data = {
"table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist,
"columns_name" : [first_column_name,second_column_name,...,last_column_name],
"rows" : [[first_raw_value,second_raw_value,...,last_raw_value],...]
} | [
"data",
"=",
"{",
"table_name",
":",
"name_of_the_azure_schema",
"+",
".",
"+",
"name_of_the_azure_table",
"#Must",
"already",
"exist",
"columns_name",
":",
"[",
"first_column_name",
"second_column_name",
"...",
"last_column_name",
"]",
"rows",
":",
"[[",
"first_raw_v... | train | https://github.com/dacker-team/pyzure/blob/1e6d202f91ca0f080635adc470d9d18585056d53/pyzure/send/send_multi_threads.py#L116-L182 |
paydunya/paydunya-python | paydunya/invoice.py | Invoice.create | def create(self, items=[], taxes=[], custom_data=[]):
"""Adds the items to the invoice
Format of 'items':
[
InvoiceItem(
name="VIP Ticket",
quantity= 2,
unit_price= "3500",
total_price= "7000",
description= "VIP Tickets f... | python | def create(self, items=[], taxes=[], custom_data=[]):
"""Adds the items to the invoice
Format of 'items':
[
InvoiceItem(
name="VIP Ticket",
quantity= 2,
unit_price= "3500",
total_price= "7000",
description= "VIP Tickets f... | [
"def",
"create",
"(",
"self",
",",
"items",
"=",
"[",
"]",
",",
"taxes",
"=",
"[",
"]",
",",
"custom_data",
"=",
"[",
"]",
")",
":",
"self",
".",
"add_items",
"(",
"items",
")",
"self",
".",
"add_taxes",
"(",
"taxes",
")",
"self",
".",
"add_custo... | Adds the items to the invoice
Format of 'items':
[
InvoiceItem(
name="VIP Ticket",
quantity= 2,
unit_price= "3500",
total_price= "7000",
description= "VIP Tickets for the Party"
}
,...
] | [
"Adds",
"the",
"items",
"to",
"the",
"invoice"
] | train | https://github.com/paydunya/paydunya-python/blob/bb55791e2814788aec74162d9d78970815f37c30/paydunya/invoice.py#L31-L49 |
paydunya/paydunya-python | paydunya/invoice.py | Invoice.confirm | def confirm(self, token=None):
"""Returns the status of the invoice
STATUSES: pending, completed, cancelled
"""
_token = token if token else self._response.get("token")
return self._process('checkout-invoice/confirm/' + str(_token)) | python | def confirm(self, token=None):
"""Returns the status of the invoice
STATUSES: pending, completed, cancelled
"""
_token = token if token else self._response.get("token")
return self._process('checkout-invoice/confirm/' + str(_token)) | [
"def",
"confirm",
"(",
"self",
",",
"token",
"=",
"None",
")",
":",
"_token",
"=",
"token",
"if",
"token",
"else",
"self",
".",
"_response",
".",
"get",
"(",
"\"token\"",
")",
"return",
"self",
".",
"_process",
"(",
"'checkout-invoice/confirm/'",
"+",
"s... | Returns the status of the invoice
STATUSES: pending, completed, cancelled | [
"Returns",
"the",
"status",
"of",
"the",
"invoice"
] | train | https://github.com/paydunya/paydunya-python/blob/bb55791e2814788aec74162d9d78970815f37c30/paydunya/invoice.py#L51-L57 |
paydunya/paydunya-python | paydunya/invoice.py | Invoice.add_taxes | def add_taxes(self, taxes):
"""Appends the data to the 'taxes' key in the request object
'taxes' should be in format: [("tax_name", "tax_amount")]
For example:
[("Other TAX", 700), ("VAT", 5000)]
"""
# fixme: how to resolve duplicate tax names
_idx = len(self.tax... | python | def add_taxes(self, taxes):
"""Appends the data to the 'taxes' key in the request object
'taxes' should be in format: [("tax_name", "tax_amount")]
For example:
[("Other TAX", 700), ("VAT", 5000)]
"""
# fixme: how to resolve duplicate tax names
_idx = len(self.tax... | [
"def",
"add_taxes",
"(",
"self",
",",
"taxes",
")",
":",
"# fixme: how to resolve duplicate tax names",
"_idx",
"=",
"len",
"(",
"self",
".",
"taxes",
")",
"# current index to prevent overwriting",
"for",
"idx",
",",
"tax",
"in",
"enumerate",
"(",
"taxes",
")",
... | Appends the data to the 'taxes' key in the request object
'taxes' should be in format: [("tax_name", "tax_amount")]
For example:
[("Other TAX", 700), ("VAT", 5000)] | [
"Appends",
"the",
"data",
"to",
"the",
"taxes",
"key",
"in",
"the",
"request",
"object"
] | train | https://github.com/paydunya/paydunya-python/blob/bb55791e2814788aec74162d9d78970815f37c30/paydunya/invoice.py#L59-L70 |
paydunya/paydunya-python | paydunya/invoice.py | Invoice.add_item | def add_item(self, item):
"""Updates the list of items in the current transaction"""
_idx = len(self.items)
self.items.update({"item_" + str(_idx + 1): item}) | python | def add_item(self, item):
"""Updates the list of items in the current transaction"""
_idx = len(self.items)
self.items.update({"item_" + str(_idx + 1): item}) | [
"def",
"add_item",
"(",
"self",
",",
"item",
")",
":",
"_idx",
"=",
"len",
"(",
"self",
".",
"items",
")",
"self",
".",
"items",
".",
"update",
"(",
"{",
"\"item_\"",
"+",
"str",
"(",
"_idx",
"+",
"1",
")",
":",
"item",
"}",
")"
] | Updates the list of items in the current transaction | [
"Updates",
"the",
"list",
"of",
"items",
"in",
"the",
"current",
"transaction"
] | train | https://github.com/paydunya/paydunya-python/blob/bb55791e2814788aec74162d9d78970815f37c30/paydunya/invoice.py#L79-L82 |
paydunya/paydunya-python | paydunya/invoice.py | Invoice._prepare_data | def _prepare_data(self):
"""Formats the data in the current transaction for processing"""
total_amount = self.total_amount or self.calculate_total_amt()
self._data = {
"invoice": {
"items": self.__encode_items(self.items),
"taxes": self.taxes,
... | python | def _prepare_data(self):
"""Formats the data in the current transaction for processing"""
total_amount = self.total_amount or self.calculate_total_amt()
self._data = {
"invoice": {
"items": self.__encode_items(self.items),
"taxes": self.taxes,
... | [
"def",
"_prepare_data",
"(",
"self",
")",
":",
"total_amount",
"=",
"self",
".",
"total_amount",
"or",
"self",
".",
"calculate_total_amt",
"(",
")",
"self",
".",
"_data",
"=",
"{",
"\"invoice\"",
":",
"{",
"\"items\"",
":",
"self",
".",
"__encode_items",
"... | Formats the data in the current transaction for processing | [
"Formats",
"the",
"data",
"in",
"the",
"current",
"transaction",
"for",
"processing"
] | train | https://github.com/paydunya/paydunya-python/blob/bb55791e2814788aec74162d9d78970815f37c30/paydunya/invoice.py#L97-L116 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.