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
pjmark/NIMPA
resources/resources.py
get_mmr_constants
def get_mmr_constants(): ''' Put all the constants together in a dictionary ''' Cnt = { 'ISOTOPE':'F18', 'DCYCRR':DCYCRR, 'ALPHA':ALPHA, 'NRNG':NRNG, 'NSRNG':NSRNG, 'NCRS':NCRS, 'NCRSR':NCRSR, 'NBCKT':224, 'NSANGLES':A, 'NSBINS':W, 'Naw':-1, # number of total active bins per 2D sino 'NSN11': NSN11, # number of sinos in span-11 'NSN1': NSN1, # number of sinos in span-1 'NSN64': NSN64, # number of sinos in span-1 with no MRD limit 'MRD': MRD, # maximum ring difference RD 'SPN':SPAN, # span-1 (1), span-11 (11), ssrb (0) 'TFOV2':TFOV2, # squared radius of TFOV 'RNG_STRT':RNG_STRT, # limit axial extension by defining start and end ring 'RNG_END' :RNG_END, # this feature only works with span-1 processing (Cnt['SPN']=1) 'SS_IMZ':SS_IMZ, #Scatter mu-map iamge size 'SS_IMY':SS_IMY, 'SS_IMX':SS_IMX, 'SS_VXZ':SS_VXZ, 'SS_VXY':SS_VXY, 'IS_VXZ':IS_VXZ, 'SSE_IMZ':SSE_IMZ, #Scatter emission image size 'SSE_IMY':SSE_IMY, 'SSE_IMX':SSE_IMX, 'SSE_VXZ':SSE_VXZ, 'SSE_VXY':SSE_VXY, 'SZ_IMZ':SZ_IMZ, #GPU optimised image size 'SZ_IMY':SZ_IMY, 'SZ_IMX':SZ_IMX, 'SZ_VOXZ':SZ_VOXZ, 'SZ_VOXY':SZ_VOXY, 'SZ_VOXZi':SZ_VOXZi, 'SO_IMZ':SO_IMZ, #Original image size (from Siemens) 'SO_IMY':SO_IMY, 'SO_IMX':SO_IMX, 'SO_VXZ':SO_VXZ, 'SO_VXY':SO_VXY, 'SO_VXX':SO_VXX, 'NSEG0':SEG0, 'RE':RE, #effective ring radius 'R':R, 'SEG':seg, 'MNRD':minrd, 'MXRD':maxrd, 'SCTRNG':sct_irng, 'TGAP':TGAP, 'OFFGAP':OFFGAP, 'AXR':AXR, 'R02':R02, #squared electron radius 'LLD':LLD, #lower energy threashold 'E511':E511, 'ER':ER, #energy resolution 'COSUPSMX':COSUPSMX, #cosine of max allowed scatter angle 'NCOS':NCOS, #number of cos samples for LUT 'COSSTP':COSSTP, #cosine step 'ICOSSTP':ICOSSTP, #inverse of cosine step 'ETHRLD':ETHRLD, #intensity emission image threshold (used in scatter modelling) 'CLGHT':CLGHT, #speed of light [cm/s] 'CWND':CWND, #coincidence time window [ps] 'TOFBINN':TOFBINN, #number of TOF bins 'TOFBINS':TOFBINS, #TOF bin width [ps] 'TOFBIND':TOFBIND, 'ITOFBIND':ITOFBIND, # affine and image size for the reconstructed image, assuming the centre of voxels in mm 'AFFINE':np.array([ [-10*SO_VXX, 0., 0., 5.*SO_IMX*SO_VXX ], #+5.*SO_VXX [0., 10*SO_VXY, 0., -5.*SO_IMY*SO_VXY ], #+5.*SO_VXY [0., 0., 10*SO_VXZ, -5.*SO_IMZ*SO_VXZ ], #-5.*SO_VXZ [0., 0., 0., 1.]]), 'IMSIZE':np.array([SO_IMZ, SO_IMY, SO_IMX]), 'BTP':0, #1:non parametric bootstrap, 2: parametric bootstrap (recommended) 'BTPRT':1.0, # Ratio of bootstrapped/original events (enables downsampling) 'VERBOSE':False, 'SCTSCLEM':SCTSCLEM, 'SCTSCLMU':SCTSCLMU, } # get the setup for GPU and third party apps Cnt = get_setup(Cnt=Cnt) return Cnt
python
def get_mmr_constants(): ''' Put all the constants together in a dictionary ''' Cnt = { 'ISOTOPE':'F18', 'DCYCRR':DCYCRR, 'ALPHA':ALPHA, 'NRNG':NRNG, 'NSRNG':NSRNG, 'NCRS':NCRS, 'NCRSR':NCRSR, 'NBCKT':224, 'NSANGLES':A, 'NSBINS':W, 'Naw':-1, # number of total active bins per 2D sino 'NSN11': NSN11, # number of sinos in span-11 'NSN1': NSN1, # number of sinos in span-1 'NSN64': NSN64, # number of sinos in span-1 with no MRD limit 'MRD': MRD, # maximum ring difference RD 'SPN':SPAN, # span-1 (1), span-11 (11), ssrb (0) 'TFOV2':TFOV2, # squared radius of TFOV 'RNG_STRT':RNG_STRT, # limit axial extension by defining start and end ring 'RNG_END' :RNG_END, # this feature only works with span-1 processing (Cnt['SPN']=1) 'SS_IMZ':SS_IMZ, #Scatter mu-map iamge size 'SS_IMY':SS_IMY, 'SS_IMX':SS_IMX, 'SS_VXZ':SS_VXZ, 'SS_VXY':SS_VXY, 'IS_VXZ':IS_VXZ, 'SSE_IMZ':SSE_IMZ, #Scatter emission image size 'SSE_IMY':SSE_IMY, 'SSE_IMX':SSE_IMX, 'SSE_VXZ':SSE_VXZ, 'SSE_VXY':SSE_VXY, 'SZ_IMZ':SZ_IMZ, #GPU optimised image size 'SZ_IMY':SZ_IMY, 'SZ_IMX':SZ_IMX, 'SZ_VOXZ':SZ_VOXZ, 'SZ_VOXY':SZ_VOXY, 'SZ_VOXZi':SZ_VOXZi, 'SO_IMZ':SO_IMZ, #Original image size (from Siemens) 'SO_IMY':SO_IMY, 'SO_IMX':SO_IMX, 'SO_VXZ':SO_VXZ, 'SO_VXY':SO_VXY, 'SO_VXX':SO_VXX, 'NSEG0':SEG0, 'RE':RE, #effective ring radius 'R':R, 'SEG':seg, 'MNRD':minrd, 'MXRD':maxrd, 'SCTRNG':sct_irng, 'TGAP':TGAP, 'OFFGAP':OFFGAP, 'AXR':AXR, 'R02':R02, #squared electron radius 'LLD':LLD, #lower energy threashold 'E511':E511, 'ER':ER, #energy resolution 'COSUPSMX':COSUPSMX, #cosine of max allowed scatter angle 'NCOS':NCOS, #number of cos samples for LUT 'COSSTP':COSSTP, #cosine step 'ICOSSTP':ICOSSTP, #inverse of cosine step 'ETHRLD':ETHRLD, #intensity emission image threshold (used in scatter modelling) 'CLGHT':CLGHT, #speed of light [cm/s] 'CWND':CWND, #coincidence time window [ps] 'TOFBINN':TOFBINN, #number of TOF bins 'TOFBINS':TOFBINS, #TOF bin width [ps] 'TOFBIND':TOFBIND, 'ITOFBIND':ITOFBIND, # affine and image size for the reconstructed image, assuming the centre of voxels in mm 'AFFINE':np.array([ [-10*SO_VXX, 0., 0., 5.*SO_IMX*SO_VXX ], #+5.*SO_VXX [0., 10*SO_VXY, 0., -5.*SO_IMY*SO_VXY ], #+5.*SO_VXY [0., 0., 10*SO_VXZ, -5.*SO_IMZ*SO_VXZ ], #-5.*SO_VXZ [0., 0., 0., 1.]]), 'IMSIZE':np.array([SO_IMZ, SO_IMY, SO_IMX]), 'BTP':0, #1:non parametric bootstrap, 2: parametric bootstrap (recommended) 'BTPRT':1.0, # Ratio of bootstrapped/original events (enables downsampling) 'VERBOSE':False, 'SCTSCLEM':SCTSCLEM, 'SCTSCLMU':SCTSCLMU, } # get the setup for GPU and third party apps Cnt = get_setup(Cnt=Cnt) return Cnt
[ "def", "get_mmr_constants", "(", ")", ":", "Cnt", "=", "{", "'ISOTOPE'", ":", "'F18'", ",", "'DCYCRR'", ":", "DCYCRR", ",", "'ALPHA'", ":", "ALPHA", ",", "'NRNG'", ":", "NRNG", ",", "'NSRNG'", ":", "NSRNG", ",", "'NCRS'", ":", "NCRS", ",", "'NCRSR'", ...
Put all the constants together in a dictionary
[ "Put", "all", "the", "constants", "together", "in", "a", "dictionary" ]
3f4231fed2934a1d92e4cd8e9e153b0118e29d86
https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/resources/resources.py#L281-L376
train
46,800
pjmark/NIMPA
install_tools.py
check_version
def check_version(Cnt, chcklst=['RESPATH','REGPATH','DCM2NIIX','HMUDIR']): ''' Check version and existence of all third-party software and input data. Output a dictionary with bool type of the requested bits in 'chcklst' ''' # at start, assume that nothing is present yet output = {} for itm in chcklst: output[itm] = False # niftyreg reg_resample first if 'RESPATH' in chcklst and 'RESPATH' in Cnt: try: proc = Popen([Cnt['RESPATH'], '--version'], stdout=PIPE) out = proc.stdout.read() if reg_ver in out: output['RESPATH'] = True except OSError: print 'e> NiftyReg (reg_resample) either is NOT installed or is corrupt.' # niftyreg reg_aladin if 'REGPATH' in chcklst and 'REGPATH' in Cnt: try: proc = Popen([Cnt['REGPATH'], '--version'], stdout=PIPE) out = proc.stdout.read() if reg_ver in out: output['REGPATH'] = True except OSError: print 'e> NiftyReg (reg_aladin) either is NOT installed or is corrupt.' # dcm2niix if 'DCM2NIIX' in chcklst and 'DCM2NIIX' in Cnt: try: proc = Popen([Cnt['DCM2NIIX'], '-h'], stdout=PIPE) out = proc.stdout.read() ver_str = re.search('(?<=dcm2niiX version v)\d{1,2}.\d{1,2}.\d*', out) if ver_str and dcm_ver in ver_str.group(0): output['DCM2NIIX'] = True except OSError: print 'e> dcm2niix either is NOT installed or is corrupt.' # hdw mu-map list if 'HMUDIR' in chcklst and 'HMUDIR' in Cnt: for hi in Cnt['HMULIST']: if os.path.isfile(os.path.join(Cnt['HMUDIR'],hi)): output['HMUDIR'] = True else: output['HMUDIR'] = False break return output
python
def check_version(Cnt, chcklst=['RESPATH','REGPATH','DCM2NIIX','HMUDIR']): ''' Check version and existence of all third-party software and input data. Output a dictionary with bool type of the requested bits in 'chcklst' ''' # at start, assume that nothing is present yet output = {} for itm in chcklst: output[itm] = False # niftyreg reg_resample first if 'RESPATH' in chcklst and 'RESPATH' in Cnt: try: proc = Popen([Cnt['RESPATH'], '--version'], stdout=PIPE) out = proc.stdout.read() if reg_ver in out: output['RESPATH'] = True except OSError: print 'e> NiftyReg (reg_resample) either is NOT installed or is corrupt.' # niftyreg reg_aladin if 'REGPATH' in chcklst and 'REGPATH' in Cnt: try: proc = Popen([Cnt['REGPATH'], '--version'], stdout=PIPE) out = proc.stdout.read() if reg_ver in out: output['REGPATH'] = True except OSError: print 'e> NiftyReg (reg_aladin) either is NOT installed or is corrupt.' # dcm2niix if 'DCM2NIIX' in chcklst and 'DCM2NIIX' in Cnt: try: proc = Popen([Cnt['DCM2NIIX'], '-h'], stdout=PIPE) out = proc.stdout.read() ver_str = re.search('(?<=dcm2niiX version v)\d{1,2}.\d{1,2}.\d*', out) if ver_str and dcm_ver in ver_str.group(0): output['DCM2NIIX'] = True except OSError: print 'e> dcm2niix either is NOT installed or is corrupt.' # hdw mu-map list if 'HMUDIR' in chcklst and 'HMUDIR' in Cnt: for hi in Cnt['HMULIST']: if os.path.isfile(os.path.join(Cnt['HMUDIR'],hi)): output['HMUDIR'] = True else: output['HMUDIR'] = False break return output
[ "def", "check_version", "(", "Cnt", ",", "chcklst", "=", "[", "'RESPATH'", ",", "'REGPATH'", ",", "'DCM2NIIX'", ",", "'HMUDIR'", "]", ")", ":", "# at start, assume that nothing is present yet", "output", "=", "{", "}", "for", "itm", "in", "chcklst", ":", "outp...
Check version and existence of all third-party software and input data. Output a dictionary with bool type of the requested bits in 'chcklst'
[ "Check", "version", "and", "existence", "of", "all", "third", "-", "party", "software", "and", "input", "data", ".", "Output", "a", "dictionary", "with", "bool", "type", "of", "the", "requested", "bits", "in", "chcklst" ]
3f4231fed2934a1d92e4cd8e9e153b0118e29d86
https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/install_tools.py#L120-L170
train
46,801
pjmark/NIMPA
install_tools.py
update_resources
def update_resources(Cnt): '''Update resources.py with the paths to the new installed apps. ''' # list of path names which will be saved key_list = ['PATHTOOLS', 'RESPATH', 'REGPATH', 'DCM2NIIX', 'HMUDIR'] # get the local path to NiftyPET resources.py path_resources = cs.path_niftypet_local() resources_file = os.path.join(path_resources,'resources.py') # update resources.py if os.path.isfile(resources_file): f = open(resources_file, 'r') rsrc = f.read() f.close() # get the region of keeping in synch with Python i0 = rsrc.find('### start NiftyPET tools ###') i1 = rsrc.find('### end NiftyPET tools ###') pth_list = [] for k in key_list: if k in Cnt: pth_list.append('\'' + Cnt[k].replace("\\","/") + '\'') else: pth_list.append('\'\'') # modify resources.py with the new paths strNew = '### start NiftyPET tools ###\n' for i in range(len(key_list)): if pth_list[i] != '\'\'': strNew += key_list[i]+' = '+pth_list[i] + '\n' rsrcNew = rsrc[:i0] + strNew + rsrc[i1:] f = open(resources_file, 'w') f.write(rsrcNew) f.close() return Cnt
python
def update_resources(Cnt): '''Update resources.py with the paths to the new installed apps. ''' # list of path names which will be saved key_list = ['PATHTOOLS', 'RESPATH', 'REGPATH', 'DCM2NIIX', 'HMUDIR'] # get the local path to NiftyPET resources.py path_resources = cs.path_niftypet_local() resources_file = os.path.join(path_resources,'resources.py') # update resources.py if os.path.isfile(resources_file): f = open(resources_file, 'r') rsrc = f.read() f.close() # get the region of keeping in synch with Python i0 = rsrc.find('### start NiftyPET tools ###') i1 = rsrc.find('### end NiftyPET tools ###') pth_list = [] for k in key_list: if k in Cnt: pth_list.append('\'' + Cnt[k].replace("\\","/") + '\'') else: pth_list.append('\'\'') # modify resources.py with the new paths strNew = '### start NiftyPET tools ###\n' for i in range(len(key_list)): if pth_list[i] != '\'\'': strNew += key_list[i]+' = '+pth_list[i] + '\n' rsrcNew = rsrc[:i0] + strNew + rsrc[i1:] f = open(resources_file, 'w') f.write(rsrcNew) f.close() return Cnt
[ "def", "update_resources", "(", "Cnt", ")", ":", "# list of path names which will be saved", "key_list", "=", "[", "'PATHTOOLS'", ",", "'RESPATH'", ",", "'REGPATH'", ",", "'DCM2NIIX'", ",", "'HMUDIR'", "]", "# get the local path to NiftyPET resources.py", "path_resources", ...
Update resources.py with the paths to the new installed apps.
[ "Update", "resources", ".", "py", "with", "the", "paths", "to", "the", "new", "installed", "apps", "." ]
3f4231fed2934a1d92e4cd8e9e153b0118e29d86
https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/install_tools.py#L343-L379
train
46,802
Syndace/python-omemo
omemo/storage.py
Storage.loadSessions
def loadSessions(self, callback, bare_jid, device_ids): """ Return a dict containing the session for each device id. By default, this method calls loadSession for each device id. """ if self.is_async: self.__loadSessionsAsync(callback, bare_jid, device_ids, {}) else: return self.__loadSessionsSync(bare_jid, device_ids)
python
def loadSessions(self, callback, bare_jid, device_ids): """ Return a dict containing the session for each device id. By default, this method calls loadSession for each device id. """ if self.is_async: self.__loadSessionsAsync(callback, bare_jid, device_ids, {}) else: return self.__loadSessionsSync(bare_jid, device_ids)
[ "def", "loadSessions", "(", "self", ",", "callback", ",", "bare_jid", ",", "device_ids", ")", ":", "if", "self", ".", "is_async", ":", "self", ".", "__loadSessionsAsync", "(", "callback", ",", "bare_jid", ",", "device_ids", ",", "{", "}", ")", "else", ":...
Return a dict containing the session for each device id. By default, this method calls loadSession for each device id.
[ "Return", "a", "dict", "containing", "the", "session", "for", "each", "device", "id", ".", "By", "default", "this", "method", "calls", "loadSession", "for", "each", "device", "id", "." ]
f99be4715a3fad4d3082f5093aceb2c42385b8bd
https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/storage.py#L88-L97
train
46,803
Syndace/python-omemo
omemo/storage.py
Storage.loadTrusts
def loadTrusts(self, callback, bare_jid, device_ids): """ Return a dict containing the trust status for each device id. By default, this method calls loadTrust for each device id. """ if self.is_async: self.__loadTrustsAsync(callback, bare_jid, device_ids, {}) else: return self.__loadTrustsSync(bare_jid, device_ids)
python
def loadTrusts(self, callback, bare_jid, device_ids): """ Return a dict containing the trust status for each device id. By default, this method calls loadTrust for each device id. """ if self.is_async: self.__loadTrustsAsync(callback, bare_jid, device_ids, {}) else: return self.__loadTrustsSync(bare_jid, device_ids)
[ "def", "loadTrusts", "(", "self", ",", "callback", ",", "bare_jid", ",", "device_ids", ")", ":", "if", "self", ".", "is_async", ":", "self", ".", "__loadTrustsAsync", "(", "callback", ",", "bare_jid", ",", "device_ids", ",", "{", "}", ")", "else", ":", ...
Return a dict containing the trust status for each device id. By default, this method calls loadTrust for each device id.
[ "Return", "a", "dict", "containing", "the", "trust", "status", "for", "each", "device", "id", ".", "By", "default", "this", "method", "calls", "loadTrust", "for", "each", "device", "id", "." ]
f99be4715a3fad4d3082f5093aceb2c42385b8bd
https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/storage.py#L205-L214
train
46,804
Syndace/python-omemo
omemo/extendedpublicbundle.py
ExtendedPublicBundle.parse
def parse(cls, backend, ik, spk, spk_signature, otpks): """ Use this method when creating a bundle from data you retrieved directly from some PEP node. This method applies an additional decoding step to the public keys in the bundle. Pass the same structure as the constructor expects. """ ik = backend.decodePublicKey(ik)[0] spk["key"] = backend.decodePublicKey(spk["key"])[0] otpks = list(map(lambda otpk: { "key" : backend.decodePublicKey(otpk["key"])[0], "id" : otpk["id"] }, otpks)) return cls(ik, spk, spk_signature, otpks)
python
def parse(cls, backend, ik, spk, spk_signature, otpks): """ Use this method when creating a bundle from data you retrieved directly from some PEP node. This method applies an additional decoding step to the public keys in the bundle. Pass the same structure as the constructor expects. """ ik = backend.decodePublicKey(ik)[0] spk["key"] = backend.decodePublicKey(spk["key"])[0] otpks = list(map(lambda otpk: { "key" : backend.decodePublicKey(otpk["key"])[0], "id" : otpk["id"] }, otpks)) return cls(ik, spk, spk_signature, otpks)
[ "def", "parse", "(", "cls", ",", "backend", ",", "ik", ",", "spk", ",", "spk_signature", ",", "otpks", ")", ":", "ik", "=", "backend", ".", "decodePublicKey", "(", "ik", ")", "[", "0", "]", "spk", "[", "\"key\"", "]", "=", "backend", ".", "decodePu...
Use this method when creating a bundle from data you retrieved directly from some PEP node. This method applies an additional decoding step to the public keys in the bundle. Pass the same structure as the constructor expects.
[ "Use", "this", "method", "when", "creating", "a", "bundle", "from", "data", "you", "retrieved", "directly", "from", "some", "PEP", "node", ".", "This", "method", "applies", "an", "additional", "decoding", "step", "to", "the", "public", "keys", "in", "the", ...
f99be4715a3fad4d3082f5093aceb2c42385b8bd
https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/extendedpublicbundle.py#L38-L54
train
46,805
Syndace/python-omemo
omemo/extendedpublicbundle.py
ExtendedPublicBundle.serialize
def serialize(self, backend): """ Use this method to prepare the data to be uploaded directly to some PEP node. This method applies an additional encoding step to the public keys in the bundle. The result is a dictionary with the keys ik, spk, spk_signature and otpks. The values are structured the same way as the inputs of the constructor. """ return { "ik": backend.encodePublicKey(self.ik, "25519"), "spk": { "id" : self.spk["id"], "key" : backend.encodePublicKey(self.spk["key"], "25519"), }, "spk_signature": self.spk_signature, "otpks": list(map(lambda otpk: { "id" : otpk["id"], "key" : backend.encodePublicKey(otpk["key"], "25519") }, self.otpks)) }
python
def serialize(self, backend): """ Use this method to prepare the data to be uploaded directly to some PEP node. This method applies an additional encoding step to the public keys in the bundle. The result is a dictionary with the keys ik, spk, spk_signature and otpks. The values are structured the same way as the inputs of the constructor. """ return { "ik": backend.encodePublicKey(self.ik, "25519"), "spk": { "id" : self.spk["id"], "key" : backend.encodePublicKey(self.spk["key"], "25519"), }, "spk_signature": self.spk_signature, "otpks": list(map(lambda otpk: { "id" : otpk["id"], "key" : backend.encodePublicKey(otpk["key"], "25519") }, self.otpks)) }
[ "def", "serialize", "(", "self", ",", "backend", ")", ":", "return", "{", "\"ik\"", ":", "backend", ".", "encodePublicKey", "(", "self", ".", "ik", ",", "\"25519\"", ")", ",", "\"spk\"", ":", "{", "\"id\"", ":", "self", ".", "spk", "[", "\"id\"", "]"...
Use this method to prepare the data to be uploaded directly to some PEP node. This method applies an additional encoding step to the public keys in the bundle. The result is a dictionary with the keys ik, spk, spk_signature and otpks. The values are structured the same way as the inputs of the constructor.
[ "Use", "this", "method", "to", "prepare", "the", "data", "to", "be", "uploaded", "directly", "to", "some", "PEP", "node", ".", "This", "method", "applies", "an", "additional", "encoding", "step", "to", "the", "public", "keys", "in", "the", "bundle", ".", ...
f99be4715a3fad4d3082f5093aceb2c42385b8bd
https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/extendedpublicbundle.py#L56-L75
train
46,806
pjmark/NIMPA
niftypet/nimpa/prc/regseg.py
imfill
def imfill(immsk): '''fill the empty patches of image mask 'immsk' ''' for iz in range(immsk.shape[0]): for iy in range(immsk.shape[1]): ix0 = np.argmax(immsk[iz,iy,:]>0) ix1 = immsk.shape[2] - np.argmax(immsk[iz,iy,::-1]>0) if (ix1-ix0) > immsk.shape[2]-10: continue immsk[iz,iy,ix0:ix1] = 1 return immsk
python
def imfill(immsk): '''fill the empty patches of image mask 'immsk' ''' for iz in range(immsk.shape[0]): for iy in range(immsk.shape[1]): ix0 = np.argmax(immsk[iz,iy,:]>0) ix1 = immsk.shape[2] - np.argmax(immsk[iz,iy,::-1]>0) if (ix1-ix0) > immsk.shape[2]-10: continue immsk[iz,iy,ix0:ix1] = 1 return immsk
[ "def", "imfill", "(", "immsk", ")", ":", "for", "iz", "in", "range", "(", "immsk", ".", "shape", "[", "0", "]", ")", ":", "for", "iy", "in", "range", "(", "immsk", ".", "shape", "[", "1", "]", ")", ":", "ix0", "=", "np", ".", "argmax", "(", ...
fill the empty patches of image mask 'immsk'
[ "fill", "the", "empty", "patches", "of", "image", "mask", "immsk" ]
3f4231fed2934a1d92e4cd8e9e153b0118e29d86
https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/regseg.py#L22-L31
train
46,807
pjmark/NIMPA
niftypet/nimpa/prc/regseg.py
create_mask
def create_mask( fnii, fimout = '', outpath = '', fill = 1, dtype_fill = np.uint8, thrsh = 0., fwhm = 0.,): ''' create mask over the whole image or over the threshold area''' #> output path if outpath=='' and fimout!='': opth = os.path.dirname(fimout) if opth=='': opth = os.path.dirname(fnii) fimout = os.path.join(opth, fimout) elif outpath=='': opth = os.path.dirname(fnii) else: opth = outpath #> output file name if not given if fimout=='': fniis = os.path.split(fnii) fimout = os.path.join(opth, fniis[1].split('.nii')[0]+'_mask.nii.gz') niidct = imio.getnii(fnii, output='all') im = niidct['im'] hdr = niidct['hdr'] if im.ndim>3: raise ValueError('The masking function only accepts 3-D images.') #> generate output image if thrsh>0.: smoim = ndi.filters.gaussian_filter( im, imio.fwhm2sig(fwhm, voxsize=abs(hdr['pixdim'][1])), mode='mirror') thrsh = thrsh*smoim.max() immsk = np.int8(smoim>thrsh) immsk = imfill(immsk) #> output image imo = fill * immsk.astype(dtype_fill) else: imo = fill * np.ones(im.shape, dtype = dtype_fill) #> save output image imio.array2nii( imo, niidct['affine'], fimout, trnsp = (niidct['transpose'].index(0), niidct['transpose'].index(1), niidct['transpose'].index(2)), flip = niidct['flip']) return {'fim':fimout, 'im':imo}
python
def create_mask( fnii, fimout = '', outpath = '', fill = 1, dtype_fill = np.uint8, thrsh = 0., fwhm = 0.,): ''' create mask over the whole image or over the threshold area''' #> output path if outpath=='' and fimout!='': opth = os.path.dirname(fimout) if opth=='': opth = os.path.dirname(fnii) fimout = os.path.join(opth, fimout) elif outpath=='': opth = os.path.dirname(fnii) else: opth = outpath #> output file name if not given if fimout=='': fniis = os.path.split(fnii) fimout = os.path.join(opth, fniis[1].split('.nii')[0]+'_mask.nii.gz') niidct = imio.getnii(fnii, output='all') im = niidct['im'] hdr = niidct['hdr'] if im.ndim>3: raise ValueError('The masking function only accepts 3-D images.') #> generate output image if thrsh>0.: smoim = ndi.filters.gaussian_filter( im, imio.fwhm2sig(fwhm, voxsize=abs(hdr['pixdim'][1])), mode='mirror') thrsh = thrsh*smoim.max() immsk = np.int8(smoim>thrsh) immsk = imfill(immsk) #> output image imo = fill * immsk.astype(dtype_fill) else: imo = fill * np.ones(im.shape, dtype = dtype_fill) #> save output image imio.array2nii( imo, niidct['affine'], fimout, trnsp = (niidct['transpose'].index(0), niidct['transpose'].index(1), niidct['transpose'].index(2)), flip = niidct['flip']) return {'fim':fimout, 'im':imo}
[ "def", "create_mask", "(", "fnii", ",", "fimout", "=", "''", ",", "outpath", "=", "''", ",", "fill", "=", "1", ",", "dtype_fill", "=", "np", ".", "uint8", ",", "thrsh", "=", "0.", ",", "fwhm", "=", "0.", ",", ")", ":", "#> output path", "if", "ou...
create mask over the whole image or over the threshold area
[ "create", "mask", "over", "the", "whole", "image", "or", "over", "the", "threshold", "area" ]
3f4231fed2934a1d92e4cd8e9e153b0118e29d86
https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/regseg.py#L38-L103
train
46,808
MisterWil/skybellpy
skybellpy/utils.py
gen_token
def gen_token(): """Generate a new Skybellpy token.""" return ''.join( random.choice( string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(32))
python
def gen_token(): """Generate a new Skybellpy token.""" return ''.join( random.choice( string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(32))
[ "def", "gen_token", "(", ")", ":", "return", "''", ".", "join", "(", "random", ".", "choice", "(", "string", ".", "ascii_uppercase", "+", "string", ".", "ascii_lowercase", "+", "string", ".", "digits", ")", "for", "_", "in", "range", "(", "32", ")", ...
Generate a new Skybellpy token.
[ "Generate", "a", "new", "Skybellpy", "token", "." ]
ac966d9f590cda7654f6de7eecc94e2103459eef
https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/utils.py#L25-L30
train
46,809
MisterWil/skybellpy
skybellpy/device.py
_validate_setting
def _validate_setting(setting, value): """Validate the setting and value.""" if setting not in CONST.ALL_SETTINGS: raise SkybellException(ERROR.INVALID_SETTING, setting) if setting == CONST.SETTINGS_DO_NOT_DISTURB: if value not in CONST.SETTINGS_DO_NOT_DISTURB_VALUES: raise SkybellException(ERROR.INVALID_SETTING_VALUE, (setting, value)) if setting == CONST.SETTINGS_OUTDOOR_CHIME: if value not in CONST.SETTINGS_OUTDOOR_CHIME_VALUES: raise SkybellException(ERROR.INVALID_SETTING_VALUE, (setting, value)) if setting == CONST.SETTINGS_MOTION_POLICY: if value not in CONST.SETTINGS_MOTION_POLICY_VALUES: raise SkybellException(ERROR.INVALID_SETTING_VALUE, (setting, value)) if setting == CONST.SETTINGS_MOTION_THRESHOLD: if value not in CONST.SETTINGS_MOTION_THRESHOLD_VALUES: raise SkybellException(ERROR.INVALID_SETTING_VALUE, (setting, value)) if setting == CONST.SETTINGS_VIDEO_PROFILE: if value not in CONST.SETTINGS_VIDEO_PROFILE_VALUES: raise SkybellException(ERROR.INVALID_SETTING_VALUE, (setting, value)) if setting in CONST.SETTINGS_LED_COLOR: if (value < CONST.SETTINGS_LED_VALUES[0] or value > CONST.SETTINGS_LED_VALUES[1]): raise SkybellException(ERROR.INVALID_SETTING_VALUE, (setting, value)) if setting == CONST.SETTINGS_LED_INTENSITY: if not isinstance(value, int): raise SkybellException(ERROR.COLOR_INTENSITY_NOT_VALID, value) if (value < CONST.SETTINGS_LED_INTENSITY_VALUES[0] or value > CONST.SETTINGS_LED_INTENSITY_VALUES[1]): raise SkybellException(ERROR.INVALID_SETTING_VALUE, (setting, value))
python
def _validate_setting(setting, value): """Validate the setting and value.""" if setting not in CONST.ALL_SETTINGS: raise SkybellException(ERROR.INVALID_SETTING, setting) if setting == CONST.SETTINGS_DO_NOT_DISTURB: if value not in CONST.SETTINGS_DO_NOT_DISTURB_VALUES: raise SkybellException(ERROR.INVALID_SETTING_VALUE, (setting, value)) if setting == CONST.SETTINGS_OUTDOOR_CHIME: if value not in CONST.SETTINGS_OUTDOOR_CHIME_VALUES: raise SkybellException(ERROR.INVALID_SETTING_VALUE, (setting, value)) if setting == CONST.SETTINGS_MOTION_POLICY: if value not in CONST.SETTINGS_MOTION_POLICY_VALUES: raise SkybellException(ERROR.INVALID_SETTING_VALUE, (setting, value)) if setting == CONST.SETTINGS_MOTION_THRESHOLD: if value not in CONST.SETTINGS_MOTION_THRESHOLD_VALUES: raise SkybellException(ERROR.INVALID_SETTING_VALUE, (setting, value)) if setting == CONST.SETTINGS_VIDEO_PROFILE: if value not in CONST.SETTINGS_VIDEO_PROFILE_VALUES: raise SkybellException(ERROR.INVALID_SETTING_VALUE, (setting, value)) if setting in CONST.SETTINGS_LED_COLOR: if (value < CONST.SETTINGS_LED_VALUES[0] or value > CONST.SETTINGS_LED_VALUES[1]): raise SkybellException(ERROR.INVALID_SETTING_VALUE, (setting, value)) if setting == CONST.SETTINGS_LED_INTENSITY: if not isinstance(value, int): raise SkybellException(ERROR.COLOR_INTENSITY_NOT_VALID, value) if (value < CONST.SETTINGS_LED_INTENSITY_VALUES[0] or value > CONST.SETTINGS_LED_INTENSITY_VALUES[1]): raise SkybellException(ERROR.INVALID_SETTING_VALUE, (setting, value))
[ "def", "_validate_setting", "(", "setting", ",", "value", ")", ":", "if", "setting", "not", "in", "CONST", ".", "ALL_SETTINGS", ":", "raise", "SkybellException", "(", "ERROR", ".", "INVALID_SETTING", ",", "setting", ")", "if", "setting", "==", "CONST", ".", ...
Validate the setting and value.
[ "Validate", "the", "setting", "and", "value", "." ]
ac966d9f590cda7654f6de7eecc94e2103459eef
https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/device.py#L342-L385
train
46,810
MisterWil/skybellpy
skybellpy/device.py
SkybellDevice.update
def update(self, device_json=None, info_json=None, settings_json=None, avatar_json=None): """Update the internal device json data.""" if device_json: UTILS.update(self._device_json, device_json) if avatar_json: UTILS.update(self._avatar_json, avatar_json) if info_json: UTILS.update(self._info_json, info_json) if settings_json: UTILS.update(self._settings_json, settings_json)
python
def update(self, device_json=None, info_json=None, settings_json=None, avatar_json=None): """Update the internal device json data.""" if device_json: UTILS.update(self._device_json, device_json) if avatar_json: UTILS.update(self._avatar_json, avatar_json) if info_json: UTILS.update(self._info_json, info_json) if settings_json: UTILS.update(self._settings_json, settings_json)
[ "def", "update", "(", "self", ",", "device_json", "=", "None", ",", "info_json", "=", "None", ",", "settings_json", "=", "None", ",", "avatar_json", "=", "None", ")", ":", "if", "device_json", ":", "UTILS", ".", "update", "(", "self", ".", "_device_json"...
Update the internal device json data.
[ "Update", "the", "internal", "device", "json", "data", "." ]
ac966d9f590cda7654f6de7eecc94e2103459eef
https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/device.py#L85-L98
train
46,811
MisterWil/skybellpy
skybellpy/device.py
SkybellDevice._update_activities
def _update_activities(self): """Update stored activities and update caches as required.""" self._activities = self._activities_request() _LOGGER.debug("Device Activities Response: %s", self._activities) if not self._activities: self._activities = [] elif not isinstance(self._activities, (list, tuple)): self._activities = [self._activities] self._update_events()
python
def _update_activities(self): """Update stored activities and update caches as required.""" self._activities = self._activities_request() _LOGGER.debug("Device Activities Response: %s", self._activities) if not self._activities: self._activities = [] elif not isinstance(self._activities, (list, tuple)): self._activities = [self._activities] self._update_events()
[ "def", "_update_activities", "(", "self", ")", ":", "self", ".", "_activities", "=", "self", ".", "_activities_request", "(", ")", "_LOGGER", ".", "debug", "(", "\"Device Activities Response: %s\"", ",", "self", ".", "_activities", ")", "if", "not", "self", "....
Update stored activities and update caches as required.
[ "Update", "stored", "activities", "and", "update", "caches", "as", "required", "." ]
ac966d9f590cda7654f6de7eecc94e2103459eef
https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/device.py#L100-L110
train
46,812
MisterWil/skybellpy
skybellpy/device.py
SkybellDevice._update_events
def _update_events(self): """Update our cached list of latest activity events.""" events = self._skybell.dev_cache(self, CONST.EVENT) or {} for activity in self._activities: event = activity.get(CONST.EVENT) created_at = activity.get(CONST.CREATED_AT) old_event = events.get(event) if old_event and created_at < old_event.get(CONST.CREATED_AT): continue else: events[event] = activity self._skybell.update_dev_cache( self, { CONST.EVENT: events })
python
def _update_events(self): """Update our cached list of latest activity events.""" events = self._skybell.dev_cache(self, CONST.EVENT) or {} for activity in self._activities: event = activity.get(CONST.EVENT) created_at = activity.get(CONST.CREATED_AT) old_event = events.get(event) if old_event and created_at < old_event.get(CONST.CREATED_AT): continue else: events[event] = activity self._skybell.update_dev_cache( self, { CONST.EVENT: events })
[ "def", "_update_events", "(", "self", ")", ":", "events", "=", "self", ".", "_skybell", ".", "dev_cache", "(", "self", ",", "CONST", ".", "EVENT", ")", "or", "{", "}", "for", "activity", "in", "self", ".", "_activities", ":", "event", "=", "activity", ...
Update our cached list of latest activity events.
[ "Update", "our", "cached", "list", "of", "latest", "activity", "events", "." ]
ac966d9f590cda7654f6de7eecc94e2103459eef
https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/device.py#L112-L131
train
46,813
MisterWil/skybellpy
skybellpy/device.py
SkybellDevice.activities
def activities(self, limit=1, event=None): """Return device activity information.""" activities = self._activities or [] # Filter our activity array if requested if event: activities = list( filter( lambda activity: activity[CONST.EVENT] == event, activities)) # Return the requested number return activities[:limit]
python
def activities(self, limit=1, event=None): """Return device activity information.""" activities = self._activities or [] # Filter our activity array if requested if event: activities = list( filter( lambda activity: activity[CONST.EVENT] == event, activities)) # Return the requested number return activities[:limit]
[ "def", "activities", "(", "self", ",", "limit", "=", "1", ",", "event", "=", "None", ")", ":", "activities", "=", "self", ".", "_activities", "or", "[", "]", "# Filter our activity array if requested", "if", "event", ":", "activities", "=", "list", "(", "f...
Return device activity information.
[ "Return", "device", "activity", "information", "." ]
ac966d9f590cda7654f6de7eecc94e2103459eef
https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/device.py#L133-L145
train
46,814
MisterWil/skybellpy
skybellpy/device.py
SkybellDevice._set_setting
def _set_setting(self, settings): """Validate the settings and then send the PATCH request.""" for key, value in settings.items(): _validate_setting(key, value) try: self._settings_request(method="patch", json_data=settings) self.update(settings_json=settings) except SkybellException as exc: _LOGGER.warning("Exception changing settings: %s", settings) _LOGGER.warning(exc)
python
def _set_setting(self, settings): """Validate the settings and then send the PATCH request.""" for key, value in settings.items(): _validate_setting(key, value) try: self._settings_request(method="patch", json_data=settings) self.update(settings_json=settings) except SkybellException as exc: _LOGGER.warning("Exception changing settings: %s", settings) _LOGGER.warning(exc)
[ "def", "_set_setting", "(", "self", ",", "settings", ")", ":", "for", "key", ",", "value", "in", "settings", ".", "items", "(", ")", ":", "_validate_setting", "(", "key", ",", "value", ")", "try", ":", "self", ".", "_settings_request", "(", "method", "...
Validate the settings and then send the PATCH request.
[ "Validate", "the", "settings", "and", "then", "send", "the", "PATCH", "request", "." ]
ac966d9f590cda7654f6de7eecc94e2103459eef
https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/device.py#L162-L173
train
46,815
MisterWil/skybellpy
skybellpy/device.py
SkybellDevice.location
def location(self): """Return lat and lng tuple.""" location = self._device_json.get(CONST.LOCATION, {}) return (location.get(CONST.LOCATION_LAT, 0), location.get(CONST.LOCATION_LNG, 0))
python
def location(self): """Return lat and lng tuple.""" location = self._device_json.get(CONST.LOCATION, {}) return (location.get(CONST.LOCATION_LAT, 0), location.get(CONST.LOCATION_LNG, 0))
[ "def", "location", "(", "self", ")", ":", "location", "=", "self", ".", "_device_json", ".", "get", "(", "CONST", ".", "LOCATION", ",", "{", "}", ")", "return", "(", "location", ".", "get", "(", "CONST", ".", "LOCATION_LAT", ",", "0", ")", ",", "lo...
Return lat and lng tuple.
[ "Return", "lat", "and", "lng", "tuple", "." ]
ac966d9f590cda7654f6de7eecc94e2103459eef
https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/device.py#L201-L206
train
46,816
MisterWil/skybellpy
skybellpy/device.py
SkybellDevice.wifi_status
def wifi_status(self): """Get the wifi status.""" return self._info_json.get(CONST.STATUS, {}).get(CONST.WIFI_LINK)
python
def wifi_status(self): """Get the wifi status.""" return self._info_json.get(CONST.STATUS, {}).get(CONST.WIFI_LINK)
[ "def", "wifi_status", "(", "self", ")", ":", "return", "self", ".", "_info_json", ".", "get", "(", "CONST", ".", "STATUS", ",", "{", "}", ")", ".", "get", "(", "CONST", ".", "WIFI_LINK", ")" ]
Get the wifi status.
[ "Get", "the", "wifi", "status", "." ]
ac966d9f590cda7654f6de7eecc94e2103459eef
https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/device.py#L219-L221
train
46,817
MisterWil/skybellpy
skybellpy/device.py
SkybellDevice.do_not_disturb
def do_not_disturb(self): """Get if do not disturb is enabled.""" return bool(strtobool(str(self._settings_json.get( CONST.SETTINGS_DO_NOT_DISTURB))))
python
def do_not_disturb(self): """Get if do not disturb is enabled.""" return bool(strtobool(str(self._settings_json.get( CONST.SETTINGS_DO_NOT_DISTURB))))
[ "def", "do_not_disturb", "(", "self", ")", ":", "return", "bool", "(", "strtobool", "(", "str", "(", "self", ".", "_settings_json", ".", "get", "(", "CONST", ".", "SETTINGS_DO_NOT_DISTURB", ")", ")", ")", ")" ]
Get if do not disturb is enabled.
[ "Get", "if", "do", "not", "disturb", "is", "enabled", "." ]
ac966d9f590cda7654f6de7eecc94e2103459eef
https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/device.py#L234-L237
train
46,818
MisterWil/skybellpy
skybellpy/device.py
SkybellDevice.do_not_disturb
def do_not_disturb(self, enabled): """Set do not disturb.""" self._set_setting( { CONST.SETTINGS_DO_NOT_DISTURB: str(enabled).lower() })
python
def do_not_disturb(self, enabled): """Set do not disturb.""" self._set_setting( { CONST.SETTINGS_DO_NOT_DISTURB: str(enabled).lower() })
[ "def", "do_not_disturb", "(", "self", ",", "enabled", ")", ":", "self", ".", "_set_setting", "(", "{", "CONST", ".", "SETTINGS_DO_NOT_DISTURB", ":", "str", "(", "enabled", ")", ".", "lower", "(", ")", "}", ")" ]
Set do not disturb.
[ "Set", "do", "not", "disturb", "." ]
ac966d9f590cda7654f6de7eecc94e2103459eef
https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/device.py#L240-L245
train
46,819
MisterWil/skybellpy
skybellpy/device.py
SkybellDevice.motion_sensor
def motion_sensor(self, enabled): """Set the motion sensor state.""" if enabled is True: value = CONST.SETTINGS_MOTION_POLICY_ON elif enabled is False: value = CONST.SETTINGS_MOTION_POLICY_OFF else: raise SkybellException(ERROR.INVALID_SETTING_VALUE, (CONST.SETTINGS_MOTION_POLICY, enabled)) self._set_setting({CONST.SETTINGS_MOTION_POLICY: value})
python
def motion_sensor(self, enabled): """Set the motion sensor state.""" if enabled is True: value = CONST.SETTINGS_MOTION_POLICY_ON elif enabled is False: value = CONST.SETTINGS_MOTION_POLICY_OFF else: raise SkybellException(ERROR.INVALID_SETTING_VALUE, (CONST.SETTINGS_MOTION_POLICY, enabled)) self._set_setting({CONST.SETTINGS_MOTION_POLICY: value})
[ "def", "motion_sensor", "(", "self", ",", "enabled", ")", ":", "if", "enabled", "is", "True", ":", "value", "=", "CONST", ".", "SETTINGS_MOTION_POLICY_ON", "elif", "enabled", "is", "False", ":", "value", "=", "CONST", ".", "SETTINGS_MOTION_POLICY_OFF", "else",...
Set the motion sensor state.
[ "Set", "the", "motion", "sensor", "state", "." ]
ac966d9f590cda7654f6de7eecc94e2103459eef
https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/device.py#L270-L280
train
46,820
MisterWil/skybellpy
skybellpy/device.py
SkybellDevice.led_rgb
def led_rgb(self): """Get devices LED color.""" return (int(self._settings_json.get(CONST.SETTINGS_LED_R)), int(self._settings_json.get(CONST.SETTINGS_LED_G)), int(self._settings_json.get(CONST.SETTINGS_LED_B)))
python
def led_rgb(self): """Get devices LED color.""" return (int(self._settings_json.get(CONST.SETTINGS_LED_R)), int(self._settings_json.get(CONST.SETTINGS_LED_G)), int(self._settings_json.get(CONST.SETTINGS_LED_B)))
[ "def", "led_rgb", "(", "self", ")", ":", "return", "(", "int", "(", "self", ".", "_settings_json", ".", "get", "(", "CONST", ".", "SETTINGS_LED_R", ")", ")", ",", "int", "(", "self", ".", "_settings_json", ".", "get", "(", "CONST", ".", "SETTINGS_LED_G...
Get devices LED color.
[ "Get", "devices", "LED", "color", "." ]
ac966d9f590cda7654f6de7eecc94e2103459eef
https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/device.py#L303-L307
train
46,821
MisterWil/skybellpy
skybellpy/device.py
SkybellDevice.led_rgb
def led_rgb(self, color): """Set devices LED color.""" if (not isinstance(color, (list, tuple)) or not all(isinstance(item, int) for item in color)): raise SkybellException(ERROR.COLOR_VALUE_NOT_VALID, color) self._set_setting( { CONST.SETTINGS_LED_R: color[0], CONST.SETTINGS_LED_G: color[1], CONST.SETTINGS_LED_B: color[2] })
python
def led_rgb(self, color): """Set devices LED color.""" if (not isinstance(color, (list, tuple)) or not all(isinstance(item, int) for item in color)): raise SkybellException(ERROR.COLOR_VALUE_NOT_VALID, color) self._set_setting( { CONST.SETTINGS_LED_R: color[0], CONST.SETTINGS_LED_G: color[1], CONST.SETTINGS_LED_B: color[2] })
[ "def", "led_rgb", "(", "self", ",", "color", ")", ":", "if", "(", "not", "isinstance", "(", "color", ",", "(", "list", ",", "tuple", ")", ")", "or", "not", "all", "(", "isinstance", "(", "item", ",", "int", ")", "for", "item", "in", "color", ")",...
Set devices LED color.
[ "Set", "devices", "LED", "color", "." ]
ac966d9f590cda7654f6de7eecc94e2103459eef
https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/device.py#L310-L321
train
46,822
sdss/sdss_access
python/sdss_access/sync/http.py
HttpAccess.get
def get(self, filetype, **kwargs): """Returns file name, downloading if remote access configured. Parameters ---------- filetype : str type of file keyword arguments : keywords to fully specify path Notes ----- Path templates are defined in $DIMAGE_DIR/data/dimage_paths.ini """ path = self.full(filetype, **kwargs) if path: if self._remote: self.download_url_to_path(self.url(filetype, **kwargs), path) else: print("There is no file with filetype=%r to access in the tree module loaded" % filetype)
python
def get(self, filetype, **kwargs): """Returns file name, downloading if remote access configured. Parameters ---------- filetype : str type of file keyword arguments : keywords to fully specify path Notes ----- Path templates are defined in $DIMAGE_DIR/data/dimage_paths.ini """ path = self.full(filetype, **kwargs) if path: if self._remote: self.download_url_to_path(self.url(filetype, **kwargs), path) else: print("There is no file with filetype=%r to access in the tree module loaded" % filetype)
[ "def", "get", "(", "self", ",", "filetype", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "full", "(", "filetype", ",", "*", "*", "kwargs", ")", "if", "path", ":", "if", "self", ".", "_remote", ":", "self", ".", "download_url_to_path...
Returns file name, downloading if remote access configured. Parameters ---------- filetype : str type of file keyword arguments : keywords to fully specify path Notes ----- Path templates are defined in $DIMAGE_DIR/data/dimage_paths.ini
[ "Returns", "file", "name", "downloading", "if", "remote", "access", "configured", "." ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/sync/http.py#L63-L85
train
46,823
sdss/sdss_access
python/sdss_access/sync/http.py
HttpAccess.download_url_to_path
def download_url_to_path(self, url, path, force=False): """ Download a file from url via http, and put it at path Parameters ---------- url : str URL of file to download path : str local path to put file in """ path_exists = isfile(path) if not path_exists or force: dir = dirname(path) if not exists(dir): if self.verbose: print("CREATE %s" % dir) makedirs(dir) try: u = urlopen(url) except HTTPError as e: u = None print("HTTP error code %r. Please check you ~/.netrc has the correct authorization" % e.code) if u: with open(path, 'wb') as file: meta = u.info() meta_func = meta.getheaders \ if hasattr(meta, 'getheaders') else meta.get_all meta_length = meta_func("Content-Length") file_size = None if meta_length: file_size = int(meta_length[0]) if self.verbose: print("Downloading: {0} Bytes: {1}".format(url, file_size)) file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break file_size_dl += len(buffer) file.write(buffer) if self.verbose: if path_exists: print("OVERWRITING %s" % path) else: print("CREATE %s" % path) elif self.verbose: print("FOUND %s (already downloaded)" % path)
python
def download_url_to_path(self, url, path, force=False): """ Download a file from url via http, and put it at path Parameters ---------- url : str URL of file to download path : str local path to put file in """ path_exists = isfile(path) if not path_exists or force: dir = dirname(path) if not exists(dir): if self.verbose: print("CREATE %s" % dir) makedirs(dir) try: u = urlopen(url) except HTTPError as e: u = None print("HTTP error code %r. Please check you ~/.netrc has the correct authorization" % e.code) if u: with open(path, 'wb') as file: meta = u.info() meta_func = meta.getheaders \ if hasattr(meta, 'getheaders') else meta.get_all meta_length = meta_func("Content-Length") file_size = None if meta_length: file_size = int(meta_length[0]) if self.verbose: print("Downloading: {0} Bytes: {1}".format(url, file_size)) file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break file_size_dl += len(buffer) file.write(buffer) if self.verbose: if path_exists: print("OVERWRITING %s" % path) else: print("CREATE %s" % path) elif self.verbose: print("FOUND %s (already downloaded)" % path)
[ "def", "download_url_to_path", "(", "self", ",", "url", ",", "path", ",", "force", "=", "False", ")", ":", "path_exists", "=", "isfile", "(", "path", ")", "if", "not", "path_exists", "or", "force", ":", "dir", "=", "dirname", "(", "path", ")", "if", ...
Download a file from url via http, and put it at path Parameters ---------- url : str URL of file to download path : str local path to put file in
[ "Download", "a", "file", "from", "url", "via", "http", "and", "put", "it", "at", "path" ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/sync/http.py#L87-L144
train
46,824
sdss/sdss_access
python/sdss_access/sync/rsync.py
RsyncAccess.reset
def reset(self): ''' Reset all streams ''' # reset the main stream if self.stream: self.stream.reset() # reset the initial stream (otherwise old 'adds' remain in the new stream) if self.initial_stream: self.initial_stream.reset()
python
def reset(self): ''' Reset all streams ''' # reset the main stream if self.stream: self.stream.reset() # reset the initial stream (otherwise old 'adds' remain in the new stream) if self.initial_stream: self.initial_stream.reset()
[ "def", "reset", "(", "self", ")", ":", "# reset the main stream", "if", "self", ".", "stream", ":", "self", ".", "stream", ".", "reset", "(", ")", "# reset the initial stream (otherwise old 'adds' remain in the new stream)", "if", "self", ".", "initial_stream", ":", ...
Reset all streams
[ "Reset", "all", "streams" ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/sync/rsync.py#L47-L56
train
46,825
sdss/sdss_access
python/sdss_access/sync/rsync.py
RsyncAccess.add
def add(self, filetype, **kwargs): """ Adds a filepath into the list of tasks to download""" location = self.location(filetype, **kwargs) source = self.url(filetype, sasdir='sas' if not self.public else '', **kwargs) if 'full' not in kwargs: destination = self.full(filetype, **kwargs) else: destination = kwargs.get('full') if location and source and destination: self.initial_stream.append_task(location=location, source=source, destination=destination) else: print("There is no file with filetype=%r to access in the tree module loaded" % filetype)
python
def add(self, filetype, **kwargs): """ Adds a filepath into the list of tasks to download""" location = self.location(filetype, **kwargs) source = self.url(filetype, sasdir='sas' if not self.public else '', **kwargs) if 'full' not in kwargs: destination = self.full(filetype, **kwargs) else: destination = kwargs.get('full') if location and source and destination: self.initial_stream.append_task(location=location, source=source, destination=destination) else: print("There is no file with filetype=%r to access in the tree module loaded" % filetype)
[ "def", "add", "(", "self", ",", "filetype", ",", "*", "*", "kwargs", ")", ":", "location", "=", "self", ".", "location", "(", "filetype", ",", "*", "*", "kwargs", ")", "source", "=", "self", ".", "url", "(", "filetype", ",", "sasdir", "=", "'sas'",...
Adds a filepath into the list of tasks to download
[ "Adds", "a", "filepath", "into", "the", "list", "of", "tasks", "to", "download" ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/sync/rsync.py#L58-L71
train
46,826
sdss/sdss_access
python/sdss_access/sync/rsync.py
RsyncAccess.set_stream
def set_stream(self): """ Sets the download streams """ if not self.auth: raise AccessError("Please use the remote() method to set rsync authorization or use remote(public=True) for public data") elif not self.initial_stream.task: raise AccessError("No files to download.") else: self.stream = self.get_stream() self.stream.source = join(self.remote_base, 'sas') if self.remote_base and not self.public else join(self.remote_base, self.release) if self.release else self.remote_base self.stream.destination = join(self.base_dir, self.release) if self.public and self.release else self.base_dir self.stream.cli.env = {'RSYNC_PASSWORD': self.auth.password} if self.auth.ready() else None if self.stream.source and self.stream.destination: for task in self.initial_stream.task: self.set_stream_task(task) ntask = len(self.stream.task) if self.stream.stream_count > ntask: if self.verbose: print("SDSS_ACCESS> Reducing the number of streams from %r to %r, the number of download tasks." % (self.stream.stream_count, ntask)) self.stream.stream_count = ntask self.stream.streamlet = self.stream.streamlet[:ntask]
python
def set_stream(self): """ Sets the download streams """ if not self.auth: raise AccessError("Please use the remote() method to set rsync authorization or use remote(public=True) for public data") elif not self.initial_stream.task: raise AccessError("No files to download.") else: self.stream = self.get_stream() self.stream.source = join(self.remote_base, 'sas') if self.remote_base and not self.public else join(self.remote_base, self.release) if self.release else self.remote_base self.stream.destination = join(self.base_dir, self.release) if self.public and self.release else self.base_dir self.stream.cli.env = {'RSYNC_PASSWORD': self.auth.password} if self.auth.ready() else None if self.stream.source and self.stream.destination: for task in self.initial_stream.task: self.set_stream_task(task) ntask = len(self.stream.task) if self.stream.stream_count > ntask: if self.verbose: print("SDSS_ACCESS> Reducing the number of streams from %r to %r, the number of download tasks." % (self.stream.stream_count, ntask)) self.stream.stream_count = ntask self.stream.streamlet = self.stream.streamlet[:ntask]
[ "def", "set_stream", "(", "self", ")", ":", "if", "not", "self", ".", "auth", ":", "raise", "AccessError", "(", "\"Please use the remote() method to set rsync authorization or use remote(public=True) for public data\"", ")", "elif", "not", "self", ".", "initial_stream", "...
Sets the download streams
[ "Sets", "the", "download", "streams" ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/sync/rsync.py#L73-L93
train
46,827
sdss/sdss_access
python/sdss_access/sync/rsync.py
RsyncAccess.commit
def commit(self, offset=None, limit=None, dryrun=False): """ Start the rsync download """ self.stream.command = "rsync -avRK --files-from={path} {source} {destination}" self.stream.append_tasks_to_streamlets(offset=offset, limit=limit) self.stream.commit_streamlets() self.stream.run_streamlets() self.stream.reset_streamlet()
python
def commit(self, offset=None, limit=None, dryrun=False): """ Start the rsync download """ self.stream.command = "rsync -avRK --files-from={path} {source} {destination}" self.stream.append_tasks_to_streamlets(offset=offset, limit=limit) self.stream.commit_streamlets() self.stream.run_streamlets() self.stream.reset_streamlet()
[ "def", "commit", "(", "self", ",", "offset", "=", "None", ",", "limit", "=", "None", ",", "dryrun", "=", "False", ")", ":", "self", ".", "stream", ".", "command", "=", "\"rsync -avRK --files-from={path} {source} {destination}\"", "self", ".", "stream", ".", ...
Start the rsync download
[ "Start", "the", "rsync", "download" ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/sync/rsync.py#L160-L167
train
46,828
kpdyer/regex2dfa
third_party/re2/re2/make_unicode_groups.py
PrintRanges
def PrintRanges(type, name, ranges): """Print the ranges as an array of type named name.""" print "static const %s %s[] = {" % (type, name,) for lo, hi in ranges: print "\t{ %d, %d }," % (lo, hi) print "};"
python
def PrintRanges(type, name, ranges): """Print the ranges as an array of type named name.""" print "static const %s %s[] = {" % (type, name,) for lo, hi in ranges: print "\t{ %d, %d }," % (lo, hi) print "};"
[ "def", "PrintRanges", "(", "type", ",", "name", ",", "ranges", ")", ":", "print", "\"static const %s %s[] = {\"", "%", "(", "type", ",", "name", ",", ")", "for", "lo", ",", "hi", "in", "ranges", ":", "print", "\"\\t{ %d, %d },\"", "%", "(", "lo", ",", ...
Print the ranges as an array of type named name.
[ "Print", "the", "ranges", "as", "an", "array", "of", "type", "named", "name", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/re2/make_unicode_groups.py#L42-L47
train
46,829
kpdyer/regex2dfa
third_party/re2/re2/make_unicode_groups.py
PrintGroup
def PrintGroup(name, codes): """Print the data structures for the group of codes. Return a UGroup literal for the group.""" # See unicode_groups.h for a description of the data structure. # Split codes into 16-bit ranges and 32-bit ranges. range16 = MakeRanges([c for c in codes if c < 65536]) range32 = MakeRanges([c for c in codes if c >= 65536]) # Pull singleton ranges out of range16. # code16 = [lo for lo, hi in range16 if lo == hi] # range16 = [[lo, hi] for lo, hi in range16 if lo != hi] global n16 global n32 n16 += len(range16) n32 += len(range32) ugroup = "{ \"%s\", +1" % (name,) # if len(code16) > 0: # PrintCodes("uint16", name+"_code16", code16) # ugroup += ", %s_code16, %d" % (name, len(code16)) # else: # ugroup += ", 0, 0" if len(range16) > 0: PrintRanges("URange16", name+"_range16", range16) ugroup += ", %s_range16, %d" % (name, len(range16)) else: ugroup += ", 0, 0" if len(range32) > 0: PrintRanges("URange32", name+"_range32", range32) ugroup += ", %s_range32, %d" % (name, len(range32)) else: ugroup += ", 0, 0" ugroup += " }" return ugroup
python
def PrintGroup(name, codes): """Print the data structures for the group of codes. Return a UGroup literal for the group.""" # See unicode_groups.h for a description of the data structure. # Split codes into 16-bit ranges and 32-bit ranges. range16 = MakeRanges([c for c in codes if c < 65536]) range32 = MakeRanges([c for c in codes if c >= 65536]) # Pull singleton ranges out of range16. # code16 = [lo for lo, hi in range16 if lo == hi] # range16 = [[lo, hi] for lo, hi in range16 if lo != hi] global n16 global n32 n16 += len(range16) n32 += len(range32) ugroup = "{ \"%s\", +1" % (name,) # if len(code16) > 0: # PrintCodes("uint16", name+"_code16", code16) # ugroup += ", %s_code16, %d" % (name, len(code16)) # else: # ugroup += ", 0, 0" if len(range16) > 0: PrintRanges("URange16", name+"_range16", range16) ugroup += ", %s_range16, %d" % (name, len(range16)) else: ugroup += ", 0, 0" if len(range32) > 0: PrintRanges("URange32", name+"_range32", range32) ugroup += ", %s_range32, %d" % (name, len(range32)) else: ugroup += ", 0, 0" ugroup += " }" return ugroup
[ "def", "PrintGroup", "(", "name", ",", "codes", ")", ":", "# See unicode_groups.h for a description of the data structure.", "# Split codes into 16-bit ranges and 32-bit ranges.", "range16", "=", "MakeRanges", "(", "[", "c", "for", "c", "in", "codes", "if", "c", "<", "6...
Print the data structures for the group of codes. Return a UGroup literal for the group.
[ "Print", "the", "data", "structures", "for", "the", "group", "of", "codes", ".", "Return", "a", "UGroup", "literal", "for", "the", "group", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/re2/make_unicode_groups.py#L56-L92
train
46,830
sdss/sdss_access
python/sdss_access/path/path.py
BasePath._input_templates
def _input_templates(self): """Read the path template file. """ foo = self._config.read([self._pathfile]) if len(foo) == 1: for k, v in self._config.items('paths'): self.templates[k] = v else: raise ValueError("Could not read {0}!".format(self._pathfile)) return
python
def _input_templates(self): """Read the path template file. """ foo = self._config.read([self._pathfile]) if len(foo) == 1: for k, v in self._config.items('paths'): self.templates[k] = v else: raise ValueError("Could not read {0}!".format(self._pathfile)) return
[ "def", "_input_templates", "(", "self", ")", ":", "foo", "=", "self", ".", "_config", ".", "read", "(", "[", "self", ".", "_pathfile", "]", ")", "if", "len", "(", "foo", ")", "==", "1", ":", "for", "k", ",", "v", "in", "self", ".", "_config", "...
Read the path template file.
[ "Read", "the", "path", "template", "file", "." ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/path/path.py#L69-L78
train
46,831
sdss/sdss_access
python/sdss_access/path/path.py
BasePath.lookup_keys
def lookup_keys(self, name): ''' Lookup the keyword arguments needed for a given path name Parameters: name (str): The name of the path Returns: A list of keywords needed for filepath generation ''' assert name, 'Must specify a path name' assert name in self.templates.keys(), '{0} must be defined in the path templates'.format(name) # find all words inside brackets keys = list(set(re.findall(r'{(.*?)}', self.templates[name]))) # lookup any keys referenced inside special functions skeys = self._check_special_kwargs(name) keys.extend(skeys) # remove any duplicates keys = list(set(keys)) # remove the type : descriptor keys = [k.split(':')[0] for k in keys] return keys
python
def lookup_keys(self, name): ''' Lookup the keyword arguments needed for a given path name Parameters: name (str): The name of the path Returns: A list of keywords needed for filepath generation ''' assert name, 'Must specify a path name' assert name in self.templates.keys(), '{0} must be defined in the path templates'.format(name) # find all words inside brackets keys = list(set(re.findall(r'{(.*?)}', self.templates[name]))) # lookup any keys referenced inside special functions skeys = self._check_special_kwargs(name) keys.extend(skeys) # remove any duplicates keys = list(set(keys)) # remove the type : descriptor keys = [k.split(':')[0] for k in keys] return keys
[ "def", "lookup_keys", "(", "self", ",", "name", ")", ":", "assert", "name", ",", "'Must specify a path name'", "assert", "name", "in", "self", ".", "templates", ".", "keys", "(", ")", ",", "'{0} must be defined in the path templates'", ".", "format", "(", "name"...
Lookup the keyword arguments needed for a given path name Parameters: name (str): The name of the path Returns: A list of keywords needed for filepath generation
[ "Lookup", "the", "keyword", "arguments", "needed", "for", "a", "given", "path", "name" ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/path/path.py#L80-L103
train
46,832
sdss/sdss_access
python/sdss_access/path/path.py
BasePath._find_source
def _find_source(method): ''' find source code of a given method Find and extract the source code of a given method in a module. Uses inspect.findsource to get all source code and performs some selection magic to identify method source code. Doing it this way because inspect.getsource returns wrong method. Parameters: method (obj): A method object Returns: A string containing the source code of a given method Example: >>> from sdss_access.path import Path >>> path = Path() >>> path._find_source(path.full) ''' # get source code lines of entire module method is in source = inspect.findsource(method) is_method = inspect.ismethod(method) # create single source code string source_str = '\n'.join(source[0]) # define search pattern if is_method: pattern = r'def\s{0}\(self'.format(method.__name__) # search for pattern within the string start = re.search(pattern, source_str) if start: # find start and end positions of source code startpos = start.start() endpos = source_str.find('def ', startpos + 1) code = source_str[startpos:endpos] else: code = None return code
python
def _find_source(method): ''' find source code of a given method Find and extract the source code of a given method in a module. Uses inspect.findsource to get all source code and performs some selection magic to identify method source code. Doing it this way because inspect.getsource returns wrong method. Parameters: method (obj): A method object Returns: A string containing the source code of a given method Example: >>> from sdss_access.path import Path >>> path = Path() >>> path._find_source(path.full) ''' # get source code lines of entire module method is in source = inspect.findsource(method) is_method = inspect.ismethod(method) # create single source code string source_str = '\n'.join(source[0]) # define search pattern if is_method: pattern = r'def\s{0}\(self'.format(method.__name__) # search for pattern within the string start = re.search(pattern, source_str) if start: # find start and end positions of source code startpos = start.start() endpos = source_str.find('def ', startpos + 1) code = source_str[startpos:endpos] else: code = None return code
[ "def", "_find_source", "(", "method", ")", ":", "# get source code lines of entire module method is in", "source", "=", "inspect", ".", "findsource", "(", "method", ")", "is_method", "=", "inspect", ".", "ismethod", "(", "method", ")", "# create single source code strin...
find source code of a given method Find and extract the source code of a given method in a module. Uses inspect.findsource to get all source code and performs some selection magic to identify method source code. Doing it this way because inspect.getsource returns wrong method. Parameters: method (obj): A method object Returns: A string containing the source code of a given method Example: >>> from sdss_access.path import Path >>> path = Path() >>> path._find_source(path.full)
[ "find", "source", "code", "of", "a", "given", "method", "Find", "and", "extract", "the", "source", "code", "of", "a", "given", "method", "in", "a", "module", ".", "Uses", "inspect", ".", "findsource", "to", "get", "all", "source", "code", "and", "perform...
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/path/path.py#L137-L175
train
46,833
sdss/sdss_access
python/sdss_access/path/path.py
BasePath.extract
def extract(self, name, example): ''' Extract keywords from an example path ''' # if pathlib not available do nothing if not pathlib: return None # ensure example is a string if isinstance(example, pathlib.Path): example = str(example) assert isinstance(example, six.string_types), 'example file must be a string' # get the template assert name in self.lookup_names(), '{0} must be a valid template name'.format(name) template = self.templates[name] # expand the environment variable template = os.path.expandvars(template) # handle special functions; perform a drop in replacement if re.match('%spectrodir', template): template = re.sub('%spectrodir', os.environ['BOSS_SPECTRO_REDUX'], template) elif re.search('%platedir', template): template = re.sub('%platedir', '(.*)/{plateid:0>6}', template) elif re.search('%definitiondir', template): template = re.sub('%definitiondir', '{designid:0>6}', template) if re.search('%plateid6', template): template = re.sub('%plateid6', '{plateid:0>6}', template) # check if template has any brackets haskwargs = re.search('[{}]', template) if not haskwargs: return None # escape the envvar $ and any dots subtemp = template.replace('$', '\\$').replace('.', '\\.') # define search pattern; replace all template keywords with regex "(.*)" group research = re.sub('{(.*?)}', '(.*)', subtemp) # look for matches in template and example pmatch = re.search(research, template) tmatch = re.search(research, example) path_dict = {} # if example match extract keys and values from the match groups if tmatch: values = tmatch.groups(0) keys = pmatch.groups(0) assert len(keys) == len(values), 'pattern and template matches must have same length' parts = zip(keys, values) # parse into dictionary for part in parts: value = part[1] if re.findall('{(.*?)}', part[0]): # get the key name inside the brackets keys = re.findall('{(.*?)}', part[0]) # remove the type : designation keys = [k.split(':')[0] for k in keys] # handle double bracket edge cases; remove this when better solution found if len(keys) > 1: if keys[0] == 'dr': # for {dr}{version} drval = re.match('^DR[1-9][0-9]', value).group(0) otherval = value.split(drval)[-1] pdict = {keys[0]: drval, keys[1]: otherval} elif keys[0] in ['rc', 'br', 'filter', 'camrow']: # for {camrow}{camcol}, {filter}{camcol}, {br}{id}, etc pdict = {keys[0]: value[0], keys[1]: value[1:]} else: raise ValueError('This case has not yet been accounted for.') path_dict.update(pdict) else: path_dict[keys[0]] = value return path_dict
python
def extract(self, name, example): ''' Extract keywords from an example path ''' # if pathlib not available do nothing if not pathlib: return None # ensure example is a string if isinstance(example, pathlib.Path): example = str(example) assert isinstance(example, six.string_types), 'example file must be a string' # get the template assert name in self.lookup_names(), '{0} must be a valid template name'.format(name) template = self.templates[name] # expand the environment variable template = os.path.expandvars(template) # handle special functions; perform a drop in replacement if re.match('%spectrodir', template): template = re.sub('%spectrodir', os.environ['BOSS_SPECTRO_REDUX'], template) elif re.search('%platedir', template): template = re.sub('%platedir', '(.*)/{plateid:0>6}', template) elif re.search('%definitiondir', template): template = re.sub('%definitiondir', '{designid:0>6}', template) if re.search('%plateid6', template): template = re.sub('%plateid6', '{plateid:0>6}', template) # check if template has any brackets haskwargs = re.search('[{}]', template) if not haskwargs: return None # escape the envvar $ and any dots subtemp = template.replace('$', '\\$').replace('.', '\\.') # define search pattern; replace all template keywords with regex "(.*)" group research = re.sub('{(.*?)}', '(.*)', subtemp) # look for matches in template and example pmatch = re.search(research, template) tmatch = re.search(research, example) path_dict = {} # if example match extract keys and values from the match groups if tmatch: values = tmatch.groups(0) keys = pmatch.groups(0) assert len(keys) == len(values), 'pattern and template matches must have same length' parts = zip(keys, values) # parse into dictionary for part in parts: value = part[1] if re.findall('{(.*?)}', part[0]): # get the key name inside the brackets keys = re.findall('{(.*?)}', part[0]) # remove the type : designation keys = [k.split(':')[0] for k in keys] # handle double bracket edge cases; remove this when better solution found if len(keys) > 1: if keys[0] == 'dr': # for {dr}{version} drval = re.match('^DR[1-9][0-9]', value).group(0) otherval = value.split(drval)[-1] pdict = {keys[0]: drval, keys[1]: otherval} elif keys[0] in ['rc', 'br', 'filter', 'camrow']: # for {camrow}{camcol}, {filter}{camcol}, {br}{id}, etc pdict = {keys[0]: value[0], keys[1]: value[1:]} else: raise ValueError('This case has not yet been accounted for.') path_dict.update(pdict) else: path_dict[keys[0]] = value return path_dict
[ "def", "extract", "(", "self", ",", "name", ",", "example", ")", ":", "# if pathlib not available do nothing", "if", "not", "pathlib", ":", "return", "None", "# ensure example is a string", "if", "isinstance", "(", "example", ",", "pathlib", ".", "Path", ")", ":...
Extract keywords from an example path
[ "Extract", "keywords", "from", "an", "example", "path" ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/path/path.py#L189-L261
train
46,834
sdss/sdss_access
python/sdss_access/path/path.py
BasePath.exists
def exists(self, filetype, remote=None, **kwargs): '''Checks if the given type of file exists locally Parameters ---------- filetype : str File type parameter. remote : bool If True, checks for remote existence of the file Returns ------- exists : bool Boolean indicating if the file exists. ''' full = kwargs.get('full', None) if not full: full = self.full(filetype, **kwargs) if remote: # check for remote existence using a HEAD request url = self.url('', full=full) try: resp = requests.head(url) except Exception as e: raise AccessError('Cannot check for remote file existence for {0}: {1}'.format(url, e)) else: return resp.ok else: return os.path.isfile(full)
python
def exists(self, filetype, remote=None, **kwargs): '''Checks if the given type of file exists locally Parameters ---------- filetype : str File type parameter. remote : bool If True, checks for remote existence of the file Returns ------- exists : bool Boolean indicating if the file exists. ''' full = kwargs.get('full', None) if not full: full = self.full(filetype, **kwargs) if remote: # check for remote existence using a HEAD request url = self.url('', full=full) try: resp = requests.head(url) except Exception as e: raise AccessError('Cannot check for remote file existence for {0}: {1}'.format(url, e)) else: return resp.ok else: return os.path.isfile(full)
[ "def", "exists", "(", "self", ",", "filetype", ",", "remote", "=", "None", ",", "*", "*", "kwargs", ")", ":", "full", "=", "kwargs", ".", "get", "(", "'full'", ",", "None", ")", "if", "not", "full", ":", "full", "=", "self", ".", "full", "(", "...
Checks if the given type of file exists locally Parameters ---------- filetype : str File type parameter. remote : bool If True, checks for remote existence of the file Returns ------- exists : bool Boolean indicating if the file exists.
[ "Checks", "if", "the", "given", "type", "of", "file", "exists", "locally" ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/path/path.py#L303-L335
train
46,835
sdss/sdss_access
python/sdss_access/path/path.py
BasePath.expand
def expand(self, filetype, **kwargs): ''' Expand a wildcard path locally Parameters ---------- filetype : str File type parameter. as_url: bool Boolean to return SAS urls refine: str Regular expression string to filter the list of files by before random selection Returns ------- expand : list List of expanded full paths of the given type. ''' full = kwargs.get('full', None) if not full: full = self.full(filetype, **kwargs) # assert '*' in full, 'Wildcard must be present in full path' files = glob(full) # return as urls? as_url = kwargs.get('as_url', None) newfiles = [self.url('', full=full) for full in files] if as_url else files # optionally refine the results refine = kwargs.get('refine', None) if refine: newfiles = self.refine(newfiles, refine, **kwargs) return newfiles
python
def expand(self, filetype, **kwargs): ''' Expand a wildcard path locally Parameters ---------- filetype : str File type parameter. as_url: bool Boolean to return SAS urls refine: str Regular expression string to filter the list of files by before random selection Returns ------- expand : list List of expanded full paths of the given type. ''' full = kwargs.get('full', None) if not full: full = self.full(filetype, **kwargs) # assert '*' in full, 'Wildcard must be present in full path' files = glob(full) # return as urls? as_url = kwargs.get('as_url', None) newfiles = [self.url('', full=full) for full in files] if as_url else files # optionally refine the results refine = kwargs.get('refine', None) if refine: newfiles = self.refine(newfiles, refine, **kwargs) return newfiles
[ "def", "expand", "(", "self", ",", "filetype", ",", "*", "*", "kwargs", ")", ":", "full", "=", "kwargs", ".", "get", "(", "'full'", ",", "None", ")", "if", "not", "full", ":", "full", "=", "self", ".", "full", "(", "filetype", ",", "*", "*", "k...
Expand a wildcard path locally Parameters ---------- filetype : str File type parameter. as_url: bool Boolean to return SAS urls refine: str Regular expression string to filter the list of files by before random selection Returns ------- expand : list List of expanded full paths of the given type.
[ "Expand", "a", "wildcard", "path", "locally" ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/path/path.py#L337-L375
train
46,836
sdss/sdss_access
python/sdss_access/path/path.py
BasePath.any
def any(self, filetype, **kwargs): ''' Checks if the local directory contains any of the type of file Parameters ---------- filetype : str File type parameter. Returns ------- any : bool Boolean indicating if the any files exist in the expanded path on disk. ''' expanded_files = self.expand(filetype, **kwargs) return any(expanded_files)
python
def any(self, filetype, **kwargs): ''' Checks if the local directory contains any of the type of file Parameters ---------- filetype : str File type parameter. Returns ------- any : bool Boolean indicating if the any files exist in the expanded path on disk. ''' expanded_files = self.expand(filetype, **kwargs) return any(expanded_files)
[ "def", "any", "(", "self", ",", "filetype", ",", "*", "*", "kwargs", ")", ":", "expanded_files", "=", "self", ".", "expand", "(", "filetype", ",", "*", "*", "kwargs", ")", "return", "any", "(", "expanded_files", ")" ]
Checks if the local directory contains any of the type of file Parameters ---------- filetype : str File type parameter. Returns ------- any : bool Boolean indicating if the any files exist in the expanded path on disk.
[ "Checks", "if", "the", "local", "directory", "contains", "any", "of", "the", "type", "of", "file" ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/path/path.py#L377-L392
train
46,837
sdss/sdss_access
python/sdss_access/path/path.py
BasePath.one
def one(self, filetype, **kwargs): ''' Returns random one of the given type of file Parameters ---------- filetype : str File type parameter. as_url: bool Boolean to return SAS urls refine: str Regular expression string to filter the list of files by before random selection Returns ------- one : str Random file selected from the expanded list of full paths on disk. ''' expanded_files = self.expand(filetype, **kwargs) isany = self.any(filetype, **kwargs) return choice(expanded_files) if isany else None
python
def one(self, filetype, **kwargs): ''' Returns random one of the given type of file Parameters ---------- filetype : str File type parameter. as_url: bool Boolean to return SAS urls refine: str Regular expression string to filter the list of files by before random selection Returns ------- one : str Random file selected from the expanded list of full paths on disk. ''' expanded_files = self.expand(filetype, **kwargs) isany = self.any(filetype, **kwargs) return choice(expanded_files) if isany else None
[ "def", "one", "(", "self", ",", "filetype", ",", "*", "*", "kwargs", ")", ":", "expanded_files", "=", "self", ".", "expand", "(", "filetype", ",", "*", "*", "kwargs", ")", "isany", "=", "self", ".", "any", "(", "filetype", ",", "*", "*", "kwargs", ...
Returns random one of the given type of file Parameters ---------- filetype : str File type parameter. as_url: bool Boolean to return SAS urls refine: str Regular expression string to filter the list of files by before random selection Returns ------- one : str Random file selected from the expanded list of full paths on disk.
[ "Returns", "random", "one", "of", "the", "given", "type", "of", "file" ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/path/path.py#L394-L417
train
46,838
sdss/sdss_access
python/sdss_access/path/path.py
BasePath.random
def random(self, filetype, **kwargs): ''' Returns random number of the given type of file Parameters ---------- filetype : str File type parameter. num : int The number of files to return as_url: bool Boolean to return SAS urls refine: str Regular expression string to filter the list of files by before random selection Returns ------- random : list Random file selected from the expanded list of full paths on disk. ''' expanded_files = self.expand(filetype, **kwargs) isany = self.any(filetype, **kwargs) if isany: # get the desired number num = kwargs.get('num', 1) assert num <= len(expanded_files), 'Requested number must be larger the sample. Reduce your number.' return sample(expanded_files, num) else: return None
python
def random(self, filetype, **kwargs): ''' Returns random number of the given type of file Parameters ---------- filetype : str File type parameter. num : int The number of files to return as_url: bool Boolean to return SAS urls refine: str Regular expression string to filter the list of files by before random selection Returns ------- random : list Random file selected from the expanded list of full paths on disk. ''' expanded_files = self.expand(filetype, **kwargs) isany = self.any(filetype, **kwargs) if isany: # get the desired number num = kwargs.get('num', 1) assert num <= len(expanded_files), 'Requested number must be larger the sample. Reduce your number.' return sample(expanded_files, num) else: return None
[ "def", "random", "(", "self", ",", "filetype", ",", "*", "*", "kwargs", ")", ":", "expanded_files", "=", "self", ".", "expand", "(", "filetype", ",", "*", "*", "kwargs", ")", "isany", "=", "self", ".", "any", "(", "filetype", ",", "*", "*", "kwargs...
Returns random number of the given type of file Parameters ---------- filetype : str File type parameter. num : int The number of files to return as_url: bool Boolean to return SAS urls refine: str Regular expression string to filter the list of files by before random selection Returns ------- random : list Random file selected from the expanded list of full paths on disk.
[ "Returns", "random", "number", "of", "the", "given", "type", "of", "file" ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/path/path.py#L419-L451
train
46,839
sdss/sdss_access
python/sdss_access/path/path.py
BasePath.refine
def refine(self, filelist, regex, filterdir='out', **kwargs): ''' Returns a list of files filterd by a regular expression Parameters ---------- filelist : list A list of files to filter on. regex : str The regular expression string to filter your list filterdir: {'in', 'out'} Indicates the filter to be inclusive or exclusive 'out' removes the items satisfying the regular expression 'in' keeps the items satisfying the regular expression Returns ------- refine : list A file list refined by an input regular expression. ''' assert filelist, 'Must provide a list of filenames to refine on' assert regex, 'Must provide a regular expression to refine the file list' r = re.compile(regex) # icheck filter direction; default is out assert filterdir in ['in', 'out'], 'Filter direction must be either "in" or "out"' if filterdir == 'out': subset = list(filter(lambda i: r.search(i), filelist)) elif filterdir == 'in': subset = list(filter(lambda i: not r.search(i), filelist)) return subset
python
def refine(self, filelist, regex, filterdir='out', **kwargs): ''' Returns a list of files filterd by a regular expression Parameters ---------- filelist : list A list of files to filter on. regex : str The regular expression string to filter your list filterdir: {'in', 'out'} Indicates the filter to be inclusive or exclusive 'out' removes the items satisfying the regular expression 'in' keeps the items satisfying the regular expression Returns ------- refine : list A file list refined by an input regular expression. ''' assert filelist, 'Must provide a list of filenames to refine on' assert regex, 'Must provide a regular expression to refine the file list' r = re.compile(regex) # icheck filter direction; default is out assert filterdir in ['in', 'out'], 'Filter direction must be either "in" or "out"' if filterdir == 'out': subset = list(filter(lambda i: r.search(i), filelist)) elif filterdir == 'in': subset = list(filter(lambda i: not r.search(i), filelist)) return subset
[ "def", "refine", "(", "self", ",", "filelist", ",", "regex", ",", "filterdir", "=", "'out'", ",", "*", "*", "kwargs", ")", ":", "assert", "filelist", ",", "'Must provide a list of filenames to refine on'", "assert", "regex", ",", "'Must provide a regular expression ...
Returns a list of files filterd by a regular expression Parameters ---------- filelist : list A list of files to filter on. regex : str The regular expression string to filter your list filterdir: {'in', 'out'} Indicates the filter to be inclusive or exclusive 'out' removes the items satisfying the regular expression 'in' keeps the items satisfying the regular expression Returns ------- refine : list A file list refined by an input regular expression.
[ "Returns", "a", "list", "of", "files", "filterd", "by", "a", "regular", "expression" ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/path/path.py#L453-L485
train
46,840
sdss/sdss_access
python/sdss_access/path/path.py
BasePath.full
def full(self, filetype, **kwargs): """Return the full name of a given type of file. Parameters ---------- filetype : str File type parameter. Returns ------- full : str The full path to the file. """ # check if full already in kwargs if 'full' in kwargs: return kwargs.get('full') # check for filetype in template assert filetype in self.templates, ('No entry {0} found. Filetype must ' 'be one of the designated templates ' 'in the currently loaded tree'.format(filetype)) template = self.templates[filetype] # Now replace {} items if template: # check for missing keyword arguments keys = self.lookup_keys(filetype) # split keys to remove :format from any "key:format" keys = [k.split(':')[0] for k in keys] missing_keys = set(keys) - set(kwargs.keys()) if missing_keys: raise KeyError('Missing required keyword arguments: {0}'.format(list(missing_keys))) else: template = template.format(**kwargs) if template: # Now replace environmental variables template = os.path.expandvars(template) # Now call special functions as appropriate template = self._call_special_functions(filetype, template, **kwargs) return template
python
def full(self, filetype, **kwargs): """Return the full name of a given type of file. Parameters ---------- filetype : str File type parameter. Returns ------- full : str The full path to the file. """ # check if full already in kwargs if 'full' in kwargs: return kwargs.get('full') # check for filetype in template assert filetype in self.templates, ('No entry {0} found. Filetype must ' 'be one of the designated templates ' 'in the currently loaded tree'.format(filetype)) template = self.templates[filetype] # Now replace {} items if template: # check for missing keyword arguments keys = self.lookup_keys(filetype) # split keys to remove :format from any "key:format" keys = [k.split(':')[0] for k in keys] missing_keys = set(keys) - set(kwargs.keys()) if missing_keys: raise KeyError('Missing required keyword arguments: {0}'.format(list(missing_keys))) else: template = template.format(**kwargs) if template: # Now replace environmental variables template = os.path.expandvars(template) # Now call special functions as appropriate template = self._call_special_functions(filetype, template, **kwargs) return template
[ "def", "full", "(", "self", ",", "filetype", ",", "*", "*", "kwargs", ")", ":", "# check if full already in kwargs", "if", "'full'", "in", "kwargs", ":", "return", "kwargs", ".", "get", "(", "'full'", ")", "# check for filetype in template", "assert", "filetype"...
Return the full name of a given type of file. Parameters ---------- filetype : str File type parameter. Returns ------- full : str The full path to the file.
[ "Return", "the", "full", "name", "of", "a", "given", "type", "of", "file", "." ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/path/path.py#L487-L530
train
46,841
sdss/sdss_access
python/sdss_access/path/path.py
BasePath._call_special_functions
def _call_special_functions(self, filetype, template, **kwargs): ''' Call the special functions found in a template path Calls special functions indicated by %methodname found in the sdss_paths.ini template file, and replaces the %location in the path with the returned content. Parameters: filetype (str): template name of file template (str): the template path kwargs (dict): Any kwargs needed to pass into the methods Returns: The expanded template path ''' # Now call special functions as appropriate functions = re.findall(r"\%\w+", template) if not functions: return template for function in functions: try: method = getattr(self, function[1:]) except AttributeError: return None else: value = method(filetype, **kwargs) template = re.sub(function, value, template) return template
python
def _call_special_functions(self, filetype, template, **kwargs): ''' Call the special functions found in a template path Calls special functions indicated by %methodname found in the sdss_paths.ini template file, and replaces the %location in the path with the returned content. Parameters: filetype (str): template name of file template (str): the template path kwargs (dict): Any kwargs needed to pass into the methods Returns: The expanded template path ''' # Now call special functions as appropriate functions = re.findall(r"\%\w+", template) if not functions: return template for function in functions: try: method = getattr(self, function[1:]) except AttributeError: return None else: value = method(filetype, **kwargs) template = re.sub(function, value, template) return template
[ "def", "_call_special_functions", "(", "self", ",", "filetype", ",", "template", ",", "*", "*", "kwargs", ")", ":", "# Now call special functions as appropriate", "functions", "=", "re", ".", "findall", "(", "r\"\\%\\w+\"", ",", "template", ")", "if", "not", "fu...
Call the special functions found in a template path Calls special functions indicated by %methodname found in the sdss_paths.ini template file, and replaces the %location in the path with the returned content. Parameters: filetype (str): template name of file template (str): the template path kwargs (dict): Any kwargs needed to pass into the methods Returns: The expanded template path
[ "Call", "the", "special", "functions", "found", "in", "a", "template", "path" ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/path/path.py#L532-L563
train
46,842
sdss/sdss_access
python/sdss_access/path/path.py
BasePath.location
def location(self, filetype, base_dir=None, **kwargs): """Return the location of the relative sas path of a given type of file. Parameters ---------- filetype : str File type parameter. Returns ------- full : str The relative sas path to the file. """ full = kwargs.get('full', None) if not full: full = self.full(filetype, **kwargs) self.set_base_dir(base_dir=base_dir) location = full[len(self.base_dir):] if full and full.startswith(self.base_dir) else None if location and '//' in location: location = location.replace('//', '/') return location
python
def location(self, filetype, base_dir=None, **kwargs): """Return the location of the relative sas path of a given type of file. Parameters ---------- filetype : str File type parameter. Returns ------- full : str The relative sas path to the file. """ full = kwargs.get('full', None) if not full: full = self.full(filetype, **kwargs) self.set_base_dir(base_dir=base_dir) location = full[len(self.base_dir):] if full and full.startswith(self.base_dir) else None if location and '//' in location: location = location.replace('//', '/') return location
[ "def", "location", "(", "self", ",", "filetype", ",", "base_dir", "=", "None", ",", "*", "*", "kwargs", ")", ":", "full", "=", "kwargs", ".", "get", "(", "'full'", ",", "None", ")", "if", "not", "full", ":", "full", "=", "self", ".", "full", "(",...
Return the location of the relative sas path of a given type of file. Parameters ---------- filetype : str File type parameter. Returns ------- full : str The relative sas path to the file.
[ "Return", "the", "location", "of", "the", "relative", "sas", "path", "of", "a", "given", "type", "of", "file", "." ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/path/path.py#L584-L608
train
46,843
sdss/sdss_access
python/sdss_access/path/path.py
BasePath.url
def url(self, filetype, base_dir=None, sasdir='sas', **kwargs): """Return the url of a given type of file. Parameters ---------- filetype : str File type parameter. Returns ------- full : str The sas url to the file. """ location = self.location(filetype, **kwargs) return join(self.remote_base, sasdir, location) if self.remote_base and location else None
python
def url(self, filetype, base_dir=None, sasdir='sas', **kwargs): """Return the url of a given type of file. Parameters ---------- filetype : str File type parameter. Returns ------- full : str The sas url to the file. """ location = self.location(filetype, **kwargs) return join(self.remote_base, sasdir, location) if self.remote_base and location else None
[ "def", "url", "(", "self", ",", "filetype", ",", "base_dir", "=", "None", ",", "sasdir", "=", "'sas'", ",", "*", "*", "kwargs", ")", ":", "location", "=", "self", ".", "location", "(", "filetype", ",", "*", "*", "kwargs", ")", "return", "join", "("...
Return the url of a given type of file. Parameters ---------- filetype : str File type parameter. Returns ------- full : str The sas url to the file.
[ "Return", "the", "url", "of", "a", "given", "type", "of", "file", "." ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/path/path.py#L610-L625
train
46,844
sdss/sdss_access
python/sdss_access/path/path.py
Path.plateid6
def plateid6(self, filetype, **kwargs): """Print plate ID, accounting for 5-6 digit plate IDs. Parameters ---------- filetype : str File type parameter. plateid : int or str Plate ID number. Will be converted to int internally. Returns ------- plateid6 : str Plate ID formatted to a string of 6 characters. """ plateid = int(kwargs['plateid']) if plateid < 10000: return "{:0>6d}".format(plateid) else: return "{:d}".format(plateid)
python
def plateid6(self, filetype, **kwargs): """Print plate ID, accounting for 5-6 digit plate IDs. Parameters ---------- filetype : str File type parameter. plateid : int or str Plate ID number. Will be converted to int internally. Returns ------- plateid6 : str Plate ID formatted to a string of 6 characters. """ plateid = int(kwargs['plateid']) if plateid < 10000: return "{:0>6d}".format(plateid) else: return "{:d}".format(plateid)
[ "def", "plateid6", "(", "self", ",", "filetype", ",", "*", "*", "kwargs", ")", ":", "plateid", "=", "int", "(", "kwargs", "[", "'plateid'", "]", ")", "if", "plateid", "<", "10000", ":", "return", "\"{:0>6d}\"", ".", "format", "(", "plateid", ")", "el...
Print plate ID, accounting for 5-6 digit plate IDs. Parameters ---------- filetype : str File type parameter. plateid : int or str Plate ID number. Will be converted to int internally. Returns ------- plateid6 : str Plate ID formatted to a string of 6 characters.
[ "Print", "plate", "ID", "accounting", "for", "5", "-", "6", "digit", "plate", "IDs", "." ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/path/path.py#L640-L659
train
46,845
sdss/sdss_access
python/sdss_access/sync/cli.py
Cli.foreground_run
def foreground_run(self, command, test=False, logger=None, logall=False, message=None, outname=None, errname=None): """A convenient wrapper to log and perform system calls. Parameters ---------- command : str The system command to run. It will be split internally by shlex.split(). test : bool, optional Set this to true to not actually run the commands. logger : logging.logging, optional If passed a logging object, diagnostic output will be set to this object. logall : bool, optional Set this to true to always log stdout and stderr (at level DEBUG). Otherwise stdout and stderr will only be logged for nonzero status message : str, optional Call logger.critical(message) with this message and then call sys.exit(status). outname : str, optional If set, use ``outname`` as the name of a file to contain stdout. It is the responsibility of the caller of this function to clean up the resulting file. Otherwise a temporary file will be used. errname : str, optional Same as ``outname``, but will contain stderr. Returns ------- (status,out,err) : tuple The exit status, stdout and stderr of the process Examples -------- >>> status,out,err = transfer.common.system_call('date') """ if logger is not None: logger.debug(command) status = 0 out = '' err = '' if not test: if outname is None: outfile = TemporaryFile() else: outfile = open(outname, 'w+') if errname is None: errfile = TemporaryFile() else: errfile = open(errname, 'w+') proc = Popen(split(str(command)), stdout=outfile, stderr=errfile, env=self.env) tstart = time() while proc.poll() is None: elapsed = time() - tstart if elapsed > 500000: message = "Process still running after more than 5 days!" proc.kill() break tsleep = 10**(int(log10(elapsed)) - 1) if tsleep < 1: tsleep = 1 sleep(tsleep) # proc.wait() status = proc.returncode outfile.seek(0) out = outfile.read() errfile.seek(0) err = errfile.read() outfile.close() errfile.close() if logger is not None: if status == 0 and logall: if len(out) > 0: logger.debug('STDOUT = \n' + out) if len(err) > 0: logger.debug('STDERR = \n' + err) if status != 0: logger.error('status = {0}'.format(status)) if len(out) > 0: logger.error('STDOUT = \n' + out) if len(err) > 0: logger.error('STDERR = \n' + err) if message is not None: logger.critical(message) exit(status) return (status, out, err)
python
def foreground_run(self, command, test=False, logger=None, logall=False, message=None, outname=None, errname=None): """A convenient wrapper to log and perform system calls. Parameters ---------- command : str The system command to run. It will be split internally by shlex.split(). test : bool, optional Set this to true to not actually run the commands. logger : logging.logging, optional If passed a logging object, diagnostic output will be set to this object. logall : bool, optional Set this to true to always log stdout and stderr (at level DEBUG). Otherwise stdout and stderr will only be logged for nonzero status message : str, optional Call logger.critical(message) with this message and then call sys.exit(status). outname : str, optional If set, use ``outname`` as the name of a file to contain stdout. It is the responsibility of the caller of this function to clean up the resulting file. Otherwise a temporary file will be used. errname : str, optional Same as ``outname``, but will contain stderr. Returns ------- (status,out,err) : tuple The exit status, stdout and stderr of the process Examples -------- >>> status,out,err = transfer.common.system_call('date') """ if logger is not None: logger.debug(command) status = 0 out = '' err = '' if not test: if outname is None: outfile = TemporaryFile() else: outfile = open(outname, 'w+') if errname is None: errfile = TemporaryFile() else: errfile = open(errname, 'w+') proc = Popen(split(str(command)), stdout=outfile, stderr=errfile, env=self.env) tstart = time() while proc.poll() is None: elapsed = time() - tstart if elapsed > 500000: message = "Process still running after more than 5 days!" proc.kill() break tsleep = 10**(int(log10(elapsed)) - 1) if tsleep < 1: tsleep = 1 sleep(tsleep) # proc.wait() status = proc.returncode outfile.seek(0) out = outfile.read() errfile.seek(0) err = errfile.read() outfile.close() errfile.close() if logger is not None: if status == 0 and logall: if len(out) > 0: logger.debug('STDOUT = \n' + out) if len(err) > 0: logger.debug('STDERR = \n' + err) if status != 0: logger.error('status = {0}'.format(status)) if len(out) > 0: logger.error('STDOUT = \n' + out) if len(err) > 0: logger.error('STDERR = \n' + err) if message is not None: logger.critical(message) exit(status) return (status, out, err)
[ "def", "foreground_run", "(", "self", ",", "command", ",", "test", "=", "False", ",", "logger", "=", "None", ",", "logall", "=", "False", ",", "message", "=", "None", ",", "outname", "=", "None", ",", "errname", "=", "None", ")", ":", "if", "logger",...
A convenient wrapper to log and perform system calls. Parameters ---------- command : str The system command to run. It will be split internally by shlex.split(). test : bool, optional Set this to true to not actually run the commands. logger : logging.logging, optional If passed a logging object, diagnostic output will be set to this object. logall : bool, optional Set this to true to always log stdout and stderr (at level DEBUG). Otherwise stdout and stderr will only be logged for nonzero status message : str, optional Call logger.critical(message) with this message and then call sys.exit(status). outname : str, optional If set, use ``outname`` as the name of a file to contain stdout. It is the responsibility of the caller of this function to clean up the resulting file. Otherwise a temporary file will be used. errname : str, optional Same as ``outname``, but will contain stderr. Returns ------- (status,out,err) : tuple The exit status, stdout and stderr of the process Examples -------- >>> status,out,err = transfer.common.system_call('date')
[ "A", "convenient", "wrapper", "to", "log", "and", "perform", "system", "calls", "." ]
76375bbf37d39d2e4ccbed90bdfa9a4298784470
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/sync/cli.py#L81-L163
train
46,846
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
undo
def undo(ui, repo, clname, **opts): """undo the effect of a CL Creates a new CL that undoes an earlier CL. After creating the CL, opens the CL text for editing so that you can add the reason for the undo to the description. """ if repo[None].branch() != "default": raise hg_util.Abort("cannot run hg undo outside default branch") err = clpatch_or_undo(ui, repo, clname, opts, mode="undo") if err: raise hg_util.Abort(err)
python
def undo(ui, repo, clname, **opts): """undo the effect of a CL Creates a new CL that undoes an earlier CL. After creating the CL, opens the CL text for editing so that you can add the reason for the undo to the description. """ if repo[None].branch() != "default": raise hg_util.Abort("cannot run hg undo outside default branch") err = clpatch_or_undo(ui, repo, clname, opts, mode="undo") if err: raise hg_util.Abort(err)
[ "def", "undo", "(", "ui", ",", "repo", ",", "clname", ",", "*", "*", "opts", ")", ":", "if", "repo", "[", "None", "]", ".", "branch", "(", ")", "!=", "\"default\"", ":", "raise", "hg_util", ".", "Abort", "(", "\"cannot run hg undo outside default branch\...
undo the effect of a CL Creates a new CL that undoes an earlier CL. After creating the CL, opens the CL text for editing so that you can add the reason for the undo to the description.
[ "undo", "the", "effect", "of", "a", "CL", "Creates", "a", "new", "CL", "that", "undoes", "an", "earlier", "CL", ".", "After", "creating", "the", "CL", "opens", "the", "CL", "text", "for", "editing", "so", "that", "you", "can", "add", "the", "reason", ...
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L1424-L1435
train
46,847
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
release_apply
def release_apply(ui, repo, clname, **opts): """apply a CL to the release branch Creates a new CL copying a previously committed change from the main branch to the release branch. The current client must either be clean or already be in the release branch. The release branch must be created by starting with a clean client, disabling the code review plugin, and running: hg update weekly.YYYY-MM-DD hg branch release-branch.rNN hg commit -m 'create release-branch.rNN' hg push --new-branch Then re-enable the code review plugin. People can test the release branch by running hg update release-branch.rNN in a clean client. To return to the normal tree, hg update default Move changes since the weekly into the release branch using hg release-apply followed by the usual code review process and hg submit. When it comes time to tag the release, record the final long-form tag of the release-branch.rNN in the *default* branch's .hgtags file. That is, run hg update default and then edit .hgtags as you would for a weekly. """ c = repo[None] if not releaseBranch: raise hg_util.Abort("no active release branches") if c.branch() != releaseBranch: if c.modified() or c.added() or c.removed(): raise hg_util.Abort("uncommitted local changes - cannot switch branches") err = hg_clean(repo, releaseBranch) if err: raise hg_util.Abort(err) try: err = clpatch_or_undo(ui, repo, clname, opts, mode="backport") if err: raise hg_util.Abort(err) except Exception, e: hg_clean(repo, "default") raise e
python
def release_apply(ui, repo, clname, **opts): """apply a CL to the release branch Creates a new CL copying a previously committed change from the main branch to the release branch. The current client must either be clean or already be in the release branch. The release branch must be created by starting with a clean client, disabling the code review plugin, and running: hg update weekly.YYYY-MM-DD hg branch release-branch.rNN hg commit -m 'create release-branch.rNN' hg push --new-branch Then re-enable the code review plugin. People can test the release branch by running hg update release-branch.rNN in a clean client. To return to the normal tree, hg update default Move changes since the weekly into the release branch using hg release-apply followed by the usual code review process and hg submit. When it comes time to tag the release, record the final long-form tag of the release-branch.rNN in the *default* branch's .hgtags file. That is, run hg update default and then edit .hgtags as you would for a weekly. """ c = repo[None] if not releaseBranch: raise hg_util.Abort("no active release branches") if c.branch() != releaseBranch: if c.modified() or c.added() or c.removed(): raise hg_util.Abort("uncommitted local changes - cannot switch branches") err = hg_clean(repo, releaseBranch) if err: raise hg_util.Abort(err) try: err = clpatch_or_undo(ui, repo, clname, opts, mode="backport") if err: raise hg_util.Abort(err) except Exception, e: hg_clean(repo, "default") raise e
[ "def", "release_apply", "(", "ui", ",", "repo", ",", "clname", ",", "*", "*", "opts", ")", ":", "c", "=", "repo", "[", "None", "]", "if", "not", "releaseBranch", ":", "raise", "hg_util", ".", "Abort", "(", "\"no active release branches\"", ")", "if", "...
apply a CL to the release branch Creates a new CL copying a previously committed change from the main branch to the release branch. The current client must either be clean or already be in the release branch. The release branch must be created by starting with a clean client, disabling the code review plugin, and running: hg update weekly.YYYY-MM-DD hg branch release-branch.rNN hg commit -m 'create release-branch.rNN' hg push --new-branch Then re-enable the code review plugin. People can test the release branch by running hg update release-branch.rNN in a clean client. To return to the normal tree, hg update default Move changes since the weekly into the release branch using hg release-apply followed by the usual code review process and hg submit. When it comes time to tag the release, record the final long-form tag of the release-branch.rNN in the *default* branch's .hgtags file. That is, run hg update default and then edit .hgtags as you would for a weekly.
[ "apply", "a", "CL", "to", "the", "release", "branch" ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L1438-L1492
train
46,848
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
download
def download(ui, repo, clname, **opts): """download a change from the code review server Download prints a description of the given change list followed by its diff, downloaded from the code review server. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) cl, vers, patch, err = DownloadCL(ui, repo, clname) if err != "": return err ui.write(cl.EditorText() + "\n") ui.write(patch + "\n") return
python
def download(ui, repo, clname, **opts): """download a change from the code review server Download prints a description of the given change list followed by its diff, downloaded from the code review server. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) cl, vers, patch, err = DownloadCL(ui, repo, clname) if err != "": return err ui.write(cl.EditorText() + "\n") ui.write(patch + "\n") return
[ "def", "download", "(", "ui", ",", "repo", ",", "clname", ",", "*", "*", "opts", ")", ":", "if", "codereview_disabled", ":", "raise", "hg_util", ".", "Abort", "(", "codereview_disabled", ")", "cl", ",", "vers", ",", "patch", ",", "err", "=", "DownloadC...
download a change from the code review server Download prints a description of the given change list followed by its diff, downloaded from the code review server.
[ "download", "a", "change", "from", "the", "code", "review", "server" ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L1690-L1704
train
46,849
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
file
def file(ui, repo, clname, pat, *pats, **opts): """assign files to or remove files from a change list Assign files to or (with -d) remove files from a change list. The -d option only removes files from the change list. It does not edit them or remove them from the repository. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) pats = tuple([pat] + list(pats)) if not GoodCLName(clname): return "invalid CL name " + clname dirty = {} cl, err = LoadCL(ui, repo, clname, web=False) if err != '': return err if not cl.local: return "cannot change non-local CL " + clname files = ChangedFiles(ui, repo, pats) if opts["delete"]: oldfiles = Intersect(files, cl.files) if oldfiles: if not ui.quiet: ui.status("# Removing files from CL. To undo:\n") ui.status("# cd %s\n" % (repo.root)) for f in oldfiles: ui.status("# hg file %s %s\n" % (cl.name, f)) cl.files = Sub(cl.files, oldfiles) cl.Flush(ui, repo) else: ui.status("no such files in CL") return if not files: return "no such modified files" files = Sub(files, cl.files) taken = Taken(ui, repo) warned = False for f in files: if f in taken: if not warned and not ui.quiet: ui.status("# Taking files from other CLs. To undo:\n") ui.status("# cd %s\n" % (repo.root)) warned = True ocl = taken[f] if not ui.quiet: ui.status("# hg file %s %s\n" % (ocl.name, f)) if ocl not in dirty: ocl.files = Sub(ocl.files, files) dirty[ocl] = True cl.files = Add(cl.files, files) dirty[cl] = True for d, _ in dirty.items(): d.Flush(ui, repo) return
python
def file(ui, repo, clname, pat, *pats, **opts): """assign files to or remove files from a change list Assign files to or (with -d) remove files from a change list. The -d option only removes files from the change list. It does not edit them or remove them from the repository. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) pats = tuple([pat] + list(pats)) if not GoodCLName(clname): return "invalid CL name " + clname dirty = {} cl, err = LoadCL(ui, repo, clname, web=False) if err != '': return err if not cl.local: return "cannot change non-local CL " + clname files = ChangedFiles(ui, repo, pats) if opts["delete"]: oldfiles = Intersect(files, cl.files) if oldfiles: if not ui.quiet: ui.status("# Removing files from CL. To undo:\n") ui.status("# cd %s\n" % (repo.root)) for f in oldfiles: ui.status("# hg file %s %s\n" % (cl.name, f)) cl.files = Sub(cl.files, oldfiles) cl.Flush(ui, repo) else: ui.status("no such files in CL") return if not files: return "no such modified files" files = Sub(files, cl.files) taken = Taken(ui, repo) warned = False for f in files: if f in taken: if not warned and not ui.quiet: ui.status("# Taking files from other CLs. To undo:\n") ui.status("# cd %s\n" % (repo.root)) warned = True ocl = taken[f] if not ui.quiet: ui.status("# hg file %s %s\n" % (ocl.name, f)) if ocl not in dirty: ocl.files = Sub(ocl.files, files) dirty[ocl] = True cl.files = Add(cl.files, files) dirty[cl] = True for d, _ in dirty.items(): d.Flush(ui, repo) return
[ "def", "file", "(", "ui", ",", "repo", ",", "clname", ",", "pat", ",", "*", "pats", ",", "*", "*", "opts", ")", ":", "if", "codereview_disabled", ":", "raise", "hg_util", ".", "Abort", "(", "codereview_disabled", ")", "pats", "=", "tuple", "(", "[", ...
assign files to or remove files from a change list Assign files to or (with -d) remove files from a change list. The -d option only removes files from the change list. It does not edit them or remove them from the repository.
[ "assign", "files", "to", "or", "remove", "files", "from", "a", "change", "list" ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L1710-L1770
train
46,850
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
gofmt
def gofmt(ui, repo, *pats, **opts): """apply gofmt to modified files Applies gofmt to the modified files in the repository that match the given patterns. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) files = ChangedExistingFiles(ui, repo, pats, opts) files = gofmt_required(files) if not files: ui.status("no modified go files\n") return cwd = os.getcwd() files = [RelativePath(repo.root + '/' + f, cwd) for f in files] try: cmd = ["gofmt", "-l"] if not opts["list"]: cmd += ["-w"] if subprocess.call(cmd + files) != 0: raise hg_util.Abort("gofmt did not exit cleanly") except hg_error.Abort, e: raise except: raise hg_util.Abort("gofmt: " + ExceptionDetail()) return
python
def gofmt(ui, repo, *pats, **opts): """apply gofmt to modified files Applies gofmt to the modified files in the repository that match the given patterns. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) files = ChangedExistingFiles(ui, repo, pats, opts) files = gofmt_required(files) if not files: ui.status("no modified go files\n") return cwd = os.getcwd() files = [RelativePath(repo.root + '/' + f, cwd) for f in files] try: cmd = ["gofmt", "-l"] if not opts["list"]: cmd += ["-w"] if subprocess.call(cmd + files) != 0: raise hg_util.Abort("gofmt did not exit cleanly") except hg_error.Abort, e: raise except: raise hg_util.Abort("gofmt: " + ExceptionDetail()) return
[ "def", "gofmt", "(", "ui", ",", "repo", ",", "*", "pats", ",", "*", "*", "opts", ")", ":", "if", "codereview_disabled", ":", "raise", "hg_util", ".", "Abort", "(", "codereview_disabled", ")", "files", "=", "ChangedExistingFiles", "(", "ui", ",", "repo", ...
apply gofmt to modified files Applies gofmt to the modified files in the repository that match the given patterns.
[ "apply", "gofmt", "to", "modified", "files" ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L1776-L1802
train
46,851
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
mail
def mail(ui, repo, *pats, **opts): """mail a change for review Uploads a patch to the code review server and then sends mail to the reviewer and CC list asking for a review. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) cl, err = CommandLineCL(ui, repo, pats, opts, op="mail", defaultcc=defaultcc) if err != "": raise hg_util.Abort(err) cl.Upload(ui, repo, gofmt_just_warn=True) if not cl.reviewer: # If no reviewer is listed, assign the review to defaultcc. # This makes sure that it appears in the # codereview.appspot.com/user/defaultcc # page, so that it doesn't get dropped on the floor. if not defaultcc: raise hg_util.Abort("no reviewers listed in CL") cl.cc = Sub(cl.cc, defaultcc) cl.reviewer = defaultcc cl.Flush(ui, repo) if cl.files == []: raise hg_util.Abort("no changed files, not sending mail") cl.Mail(ui, repo)
python
def mail(ui, repo, *pats, **opts): """mail a change for review Uploads a patch to the code review server and then sends mail to the reviewer and CC list asking for a review. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) cl, err = CommandLineCL(ui, repo, pats, opts, op="mail", defaultcc=defaultcc) if err != "": raise hg_util.Abort(err) cl.Upload(ui, repo, gofmt_just_warn=True) if not cl.reviewer: # If no reviewer is listed, assign the review to defaultcc. # This makes sure that it appears in the # codereview.appspot.com/user/defaultcc # page, so that it doesn't get dropped on the floor. if not defaultcc: raise hg_util.Abort("no reviewers listed in CL") cl.cc = Sub(cl.cc, defaultcc) cl.reviewer = defaultcc cl.Flush(ui, repo) if cl.files == []: raise hg_util.Abort("no changed files, not sending mail") cl.Mail(ui, repo)
[ "def", "mail", "(", "ui", ",", "repo", ",", "*", "pats", ",", "*", "*", "opts", ")", ":", "if", "codereview_disabled", ":", "raise", "hg_util", ".", "Abort", "(", "codereview_disabled", ")", "cl", ",", "err", "=", "CommandLineCL", "(", "ui", ",", "re...
mail a change for review Uploads a patch to the code review server and then sends mail to the reviewer and CC list asking for a review.
[ "mail", "a", "change", "for", "review" ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L1811-L1838
train
46,852
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
pending
def pending(ui, repo, *pats, **opts): """show pending changes Lists pending changes followed by a list of unassigned but modified files. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) quick = opts.get('quick', False) short = opts.get('short', False) m = LoadAllCL(ui, repo, web=not quick and not short) names = m.keys() names.sort() for name in names: cl = m[name] if short: ui.write(name + "\t" + line1(cl.desc) + "\n") else: ui.write(cl.PendingText(quick=quick) + "\n") if short: return 0 files = DefaultFiles(ui, repo, []) if len(files) > 0: s = "Changed files not in any CL:\n" for f in files: s += "\t" + f + "\n" ui.write(s)
python
def pending(ui, repo, *pats, **opts): """show pending changes Lists pending changes followed by a list of unassigned but modified files. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) quick = opts.get('quick', False) short = opts.get('short', False) m = LoadAllCL(ui, repo, web=not quick and not short) names = m.keys() names.sort() for name in names: cl = m[name] if short: ui.write(name + "\t" + line1(cl.desc) + "\n") else: ui.write(cl.PendingText(quick=quick) + "\n") if short: return 0 files = DefaultFiles(ui, repo, []) if len(files) > 0: s = "Changed files not in any CL:\n" for f in files: s += "\t" + f + "\n" ui.write(s)
[ "def", "pending", "(", "ui", ",", "repo", ",", "*", "pats", ",", "*", "*", "opts", ")", ":", "if", "codereview_disabled", ":", "raise", "hg_util", ".", "Abort", "(", "codereview_disabled", ")", "quick", "=", "opts", ".", "get", "(", "'quick'", ",", "...
show pending changes Lists pending changes followed by a list of unassigned but modified files.
[ "show", "pending", "changes" ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L1858-L1885
train
46,853
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
sync
def sync(ui, repo, **opts): """synchronize with remote repository Incorporates recent changes from the remote repository into the local repository. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) if not opts["local"]: # If there are incoming CLs, pull -u will do the update. # If there are no incoming CLs, do hg update to make sure # that an update always happens regardless. This is less # surprising than update depending on incoming CLs. # It is important not to do both hg pull -u and hg update # in the same command, because the hg update will end # up marking resolve conflicts from the hg pull -u as resolved, # causing files with <<< >>> markers to not show up in # hg resolve -l. Yay Mercurial. if hg_incoming(ui, repo): err = hg_pull(ui, repo, update=True) else: err = hg_update(ui, repo) if err: return err sync_changes(ui, repo)
python
def sync(ui, repo, **opts): """synchronize with remote repository Incorporates recent changes from the remote repository into the local repository. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) if not opts["local"]: # If there are incoming CLs, pull -u will do the update. # If there are no incoming CLs, do hg update to make sure # that an update always happens regardless. This is less # surprising than update depending on incoming CLs. # It is important not to do both hg pull -u and hg update # in the same command, because the hg update will end # up marking resolve conflicts from the hg pull -u as resolved, # causing files with <<< >>> markers to not show up in # hg resolve -l. Yay Mercurial. if hg_incoming(ui, repo): err = hg_pull(ui, repo, update=True) else: err = hg_update(ui, repo) if err: return err sync_changes(ui, repo)
[ "def", "sync", "(", "ui", ",", "repo", ",", "*", "*", "opts", ")", ":", "if", "codereview_disabled", ":", "raise", "hg_util", ".", "Abort", "(", "codereview_disabled", ")", "if", "not", "opts", "[", "\"local\"", "]", ":", "# If there are incoming CLs, pull -...
synchronize with remote repository Incorporates recent changes from the remote repository into the local repository.
[ "synchronize", "with", "remote", "repository" ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L2031-L2056
train
46,854
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
upload
def upload(ui, repo, name, **opts): """upload diffs to the code review server Uploads the current modifications for a given change to the server. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) repo.ui.quiet = True cl, err = LoadCL(ui, repo, name, web=True) if err != "": raise hg_util.Abort(err) if not cl.local: raise hg_util.Abort("cannot upload non-local change") cl.Upload(ui, repo) print "%s%s\n" % (server_url_base, cl.name) return 0
python
def upload(ui, repo, name, **opts): """upload diffs to the code review server Uploads the current modifications for a given change to the server. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) repo.ui.quiet = True cl, err = LoadCL(ui, repo, name, web=True) if err != "": raise hg_util.Abort(err) if not cl.local: raise hg_util.Abort("cannot upload non-local change") cl.Upload(ui, repo) print "%s%s\n" % (server_url_base, cl.name) return 0
[ "def", "upload", "(", "ui", ",", "repo", ",", "name", ",", "*", "*", "opts", ")", ":", "if", "codereview_disabled", ":", "raise", "hg_util", ".", "Abort", "(", "codereview_disabled", ")", "repo", ".", "ui", ".", "quiet", "=", "True", "cl", ",", "err"...
upload diffs to the code review server Uploads the current modifications for a given change to the server.
[ "upload", "diffs", "to", "the", "code", "review", "server" ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L2097-L2113
train
46,855
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
MySend
def MySend(request_path, payload=None, content_type="application/octet-stream", timeout=None, force_auth=True, **kwargs): """Run MySend1 maybe twice, because Rietveld is unreliable.""" try: return MySend1(request_path, payload, content_type, timeout, force_auth, **kwargs) except Exception, e: if type(e) != urllib2.HTTPError or e.code != 500: # only retry on HTTP 500 error raise print >>sys.stderr, "Loading "+request_path+": "+ExceptionDetail()+"; trying again in 2 seconds." time.sleep(2) return MySend1(request_path, payload, content_type, timeout, force_auth, **kwargs)
python
def MySend(request_path, payload=None, content_type="application/octet-stream", timeout=None, force_auth=True, **kwargs): """Run MySend1 maybe twice, because Rietveld is unreliable.""" try: return MySend1(request_path, payload, content_type, timeout, force_auth, **kwargs) except Exception, e: if type(e) != urllib2.HTTPError or e.code != 500: # only retry on HTTP 500 error raise print >>sys.stderr, "Loading "+request_path+": "+ExceptionDetail()+"; trying again in 2 seconds." time.sleep(2) return MySend1(request_path, payload, content_type, timeout, force_auth, **kwargs)
[ "def", "MySend", "(", "request_path", ",", "payload", "=", "None", ",", "content_type", "=", "\"application/octet-stream\"", ",", "timeout", "=", "None", ",", "force_auth", "=", "True", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "MySend1", "(...
Run MySend1 maybe twice, because Rietveld is unreliable.
[ "Run", "MySend1", "maybe", "twice", "because", "Rietveld", "is", "unreliable", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L2444-L2456
train
46,856
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
GetEmail
def GetEmail(prompt): """Prompts the user for their email address and returns it. The last used email address is saved to a file and offered up as a suggestion to the user. If the user presses enter without typing in anything the last used email address is used. If the user enters a new address, it is saved for next time we prompt. """ last_email_file_name = os.path.expanduser("~/.last_codereview_email_address") last_email = "" if os.path.exists(last_email_file_name): try: last_email_file = open(last_email_file_name, "r") last_email = last_email_file.readline().strip("\n") last_email_file.close() prompt += " [%s]" % last_email except IOError, e: pass email = raw_input(prompt + ": ").strip() if email: try: last_email_file = open(last_email_file_name, "w") last_email_file.write(email) last_email_file.close() except IOError, e: pass else: email = last_email return email
python
def GetEmail(prompt): """Prompts the user for their email address and returns it. The last used email address is saved to a file and offered up as a suggestion to the user. If the user presses enter without typing in anything the last used email address is used. If the user enters a new address, it is saved for next time we prompt. """ last_email_file_name = os.path.expanduser("~/.last_codereview_email_address") last_email = "" if os.path.exists(last_email_file_name): try: last_email_file = open(last_email_file_name, "r") last_email = last_email_file.readline().strip("\n") last_email_file.close() prompt += " [%s]" % last_email except IOError, e: pass email = raw_input(prompt + ": ").strip() if email: try: last_email_file = open(last_email_file_name, "w") last_email_file.write(email) last_email_file.close() except IOError, e: pass else: email = last_email return email
[ "def", "GetEmail", "(", "prompt", ")", ":", "last_email_file_name", "=", "os", ".", "path", ".", "expanduser", "(", "\"~/.last_codereview_email_address\"", ")", "last_email", "=", "\"\"", "if", "os", ".", "path", ".", "exists", "(", "last_email_file_name", ")", ...
Prompts the user for their email address and returns it. The last used email address is saved to a file and offered up as a suggestion to the user. If the user presses enter without typing in anything the last used email address is used. If the user enters a new address, it is saved for next time we prompt.
[ "Prompts", "the", "user", "for", "their", "email", "address", "and", "returns", "it", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L2729-L2758
train
46,857
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
GetRpcServer
def GetRpcServer(options): """Returns an instance of an AbstractRpcServer. Returns: A new AbstractRpcServer, on which RPC calls can be made. """ rpc_server_class = HttpRpcServer def GetUserCredentials(): """Prompts the user for a username and password.""" # Disable status prints so they don't obscure the password prompt. global global_status st = global_status global_status = None email = options.email if email is None: email = GetEmail("Email (login for uploading to %s)" % options.server) password = getpass.getpass("Password for %s: " % email) # Put status back. global_status = st return (email, password) # If this is the dev_appserver, use fake authentication. host = (options.host or options.server).lower() if host == "localhost" or host.startswith("localhost:"): email = options.email if email is None: email = "test@example.com" logging.info("Using debug user %s. Override with --email" % email) server = rpc_server_class( options.server, lambda: (email, "password"), host_override=options.host, extra_headers={"Cookie": 'dev_appserver_login="%s:False"' % email}, save_cookies=options.save_cookies) # Don't try to talk to ClientLogin. server.authenticated = True return server return rpc_server_class(options.server, GetUserCredentials, host_override=options.host, save_cookies=options.save_cookies)
python
def GetRpcServer(options): """Returns an instance of an AbstractRpcServer. Returns: A new AbstractRpcServer, on which RPC calls can be made. """ rpc_server_class = HttpRpcServer def GetUserCredentials(): """Prompts the user for a username and password.""" # Disable status prints so they don't obscure the password prompt. global global_status st = global_status global_status = None email = options.email if email is None: email = GetEmail("Email (login for uploading to %s)" % options.server) password = getpass.getpass("Password for %s: " % email) # Put status back. global_status = st return (email, password) # If this is the dev_appserver, use fake authentication. host = (options.host or options.server).lower() if host == "localhost" or host.startswith("localhost:"): email = options.email if email is None: email = "test@example.com" logging.info("Using debug user %s. Override with --email" % email) server = rpc_server_class( options.server, lambda: (email, "password"), host_override=options.host, extra_headers={"Cookie": 'dev_appserver_login="%s:False"' % email}, save_cookies=options.save_cookies) # Don't try to talk to ClientLogin. server.authenticated = True return server return rpc_server_class(options.server, GetUserCredentials, host_override=options.host, save_cookies=options.save_cookies)
[ "def", "GetRpcServer", "(", "options", ")", ":", "rpc_server_class", "=", "HttpRpcServer", "def", "GetUserCredentials", "(", ")", ":", "\"\"\"Prompts the user for a username and password.\"\"\"", "# Disable status prints so they don't obscure the password prompt.", "global", "globa...
Returns an instance of an AbstractRpcServer. Returns: A new AbstractRpcServer, on which RPC calls can be made.
[ "Returns", "an", "instance", "of", "an", "AbstractRpcServer", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L3048-L3091
train
46,858
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
RunShellWithReturnCode
def RunShellWithReturnCode(command, print_output=False, universal_newlines=True, env=os.environ): """Executes a command and returns the output from stdout and the return code. Args: command: Command to execute. print_output: If True, the output is printed to stdout. If False, both stdout and stderr are ignored. universal_newlines: Use universal_newlines flag (default: True). Returns: Tuple (output, return code) """ logging.info("Running %s", command) p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=use_shell, universal_newlines=universal_newlines, env=env) if print_output: output_array = [] while True: line = p.stdout.readline() if not line: break print line.strip("\n") output_array.append(line) output = "".join(output_array) else: output = p.stdout.read() p.wait() errout = p.stderr.read() if print_output and errout: print >>sys.stderr, errout p.stdout.close() p.stderr.close() return output, p.returncode
python
def RunShellWithReturnCode(command, print_output=False, universal_newlines=True, env=os.environ): """Executes a command and returns the output from stdout and the return code. Args: command: Command to execute. print_output: If True, the output is printed to stdout. If False, both stdout and stderr are ignored. universal_newlines: Use universal_newlines flag (default: True). Returns: Tuple (output, return code) """ logging.info("Running %s", command) p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=use_shell, universal_newlines=universal_newlines, env=env) if print_output: output_array = [] while True: line = p.stdout.readline() if not line: break print line.strip("\n") output_array.append(line) output = "".join(output_array) else: output = p.stdout.read() p.wait() errout = p.stderr.read() if print_output and errout: print >>sys.stderr, errout p.stdout.close() p.stderr.close() return output, p.returncode
[ "def", "RunShellWithReturnCode", "(", "command", ",", "print_output", "=", "False", ",", "universal_newlines", "=", "True", ",", "env", "=", "os", ".", "environ", ")", ":", "logging", ".", "info", "(", "\"Running %s\"", ",", "command", ")", "p", "=", "subp...
Executes a command and returns the output from stdout and the return code. Args: command: Command to execute. print_output: If True, the output is printed to stdout. If False, both stdout and stderr are ignored. universal_newlines: Use universal_newlines flag (default: True). Returns: Tuple (output, return code)
[ "Executes", "a", "command", "and", "returns", "the", "output", "from", "stdout", "and", "the", "return", "code", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L3141-L3174
train
46,859
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
SplitPatch
def SplitPatch(data): """Splits a patch into separate pieces for each file. Args: data: A string containing the output of svn diff. Returns: A list of 2-tuple (filename, text) where text is the svn diff output pertaining to filename. """ patches = [] filename = None diff = [] for line in data.splitlines(True): new_filename = None if line.startswith('Index:'): unused, new_filename = line.split(':', 1) new_filename = new_filename.strip() elif line.startswith('Property changes on:'): unused, temp_filename = line.split(':', 1) # When a file is modified, paths use '/' between directories, however # when a property is modified '\' is used on Windows. Make them the same # otherwise the file shows up twice. temp_filename = to_slash(temp_filename.strip()) if temp_filename != filename: # File has property changes but no modifications, create a new diff. new_filename = temp_filename if new_filename: if filename and diff: patches.append((filename, ''.join(diff))) filename = new_filename diff = [line] continue if diff is not None: diff.append(line) if filename and diff: patches.append((filename, ''.join(diff))) return patches
python
def SplitPatch(data): """Splits a patch into separate pieces for each file. Args: data: A string containing the output of svn diff. Returns: A list of 2-tuple (filename, text) where text is the svn diff output pertaining to filename. """ patches = [] filename = None diff = [] for line in data.splitlines(True): new_filename = None if line.startswith('Index:'): unused, new_filename = line.split(':', 1) new_filename = new_filename.strip() elif line.startswith('Property changes on:'): unused, temp_filename = line.split(':', 1) # When a file is modified, paths use '/' between directories, however # when a property is modified '\' is used on Windows. Make them the same # otherwise the file shows up twice. temp_filename = to_slash(temp_filename.strip()) if temp_filename != filename: # File has property changes but no modifications, create a new diff. new_filename = temp_filename if new_filename: if filename and diff: patches.append((filename, ''.join(diff))) filename = new_filename diff = [line] continue if diff is not None: diff.append(line) if filename and diff: patches.append((filename, ''.join(diff))) return patches
[ "def", "SplitPatch", "(", "data", ")", ":", "patches", "=", "[", "]", "filename", "=", "None", "diff", "=", "[", "]", "for", "line", "in", "data", ".", "splitlines", "(", "True", ")", ":", "new_filename", "=", "None", "if", "line", ".", "startswith",...
Splits a patch into separate pieces for each file. Args: data: A string containing the output of svn diff. Returns: A list of 2-tuple (filename, text) where text is the svn diff output pertaining to filename.
[ "Splits", "a", "patch", "into", "separate", "pieces", "for", "each", "file", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L3525-L3562
train
46,860
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
UploadSeparatePatches
def UploadSeparatePatches(issue, rpc_server, patchset, data, options): """Uploads a separate patch for each file in the diff output. Returns a list of [patch_key, filename] for each file. """ patches = SplitPatch(data) rv = [] for patch in patches: set_status("uploading patch for " + patch[0]) if len(patch[1]) > MAX_UPLOAD_SIZE: print ("Not uploading the patch for " + patch[0] + " because the file is too large.") continue form_fields = [("filename", patch[0])] if not options.download_base: form_fields.append(("content_upload", "1")) files = [("data", "data.diff", patch[1])] ctype, body = EncodeMultipartFormData(form_fields, files) url = "/%d/upload_patch/%d" % (int(issue), int(patchset)) print "Uploading patch for " + patch[0] response_body = rpc_server.Send(url, body, content_type=ctype) lines = response_body.splitlines() if not lines or lines[0] != "OK": StatusUpdate(" --> %s" % response_body) sys.exit(1) rv.append([lines[1], patch[0]]) return rv
python
def UploadSeparatePatches(issue, rpc_server, patchset, data, options): """Uploads a separate patch for each file in the diff output. Returns a list of [patch_key, filename] for each file. """ patches = SplitPatch(data) rv = [] for patch in patches: set_status("uploading patch for " + patch[0]) if len(patch[1]) > MAX_UPLOAD_SIZE: print ("Not uploading the patch for " + patch[0] + " because the file is too large.") continue form_fields = [("filename", patch[0])] if not options.download_base: form_fields.append(("content_upload", "1")) files = [("data", "data.diff", patch[1])] ctype, body = EncodeMultipartFormData(form_fields, files) url = "/%d/upload_patch/%d" % (int(issue), int(patchset)) print "Uploading patch for " + patch[0] response_body = rpc_server.Send(url, body, content_type=ctype) lines = response_body.splitlines() if not lines or lines[0] != "OK": StatusUpdate(" --> %s" % response_body) sys.exit(1) rv.append([lines[1], patch[0]]) return rv
[ "def", "UploadSeparatePatches", "(", "issue", ",", "rpc_server", ",", "patchset", ",", "data", ",", "options", ")", ":", "patches", "=", "SplitPatch", "(", "data", ")", "rv", "=", "[", "]", "for", "patch", "in", "patches", ":", "set_status", "(", "\"uplo...
Uploads a separate patch for each file in the diff output. Returns a list of [patch_key, filename] for each file.
[ "Uploads", "a", "separate", "patch", "for", "each", "file", "in", "the", "diff", "output", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L3565-L3591
train
46,861
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
AbstractRpcServer._CreateRequest
def _CreateRequest(self, url, data=None): """Creates a new urllib request.""" logging.debug("Creating request for: '%s' with payload:\n%s", url, data) req = urllib2.Request(url, data=data) if self.host_override: req.add_header("Host", self.host_override) for key, value in self.extra_headers.iteritems(): req.add_header(key, value) return req
python
def _CreateRequest(self, url, data=None): """Creates a new urllib request.""" logging.debug("Creating request for: '%s' with payload:\n%s", url, data) req = urllib2.Request(url, data=data) if self.host_override: req.add_header("Host", self.host_override) for key, value in self.extra_headers.iteritems(): req.add_header(key, value) return req
[ "def", "_CreateRequest", "(", "self", ",", "url", ",", "data", "=", "None", ")", ":", "logging", ".", "debug", "(", "\"Creating request for: '%s' with payload:\\n%s\"", ",", "url", ",", "data", ")", "req", "=", "urllib2", ".", "Request", "(", "url", ",", "...
Creates a new urllib request.
[ "Creates", "a", "new", "urllib", "request", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L2827-L2835
train
46,862
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
AbstractRpcServer._GetAuthToken
def _GetAuthToken(self, email, password): """Uses ClientLogin to authenticate the user, returning an auth token. Args: email: The user's email address password: The user's password Raises: ClientLoginError: If there was an error authenticating with ClientLogin. HTTPError: If there was some other form of HTTP error. Returns: The authentication token returned by ClientLogin. """ account_type = "GOOGLE" if self.host.endswith(".google.com") and not force_google_account: # Needed for use inside Google. account_type = "HOSTED" req = self._CreateRequest( url="https://www.google.com/accounts/ClientLogin", data=urllib.urlencode({ "Email": email, "Passwd": password, "service": "ah", "source": "rietveld-codereview-upload", "accountType": account_type, }), ) try: response = self.opener.open(req) response_body = response.read() response_dict = dict(x.split("=") for x in response_body.split("\n") if x) return response_dict["Auth"] except urllib2.HTTPError, e: if e.code == 403: body = e.read() response_dict = dict(x.split("=", 1) for x in body.split("\n") if x) raise ClientLoginError(req.get_full_url(), e.code, e.msg, e.headers, response_dict) else: raise
python
def _GetAuthToken(self, email, password): """Uses ClientLogin to authenticate the user, returning an auth token. Args: email: The user's email address password: The user's password Raises: ClientLoginError: If there was an error authenticating with ClientLogin. HTTPError: If there was some other form of HTTP error. Returns: The authentication token returned by ClientLogin. """ account_type = "GOOGLE" if self.host.endswith(".google.com") and not force_google_account: # Needed for use inside Google. account_type = "HOSTED" req = self._CreateRequest( url="https://www.google.com/accounts/ClientLogin", data=urllib.urlencode({ "Email": email, "Passwd": password, "service": "ah", "source": "rietveld-codereview-upload", "accountType": account_type, }), ) try: response = self.opener.open(req) response_body = response.read() response_dict = dict(x.split("=") for x in response_body.split("\n") if x) return response_dict["Auth"] except urllib2.HTTPError, e: if e.code == 403: body = e.read() response_dict = dict(x.split("=", 1) for x in body.split("\n") if x) raise ClientLoginError(req.get_full_url(), e.code, e.msg, e.headers, response_dict) else: raise
[ "def", "_GetAuthToken", "(", "self", ",", "email", ",", "password", ")", ":", "account_type", "=", "\"GOOGLE\"", "if", "self", ".", "host", ".", "endswith", "(", "\".google.com\"", ")", "and", "not", "force_google_account", ":", "# Needed for use inside Google.", ...
Uses ClientLogin to authenticate the user, returning an auth token. Args: email: The user's email address password: The user's password Raises: ClientLoginError: If there was an error authenticating with ClientLogin. HTTPError: If there was some other form of HTTP error. Returns: The authentication token returned by ClientLogin.
[ "Uses", "ClientLogin", "to", "authenticate", "the", "user", "returning", "an", "auth", "token", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L2837-L2876
train
46,863
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
AbstractRpcServer._GetAuthCookie
def _GetAuthCookie(self, auth_token): """Fetches authentication cookies for an authentication token. Args: auth_token: The authentication token returned by ClientLogin. Raises: HTTPError: If there was an error fetching the authentication cookies. """ # This is a dummy value to allow us to identify when we're successful. continue_location = "http://localhost/" args = {"continue": continue_location, "auth": auth_token} req = self._CreateRequest("https://%s/_ah/login?%s" % (self.host, urllib.urlencode(args))) try: response = self.opener.open(req) except urllib2.HTTPError, e: response = e if (response.code != 302 or response.info()["location"] != continue_location): raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg, response.headers, response.fp) self.authenticated = True
python
def _GetAuthCookie(self, auth_token): """Fetches authentication cookies for an authentication token. Args: auth_token: The authentication token returned by ClientLogin. Raises: HTTPError: If there was an error fetching the authentication cookies. """ # This is a dummy value to allow us to identify when we're successful. continue_location = "http://localhost/" args = {"continue": continue_location, "auth": auth_token} req = self._CreateRequest("https://%s/_ah/login?%s" % (self.host, urllib.urlencode(args))) try: response = self.opener.open(req) except urllib2.HTTPError, e: response = e if (response.code != 302 or response.info()["location"] != continue_location): raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg, response.headers, response.fp) self.authenticated = True
[ "def", "_GetAuthCookie", "(", "self", ",", "auth_token", ")", ":", "# This is a dummy value to allow us to identify when we're successful.", "continue_location", "=", "\"http://localhost/\"", "args", "=", "{", "\"continue\"", ":", "continue_location", ",", "\"auth\"", ":", ...
Fetches authentication cookies for an authentication token. Args: auth_token: The authentication token returned by ClientLogin. Raises: HTTPError: If there was an error fetching the authentication cookies.
[ "Fetches", "authentication", "cookies", "for", "an", "authentication", "token", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L2878-L2898
train
46,864
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
AbstractRpcServer._Authenticate
def _Authenticate(self): """Authenticates the user. The authentication process works as follows: 1) We get a username and password from the user 2) We use ClientLogin to obtain an AUTH token for the user (see http://code.google.com/apis/accounts/AuthForInstalledApps.html). 3) We pass the auth token to /_ah/login on the server to obtain an authentication cookie. If login was successful, it tries to redirect us to the URL we provided. If we attempt to access the upload API without first obtaining an authentication cookie, it returns a 401 response (or a 302) and directs us to authenticate ourselves with ClientLogin. """ for i in range(3): credentials = self.auth_function() try: auth_token = self._GetAuthToken(credentials[0], credentials[1]) except ClientLoginError, e: if e.msg == "BadAuthentication": print >>sys.stderr, "Invalid username or password." continue if e.msg == "CaptchaRequired": print >>sys.stderr, ( "Please go to\n" "https://www.google.com/accounts/DisplayUnlockCaptcha\n" "and verify you are a human. Then try again.") break if e.msg == "NotVerified": print >>sys.stderr, "Account not verified." break if e.msg == "TermsNotAgreed": print >>sys.stderr, "User has not agreed to TOS." break if e.msg == "AccountDeleted": print >>sys.stderr, "The user account has been deleted." break if e.msg == "AccountDisabled": print >>sys.stderr, "The user account has been disabled." break if e.msg == "ServiceDisabled": print >>sys.stderr, "The user's access to the service has been disabled." break if e.msg == "ServiceUnavailable": print >>sys.stderr, "The service is not available; try again later." break raise self._GetAuthCookie(auth_token) return
python
def _Authenticate(self): """Authenticates the user. The authentication process works as follows: 1) We get a username and password from the user 2) We use ClientLogin to obtain an AUTH token for the user (see http://code.google.com/apis/accounts/AuthForInstalledApps.html). 3) We pass the auth token to /_ah/login on the server to obtain an authentication cookie. If login was successful, it tries to redirect us to the URL we provided. If we attempt to access the upload API without first obtaining an authentication cookie, it returns a 401 response (or a 302) and directs us to authenticate ourselves with ClientLogin. """ for i in range(3): credentials = self.auth_function() try: auth_token = self._GetAuthToken(credentials[0], credentials[1]) except ClientLoginError, e: if e.msg == "BadAuthentication": print >>sys.stderr, "Invalid username or password." continue if e.msg == "CaptchaRequired": print >>sys.stderr, ( "Please go to\n" "https://www.google.com/accounts/DisplayUnlockCaptcha\n" "and verify you are a human. Then try again.") break if e.msg == "NotVerified": print >>sys.stderr, "Account not verified." break if e.msg == "TermsNotAgreed": print >>sys.stderr, "User has not agreed to TOS." break if e.msg == "AccountDeleted": print >>sys.stderr, "The user account has been deleted." break if e.msg == "AccountDisabled": print >>sys.stderr, "The user account has been disabled." break if e.msg == "ServiceDisabled": print >>sys.stderr, "The user's access to the service has been disabled." break if e.msg == "ServiceUnavailable": print >>sys.stderr, "The service is not available; try again later." break raise self._GetAuthCookie(auth_token) return
[ "def", "_Authenticate", "(", "self", ")", ":", "for", "i", "in", "range", "(", "3", ")", ":", "credentials", "=", "self", ".", "auth_function", "(", ")", "try", ":", "auth_token", "=", "self", ".", "_GetAuthToken", "(", "credentials", "[", "0", "]", ...
Authenticates the user. The authentication process works as follows: 1) We get a username and password from the user 2) We use ClientLogin to obtain an AUTH token for the user (see http://code.google.com/apis/accounts/AuthForInstalledApps.html). 3) We pass the auth token to /_ah/login on the server to obtain an authentication cookie. If login was successful, it tries to redirect us to the URL we provided. If we attempt to access the upload API without first obtaining an authentication cookie, it returns a 401 response (or a 302) and directs us to authenticate ourselves with ClientLogin.
[ "Authenticates", "the", "user", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L2900-L2949
train
46,865
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
HttpRpcServer._Authenticate
def _Authenticate(self): """Save the cookie jar after authentication.""" super(HttpRpcServer, self)._Authenticate() if self.save_cookies: StatusUpdate("Saving authentication cookies to %s" % self.cookie_file) self.cookie_jar.save()
python
def _Authenticate(self): """Save the cookie jar after authentication.""" super(HttpRpcServer, self)._Authenticate() if self.save_cookies: StatusUpdate("Saving authentication cookies to %s" % self.cookie_file) self.cookie_jar.save()
[ "def", "_Authenticate", "(", "self", ")", ":", "super", "(", "HttpRpcServer", ",", "self", ")", ".", "_Authenticate", "(", ")", "if", "self", ".", "save_cookies", ":", "StatusUpdate", "(", "\"Saving authentication cookies to %s\"", "%", "self", ".", "cookie_file...
Save the cookie jar after authentication.
[ "Save", "the", "cookie", "jar", "after", "authentication", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L3004-L3009
train
46,866
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
HttpRpcServer._GetOpener
def _GetOpener(self): """Returns an OpenerDirector that supports cookies and ignores redirects. Returns: A urllib2.OpenerDirector object. """ opener = urllib2.OpenerDirector() opener.add_handler(urllib2.ProxyHandler()) opener.add_handler(urllib2.UnknownHandler()) opener.add_handler(urllib2.HTTPHandler()) opener.add_handler(urllib2.HTTPDefaultErrorHandler()) opener.add_handler(urllib2.HTTPSHandler()) opener.add_handler(urllib2.HTTPErrorProcessor()) if self.save_cookies: self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies_" + server) self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file) if os.path.exists(self.cookie_file): try: self.cookie_jar.load() self.authenticated = True StatusUpdate("Loaded authentication cookies from %s" % self.cookie_file) except (cookielib.LoadError, IOError): # Failed to load cookies - just ignore them. pass else: # Create an empty cookie file with mode 600 fd = os.open(self.cookie_file, os.O_CREAT, 0600) os.close(fd) # Always chmod the cookie file os.chmod(self.cookie_file, 0600) else: # Don't save cookies across runs of update.py. self.cookie_jar = cookielib.CookieJar() opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar)) return opener
python
def _GetOpener(self): """Returns an OpenerDirector that supports cookies and ignores redirects. Returns: A urllib2.OpenerDirector object. """ opener = urllib2.OpenerDirector() opener.add_handler(urllib2.ProxyHandler()) opener.add_handler(urllib2.UnknownHandler()) opener.add_handler(urllib2.HTTPHandler()) opener.add_handler(urllib2.HTTPDefaultErrorHandler()) opener.add_handler(urllib2.HTTPSHandler()) opener.add_handler(urllib2.HTTPErrorProcessor()) if self.save_cookies: self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies_" + server) self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file) if os.path.exists(self.cookie_file): try: self.cookie_jar.load() self.authenticated = True StatusUpdate("Loaded authentication cookies from %s" % self.cookie_file) except (cookielib.LoadError, IOError): # Failed to load cookies - just ignore them. pass else: # Create an empty cookie file with mode 600 fd = os.open(self.cookie_file, os.O_CREAT, 0600) os.close(fd) # Always chmod the cookie file os.chmod(self.cookie_file, 0600) else: # Don't save cookies across runs of update.py. self.cookie_jar = cookielib.CookieJar() opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar)) return opener
[ "def", "_GetOpener", "(", "self", ")", ":", "opener", "=", "urllib2", ".", "OpenerDirector", "(", ")", "opener", ".", "add_handler", "(", "urllib2", ".", "ProxyHandler", "(", ")", ")", "opener", ".", "add_handler", "(", "urllib2", ".", "UnknownHandler", "(...
Returns an OpenerDirector that supports cookies and ignores redirects. Returns: A urllib2.OpenerDirector object.
[ "Returns", "an", "OpenerDirector", "that", "supports", "cookies", "and", "ignores", "redirects", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L3011-L3045
train
46,867
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
VersionControlSystem.CheckForUnknownFiles
def CheckForUnknownFiles(self): """Show an "are you sure?" prompt if there are unknown files.""" unknown_files = self.GetUnknownFiles() if unknown_files: print "The following files are not added to version control:" for line in unknown_files: print line prompt = "Are you sure to continue?(y/N) " answer = raw_input(prompt).strip() if answer != "y": ErrorExit("User aborted")
python
def CheckForUnknownFiles(self): """Show an "are you sure?" prompt if there are unknown files.""" unknown_files = self.GetUnknownFiles() if unknown_files: print "The following files are not added to version control:" for line in unknown_files: print line prompt = "Are you sure to continue?(y/N) " answer = raw_input(prompt).strip() if answer != "y": ErrorExit("User aborted")
[ "def", "CheckForUnknownFiles", "(", "self", ")", ":", "unknown_files", "=", "self", ".", "GetUnknownFiles", "(", ")", "if", "unknown_files", ":", "print", "\"The following files are not added to version control:\"", "for", "line", "in", "unknown_files", ":", "print", ...
Show an "are you sure?" prompt if there are unknown files.
[ "Show", "an", "are", "you", "sure?", "prompt", "if", "there", "are", "unknown", "files", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L3212-L3222
train
46,868
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
VersionControlSystem.GetBaseFiles
def GetBaseFiles(self, diff): """Helper that calls GetBase file for each file in the patch. Returns: A dictionary that maps from filename to GetBaseFile's tuple. Filenames are retrieved based on lines that start with "Index:" or "Property changes on:". """ files = {} for line in diff.splitlines(True): if line.startswith('Index:') or line.startswith('Property changes on:'): unused, filename = line.split(':', 1) # On Windows if a file has property changes its filename uses '\' # instead of '/'. filename = to_slash(filename.strip()) files[filename] = self.GetBaseFile(filename) return files
python
def GetBaseFiles(self, diff): """Helper that calls GetBase file for each file in the patch. Returns: A dictionary that maps from filename to GetBaseFile's tuple. Filenames are retrieved based on lines that start with "Index:" or "Property changes on:". """ files = {} for line in diff.splitlines(True): if line.startswith('Index:') or line.startswith('Property changes on:'): unused, filename = line.split(':', 1) # On Windows if a file has property changes its filename uses '\' # instead of '/'. filename = to_slash(filename.strip()) files[filename] = self.GetBaseFile(filename) return files
[ "def", "GetBaseFiles", "(", "self", ",", "diff", ")", ":", "files", "=", "{", "}", "for", "line", "in", "diff", ".", "splitlines", "(", "True", ")", ":", "if", "line", ".", "startswith", "(", "'Index:'", ")", "or", "line", ".", "startswith", "(", "...
Helper that calls GetBase file for each file in the patch. Returns: A dictionary that maps from filename to GetBaseFile's tuple. Filenames are retrieved based on lines that start with "Index:" or "Property changes on:".
[ "Helper", "that", "calls", "GetBase", "file", "for", "each", "file", "in", "the", "patch", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L3241-L3257
train
46,869
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
VersionControlSystem.IsImage
def IsImage(self, filename): """Returns true if the filename has an image extension.""" mimetype = mimetypes.guess_type(filename)[0] if not mimetype: return False return mimetype.startswith("image/")
python
def IsImage(self, filename): """Returns true if the filename has an image extension.""" mimetype = mimetypes.guess_type(filename)[0] if not mimetype: return False return mimetype.startswith("image/")
[ "def", "IsImage", "(", "self", ",", "filename", ")", ":", "mimetype", "=", "mimetypes", ".", "guess_type", "(", "filename", ")", "[", "0", "]", "if", "not", "mimetype", ":", "return", "False", "return", "mimetype", ".", "startswith", "(", "\"image/\"", "...
Returns true if the filename has an image extension.
[ "Returns", "true", "if", "the", "filename", "has", "an", "image", "extension", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L3346-L3351
train
46,870
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
VersionControlSystem.IsBinary
def IsBinary(self, filename): """Returns true if the guessed mimetyped isnt't in text group.""" mimetype = mimetypes.guess_type(filename)[0] if not mimetype: return False # e.g. README, "real" binaries usually have an extension # special case for text files which don't start with text/ if mimetype in TEXT_MIMETYPES: return False return not mimetype.startswith("text/")
python
def IsBinary(self, filename): """Returns true if the guessed mimetyped isnt't in text group.""" mimetype = mimetypes.guess_type(filename)[0] if not mimetype: return False # e.g. README, "real" binaries usually have an extension # special case for text files which don't start with text/ if mimetype in TEXT_MIMETYPES: return False return not mimetype.startswith("text/")
[ "def", "IsBinary", "(", "self", ",", "filename", ")", ":", "mimetype", "=", "mimetypes", ".", "guess_type", "(", "filename", ")", "[", "0", "]", "if", "not", "mimetype", ":", "return", "False", "# e.g. README, \"real\" binaries usually have an extension", "# speci...
Returns true if the guessed mimetyped isnt't in text group.
[ "Returns", "true", "if", "the", "guessed", "mimetyped", "isnt", "t", "in", "text", "group", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L3353-L3361
train
46,871
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
MercurialVCS._GetRelPath
def _GetRelPath(self, filename): """Get relative path of a file according to the current directory, given its logical path in the repo.""" assert filename.startswith(self.subdir), (filename, self.subdir) return filename[len(self.subdir):].lstrip(r"\/")
python
def _GetRelPath(self, filename): """Get relative path of a file according to the current directory, given its logical path in the repo.""" assert filename.startswith(self.subdir), (filename, self.subdir) return filename[len(self.subdir):].lstrip(r"\/")
[ "def", "_GetRelPath", "(", "self", ",", "filename", ")", ":", "assert", "filename", ".", "startswith", "(", "self", ".", "subdir", ")", ",", "(", "filename", ",", "self", ".", "subdir", ")", "return", "filename", "[", "len", "(", "self", ".", "subdir",...
Get relative path of a file according to the current directory, given its logical path in the repo.
[ "Get", "relative", "path", "of", "a", "file", "according", "to", "the", "current", "directory", "given", "its", "logical", "path", "in", "the", "repo", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L3417-L3421
train
46,872
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
MercurialVCS.GetUnknownFiles
def GetUnknownFiles(self): """Return a list of files unknown to the VCS.""" args = [] status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."], silent_ok=True) unknown_files = [] for line in status.splitlines(): st, fn = line.split(" ", 1) if st == "?": unknown_files.append(fn) return unknown_files
python
def GetUnknownFiles(self): """Return a list of files unknown to the VCS.""" args = [] status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."], silent_ok=True) unknown_files = [] for line in status.splitlines(): st, fn = line.split(" ", 1) if st == "?": unknown_files.append(fn) return unknown_files
[ "def", "GetUnknownFiles", "(", "self", ")", ":", "args", "=", "[", "]", "status", "=", "RunShell", "(", "[", "\"hg\"", ",", "\"status\"", ",", "\"--rev\"", ",", "self", ".", "base_rev", ",", "\"-u\"", ",", "\".\"", "]", ",", "silent_ok", "=", "True", ...
Return a list of files unknown to the VCS.
[ "Return", "a", "list", "of", "files", "unknown", "to", "the", "VCS", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L3449-L3459
train
46,873
kpdyer/regex2dfa
third_party/re2/re2/unicode.py
_URange
def _URange(s): """Converts string to Unicode range. '0001..0003' => [1, 2, 3]. '0001' => [1]. Args: s: string to convert Returns: Unicode range Raises: InputError: the string is not a valid Unicode range. """ a = s.split("..") if len(a) == 1: return [_UInt(a[0])] if len(a) == 2: lo = _UInt(a[0]) hi = _UInt(a[1]) if lo < hi: return range(lo, hi + 1) raise InputError("invalid Unicode range %s" % (s,))
python
def _URange(s): """Converts string to Unicode range. '0001..0003' => [1, 2, 3]. '0001' => [1]. Args: s: string to convert Returns: Unicode range Raises: InputError: the string is not a valid Unicode range. """ a = s.split("..") if len(a) == 1: return [_UInt(a[0])] if len(a) == 2: lo = _UInt(a[0]) hi = _UInt(a[1]) if lo < hi: return range(lo, hi + 1) raise InputError("invalid Unicode range %s" % (s,))
[ "def", "_URange", "(", "s", ")", ":", "a", "=", "s", ".", "split", "(", "\"..\"", ")", "if", "len", "(", "a", ")", "==", "1", ":", "return", "[", "_UInt", "(", "a", "[", "0", "]", ")", "]", "if", "len", "(", "a", ")", "==", "2", ":", "l...
Converts string to Unicode range. '0001..0003' => [1, 2, 3]. '0001' => [1]. Args: s: string to convert Returns: Unicode range Raises: InputError: the string is not a valid Unicode range.
[ "Converts", "string", "to", "Unicode", "range", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/re2/unicode.py#L48-L71
train
46,874
kpdyer/regex2dfa
third_party/re2/re2/unicode.py
_ParseContinue
def _ParseContinue(s): """Parses a Unicode continuation field. These are of the form '<Name, First>' or '<Name, Last>'. Instead of giving an explicit range in a single table entry, some Unicode tables use two entries, one for the first code value in the range and one for the last. The first entry's description is '<Name, First>' instead of 'Name' and the second is '<Name, Last>'. '<Name, First>' => ('Name', 'First') '<Name, Last>' => ('Name', 'Last') 'Anything else' => ('Anything else', None) Args: s: continuation field string Returns: pair: name and ('First', 'Last', or None) """ match = re.match("<(.*), (First|Last)>", s) if match is not None: return match.groups() return (s, None)
python
def _ParseContinue(s): """Parses a Unicode continuation field. These are of the form '<Name, First>' or '<Name, Last>'. Instead of giving an explicit range in a single table entry, some Unicode tables use two entries, one for the first code value in the range and one for the last. The first entry's description is '<Name, First>' instead of 'Name' and the second is '<Name, Last>'. '<Name, First>' => ('Name', 'First') '<Name, Last>' => ('Name', 'Last') 'Anything else' => ('Anything else', None) Args: s: continuation field string Returns: pair: name and ('First', 'Last', or None) """ match = re.match("<(.*), (First|Last)>", s) if match is not None: return match.groups() return (s, None)
[ "def", "_ParseContinue", "(", "s", ")", ":", "match", "=", "re", ".", "match", "(", "\"<(.*), (First|Last)>\"", ",", "s", ")", "if", "match", "is", "not", "None", ":", "return", "match", ".", "groups", "(", ")", "return", "(", "s", ",", "None", ")" ]
Parses a Unicode continuation field. These are of the form '<Name, First>' or '<Name, Last>'. Instead of giving an explicit range in a single table entry, some Unicode tables use two entries, one for the first code value in the range and one for the last. The first entry's description is '<Name, First>' instead of 'Name' and the second is '<Name, Last>'. '<Name, First>' => ('Name', 'First') '<Name, Last>' => ('Name', 'Last') 'Anything else' => ('Anything else', None) Args: s: continuation field string Returns: pair: name and ('First', 'Last', or None)
[ "Parses", "a", "Unicode", "continuation", "field", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/re2/unicode.py#L93-L117
train
46,875
kpdyer/regex2dfa
third_party/re2/re2/unicode.py
ReadUnicodeTable
def ReadUnicodeTable(filename, nfields, doline): """Generic Unicode table text file reader. The reader takes care of stripping out comments and also parsing the two different ways that the Unicode tables specify code ranges (using the .. notation and splitting the range across multiple lines). Each non-comment line in the table is expected to have the given number of fields. The first field is known to be the Unicode value and the second field its description. The reader calls doline(codes, fields) for each entry in the table. If fn raises an exception, the reader prints that exception, prefixed with the file name and line number, and continues processing the file. When done with the file, the reader re-raises the first exception encountered during the file. Arguments: filename: the Unicode data file to read, or a file-like object. nfields: the number of expected fields per line in that file. doline: the function to call for each table entry. Raises: InputError: nfields is invalid (must be >= 2). """ if nfields < 2: raise InputError("invalid number of fields %d" % (nfields,)) if type(filename) == str: if filename.startswith("http://"): fil = urllib2.urlopen(filename) else: fil = open(filename, "r") else: fil = filename first = None # first code in multiline range expect_last = None # tag expected for "Last" line in multiline range lineno = 0 # current line number for line in fil: lineno += 1 try: # Chop # comments and white space; ignore empty lines. sharp = line.find("#") if sharp >= 0: line = line[:sharp] line = line.strip() if not line: continue # Split fields on ";", chop more white space. # Must have the expected number of fields. fields = [s.strip() for s in line.split(";")] if len(fields) != nfields: raise InputError("wrong number of fields %d %d - %s" % (len(fields), nfields, line)) # The Unicode text files have two different ways # to list a Unicode range. Either the first field is # itself a range (0000..FFFF), or the range is split # across two lines, with the second field noting # the continuation. codes = _URange(fields[0]) (name, cont) = _ParseContinue(fields[1]) if expect_last is not None: # If the last line gave the First code in a range, # this one had better give the Last one. if (len(codes) != 1 or codes[0] <= first or cont != "Last" or name != expect_last): raise InputError("expected Last line for %s" % (expect_last,)) codes = range(first, codes[0] + 1) first = None expect_last = None fields[0] = "%04X..%04X" % (codes[0], codes[-1]) fields[1] = name elif cont == "First": # Otherwise, if this is the First code in a range, # remember it and go to the next line. if len(codes) != 1: raise InputError("bad First line: range given") expect_last = name first = codes[0] continue doline(codes, fields) except Exception, e: print "%s:%d: %s" % (filename, lineno, e) raise if expect_last is not None: raise InputError("expected Last line for %s; got EOF" % (expect_last,))
python
def ReadUnicodeTable(filename, nfields, doline): """Generic Unicode table text file reader. The reader takes care of stripping out comments and also parsing the two different ways that the Unicode tables specify code ranges (using the .. notation and splitting the range across multiple lines). Each non-comment line in the table is expected to have the given number of fields. The first field is known to be the Unicode value and the second field its description. The reader calls doline(codes, fields) for each entry in the table. If fn raises an exception, the reader prints that exception, prefixed with the file name and line number, and continues processing the file. When done with the file, the reader re-raises the first exception encountered during the file. Arguments: filename: the Unicode data file to read, or a file-like object. nfields: the number of expected fields per line in that file. doline: the function to call for each table entry. Raises: InputError: nfields is invalid (must be >= 2). """ if nfields < 2: raise InputError("invalid number of fields %d" % (nfields,)) if type(filename) == str: if filename.startswith("http://"): fil = urllib2.urlopen(filename) else: fil = open(filename, "r") else: fil = filename first = None # first code in multiline range expect_last = None # tag expected for "Last" line in multiline range lineno = 0 # current line number for line in fil: lineno += 1 try: # Chop # comments and white space; ignore empty lines. sharp = line.find("#") if sharp >= 0: line = line[:sharp] line = line.strip() if not line: continue # Split fields on ";", chop more white space. # Must have the expected number of fields. fields = [s.strip() for s in line.split(";")] if len(fields) != nfields: raise InputError("wrong number of fields %d %d - %s" % (len(fields), nfields, line)) # The Unicode text files have two different ways # to list a Unicode range. Either the first field is # itself a range (0000..FFFF), or the range is split # across two lines, with the second field noting # the continuation. codes = _URange(fields[0]) (name, cont) = _ParseContinue(fields[1]) if expect_last is not None: # If the last line gave the First code in a range, # this one had better give the Last one. if (len(codes) != 1 or codes[0] <= first or cont != "Last" or name != expect_last): raise InputError("expected Last line for %s" % (expect_last,)) codes = range(first, codes[0] + 1) first = None expect_last = None fields[0] = "%04X..%04X" % (codes[0], codes[-1]) fields[1] = name elif cont == "First": # Otherwise, if this is the First code in a range, # remember it and go to the next line. if len(codes) != 1: raise InputError("bad First line: range given") expect_last = name first = codes[0] continue doline(codes, fields) except Exception, e: print "%s:%d: %s" % (filename, lineno, e) raise if expect_last is not None: raise InputError("expected Last line for %s; got EOF" % (expect_last,))
[ "def", "ReadUnicodeTable", "(", "filename", ",", "nfields", ",", "doline", ")", ":", "if", "nfields", "<", "2", ":", "raise", "InputError", "(", "\"invalid number of fields %d\"", "%", "(", "nfields", ",", ")", ")", "if", "type", "(", "filename", ")", "=="...
Generic Unicode table text file reader. The reader takes care of stripping out comments and also parsing the two different ways that the Unicode tables specify code ranges (using the .. notation and splitting the range across multiple lines). Each non-comment line in the table is expected to have the given number of fields. The first field is known to be the Unicode value and the second field its description. The reader calls doline(codes, fields) for each entry in the table. If fn raises an exception, the reader prints that exception, prefixed with the file name and line number, and continues processing the file. When done with the file, the reader re-raises the first exception encountered during the file. Arguments: filename: the Unicode data file to read, or a file-like object. nfields: the number of expected fields per line in that file. doline: the function to call for each table entry. Raises: InputError: nfields is invalid (must be >= 2).
[ "Generic", "Unicode", "table", "text", "file", "reader", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/re2/unicode.py#L120-L216
train
46,876
kpdyer/regex2dfa
third_party/re2/re2/unicode.py
CaseGroups
def CaseGroups(unicode_dir=_UNICODE_DIR): """Returns list of Unicode code groups equivalent under case folding. Each group is a sorted list of code points, and the list of groups is sorted by first code point in the group. Args: unicode_dir: Unicode data directory Returns: list of Unicode code groups """ # Dict mapping lowercase code point to fold-equivalent group. togroup = {} def DoLine(codes, fields): """Process single CaseFolding.txt line, updating togroup.""" (_, foldtype, lower, _) = fields if foldtype not in ("C", "S"): return lower = _UInt(lower) togroup.setdefault(lower, [lower]).extend(codes) ReadUnicodeTable(unicode_dir+"/CaseFolding.txt", 4, DoLine) groups = togroup.values() for g in groups: g.sort() groups.sort() return togroup, groups
python
def CaseGroups(unicode_dir=_UNICODE_DIR): """Returns list of Unicode code groups equivalent under case folding. Each group is a sorted list of code points, and the list of groups is sorted by first code point in the group. Args: unicode_dir: Unicode data directory Returns: list of Unicode code groups """ # Dict mapping lowercase code point to fold-equivalent group. togroup = {} def DoLine(codes, fields): """Process single CaseFolding.txt line, updating togroup.""" (_, foldtype, lower, _) = fields if foldtype not in ("C", "S"): return lower = _UInt(lower) togroup.setdefault(lower, [lower]).extend(codes) ReadUnicodeTable(unicode_dir+"/CaseFolding.txt", 4, DoLine) groups = togroup.values() for g in groups: g.sort() groups.sort() return togroup, groups
[ "def", "CaseGroups", "(", "unicode_dir", "=", "_UNICODE_DIR", ")", ":", "# Dict mapping lowercase code point to fold-equivalent group.", "togroup", "=", "{", "}", "def", "DoLine", "(", "codes", ",", "fields", ")", ":", "\"\"\"Process single CaseFolding.txt line, updating to...
Returns list of Unicode code groups equivalent under case folding. Each group is a sorted list of code points, and the list of groups is sorted by first code point in the group. Args: unicode_dir: Unicode data directory Returns: list of Unicode code groups
[ "Returns", "list", "of", "Unicode", "code", "groups", "equivalent", "under", "case", "folding", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/re2/unicode.py#L219-L250
train
46,877
kpdyer/regex2dfa
third_party/re2/re2/unicode.py
Scripts
def Scripts(unicode_dir=_UNICODE_DIR): """Returns dict mapping script names to code lists. Args: unicode_dir: Unicode data directory Returns: dict mapping script names to code lists """ scripts = {} def DoLine(codes, fields): """Process single Scripts.txt line, updating scripts.""" (_, name) = fields scripts.setdefault(name, []).extend(codes) ReadUnicodeTable(unicode_dir+"/Scripts.txt", 2, DoLine) return scripts
python
def Scripts(unicode_dir=_UNICODE_DIR): """Returns dict mapping script names to code lists. Args: unicode_dir: Unicode data directory Returns: dict mapping script names to code lists """ scripts = {} def DoLine(codes, fields): """Process single Scripts.txt line, updating scripts.""" (_, name) = fields scripts.setdefault(name, []).extend(codes) ReadUnicodeTable(unicode_dir+"/Scripts.txt", 2, DoLine) return scripts
[ "def", "Scripts", "(", "unicode_dir", "=", "_UNICODE_DIR", ")", ":", "scripts", "=", "{", "}", "def", "DoLine", "(", "codes", ",", "fields", ")", ":", "\"\"\"Process single Scripts.txt line, updating scripts.\"\"\"", "(", "_", ",", "name", ")", "=", "fields", ...
Returns dict mapping script names to code lists. Args: unicode_dir: Unicode data directory Returns: dict mapping script names to code lists
[ "Returns", "dict", "mapping", "script", "names", "to", "code", "lists", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/re2/unicode.py#L253-L271
train
46,878
kpdyer/regex2dfa
third_party/re2/re2/unicode.py
Categories
def Categories(unicode_dir=_UNICODE_DIR): """Returns dict mapping category names to code lists. Args: unicode_dir: Unicode data directory Returns: dict mapping category names to code lists """ categories = {} def DoLine(codes, fields): """Process single UnicodeData.txt line, updating categories.""" category = fields[2] categories.setdefault(category, []).extend(codes) # Add codes from Lu into L, etc. if len(category) > 1: short = category[0] categories.setdefault(short, []).extend(codes) ReadUnicodeTable(unicode_dir+"/UnicodeData.txt", 15, DoLine) return categories
python
def Categories(unicode_dir=_UNICODE_DIR): """Returns dict mapping category names to code lists. Args: unicode_dir: Unicode data directory Returns: dict mapping category names to code lists """ categories = {} def DoLine(codes, fields): """Process single UnicodeData.txt line, updating categories.""" category = fields[2] categories.setdefault(category, []).extend(codes) # Add codes from Lu into L, etc. if len(category) > 1: short = category[0] categories.setdefault(short, []).extend(codes) ReadUnicodeTable(unicode_dir+"/UnicodeData.txt", 15, DoLine) return categories
[ "def", "Categories", "(", "unicode_dir", "=", "_UNICODE_DIR", ")", ":", "categories", "=", "{", "}", "def", "DoLine", "(", "codes", ",", "fields", ")", ":", "\"\"\"Process single UnicodeData.txt line, updating categories.\"\"\"", "category", "=", "fields", "[", "2",...
Returns dict mapping category names to code lists. Args: unicode_dir: Unicode data directory Returns: dict mapping category names to code lists
[ "Returns", "dict", "mapping", "category", "names", "to", "code", "lists", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/re2/unicode.py#L274-L296
train
46,879
kpdyer/regex2dfa
third_party/re2/re2/make_unicode_casefold.py
_AddDelta
def _AddDelta(a, delta): """Return a + delta, handling EvenOdd and OddEven specially.""" if type(delta) == int: return a+delta if delta == 'EvenOdd': if a%2 == 0: return a+1 else: return a-1 if delta == 'OddEven': if a%2 == 1: return a+1 else: return a-1 print >>sys.stderr, "Bad Delta: ", delta raise "Bad Delta"
python
def _AddDelta(a, delta): """Return a + delta, handling EvenOdd and OddEven specially.""" if type(delta) == int: return a+delta if delta == 'EvenOdd': if a%2 == 0: return a+1 else: return a-1 if delta == 'OddEven': if a%2 == 1: return a+1 else: return a-1 print >>sys.stderr, "Bad Delta: ", delta raise "Bad Delta"
[ "def", "_AddDelta", "(", "a", ",", "delta", ")", ":", "if", "type", "(", "delta", ")", "==", "int", ":", "return", "a", "+", "delta", "if", "delta", "==", "'EvenOdd'", ":", "if", "a", "%", "2", "==", "0", ":", "return", "a", "+", "1", "else", ...
Return a + delta, handling EvenOdd and OddEven specially.
[ "Return", "a", "+", "delta", "handling", "EvenOdd", "and", "OddEven", "specially", "." ]
109f877e60ef0dfcb430f11516d215930b7b9936
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/re2/make_unicode_casefold.py#L45-L60
train
46,880
marten-de-vries/Flask-WebSub
flask_websub/subscriber/__init__.py
Subscriber.unsubscribe
def unsubscribe(self, callback_id): """Ask the hub to cancel the subscription for callback_id, then delete it from the local database if successful. """ request = self.get_active_subscription(callback_id) request['mode'] = 'unsubscribe' self.subscribe_impl(callback_id, **request)
python
def unsubscribe(self, callback_id): """Ask the hub to cancel the subscription for callback_id, then delete it from the local database if successful. """ request = self.get_active_subscription(callback_id) request['mode'] = 'unsubscribe' self.subscribe_impl(callback_id, **request)
[ "def", "unsubscribe", "(", "self", ",", "callback_id", ")", ":", "request", "=", "self", ".", "get_active_subscription", "(", "callback_id", ")", "request", "[", "'mode'", "]", "=", "'unsubscribe'", "self", ".", "subscribe_impl", "(", "callback_id", ",", "*", ...
Ask the hub to cancel the subscription for callback_id, then delete it from the local database if successful.
[ "Ask", "the", "hub", "to", "cancel", "the", "subscription", "for", "callback_id", "then", "delete", "it", "from", "the", "local", "database", "if", "successful", "." ]
422d5b597245554c47e881483f99cae7c57a81ba
https://github.com/marten-de-vries/Flask-WebSub/blob/422d5b597245554c47e881483f99cae7c57a81ba/flask_websub/subscriber/__init__.py#L161-L168
train
46,881
marten-de-vries/Flask-WebSub
flask_websub/subscriber/discovery.py
discover
def discover(url, timeout=None): """Discover the hub url and topic url of a given url. Firstly, by inspecting the page's headers, secondarily by inspecting the content for link tags. timeout determines how long to wait for the url to load. It defaults to 3. """ resp = get_content({'REQUEST_TIMEOUT': timeout}, url) parser = LinkParser() parser.hub_url = (resp.links.get('hub') or {}).get('url') parser.topic_url = (resp.links.get('self') or {}).get('url') try: parser.updated() for chunk in resp.iter_content(chunk_size=None, decode_unicode=True): parser.feed(chunk) parser.close() except Finished: return {'hub_url': parser.hub_url, 'topic_url': parser.topic_url} raise DiscoveryError("Could not find hub url in topic page")
python
def discover(url, timeout=None): """Discover the hub url and topic url of a given url. Firstly, by inspecting the page's headers, secondarily by inspecting the content for link tags. timeout determines how long to wait for the url to load. It defaults to 3. """ resp = get_content({'REQUEST_TIMEOUT': timeout}, url) parser = LinkParser() parser.hub_url = (resp.links.get('hub') or {}).get('url') parser.topic_url = (resp.links.get('self') or {}).get('url') try: parser.updated() for chunk in resp.iter_content(chunk_size=None, decode_unicode=True): parser.feed(chunk) parser.close() except Finished: return {'hub_url': parser.hub_url, 'topic_url': parser.topic_url} raise DiscoveryError("Could not find hub url in topic page")
[ "def", "discover", "(", "url", ",", "timeout", "=", "None", ")", ":", "resp", "=", "get_content", "(", "{", "'REQUEST_TIMEOUT'", ":", "timeout", "}", ",", "url", ")", "parser", "=", "LinkParser", "(", ")", "parser", ".", "hub_url", "=", "(", "resp", ...
Discover the hub url and topic url of a given url. Firstly, by inspecting the page's headers, secondarily by inspecting the content for link tags. timeout determines how long to wait for the url to load. It defaults to 3.
[ "Discover", "the", "hub", "url", "and", "topic", "url", "of", "a", "given", "url", ".", "Firstly", "by", "inspecting", "the", "page", "s", "headers", "secondarily", "by", "inspecting", "the", "content", "for", "link", "tags", "." ]
422d5b597245554c47e881483f99cae7c57a81ba
https://github.com/marten-de-vries/Flask-WebSub/blob/422d5b597245554c47e881483f99cae7c57a81ba/flask_websub/subscriber/discovery.py#L8-L28
train
46,882
LLNL/certipy
certipy/certipy.py
open_tls_file
def open_tls_file(file_path, mode, private=True): """Context to ensure correct file permissions for certs and directories Ensures: - A containing directory with appropriate permissions - Correct file permissions based on what the file is (0o600 for keys and 0o644 for certs) """ containing_dir = os.path.dirname(file_path) fh = None try: if 'w' in mode: os.chmod(containing_dir, mode=0o755) fh = open(file_path, mode) except OSError as e: if 'w' in mode: os.makedirs(containing_dir, mode=0o755, exist_ok=True) os.chmod(containing_dir, mode=0o755) fh = open(file_path, 'w') else: raise yield fh mode = 0o600 if private else 0o644 os.chmod(file_path, mode=mode) fh.close()
python
def open_tls_file(file_path, mode, private=True): """Context to ensure correct file permissions for certs and directories Ensures: - A containing directory with appropriate permissions - Correct file permissions based on what the file is (0o600 for keys and 0o644 for certs) """ containing_dir = os.path.dirname(file_path) fh = None try: if 'w' in mode: os.chmod(containing_dir, mode=0o755) fh = open(file_path, mode) except OSError as e: if 'w' in mode: os.makedirs(containing_dir, mode=0o755, exist_ok=True) os.chmod(containing_dir, mode=0o755) fh = open(file_path, 'w') else: raise yield fh mode = 0o600 if private else 0o644 os.chmod(file_path, mode=mode) fh.close()
[ "def", "open_tls_file", "(", "file_path", ",", "mode", ",", "private", "=", "True", ")", ":", "containing_dir", "=", "os", ".", "path", ".", "dirname", "(", "file_path", ")", "fh", "=", "None", "try", ":", "if", "'w'", "in", "mode", ":", "os", ".", ...
Context to ensure correct file permissions for certs and directories Ensures: - A containing directory with appropriate permissions - Correct file permissions based on what the file is (0o600 for keys and 0o644 for certs)
[ "Context", "to", "ensure", "correct", "file", "permissions", "for", "certs", "and", "directories" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L49-L74
train
46,883
LLNL/certipy
certipy/certipy.py
TLSFile.load
def load(self): """Load from a file and return an x509 object""" private = self.is_private() with open_tls_file(self.file_path, 'r', private=private) as fh: if private: self.x509 = crypto.load_privatekey(self.encoding, fh.read()) else: self.x509 = crypto.load_certificate(self.encoding, fh.read()) return self.x509
python
def load(self): """Load from a file and return an x509 object""" private = self.is_private() with open_tls_file(self.file_path, 'r', private=private) as fh: if private: self.x509 = crypto.load_privatekey(self.encoding, fh.read()) else: self.x509 = crypto.load_certificate(self.encoding, fh.read()) return self.x509
[ "def", "load", "(", "self", ")", ":", "private", "=", "self", ".", "is_private", "(", ")", "with", "open_tls_file", "(", "self", ".", "file_path", ",", "'r'", ",", "private", "=", "private", ")", "as", "fh", ":", "if", "private", ":", "self", ".", ...
Load from a file and return an x509 object
[ "Load", "from", "a", "file", "and", "return", "an", "x509", "object" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L133-L142
train
46,884
LLNL/certipy
certipy/certipy.py
TLSFile.save
def save(self, x509): """Persist this x509 object to disk""" self.x509 = x509 with open_tls_file(self.file_path, 'w', private=self.is_private()) as fh: fh.write(str(self))
python
def save(self, x509): """Persist this x509 object to disk""" self.x509 = x509 with open_tls_file(self.file_path, 'w', private=self.is_private()) as fh: fh.write(str(self))
[ "def", "save", "(", "self", ",", "x509", ")", ":", "self", ".", "x509", "=", "x509", "with", "open_tls_file", "(", "self", ".", "file_path", ",", "'w'", ",", "private", "=", "self", ".", "is_private", "(", ")", ")", "as", "fh", ":", "fh", ".", "w...
Persist this x509 object to disk
[ "Persist", "this", "x509", "object", "to", "disk" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L144-L150
train
46,885
LLNL/certipy
certipy/certipy.py
TLSFileBundle._setup_tls_files
def _setup_tls_files(self, files): """Initiates TLSFIle objects with the paths given to this bundle""" for file_type in TLSFileType: if file_type.value in files: file_path = files[file_type.value] setattr(self, file_type.value, TLSFile(file_path, file_type=file_type))
python
def _setup_tls_files(self, files): """Initiates TLSFIle objects with the paths given to this bundle""" for file_type in TLSFileType: if file_type.value in files: file_path = files[file_type.value] setattr(self, file_type.value, TLSFile(file_path, file_type=file_type))
[ "def", "_setup_tls_files", "(", "self", ",", "files", ")", ":", "for", "file_type", "in", "TLSFileType", ":", "if", "file_type", ".", "value", "in", "files", ":", "file_path", "=", "files", "[", "file_type", ".", "value", "]", "setattr", "(", "self", ","...
Initiates TLSFIle objects with the paths given to this bundle
[ "Initiates", "TLSFIle", "objects", "with", "the", "paths", "given", "to", "this", "bundle" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L171-L178
train
46,886
LLNL/certipy
certipy/certipy.py
TLSFileBundle.save_x509s
def save_x509s(self, x509s): """Saves the x509 objects to the paths known by this bundle""" for file_type in TLSFileType: if file_type.value in x509s: x509 = x509s[file_type.value] if file_type is not TLSFileType.CA: # persist this key or cert to disk tlsfile = getattr(self, file_type.value) if tlsfile: tlsfile.save(x509)
python
def save_x509s(self, x509s): """Saves the x509 objects to the paths known by this bundle""" for file_type in TLSFileType: if file_type.value in x509s: x509 = x509s[file_type.value] if file_type is not TLSFileType.CA: # persist this key or cert to disk tlsfile = getattr(self, file_type.value) if tlsfile: tlsfile.save(x509)
[ "def", "save_x509s", "(", "self", ",", "x509s", ")", ":", "for", "file_type", "in", "TLSFileType", ":", "if", "file_type", ".", "value", "in", "x509s", ":", "x509", "=", "x509s", "[", "file_type", ".", "value", "]", "if", "file_type", "is", "not", "TLS...
Saves the x509 objects to the paths known by this bundle
[ "Saves", "the", "x509", "objects", "to", "the", "paths", "known", "by", "this", "bundle" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L180-L190
train
46,887
LLNL/certipy
certipy/certipy.py
TLSFileBundle.to_record
def to_record(self): """Create a CertStore record from this TLSFileBundle""" tf_list = [getattr(self, k, None) for k in [_.value for _ in TLSFileType]] # If a cert isn't defined in this bundle, remove it tf_list = filter(lambda x: x, tf_list) files = {tf.file_type.value: tf.file_path for tf in tf_list} self.record['files'] = files return self.record
python
def to_record(self): """Create a CertStore record from this TLSFileBundle""" tf_list = [getattr(self, k, None) for k in [_.value for _ in TLSFileType]] # If a cert isn't defined in this bundle, remove it tf_list = filter(lambda x: x, tf_list) files = {tf.file_type.value: tf.file_path for tf in tf_list} self.record['files'] = files return self.record
[ "def", "to_record", "(", "self", ")", ":", "tf_list", "=", "[", "getattr", "(", "self", ",", "k", ",", "None", ")", "for", "k", "in", "[", "_", ".", "value", "for", "_", "in", "TLSFileType", "]", "]", "# If a cert isn't defined in this bundle, remove it", ...
Create a CertStore record from this TLSFileBundle
[ "Create", "a", "CertStore", "record", "from", "this", "TLSFileBundle" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L203-L212
train
46,888
LLNL/certipy
certipy/certipy.py
TLSFileBundle.from_record
def from_record(self, record): """Build a bundle from a CertStore record""" self.record = record self._setup_tls_files(self.record['files']) return self
python
def from_record(self, record): """Build a bundle from a CertStore record""" self.record = record self._setup_tls_files(self.record['files']) return self
[ "def", "from_record", "(", "self", ",", "record", ")", ":", "self", ".", "record", "=", "record", "self", ".", "_setup_tls_files", "(", "self", ".", "record", "[", "'files'", "]", ")", "return", "self" ]
Build a bundle from a CertStore record
[ "Build", "a", "bundle", "from", "a", "CertStore", "record" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L214-L219
train
46,889
LLNL/certipy
certipy/certipy.py
CertStore.save
def save(self): """Write the store dict to a file specified by store_file_path""" with open(self.store_file_path, 'w') as fh: fh.write(json.dumps(self.store, indent=4))
python
def save(self): """Write the store dict to a file specified by store_file_path""" with open(self.store_file_path, 'w') as fh: fh.write(json.dumps(self.store, indent=4))
[ "def", "save", "(", "self", ")", ":", "with", "open", "(", "self", ".", "store_file_path", ",", "'w'", ")", "as", "fh", ":", "fh", ".", "write", "(", "json", ".", "dumps", "(", "self", ".", "store", ",", "indent", "=", "4", ")", ")" ]
Write the store dict to a file specified by store_file_path
[ "Write", "the", "store", "dict", "to", "a", "file", "specified", "by", "store_file_path" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L253-L257
train
46,890
LLNL/certipy
certipy/certipy.py
CertStore.load
def load(self): """Read the store dict from file""" with open(self.store_file_path, 'r') as fh: self.store = json.loads(fh.read())
python
def load(self): """Read the store dict from file""" with open(self.store_file_path, 'r') as fh: self.store = json.loads(fh.read())
[ "def", "load", "(", "self", ")", ":", "with", "open", "(", "self", ".", "store_file_path", ",", "'r'", ")", "as", "fh", ":", "self", ".", "store", "=", "json", ".", "loads", "(", "fh", ".", "read", "(", ")", ")" ]
Read the store dict from file
[ "Read", "the", "store", "dict", "from", "file" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L259-L263
train
46,891
LLNL/certipy
certipy/certipy.py
CertStore.get_record
def get_record(self, common_name): """Return the record associated with this common name In most cases, all that's really needed to use an existing cert are the file paths to the files that make up that cert. This method returns just that and doesn't bother loading the associated files. """ try: record = self.store[common_name] return record except KeyError as e: raise CertNotFoundError( "Unable to find record of {name}" .format(name=common_name), errors=e)
python
def get_record(self, common_name): """Return the record associated with this common name In most cases, all that's really needed to use an existing cert are the file paths to the files that make up that cert. This method returns just that and doesn't bother loading the associated files. """ try: record = self.store[common_name] return record except KeyError as e: raise CertNotFoundError( "Unable to find record of {name}" .format(name=common_name), errors=e)
[ "def", "get_record", "(", "self", ",", "common_name", ")", ":", "try", ":", "record", "=", "self", ".", "store", "[", "common_name", "]", "return", "record", "except", "KeyError", "as", "e", ":", "raise", "CertNotFoundError", "(", "\"Unable to find record of {...
Return the record associated with this common name In most cases, all that's really needed to use an existing cert are the file paths to the files that make up that cert. This method returns just that and doesn't bother loading the associated files.
[ "Return", "the", "record", "associated", "with", "this", "common", "name" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L265-L279
train
46,892
LLNL/certipy
certipy/certipy.py
CertStore.get_files
def get_files(self, common_name): """Return a bundle of TLS files associated with a common name""" record = self.get_record(common_name) return TLSFileBundle(common_name).from_record(record)
python
def get_files(self, common_name): """Return a bundle of TLS files associated with a common name""" record = self.get_record(common_name) return TLSFileBundle(common_name).from_record(record)
[ "def", "get_files", "(", "self", ",", "common_name", ")", ":", "record", "=", "self", ".", "get_record", "(", "common_name", ")", "return", "TLSFileBundle", "(", "common_name", ")", ".", "from_record", "(", "record", ")" ]
Return a bundle of TLS files associated with a common name
[ "Return", "a", "bundle", "of", "TLS", "files", "associated", "with", "a", "common", "name" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L281-L285
train
46,893
LLNL/certipy
certipy/certipy.py
CertStore.add_record
def add_record(self, common_name, serial=0, parent_ca='', signees=None, files=None, record=None, is_ca=False, overwrite=False): """Manually create a record of certs Generally, Certipy can be left to manage certificate locations and storage, but it is occasionally useful to keep track of a set of certs that were created externally (for example, let's encrypt) """ if not overwrite: try: self.get_record(common_name) raise CertExistsError( "Certificate {name} already exists!" " Set overwrite=True to force add." .format(name=common_name)) except CertNotFoundError: pass record = record or { 'serial': serial, 'is_ca': is_ca, 'parent_ca': parent_ca, 'signees': signees, 'files': files, } self.store[common_name] = record self.save()
python
def add_record(self, common_name, serial=0, parent_ca='', signees=None, files=None, record=None, is_ca=False, overwrite=False): """Manually create a record of certs Generally, Certipy can be left to manage certificate locations and storage, but it is occasionally useful to keep track of a set of certs that were created externally (for example, let's encrypt) """ if not overwrite: try: self.get_record(common_name) raise CertExistsError( "Certificate {name} already exists!" " Set overwrite=True to force add." .format(name=common_name)) except CertNotFoundError: pass record = record or { 'serial': serial, 'is_ca': is_ca, 'parent_ca': parent_ca, 'signees': signees, 'files': files, } self.store[common_name] = record self.save()
[ "def", "add_record", "(", "self", ",", "common_name", ",", "serial", "=", "0", ",", "parent_ca", "=", "''", ",", "signees", "=", "None", ",", "files", "=", "None", ",", "record", "=", "None", ",", "is_ca", "=", "False", ",", "overwrite", "=", "False"...
Manually create a record of certs Generally, Certipy can be left to manage certificate locations and storage, but it is occasionally useful to keep track of a set of certs that were created externally (for example, let's encrypt)
[ "Manually", "create", "a", "record", "of", "certs" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L287-L315
train
46,894
LLNL/certipy
certipy/certipy.py
CertStore.add_files
def add_files(self, common_name, x509s, files=None, parent_ca='', is_ca=False, signees=None, serial=0, overwrite=False): """Add a set files comprising a certificate to Certipy Used with all the defaults, Certipy will manage creation of file paths to be used to store these files to disk and automatically calls save on all TLSFiles that it creates (and where it makes sense to). """ if common_name in self.store and not overwrite: raise CertExistsError( "Certificate {name} already exists!" " Set overwrite=True to force add." .format(name=common_name)) elif common_name in self.store and overwrite: record = self.get_record(common_name) serial = int(record['serial']) record['serial'] = serial + 1 TLSFileBundle(common_name).from_record(record).save_x509s(x509s) else: file_base_tmpl = "{prefix}/{cn}/{cn}" file_base = file_base_tmpl.format( prefix=self.containing_dir, cn=common_name ) try: ca_record = self.get_record(parent_ca) ca_file = ca_record['files']['cert'] except CertNotFoundError: ca_file = '' files = files or { 'key': file_base + '.key', 'cert': file_base + '.crt', 'ca': ca_file, } bundle = TLSFileBundle( common_name, files=files, x509s=x509s, is_ca=is_ca, serial=serial, parent_ca=parent_ca, signees=signees) self.store[common_name] = bundle.to_record() self.save()
python
def add_files(self, common_name, x509s, files=None, parent_ca='', is_ca=False, signees=None, serial=0, overwrite=False): """Add a set files comprising a certificate to Certipy Used with all the defaults, Certipy will manage creation of file paths to be used to store these files to disk and automatically calls save on all TLSFiles that it creates (and where it makes sense to). """ if common_name in self.store and not overwrite: raise CertExistsError( "Certificate {name} already exists!" " Set overwrite=True to force add." .format(name=common_name)) elif common_name in self.store and overwrite: record = self.get_record(common_name) serial = int(record['serial']) record['serial'] = serial + 1 TLSFileBundle(common_name).from_record(record).save_x509s(x509s) else: file_base_tmpl = "{prefix}/{cn}/{cn}" file_base = file_base_tmpl.format( prefix=self.containing_dir, cn=common_name ) try: ca_record = self.get_record(parent_ca) ca_file = ca_record['files']['cert'] except CertNotFoundError: ca_file = '' files = files or { 'key': file_base + '.key', 'cert': file_base + '.crt', 'ca': ca_file, } bundle = TLSFileBundle( common_name, files=files, x509s=x509s, is_ca=is_ca, serial=serial, parent_ca=parent_ca, signees=signees) self.store[common_name] = bundle.to_record() self.save()
[ "def", "add_files", "(", "self", ",", "common_name", ",", "x509s", ",", "files", "=", "None", ",", "parent_ca", "=", "''", ",", "is_ca", "=", "False", ",", "signees", "=", "None", ",", "serial", "=", "0", ",", "overwrite", "=", "False", ")", ":", "...
Add a set files comprising a certificate to Certipy Used with all the defaults, Certipy will manage creation of file paths to be used to store these files to disk and automatically calls save on all TLSFiles that it creates (and where it makes sense to).
[ "Add", "a", "set", "files", "comprising", "a", "certificate", "to", "Certipy" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L317-L355
train
46,895
LLNL/certipy
certipy/certipy.py
CertStore.remove_sign_link
def remove_sign_link(self, ca_name, signee_name): """Removes signee_name to the signee list for ca_name""" ca_record = self.get_record(ca_name) signee_record = self.get_record(signee_name) signees = ca_record['signees'] or {} signees = Counter(signees) if signee_name in signees: signees[signee_name] = 0 ca_record['signees'] = signees signee_record['parent_ca'] = '' self.save()
python
def remove_sign_link(self, ca_name, signee_name): """Removes signee_name to the signee list for ca_name""" ca_record = self.get_record(ca_name) signee_record = self.get_record(signee_name) signees = ca_record['signees'] or {} signees = Counter(signees) if signee_name in signees: signees[signee_name] = 0 ca_record['signees'] = signees signee_record['parent_ca'] = '' self.save()
[ "def", "remove_sign_link", "(", "self", ",", "ca_name", ",", "signee_name", ")", ":", "ca_record", "=", "self", ".", "get_record", "(", "ca_name", ")", "signee_record", "=", "self", ".", "get_record", "(", "signee_name", ")", "signees", "=", "ca_record", "["...
Removes signee_name to the signee list for ca_name
[ "Removes", "signee_name", "to", "the", "signee", "list", "for", "ca_name" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L370-L381
train
46,896
LLNL/certipy
certipy/certipy.py
CertStore.update_record
def update_record(self, common_name, **fields): """Update fields in an existing record""" record = self.get_record(common_name) if fields is not None: for field, value in fields: record[field] = value self.save() return record
python
def update_record(self, common_name, **fields): """Update fields in an existing record""" record = self.get_record(common_name) if fields is not None: for field, value in fields: record[field] = value self.save() return record
[ "def", "update_record", "(", "self", ",", "common_name", ",", "*", "*", "fields", ")", ":", "record", "=", "self", ".", "get_record", "(", "common_name", ")", "if", "fields", "is", "not", "None", ":", "for", "field", ",", "value", "in", "fields", ":", ...
Update fields in an existing record
[ "Update", "fields", "in", "an", "existing", "record" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L383-L391
train
46,897
LLNL/certipy
certipy/certipy.py
CertStore.remove_record
def remove_record(self, common_name): """Delete the record associated with this common name""" bundle = self.get_files(common_name) num_signees = len(Counter(bundle.record['signees'])) if bundle.is_ca() and num_signees > 0: raise CertificateAuthorityInUseError( "Authority {name} has signed {x} certificates" .format(name=common_name, x=num_signees) ) try: ca_name = bundle.record['parent_ca'] ca_record = self.get_record(ca_name) self.remove_sign_link(ca_name, common_name) except CertNotFoundError: pass record_copy = dict(self.store[common_name]) del self.store[common_name] self.save() return record_copy
python
def remove_record(self, common_name): """Delete the record associated with this common name""" bundle = self.get_files(common_name) num_signees = len(Counter(bundle.record['signees'])) if bundle.is_ca() and num_signees > 0: raise CertificateAuthorityInUseError( "Authority {name} has signed {x} certificates" .format(name=common_name, x=num_signees) ) try: ca_name = bundle.record['parent_ca'] ca_record = self.get_record(ca_name) self.remove_sign_link(ca_name, common_name) except CertNotFoundError: pass record_copy = dict(self.store[common_name]) del self.store[common_name] self.save() return record_copy
[ "def", "remove_record", "(", "self", ",", "common_name", ")", ":", "bundle", "=", "self", ".", "get_files", "(", "common_name", ")", "num_signees", "=", "len", "(", "Counter", "(", "bundle", ".", "record", "[", "'signees'", "]", ")", ")", "if", "bundle",...
Delete the record associated with this common name
[ "Delete", "the", "record", "associated", "with", "this", "common", "name" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L393-L412
train
46,898
LLNL/certipy
certipy/certipy.py
CertStore.remove_files
def remove_files(self, common_name, delete_dir=False): """Delete files and record associated with this common name""" record = self.remove_record(common_name) if delete_dir: delete_dirs = [] if 'files' in record: key_containing_dir = os.path.dirname(record['files']['key']) delete_dirs.append(key_containing_dir) cert_containing_dir = os.path.dirname(record['files']['cert']) if key_containing_dir != cert_containing_dir: delete_dirs.append(cert_containing_dir) for d in delete_dirs: shutil.rmtree(d) return record
python
def remove_files(self, common_name, delete_dir=False): """Delete files and record associated with this common name""" record = self.remove_record(common_name) if delete_dir: delete_dirs = [] if 'files' in record: key_containing_dir = os.path.dirname(record['files']['key']) delete_dirs.append(key_containing_dir) cert_containing_dir = os.path.dirname(record['files']['cert']) if key_containing_dir != cert_containing_dir: delete_dirs.append(cert_containing_dir) for d in delete_dirs: shutil.rmtree(d) return record
[ "def", "remove_files", "(", "self", ",", "common_name", ",", "delete_dir", "=", "False", ")", ":", "record", "=", "self", ".", "remove_record", "(", "common_name", ")", "if", "delete_dir", ":", "delete_dirs", "=", "[", "]", "if", "'files'", "in", "record",...
Delete files and record associated with this common name
[ "Delete", "files", "and", "record", "associated", "with", "this", "common", "name" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L414-L428
train
46,899