repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
jobovy/galpy | galpy/df/streamdf.py | streamdf._find_closest_trackpoint | def _find_closest_trackpoint(self,R,vR,vT,z,vz,phi,interp=True,xy=False,
usev=False):
"""For backward compatibility"""
return self.find_closest_trackpoint(R,vR,vT,z,vz,phi,
interp=interp,xy=xy,
... | python | def _find_closest_trackpoint(self,R,vR,vT,z,vz,phi,interp=True,xy=False,
usev=False):
"""For backward compatibility"""
return self.find_closest_trackpoint(R,vR,vT,z,vz,phi,
interp=interp,xy=xy,
... | [
"def",
"_find_closest_trackpoint",
"(",
"self",
",",
"R",
",",
"vR",
",",
"vT",
",",
"z",
",",
"vz",
",",
"phi",
",",
"interp",
"=",
"True",
",",
"xy",
"=",
"False",
",",
"usev",
"=",
"False",
")",
":",
"return",
"self",
".",
"find_closest_trackpoint... | For backward compatibility | [
"For",
"backward",
"compatibility"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamdf.py#L1556-L1561 | train | 27,900 |
jobovy/galpy | galpy/df/streamdf.py | streamdf._density_par | def _density_par(self,dangle,tdisrupt=None):
"""The raw density as a function of parallel angle"""
if tdisrupt is None: tdisrupt= self._tdisrupt
dOmin= dangle/tdisrupt
# Normalize to 1 close to progenitor
return 0.5\
*(1.+special.erf((self._meandO-dOmin)\
... | python | def _density_par(self,dangle,tdisrupt=None):
"""The raw density as a function of parallel angle"""
if tdisrupt is None: tdisrupt= self._tdisrupt
dOmin= dangle/tdisrupt
# Normalize to 1 close to progenitor
return 0.5\
*(1.+special.erf((self._meandO-dOmin)\
... | [
"def",
"_density_par",
"(",
"self",
",",
"dangle",
",",
"tdisrupt",
"=",
"None",
")",
":",
"if",
"tdisrupt",
"is",
"None",
":",
"tdisrupt",
"=",
"self",
".",
"_tdisrupt",
"dOmin",
"=",
"dangle",
"/",
"tdisrupt",
"# Normalize to 1 close to progenitor",
"return"... | The raw density as a function of parallel angle | [
"The",
"raw",
"density",
"as",
"a",
"function",
"of",
"parallel",
"angle"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamdf.py#L1896-L1903 | train | 27,901 |
jobovy/galpy | galpy/df/streamdf.py | streamdf._sample_aAt | def _sample_aAt(self,n):
"""Sampling frequencies, angles, and times part of sampling"""
#Sample frequency along largest eigenvalue using ARS
dO1s=\
bovy_ars.bovy_ars([0.,0.],[True,False],
[self._meandO-numpy.sqrt(self._sortedSigOEig[2]),
... | python | def _sample_aAt(self,n):
"""Sampling frequencies, angles, and times part of sampling"""
#Sample frequency along largest eigenvalue using ARS
dO1s=\
bovy_ars.bovy_ars([0.,0.],[True,False],
[self._meandO-numpy.sqrt(self._sortedSigOEig[2]),
... | [
"def",
"_sample_aAt",
"(",
"self",
",",
"n",
")",
":",
"#Sample frequency along largest eigenvalue using ARS",
"dO1s",
"=",
"bovy_ars",
".",
"bovy_ars",
"(",
"[",
"0.",
",",
"0.",
"]",
",",
"[",
"True",
",",
"False",
"]",
",",
"[",
"self",
".",
"_meandO",
... | Sampling frequencies, angles, and times part of sampling | [
"Sampling",
"frequencies",
"angles",
"and",
"times",
"part",
"of",
"sampling"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamdf.py#L3050-L3075 | train | 27,902 |
jobovy/galpy | galpy/actionAngle/actionAngle.py | actionAngle._check_consistent_units | def _check_consistent_units(self):
"""Internal function to check that the set of units for this object is consistent with that for the potential"""
if isinstance(self._pot,list):
if self._roSet and self._pot[0]._roSet:
assert m.fabs(self._ro-self._pot[0]._ro) < 10.**-10., 'Ph... | python | def _check_consistent_units(self):
"""Internal function to check that the set of units for this object is consistent with that for the potential"""
if isinstance(self._pot,list):
if self._roSet and self._pot[0]._roSet:
assert m.fabs(self._ro-self._pot[0]._ro) < 10.**-10., 'Ph... | [
"def",
"_check_consistent_units",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_pot",
",",
"list",
")",
":",
"if",
"self",
".",
"_roSet",
"and",
"self",
".",
"_pot",
"[",
"0",
"]",
".",
"_roSet",
":",
"assert",
"m",
".",
"fabs",
"(... | Internal function to check that the set of units for this object is consistent with that for the potential | [
"Internal",
"function",
"to",
"check",
"that",
"the",
"set",
"of",
"units",
"for",
"this",
"object",
"is",
"consistent",
"with",
"that",
"for",
"the",
"potential"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/actionAngle/actionAngle.py#L71-L83 | train | 27,903 |
jobovy/galpy | galpy/actionAngle/actionAngle.py | actionAngle._check_consistent_units_orbitInput | def _check_consistent_units_orbitInput(self,orb):
"""Internal function to check that the set of units for this object is consistent with that for an input orbit"""
if self._roSet and orb._roSet:
assert m.fabs(self._ro-orb._ro) < 10.**-10., 'Physical conversion for the actionAngle object is n... | python | def _check_consistent_units_orbitInput(self,orb):
"""Internal function to check that the set of units for this object is consistent with that for an input orbit"""
if self._roSet and orb._roSet:
assert m.fabs(self._ro-orb._ro) < 10.**-10., 'Physical conversion for the actionAngle object is n... | [
"def",
"_check_consistent_units_orbitInput",
"(",
"self",
",",
"orb",
")",
":",
"if",
"self",
".",
"_roSet",
"and",
"orb",
".",
"_roSet",
":",
"assert",
"m",
".",
"fabs",
"(",
"self",
".",
"_ro",
"-",
"orb",
".",
"_ro",
")",
"<",
"10.",
"**",
"-",
... | Internal function to check that the set of units for this object is consistent with that for an input orbit | [
"Internal",
"function",
"to",
"check",
"that",
"the",
"set",
"of",
"units",
"for",
"this",
"object",
"is",
"consistent",
"with",
"that",
"for",
"an",
"input",
"orbit"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/actionAngle/actionAngle.py#L85-L91 | train | 27,904 |
jobovy/galpy | galpy/potential/SpiralArmsPotential.py | check_inputs_not_arrays | def check_inputs_not_arrays(func):
"""
Decorator to check inputs and throw TypeError if any of the inputs are arrays.
Methods potentially return with silent errors if inputs are not checked.
"""
@wraps(func)
def func_wrapper(self, R, z, phi, t):
if (hasattr(R, '__len__') and len(R) > 1) ... | python | def check_inputs_not_arrays(func):
"""
Decorator to check inputs and throw TypeError if any of the inputs are arrays.
Methods potentially return with silent errors if inputs are not checked.
"""
@wraps(func)
def func_wrapper(self, R, z, phi, t):
if (hasattr(R, '__len__') and len(R) > 1) ... | [
"def",
"check_inputs_not_arrays",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"func_wrapper",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
",",
"t",
")",
":",
"if",
"(",
"hasattr",
"(",
"R",
",",
"'__len__'",
")",
"and",
"len",
... | Decorator to check inputs and throw TypeError if any of the inputs are arrays.
Methods potentially return with silent errors if inputs are not checked. | [
"Decorator",
"to",
"check",
"inputs",
"and",
"throw",
"TypeError",
"if",
"any",
"of",
"the",
"inputs",
"are",
"arrays",
".",
"Methods",
"potentially",
"return",
"with",
"silent",
"errors",
"if",
"inputs",
"are",
"not",
"checked",
"."
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/SpiralArmsPotential.py#L21-L35 | train | 27,905 |
jobovy/galpy | galpy/actionAngle/actionAngleAxi.py | _JRAxiIntegrand | def _JRAxiIntegrand(r,E,L,pot):
"""The J_R integrand"""
return nu.sqrt(2.*(E-potentialAxi(r,pot))-L**2./r**2.) | python | def _JRAxiIntegrand(r,E,L,pot):
"""The J_R integrand"""
return nu.sqrt(2.*(E-potentialAxi(r,pot))-L**2./r**2.) | [
"def",
"_JRAxiIntegrand",
"(",
"r",
",",
"E",
",",
"L",
",",
"pot",
")",
":",
"return",
"nu",
".",
"sqrt",
"(",
"2.",
"*",
"(",
"E",
"-",
"potentialAxi",
"(",
"r",
",",
"pot",
")",
")",
"-",
"L",
"**",
"2.",
"/",
"r",
"**",
"2.",
")"
] | The J_R integrand | [
"The",
"J_R",
"integrand"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/actionAngle/actionAngleAxi.py#L367-L369 | train | 27,906 |
jobovy/galpy | galpy/actionAngle/actionAngleAxi.py | _rapRperiAxiEq | def _rapRperiAxiEq(R,E,L,pot):
"""The vr=0 equation that needs to be solved to find apo- and pericenter"""
return E-potentialAxi(R,pot)-L**2./2./R**2. | python | def _rapRperiAxiEq(R,E,L,pot):
"""The vr=0 equation that needs to be solved to find apo- and pericenter"""
return E-potentialAxi(R,pot)-L**2./2./R**2. | [
"def",
"_rapRperiAxiEq",
"(",
"R",
",",
"E",
",",
"L",
",",
"pot",
")",
":",
"return",
"E",
"-",
"potentialAxi",
"(",
"R",
",",
"pot",
")",
"-",
"L",
"**",
"2.",
"/",
"2.",
"/",
"R",
"**",
"2."
] | The vr=0 equation that needs to be solved to find apo- and pericenter | [
"The",
"vr",
"=",
"0",
"equation",
"that",
"needs",
"to",
"be",
"solved",
"to",
"find",
"apo",
"-",
"and",
"pericenter"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/actionAngle/actionAngleAxi.py#L387-L389 | train | 27,907 |
jobovy/galpy | galpy/potential/Potential.py | _rlfunc | def _rlfunc(rl,lz,pot):
"""Function that gives rvc-lz"""
thisvcirc= vcirc(pot,rl,use_physical=False)
return rl*thisvcirc-lz | python | def _rlfunc(rl,lz,pot):
"""Function that gives rvc-lz"""
thisvcirc= vcirc(pot,rl,use_physical=False)
return rl*thisvcirc-lz | [
"def",
"_rlfunc",
"(",
"rl",
",",
"lz",
",",
"pot",
")",
":",
"thisvcirc",
"=",
"vcirc",
"(",
"pot",
",",
"rl",
",",
"use_physical",
"=",
"False",
")",
"return",
"rl",
"*",
"thisvcirc",
"-",
"lz"
] | Function that gives rvc-lz | [
"Function",
"that",
"gives",
"rvc",
"-",
"lz"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/Potential.py#L2678-L2681 | train | 27,908 |
jobovy/galpy | galpy/potential/Potential.py | _rlFindStart | def _rlFindStart(rl,lz,pot,lower=False):
"""find a starting interval for rl"""
rtry= 2.*rl
while (2.*lower-1.)*_rlfunc(rtry,lz,pot) > 0.:
if lower:
rtry/= 2.
else:
rtry*= 2.
return rtry | python | def _rlFindStart(rl,lz,pot,lower=False):
"""find a starting interval for rl"""
rtry= 2.*rl
while (2.*lower-1.)*_rlfunc(rtry,lz,pot) > 0.:
if lower:
rtry/= 2.
else:
rtry*= 2.
return rtry | [
"def",
"_rlFindStart",
"(",
"rl",
",",
"lz",
",",
"pot",
",",
"lower",
"=",
"False",
")",
":",
"rtry",
"=",
"2.",
"*",
"rl",
"while",
"(",
"2.",
"*",
"lower",
"-",
"1.",
")",
"*",
"_rlfunc",
"(",
"rtry",
",",
"lz",
",",
"pot",
")",
">",
"0.",... | find a starting interval for rl | [
"find",
"a",
"starting",
"interval",
"for",
"rl"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/Potential.py#L2683-L2691 | train | 27,909 |
jobovy/galpy | galpy/orbit/OrbitTop.py | _check_roSet | def _check_roSet(orb,kwargs,funcName):
"""Function to check whether ro is set, because it's required for funcName"""
if not orb._roSet and kwargs.get('ro',None) is None:
warnings.warn("Method %s(.) requires ro to be given at Orbit initialization or at method evaluation; using default ro which is %f kpc"... | python | def _check_roSet(orb,kwargs,funcName):
"""Function to check whether ro is set, because it's required for funcName"""
if not orb._roSet and kwargs.get('ro',None) is None:
warnings.warn("Method %s(.) requires ro to be given at Orbit initialization or at method evaluation; using default ro which is %f kpc"... | [
"def",
"_check_roSet",
"(",
"orb",
",",
"kwargs",
",",
"funcName",
")",
":",
"if",
"not",
"orb",
".",
"_roSet",
"and",
"kwargs",
".",
"get",
"(",
"'ro'",
",",
"None",
")",
"is",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"Method %s(.) requires ro to be... | Function to check whether ro is set, because it's required for funcName | [
"Function",
"to",
"check",
"whether",
"ro",
"is",
"set",
"because",
"it",
"s",
"required",
"for",
"funcName"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L2398-L2402 | train | 27,910 |
jobovy/galpy | galpy/orbit/OrbitTop.py | _check_voSet | def _check_voSet(orb,kwargs,funcName):
"""Function to check whether vo is set, because it's required for funcName"""
if not orb._voSet and kwargs.get('vo',None) is None:
warnings.warn("Method %s(.) requires vo to be given at Orbit initialization or at method evaluation; using default vo which is %f km/s... | python | def _check_voSet(orb,kwargs,funcName):
"""Function to check whether vo is set, because it's required for funcName"""
if not orb._voSet and kwargs.get('vo',None) is None:
warnings.warn("Method %s(.) requires vo to be given at Orbit initialization or at method evaluation; using default vo which is %f km/s... | [
"def",
"_check_voSet",
"(",
"orb",
",",
"kwargs",
",",
"funcName",
")",
":",
"if",
"not",
"orb",
".",
"_voSet",
"and",
"kwargs",
".",
"get",
"(",
"'vo'",
",",
"None",
")",
"is",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"Method %s(.) requires vo to be... | Function to check whether vo is set, because it's required for funcName | [
"Function",
"to",
"check",
"whether",
"vo",
"is",
"set",
"because",
"it",
"s",
"required",
"for",
"funcName"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L2404-L2408 | train | 27,911 |
jobovy/galpy | galpy/orbit/OrbitTop.py | OrbitTop._radec | def _radec(self,*args,**kwargs):
"""Calculate ra and dec"""
lbd= self._lbd(*args,**kwargs)
return coords.lb_to_radec(lbd[:,0],lbd[:,1],degree=True,epoch=None) | python | def _radec(self,*args,**kwargs):
"""Calculate ra and dec"""
lbd= self._lbd(*args,**kwargs)
return coords.lb_to_radec(lbd[:,0],lbd[:,1],degree=True,epoch=None) | [
"def",
"_radec",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"lbd",
"=",
"self",
".",
"_lbd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"coords",
".",
"lb_to_radec",
"(",
"lbd",
"[",
":",
",",
"0",
"]",
"... | Calculate ra and dec | [
"Calculate",
"ra",
"and",
"dec"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L919-L922 | train | 27,912 |
jobovy/galpy | galpy/orbit/OrbitTop.py | OrbitTop._pmrapmdec | def _pmrapmdec(self,*args,**kwargs):
"""Calculate pmra and pmdec"""
lbdvrpmllpmbb= self._lbdvrpmllpmbb(*args,**kwargs)
return coords.pmllpmbb_to_pmrapmdec(lbdvrpmllpmbb[:,4],
lbdvrpmllpmbb[:,5],
lbdvrpmllpmbb... | python | def _pmrapmdec(self,*args,**kwargs):
"""Calculate pmra and pmdec"""
lbdvrpmllpmbb= self._lbdvrpmllpmbb(*args,**kwargs)
return coords.pmllpmbb_to_pmrapmdec(lbdvrpmllpmbb[:,4],
lbdvrpmllpmbb[:,5],
lbdvrpmllpmbb... | [
"def",
"_pmrapmdec",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"lbdvrpmllpmbb",
"=",
"self",
".",
"_lbdvrpmllpmbb",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"coords",
".",
"pmllpmbb_to_pmrapmdec",
"(",
"lbdvrpmllp... | Calculate pmra and pmdec | [
"Calculate",
"pmra",
"and",
"pmdec"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L924-L931 | train | 27,913 |
jobovy/galpy | galpy/orbit/OrbitTop.py | OrbitTop._lbd | def _lbd(self,*args,**kwargs):
"""Calculate l,b, and d"""
obs, ro, vo= self._parse_radec_kwargs(kwargs,dontpop=True)
X,Y,Z= self._helioXYZ(*args,**kwargs)
bad_indx= (X == 0.)*(Y == 0.)*(Z == 0.)
if True in bad_indx:
X[bad_indx]+= ro/10000.
return coords.XYZ_to... | python | def _lbd(self,*args,**kwargs):
"""Calculate l,b, and d"""
obs, ro, vo= self._parse_radec_kwargs(kwargs,dontpop=True)
X,Y,Z= self._helioXYZ(*args,**kwargs)
bad_indx= (X == 0.)*(Y == 0.)*(Z == 0.)
if True in bad_indx:
X[bad_indx]+= ro/10000.
return coords.XYZ_to... | [
"def",
"_lbd",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"obs",
",",
"ro",
",",
"vo",
"=",
"self",
".",
"_parse_radec_kwargs",
"(",
"kwargs",
",",
"dontpop",
"=",
"True",
")",
"X",
",",
"Y",
",",
"Z",
"=",
"self",
".",
... | Calculate l,b, and d | [
"Calculate",
"l",
"b",
"and",
"d"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L933-L940 | train | 27,914 |
jobovy/galpy | galpy/orbit/OrbitTop.py | OrbitTop._lbdvrpmllpmbb | def _lbdvrpmllpmbb(self,*args,**kwargs):
"""Calculate l,b,d,vr,pmll,pmbb"""
obs, ro, vo= self._parse_radec_kwargs(kwargs,dontpop=True)
X,Y,Z,vX,vY,vZ= self._XYZvxvyvz(*args,**kwargs)
bad_indx= (X == 0.)*(Y == 0.)*(Z == 0.)
if True in bad_indx:
X[bad_indx]+= ro/10000.
... | python | def _lbdvrpmllpmbb(self,*args,**kwargs):
"""Calculate l,b,d,vr,pmll,pmbb"""
obs, ro, vo= self._parse_radec_kwargs(kwargs,dontpop=True)
X,Y,Z,vX,vY,vZ= self._XYZvxvyvz(*args,**kwargs)
bad_indx= (X == 0.)*(Y == 0.)*(Z == 0.)
if True in bad_indx:
X[bad_indx]+= ro/10000.
... | [
"def",
"_lbdvrpmllpmbb",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"obs",
",",
"ro",
",",
"vo",
"=",
"self",
".",
"_parse_radec_kwargs",
"(",
"kwargs",
",",
"dontpop",
"=",
"True",
")",
"X",
",",
"Y",
",",
"Z",
",",
"vX",
... | Calculate l,b,d,vr,pmll,pmbb | [
"Calculate",
"l",
"b",
"d",
"vr",
"pmll",
"pmbb"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L992-L999 | train | 27,915 |
jobovy/galpy | galpy/orbit/OrbitTop.py | OrbitTop._parse_plot_quantity | def _parse_plot_quantity(self,quant,**kwargs):
"""Internal function to parse a quantity to be plotted based on input data"""
# Cannot be using Quantity output
kwargs['quantity']= False
if callable(quant):
return quant(self.t)
def _eval(q):
# Check those th... | python | def _parse_plot_quantity(self,quant,**kwargs):
"""Internal function to parse a quantity to be plotted based on input data"""
# Cannot be using Quantity output
kwargs['quantity']= False
if callable(quant):
return quant(self.t)
def _eval(q):
# Check those th... | [
"def",
"_parse_plot_quantity",
"(",
"self",
",",
"quant",
",",
"*",
"*",
"kwargs",
")",
":",
"# Cannot be using Quantity output",
"kwargs",
"[",
"'quantity'",
"]",
"=",
"False",
"if",
"callable",
"(",
"quant",
")",
":",
"return",
"quant",
"(",
"self",
".",
... | Internal function to parse a quantity to be plotted based on input data | [
"Internal",
"function",
"to",
"parse",
"a",
"quantity",
"to",
"be",
"plotted",
"based",
"on",
"input",
"data"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L1631-L1667 | train | 27,916 |
jobovy/galpy | galpy/df/quasiisothermaldf.py | quasiisothermaldf._jmomentdensity | def _jmomentdensity(self,R,z,n,m,o,nsigma=None,mc=True,nmc=10000,
_returnmc=False,_vrs=None,_vts=None,_vzs=None,
**kwargs):
"""Non-physical version of jmomentdensity, otherwise the same"""
if nsigma == None:
nsigma= _NSIGMA
sigmaR1= self.... | python | def _jmomentdensity(self,R,z,n,m,o,nsigma=None,mc=True,nmc=10000,
_returnmc=False,_vrs=None,_vts=None,_vzs=None,
**kwargs):
"""Non-physical version of jmomentdensity, otherwise the same"""
if nsigma == None:
nsigma= _NSIGMA
sigmaR1= self.... | [
"def",
"_jmomentdensity",
"(",
"self",
",",
"R",
",",
"z",
",",
"n",
",",
"m",
",",
"o",
",",
"nsigma",
"=",
"None",
",",
"mc",
"=",
"True",
",",
"nmc",
"=",
"10000",
",",
"_returnmc",
"=",
"False",
",",
"_vrs",
"=",
"None",
",",
"_vts",
"=",
... | Non-physical version of jmomentdensity, otherwise the same | [
"Non",
"-",
"physical",
"version",
"of",
"jmomentdensity",
"otherwise",
"the",
"same"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/quasiisothermaldf.py#L811-L854 | train | 27,917 |
jobovy/galpy | galpy/df/streamgapdf.py | impact_check_range | def impact_check_range(func):
"""Decorator to check the range of interpolated kicks"""
@wraps(func)
def impact_wrapper(*args,**kwargs):
if isinstance(args[1],numpy.ndarray):
out= numpy.zeros(len(args[1]))
goodIndx= (args[1] < args[0]._deltaAngleTrackImpact)*(args[1] > 0.)
... | python | def impact_check_range(func):
"""Decorator to check the range of interpolated kicks"""
@wraps(func)
def impact_wrapper(*args,**kwargs):
if isinstance(args[1],numpy.ndarray):
out= numpy.zeros(len(args[1]))
goodIndx= (args[1] < args[0]._deltaAngleTrackImpact)*(args[1] > 0.)
... | [
"def",
"impact_check_range",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"impact_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"args",
"[",
"1",
"]",
",",
"numpy",
".",
"ndarray",
")",
":"... | Decorator to check the range of interpolated kicks | [
"Decorator",
"to",
"check",
"the",
"range",
"of",
"interpolated",
"kicks"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamgapdf.py#L20-L33 | train | 27,918 |
jobovy/galpy | galpy/df/streamgapdf.py | streamgapdf._density_par | def _density_par(self,dangle,tdisrupt=None,approx=True,
higherorder=None):
"""The raw density as a function of parallel angle,
approx= use faster method that directly integrates the spline
representation"""
if higherorder is None: higherorder= self._higherorderTrack
... | python | def _density_par(self,dangle,tdisrupt=None,approx=True,
higherorder=None):
"""The raw density as a function of parallel angle,
approx= use faster method that directly integrates the spline
representation"""
if higherorder is None: higherorder= self._higherorderTrack
... | [
"def",
"_density_par",
"(",
"self",
",",
"dangle",
",",
"tdisrupt",
"=",
"None",
",",
"approx",
"=",
"True",
",",
"higherorder",
"=",
"None",
")",
":",
"if",
"higherorder",
"is",
"None",
":",
"higherorder",
"=",
"self",
".",
"_higherorderTrack",
"if",
"t... | The raw density as a function of parallel angle,
approx= use faster method that directly integrates the spline
representation | [
"The",
"raw",
"density",
"as",
"a",
"function",
"of",
"parallel",
"angle",
"approx",
"=",
"use",
"faster",
"method",
"that",
"directly",
"integrates",
"the",
"spline",
"representation"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamgapdf.py#L225-L241 | train | 27,919 |
jobovy/galpy | galpy/df/streamgapdf.py | streamgapdf._density_par_approx | def _density_par_approx(self,dangle,tdisrupt,_return_array=False,
higherorder=False):
"""Compute the density as a function of parallel angle using the
spline representation + approximations"""
# First construct the breakpoints for this dangle
Oparb= (dangle-s... | python | def _density_par_approx(self,dangle,tdisrupt,_return_array=False,
higherorder=False):
"""Compute the density as a function of parallel angle using the
spline representation + approximations"""
# First construct the breakpoints for this dangle
Oparb= (dangle-s... | [
"def",
"_density_par_approx",
"(",
"self",
",",
"dangle",
",",
"tdisrupt",
",",
"_return_array",
"=",
"False",
",",
"higherorder",
"=",
"False",
")",
":",
"# First construct the breakpoints for this dangle",
"Oparb",
"=",
"(",
"dangle",
"-",
"self",
".",
"_kick_in... | Compute the density as a function of parallel angle using the
spline representation + approximations | [
"Compute",
"the",
"density",
"as",
"a",
"function",
"of",
"parallel",
"angle",
"using",
"the",
"spline",
"representation",
"+",
"approximations"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamgapdf.py#L243-L268 | train | 27,920 |
jobovy/galpy | galpy/df/streamgapdf.py | streamgapdf._density_par_approx_higherorder | def _density_par_approx_higherorder(self,Oparb,lowbindx,
_return_array=False,
gaussxpolyInt=None):
"""Contribution from non-linear spline terms"""
spline_order= self._kick_interpdOpar_raw._eval_args[2]
if spline_orde... | python | def _density_par_approx_higherorder(self,Oparb,lowbindx,
_return_array=False,
gaussxpolyInt=None):
"""Contribution from non-linear spline terms"""
spline_order= self._kick_interpdOpar_raw._eval_args[2]
if spline_orde... | [
"def",
"_density_par_approx_higherorder",
"(",
"self",
",",
"Oparb",
",",
"lowbindx",
",",
"_return_array",
"=",
"False",
",",
"gaussxpolyInt",
"=",
"None",
")",
":",
"spline_order",
"=",
"self",
".",
"_kick_interpdOpar_raw",
".",
"_eval_args",
"[",
"2",
"]",
... | Contribution from non-linear spline terms | [
"Contribution",
"from",
"non",
"-",
"linear",
"spline",
"terms"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamgapdf.py#L270-L307 | train | 27,921 |
jobovy/galpy | galpy/df/streamgapdf.py | streamgapdf._densMoments_approx_higherorder_gaussxpolyInts | def _densMoments_approx_higherorder_gaussxpolyInts(self,ll,ul,maxj):
"""Calculate all of the polynomial x Gaussian integrals occuring
in the higher-order terms, recursively"""
gaussxpolyInt= numpy.zeros((maxj,len(ul)))
gaussxpolyInt[-1]= 1./numpy.sqrt(numpy.pi)\
*(numpy.exp(... | python | def _densMoments_approx_higherorder_gaussxpolyInts(self,ll,ul,maxj):
"""Calculate all of the polynomial x Gaussian integrals occuring
in the higher-order terms, recursively"""
gaussxpolyInt= numpy.zeros((maxj,len(ul)))
gaussxpolyInt[-1]= 1./numpy.sqrt(numpy.pi)\
*(numpy.exp(... | [
"def",
"_densMoments_approx_higherorder_gaussxpolyInts",
"(",
"self",
",",
"ll",
",",
"ul",
",",
"maxj",
")",
":",
"gaussxpolyInt",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"maxj",
",",
"len",
"(",
"ul",
")",
")",
")",
"gaussxpolyInt",
"[",
"-",
"1",
"]",
... | Calculate all of the polynomial x Gaussian integrals occuring
in the higher-order terms, recursively | [
"Calculate",
"all",
"of",
"the",
"polynomial",
"x",
"Gaussian",
"integrals",
"occuring",
"in",
"the",
"higher",
"-",
"order",
"terms",
"recursively"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamgapdf.py#L309-L322 | train | 27,922 |
jobovy/galpy | galpy/df/streamgapdf.py | streamgapdf._meanOmega_num_approx | def _meanOmega_num_approx(self,dangle,tdisrupt,higherorder=False):
"""Compute the numerator going into meanOmega using the direct integration of the spline representation"""
# First construct the breakpoints for this dangle
Oparb= (dangle-self._kick_interpdOpar_poly.x)/self._timpact
# Fi... | python | def _meanOmega_num_approx(self,dangle,tdisrupt,higherorder=False):
"""Compute the numerator going into meanOmega using the direct integration of the spline representation"""
# First construct the breakpoints for this dangle
Oparb= (dangle-self._kick_interpdOpar_poly.x)/self._timpact
# Fi... | [
"def",
"_meanOmega_num_approx",
"(",
"self",
",",
"dangle",
",",
"tdisrupt",
",",
"higherorder",
"=",
"False",
")",
":",
"# First construct the breakpoints for this dangle",
"Oparb",
"=",
"(",
"dangle",
"-",
"self",
".",
"_kick_interpdOpar_poly",
".",
"x",
")",
"/... | Compute the numerator going into meanOmega using the direct integration of the spline representation | [
"Compute",
"the",
"numerator",
"going",
"into",
"meanOmega",
"using",
"the",
"direct",
"integration",
"of",
"the",
"spline",
"representation"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamgapdf.py#L418-L454 | train | 27,923 |
jobovy/galpy | galpy/df/streamgapdf.py | streamgapdf._interpolate_stream_track_kick_aA | def _interpolate_stream_track_kick_aA(self):
"""Build interpolations of the stream track near the impact in action-angle coordinates"""
if hasattr(self,'_kick_interpolatedObsTrackAA'): #pragma: no cover
return None #Already did this
#Calculate 1D meanOmega on a fine grid in angle and... | python | def _interpolate_stream_track_kick_aA(self):
"""Build interpolations of the stream track near the impact in action-angle coordinates"""
if hasattr(self,'_kick_interpolatedObsTrackAA'): #pragma: no cover
return None #Already did this
#Calculate 1D meanOmega on a fine grid in angle and... | [
"def",
"_interpolate_stream_track_kick_aA",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_kick_interpolatedObsTrackAA'",
")",
":",
"#pragma: no cover",
"return",
"None",
"#Already did this",
"#Calculate 1D meanOmega on a fine grid in angle and interpolate",
"dmOs... | Build interpolations of the stream track near the impact in action-angle coordinates | [
"Build",
"interpolations",
"of",
"the",
"stream",
"track",
"near",
"the",
"impact",
"in",
"action",
"-",
"angle",
"coordinates"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamgapdf.py#L753-L780 | train | 27,924 |
jobovy/galpy | galpy/df/streamgapdf.py | streamgapdf._gap_progenitor_setup | def _gap_progenitor_setup(self):
"""Setup an Orbit instance that's the progenitor integrated backwards"""
self._gap_progenitor= self._progenitor().flip() # new orbit, flip velocities
# Make sure we do not use physical coordinates
self._gap_progenitor.turn_physical_off()
# Now int... | python | def _gap_progenitor_setup(self):
"""Setup an Orbit instance that's the progenitor integrated backwards"""
self._gap_progenitor= self._progenitor().flip() # new orbit, flip velocities
# Make sure we do not use physical coordinates
self._gap_progenitor.turn_physical_off()
# Now int... | [
"def",
"_gap_progenitor_setup",
"(",
"self",
")",
":",
"self",
".",
"_gap_progenitor",
"=",
"self",
".",
"_progenitor",
"(",
")",
".",
"flip",
"(",
")",
"# new orbit, flip velocities",
"# Make sure we do not use physical coordinates",
"self",
".",
"_gap_progenitor",
"... | Setup an Orbit instance that's the progenitor integrated backwards | [
"Setup",
"an",
"Orbit",
"instance",
"that",
"s",
"the",
"progenitor",
"integrated",
"backwards"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamgapdf.py#L963-L975 | train | 27,925 |
jobovy/galpy | galpy/df/streamgapdf.py | streamgapdf._sample_aAt | def _sample_aAt(self,n):
"""Sampling frequencies, angles, and times part of sampling, for stream with gap"""
# Use streamdf's _sample_aAt to generate unperturbed frequencies,
# angles
Om,angle,dt= super(streamgapdf,self)._sample_aAt(n)
# Now rewind angles by timpact, apply the ki... | python | def _sample_aAt(self,n):
"""Sampling frequencies, angles, and times part of sampling, for stream with gap"""
# Use streamdf's _sample_aAt to generate unperturbed frequencies,
# angles
Om,angle,dt= super(streamgapdf,self)._sample_aAt(n)
# Now rewind angles by timpact, apply the ki... | [
"def",
"_sample_aAt",
"(",
"self",
",",
"n",
")",
":",
"# Use streamdf's _sample_aAt to generate unperturbed frequencies,",
"# angles",
"Om",
",",
"angle",
",",
"dt",
"=",
"super",
"(",
"streamgapdf",
",",
"self",
")",
".",
"_sample_aAt",
"(",
"n",
")",
"# Now r... | Sampling frequencies, angles, and times part of sampling, for stream with gap | [
"Sampling",
"frequencies",
"angles",
"and",
"times",
"part",
"of",
"sampling",
"for",
"stream",
"with",
"gap"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamgapdf.py#L978-L1002 | train | 27,926 |
jobovy/galpy | galpy/util/multi.py | worker | def worker(f, ii, chunk, out_q, err_q, lock):
"""
A worker function that maps an input function over a
slice of the input iterable.
:param f : callable function that accepts argument from iterable
:param ii : process ID
:param chunk: slice of input iterable
:param out_q: thread-safe output queue
:par... | python | def worker(f, ii, chunk, out_q, err_q, lock):
"""
A worker function that maps an input function over a
slice of the input iterable.
:param f : callable function that accepts argument from iterable
:param ii : process ID
:param chunk: slice of input iterable
:param out_q: thread-safe output queue
:par... | [
"def",
"worker",
"(",
"f",
",",
"ii",
",",
"chunk",
",",
"out_q",
",",
"err_q",
",",
"lock",
")",
":",
"vals",
"=",
"[",
"]",
"# iterate over slice ",
"for",
"val",
"in",
"chunk",
":",
"try",
":",
"result",
"=",
"f",
"(",
"val",
")",
"except",
"E... | A worker function that maps an input function over a
slice of the input iterable.
:param f : callable function that accepts argument from iterable
:param ii : process ID
:param chunk: slice of input iterable
:param out_q: thread-safe output queue
:param err_q: thread-safe queue to populate on exception
... | [
"A",
"worker",
"function",
"that",
"maps",
"an",
"input",
"function",
"over",
"a",
"slice",
"of",
"the",
"input",
"iterable",
"."
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/util/multi.py#L53-L79 | train | 27,927 |
jobovy/galpy | galpy/util/multi.py | run_tasks | def run_tasks(procs, err_q, out_q, num):
"""
A function that executes populated processes and processes
the resultant array. Checks error queue for any exceptions.
:param procs: list of Process objects
:param out_q: thread-safe output queue
:param err_q: thread-safe queue to populate on exception
:param ... | python | def run_tasks(procs, err_q, out_q, num):
"""
A function that executes populated processes and processes
the resultant array. Checks error queue for any exceptions.
:param procs: list of Process objects
:param out_q: thread-safe output queue
:param err_q: thread-safe queue to populate on exception
:param ... | [
"def",
"run_tasks",
"(",
"procs",
",",
"err_q",
",",
"out_q",
",",
"num",
")",
":",
"# function to terminate processes that are still running.",
"die",
"=",
"(",
"lambda",
"vals",
":",
"[",
"val",
".",
"terminate",
"(",
")",
"for",
"val",
"in",
"vals",
"if",... | A function that executes populated processes and processes
the resultant array. Checks error queue for any exceptions.
:param procs: list of Process objects
:param out_q: thread-safe output queue
:param err_q: thread-safe queue to populate on exception
:param num : length of resultant array | [
"A",
"function",
"that",
"executes",
"populated",
"processes",
"and",
"processes",
"the",
"resultant",
"array",
".",
"Checks",
"error",
"queue",
"for",
"any",
"exceptions",
"."
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/util/multi.py#L82-L126 | train | 27,928 |
jobovy/galpy | galpy/util/multi.py | parallel_map | def parallel_map(function, sequence, numcores=None):
"""
A parallelized version of the native Python map function that
utilizes the Python multiprocessing module to divide and
conquer sequence.
parallel_map does not yet support multiple argument sequences.
:param function: callable function that accepts ... | python | def parallel_map(function, sequence, numcores=None):
"""
A parallelized version of the native Python map function that
utilizes the Python multiprocessing module to divide and
conquer sequence.
parallel_map does not yet support multiple argument sequences.
:param function: callable function that accepts ... | [
"def",
"parallel_map",
"(",
"function",
",",
"sequence",
",",
"numcores",
"=",
"None",
")",
":",
"if",
"not",
"callable",
"(",
"function",
")",
":",
"raise",
"TypeError",
"(",
"\"input function '%s' is not callable\"",
"%",
"repr",
"(",
"function",
")",
")",
... | A parallelized version of the native Python map function that
utilizes the Python multiprocessing module to divide and
conquer sequence.
parallel_map does not yet support multiple argument sequences.
:param function: callable function that accepts argument from iterable
:param sequence: iterable sequence
... | [
"A",
"parallelized",
"version",
"of",
"the",
"native",
"Python",
"map",
"function",
"that",
"utilizes",
"the",
"Python",
"multiprocessing",
"module",
"to",
"divide",
"and",
"conquer",
"sequence",
"."
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/util/multi.py#L129-L185 | train | 27,929 |
jobovy/galpy | galpy/actionAngle/actionAngleStaeckelGrid.py | _u0Eq | def _u0Eq(logu,delta,pot,E,Lz22):
"""The equation that needs to be minimized to find u0"""
u= numpy.exp(logu)
sinh2u= numpy.sinh(u)**2.
cosh2u= numpy.cosh(u)**2.
dU= cosh2u*actionAngleStaeckel.potentialStaeckel(u,numpy.pi/2.,pot,delta)
return -(E*sinh2u-dU-Lz22/delta**2./sinh2u) | python | def _u0Eq(logu,delta,pot,E,Lz22):
"""The equation that needs to be minimized to find u0"""
u= numpy.exp(logu)
sinh2u= numpy.sinh(u)**2.
cosh2u= numpy.cosh(u)**2.
dU= cosh2u*actionAngleStaeckel.potentialStaeckel(u,numpy.pi/2.,pot,delta)
return -(E*sinh2u-dU-Lz22/delta**2./sinh2u) | [
"def",
"_u0Eq",
"(",
"logu",
",",
"delta",
",",
"pot",
",",
"E",
",",
"Lz22",
")",
":",
"u",
"=",
"numpy",
".",
"exp",
"(",
"logu",
")",
"sinh2u",
"=",
"numpy",
".",
"sinh",
"(",
"u",
")",
"**",
"2.",
"cosh2u",
"=",
"numpy",
".",
"cosh",
"(",... | The equation that needs to be minimized to find u0 | [
"The",
"equation",
"that",
"needs",
"to",
"be",
"minimized",
"to",
"find",
"u0"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/actionAngle/actionAngleStaeckelGrid.py#L672-L678 | train | 27,930 |
jobovy/galpy | galpy/actionAngle/actionAngleSpherical.py | _JrSphericalIntegrand | def _JrSphericalIntegrand(r,E,L,pot):
"""The J_r integrand"""
return nu.sqrt(2.*(E-potentialAxi(r,pot))-L**2./r**2.) | python | def _JrSphericalIntegrand(r,E,L,pot):
"""The J_r integrand"""
return nu.sqrt(2.*(E-potentialAxi(r,pot))-L**2./r**2.) | [
"def",
"_JrSphericalIntegrand",
"(",
"r",
",",
"E",
",",
"L",
",",
"pot",
")",
":",
"return",
"nu",
".",
"sqrt",
"(",
"2.",
"*",
"(",
"E",
"-",
"potentialAxi",
"(",
"r",
",",
"pot",
")",
")",
"-",
"L",
"**",
"2.",
"/",
"r",
"**",
"2.",
")"
] | The J_r integrand | [
"The",
"J_r",
"integrand"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/actionAngle/actionAngleSpherical.py#L538-L540 | train | 27,931 |
jobovy/galpy | galpy/potential/FerrersPotential.py | FerrersPotential.rot | def rot(self, t=0., transposed=False):
"""2D Rotation matrix for non-zero pa or pattern speed
to goto the aligned coordinates
"""
rotmat = np.array(
[[np.cos(self._pa+self._omegab*t),np.sin(self._pa+self._omegab*t)],
[-np.sin(self._pa+self._omegab*t),np.cos(se... | python | def rot(self, t=0., transposed=False):
"""2D Rotation matrix for non-zero pa or pattern speed
to goto the aligned coordinates
"""
rotmat = np.array(
[[np.cos(self._pa+self._omegab*t),np.sin(self._pa+self._omegab*t)],
[-np.sin(self._pa+self._omegab*t),np.cos(se... | [
"def",
"rot",
"(",
"self",
",",
"t",
"=",
"0.",
",",
"transposed",
"=",
"False",
")",
":",
"rotmat",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"np",
".",
"cos",
"(",
"self",
".",
"_pa",
"+",
"self",
".",
"_omegab",
"*",
"t",
")",
",",
"np",
"... | 2D Rotation matrix for non-zero pa or pattern speed
to goto the aligned coordinates | [
"2D",
"Rotation",
"matrix",
"for",
"non",
"-",
"zero",
"pa",
"or",
"pattern",
"speed",
"to",
"goto",
"the",
"aligned",
"coordinates"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/FerrersPotential.py#L407-L417 | train | 27,932 |
jobovy/galpy | galpy/actionAngle/actionAngleVertical.py | _JzIntegrand | def _JzIntegrand(z,Ez,pot):
"""The J_z integrand"""
return nu.sqrt(2.*(Ez-potentialVertical(z,pot))) | python | def _JzIntegrand(z,Ez,pot):
"""The J_z integrand"""
return nu.sqrt(2.*(Ez-potentialVertical(z,pot))) | [
"def",
"_JzIntegrand",
"(",
"z",
",",
"Ez",
",",
"pot",
")",
":",
"return",
"nu",
".",
"sqrt",
"(",
"2.",
"*",
"(",
"Ez",
"-",
"potentialVertical",
"(",
"z",
",",
"pot",
")",
")",
")"
] | The J_z integrand | [
"The",
"J_z",
"integrand"
] | 9c5b9fe65d58835624dffe432be282060918ee08 | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/actionAngle/actionAngleVertical.py#L187-L189 | train | 27,933 |
ContinuumIO/menuinst | menuinst/win32.py | quoted | def quoted(s):
"""
quotes a string if necessary.
"""
# strip any existing quotes
s = s.strip(u'"')
# don't add quotes for minus or leading space
if s[0] in (u'-', u' '):
return s
if u' ' in s or u'/' in s:
return u'"%s"' % s
else:
return s | python | def quoted(s):
"""
quotes a string if necessary.
"""
# strip any existing quotes
s = s.strip(u'"')
# don't add quotes for minus or leading space
if s[0] in (u'-', u' '):
return s
if u' ' in s or u'/' in s:
return u'"%s"' % s
else:
return s | [
"def",
"quoted",
"(",
"s",
")",
":",
"# strip any existing quotes",
"s",
"=",
"s",
".",
"strip",
"(",
"u'\"'",
")",
"# don't add quotes for minus or leading space",
"if",
"s",
"[",
"0",
"]",
"in",
"(",
"u'-'",
",",
"u' '",
")",
":",
"return",
"s",
"if",
... | quotes a string if necessary. | [
"quotes",
"a",
"string",
"if",
"necessary",
"."
] | dae53065e9e82a3352b817cca5895a9b271ddfdb | https://github.com/ContinuumIO/menuinst/blob/dae53065e9e82a3352b817cca5895a9b271ddfdb/menuinst/win32.py#L106-L118 | train | 27,934 |
ContinuumIO/menuinst | menuinst/__init__.py | install | def install(path, remove=False, prefix=sys.prefix, recursing=False):
"""
install Menu and shortcuts
"""
# this sys.prefix is intentional. We want to reflect the state of the root installation.
if sys.platform == 'win32' and not exists(join(sys.prefix, '.nonadmin')):
if isUserAdmin():
... | python | def install(path, remove=False, prefix=sys.prefix, recursing=False):
"""
install Menu and shortcuts
"""
# this sys.prefix is intentional. We want to reflect the state of the root installation.
if sys.platform == 'win32' and not exists(join(sys.prefix, '.nonadmin')):
if isUserAdmin():
... | [
"def",
"install",
"(",
"path",
",",
"remove",
"=",
"False",
",",
"prefix",
"=",
"sys",
".",
"prefix",
",",
"recursing",
"=",
"False",
")",
":",
"# this sys.prefix is intentional. We want to reflect the state of the root installation.",
"if",
"sys",
".",
"platform",
... | install Menu and shortcuts | [
"install",
"Menu",
"and",
"shortcuts"
] | dae53065e9e82a3352b817cca5895a9b271ddfdb | https://github.com/ContinuumIO/menuinst/blob/dae53065e9e82a3352b817cca5895a9b271ddfdb/menuinst/__init__.py#L51-L76 | train | 27,935 |
ContinuumIO/menuinst | menuinst/linux.py | add_child | def add_child(parent, tag, text=None):
"""
Add a child element of specified tag type to parent.
The new child element is returned.
"""
elem = ET.SubElement(parent, tag)
if text is not None:
elem.text = text
return elem | python | def add_child(parent, tag, text=None):
"""
Add a child element of specified tag type to parent.
The new child element is returned.
"""
elem = ET.SubElement(parent, tag)
if text is not None:
elem.text = text
return elem | [
"def",
"add_child",
"(",
"parent",
",",
"tag",
",",
"text",
"=",
"None",
")",
":",
"elem",
"=",
"ET",
".",
"SubElement",
"(",
"parent",
",",
"tag",
")",
"if",
"text",
"is",
"not",
"None",
":",
"elem",
".",
"text",
"=",
"text",
"return",
"elem"
] | Add a child element of specified tag type to parent.
The new child element is returned. | [
"Add",
"a",
"child",
"element",
"of",
"specified",
"tag",
"type",
"to",
"parent",
".",
"The",
"new",
"child",
"element",
"is",
"returned",
"."
] | dae53065e9e82a3352b817cca5895a9b271ddfdb | https://github.com/ContinuumIO/menuinst/blob/dae53065e9e82a3352b817cca5895a9b271ddfdb/menuinst/linux.py#L61-L69 | train | 27,936 |
ContinuumIO/menuinst | menuinst/darwin.py | Application._writePlistInfo | def _writePlistInfo(self):
"""
Writes the Info.plist file in the Contests directory.
"""
pl = Plist(
CFBundleExecutable=self.executable,
CFBundleGetInfoString='%s-1.0.0' % self.name,
CFBundleIconFile=basename(self.icns),
CFBundleIdentifier=... | python | def _writePlistInfo(self):
"""
Writes the Info.plist file in the Contests directory.
"""
pl = Plist(
CFBundleExecutable=self.executable,
CFBundleGetInfoString='%s-1.0.0' % self.name,
CFBundleIconFile=basename(self.icns),
CFBundleIdentifier=... | [
"def",
"_writePlistInfo",
"(",
"self",
")",
":",
"pl",
"=",
"Plist",
"(",
"CFBundleExecutable",
"=",
"self",
".",
"executable",
",",
"CFBundleGetInfoString",
"=",
"'%s-1.0.0'",
"%",
"self",
".",
"name",
",",
"CFBundleIconFile",
"=",
"basename",
"(",
"self",
... | Writes the Info.plist file in the Contests directory. | [
"Writes",
"the",
"Info",
".",
"plist",
"file",
"in",
"the",
"Contests",
"directory",
"."
] | dae53065e9e82a3352b817cca5895a9b271ddfdb | https://github.com/ContinuumIO/menuinst/blob/dae53065e9e82a3352b817cca5895a9b271ddfdb/menuinst/darwin.py#L93-L106 | train | 27,937 |
SuperCowPowers/bat | bat/utils/file_tailer.py | FileTailer.readlines | def readlines(self, offset=0):
"""Open the file for reading and yield lines as they are added"""
try:
with open(self._filepath) as fp:
# For full read go through existing lines in file
if self._full_read:
fp.seek(offset)
... | python | def readlines(self, offset=0):
"""Open the file for reading and yield lines as they are added"""
try:
with open(self._filepath) as fp:
# For full read go through existing lines in file
if self._full_read:
fp.seek(offset)
... | [
"def",
"readlines",
"(",
"self",
",",
"offset",
"=",
"0",
")",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"_filepath",
")",
"as",
"fp",
":",
"# For full read go through existing lines in file",
"if",
"self",
".",
"_full_read",
":",
"fp",
".",
"seek... | Open the file for reading and yield lines as they are added | [
"Open",
"the",
"file",
"for",
"reading",
"and",
"yield",
"lines",
"as",
"they",
"are",
"added"
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/file_tailer.py#L27-L50 | train | 27,938 |
SuperCowPowers/bat | setup.py | get_files | def get_files(dir_name):
"""Simple directory walker"""
return [(os.path.join('.', d), [os.path.join(d, f) for f in files]) for d, _, files in os.walk(dir_name)] | python | def get_files(dir_name):
"""Simple directory walker"""
return [(os.path.join('.', d), [os.path.join(d, f) for f in files]) for d, _, files in os.walk(dir_name)] | [
"def",
"get_files",
"(",
"dir_name",
")",
":",
"return",
"[",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'.'",
",",
"d",
")",
",",
"[",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"f",
")",
"for",
"f",
"in",
"files",
"]",
")",
"for",
"d"... | Simple directory walker | [
"Simple",
"directory",
"walker"
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/setup.py#L19-L21 | train | 27,939 |
SuperCowPowers/bat | bat/bro_multi_log_reader.py | BroMultiLogReader.readrows | def readrows(self):
"""The readrows method reads simply 'combines' the rows of
multiple files OR gunzips the file and then reads the rows
"""
# For each file (may be just one) create a BroLogReader and use it
for self._filepath in self._files:
# Check if the file... | python | def readrows(self):
"""The readrows method reads simply 'combines' the rows of
multiple files OR gunzips the file and then reads the rows
"""
# For each file (may be just one) create a BroLogReader and use it
for self._filepath in self._files:
# Check if the file... | [
"def",
"readrows",
"(",
"self",
")",
":",
"# For each file (may be just one) create a BroLogReader and use it",
"for",
"self",
".",
"_filepath",
"in",
"self",
".",
"_files",
":",
"# Check if the file is zipped",
"tmp",
"=",
"None",
"if",
"self",
".",
"_filepath",
".",... | The readrows method reads simply 'combines' the rows of
multiple files OR gunzips the file and then reads the rows | [
"The",
"readrows",
"method",
"reads",
"simply",
"combines",
"the",
"rows",
"of",
"multiple",
"files",
"OR",
"gunzips",
"the",
"file",
"and",
"then",
"reads",
"the",
"rows"
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/bro_multi_log_reader.py#L30-L59 | train | 27,940 |
SuperCowPowers/bat | bat/utils/file_utils.py | most_recent | def most_recent(path, startswith=None, endswith=None):
"""Recursively inspect all files under a directory and return the most recent
Args:
path (str): the path of the directory to traverse
startswith (str): the file name start with (optional)
endswith (str): the file nam... | python | def most_recent(path, startswith=None, endswith=None):
"""Recursively inspect all files under a directory and return the most recent
Args:
path (str): the path of the directory to traverse
startswith (str): the file name start with (optional)
endswith (str): the file nam... | [
"def",
"most_recent",
"(",
"path",
",",
"startswith",
"=",
"None",
",",
"endswith",
"=",
"None",
")",
":",
"candidate_files",
"=",
"[",
"]",
"for",
"filename",
"in",
"all_files_in_directory",
"(",
"path",
")",
":",
"if",
"startswith",
"and",
"not",
"os",
... | Recursively inspect all files under a directory and return the most recent
Args:
path (str): the path of the directory to traverse
startswith (str): the file name start with (optional)
endswith (str): the file name ends with (optional)
Returns:
the most r... | [
"Recursively",
"inspect",
"all",
"files",
"under",
"a",
"directory",
"and",
"return",
"the",
"most",
"recent"
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/file_utils.py#L23-L43 | train | 27,941 |
SuperCowPowers/bat | examples/yara_matches.py | yara_match | def yara_match(file_path, rules):
"""Callback for a newly extracted file"""
print('New Extracted File: {:s}'.format(file_path))
print('Mathes:')
pprint(rules.match(file_path)) | python | def yara_match(file_path, rules):
"""Callback for a newly extracted file"""
print('New Extracted File: {:s}'.format(file_path))
print('Mathes:')
pprint(rules.match(file_path)) | [
"def",
"yara_match",
"(",
"file_path",
",",
"rules",
")",
":",
"print",
"(",
"'New Extracted File: {:s}'",
".",
"format",
"(",
"file_path",
")",
")",
"print",
"(",
"'Mathes:'",
")",
"pprint",
"(",
"rules",
".",
"match",
"(",
"file_path",
")",
")"
] | Callback for a newly extracted file | [
"Callback",
"for",
"a",
"newly",
"extracted",
"file"
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/examples/yara_matches.py#L23-L27 | train | 27,942 |
SuperCowPowers/bat | bat/live_simulator.py | LiveSimulator.readrows | def readrows(self):
"""Using the BroLogReader this method yields each row of the log file
replacing timestamps, looping and emitting rows based on EPS rate
"""
# Loop forever or until max_rows is reached
num_rows = 0
while True:
# Yield the rows from the ... | python | def readrows(self):
"""Using the BroLogReader this method yields each row of the log file
replacing timestamps, looping and emitting rows based on EPS rate
"""
# Loop forever or until max_rows is reached
num_rows = 0
while True:
# Yield the rows from the ... | [
"def",
"readrows",
"(",
"self",
")",
":",
"# Loop forever or until max_rows is reached",
"num_rows",
"=",
"0",
"while",
"True",
":",
"# Yield the rows from the internal reader",
"for",
"row",
"in",
"self",
".",
"log_reader",
".",
"readrows",
"(",
")",
":",
"yield",
... | Using the BroLogReader this method yields each row of the log file
replacing timestamps, looping and emitting rows based on EPS rate | [
"Using",
"the",
"BroLogReader",
"this",
"method",
"yields",
"each",
"row",
"of",
"the",
"log",
"file",
"replacing",
"timestamps",
"looping",
"and",
"emitting",
"rows",
"based",
"on",
"EPS",
"rate"
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/live_simulator.py#L48-L67 | train | 27,943 |
SuperCowPowers/bat | bat/bro_log_reader.py | BroLogReader._parse_bro_header | def _parse_bro_header(self, bro_log):
"""Parse the Bro log header section.
Format example:
#separator \x09
#set_separator ,
#empty_field (empty)
#unset_field -
#path httpheader_recon
#fields ts origin us... | python | def _parse_bro_header(self, bro_log):
"""Parse the Bro log header section.
Format example:
#separator \x09
#set_separator ,
#empty_field (empty)
#unset_field -
#path httpheader_recon
#fields ts origin us... | [
"def",
"_parse_bro_header",
"(",
"self",
",",
"bro_log",
")",
":",
"# Open the Bro logfile",
"with",
"open",
"(",
"bro_log",
",",
"'r'",
")",
"as",
"bro_file",
":",
"# Skip until you find the #fields line",
"_line",
"=",
"bro_file",
".",
"readline",
"(",
")",
"w... | Parse the Bro log header section.
Format example:
#separator \x09
#set_separator ,
#empty_field (empty)
#unset_field -
#path httpheader_recon
#fields ts origin useragent header_events_json
#types... | [
"Parse",
"the",
"Bro",
"log",
"header",
"section",
"."
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/bro_log_reader.py#L115-L152 | train | 27,944 |
SuperCowPowers/bat | bat/bro_log_reader.py | BroLogReader.make_dict | def make_dict(self, field_values):
''' Internal method that makes sure any dictionary elements
are properly cast into the correct types.
'''
data_dict = {}
for key, value, field_type, converter in zip(self.field_names, field_values, self.field_types, self.type_converters):
... | python | def make_dict(self, field_values):
''' Internal method that makes sure any dictionary elements
are properly cast into the correct types.
'''
data_dict = {}
for key, value, field_type, converter in zip(self.field_names, field_values, self.field_types, self.type_converters):
... | [
"def",
"make_dict",
"(",
"self",
",",
"field_values",
")",
":",
"data_dict",
"=",
"{",
"}",
"for",
"key",
",",
"value",
",",
"field_type",
",",
"converter",
"in",
"zip",
"(",
"self",
".",
"field_names",
",",
"field_values",
",",
"self",
".",
"field_types... | Internal method that makes sure any dictionary elements
are properly cast into the correct types. | [
"Internal",
"method",
"that",
"makes",
"sure",
"any",
"dictionary",
"elements",
"are",
"properly",
"cast",
"into",
"the",
"correct",
"types",
"."
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/bro_log_reader.py#L154-L169 | train | 27,945 |
SuperCowPowers/bat | bat/utils/net_utils.py | str_to_mac | def str_to_mac(mac_string):
"""Convert a readable string to a MAC address
Args:
mac_string (str): a readable string (e.g. '01:02:03:04:05:06')
Returns:
str: a MAC address in hex form
"""
sp = mac_string.split(':')
mac_string = ''.join(sp)
retu... | python | def str_to_mac(mac_string):
"""Convert a readable string to a MAC address
Args:
mac_string (str): a readable string (e.g. '01:02:03:04:05:06')
Returns:
str: a MAC address in hex form
"""
sp = mac_string.split(':')
mac_string = ''.join(sp)
retu... | [
"def",
"str_to_mac",
"(",
"mac_string",
")",
":",
"sp",
"=",
"mac_string",
".",
"split",
"(",
"':'",
")",
"mac_string",
"=",
"''",
".",
"join",
"(",
"sp",
")",
"return",
"binascii",
".",
"unhexlify",
"(",
"mac_string",
")"
] | Convert a readable string to a MAC address
Args:
mac_string (str): a readable string (e.g. '01:02:03:04:05:06')
Returns:
str: a MAC address in hex form | [
"Convert",
"a",
"readable",
"string",
"to",
"a",
"MAC",
"address"
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/net_utils.py#L22-L32 | train | 27,946 |
SuperCowPowers/bat | bat/utils/net_utils.py | inet_to_str | def inet_to_str(inet):
"""Convert inet object to a string
Args:
inet (inet struct): inet network address
Returns:
str: Printable/readable IP address
"""
# First try ipv4 and then ipv6
try:
return socket.inet_ntop(socket.AF_INET, inet)
except ValueErro... | python | def inet_to_str(inet):
"""Convert inet object to a string
Args:
inet (inet struct): inet network address
Returns:
str: Printable/readable IP address
"""
# First try ipv4 and then ipv6
try:
return socket.inet_ntop(socket.AF_INET, inet)
except ValueErro... | [
"def",
"inet_to_str",
"(",
"inet",
")",
":",
"# First try ipv4 and then ipv6",
"try",
":",
"return",
"socket",
".",
"inet_ntop",
"(",
"socket",
".",
"AF_INET",
",",
"inet",
")",
"except",
"ValueError",
":",
"return",
"socket",
".",
"inet_ntop",
"(",
"socket",
... | Convert inet object to a string
Args:
inet (inet struct): inet network address
Returns:
str: Printable/readable IP address | [
"Convert",
"inet",
"object",
"to",
"a",
"string"
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/net_utils.py#L35-L47 | train | 27,947 |
SuperCowPowers/bat | bat/utils/net_utils.py | str_to_inet | def str_to_inet(address):
"""Convert an a string IP address to a inet struct
Args:
address (str): String representation of address
Returns:
inet: Inet network address
"""
# First try ipv4 and then ipv6
try:
return socket.inet_pton(socket.AF_INET, address)... | python | def str_to_inet(address):
"""Convert an a string IP address to a inet struct
Args:
address (str): String representation of address
Returns:
inet: Inet network address
"""
# First try ipv4 and then ipv6
try:
return socket.inet_pton(socket.AF_INET, address)... | [
"def",
"str_to_inet",
"(",
"address",
")",
":",
"# First try ipv4 and then ipv6",
"try",
":",
"return",
"socket",
".",
"inet_pton",
"(",
"socket",
".",
"AF_INET",
",",
"address",
")",
"except",
"socket",
".",
"error",
":",
"return",
"socket",
".",
"inet_pton",... | Convert an a string IP address to a inet struct
Args:
address (str): String representation of address
Returns:
inet: Inet network address | [
"Convert",
"an",
"a",
"string",
"IP",
"address",
"to",
"a",
"inet",
"struct"
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/net_utils.py#L50-L62 | train | 27,948 |
SuperCowPowers/bat | bat/utils/signal_utils.py | signal_catcher | def signal_catcher(callback):
"""Catch signals and invoke the callback method"""
def _catch_exit_signal(sig_num, _frame):
print('Received signal {:d} invoking callback...'.format(sig_num))
callback()
signal.signal(signal.SIGINT, _catch_exit_signal)
signal.signal(signal.SIGQUIT, _catch_e... | python | def signal_catcher(callback):
"""Catch signals and invoke the callback method"""
def _catch_exit_signal(sig_num, _frame):
print('Received signal {:d} invoking callback...'.format(sig_num))
callback()
signal.signal(signal.SIGINT, _catch_exit_signal)
signal.signal(signal.SIGQUIT, _catch_e... | [
"def",
"signal_catcher",
"(",
"callback",
")",
":",
"def",
"_catch_exit_signal",
"(",
"sig_num",
",",
"_frame",
")",
":",
"print",
"(",
"'Received signal {:d} invoking callback...'",
".",
"format",
"(",
"sig_num",
")",
")",
"callback",
"(",
")",
"signal",
".",
... | Catch signals and invoke the callback method | [
"Catch",
"signals",
"and",
"invoke",
"the",
"callback",
"method"
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/signal_utils.py#L11-L20 | train | 27,949 |
SuperCowPowers/bat | examples/anomaly_detection.py | entropy | def entropy(string):
"""Compute entropy on the string"""
p, lns = Counter(string), float(len(string))
return -sum(count/lns * math.log(count/lns, 2) for count in p.values()) | python | def entropy(string):
"""Compute entropy on the string"""
p, lns = Counter(string), float(len(string))
return -sum(count/lns * math.log(count/lns, 2) for count in p.values()) | [
"def",
"entropy",
"(",
"string",
")",
":",
"p",
",",
"lns",
"=",
"Counter",
"(",
"string",
")",
",",
"float",
"(",
"len",
"(",
"string",
")",
")",
"return",
"-",
"sum",
"(",
"count",
"/",
"lns",
"*",
"math",
".",
"log",
"(",
"count",
"/",
"lns"... | Compute entropy on the string | [
"Compute",
"entropy",
"on",
"the",
"string"
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/examples/anomaly_detection.py#L18-L21 | train | 27,950 |
SuperCowPowers/bat | bat/utils/dir_watcher.py | DirWatcher.on_any_event | def on_any_event(self, event):
"""File created or modified"""
if os.path.isfile(event.src_path):
self.callback(event.src_path, **self.kwargs) | python | def on_any_event(self, event):
"""File created or modified"""
if os.path.isfile(event.src_path):
self.callback(event.src_path, **self.kwargs) | [
"def",
"on_any_event",
"(",
"self",
",",
"event",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"event",
".",
"src_path",
")",
":",
"self",
".",
"callback",
"(",
"event",
".",
"src_path",
",",
"*",
"*",
"self",
".",
"kwargs",
")"
] | File created or modified | [
"File",
"created",
"or",
"modified"
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/dir_watcher.py#L27-L30 | train | 27,951 |
SuperCowPowers/bat | bat/utils/reverse_dns.py | ReverseDNS.lookup | def lookup(self, ip_address):
"""Try to do a reverse dns lookup on the given ip_address"""
# Is this already in our cache
if self.ip_lookup_cache.get(ip_address):
domain = self.ip_lookup_cache.get(ip_address)
# Is the ip_address local or special
elif not self.lookup... | python | def lookup(self, ip_address):
"""Try to do a reverse dns lookup on the given ip_address"""
# Is this already in our cache
if self.ip_lookup_cache.get(ip_address):
domain = self.ip_lookup_cache.get(ip_address)
# Is the ip_address local or special
elif not self.lookup... | [
"def",
"lookup",
"(",
"self",
",",
"ip_address",
")",
":",
"# Is this already in our cache",
"if",
"self",
".",
"ip_lookup_cache",
".",
"get",
"(",
"ip_address",
")",
":",
"domain",
"=",
"self",
".",
"ip_lookup_cache",
".",
"get",
"(",
"ip_address",
")",
"# ... | Try to do a reverse dns lookup on the given ip_address | [
"Try",
"to",
"do",
"a",
"reverse",
"dns",
"lookup",
"on",
"the",
"given",
"ip_address"
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/reverse_dns.py#L17-L38 | train | 27,952 |
SuperCowPowers/bat | bat/dataframe_cache.py | DataFrameCache.add_rows | def add_rows(self, list_of_rows):
"""Add a list of rows to the DataFrameCache class"""
for row in list_of_rows:
self.row_deque.append(row)
self.time_deque.append(time.time())
# Update the data structure
self.update() | python | def add_rows(self, list_of_rows):
"""Add a list of rows to the DataFrameCache class"""
for row in list_of_rows:
self.row_deque.append(row)
self.time_deque.append(time.time())
# Update the data structure
self.update() | [
"def",
"add_rows",
"(",
"self",
",",
"list_of_rows",
")",
":",
"for",
"row",
"in",
"list_of_rows",
":",
"self",
".",
"row_deque",
".",
"append",
"(",
"row",
")",
"self",
".",
"time_deque",
".",
"append",
"(",
"time",
".",
"time",
"(",
")",
")",
"# Up... | Add a list of rows to the DataFrameCache class | [
"Add",
"a",
"list",
"of",
"rows",
"to",
"the",
"DataFrameCache",
"class"
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/dataframe_cache.py#L27-L33 | train | 27,953 |
SuperCowPowers/bat | bat/dataframe_cache.py | DataFrameCache.update | def update(self):
"""Update the deque, removing rows based on time"""
expire_time = time.time() - self.max_time
while self.row_deque and self.time_deque[0] < expire_time:
self.row_deque.popleft() # FIFO
self.time_deque.popleft() | python | def update(self):
"""Update the deque, removing rows based on time"""
expire_time = time.time() - self.max_time
while self.row_deque and self.time_deque[0] < expire_time:
self.row_deque.popleft() # FIFO
self.time_deque.popleft() | [
"def",
"update",
"(",
"self",
")",
":",
"expire_time",
"=",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"max_time",
"while",
"self",
".",
"row_deque",
"and",
"self",
".",
"time_deque",
"[",
"0",
"]",
"<",
"expire_time",
":",
"self",
".",
"row_de... | Update the deque, removing rows based on time | [
"Update",
"the",
"deque",
"removing",
"rows",
"based",
"on",
"time"
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/dataframe_cache.py#L41-L46 | train | 27,954 |
SuperCowPowers/bat | bat/utils/cache.py | Cache._compress | def _compress(self):
"""Internal method to compress the cache. This method will
expire any old items in the cache, making the cache smaller"""
# Don't compress too often
now = time.time()
if self._last_compression + self._compression_timer < now:
self._last_compre... | python | def _compress(self):
"""Internal method to compress the cache. This method will
expire any old items in the cache, making the cache smaller"""
# Don't compress too often
now = time.time()
if self._last_compression + self._compression_timer < now:
self._last_compre... | [
"def",
"_compress",
"(",
"self",
")",
":",
"# Don't compress too often",
"now",
"=",
"time",
".",
"time",
"(",
")",
"if",
"self",
".",
"_last_compression",
"+",
"self",
".",
"_compression_timer",
"<",
"now",
":",
"self",
".",
"_last_compression",
"=",
"now",... | Internal method to compress the cache. This method will
expire any old items in the cache, making the cache smaller | [
"Internal",
"method",
"to",
"compress",
"the",
"cache",
".",
"This",
"method",
"will",
"expire",
"any",
"old",
"items",
"in",
"the",
"cache",
"making",
"the",
"cache",
"smaller"
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/cache.py#L77-L86 | train | 27,955 |
SuperCowPowers/bat | examples/risky_dns.py | save_vtq | def save_vtq():
"""Exit on Signal"""
global vtq
print('Saving VirusTotal Query Cache...')
pickle.dump(vtq, open('vtq.pkl', 'wb'), protocol=pickle.HIGHEST_PROTOCOL)
sys.exit() | python | def save_vtq():
"""Exit on Signal"""
global vtq
print('Saving VirusTotal Query Cache...')
pickle.dump(vtq, open('vtq.pkl', 'wb'), protocol=pickle.HIGHEST_PROTOCOL)
sys.exit() | [
"def",
"save_vtq",
"(",
")",
":",
"global",
"vtq",
"print",
"(",
"'Saving VirusTotal Query Cache...'",
")",
"pickle",
".",
"dump",
"(",
"vtq",
",",
"open",
"(",
"'vtq.pkl'",
",",
"'wb'",
")",
",",
"protocol",
"=",
"pickle",
".",
"HIGHEST_PROTOCOL",
")",
"s... | Exit on Signal | [
"Exit",
"on",
"Signal"
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/examples/risky_dns.py#L20-L26 | train | 27,956 |
SuperCowPowers/bat | bat/utils/dummy_encoder.py | DummyEncoder.fit_transform | def fit_transform(self, df):
"""Fit method for the DummyEncoder"""
self.index_ = df.index
self.columns_ = df.columns
self.cat_columns_ = df.select_dtypes(include=['category']).columns
self.non_cat_columns_ = df.columns.drop(self.cat_columns_)
self.cat_map_ = {col: df[col]... | python | def fit_transform(self, df):
"""Fit method for the DummyEncoder"""
self.index_ = df.index
self.columns_ = df.columns
self.cat_columns_ = df.select_dtypes(include=['category']).columns
self.non_cat_columns_ = df.columns.drop(self.cat_columns_)
self.cat_map_ = {col: df[col]... | [
"def",
"fit_transform",
"(",
"self",
",",
"df",
")",
":",
"self",
".",
"index_",
"=",
"df",
".",
"index",
"self",
".",
"columns_",
"=",
"df",
".",
"columns",
"self",
".",
"cat_columns_",
"=",
"df",
".",
"select_dtypes",
"(",
"include",
"=",
"[",
"'ca... | Fit method for the DummyEncoder | [
"Fit",
"method",
"for",
"the",
"DummyEncoder"
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/dummy_encoder.py#L24-L44 | train | 27,957 |
SuperCowPowers/bat | bat/log_to_parquet.py | _make_df | def _make_df(rows):
"""Internal Method to make and clean the dataframe in preparation for sending to Parquet"""
# Make DataFrame
df = pd.DataFrame(rows).set_index('ts')
# TimeDelta Support: https://issues.apache.org/jira/browse/ARROW-835
for column in df.columns:
if(df[column].dtype == 'ti... | python | def _make_df(rows):
"""Internal Method to make and clean the dataframe in preparation for sending to Parquet"""
# Make DataFrame
df = pd.DataFrame(rows).set_index('ts')
# TimeDelta Support: https://issues.apache.org/jira/browse/ARROW-835
for column in df.columns:
if(df[column].dtype == 'ti... | [
"def",
"_make_df",
"(",
"rows",
")",
":",
"# Make DataFrame",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"rows",
")",
".",
"set_index",
"(",
"'ts'",
")",
"# TimeDelta Support: https://issues.apache.org/jira/browse/ARROW-835",
"for",
"column",
"in",
"df",
".",
"column... | Internal Method to make and clean the dataframe in preparation for sending to Parquet | [
"Internal",
"Method",
"to",
"make",
"and",
"clean",
"the",
"dataframe",
"in",
"preparation",
"for",
"sending",
"to",
"Parquet"
] | 069e6bc52843dc07760969c531cc442ca7da8e0c | https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/log_to_parquet.py#L17-L28 | train | 27,958 |
mozilla-releng/scriptworker | scriptworker/context.py | Context.create_queue | def create_queue(self, credentials):
"""Create a taskcluster queue.
Args:
credentials (dict): taskcluster credentials.
"""
if credentials:
session = self.session or aiohttp.ClientSession(loop=self.event_loop)
return Queue(
options={
... | python | def create_queue(self, credentials):
"""Create a taskcluster queue.
Args:
credentials (dict): taskcluster credentials.
"""
if credentials:
session = self.session or aiohttp.ClientSession(loop=self.event_loop)
return Queue(
options={
... | [
"def",
"create_queue",
"(",
"self",
",",
"credentials",
")",
":",
"if",
"credentials",
":",
"session",
"=",
"self",
".",
"session",
"or",
"aiohttp",
".",
"ClientSession",
"(",
"loop",
"=",
"self",
".",
"event_loop",
")",
"return",
"Queue",
"(",
"options",
... | Create a taskcluster queue.
Args:
credentials (dict): taskcluster credentials. | [
"Create",
"a",
"taskcluster",
"queue",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/context.py#L111-L126 | train | 27,959 |
mozilla-releng/scriptworker | scriptworker/context.py | Context.write_json | def write_json(self, path, contents, message):
"""Write json to disk.
Args:
path (str): the path to write to
contents (dict): the contents of the json blob
message (str): the message to log
"""
log.debug(message.format(path=path))
makedirs(os... | python | def write_json(self, path, contents, message):
"""Write json to disk.
Args:
path (str): the path to write to
contents (dict): the contents of the json blob
message (str): the message to log
"""
log.debug(message.format(path=path))
makedirs(os... | [
"def",
"write_json",
"(",
"self",
",",
"path",
",",
"contents",
",",
"message",
")",
":",
"log",
".",
"debug",
"(",
"message",
".",
"format",
"(",
"path",
"=",
"path",
")",
")",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
... | Write json to disk.
Args:
path (str): the path to write to
contents (dict): the contents of the json blob
message (str): the message to log | [
"Write",
"json",
"to",
"disk",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/context.py#L164-L176 | train | 27,960 |
mozilla-releng/scriptworker | scriptworker/context.py | Context.populate_projects | async def populate_projects(self, force=False):
"""Download the ``projects.yml`` file and populate ``self.projects``.
This only sets it once, unless ``force`` is set.
Args:
force (bool, optional): Re-run the download, even if ``self.projects``
is already defined. De... | python | async def populate_projects(self, force=False):
"""Download the ``projects.yml`` file and populate ``self.projects``.
This only sets it once, unless ``force`` is set.
Args:
force (bool, optional): Re-run the download, even if ``self.projects``
is already defined. De... | [
"async",
"def",
"populate_projects",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"force",
"or",
"not",
"self",
".",
"projects",
":",
"with",
"tempfile",
".",
"TemporaryDirectory",
"(",
")",
"as",
"tmpdirname",
":",
"self",
".",
"projects",
"... | Download the ``projects.yml`` file and populate ``self.projects``.
This only sets it once, unless ``force`` is set.
Args:
force (bool, optional): Re-run the download, even if ``self.projects``
is already defined. Defaults to False. | [
"Download",
"the",
"projects",
".",
"yml",
"file",
"and",
"populate",
"self",
".",
"projects",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/context.py#L208-L223 | train | 27,961 |
mozilla-releng/scriptworker | scriptworker/worker.py | do_run_task | async def do_run_task(context, run_cancellable, to_cancellable_process):
"""Run the task logic.
Returns the integer status of the task.
args:
context (scriptworker.context.Context): the scriptworker context.
run_cancellable (typing.Callable): wraps future such that it'll cancel upon worker... | python | async def do_run_task(context, run_cancellable, to_cancellable_process):
"""Run the task logic.
Returns the integer status of the task.
args:
context (scriptworker.context.Context): the scriptworker context.
run_cancellable (typing.Callable): wraps future such that it'll cancel upon worker... | [
"async",
"def",
"do_run_task",
"(",
"context",
",",
"run_cancellable",
",",
"to_cancellable_process",
")",
":",
"status",
"=",
"0",
"try",
":",
"if",
"context",
".",
"config",
"[",
"'verify_chain_of_trust'",
"]",
":",
"chain",
"=",
"ChainOfTrust",
"(",
"contex... | Run the task logic.
Returns the integer status of the task.
args:
context (scriptworker.context.Context): the scriptworker context.
run_cancellable (typing.Callable): wraps future such that it'll cancel upon worker shutdown
to_cancellable_process (typing.Callable): wraps ``TaskProcess`... | [
"Run",
"the",
"task",
"logic",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/worker.py#L32-L66 | train | 27,962 |
mozilla-releng/scriptworker | scriptworker/worker.py | do_upload | async def do_upload(context, files):
"""Upload artifacts and return status.
Returns the integer status of the upload.
args:
context (scriptworker.context.Context): the scriptworker context.
files (list of str): list of files to be uploaded as artifacts
Raises:
Exception: on un... | python | async def do_upload(context, files):
"""Upload artifacts and return status.
Returns the integer status of the upload.
args:
context (scriptworker.context.Context): the scriptworker context.
files (list of str): list of files to be uploaded as artifacts
Raises:
Exception: on un... | [
"async",
"def",
"do_upload",
"(",
"context",
",",
"files",
")",
":",
"status",
"=",
"0",
"try",
":",
"await",
"upload_artifacts",
"(",
"context",
",",
"files",
")",
"except",
"ScriptWorkerException",
"as",
"e",
":",
"status",
"=",
"worst_level",
"(",
"stat... | Upload artifacts and return status.
Returns the integer status of the upload.
args:
context (scriptworker.context.Context): the scriptworker context.
files (list of str): list of files to be uploaded as artifacts
Raises:
Exception: on unexpected exception.
Returns:
in... | [
"Upload",
"artifacts",
"and",
"return",
"status",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/worker.py#L70-L98 | train | 27,963 |
mozilla-releng/scriptworker | scriptworker/worker.py | run_tasks | async def run_tasks(context):
"""Run any tasks returned by claimWork.
Returns the integer status of the task that was run, or None if no task was
run.
args:
context (scriptworker.context.Context): the scriptworker context.
Raises:
Exception: on unexpected exception.
Returns:
... | python | async def run_tasks(context):
"""Run any tasks returned by claimWork.
Returns the integer status of the task that was run, or None if no task was
run.
args:
context (scriptworker.context.Context): the scriptworker context.
Raises:
Exception: on unexpected exception.
Returns:
... | [
"async",
"def",
"run_tasks",
"(",
"context",
")",
":",
"running_tasks",
"=",
"RunTasks",
"(",
")",
"context",
".",
"running_tasks",
"=",
"running_tasks",
"status",
"=",
"await",
"running_tasks",
".",
"invoke",
"(",
"context",
")",
"context",
".",
"running_task... | Run any tasks returned by claimWork.
Returns the integer status of the task that was run, or None if no task was
run.
args:
context (scriptworker.context.Context): the scriptworker context.
Raises:
Exception: on unexpected exception.
Returns:
int: exit status
None... | [
"Run",
"any",
"tasks",
"returned",
"by",
"claimWork",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/worker.py#L180-L201 | train | 27,964 |
mozilla-releng/scriptworker | scriptworker/worker.py | async_main | async def async_main(context, credentials):
"""Set up and run tasks for this iteration.
http://docs.taskcluster.net/queue/worker-interaction/
Args:
context (scriptworker.context.Context): the scriptworker context.
"""
conn = aiohttp.TCPConnector(limit=context.config['aiohttp_max_connection... | python | async def async_main(context, credentials):
"""Set up and run tasks for this iteration.
http://docs.taskcluster.net/queue/worker-interaction/
Args:
context (scriptworker.context.Context): the scriptworker context.
"""
conn = aiohttp.TCPConnector(limit=context.config['aiohttp_max_connection... | [
"async",
"def",
"async_main",
"(",
"context",
",",
"credentials",
")",
":",
"conn",
"=",
"aiohttp",
".",
"TCPConnector",
"(",
"limit",
"=",
"context",
".",
"config",
"[",
"'aiohttp_max_connections'",
"]",
")",
"async",
"with",
"aiohttp",
".",
"ClientSession",
... | Set up and run tasks for this iteration.
http://docs.taskcluster.net/queue/worker-interaction/
Args:
context (scriptworker.context.Context): the scriptworker context. | [
"Set",
"up",
"and",
"run",
"tasks",
"for",
"this",
"iteration",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/worker.py#L205-L217 | train | 27,965 |
mozilla-releng/scriptworker | scriptworker/worker.py | RunTasks.invoke | async def invoke(self, context):
"""Claims and processes Taskcluster work.
Args:
context (scriptworker.context.Context): context of worker
Returns: status code of build
"""
try:
# Note: claim_work(...) might not be safely interruptible! See
... | python | async def invoke(self, context):
"""Claims and processes Taskcluster work.
Args:
context (scriptworker.context.Context): context of worker
Returns: status code of build
"""
try:
# Note: claim_work(...) might not be safely interruptible! See
... | [
"async",
"def",
"invoke",
"(",
"self",
",",
"context",
")",
":",
"try",
":",
"# Note: claim_work(...) might not be safely interruptible! See",
"# https://bugzilla.mozilla.org/show_bug.cgi?id=1524069",
"tasks",
"=",
"await",
"self",
".",
"_run_cancellable",
"(",
"claim_work",
... | Claims and processes Taskcluster work.
Args:
context (scriptworker.context.Context): context of worker
Returns: status code of build | [
"Claims",
"and",
"processes",
"Taskcluster",
"work",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/worker.py#L110-L151 | train | 27,966 |
mozilla-releng/scriptworker | scriptworker/worker.py | RunTasks.cancel | async def cancel(self):
"""Cancel current work."""
self.is_cancelled = True
if self.future is not None:
self.future.cancel()
if self.task_process is not None:
log.warning("Worker is shutting down, but a task is running. Terminating task")
await self.ta... | python | async def cancel(self):
"""Cancel current work."""
self.is_cancelled = True
if self.future is not None:
self.future.cancel()
if self.task_process is not None:
log.warning("Worker is shutting down, but a task is running. Terminating task")
await self.ta... | [
"async",
"def",
"cancel",
"(",
"self",
")",
":",
"self",
".",
"is_cancelled",
"=",
"True",
"if",
"self",
".",
"future",
"is",
"not",
"None",
":",
"self",
".",
"future",
".",
"cancel",
"(",
")",
"if",
"self",
".",
"task_process",
"is",
"not",
"None",
... | Cancel current work. | [
"Cancel",
"current",
"work",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/worker.py#L169-L176 | train | 27,967 |
mozilla-releng/scriptworker | scriptworker/utils.py | request | async def request(context, url, timeout=60, method='get', good=(200, ),
retry=tuple(range(500, 512)), return_type='text', **kwargs):
"""Async aiohttp request wrapper.
Args:
context (scriptworker.context.Context): the scriptworker context.
url (str): the url to request
... | python | async def request(context, url, timeout=60, method='get', good=(200, ),
retry=tuple(range(500, 512)), return_type='text', **kwargs):
"""Async aiohttp request wrapper.
Args:
context (scriptworker.context.Context): the scriptworker context.
url (str): the url to request
... | [
"async",
"def",
"request",
"(",
"context",
",",
"url",
",",
"timeout",
"=",
"60",
",",
"method",
"=",
"'get'",
",",
"good",
"=",
"(",
"200",
",",
")",
",",
"retry",
"=",
"tuple",
"(",
"range",
"(",
"500",
",",
"512",
")",
")",
",",
"return_type",... | Async aiohttp request wrapper.
Args:
context (scriptworker.context.Context): the scriptworker context.
url (str): the url to request
timeout (int, optional): timeout after this many seconds. Default is 60.
method (str, optional): The request method to use. Default is 'get'.
... | [
"Async",
"aiohttp",
"request",
"wrapper",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L36-L80 | train | 27,968 |
mozilla-releng/scriptworker | scriptworker/utils.py | retry_request | async def retry_request(*args, retry_exceptions=(asyncio.TimeoutError,
ScriptWorkerRetryException),
retry_async_kwargs=None, **kwargs):
"""Retry the ``request`` function.
Args:
*args: the args to send to request() through retry_as... | python | async def retry_request(*args, retry_exceptions=(asyncio.TimeoutError,
ScriptWorkerRetryException),
retry_async_kwargs=None, **kwargs):
"""Retry the ``request`` function.
Args:
*args: the args to send to request() through retry_as... | [
"async",
"def",
"retry_request",
"(",
"*",
"args",
",",
"retry_exceptions",
"=",
"(",
"asyncio",
".",
"TimeoutError",
",",
"ScriptWorkerRetryException",
")",
",",
"retry_async_kwargs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"retry_async_kwargs",
"=",
... | Retry the ``request`` function.
Args:
*args: the args to send to request() through retry_async().
retry_exceptions (list, optional): the exceptions to retry on.
Defaults to (ScriptWorkerRetryException, ).
retry_async_kwargs (dict, optional): the kwargs for retry_async.
... | [
"Retry",
"the",
"request",
"function",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L84-L103 | train | 27,969 |
mozilla-releng/scriptworker | scriptworker/utils.py | makedirs | def makedirs(path):
"""Equivalent to mkdir -p.
Args:
path (str): the path to mkdir -p
Raises:
ScriptWorkerException: if path exists already and the realpath is not a dir.
"""
if path:
if not os.path.exists(path):
log.debug("makedirs({})".format(path))
... | python | def makedirs(path):
"""Equivalent to mkdir -p.
Args:
path (str): the path to mkdir -p
Raises:
ScriptWorkerException: if path exists already and the realpath is not a dir.
"""
if path:
if not os.path.exists(path):
log.debug("makedirs({})".format(path))
... | [
"def",
"makedirs",
"(",
"path",
")",
":",
"if",
"path",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"log",
".",
"debug",
"(",
"\"makedirs({})\"",
".",
"format",
"(",
"path",
")",
")",
"os",
".",
"makedirs",
"(",
"pa... | Equivalent to mkdir -p.
Args:
path (str): the path to mkdir -p
Raises:
ScriptWorkerException: if path exists already and the realpath is not a dir. | [
"Equivalent",
"to",
"mkdir",
"-",
"p",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L141-L160 | train | 27,970 |
mozilla-releng/scriptworker | scriptworker/utils.py | rm | def rm(path):
"""Equivalent to rm -rf.
Make sure ``path`` doesn't exist after this call. If it's a dir,
shutil.rmtree(); if it's a file, os.remove(); if it doesn't exist,
ignore.
Args:
path (str): the path to nuke.
"""
if path and os.path.exists(path):
if os.path.isdir(pa... | python | def rm(path):
"""Equivalent to rm -rf.
Make sure ``path`` doesn't exist after this call. If it's a dir,
shutil.rmtree(); if it's a file, os.remove(); if it doesn't exist,
ignore.
Args:
path (str): the path to nuke.
"""
if path and os.path.exists(path):
if os.path.isdir(pa... | [
"def",
"rm",
"(",
"path",
")",
":",
"if",
"path",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"shutil",
".",
"rmtree",
"(",
"path",
")",
"else",
":",
"os",
".",... | Equivalent to rm -rf.
Make sure ``path`` doesn't exist after this call. If it's a dir,
shutil.rmtree(); if it's a file, os.remove(); if it doesn't exist,
ignore.
Args:
path (str): the path to nuke. | [
"Equivalent",
"to",
"rm",
"-",
"rf",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L164-L179 | train | 27,971 |
mozilla-releng/scriptworker | scriptworker/utils.py | cleanup | def cleanup(context):
"""Clean up the work_dir and artifact_dir between task runs, then recreate.
Args:
context (scriptworker.context.Context): the scriptworker context.
"""
for name in 'work_dir', 'artifact_dir', 'task_log_dir':
path = context.config[name]
if os.path.exists(pa... | python | def cleanup(context):
"""Clean up the work_dir and artifact_dir between task runs, then recreate.
Args:
context (scriptworker.context.Context): the scriptworker context.
"""
for name in 'work_dir', 'artifact_dir', 'task_log_dir':
path = context.config[name]
if os.path.exists(pa... | [
"def",
"cleanup",
"(",
"context",
")",
":",
"for",
"name",
"in",
"'work_dir'",
",",
"'artifact_dir'",
",",
"'task_log_dir'",
":",
"path",
"=",
"context",
".",
"config",
"[",
"name",
"]",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
... | Clean up the work_dir and artifact_dir between task runs, then recreate.
Args:
context (scriptworker.context.Context): the scriptworker context. | [
"Clean",
"up",
"the",
"work_dir",
"and",
"artifact_dir",
"between",
"task",
"runs",
"then",
"recreate",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L183-L195 | train | 27,972 |
mozilla-releng/scriptworker | scriptworker/utils.py | calculate_sleep_time | def calculate_sleep_time(attempt, delay_factor=5.0, randomization_factor=.5, max_delay=120):
"""Calculate the sleep time between retries, in seconds.
Based off of `taskcluster.utils.calculateSleepTime`, but with kwargs instead
of constant `delay_factor`/`randomization_factor`/`max_delay`. The taskcluster
... | python | def calculate_sleep_time(attempt, delay_factor=5.0, randomization_factor=.5, max_delay=120):
"""Calculate the sleep time between retries, in seconds.
Based off of `taskcluster.utils.calculateSleepTime`, but with kwargs instead
of constant `delay_factor`/`randomization_factor`/`max_delay`. The taskcluster
... | [
"def",
"calculate_sleep_time",
"(",
"attempt",
",",
"delay_factor",
"=",
"5.0",
",",
"randomization_factor",
"=",
".5",
",",
"max_delay",
"=",
"120",
")",
":",
"if",
"attempt",
"<=",
"0",
":",
"return",
"0",
"# We subtract one to get exponents: 1, 2, 3, 4, 5, ..",
... | Calculate the sleep time between retries, in seconds.
Based off of `taskcluster.utils.calculateSleepTime`, but with kwargs instead
of constant `delay_factor`/`randomization_factor`/`max_delay`. The taskcluster
function generally slept for less than a second, which didn't always get
past server issues.... | [
"Calculate",
"the",
"sleep",
"time",
"between",
"retries",
"in",
"seconds",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L199-L226 | train | 27,973 |
mozilla-releng/scriptworker | scriptworker/utils.py | retry_async | async def retry_async(func, attempts=5, sleeptime_callback=calculate_sleep_time,
retry_exceptions=Exception, args=(), kwargs=None,
sleeptime_kwargs=None):
"""Retry ``func``, where ``func`` is an awaitable.
Args:
func (function): an awaitable function.
... | python | async def retry_async(func, attempts=5, sleeptime_callback=calculate_sleep_time,
retry_exceptions=Exception, args=(), kwargs=None,
sleeptime_kwargs=None):
"""Retry ``func``, where ``func`` is an awaitable.
Args:
func (function): an awaitable function.
... | [
"async",
"def",
"retry_async",
"(",
"func",
",",
"attempts",
"=",
"5",
",",
"sleeptime_callback",
"=",
"calculate_sleep_time",
",",
"retry_exceptions",
"=",
"Exception",
",",
"args",
"=",
"(",
")",
",",
"kwargs",
"=",
"None",
",",
"sleeptime_kwargs",
"=",
"N... | Retry ``func``, where ``func`` is an awaitable.
Args:
func (function): an awaitable function.
attempts (int, optional): the number of attempts to make. Default is 5.
sleeptime_callback (function, optional): the function to use to determine
how long to sleep after each attempt. ... | [
"Retry",
"func",
"where",
"func",
"is",
"an",
"awaitable",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L230-L270 | train | 27,974 |
mozilla-releng/scriptworker | scriptworker/utils.py | create_temp_creds | def create_temp_creds(client_id, access_token, start=None, expires=None,
scopes=None, name=None):
"""Request temp TC creds with our permanent creds.
Args:
client_id (str): the taskcluster client_id to use
access_token (str): the taskcluster access_token to use
star... | python | def create_temp_creds(client_id, access_token, start=None, expires=None,
scopes=None, name=None):
"""Request temp TC creds with our permanent creds.
Args:
client_id (str): the taskcluster client_id to use
access_token (str): the taskcluster access_token to use
star... | [
"def",
"create_temp_creds",
"(",
"client_id",
",",
"access_token",
",",
"start",
"=",
"None",
",",
"expires",
"=",
"None",
",",
"scopes",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"now",
"=",
"arrow",
".",
"utcnow",
"(",
")",
".",
"replace",
"... | Request temp TC creds with our permanent creds.
Args:
client_id (str): the taskcluster client_id to use
access_token (str): the taskcluster access_token to use
start (str, optional): the datetime string when the credentials will
start to be valid. Defaults to 10 minutes ago, fo... | [
"Request",
"temp",
"TC",
"creds",
"with",
"our",
"permanent",
"creds",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L274-L304 | train | 27,975 |
mozilla-releng/scriptworker | scriptworker/utils.py | filepaths_in_dir | def filepaths_in_dir(path):
"""Find all files in a directory, and return the relative paths to those files.
Args:
path (str): the directory path to walk
Returns:
list: the list of relative paths to all files inside of ``path`` or its
subdirectories.
"""
filepaths = []
... | python | def filepaths_in_dir(path):
"""Find all files in a directory, and return the relative paths to those files.
Args:
path (str): the directory path to walk
Returns:
list: the list of relative paths to all files inside of ``path`` or its
subdirectories.
"""
filepaths = []
... | [
"def",
"filepaths_in_dir",
"(",
"path",
")",
":",
"filepaths",
"=",
"[",
"]",
"for",
"root",
",",
"directories",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"filename",
"in",
"filenames",
":",
"filepath",
"=",
"os",
".",
... | Find all files in a directory, and return the relative paths to those files.
Args:
path (str): the directory path to walk
Returns:
list: the list of relative paths to all files inside of ``path`` or its
subdirectories. | [
"Find",
"all",
"files",
"in",
"a",
"directory",
"and",
"return",
"the",
"relative",
"paths",
"to",
"those",
"files",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L372-L389 | train | 27,976 |
mozilla-releng/scriptworker | scriptworker/utils.py | get_hash | def get_hash(path, hash_alg="sha256"):
"""Get the hash of the file at ``path``.
I'd love to make this async, but evidently file i/o is always ready
Args:
path (str): the path to the file to hash.
hash_alg (str, optional): the algorithm to use. Defaults to 'sha256'.
Returns:
s... | python | def get_hash(path, hash_alg="sha256"):
"""Get the hash of the file at ``path``.
I'd love to make this async, but evidently file i/o is always ready
Args:
path (str): the path to the file to hash.
hash_alg (str, optional): the algorithm to use. Defaults to 'sha256'.
Returns:
s... | [
"def",
"get_hash",
"(",
"path",
",",
"hash_alg",
"=",
"\"sha256\"",
")",
":",
"h",
"=",
"hashlib",
".",
"new",
"(",
"hash_alg",
")",
"with",
"open",
"(",
"path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"iter",
"(",
"functools",
".... | Get the hash of the file at ``path``.
I'd love to make this async, but evidently file i/o is always ready
Args:
path (str): the path to the file to hash.
hash_alg (str, optional): the algorithm to use. Defaults to 'sha256'.
Returns:
str: the hexdigest of the hash. | [
"Get",
"the",
"hash",
"of",
"the",
"file",
"at",
"path",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L393-L410 | train | 27,977 |
mozilla-releng/scriptworker | scriptworker/utils.py | load_json_or_yaml | def load_json_or_yaml(string, is_path=False, file_type='json',
exception=ScriptWorkerTaskException,
message="Failed to load %(file_type)s: %(exc)s"):
"""Load json or yaml from a filehandle or string, and raise a custom exception on failure.
Args:
string (str)... | python | def load_json_or_yaml(string, is_path=False, file_type='json',
exception=ScriptWorkerTaskException,
message="Failed to load %(file_type)s: %(exc)s"):
"""Load json or yaml from a filehandle or string, and raise a custom exception on failure.
Args:
string (str)... | [
"def",
"load_json_or_yaml",
"(",
"string",
",",
"is_path",
"=",
"False",
",",
"file_type",
"=",
"'json'",
",",
"exception",
"=",
"ScriptWorkerTaskException",
",",
"message",
"=",
"\"Failed to load %(file_type)s: %(exc)s\"",
")",
":",
"if",
"file_type",
"==",
"'json'... | Load json or yaml from a filehandle or string, and raise a custom exception on failure.
Args:
string (str): json/yaml body or a path to open
is_path (bool, optional): if ``string`` is a path. Defaults to False.
file_type (str, optional): either "json" or "yaml". Defaults to "json".
... | [
"Load",
"json",
"or",
"yaml",
"from",
"a",
"filehandle",
"or",
"string",
"and",
"raise",
"a",
"custom",
"exception",
"on",
"failure",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L428-L466 | train | 27,978 |
mozilla-releng/scriptworker | scriptworker/utils.py | write_to_file | def write_to_file(path, contents, file_type='text'):
"""Write ``contents`` to ``path`` with optional formatting.
Small helper function to write ``contents`` to ``file`` with optional formatting.
Args:
path (str): the path to write to
contents (str, object, or bytes): the contents to write ... | python | def write_to_file(path, contents, file_type='text'):
"""Write ``contents`` to ``path`` with optional formatting.
Small helper function to write ``contents`` to ``file`` with optional formatting.
Args:
path (str): the path to write to
contents (str, object, or bytes): the contents to write ... | [
"def",
"write_to_file",
"(",
"path",
",",
"contents",
",",
"file_type",
"=",
"'text'",
")",
":",
"FILE_TYPES",
"=",
"(",
"'json'",
",",
"'text'",
",",
"'binary'",
")",
"if",
"file_type",
"not",
"in",
"FILE_TYPES",
":",
"raise",
"ScriptWorkerException",
"(",
... | Write ``contents`` to ``path`` with optional formatting.
Small helper function to write ``contents`` to ``file`` with optional formatting.
Args:
path (str): the path to write to
contents (str, object, or bytes): the contents to write to the file
file_type (str, optional): the type of f... | [
"Write",
"contents",
"to",
"path",
"with",
"optional",
"formatting",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L470-L497 | train | 27,979 |
mozilla-releng/scriptworker | scriptworker/utils.py | read_from_file | def read_from_file(path, file_type='text', exception=ScriptWorkerException):
"""Read from ``path``.
Small helper function to read from ``file``.
Args:
path (str): the path to read from.
file_type (str, optional): the type of file. Currently accepts
``text`` or ``binary``. Defau... | python | def read_from_file(path, file_type='text', exception=ScriptWorkerException):
"""Read from ``path``.
Small helper function to read from ``file``.
Args:
path (str): the path to read from.
file_type (str, optional): the type of file. Currently accepts
``text`` or ``binary``. Defau... | [
"def",
"read_from_file",
"(",
"path",
",",
"file_type",
"=",
"'text'",
",",
"exception",
"=",
"ScriptWorkerException",
")",
":",
"FILE_TYPE_MAP",
"=",
"{",
"'text'",
":",
"'r'",
",",
"'binary'",
":",
"'rb'",
"}",
"if",
"file_type",
"not",
"in",
"FILE_TYPE_MA... | Read from ``path``.
Small helper function to read from ``file``.
Args:
path (str): the path to read from.
file_type (str, optional): the type of file. Currently accepts
``text`` or ``binary``. Defaults to ``text``.
exception (Exception, optional): the exception to raise
... | [
"Read",
"from",
"path",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L501-L528 | train | 27,980 |
mozilla-releng/scriptworker | scriptworker/utils.py | download_file | async def download_file(context, url, abs_filename, session=None, chunk_size=128):
"""Download a file, async.
Args:
context (scriptworker.context.Context): the scriptworker context.
url (str): the url to download
abs_filename (str): the path to download to
session (aiohttp.Clien... | python | async def download_file(context, url, abs_filename, session=None, chunk_size=128):
"""Download a file, async.
Args:
context (scriptworker.context.Context): the scriptworker context.
url (str): the url to download
abs_filename (str): the path to download to
session (aiohttp.Clien... | [
"async",
"def",
"download_file",
"(",
"context",
",",
"url",
",",
"abs_filename",
",",
"session",
"=",
"None",
",",
"chunk_size",
"=",
"128",
")",
":",
"session",
"=",
"session",
"or",
"context",
".",
"session",
"loggable_url",
"=",
"get_loggable_url",
"(",
... | Download a file, async.
Args:
context (scriptworker.context.Context): the scriptworker context.
url (str): the url to download
abs_filename (str): the path to download to
session (aiohttp.ClientSession, optional): the session to use. If
None, use context.session. Defau... | [
"Download",
"a",
"file",
"async",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L538-L569 | train | 27,981 |
mozilla-releng/scriptworker | scriptworker/utils.py | get_loggable_url | def get_loggable_url(url):
"""Strip out secrets from taskcluster urls.
Args:
url (str): the url to strip
Returns:
str: the loggable url
"""
loggable_url = url or ""
for secret_string in ("bewit=", "AWSAccessKeyId=", "access_token="):
parts = loggable_url.split(secret_s... | python | def get_loggable_url(url):
"""Strip out secrets from taskcluster urls.
Args:
url (str): the url to strip
Returns:
str: the loggable url
"""
loggable_url = url or ""
for secret_string in ("bewit=", "AWSAccessKeyId=", "access_token="):
parts = loggable_url.split(secret_s... | [
"def",
"get_loggable_url",
"(",
"url",
")",
":",
"loggable_url",
"=",
"url",
"or",
"\"\"",
"for",
"secret_string",
"in",
"(",
"\"bewit=\"",
",",
"\"AWSAccessKeyId=\"",
",",
"\"access_token=\"",
")",
":",
"parts",
"=",
"loggable_url",
".",
"split",
"(",
"secret... | Strip out secrets from taskcluster urls.
Args:
url (str): the url to strip
Returns:
str: the loggable url | [
"Strip",
"out",
"secrets",
"from",
"taskcluster",
"urls",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L573-L589 | train | 27,982 |
mozilla-releng/scriptworker | scriptworker/utils.py | match_url_regex | def match_url_regex(rules, url, callback):
"""Given rules and a callback, find the rule that matches the url.
Rules look like::
(
{
'schemes': ['https', 'ssh'],
'netlocs': ['hg.mozilla.org'],
'path_regexes': [
"^(?P<path>/... | python | def match_url_regex(rules, url, callback):
"""Given rules and a callback, find the rule that matches the url.
Rules look like::
(
{
'schemes': ['https', 'ssh'],
'netlocs': ['hg.mozilla.org'],
'path_regexes': [
"^(?P<path>/... | [
"def",
"match_url_regex",
"(",
"rules",
",",
"url",
",",
"callback",
")",
":",
"parts",
"=",
"urlparse",
"(",
"url",
")",
"path",
"=",
"unquote",
"(",
"parts",
".",
"path",
")",
"for",
"rule",
"in",
"rules",
":",
"if",
"parts",
".",
"scheme",
"not",
... | Given rules and a callback, find the rule that matches the url.
Rules look like::
(
{
'schemes': ['https', 'ssh'],
'netlocs': ['hg.mozilla.org'],
'path_regexes': [
"^(?P<path>/mozilla-(central|unified))(/|$)",
... | [
"Given",
"rules",
"and",
"a",
"callback",
"find",
"the",
"rule",
"that",
"matches",
"the",
"url",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L654-L695 | train | 27,983 |
mozilla-releng/scriptworker | scriptworker/utils.py | add_enumerable_item_to_dict | def add_enumerable_item_to_dict(dict_, key, item):
"""Add an item to a list contained in a dict.
For example: If the dict is ``{'some_key': ['an_item']}``, then calling this function
will alter the dict to ``{'some_key': ['an_item', 'another_item']}``.
If the key doesn't exist yet, the function initia... | python | def add_enumerable_item_to_dict(dict_, key, item):
"""Add an item to a list contained in a dict.
For example: If the dict is ``{'some_key': ['an_item']}``, then calling this function
will alter the dict to ``{'some_key': ['an_item', 'another_item']}``.
If the key doesn't exist yet, the function initia... | [
"def",
"add_enumerable_item_to_dict",
"(",
"dict_",
",",
"key",
",",
"item",
")",
":",
"dict_",
".",
"setdefault",
"(",
"key",
",",
"[",
"]",
")",
"if",
"isinstance",
"(",
"item",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"dict_",
"[",
"key",
... | Add an item to a list contained in a dict.
For example: If the dict is ``{'some_key': ['an_item']}``, then calling this function
will alter the dict to ``{'some_key': ['an_item', 'another_item']}``.
If the key doesn't exist yet, the function initializes it with a list containing the
item.
List-li... | [
"Add",
"an",
"item",
"to",
"a",
"list",
"contained",
"in",
"a",
"dict",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L699-L720 | train | 27,984 |
mozilla-releng/scriptworker | scriptworker/utils.py | get_single_item_from_sequence | def get_single_item_from_sequence(
sequence, condition,
ErrorClass=ValueError,
no_item_error_message='No item matched condition',
too_many_item_error_message='Too many items matched condition',
append_sequence_to_error_message=True
):
"""Return an item from a python sequence based on the given c... | python | def get_single_item_from_sequence(
sequence, condition,
ErrorClass=ValueError,
no_item_error_message='No item matched condition',
too_many_item_error_message='Too many items matched condition',
append_sequence_to_error_message=True
):
"""Return an item from a python sequence based on the given c... | [
"def",
"get_single_item_from_sequence",
"(",
"sequence",
",",
"condition",
",",
"ErrorClass",
"=",
"ValueError",
",",
"no_item_error_message",
"=",
"'No item matched condition'",
",",
"too_many_item_error_message",
"=",
"'Too many items matched condition'",
",",
"append_sequenc... | Return an item from a python sequence based on the given condition.
Args:
sequence (sequence): The sequence to filter
condition: A function that serves to filter items from `sequence`. Function
must have one argument (a single item from the sequence) and return a boolean.
ErrorC... | [
"Return",
"an",
"item",
"from",
"a",
"python",
"sequence",
"based",
"on",
"the",
"given",
"condition",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L748-L782 | train | 27,985 |
mozilla-releng/scriptworker | scriptworker/client.py | get_task | def get_task(config):
"""Read the task.json from work_dir.
Args:
config (dict): the running config, to find work_dir.
Returns:
dict: the contents of task.json
Raises:
ScriptWorkerTaskException: on error.
"""
path = os.path.join(config['work_dir'], "task.json")
mes... | python | def get_task(config):
"""Read the task.json from work_dir.
Args:
config (dict): the running config, to find work_dir.
Returns:
dict: the contents of task.json
Raises:
ScriptWorkerTaskException: on error.
"""
path = os.path.join(config['work_dir'], "task.json")
mes... | [
"def",
"get_task",
"(",
"config",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config",
"[",
"'work_dir'",
"]",
",",
"\"task.json\"",
")",
"message",
"=",
"\"Can't read task from {}!\\n%(exc)s\"",
".",
"format",
"(",
"path",
")",
"contents",
... | Read the task.json from work_dir.
Args:
config (dict): the running config, to find work_dir.
Returns:
dict: the contents of task.json
Raises:
ScriptWorkerTaskException: on error. | [
"Read",
"the",
"task",
".",
"json",
"from",
"work_dir",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/client.py#L28-L44 | train | 27,986 |
mozilla-releng/scriptworker | scriptworker/client.py | validate_json_schema | def validate_json_schema(data, schema, name="task"):
"""Given data and a jsonschema, let's validate it.
This happens for tasks and chain of trust artifacts.
Args:
data (dict): the json to validate.
schema (dict): the jsonschema to validate against.
name (str, optional): the name of... | python | def validate_json_schema(data, schema, name="task"):
"""Given data and a jsonschema, let's validate it.
This happens for tasks and chain of trust artifacts.
Args:
data (dict): the json to validate.
schema (dict): the jsonschema to validate against.
name (str, optional): the name of... | [
"def",
"validate_json_schema",
"(",
"data",
",",
"schema",
",",
"name",
"=",
"\"task\"",
")",
":",
"try",
":",
"jsonschema",
".",
"validate",
"(",
"data",
",",
"schema",
")",
"except",
"jsonschema",
".",
"exceptions",
".",
"ValidationError",
"as",
"exc",
"... | Given data and a jsonschema, let's validate it.
This happens for tasks and chain of trust artifacts.
Args:
data (dict): the json to validate.
schema (dict): the jsonschema to validate against.
name (str, optional): the name of the json, for exception messages.
Defaults to "... | [
"Given",
"data",
"and",
"a",
"jsonschema",
"let",
"s",
"validate",
"it",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/client.py#L47-L68 | train | 27,987 |
mozilla-releng/scriptworker | scriptworker/client.py | validate_task_schema | def validate_task_schema(context, schema_key='schema_file'):
"""Validate the task definition.
Args:
context (scriptworker.context.Context): the scriptworker context. It must contain a task and
the config pointing to the schema file
schema_key: the key in `context.config` where the p... | python | def validate_task_schema(context, schema_key='schema_file'):
"""Validate the task definition.
Args:
context (scriptworker.context.Context): the scriptworker context. It must contain a task and
the config pointing to the schema file
schema_key: the key in `context.config` where the p... | [
"def",
"validate_task_schema",
"(",
"context",
",",
"schema_key",
"=",
"'schema_file'",
")",
":",
"schema_path",
"=",
"context",
".",
"config",
"schema_keys",
"=",
"schema_key",
".",
"split",
"(",
"'.'",
")",
"for",
"key",
"in",
"schema_keys",
":",
"schema_pat... | Validate the task definition.
Args:
context (scriptworker.context.Context): the scriptworker context. It must contain a task and
the config pointing to the schema file
schema_key: the key in `context.config` where the path to the schema file is. Key can contain
dots (e.g.: '... | [
"Validate",
"the",
"task",
"definition",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/client.py#L71-L95 | train | 27,988 |
mozilla-releng/scriptworker | scriptworker/client.py | validate_artifact_url | def validate_artifact_url(valid_artifact_rules, valid_artifact_task_ids, url):
"""Ensure a URL fits in given scheme, netloc, and path restrictions.
If we fail any checks, raise a ScriptWorkerTaskException with
``malformed-payload``.
Args:
valid_artifact_rules (tuple): the tests to run, with ``... | python | def validate_artifact_url(valid_artifact_rules, valid_artifact_task_ids, url):
"""Ensure a URL fits in given scheme, netloc, and path restrictions.
If we fail any checks, raise a ScriptWorkerTaskException with
``malformed-payload``.
Args:
valid_artifact_rules (tuple): the tests to run, with ``... | [
"def",
"validate_artifact_url",
"(",
"valid_artifact_rules",
",",
"valid_artifact_task_ids",
",",
"url",
")",
":",
"def",
"callback",
"(",
"match",
")",
":",
"path_info",
"=",
"match",
".",
"groupdict",
"(",
")",
"# make sure we're pointing at a valid task ID",
"if",
... | Ensure a URL fits in given scheme, netloc, and path restrictions.
If we fail any checks, raise a ScriptWorkerTaskException with
``malformed-payload``.
Args:
valid_artifact_rules (tuple): the tests to run, with ``schemas``, ``netlocs``,
and ``path_regexes``.
valid_artifact_task_... | [
"Ensure",
"a",
"URL",
"fits",
"in",
"given",
"scheme",
"netloc",
"and",
"path",
"restrictions",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/client.py#L98-L133 | train | 27,989 |
mozilla-releng/scriptworker | scriptworker/client.py | sync_main | def sync_main(async_main, config_path=None, default_config=None,
should_validate_task=True, loop_function=asyncio.get_event_loop):
"""Entry point for scripts using scriptworker.
This function sets up the basic needs for a script to run. More specifically:
* it creates the scriptworker con... | python | def sync_main(async_main, config_path=None, default_config=None,
should_validate_task=True, loop_function=asyncio.get_event_loop):
"""Entry point for scripts using scriptworker.
This function sets up the basic needs for a script to run. More specifically:
* it creates the scriptworker con... | [
"def",
"sync_main",
"(",
"async_main",
",",
"config_path",
"=",
"None",
",",
"default_config",
"=",
"None",
",",
"should_validate_task",
"=",
"True",
",",
"loop_function",
"=",
"asyncio",
".",
"get_event_loop",
")",
":",
"context",
"=",
"_init_context",
"(",
"... | Entry point for scripts using scriptworker.
This function sets up the basic needs for a script to run. More specifically:
* it creates the scriptworker context and initializes it with the provided config
* the path to the config file is either taken from `config_path` or from `sys.argv[1]`.
... | [
"Entry",
"point",
"for",
"scripts",
"using",
"scriptworker",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/client.py#L136-L164 | train | 27,990 |
mozilla-releng/scriptworker | scriptworker/task_process.py | TaskProcess.stop | async def stop(self):
"""Stop the current task process.
Starts with SIGTERM, gives the process 1 second to terminate, then kills it
"""
# negate pid so that signals apply to process group
pgid = -self.process.pid
try:
os.kill(pgid, signal.SIGTERM)
... | python | async def stop(self):
"""Stop the current task process.
Starts with SIGTERM, gives the process 1 second to terminate, then kills it
"""
# negate pid so that signals apply to process group
pgid = -self.process.pid
try:
os.kill(pgid, signal.SIGTERM)
... | [
"async",
"def",
"stop",
"(",
"self",
")",
":",
"# negate pid so that signals apply to process group",
"pgid",
"=",
"-",
"self",
".",
"process",
".",
"pid",
"try",
":",
"os",
".",
"kill",
"(",
"pgid",
",",
"signal",
".",
"SIGTERM",
")",
"await",
"asyncio",
... | Stop the current task process.
Starts with SIGTERM, gives the process 1 second to terminate, then kills it | [
"Stop",
"the",
"current",
"task",
"process",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/task_process.py#L35-L47 | train | 27,991 |
mozilla-releng/scriptworker | scriptworker/ed25519.py | ed25519_private_key_from_string | def ed25519_private_key_from_string(string):
"""Create an ed25519 private key from ``string``, which is a seed.
Args:
string (str): the string to use as a seed.
Returns:
Ed25519PrivateKey: the private key
"""
try:
return Ed25519PrivateKey.from_private_bytes(
ba... | python | def ed25519_private_key_from_string(string):
"""Create an ed25519 private key from ``string``, which is a seed.
Args:
string (str): the string to use as a seed.
Returns:
Ed25519PrivateKey: the private key
"""
try:
return Ed25519PrivateKey.from_private_bytes(
ba... | [
"def",
"ed25519_private_key_from_string",
"(",
"string",
")",
":",
"try",
":",
"return",
"Ed25519PrivateKey",
".",
"from_private_bytes",
"(",
"base64",
".",
"b64decode",
"(",
"string",
")",
")",
"except",
"(",
"UnsupportedAlgorithm",
",",
"Base64Error",
")",
"as",... | Create an ed25519 private key from ``string``, which is a seed.
Args:
string (str): the string to use as a seed.
Returns:
Ed25519PrivateKey: the private key | [
"Create",
"an",
"ed25519",
"private",
"key",
"from",
"string",
"which",
"is",
"a",
"seed",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/ed25519.py#L24-L39 | train | 27,992 |
mozilla-releng/scriptworker | scriptworker/ed25519.py | ed25519_public_key_from_string | def ed25519_public_key_from_string(string):
"""Create an ed25519 public key from ``string``, which is a seed.
Args:
string (str): the string to use as a seed.
Returns:
Ed25519PublicKey: the public key
"""
try:
return Ed25519PublicKey.from_public_bytes(
base64.b... | python | def ed25519_public_key_from_string(string):
"""Create an ed25519 public key from ``string``, which is a seed.
Args:
string (str): the string to use as a seed.
Returns:
Ed25519PublicKey: the public key
"""
try:
return Ed25519PublicKey.from_public_bytes(
base64.b... | [
"def",
"ed25519_public_key_from_string",
"(",
"string",
")",
":",
"try",
":",
"return",
"Ed25519PublicKey",
".",
"from_public_bytes",
"(",
"base64",
".",
"b64decode",
"(",
"string",
")",
")",
"except",
"(",
"UnsupportedAlgorithm",
",",
"Base64Error",
")",
"as",
... | Create an ed25519 public key from ``string``, which is a seed.
Args:
string (str): the string to use as a seed.
Returns:
Ed25519PublicKey: the public key | [
"Create",
"an",
"ed25519",
"public",
"key",
"from",
"string",
"which",
"is",
"a",
"seed",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/ed25519.py#L42-L57 | train | 27,993 |
mozilla-releng/scriptworker | scriptworker/ed25519.py | _ed25519_key_from_file | def _ed25519_key_from_file(fn, path):
"""Create an ed25519 key from the contents of ``path``.
``path`` is a filepath containing a base64-encoded ed25519 key seed.
Args:
fn (callable): the function to call with the contents from ``path``
path (str): the file path to the base64-encoded key s... | python | def _ed25519_key_from_file(fn, path):
"""Create an ed25519 key from the contents of ``path``.
``path`` is a filepath containing a base64-encoded ed25519 key seed.
Args:
fn (callable): the function to call with the contents from ``path``
path (str): the file path to the base64-encoded key s... | [
"def",
"_ed25519_key_from_file",
"(",
"fn",
",",
"path",
")",
":",
"try",
":",
"return",
"fn",
"(",
"read_from_file",
"(",
"path",
",",
"exception",
"=",
"ScriptWorkerEd25519Error",
")",
")",
"except",
"ScriptWorkerException",
"as",
"exc",
":",
"raise",
"Scrip... | Create an ed25519 key from the contents of ``path``.
``path`` is a filepath containing a base64-encoded ed25519 key seed.
Args:
fn (callable): the function to call with the contents from ``path``
path (str): the file path to the base64-encoded key seed.
Returns:
obj: the appropria... | [
"Create",
"an",
"ed25519",
"key",
"from",
"the",
"contents",
"of",
"path",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/ed25519.py#L60-L79 | train | 27,994 |
mozilla-releng/scriptworker | scriptworker/ed25519.py | ed25519_private_key_to_string | def ed25519_private_key_to_string(key):
"""Convert an ed25519 private key to a base64-encoded string.
Args:
key (Ed25519PrivateKey): the key to write to the file.
Returns:
str: the key representation as a str
"""
return base64.b64encode(key.private_bytes(
encoding=serializ... | python | def ed25519_private_key_to_string(key):
"""Convert an ed25519 private key to a base64-encoded string.
Args:
key (Ed25519PrivateKey): the key to write to the file.
Returns:
str: the key representation as a str
"""
return base64.b64encode(key.private_bytes(
encoding=serializ... | [
"def",
"ed25519_private_key_to_string",
"(",
"key",
")",
":",
"return",
"base64",
".",
"b64encode",
"(",
"key",
".",
"private_bytes",
"(",
"encoding",
"=",
"serialization",
".",
"Encoding",
".",
"Raw",
",",
"format",
"=",
"serialization",
".",
"PrivateFormat",
... | Convert an ed25519 private key to a base64-encoded string.
Args:
key (Ed25519PrivateKey): the key to write to the file.
Returns:
str: the key representation as a str | [
"Convert",
"an",
"ed25519",
"private",
"key",
"to",
"a",
"base64",
"-",
"encoded",
"string",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/ed25519.py#L86-L100 | train | 27,995 |
mozilla-releng/scriptworker | scriptworker/ed25519.py | ed25519_public_key_to_string | def ed25519_public_key_to_string(key):
"""Convert an ed25519 public key to a base64-encoded string.
Args:
key (Ed25519PublicKey): the key to write to the file.
Returns:
str: the key representation as a str
"""
return base64.b64encode(key.public_bytes(
encoding=serializatio... | python | def ed25519_public_key_to_string(key):
"""Convert an ed25519 public key to a base64-encoded string.
Args:
key (Ed25519PublicKey): the key to write to the file.
Returns:
str: the key representation as a str
"""
return base64.b64encode(key.public_bytes(
encoding=serializatio... | [
"def",
"ed25519_public_key_to_string",
"(",
"key",
")",
":",
"return",
"base64",
".",
"b64encode",
"(",
"key",
".",
"public_bytes",
"(",
"encoding",
"=",
"serialization",
".",
"Encoding",
".",
"Raw",
",",
"format",
"=",
"serialization",
".",
"PublicFormat",
".... | Convert an ed25519 public key to a base64-encoded string.
Args:
key (Ed25519PublicKey): the key to write to the file.
Returns:
str: the key representation as a str | [
"Convert",
"an",
"ed25519",
"public",
"key",
"to",
"a",
"base64",
"-",
"encoded",
"string",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/ed25519.py#L103-L116 | train | 27,996 |
mozilla-releng/scriptworker | scriptworker/ed25519.py | verify_ed25519_signature | def verify_ed25519_signature(public_key, contents, signature, message):
"""Verify that ``signature`` comes from ``public_key`` and ``contents``.
Args:
public_key (Ed25519PublicKey): the key to verify the signature
contents (bytes): the contents that was signed
signature (bytes): the sig... | python | def verify_ed25519_signature(public_key, contents, signature, message):
"""Verify that ``signature`` comes from ``public_key`` and ``contents``.
Args:
public_key (Ed25519PublicKey): the key to verify the signature
contents (bytes): the contents that was signed
signature (bytes): the sig... | [
"def",
"verify_ed25519_signature",
"(",
"public_key",
",",
"contents",
",",
"signature",
",",
"message",
")",
":",
"try",
":",
"public_key",
".",
"verify",
"(",
"signature",
",",
"contents",
")",
"except",
"InvalidSignature",
"as",
"exc",
":",
"raise",
"Script... | Verify that ``signature`` comes from ``public_key`` and ``contents``.
Args:
public_key (Ed25519PublicKey): the key to verify the signature
contents (bytes): the contents that was signed
signature (bytes): the signature to verify
message (str): the error message to raise.
Raises... | [
"Verify",
"that",
"signature",
"comes",
"from",
"public_key",
"and",
"contents",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/ed25519.py#L119-L135 | train | 27,997 |
mozilla-releng/scriptworker | scriptworker/constants.py | get_reversed_statuses | def get_reversed_statuses(context):
"""Return a mapping of exit codes to status strings.
Args:
context (scriptworker.context.Context): the scriptworker context
Returns:
dict: the mapping of exit codes to status strings.
"""
_rev = {v: k for k, v in STATUSES.items()}
_rev.updat... | python | def get_reversed_statuses(context):
"""Return a mapping of exit codes to status strings.
Args:
context (scriptworker.context.Context): the scriptworker context
Returns:
dict: the mapping of exit codes to status strings.
"""
_rev = {v: k for k, v in STATUSES.items()}
_rev.updat... | [
"def",
"get_reversed_statuses",
"(",
"context",
")",
":",
"_rev",
"=",
"{",
"v",
":",
"k",
"for",
"k",
",",
"v",
"in",
"STATUSES",
".",
"items",
"(",
")",
"}",
"_rev",
".",
"update",
"(",
"dict",
"(",
"context",
".",
"config",
"[",
"'reversed_statuse... | Return a mapping of exit codes to status strings.
Args:
context (scriptworker.context.Context): the scriptworker context
Returns:
dict: the mapping of exit codes to status strings. | [
"Return",
"a",
"mapping",
"of",
"exit",
"codes",
"to",
"status",
"strings",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/constants.py#L463-L475 | train | 27,998 |
mozilla-releng/scriptworker | scriptworker/task.py | get_repo | def get_repo(task, source_env_prefix):
"""Get the repo for a task.
Args:
task (ChainOfTrust or LinkOfTrust): the trust object to inspect
source_env_prefix (str): The environment variable prefix that is used
to get repository information.
Returns:
str: the source url.
... | python | def get_repo(task, source_env_prefix):
"""Get the repo for a task.
Args:
task (ChainOfTrust or LinkOfTrust): the trust object to inspect
source_env_prefix (str): The environment variable prefix that is used
to get repository information.
Returns:
str: the source url.
... | [
"def",
"get_repo",
"(",
"task",
",",
"source_env_prefix",
")",
":",
"repo",
"=",
"_extract_from_env_in_payload",
"(",
"task",
",",
"source_env_prefix",
"+",
"'_HEAD_REPOSITORY'",
")",
"if",
"repo",
"is",
"not",
"None",
":",
"repo",
"=",
"repo",
".",
"rstrip",
... | Get the repo for a task.
Args:
task (ChainOfTrust or LinkOfTrust): the trust object to inspect
source_env_prefix (str): The environment variable prefix that is used
to get repository information.
Returns:
str: the source url.
None: if not defined for this task. | [
"Get",
"the",
"repo",
"for",
"a",
"task",
"."
] | 8e97bbd83b9b578565ec57904c966dd6ae4ef0ae | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/task.py#L151-L167 | train | 27,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.