function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def m(self): pass | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def isModule(v):
return type(v) == type(sys) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def isNative(v):
return isinstance(v, str) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def _digester(s):
return md5(s if isBytes(s) else s.encode('utf8')).hexdigest() | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def asUnicode(v,enc='utf8'):
return v if isinstance(v,str) else v.decode(enc) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def asNative(v,enc='utf8'):
return asUnicode(v,enc=enc) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def int2Byte(i):
return bytes([i]) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def isBytes(v):
return isinstance(v, bytes) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def isClass(v):
return isinstance(v, type) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def instantiated(v):
return not isinstance(v,type) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def getBytesIO(buf=None):
'''unified StringIO instance interface'''
if buf:
return BytesIO(buf)
return BytesIO() | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def getStringIO(buf=None):
'''unified StringIO instance interface'''
if buf:
return StringIO(buf)
return StringIO() | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def encode_label(args):
return base64_encodestring(pickle_dumps(args)).strip().decode('latin1') | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def rawUnicode(s):
'''converts first 256 unicodes 1-1'''
return s.decode('latin1') if not isinstance(s,str) else s | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def char2int(s):
return s if isinstance(s,int) else ord(s if isinstance(s,str) else s.decode('latin1')) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def rl_add_builtins(**kwd):
import builtins
for k,v in kwd.items():
setattr(builtins,k,v) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def _digester(s):
return md5(s).hexdigest() | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def _digester(s):
return join(["%02x" % ord(x) for x in md5(s).digest()], '') | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def asNative(v,enc='utf8'):
return asBytes(v,enc=enc) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def isStr(v):
return isinstance(v, basestring) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def isUnicode(v):
return isinstance(v, unicode) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def asUnicodeEx(v,enc='utf8'):
return v if isinstance(v,unicode) else v.decode(enc) if isinstance(v,str) else unicode(v) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def isNonPrimitiveInstance(x):
return isinstance(x,types.InstanceType) or not isinstance(x,(float,int,long,type,tuple,list,dict,bool,unicode,str,buffer,complex,slice,types.NoneType,
types.FunctionType,types.LambdaType,types.CodeType,types.GeneratorType,
types.ClassType,types.UnboundMethodType,types.MethodType,types.BuiltinFunctionType,
types.BuiltinMethodType,types.ModuleType,types.FileType,types.XRangeType,
types.TracebackType,types.FrameType,types.EllipsisType,types.DictProxyType,
types.NotImplementedType,types.GetSetDescriptorType,types.MemberDescriptorType
)) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def getBytesIO(buf=None):
'''unified StringIO instance interface'''
if buf:
return StringIO(buf)
return StringIO() | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def bytestr(x,enc='utf8'):
if isinstance(x,unicode):
return x.encode(enc)
elif isinstance(x,str):
return x
else:
return str(x).encode(enc) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def encode_label(args):
return base64_encodestring(pickle_dumps(args)).strip() | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def rawUnicode(s):
'''converts first 256 unicodes 1-1'''
return s.decode('latin1') if not isinstance(s,unicode) else s | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def rl_exec(obj, G=None, L=None):
if G is None:
frame = sys._getframe(1)
G = frame.f_globals
if L is None:
L = frame.f_locals
del frame
elif L is None:
L = G
exec("""exec obj in G, L""") | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def rl_add_builtins(**kwd):
import __builtin__
for k,v in kwd.items():
setattr(__builtin__,k,v) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def _findFiles(dirList,ext='.ttf'):
from os.path import isfile, isdir, join as path_join
from os import listdir
ext = ext.lower()
R = []
A = R.append
for D in dirList:
if not isdir(D): continue
for fn in listdir(D):
fn = path_join(D,fn)
if isfile(fn) and (not ext or fn.lower().endswith(ext)): A(fn)
return R | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def __init__(self,*args,**kwds):
for a in args: self.update(a)
self.update(kwds) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def __setitem__(self,k,v):
try:
k = k.lower()
except:
pass
dict.__setitem__(self,k,v) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def __delitem__(self,k):
try:
k = k.lower()
except:
pass
return dict.__delitem__(self,k) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def __contains__(self,k):
try:
self[k]
return True
except:
return False | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def setdefault(self,k,*a):
try:
k = k.lower()
except:
pass
return dict.setdefault(*((self,k)+a)) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def markfilename(filename,creatorcode=None,filetype=None,ext='PDF'):
try:
if creatorcode is None or filetype is None and ext is not None:
try:
creatorcode, filetype = _KNOWN_MAC_EXT[ext.upper()]
except:
return
macfs.FSSpec(filename).SetCreatorType(creatorcode,filetype)
macostools.touched(filename)
except:
pass | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def markfilename(filename,creatorcode=None,filetype=None):
pass | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def __startswith_rl(fn,
_archivepfx=_archivepfx,
_archivedirpfx=_archivedirpfx,
_archive=_archive,
_archivedir=_archivedir,
os_path_normpath=os.path.normpath,
os_path_normcase=os.path.normcase,
os_getcwd=os.getcwd,
os_sep=os.sep,
os_sep_len = len(os.sep)):
'''if the name starts with a known prefix strip it off'''
fn = os_path_normpath(fn.replace('/',os_sep))
nfn = os_path_normcase(fn)
if nfn in (_archivedir,_archive): return 1,''
if nfn.startswith(_archivepfx): return 1,fn[_archivepfxlen:]
if nfn.startswith(_archivedirpfx): return 1,fn[_archivedirpfxlen:]
cwd = os_path_normcase(os_getcwd())
n = len(cwd)
if nfn.startswith(cwd):
if fn[n:].startswith(os_sep): return 1, fn[n+os_sep_len:]
if n==len(fn): return 1,''
return not os.path.isabs(fn),fn | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def rl_glob(pattern,glob=glob.glob,fnmatch=fnmatch.fnmatch, _RL_DIR=_RL_DIR,pjoin=os.path.join):
c, pfn = __startswith_rl(pattern)
r = glob(pfn)
if c or r==[]:
r += list(map(lambda x,D=_archivepfx,pjoin=pjoin: pjoin(_archivepfx,x),list(filter(lambda x,pfn=pfn,fnmatch=fnmatch: fnmatch(x,pfn),list(__loader__._files.keys())))))
return r | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def _startswith_rl(fn):
return fn | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def isFileSystemDistro():
'''return truth if a file system distribution'''
return _isFSD | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def isSourceDistro():
'''return truth if a source file system distribution'''
return _isFSSD | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def recursiveGetAttr(obj, name):
"Can call down into e.g. object1.object2[4].attr"
return eval(name, obj.__dict__) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def import_zlib():
try:
import zlib
except ImportError:
zlib = None
from reportlab.rl_config import ZLIB_WARNINGS
if ZLIB_WARNINGS: warnOnce('zlib not available')
return zlib | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def __init__(self,value,func):
self.value = value
self.func = func | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def handleValue(v,av,func):
if func:
v = func(av)
else:
if isStr(v):
v = av
elif isinstance(v,float):
v = float(av)
elif isinstance(v,int):
v = int(av)
elif isinstance(v,list):
v = list(eval(av))
elif isinstance(v,tuple):
v = tuple(eval(av))
else:
raise TypeError("Can't convert string %r to %s" % (av,type(v)))
return v | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def getHyphenater(hDict=None):
try:
from reportlab.lib.pyHnj import Hyphen
if hDict is None: hDict=os.path.join(os.path.dirname(__file__),'hyphen.mashed')
return Hyphen(hDict)
except ImportError as errMsg:
if str(errMsg)!='No module named pyHnj': raise
return None | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def open_for_read_by_name(name,mode='b'):
if 'r' not in mode: mode = 'r'+mode
try:
return open(name,mode)
except IOError:
if _isFSD or __loader__ is None: raise
#we have a __loader__, perhaps the filename starts with
#the dirname(reportlab.__file__) or is relative
name = _startswith_rl(name)
s = __loader__.get_data(name)
if 'b' not in mode and os.linesep!='\n': s = s.replace(os.linesep,'\n')
return getBytesIO(s) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def open_for_read(name,mode='b', urlopen=urlopen):
'''attempt to open a file or URL for reading'''
if hasattr(name,'read'): return name
try:
return open_for_read_by_name(name,mode)
except:
try:
return getBytesIO(urlopen(name).read())
except:
raise IOError('Cannot open resource "%s"' % name) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def open_and_read(name,mode='b'):
return open_for_read(name,mode).read() | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def rl_isfile(fn,os_path_isfile=os.path.isfile):
if hasattr(fn,'read'): return True
if os_path_isfile(fn): return True
if _isFSD or __loader__ is None: return False
fn = _startswith_rl(fn)
return fn in list(__loader__._files.keys()) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def rl_listdir(pn,os_path_isdir=os.path.isdir,os_path_normpath=os.path.normpath,os_listdir=os.listdir):
if os_path_isdir(pn) or _isFSD or __loader__ is None: return os_listdir(pn)
pn = _startswith_rl(os_path_normpath(pn))
if not pn.endswith(os.sep): pn += os.sep
return [x[len(pn):] for x in __loader__._files.keys() if x.startswith(pn)] | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def rl_get_module(name,dir):
if name in sys.modules:
om = sys.modules[name]
del sys.modules[name]
else:
om = None
try:
f = None
try:
f, p, desc= imp.find_module(name,[dir])
return imp.load_module(name,f,p,desc)
except:
if isCompactDistro():
#attempt a load from inside the zip archive
import zipimport
dir = _startswith_rl(dir)
dir = (dir=='.' or not dir) and _archive or os.path.join(_archive,dir.replace('/',os.sep))
zi = zipimport.zipimporter(dir)
return zi.load_module(name)
raise ImportError('%s[%s]' % (name,dir))
finally:
if om: sys.modules[name] = om
del om
if f: f.close() | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def __init__(self, fileName,ident=None):
if isinstance(fileName,ImageReader):
self.__dict__ = fileName.__dict__ #borgize
return
self._ident = ident
#start wih lots of null private fields, to be populated by
#the relevant engine.
self.fileName = fileName
self._image = None
self._width = None
self._height = None
self._transparent = None
self._data = None
if _isPILImage(fileName):
self._image = fileName
self.fp = getattr(fileName,'fp',None)
try:
self.fileName = self._image.fileName
except AttributeError:
self.fileName = 'PILIMAGE_%d' % id(self)
else:
try:
from reportlab.rl_config import imageReaderFlags
self.fp = open_for_read(fileName,'b')
if isinstance(self.fp,_bytesIOType): imageReaderFlags=0 #avoid messing with already internal files
if imageReaderFlags>0: #interning
data = self.fp.read()
if imageReaderFlags&2: #autoclose
try:
self.fp.close()
except:
pass
if imageReaderFlags&4: #cache the data
if not self._cache:
from rl_config import register_reset
register_reset(self._cache.clear)
data=self._cache.setdefault(_digester(data),data)
self.fp=getBytesIO(data)
elif imageReaderFlags==-1 and isinstance(fileName,str):
#try Ralf Schmitt's re-opening technique of avoiding too many open files
self.fp.close()
del self.fp #will become a property in the next statement
self.__class__=LazyImageReader
if haveImages:
#detect which library we are using and open the image
if not self._image:
self._image = self._read_image(self.fp)
if getattr(self._image,'format',None)=='JPEG': self.jpeg_fh = self._jpeg_fh
else:
from reportlab.pdfbase.pdfutils import readJPEGInfo
try:
self._width,self._height,c=readJPEGInfo(self.fp)
except:
annotateException('\nImaging Library not available, unable to import bitmaps only jpegs\nfileName=%r identity=%s'%(fileName,self.identity()))
self.jpeg_fh = self._jpeg_fh
self._data = self.fp.read()
self._dataA=None
self.fp.seek(0)
except:
annotateException('\nfileName=%r identity=%s'%(fileName,self.identity())) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def _read_image(self,fp):
if sys.platform[0:4] == 'java':
from javax.imageio import ImageIO
return ImageIO.read(fp)
else:
return Image.open(fp) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def jpeg_fh(self):
return None | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def getRGBData(self):
"Return byte array of RGB data as string"
try:
if self._data is None:
self._dataA = None
if sys.platform[0:4] == 'java':
import jarray
from java.awt.image import PixelGrabber
width, height = self.getSize()
buffer = jarray.zeros(width*height, 'i')
pg = PixelGrabber(self._image, 0,0,width,height,buffer,0,width)
pg.grabPixels()
# there must be a way to do this with a cast not a byte-level loop,
# I just haven't found it yet...
pixels = []
a = pixels.append
for i in range(len(buffer)):
rgb = buffer[i]
a(chr((rgb>>16)&0xff))
a(chr((rgb>>8)&0xff))
a(chr(rgb&0xff))
self._data = ''.join(pixels)
self.mode = 'RGB'
else:
im = self._image
mode = self.mode = im.mode
if mode=='RGBA':
if Image.VERSION.startswith('1.1.7'): im.load()
self._dataA = ImageReader(im.split()[3])
im = im.convert('RGB')
self.mode = 'RGB'
elif mode not in ('L','RGB','CMYK'):
im = im.convert('RGB')
self.mode = 'RGB'
if hasattr(im, 'tobytes'): #make pillow and PIL both happy, for now
self._data = im.tobytes()
else:
self._data = im.tostring()
return self._data
except:
annotateException('\nidentity=%s'%self.identity()) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def getTransparent(self):
if sys.platform[0:4] == 'java':
return None
else:
if "transparency" in self._image.info:
transparency = self._image.info["transparency"] * 3
palette = self._image.palette
try:
palette = palette.palette
except:
try:
palette = palette.data
except:
return None
if isPy3:
return palette[transparency:transparency+3]
else:
return [ord(c) for c in palette[transparency:transparency+3]]
else:
return None | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def fp(self):
return open_for_read(self.fileName, 'b') | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def _image(self):
return self._read_image(self.fp) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def getImageData(imageFileName):
"Get width, height and RGB pixels from image file. Wraps Java/PIL"
try:
return imageFileName.getImageData()
except AttributeError:
return ImageReader(imageFileName).getImageData() | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def __init__(self,fn='rl_dbgmemo.dbg',mode='w',getScript=1,modules=(),capture_traceback=1, stdout=None, **kw):
import time, socket
self.fn = fn
if not stdout:
self.stdout = sys.stdout
else:
if hasattr(stdout,'write'):
self.stdout = stdout
else:
self.stdout = open(stdout,'w')
if mode!='w': return
self.store = store = {}
if capture_traceback and sys.exc_info() != (None,None,None):
import traceback
s = getBytesIO()
traceback.print_exc(None,s)
store['__traceback'] = s.getvalue()
cwd=os.getcwd()
lcwd = os.listdir(cwd)
pcwd = os.path.dirname(cwd)
lpcwd = pcwd and os.listdir(pcwd) or '???'
exed = os.path.abspath(os.path.dirname(sys.argv[0]))
project_version='???'
md=None
try:
import marshal
md=marshal.loads(__loader__.get_data('meta_data.mar'))
project_version=md['project_version']
except:
pass
env = os.environ
K=list(env.keys())
K.sort()
store.update({ 'gmt': time.asctime(time.gmtime(time.time())),
'platform': sys.platform,
'version': sys.version,
'hexversion': hex(sys.hexversion),
'executable': sys.executable,
'exec_prefix': sys.exec_prefix,
'prefix': sys.prefix,
'path': sys.path,
'argv': sys.argv,
'cwd': cwd,
'hostname': socket.gethostname(),
'lcwd': lcwd,
'lpcwd': lpcwd,
'byteorder': sys.byteorder,
'maxint': getattr(sys,'maxunicode','????'),
'api_version': getattr(sys,'api_version','????'),
'version_info': getattr(sys,'version_info','????'),
'winver': getattr(sys,'winver','????'),
'environment': '\n\t\t\t'.join(['']+['%s=%r' % (k,env[k]) for k in K]),
'__loader__': repr(__loader__),
'project_meta_data': md,
'project_version': project_version,
})
for M,A in (
(sys,('getwindowsversion','getfilesystemencoding')),
(os,('uname', 'ctermid', 'getgid', 'getuid', 'getegid',
'geteuid', 'getlogin', 'getgroups', 'getpgrp', 'getpid', 'getppid',
)),
):
for a in A:
if hasattr(M,a):
try:
store[a] = getattr(M,a)()
except:
pass
if exed!=cwd:
try:
store.update({'exed': exed, 'lexed': os.listdir(exed),})
except:
pass
if getScript:
fn = os.path.abspath(sys.argv[0])
if os.path.isfile(fn):
try:
store['__script'] = (fn,open(fn,'r').read())
except:
pass
module_versions = {}
for n,m in sys.modules.items():
if n=='reportlab' or n=='rlextra' or n[:10]=='reportlab.' or n[:8]=='rlextra.':
v = [getattr(m,x,None) for x in ('__version__','__path__','__file__')]
if [_f for _f in v if _f]:
v = [v[0]] + [_f for _f in v[1:] if _f]
module_versions[n] = tuple(v)
store['__module_versions'] = module_versions
self.store['__payload'] = {}
self._add(kw) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def add(self,**kw):
self._add(kw) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def dump(self):
f = open(self.fn,'wb')
try:
self._dump(f)
finally:
f.close() | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def _load(self,f):
self.store = pickle_load(f) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def loads(self,s):
self._load(getBytesIO(s)) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def _banner(self,k,what):
self._writeln('###################%s %s##################' % (what,k[2:])) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def _finish(self,k):
self._banner(k,'Finish ') | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def _show_file(self,k,v):
k = '%s %s' % (k,os.path.basename(v[0]))
self._show_lines(k,v[1]) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def _show_extensions(self):
for mn in ('_rl_accel','_renderPM','sgmlop','pyRXP','pyRXPU','_imaging','Image'):
try:
A = [mn].append
__import__(mn)
m = sys.modules[mn]
A(m.__file__)
for vn in ('__version__','VERSION','_version','version'):
if hasattr(m,vn):
A('%s=%r' % (vn,getattr(m,vn)))
except:
A('not found')
self._writeln(' '+' '.join(A.__self__)) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def show(self):
K = list(self.store.keys())
K.sort()
for k in K:
if k not in list(self.specials.keys()): self._writeln('%-15s = %s' % (k,self.store[k]))
for k in K:
if k in list(self.specials.keys()): self.specials[k](self,k,self.store[k])
self._show_extensions() | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def __setitem__(self,name,value):
self.store['__payload'][name] = value | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def _writeln(self,msg):
self.stdout.write(msg+'\n') | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def flatten(L):
'''recursively flatten the list or tuple L'''
R = []
_flatten(L,R.append)
return R | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def __init__(self,obj,overrideArgs):
self.obj = obj
self._overrideArgs = overrideArgs | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def _fmt(self,fmt,**overrideArgs):
D = _FmtSelfDict(self, overrideArgs)
return fmt % D | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def simpleSplit(text,fontName,fontSize,maxWidth):
from reportlab.pdfbase.pdfmetrics import stringWidth
lines = asUnicode(text).split(u'\n')
SW = lambda text, fN=fontName, fS=fontSize: stringWidth(text, fN, fS)
if maxWidth:
L = []
for l in lines:
L[-1:-1] = _simpleSplit(l,maxWidth,SW)
lines = L
return lines | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def fileName2FSEnc(fn):
if isUnicode(fn):
return fn
else:
for enc in fsEncodings:
try:
return fn.decode(enc)
except:
pass
raise ValueError('cannot convert %r to filesystem encoding' % fn) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def fileName2FSEnc(fn):
'''attempt to convert a filename to utf8'''
from reportlab.rl_config import fsEncodings
if isUnicode(fn):
return asBytes(fn)
else:
for enc in fsEncodings:
try:
return fn.decode(enc).encode('utf8')
except:
pass
raise ValueError('cannot convert %r to utf8 for file path name' % fn) | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def prev_this_next(items):
"""
Loop over a collection with look-ahead and look-back. | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def commasplit(s):
'''
Splits the string s at every unescaped comma and returns the result as a list.
To escape a comma, double it. Individual items are stripped.
To avoid the ambiguity of 3 successive commas to denote a comma at the beginning
or end of an item, add a space between the item seperator and the escaped comma. | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def commajoin(l):
'''
Inverse of commasplit, except that whitespace around items is not conserved.
Adds more whitespace than needed for simplicity and performance. | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def findInPaths(fn,paths,isfile=True,fail=False):
'''search for relative files in likely places'''
exists = isfile and os.path.isfile or os.path.isdir
if exists(fn): return fn
pjoin = os.path.join
if not os.path.isabs(fn):
for p in paths:
pfn = pjoin(p,fn)
if exists(pfn):
return pfn
if fail: raise ValueError('cannot locate %r with paths=%r' % (fn,paths))
return fn | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def escapeOnce(data):
"""Ensure XML output is escaped just once, irrespective of input
>>> escapeOnce('A & B')
'A & B'
>>> escapeOnce('C & D')
'C & D'
>>> escapeOnce('E & F')
'E & F'
"""
data = data.replace("&", "&")
#...but if it was already escaped, make sure it
# is not done twice....this will turn any tags
# back to how they were at the start.
data = data.replace("&", "&")
data = data.replace(">", ">")
data = data.replace("&lt;", "<")
data = data.replace("&#", "&#")
#..and just in case someone had double-escaped it, do it again
data = data.replace("&amp;", "&")
data = data.replace("&gt;", ">")
data = data.replace("&lt;", "<")
return data | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def __new__(cls,value):
if isinstance(value,IdentStr):
inc = value.__inc
value = value[:-(2+len(str(inc)))]
inc += 1
else:
inc = 0
value += '[%d]' % inc
self = str.__new__(cls,value)
self.__inc = inc
return self | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def __new__(cls,v,**kwds):
self = str.__new__(cls,v)
for k,v in kwds.items():
setattr(self,k,v)
return self | ruibarreira/linuxtrail | [
2,
2,
2,
1,
1434186057
] |
def validate_transaction_id(request_mbap, response):
""" Check if Transaction id in request and response is equal. """
assert struct.unpack('>H', request_mbap[:2]) == \
struct.unpack('>H', response[:2]) | AdvancedClimateSystems/python-modbus | [
189,
68,
189,
36,
1444769179
] |
def validate_length(response):
""" Check if Length field contains actual length of response. """
assert struct.unpack('>H', response[4:6])[0] == len(response[6:]) | AdvancedClimateSystems/python-modbus | [
189,
68,
189,
36,
1444769179
] |
def validate_response_mbap(request_mbap, response):
""" Validate if fields in response MBAP contain correct values. """
validate_transaction_id(request_mbap, response)
validate_protocol_id(request_mbap, response)
validate_length(response)
validate_unit_id(request_mbap, response) | AdvancedClimateSystems/python-modbus | [
189,
68,
189,
36,
1444769179
] |
def validate_single_bit_value_byte_count(request, response):
""" Check of byte count field contains actual byte count and if byte count
matches with the amount of requests quantity.
"""
byte_count = struct.unpack('>B', response[8:9])[0]
quantity = struct.unpack('>H', request[-2:])[0]
expected_byte_count = quantity // 8
if quantity % 8 != 0:
expected_byte_count = (quantity // 8) + 1
assert byte_count == len(response[9:])
assert byte_count == expected_byte_count | AdvancedClimateSystems/python-modbus | [
189,
68,
189,
36,
1444769179
] |
def __init__(self, n_class=1000, threshold=0.5, pt_func=None):
self.threshold = threshold
self.pt_func = pt_func
self.n_class = n_class
super(Alex, self).__init__()
with self.init_scope():
self.conv1 = L.Convolution2D(3, 96, 11, stride=4, pad=4)
self.bn1 = L.BatchNormalization(96)
self.conv2 = L.Convolution2D(96, 256, 5, stride=1, pad=1)
self.bn2 = L.BatchNormalization(256)
self.conv3 = L.Convolution2D(256, 384, 3, stride=1, pad=1)
self.conv4 = L.Convolution2D(384, 384, 3, stride=1, pad=1)
self.conv5 = L.Convolution2D(384, 256, 3, stride=1, pad=1)
self.bn5 = L.BatchNormalization(256)
self.fc6 = L.Linear(33280, 4096)
self.fc7 = L.Linear(4096, 4096)
self.fc8 = L.Linear(4096, 2*n_class) | start-jsk/jsk_apc | [
35,
37,
35,
24,
1414042111
] |
def infoDialog(message, heading=addonInfo('name'), icon='', time=3000):
if icon == '':
icon = addonInfo('icon')
try:
dialog.notification(heading, message, icon, time, sound=False)
except:
execute("Notification(%s, %s, %s, %s)" % (heading, message, time, icon)) | felipenaselva/felipe.repository | [
2,
6,
2,
1,
1474110890
] |
def inputDialog(heading, _type_=''):
return dialog.input(heading, _type_) | felipenaselva/felipe.repository | [
2,
6,
2,
1,
1474110890
] |
def selectDialog(list, heading=addonInfo('name')):
return dialog.select(heading, list) | felipenaselva/felipe.repository | [
2,
6,
2,
1,
1474110890
] |
def openSettings_alt():
try:
idle()
xbmcaddon.Addon().openSettings()
except:
return | felipenaselva/felipe.repository | [
2,
6,
2,
1,
1474110890
] |
def refresh():
return execute('Container.Refresh') | felipenaselva/felipe.repository | [
2,
6,
2,
1,
1474110890
] |
def __init__(self, args, params):
super().__init__(args, params)
if self.args.distributed_weight_update == 2:
dwu_args = self.distributed_weight_update_config
print("DistributedFusedAdam",dwu_args)
self._optimizer = DistributedFusedAdam(params, **dwu_args, **self.optimizer_config)
elif self.args.distributed_weight_update == 3:
dwu_args = self.distributed_weight_update_config
print("DistributedFusedAdamV2",dwu_args)
self._optimizer = DistributedFusedAdamV2(params, **dwu_args, **self.optimizer_config)
elif self.args.distributed_weight_update == 4:
dwu_args = self.distributed_weight_update_config
print("DistributedFusedAdamV3",dwu_args)
self._optimizer = DistributedFusedAdamV3(params, **dwu_args, **self.optimizer_config)
else:
assert (self.args.distributed_weight_update == 0), "Vanilla optimizer not supported anymore"
self._optimizer = FusedAdam(params, **self.optimizer_config) | mlperf/training_results_v0.7 | [
11,
25,
11,
1,
1606268455
] |
def add_args(parser):
"""Add optimizer-specific arguments to the parser."""
parser.add_argument('--adam-betas', default='(0.9, 0.999)', metavar='B',
help='betas for Adam optimizer')
parser.add_argument('--adam-eps', type=float, default=1e-8, metavar='D',
help='epsilon for Adam optimizer') | mlperf/training_results_v0.7 | [
11,
25,
11,
1,
1606268455
] |
def optimizer_config(self):
"""
Return a kwarg dictionary that will be used to override optimizer
args stored in checkpoints. This allows us to load a checkpoint and
resume training using a different set of optimizer args, e.g., with a
different learning rate.
"""
return {
'lr': self.args.lr[0],
'betas': eval(self.args.adam_betas),
'eps': self.args.adam_eps,
'weight_decay': self.args.weight_decay,
} | mlperf/training_results_v0.7 | [
11,
25,
11,
1,
1606268455
] |
def distributed_weight_update_config(self):
"""
Return a kwarg dictionary that provides arguments for the distributed
weight update feature.
"""
return {
'distributed_weight_update': self.args.distributed_weight_update,
'dwu_group_size': self.args.dwu_group_size,
'dwu_num_blocks': self.args.dwu_num_blocks,
'dwu_num_chunks': self.args.dwu_num_chunks,
'dwu_num_rs_pg': self.args.dwu_num_rs_pg,
'dwu_num_ar_pg': self.args.dwu_num_ar_pg,
'dwu_num_ag_pg': self.args.dwu_num_ag_pg,
'overlap_reductions': self.args.dwu_overlap_reductions,
'full_pipeline': self.args.dwu_full_pipeline,
'compute_L2_grad_norm': self.args.dwu_compute_L2_grad_norm,
'flat_mt': self.args.dwu_flat_mt,
'e5m2_allgather': self.args.dwu_e5m2_allgather,
'do_not_flatten_model': self.args.dwu_do_not_flatten_model,
} | mlperf/training_results_v0.7 | [
11,
25,
11,
1,
1606268455
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.