id
int32
0
252k
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
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
232,000
projecthamster/hamster
src/hamster/idle.py
DbusIdleListener.bus_inspector
def bus_inspector(self, bus, message): """ Inspect the bus for screensaver messages of interest """ # We only care about stuff on this interface. We did filter # for it above, but even so we still hear from ourselves # (hamster messages). if message.get_interface() != self.screensaver_uri: return True member = message.get_member() if member in ("SessionIdleChanged", "ActiveChanged"): logger.debug("%s -> %s" % (member, message.get_args_list())) idle_state = message.get_args_list()[0] if idle_state: self.idle_from = dt.datetime.now() # from gnome screensaver 2.24 to 2.28 they have switched # configuration keys and signal types. # luckily we can determine key by signal type if member == "SessionIdleChanged": delay_key = "/apps/gnome-screensaver/idle_delay" else: delay_key = "/desktop/gnome/session/idle_delay" client = gconf.Client.get_default() self.timeout_minutes = client.get_int(delay_key) else: self.screen_locked = False self.idle_from = None if member == "ActiveChanged": # ActiveChanged comes before SessionIdleChanged signal # as a workaround for pre 2.26, we will wait a second - maybe # SessionIdleChanged signal kicks in def dispatch_active_changed(idle_state): if not self.idle_was_there: self.emit('idle-changed', idle_state) self.idle_was_there = False gobject.timeout_add_seconds(1, dispatch_active_changed, idle_state) else: # dispatch idle status change to interested parties self.idle_was_there = True self.emit('idle-changed', idle_state) elif member == "Lock": # in case of lock, lock signal will be sent first, followed by # ActiveChanged and SessionIdle signals logger.debug("Screen Lock Requested") self.screen_locked = True return
python
def bus_inspector(self, bus, message): """ Inspect the bus for screensaver messages of interest """ # We only care about stuff on this interface. We did filter # for it above, but even so we still hear from ourselves # (hamster messages). if message.get_interface() != self.screensaver_uri: return True member = message.get_member() if member in ("SessionIdleChanged", "ActiveChanged"): logger.debug("%s -> %s" % (member, message.get_args_list())) idle_state = message.get_args_list()[0] if idle_state: self.idle_from = dt.datetime.now() # from gnome screensaver 2.24 to 2.28 they have switched # configuration keys and signal types. # luckily we can determine key by signal type if member == "SessionIdleChanged": delay_key = "/apps/gnome-screensaver/idle_delay" else: delay_key = "/desktop/gnome/session/idle_delay" client = gconf.Client.get_default() self.timeout_minutes = client.get_int(delay_key) else: self.screen_locked = False self.idle_from = None if member == "ActiveChanged": # ActiveChanged comes before SessionIdleChanged signal # as a workaround for pre 2.26, we will wait a second - maybe # SessionIdleChanged signal kicks in def dispatch_active_changed(idle_state): if not self.idle_was_there: self.emit('idle-changed', idle_state) self.idle_was_there = False gobject.timeout_add_seconds(1, dispatch_active_changed, idle_state) else: # dispatch idle status change to interested parties self.idle_was_there = True self.emit('idle-changed', idle_state) elif member == "Lock": # in case of lock, lock signal will be sent first, followed by # ActiveChanged and SessionIdle signals logger.debug("Screen Lock Requested") self.screen_locked = True return
[ "def", "bus_inspector", "(", "self", ",", "bus", ",", "message", ")", ":", "# We only care about stuff on this interface. We did filter", "# for it above, but even so we still hear from ourselves", "# (hamster messages).", "if", "message", ".", "get_interface", "(", ")", "!=", "self", ".", "screensaver_uri", ":", "return", "True", "member", "=", "message", ".", "get_member", "(", ")", "if", "member", "in", "(", "\"SessionIdleChanged\"", ",", "\"ActiveChanged\"", ")", ":", "logger", ".", "debug", "(", "\"%s -> %s\"", "%", "(", "member", ",", "message", ".", "get_args_list", "(", ")", ")", ")", "idle_state", "=", "message", ".", "get_args_list", "(", ")", "[", "0", "]", "if", "idle_state", ":", "self", ".", "idle_from", "=", "dt", ".", "datetime", ".", "now", "(", ")", "# from gnome screensaver 2.24 to 2.28 they have switched", "# configuration keys and signal types.", "# luckily we can determine key by signal type", "if", "member", "==", "\"SessionIdleChanged\"", ":", "delay_key", "=", "\"/apps/gnome-screensaver/idle_delay\"", "else", ":", "delay_key", "=", "\"/desktop/gnome/session/idle_delay\"", "client", "=", "gconf", ".", "Client", ".", "get_default", "(", ")", "self", ".", "timeout_minutes", "=", "client", ".", "get_int", "(", "delay_key", ")", "else", ":", "self", ".", "screen_locked", "=", "False", "self", ".", "idle_from", "=", "None", "if", "member", "==", "\"ActiveChanged\"", ":", "# ActiveChanged comes before SessionIdleChanged signal", "# as a workaround for pre 2.26, we will wait a second - maybe", "# SessionIdleChanged signal kicks in", "def", "dispatch_active_changed", "(", "idle_state", ")", ":", "if", "not", "self", ".", "idle_was_there", ":", "self", ".", "emit", "(", "'idle-changed'", ",", "idle_state", ")", "self", ".", "idle_was_there", "=", "False", "gobject", ".", "timeout_add_seconds", "(", "1", ",", "dispatch_active_changed", ",", "idle_state", ")", "else", ":", "# dispatch idle status change to interested parties", "self", ".", "idle_was_there", "=", "True", "self", ".", "emit", "(", "'idle-changed'", ",", "idle_state", ")", "elif", "member", "==", "\"Lock\"", ":", "# in case of lock, lock signal will be sent first, followed by", "# ActiveChanged and SessionIdle signals", "logger", ".", "debug", "(", "\"Screen Lock Requested\"", ")", "self", ".", "screen_locked", "=", "True", "return" ]
Inspect the bus for screensaver messages of interest
[ "Inspect", "the", "bus", "for", "screensaver", "messages", "of", "interest" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/idle.py#L77-L134
232,001
projecthamster/hamster
src/hamster/lib/i18n.py
C_
def C_(ctx, s): """Provide qualified translatable strings via context. Taken from gnome-games. """ translated = gettext.gettext('%s\x04%s' % (ctx, s)) if '\x04' in translated: # no translation found, return input string return s return translated
python
def C_(ctx, s): """Provide qualified translatable strings via context. Taken from gnome-games. """ translated = gettext.gettext('%s\x04%s' % (ctx, s)) if '\x04' in translated: # no translation found, return input string return s return translated
[ "def", "C_", "(", "ctx", ",", "s", ")", ":", "translated", "=", "gettext", ".", "gettext", "(", "'%s\\x04%s'", "%", "(", "ctx", ",", "s", ")", ")", "if", "'\\x04'", "in", "translated", ":", "# no translation found, return input string", "return", "s", "return", "translated" ]
Provide qualified translatable strings via context. Taken from gnome-games.
[ "Provide", "qualified", "translatable", "strings", "via", "context", ".", "Taken", "from", "gnome", "-", "games", "." ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/i18n.py#L34-L42
232,002
projecthamster/hamster
wafadmin/Scripting.py
clean
def clean(bld): '''removes the build files''' try: proj=Environment.Environment(Options.lockfile) except IOError: raise Utils.WafError('Nothing to clean (project not configured)') bld.load_dirs(proj[SRCDIR],proj[BLDDIR]) bld.load_envs() bld.is_install=0 bld.add_subdirs([os.path.split(Utils.g_module.root_path)[0]]) try: bld.clean() finally: bld.save()
python
def clean(bld): '''removes the build files''' try: proj=Environment.Environment(Options.lockfile) except IOError: raise Utils.WafError('Nothing to clean (project not configured)') bld.load_dirs(proj[SRCDIR],proj[BLDDIR]) bld.load_envs() bld.is_install=0 bld.add_subdirs([os.path.split(Utils.g_module.root_path)[0]]) try: bld.clean() finally: bld.save()
[ "def", "clean", "(", "bld", ")", ":", "try", ":", "proj", "=", "Environment", ".", "Environment", "(", "Options", ".", "lockfile", ")", "except", "IOError", ":", "raise", "Utils", ".", "WafError", "(", "'Nothing to clean (project not configured)'", ")", "bld", ".", "load_dirs", "(", "proj", "[", "SRCDIR", "]", ",", "proj", "[", "BLDDIR", "]", ")", "bld", ".", "load_envs", "(", ")", "bld", ".", "is_install", "=", "0", "bld", ".", "add_subdirs", "(", "[", "os", ".", "path", ".", "split", "(", "Utils", ".", "g_module", ".", "root_path", ")", "[", "0", "]", "]", ")", "try", ":", "bld", ".", "clean", "(", ")", "finally", ":", "bld", ".", "save", "(", ")" ]
removes the build files
[ "removes", "the", "build", "files" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/wafadmin/Scripting.py#L188-L201
232,003
projecthamster/hamster
wafadmin/Scripting.py
install
def install(bld): '''installs the build files''' bld=check_configured(bld) Options.commands['install']=True Options.commands['uninstall']=False Options.is_install=True bld.is_install=INSTALL build_impl(bld) bld.install()
python
def install(bld): '''installs the build files''' bld=check_configured(bld) Options.commands['install']=True Options.commands['uninstall']=False Options.is_install=True bld.is_install=INSTALL build_impl(bld) bld.install()
[ "def", "install", "(", "bld", ")", ":", "bld", "=", "check_configured", "(", "bld", ")", "Options", ".", "commands", "[", "'install'", "]", "=", "True", "Options", ".", "commands", "[", "'uninstall'", "]", "=", "False", "Options", ".", "is_install", "=", "True", "bld", ".", "is_install", "=", "INSTALL", "build_impl", "(", "bld", ")", "bld", ".", "install", "(", ")" ]
installs the build files
[ "installs", "the", "build", "files" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/wafadmin/Scripting.py#L248-L256
232,004
projecthamster/hamster
wafadmin/Scripting.py
uninstall
def uninstall(bld): '''removes the installed files''' Options.commands['install']=False Options.commands['uninstall']=True Options.is_install=True bld.is_install=UNINSTALL try: def runnable_status(self): return SKIP_ME setattr(Task.Task,'runnable_status_back',Task.Task.runnable_status) setattr(Task.Task,'runnable_status',runnable_status) build_impl(bld) bld.install() finally: setattr(Task.Task,'runnable_status',Task.Task.runnable_status_back)
python
def uninstall(bld): '''removes the installed files''' Options.commands['install']=False Options.commands['uninstall']=True Options.is_install=True bld.is_install=UNINSTALL try: def runnable_status(self): return SKIP_ME setattr(Task.Task,'runnable_status_back',Task.Task.runnable_status) setattr(Task.Task,'runnable_status',runnable_status) build_impl(bld) bld.install() finally: setattr(Task.Task,'runnable_status',Task.Task.runnable_status_back)
[ "def", "uninstall", "(", "bld", ")", ":", "Options", ".", "commands", "[", "'install'", "]", "=", "False", "Options", ".", "commands", "[", "'uninstall'", "]", "=", "True", "Options", ".", "is_install", "=", "True", "bld", ".", "is_install", "=", "UNINSTALL", "try", ":", "def", "runnable_status", "(", "self", ")", ":", "return", "SKIP_ME", "setattr", "(", "Task", ".", "Task", ",", "'runnable_status_back'", ",", "Task", ".", "Task", ".", "runnable_status", ")", "setattr", "(", "Task", ".", "Task", ",", "'runnable_status'", ",", "runnable_status", ")", "build_impl", "(", "bld", ")", "bld", ".", "install", "(", ")", "finally", ":", "setattr", "(", "Task", ".", "Task", ",", "'runnable_status'", ",", "Task", ".", "Task", ".", "runnable_status_back", ")" ]
removes the installed files
[ "removes", "the", "installed", "files" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/wafadmin/Scripting.py#L257-L271
232,005
projecthamster/hamster
wafadmin/Scripting.py
distclean
def distclean(ctx=None): '''removes the build directory''' global commands lst=os.listdir('.') for f in lst: if f==Options.lockfile: try: proj=Environment.Environment(f) except: Logs.warn('could not read %r'%f) continue try: shutil.rmtree(proj[BLDDIR]) except IOError: pass except OSError,e: if e.errno!=errno.ENOENT: Logs.warn('project %r cannot be removed'%proj[BLDDIR]) try: os.remove(f) except OSError,e: if e.errno!=errno.ENOENT: Logs.warn('file %r cannot be removed'%f) if not commands and f.startswith('.waf'): shutil.rmtree(f,ignore_errors=True)
python
def distclean(ctx=None): '''removes the build directory''' global commands lst=os.listdir('.') for f in lst: if f==Options.lockfile: try: proj=Environment.Environment(f) except: Logs.warn('could not read %r'%f) continue try: shutil.rmtree(proj[BLDDIR]) except IOError: pass except OSError,e: if e.errno!=errno.ENOENT: Logs.warn('project %r cannot be removed'%proj[BLDDIR]) try: os.remove(f) except OSError,e: if e.errno!=errno.ENOENT: Logs.warn('file %r cannot be removed'%f) if not commands and f.startswith('.waf'): shutil.rmtree(f,ignore_errors=True)
[ "def", "distclean", "(", "ctx", "=", "None", ")", ":", "global", "commands", "lst", "=", "os", ".", "listdir", "(", "'.'", ")", "for", "f", "in", "lst", ":", "if", "f", "==", "Options", ".", "lockfile", ":", "try", ":", "proj", "=", "Environment", ".", "Environment", "(", "f", ")", "except", ":", "Logs", ".", "warn", "(", "'could not read %r'", "%", "f", ")", "continue", "try", ":", "shutil", ".", "rmtree", "(", "proj", "[", "BLDDIR", "]", ")", "except", "IOError", ":", "pass", "except", "OSError", ",", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "ENOENT", ":", "Logs", ".", "warn", "(", "'project %r cannot be removed'", "%", "proj", "[", "BLDDIR", "]", ")", "try", ":", "os", ".", "remove", "(", "f", ")", "except", "OSError", ",", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "ENOENT", ":", "Logs", ".", "warn", "(", "'file %r cannot be removed'", "%", "f", ")", "if", "not", "commands", "and", "f", ".", "startswith", "(", "'.waf'", ")", ":", "shutil", ".", "rmtree", "(", "f", ",", "ignore_errors", "=", "True", ")" ]
removes the build directory
[ "removes", "the", "build", "directory" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/wafadmin/Scripting.py#L318-L342
232,006
projecthamster/hamster
wafadmin/Scripting.py
dist
def dist(appname='',version=''): '''makes a tarball for redistributing the sources''' import tarfile if not appname:appname=Utils.g_module.APPNAME if not version:version=Utils.g_module.VERSION tmp_folder=appname+'-'+version if g_gz in['gz','bz2']: arch_name=tmp_folder+'.tar.'+g_gz else: arch_name=tmp_folder+'.'+'zip' try: shutil.rmtree(tmp_folder) except(OSError,IOError): pass try: os.remove(arch_name) except(OSError,IOError): pass blddir=getattr(Utils.g_module,BLDDIR,None) if not blddir: blddir=getattr(Utils.g_module,'out',None) copytree('.',tmp_folder,blddir) dist_hook=getattr(Utils.g_module,'dist_hook',None) if dist_hook: back=os.getcwd() os.chdir(tmp_folder) try: dist_hook() finally: os.chdir(back) if g_gz in['gz','bz2']: tar=tarfile.open(arch_name,'w:'+g_gz) tar.add(tmp_folder) tar.close() else: Utils.zip_folder(tmp_folder,arch_name,tmp_folder) try:from hashlib import sha1 as sha except ImportError:from sha import sha try: digest=" (sha=%r)"%sha(Utils.readf(arch_name)).hexdigest() except: digest='' info('New archive created: %s%s'%(arch_name,digest)) if os.path.exists(tmp_folder):shutil.rmtree(tmp_folder) return arch_name
python
def dist(appname='',version=''): '''makes a tarball for redistributing the sources''' import tarfile if not appname:appname=Utils.g_module.APPNAME if not version:version=Utils.g_module.VERSION tmp_folder=appname+'-'+version if g_gz in['gz','bz2']: arch_name=tmp_folder+'.tar.'+g_gz else: arch_name=tmp_folder+'.'+'zip' try: shutil.rmtree(tmp_folder) except(OSError,IOError): pass try: os.remove(arch_name) except(OSError,IOError): pass blddir=getattr(Utils.g_module,BLDDIR,None) if not blddir: blddir=getattr(Utils.g_module,'out',None) copytree('.',tmp_folder,blddir) dist_hook=getattr(Utils.g_module,'dist_hook',None) if dist_hook: back=os.getcwd() os.chdir(tmp_folder) try: dist_hook() finally: os.chdir(back) if g_gz in['gz','bz2']: tar=tarfile.open(arch_name,'w:'+g_gz) tar.add(tmp_folder) tar.close() else: Utils.zip_folder(tmp_folder,arch_name,tmp_folder) try:from hashlib import sha1 as sha except ImportError:from sha import sha try: digest=" (sha=%r)"%sha(Utils.readf(arch_name)).hexdigest() except: digest='' info('New archive created: %s%s'%(arch_name,digest)) if os.path.exists(tmp_folder):shutil.rmtree(tmp_folder) return arch_name
[ "def", "dist", "(", "appname", "=", "''", ",", "version", "=", "''", ")", ":", "import", "tarfile", "if", "not", "appname", ":", "appname", "=", "Utils", ".", "g_module", ".", "APPNAME", "if", "not", "version", ":", "version", "=", "Utils", ".", "g_module", ".", "VERSION", "tmp_folder", "=", "appname", "+", "'-'", "+", "version", "if", "g_gz", "in", "[", "'gz'", ",", "'bz2'", "]", ":", "arch_name", "=", "tmp_folder", "+", "'.tar.'", "+", "g_gz", "else", ":", "arch_name", "=", "tmp_folder", "+", "'.'", "+", "'zip'", "try", ":", "shutil", ".", "rmtree", "(", "tmp_folder", ")", "except", "(", "OSError", ",", "IOError", ")", ":", "pass", "try", ":", "os", ".", "remove", "(", "arch_name", ")", "except", "(", "OSError", ",", "IOError", ")", ":", "pass", "blddir", "=", "getattr", "(", "Utils", ".", "g_module", ",", "BLDDIR", ",", "None", ")", "if", "not", "blddir", ":", "blddir", "=", "getattr", "(", "Utils", ".", "g_module", ",", "'out'", ",", "None", ")", "copytree", "(", "'.'", ",", "tmp_folder", ",", "blddir", ")", "dist_hook", "=", "getattr", "(", "Utils", ".", "g_module", ",", "'dist_hook'", ",", "None", ")", "if", "dist_hook", ":", "back", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "tmp_folder", ")", "try", ":", "dist_hook", "(", ")", "finally", ":", "os", ".", "chdir", "(", "back", ")", "if", "g_gz", "in", "[", "'gz'", ",", "'bz2'", "]", ":", "tar", "=", "tarfile", ".", "open", "(", "arch_name", ",", "'w:'", "+", "g_gz", ")", "tar", ".", "add", "(", "tmp_folder", ")", "tar", ".", "close", "(", ")", "else", ":", "Utils", ".", "zip_folder", "(", "tmp_folder", ",", "arch_name", ",", "tmp_folder", ")", "try", ":", "from", "hashlib", "import", "sha1", "as", "sha", "except", "ImportError", ":", "from", "sha", "import", "sha", "try", ":", "digest", "=", "\" (sha=%r)\"", "%", "sha", "(", "Utils", ".", "readf", "(", "arch_name", ")", ")", ".", "hexdigest", "(", ")", "except", ":", "digest", "=", "''", "info", "(", "'New archive created: %s%s'", "%", "(", "arch_name", ",", "digest", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "tmp_folder", ")", ":", "shutil", ".", "rmtree", "(", "tmp_folder", ")", "return", "arch_name" ]
makes a tarball for redistributing the sources
[ "makes", "a", "tarball", "for", "redistributing", "the", "sources" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/wafadmin/Scripting.py#L343-L387
232,007
projecthamster/hamster
src/hamster/widgets/reportchooserdialog.py
ReportChooserDialog.show
def show(self, start_date, end_date): """setting suggested name to something readable, replace backslashes with dots so the name is valid in linux""" # title in the report file name vars = {"title": _("Time track"), "start": start_date.strftime("%x").replace("/", "."), "end": end_date.strftime("%x").replace("/", ".")} if start_date != end_date: filename = "%(title)s, %(start)s - %(end)s.html" % vars else: filename = "%(title)s, %(start)s.html" % vars self.dialog.set_current_name(filename) response = self.dialog.run() if response != gtk.ResponseType.OK: self.emit("report-chooser-closed") self.dialog.destroy() self.dialog = None else: self.on_save_button_clicked()
python
def show(self, start_date, end_date): """setting suggested name to something readable, replace backslashes with dots so the name is valid in linux""" # title in the report file name vars = {"title": _("Time track"), "start": start_date.strftime("%x").replace("/", "."), "end": end_date.strftime("%x").replace("/", ".")} if start_date != end_date: filename = "%(title)s, %(start)s - %(end)s.html" % vars else: filename = "%(title)s, %(start)s.html" % vars self.dialog.set_current_name(filename) response = self.dialog.run() if response != gtk.ResponseType.OK: self.emit("report-chooser-closed") self.dialog.destroy() self.dialog = None else: self.on_save_button_clicked()
[ "def", "show", "(", "self", ",", "start_date", ",", "end_date", ")", ":", "# title in the report file name", "vars", "=", "{", "\"title\"", ":", "_", "(", "\"Time track\"", ")", ",", "\"start\"", ":", "start_date", ".", "strftime", "(", "\"%x\"", ")", ".", "replace", "(", "\"/\"", ",", "\".\"", ")", ",", "\"end\"", ":", "end_date", ".", "strftime", "(", "\"%x\"", ")", ".", "replace", "(", "\"/\"", ",", "\".\"", ")", "}", "if", "start_date", "!=", "end_date", ":", "filename", "=", "\"%(title)s, %(start)s - %(end)s.html\"", "%", "vars", "else", ":", "filename", "=", "\"%(title)s, %(start)s.html\"", "%", "vars", "self", ".", "dialog", ".", "set_current_name", "(", "filename", ")", "response", "=", "self", ".", "dialog", ".", "run", "(", ")", "if", "response", "!=", "gtk", ".", "ResponseType", ".", "OK", ":", "self", ".", "emit", "(", "\"report-chooser-closed\"", ")", "self", ".", "dialog", ".", "destroy", "(", ")", "self", ".", "dialog", "=", "None", "else", ":", "self", ".", "on_save_button_clicked", "(", ")" ]
setting suggested name to something readable, replace backslashes with dots so the name is valid in linux
[ "setting", "suggested", "name", "to", "something", "readable", "replace", "backslashes", "with", "dots", "so", "the", "name", "is", "valid", "in", "linux" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/widgets/reportchooserdialog.py#L90-L112
232,008
projecthamster/hamster
src/hamster/lib/pytweener.py
Tweener.kill_tweens
def kill_tweens(self, obj = None): """Stop tweening an object, without completing the motion or firing the on_complete""" if obj is not None: try: del self.current_tweens[obj] except: pass else: self.current_tweens = collections.defaultdict(set)
python
def kill_tweens(self, obj = None): """Stop tweening an object, without completing the motion or firing the on_complete""" if obj is not None: try: del self.current_tweens[obj] except: pass else: self.current_tweens = collections.defaultdict(set)
[ "def", "kill_tweens", "(", "self", ",", "obj", "=", "None", ")", ":", "if", "obj", "is", "not", "None", ":", "try", ":", "del", "self", ".", "current_tweens", "[", "obj", "]", "except", ":", "pass", "else", ":", "self", ".", "current_tweens", "=", "collections", ".", "defaultdict", "(", "set", ")" ]
Stop tweening an object, without completing the motion or firing the on_complete
[ "Stop", "tweening", "an", "object", "without", "completing", "the", "motion", "or", "firing", "the", "on_complete" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/pytweener.py#L72-L81
232,009
projecthamster/hamster
src/hamster/lib/pytweener.py
Tweener.remove_tween
def remove_tween(self, tween): """"remove given tween without completing the motion or firing the on_complete""" if tween.target in self.current_tweens and tween in self.current_tweens[tween.target]: self.current_tweens[tween.target].remove(tween) if not self.current_tweens[tween.target]: del self.current_tweens[tween.target]
python
def remove_tween(self, tween): """"remove given tween without completing the motion or firing the on_complete""" if tween.target in self.current_tweens and tween in self.current_tweens[tween.target]: self.current_tweens[tween.target].remove(tween) if not self.current_tweens[tween.target]: del self.current_tweens[tween.target]
[ "def", "remove_tween", "(", "self", ",", "tween", ")", ":", "if", "tween", ".", "target", "in", "self", ".", "current_tweens", "and", "tween", "in", "self", ".", "current_tweens", "[", "tween", ".", "target", "]", ":", "self", ".", "current_tweens", "[", "tween", ".", "target", "]", ".", "remove", "(", "tween", ")", "if", "not", "self", ".", "current_tweens", "[", "tween", ".", "target", "]", ":", "del", "self", ".", "current_tweens", "[", "tween", ".", "target", "]" ]
remove given tween without completing the motion or firing the on_complete
[ "remove", "given", "tween", "without", "completing", "the", "motion", "or", "firing", "the", "on_complete" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/pytweener.py#L83-L88
232,010
projecthamster/hamster
src/hamster/lib/pytweener.py
Tweener.finish
def finish(self): """jump the the last frame of all tweens""" for obj in self.current_tweens: for tween in self.current_tweens[obj]: tween.finish() self.current_tweens = {}
python
def finish(self): """jump the the last frame of all tweens""" for obj in self.current_tweens: for tween in self.current_tweens[obj]: tween.finish() self.current_tweens = {}
[ "def", "finish", "(", "self", ")", ":", "for", "obj", "in", "self", ".", "current_tweens", ":", "for", "tween", "in", "self", ".", "current_tweens", "[", "obj", "]", ":", "tween", ".", "finish", "(", ")", "self", ".", "current_tweens", "=", "{", "}" ]
jump the the last frame of all tweens
[ "jump", "the", "the", "last", "frame", "of", "all", "tweens" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/pytweener.py#L90-L95
232,011
projecthamster/hamster
src/hamster/lib/pytweener.py
Tweener.update
def update(self, delta_seconds): """update tweeners. delta_seconds is time in seconds since last frame""" for obj in tuple(self.current_tweens): for tween in tuple(self.current_tweens[obj]): done = tween.update(delta_seconds) if done: self.current_tweens[obj].remove(tween) if tween.on_complete: tween.on_complete(tween.target) if not self.current_tweens[obj]: del self.current_tweens[obj] return self.current_tweens
python
def update(self, delta_seconds): """update tweeners. delta_seconds is time in seconds since last frame""" for obj in tuple(self.current_tweens): for tween in tuple(self.current_tweens[obj]): done = tween.update(delta_seconds) if done: self.current_tweens[obj].remove(tween) if tween.on_complete: tween.on_complete(tween.target) if not self.current_tweens[obj]: del self.current_tweens[obj] return self.current_tweens
[ "def", "update", "(", "self", ",", "delta_seconds", ")", ":", "for", "obj", "in", "tuple", "(", "self", ".", "current_tweens", ")", ":", "for", "tween", "in", "tuple", "(", "self", ".", "current_tweens", "[", "obj", "]", ")", ":", "done", "=", "tween", ".", "update", "(", "delta_seconds", ")", "if", "done", ":", "self", ".", "current_tweens", "[", "obj", "]", ".", "remove", "(", "tween", ")", "if", "tween", ".", "on_complete", ":", "tween", ".", "on_complete", "(", "tween", ".", "target", ")", "if", "not", "self", ".", "current_tweens", "[", "obj", "]", ":", "del", "self", ".", "current_tweens", "[", "obj", "]", "return", "self", ".", "current_tweens" ]
update tweeners. delta_seconds is time in seconds since last frame
[ "update", "tweeners", ".", "delta_seconds", "is", "time", "in", "seconds", "since", "last", "frame" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/pytweener.py#L97-L110
232,012
projecthamster/hamster
src/hamster/lib/pytweener.py
Tween.update
def update(self, ptime): """Update tween with the time since the last frame""" delta = self.delta + ptime total_duration = self.delay + self.duration if delta > total_duration: delta = total_duration if delta < self.delay: pass elif delta == total_duration: for key, tweenable in self.tweenables: setattr(self.target, key, tweenable.target_value) else: fraction = self.ease((delta - self.delay) / (total_duration - self.delay)) for key, tweenable in self.tweenables: res = tweenable.update(fraction) if isinstance(res, float) and self.round: res = int(res) setattr(self.target, key, res) if delta == total_duration or len(self.tweenables) == 0: self.complete = True self.delta = delta if self.on_update: self.on_update(self.target) return self.complete
python
def update(self, ptime): """Update tween with the time since the last frame""" delta = self.delta + ptime total_duration = self.delay + self.duration if delta > total_duration: delta = total_duration if delta < self.delay: pass elif delta == total_duration: for key, tweenable in self.tweenables: setattr(self.target, key, tweenable.target_value) else: fraction = self.ease((delta - self.delay) / (total_duration - self.delay)) for key, tweenable in self.tweenables: res = tweenable.update(fraction) if isinstance(res, float) and self.round: res = int(res) setattr(self.target, key, res) if delta == total_duration or len(self.tweenables) == 0: self.complete = True self.delta = delta if self.on_update: self.on_update(self.target) return self.complete
[ "def", "update", "(", "self", ",", "ptime", ")", ":", "delta", "=", "self", ".", "delta", "+", "ptime", "total_duration", "=", "self", ".", "delay", "+", "self", ".", "duration", "if", "delta", ">", "total_duration", ":", "delta", "=", "total_duration", "if", "delta", "<", "self", ".", "delay", ":", "pass", "elif", "delta", "==", "total_duration", ":", "for", "key", ",", "tweenable", "in", "self", ".", "tweenables", ":", "setattr", "(", "self", ".", "target", ",", "key", ",", "tweenable", ".", "target_value", ")", "else", ":", "fraction", "=", "self", ".", "ease", "(", "(", "delta", "-", "self", ".", "delay", ")", "/", "(", "total_duration", "-", "self", ".", "delay", ")", ")", "for", "key", ",", "tweenable", "in", "self", ".", "tweenables", ":", "res", "=", "tweenable", ".", "update", "(", "fraction", ")", "if", "isinstance", "(", "res", ",", "float", ")", "and", "self", ".", "round", ":", "res", "=", "int", "(", "res", ")", "setattr", "(", "self", ".", "target", ",", "key", ",", "res", ")", "if", "delta", "==", "total_duration", "or", "len", "(", "self", ".", "tweenables", ")", "==", "0", ":", "self", ".", "complete", "=", "True", "self", ".", "delta", "=", "delta", "if", "self", ".", "on_update", ":", "self", ".", "on_update", "(", "self", ".", "target", ")", "return", "self", ".", "complete" ]
Update tween with the time since the last frame
[ "Update", "tween", "with", "the", "time", "since", "the", "last", "frame" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/pytweener.py#L154-L184
232,013
projecthamster/hamster
src/hamster/overview.py
StackedBar.set_items
def set_items(self, items): """expects a list of key, value to work with""" res = [] max_value = max(sum((rec[1] for rec in items)), 1) for key, val in items: res.append((key, val, val * 1.0 / max_value)) self._items = res
python
def set_items(self, items): """expects a list of key, value to work with""" res = [] max_value = max(sum((rec[1] for rec in items)), 1) for key, val in items: res.append((key, val, val * 1.0 / max_value)) self._items = res
[ "def", "set_items", "(", "self", ",", "items", ")", ":", "res", "=", "[", "]", "max_value", "=", "max", "(", "sum", "(", "(", "rec", "[", "1", "]", "for", "rec", "in", "items", ")", ")", ",", "1", ")", "for", "key", ",", "val", "in", "items", ":", "res", ".", "append", "(", "(", "key", ",", "val", ",", "val", "*", "1.0", "/", "max_value", ")", ")", "self", ".", "_items", "=", "res" ]
expects a list of key, value to work with
[ "expects", "a", "list", "of", "key", "value", "to", "work", "with" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/overview.py#L138-L144
232,014
projecthamster/hamster
src/hamster/overview.py
HorizontalBarChart.set_values
def set_values(self, values): """expects a list of 2-tuples""" self.values = values self.height = len(self.values) * 14 self._max = max(rec[1] for rec in values) if values else dt.timedelta(0)
python
def set_values(self, values): """expects a list of 2-tuples""" self.values = values self.height = len(self.values) * 14 self._max = max(rec[1] for rec in values) if values else dt.timedelta(0)
[ "def", "set_values", "(", "self", ",", "values", ")", ":", "self", ".", "values", "=", "values", "self", ".", "height", "=", "len", "(", "self", ".", "values", ")", "*", "14", "self", ".", "_max", "=", "max", "(", "rec", "[", "1", "]", "for", "rec", "in", "values", ")", "if", "values", "else", "dt", ".", "timedelta", "(", "0", ")" ]
expects a list of 2-tuples
[ "expects", "a", "list", "of", "2", "-", "tuples" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/overview.py#L221-L225
232,015
projecthamster/hamster
src/hamster/lib/stuff.py
datetime_to_hamsterday
def datetime_to_hamsterday(civil_date_time): """Return the hamster day corresponding to a given civil datetime. The hamster day start is taken into account. """ # work around cyclic imports from hamster.lib.configuration import conf if civil_date_time.time() < conf.day_start: # early morning, between midnight and day_start # => the hamster day is the previous civil day hamster_date_time = civil_date_time - dt.timedelta(days=1) else: hamster_date_time = civil_date_time # return only the date return hamster_date_time.date()
python
def datetime_to_hamsterday(civil_date_time): """Return the hamster day corresponding to a given civil datetime. The hamster day start is taken into account. """ # work around cyclic imports from hamster.lib.configuration import conf if civil_date_time.time() < conf.day_start: # early morning, between midnight and day_start # => the hamster day is the previous civil day hamster_date_time = civil_date_time - dt.timedelta(days=1) else: hamster_date_time = civil_date_time # return only the date return hamster_date_time.date()
[ "def", "datetime_to_hamsterday", "(", "civil_date_time", ")", ":", "# work around cyclic imports", "from", "hamster", ".", "lib", ".", "configuration", "import", "conf", "if", "civil_date_time", ".", "time", "(", ")", "<", "conf", ".", "day_start", ":", "# early morning, between midnight and day_start", "# => the hamster day is the previous civil day", "hamster_date_time", "=", "civil_date_time", "-", "dt", ".", "timedelta", "(", "days", "=", "1", ")", "else", ":", "hamster_date_time", "=", "civil_date_time", "# return only the date", "return", "hamster_date_time", ".", "date", "(", ")" ]
Return the hamster day corresponding to a given civil datetime. The hamster day start is taken into account.
[ "Return", "the", "hamster", "day", "corresponding", "to", "a", "given", "civil", "datetime", "." ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/stuff.py#L43-L59
232,016
projecthamster/hamster
src/hamster/lib/stuff.py
hamsterday_time_to_datetime
def hamsterday_time_to_datetime(hamsterday, time): """Return the civil datetime corresponding to a given hamster day and time. The hamster day start is taken into account. """ # work around cyclic imports from hamster.lib.configuration import conf if time < conf.day_start: # early morning, between midnight and day_start # => the hamster day is the previous civil day civil_date = hamsterday + dt.timedelta(days=1) else: civil_date = hamsterday return dt.datetime.combine(civil_date, time)
python
def hamsterday_time_to_datetime(hamsterday, time): """Return the civil datetime corresponding to a given hamster day and time. The hamster day start is taken into account. """ # work around cyclic imports from hamster.lib.configuration import conf if time < conf.day_start: # early morning, between midnight and day_start # => the hamster day is the previous civil day civil_date = hamsterday + dt.timedelta(days=1) else: civil_date = hamsterday return dt.datetime.combine(civil_date, time)
[ "def", "hamsterday_time_to_datetime", "(", "hamsterday", ",", "time", ")", ":", "# work around cyclic imports", "from", "hamster", ".", "lib", ".", "configuration", "import", "conf", "if", "time", "<", "conf", ".", "day_start", ":", "# early morning, between midnight and day_start", "# => the hamster day is the previous civil day", "civil_date", "=", "hamsterday", "+", "dt", ".", "timedelta", "(", "days", "=", "1", ")", "else", ":", "civil_date", "=", "hamsterday", "return", "dt", ".", "datetime", ".", "combine", "(", "civil_date", ",", "time", ")" ]
Return the civil datetime corresponding to a given hamster day and time. The hamster day start is taken into account.
[ "Return", "the", "civil", "datetime", "corresponding", "to", "a", "given", "hamster", "day", "and", "time", "." ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/stuff.py#L67-L82
232,017
projecthamster/hamster
src/hamster/lib/stuff.py
format_duration
def format_duration(minutes, human = True): """formats duration in a human readable format. accepts either minutes or timedelta""" if isinstance(minutes, dt.timedelta): minutes = duration_minutes(minutes) if not minutes: if human: return "" else: return "00:00" if minutes < 0: # format_duration did not work for negative values anyway # return a warning return "NEGATIVE" hours = minutes / 60 minutes = minutes % 60 formatted_duration = "" if human: if minutes % 60 == 0: # duration in round hours formatted_duration += ("%dh") % (hours) elif hours == 0: # duration less than hour formatted_duration += ("%dmin") % (minutes % 60.0) else: # x hours, y minutes formatted_duration += ("%dh %dmin") % (hours, minutes % 60) else: formatted_duration += "%02d:%02d" % (hours, minutes) return formatted_duration
python
def format_duration(minutes, human = True): """formats duration in a human readable format. accepts either minutes or timedelta""" if isinstance(minutes, dt.timedelta): minutes = duration_minutes(minutes) if not minutes: if human: return "" else: return "00:00" if minutes < 0: # format_duration did not work for negative values anyway # return a warning return "NEGATIVE" hours = minutes / 60 minutes = minutes % 60 formatted_duration = "" if human: if minutes % 60 == 0: # duration in round hours formatted_duration += ("%dh") % (hours) elif hours == 0: # duration less than hour formatted_duration += ("%dmin") % (minutes % 60.0) else: # x hours, y minutes formatted_duration += ("%dh %dmin") % (hours, minutes % 60) else: formatted_duration += "%02d:%02d" % (hours, minutes) return formatted_duration
[ "def", "format_duration", "(", "minutes", ",", "human", "=", "True", ")", ":", "if", "isinstance", "(", "minutes", ",", "dt", ".", "timedelta", ")", ":", "minutes", "=", "duration_minutes", "(", "minutes", ")", "if", "not", "minutes", ":", "if", "human", ":", "return", "\"\"", "else", ":", "return", "\"00:00\"", "if", "minutes", "<", "0", ":", "# format_duration did not work for negative values anyway", "# return a warning", "return", "\"NEGATIVE\"", "hours", "=", "minutes", "/", "60", "minutes", "=", "minutes", "%", "60", "formatted_duration", "=", "\"\"", "if", "human", ":", "if", "minutes", "%", "60", "==", "0", ":", "# duration in round hours", "formatted_duration", "+=", "(", "\"%dh\"", ")", "%", "(", "hours", ")", "elif", "hours", "==", "0", ":", "# duration less than hour", "formatted_duration", "+=", "(", "\"%dmin\"", ")", "%", "(", "minutes", "%", "60.0", ")", "else", ":", "# x hours, y minutes", "formatted_duration", "+=", "(", "\"%dh %dmin\"", ")", "%", "(", "hours", ",", "minutes", "%", "60", ")", "else", ":", "formatted_duration", "+=", "\"%02d:%02d\"", "%", "(", "hours", ",", "minutes", ")", "return", "formatted_duration" ]
formats duration in a human readable format. accepts either minutes or timedelta
[ "formats", "duration", "in", "a", "human", "readable", "format", ".", "accepts", "either", "minutes", "or", "timedelta" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/stuff.py#L85-L121
232,018
projecthamster/hamster
src/hamster/lib/stuff.py
duration_minutes
def duration_minutes(duration): """returns minutes from duration, otherwise we keep bashing in same math""" if isinstance(duration, list): res = dt.timedelta() for entry in duration: res += entry return duration_minutes(res) elif isinstance(duration, dt.timedelta): return duration.total_seconds() / 60 else: return duration
python
def duration_minutes(duration): """returns minutes from duration, otherwise we keep bashing in same math""" if isinstance(duration, list): res = dt.timedelta() for entry in duration: res += entry return duration_minutes(res) elif isinstance(duration, dt.timedelta): return duration.total_seconds() / 60 else: return duration
[ "def", "duration_minutes", "(", "duration", ")", ":", "if", "isinstance", "(", "duration", ",", "list", ")", ":", "res", "=", "dt", ".", "timedelta", "(", ")", "for", "entry", "in", "duration", ":", "res", "+=", "entry", "return", "duration_minutes", "(", "res", ")", "elif", "isinstance", "(", "duration", ",", "dt", ".", "timedelta", ")", ":", "return", "duration", ".", "total_seconds", "(", ")", "/", "60", "else", ":", "return", "duration" ]
returns minutes from duration, otherwise we keep bashing in same math
[ "returns", "minutes", "from", "duration", "otherwise", "we", "keep", "bashing", "in", "same", "math" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/stuff.py#L172-L183
232,019
projecthamster/hamster
src/hamster/lib/stuff.py
locale_first_weekday
def locale_first_weekday(): """figure if week starts on monday or sunday""" first_weekday = 6 #by default settle on monday try: process = os.popen("locale first_weekday week-1stday") week_offset, week_start = process.read().split('\n')[:2] process.close() week_start = dt.date(*time.strptime(week_start, "%Y%m%d")[:3]) week_offset = dt.timedelta(int(week_offset) - 1) beginning = week_start + week_offset first_weekday = int(beginning.strftime("%w")) except: logger.warn("WARNING - Failed to get first weekday from locale") return first_weekday
python
def locale_first_weekday(): """figure if week starts on monday or sunday""" first_weekday = 6 #by default settle on monday try: process = os.popen("locale first_weekday week-1stday") week_offset, week_start = process.read().split('\n')[:2] process.close() week_start = dt.date(*time.strptime(week_start, "%Y%m%d")[:3]) week_offset = dt.timedelta(int(week_offset) - 1) beginning = week_start + week_offset first_weekday = int(beginning.strftime("%w")) except: logger.warn("WARNING - Failed to get first weekday from locale") return first_weekday
[ "def", "locale_first_weekday", "(", ")", ":", "first_weekday", "=", "6", "#by default settle on monday", "try", ":", "process", "=", "os", ".", "popen", "(", "\"locale first_weekday week-1stday\"", ")", "week_offset", ",", "week_start", "=", "process", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", "[", ":", "2", "]", "process", ".", "close", "(", ")", "week_start", "=", "dt", ".", "date", "(", "*", "time", ".", "strptime", "(", "week_start", ",", "\"%Y%m%d\"", ")", "[", ":", "3", "]", ")", "week_offset", "=", "dt", ".", "timedelta", "(", "int", "(", "week_offset", ")", "-", "1", ")", "beginning", "=", "week_start", "+", "week_offset", "first_weekday", "=", "int", "(", "beginning", ".", "strftime", "(", "\"%w\"", ")", ")", "except", ":", "logger", ".", "warn", "(", "\"WARNING - Failed to get first weekday from locale\"", ")", "return", "first_weekday" ]
figure if week starts on monday or sunday
[ "figure", "if", "week", "starts", "on", "monday", "or", "sunday" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/stuff.py#L206-L221
232,020
projecthamster/hamster
src/hamster/lib/stuff.py
totals
def totals(iter, keyfunc, sumfunc): """groups items by field described in keyfunc and counts totals using value from sumfunc """ data = sorted(iter, key=keyfunc) res = {} for k, group in groupby(data, keyfunc): res[k] = sum([sumfunc(entry) for entry in group]) return res
python
def totals(iter, keyfunc, sumfunc): """groups items by field described in keyfunc and counts totals using value from sumfunc """ data = sorted(iter, key=keyfunc) res = {} for k, group in groupby(data, keyfunc): res[k] = sum([sumfunc(entry) for entry in group]) return res
[ "def", "totals", "(", "iter", ",", "keyfunc", ",", "sumfunc", ")", ":", "data", "=", "sorted", "(", "iter", ",", "key", "=", "keyfunc", ")", "res", "=", "{", "}", "for", "k", ",", "group", "in", "groupby", "(", "data", ",", "keyfunc", ")", ":", "res", "[", "k", "]", "=", "sum", "(", "[", "sumfunc", "(", "entry", ")", "for", "entry", "in", "group", "]", ")", "return", "res" ]
groups items by field described in keyfunc and counts totals using value from sumfunc
[ "groups", "items", "by", "field", "described", "in", "keyfunc", "and", "counts", "totals", "using", "value", "from", "sumfunc" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/stuff.py#L224-L234
232,021
projecthamster/hamster
src/hamster/lib/stuff.py
dateDict
def dateDict(date, prefix = ""): """converts date into dictionary, having prefix for all the keys""" res = {} res[prefix+"a"] = date.strftime("%a") res[prefix+"A"] = date.strftime("%A") res[prefix+"b"] = date.strftime("%b") res[prefix+"B"] = date.strftime("%B") res[prefix+"c"] = date.strftime("%c") res[prefix+"d"] = date.strftime("%d") res[prefix+"H"] = date.strftime("%H") res[prefix+"I"] = date.strftime("%I") res[prefix+"j"] = date.strftime("%j") res[prefix+"m"] = date.strftime("%m") res[prefix+"M"] = date.strftime("%M") res[prefix+"p"] = date.strftime("%p") res[prefix+"S"] = date.strftime("%S") res[prefix+"U"] = date.strftime("%U") res[prefix+"w"] = date.strftime("%w") res[prefix+"W"] = date.strftime("%W") res[prefix+"x"] = date.strftime("%x") res[prefix+"X"] = date.strftime("%X") res[prefix+"y"] = date.strftime("%y") res[prefix+"Y"] = date.strftime("%Y") res[prefix+"Z"] = date.strftime("%Z") for i, value in res.items(): res[i] = locale_to_utf8(value) return res
python
def dateDict(date, prefix = ""): """converts date into dictionary, having prefix for all the keys""" res = {} res[prefix+"a"] = date.strftime("%a") res[prefix+"A"] = date.strftime("%A") res[prefix+"b"] = date.strftime("%b") res[prefix+"B"] = date.strftime("%B") res[prefix+"c"] = date.strftime("%c") res[prefix+"d"] = date.strftime("%d") res[prefix+"H"] = date.strftime("%H") res[prefix+"I"] = date.strftime("%I") res[prefix+"j"] = date.strftime("%j") res[prefix+"m"] = date.strftime("%m") res[prefix+"M"] = date.strftime("%M") res[prefix+"p"] = date.strftime("%p") res[prefix+"S"] = date.strftime("%S") res[prefix+"U"] = date.strftime("%U") res[prefix+"w"] = date.strftime("%w") res[prefix+"W"] = date.strftime("%W") res[prefix+"x"] = date.strftime("%x") res[prefix+"X"] = date.strftime("%X") res[prefix+"y"] = date.strftime("%y") res[prefix+"Y"] = date.strftime("%Y") res[prefix+"Z"] = date.strftime("%Z") for i, value in res.items(): res[i] = locale_to_utf8(value) return res
[ "def", "dateDict", "(", "date", ",", "prefix", "=", "\"\"", ")", ":", "res", "=", "{", "}", "res", "[", "prefix", "+", "\"a\"", "]", "=", "date", ".", "strftime", "(", "\"%a\"", ")", "res", "[", "prefix", "+", "\"A\"", "]", "=", "date", ".", "strftime", "(", "\"%A\"", ")", "res", "[", "prefix", "+", "\"b\"", "]", "=", "date", ".", "strftime", "(", "\"%b\"", ")", "res", "[", "prefix", "+", "\"B\"", "]", "=", "date", ".", "strftime", "(", "\"%B\"", ")", "res", "[", "prefix", "+", "\"c\"", "]", "=", "date", ".", "strftime", "(", "\"%c\"", ")", "res", "[", "prefix", "+", "\"d\"", "]", "=", "date", ".", "strftime", "(", "\"%d\"", ")", "res", "[", "prefix", "+", "\"H\"", "]", "=", "date", ".", "strftime", "(", "\"%H\"", ")", "res", "[", "prefix", "+", "\"I\"", "]", "=", "date", ".", "strftime", "(", "\"%I\"", ")", "res", "[", "prefix", "+", "\"j\"", "]", "=", "date", ".", "strftime", "(", "\"%j\"", ")", "res", "[", "prefix", "+", "\"m\"", "]", "=", "date", ".", "strftime", "(", "\"%m\"", ")", "res", "[", "prefix", "+", "\"M\"", "]", "=", "date", ".", "strftime", "(", "\"%M\"", ")", "res", "[", "prefix", "+", "\"p\"", "]", "=", "date", ".", "strftime", "(", "\"%p\"", ")", "res", "[", "prefix", "+", "\"S\"", "]", "=", "date", ".", "strftime", "(", "\"%S\"", ")", "res", "[", "prefix", "+", "\"U\"", "]", "=", "date", ".", "strftime", "(", "\"%U\"", ")", "res", "[", "prefix", "+", "\"w\"", "]", "=", "date", ".", "strftime", "(", "\"%w\"", ")", "res", "[", "prefix", "+", "\"W\"", "]", "=", "date", ".", "strftime", "(", "\"%W\"", ")", "res", "[", "prefix", "+", "\"x\"", "]", "=", "date", ".", "strftime", "(", "\"%x\"", ")", "res", "[", "prefix", "+", "\"X\"", "]", "=", "date", ".", "strftime", "(", "\"%X\"", ")", "res", "[", "prefix", "+", "\"y\"", "]", "=", "date", ".", "strftime", "(", "\"%y\"", ")", "res", "[", "prefix", "+", "\"Y\"", "]", "=", "date", ".", "strftime", "(", "\"%Y\"", ")", "res", "[", "prefix", "+", "\"Z\"", "]", "=", "date", ".", "strftime", "(", "\"%Z\"", ")", "for", "i", ",", "value", "in", "res", ".", "items", "(", ")", ":", "res", "[", "i", "]", "=", "locale_to_utf8", "(", "value", ")", "return", "res" ]
converts date into dictionary, having prefix for all the keys
[ "converts", "date", "into", "dictionary", "having", "prefix", "for", "all", "the", "keys" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/stuff.py#L237-L266
232,022
projecthamster/hamster
src/hamster/storage/db.py
Storage.__get_tag_ids
def __get_tag_ids(self, tags): """look up tags by their name. create if not found""" db_tags = self.fetchall("select * from tags where name in (%s)" % ",".join(["?"] * len(tags)), tags) # bit of magic here - using sqlites bind variables changes = False # check if any of tags needs resurrection set_complete = [str(tag["id"]) for tag in db_tags if tag["autocomplete"] == "false"] if set_complete: changes = True self.execute("update tags set autocomplete='true' where id in (%s)" % ", ".join(set_complete)) found_tags = [tag["name"] for tag in db_tags] add = set(tags) - set(found_tags) if add: statement = "insert into tags(name) values(?)" self.execute([statement] * len(add), [(tag,) for tag in add]) return self.__get_tag_ids(tags)[0], True # all done, recurse else: return db_tags, changes
python
def __get_tag_ids(self, tags): """look up tags by their name. create if not found""" db_tags = self.fetchall("select * from tags where name in (%s)" % ",".join(["?"] * len(tags)), tags) # bit of magic here - using sqlites bind variables changes = False # check if any of tags needs resurrection set_complete = [str(tag["id"]) for tag in db_tags if tag["autocomplete"] == "false"] if set_complete: changes = True self.execute("update tags set autocomplete='true' where id in (%s)" % ", ".join(set_complete)) found_tags = [tag["name"] for tag in db_tags] add = set(tags) - set(found_tags) if add: statement = "insert into tags(name) values(?)" self.execute([statement] * len(add), [(tag,) for tag in add]) return self.__get_tag_ids(tags)[0], True # all done, recurse else: return db_tags, changes
[ "def", "__get_tag_ids", "(", "self", ",", "tags", ")", ":", "db_tags", "=", "self", ".", "fetchall", "(", "\"select * from tags where name in (%s)\"", "%", "\",\"", ".", "join", "(", "[", "\"?\"", "]", "*", "len", "(", "tags", ")", ")", ",", "tags", ")", "# bit of magic here - using sqlites bind variables", "changes", "=", "False", "# check if any of tags needs resurrection", "set_complete", "=", "[", "str", "(", "tag", "[", "\"id\"", "]", ")", "for", "tag", "in", "db_tags", "if", "tag", "[", "\"autocomplete\"", "]", "==", "\"false\"", "]", "if", "set_complete", ":", "changes", "=", "True", "self", ".", "execute", "(", "\"update tags set autocomplete='true' where id in (%s)\"", "%", "\", \"", ".", "join", "(", "set_complete", ")", ")", "found_tags", "=", "[", "tag", "[", "\"name\"", "]", "for", "tag", "in", "db_tags", "]", "add", "=", "set", "(", "tags", ")", "-", "set", "(", "found_tags", ")", "if", "add", ":", "statement", "=", "\"insert into tags(name) values(?)\"", "self", ".", "execute", "(", "[", "statement", "]", "*", "len", "(", "add", ")", ",", "[", "(", "tag", ",", ")", "for", "tag", "in", "add", "]", ")", "return", "self", ".", "__get_tag_ids", "(", "tags", ")", "[", "0", "]", ",", "True", "# all done, recurse", "else", ":", "return", "db_tags", ",", "changes" ]
look up tags by their name. create if not found
[ "look", "up", "tags", "by", "their", "name", ".", "create", "if", "not", "found" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L161-L186
232,023
projecthamster/hamster
src/hamster/storage/db.py
Storage.__get_activity_by_name
def __get_activity_by_name(self, name, category_id = None, resurrect = True): """get most recent, preferably not deleted activity by it's name""" if category_id: query = """ SELECT a.id, a.name, a.deleted, coalesce(b.name, ?) as category FROM activities a LEFT JOIN categories b ON category_id = b.id WHERE lower(a.name) = lower(?) AND category_id = ? ORDER BY a.deleted, a.id desc LIMIT 1 """ res = self.fetchone(query, (self._unsorted_localized, name, category_id)) else: query = """ SELECT a.id, a.name, a.deleted, coalesce(b.name, ?) as category FROM activities a LEFT JOIN categories b ON category_id = b.id WHERE lower(a.name) = lower(?) ORDER BY a.deleted, a.id desc LIMIT 1 """ res = self.fetchone(query, (self._unsorted_localized, name, )) if res: keys = ('id', 'name', 'deleted', 'category') res = dict([(key, res[key]) for key in keys]) res['deleted'] = res['deleted'] or False # if the activity was marked as deleted, resurrect on first call # and put in the unsorted category if res['deleted'] and resurrect: update = """ UPDATE activities SET deleted = null, category_id = -1 WHERE id = ? """ self.execute(update, (res['id'], )) return res return None
python
def __get_activity_by_name(self, name, category_id = None, resurrect = True): """get most recent, preferably not deleted activity by it's name""" if category_id: query = """ SELECT a.id, a.name, a.deleted, coalesce(b.name, ?) as category FROM activities a LEFT JOIN categories b ON category_id = b.id WHERE lower(a.name) = lower(?) AND category_id = ? ORDER BY a.deleted, a.id desc LIMIT 1 """ res = self.fetchone(query, (self._unsorted_localized, name, category_id)) else: query = """ SELECT a.id, a.name, a.deleted, coalesce(b.name, ?) as category FROM activities a LEFT JOIN categories b ON category_id = b.id WHERE lower(a.name) = lower(?) ORDER BY a.deleted, a.id desc LIMIT 1 """ res = self.fetchone(query, (self._unsorted_localized, name, )) if res: keys = ('id', 'name', 'deleted', 'category') res = dict([(key, res[key]) for key in keys]) res['deleted'] = res['deleted'] or False # if the activity was marked as deleted, resurrect on first call # and put in the unsorted category if res['deleted'] and resurrect: update = """ UPDATE activities SET deleted = null, category_id = -1 WHERE id = ? """ self.execute(update, (res['id'], )) return res return None
[ "def", "__get_activity_by_name", "(", "self", ",", "name", ",", "category_id", "=", "None", ",", "resurrect", "=", "True", ")", ":", "if", "category_id", ":", "query", "=", "\"\"\"\n SELECT a.id, a.name, a.deleted, coalesce(b.name, ?) as category\n FROM activities a\n LEFT JOIN categories b ON category_id = b.id\n WHERE lower(a.name) = lower(?)\n AND category_id = ?\n ORDER BY a.deleted, a.id desc\n LIMIT 1\n \"\"\"", "res", "=", "self", ".", "fetchone", "(", "query", ",", "(", "self", ".", "_unsorted_localized", ",", "name", ",", "category_id", ")", ")", "else", ":", "query", "=", "\"\"\"\n SELECT a.id, a.name, a.deleted, coalesce(b.name, ?) as category\n FROM activities a\n LEFT JOIN categories b ON category_id = b.id\n WHERE lower(a.name) = lower(?)\n ORDER BY a.deleted, a.id desc\n LIMIT 1\n \"\"\"", "res", "=", "self", ".", "fetchone", "(", "query", ",", "(", "self", ".", "_unsorted_localized", ",", "name", ",", ")", ")", "if", "res", ":", "keys", "=", "(", "'id'", ",", "'name'", ",", "'deleted'", ",", "'category'", ")", "res", "=", "dict", "(", "[", "(", "key", ",", "res", "[", "key", "]", ")", "for", "key", "in", "keys", "]", ")", "res", "[", "'deleted'", "]", "=", "res", "[", "'deleted'", "]", "or", "False", "# if the activity was marked as deleted, resurrect on first call", "# and put in the unsorted category", "if", "res", "[", "'deleted'", "]", "and", "resurrect", ":", "update", "=", "\"\"\"\n UPDATE activities\n SET deleted = null, category_id = -1\n WHERE id = ?\n \"\"\"", "self", ".", "execute", "(", "update", ",", "(", "res", "[", "'id'", "]", ",", ")", ")", "return", "res", "return", "None" ]
get most recent, preferably not deleted activity by it's name
[ "get", "most", "recent", "preferably", "not", "deleted", "activity", "by", "it", "s", "name" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L297-L340
232,024
projecthamster/hamster
src/hamster/storage/db.py
Storage.__get_category_id
def __get_category_id(self, name): """returns category by it's name""" query = """ SELECT id from categories WHERE lower(name) = lower(?) ORDER BY id desc LIMIT 1 """ res = self.fetchone(query, (name, )) if res: return res['id'] return None
python
def __get_category_id(self, name): """returns category by it's name""" query = """ SELECT id from categories WHERE lower(name) = lower(?) ORDER BY id desc LIMIT 1 """ res = self.fetchone(query, (name, )) if res: return res['id'] return None
[ "def", "__get_category_id", "(", "self", ",", "name", ")", ":", "query", "=", "\"\"\"\n SELECT id from categories\n WHERE lower(name) = lower(?)\n ORDER BY id desc\n LIMIT 1\n \"\"\"", "res", "=", "self", ".", "fetchone", "(", "query", ",", "(", "name", ",", ")", ")", "if", "res", ":", "return", "res", "[", "'id'", "]", "return", "None" ]
returns category by it's name
[ "returns", "category", "by", "it", "s", "name" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L342-L357
232,025
projecthamster/hamster
src/hamster/storage/db.py
Storage.__group_tags
def __group_tags(self, facts): """put the fact back together and move all the unique tags to an array""" if not facts: return facts #be it None or whatever grouped_facts = [] for fact_id, fact_tags in itertools.groupby(facts, lambda f: f["id"]): fact_tags = list(fact_tags) # first one is as good as the last one grouped_fact = fact_tags[0] # we need dict so we can modify it (sqlite.Row is read only) # in python 2.5, sqlite does not have keys() yet, so we hardcode them (yay!) keys = ["id", "start_time", "end_time", "description", "name", "activity_id", "category", "tag"] grouped_fact = dict([(key, grouped_fact[key]) for key in keys]) grouped_fact["tags"] = [ft["tag"] for ft in fact_tags if ft["tag"]] grouped_facts.append(grouped_fact) return grouped_facts
python
def __group_tags(self, facts): """put the fact back together and move all the unique tags to an array""" if not facts: return facts #be it None or whatever grouped_facts = [] for fact_id, fact_tags in itertools.groupby(facts, lambda f: f["id"]): fact_tags = list(fact_tags) # first one is as good as the last one grouped_fact = fact_tags[0] # we need dict so we can modify it (sqlite.Row is read only) # in python 2.5, sqlite does not have keys() yet, so we hardcode them (yay!) keys = ["id", "start_time", "end_time", "description", "name", "activity_id", "category", "tag"] grouped_fact = dict([(key, grouped_fact[key]) for key in keys]) grouped_fact["tags"] = [ft["tag"] for ft in fact_tags if ft["tag"]] grouped_facts.append(grouped_fact) return grouped_facts
[ "def", "__group_tags", "(", "self", ",", "facts", ")", ":", "if", "not", "facts", ":", "return", "facts", "#be it None or whatever", "grouped_facts", "=", "[", "]", "for", "fact_id", ",", "fact_tags", "in", "itertools", ".", "groupby", "(", "facts", ",", "lambda", "f", ":", "f", "[", "\"id\"", "]", ")", ":", "fact_tags", "=", "list", "(", "fact_tags", ")", "# first one is as good as the last one", "grouped_fact", "=", "fact_tags", "[", "0", "]", "# we need dict so we can modify it (sqlite.Row is read only)", "# in python 2.5, sqlite does not have keys() yet, so we hardcode them (yay!)", "keys", "=", "[", "\"id\"", ",", "\"start_time\"", ",", "\"end_time\"", ",", "\"description\"", ",", "\"name\"", ",", "\"activity_id\"", ",", "\"category\"", ",", "\"tag\"", "]", "grouped_fact", "=", "dict", "(", "[", "(", "key", ",", "grouped_fact", "[", "key", "]", ")", "for", "key", "in", "keys", "]", ")", "grouped_fact", "[", "\"tags\"", "]", "=", "[", "ft", "[", "\"tag\"", "]", "for", "ft", "in", "fact_tags", "if", "ft", "[", "\"tag\"", "]", "]", "grouped_facts", ".", "append", "(", "grouped_fact", ")", "return", "grouped_facts" ]
put the fact back together and move all the unique tags to an array
[ "put", "the", "fact", "back", "together", "and", "move", "all", "the", "unique", "tags", "to", "an", "array" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L379-L398
232,026
projecthamster/hamster
src/hamster/storage/db.py
Storage.__squeeze_in
def __squeeze_in(self, start_time): """ tries to put task in the given date if there are conflicts, we will only truncate the ongoing task and replace it's end part with our activity """ # we are checking if our start time is in the middle of anything # or maybe there is something after us - so we know to adjust end time # in the latter case go only few hours ahead. everything else is madness, heh query = """ SELECT a.*, b.name FROM facts a LEFT JOIN activities b on b.id = a.activity_id WHERE ((start_time < ? and end_time > ?) OR (start_time > ? and start_time < ? and end_time is null) OR (start_time > ? and start_time < ?)) ORDER BY start_time LIMIT 1 """ fact = self.fetchone(query, (start_time, start_time, start_time - dt.timedelta(hours = 12), start_time, start_time, start_time + dt.timedelta(hours = 12))) end_time = None if fact: if start_time > fact["start_time"]: #we are in middle of a fact - truncate it to our start self.execute("UPDATE facts SET end_time=? WHERE id=?", (start_time, fact["id"])) else: #otherwise we have found a task that is after us end_time = fact["start_time"] return end_time
python
def __squeeze_in(self, start_time): """ tries to put task in the given date if there are conflicts, we will only truncate the ongoing task and replace it's end part with our activity """ # we are checking if our start time is in the middle of anything # or maybe there is something after us - so we know to adjust end time # in the latter case go only few hours ahead. everything else is madness, heh query = """ SELECT a.*, b.name FROM facts a LEFT JOIN activities b on b.id = a.activity_id WHERE ((start_time < ? and end_time > ?) OR (start_time > ? and start_time < ? and end_time is null) OR (start_time > ? and start_time < ?)) ORDER BY start_time LIMIT 1 """ fact = self.fetchone(query, (start_time, start_time, start_time - dt.timedelta(hours = 12), start_time, start_time, start_time + dt.timedelta(hours = 12))) end_time = None if fact: if start_time > fact["start_time"]: #we are in middle of a fact - truncate it to our start self.execute("UPDATE facts SET end_time=? WHERE id=?", (start_time, fact["id"])) else: #otherwise we have found a task that is after us end_time = fact["start_time"] return end_time
[ "def", "__squeeze_in", "(", "self", ",", "start_time", ")", ":", "# we are checking if our start time is in the middle of anything", "# or maybe there is something after us - so we know to adjust end time", "# in the latter case go only few hours ahead. everything else is madness, heh", "query", "=", "\"\"\"\n SELECT a.*, b.name\n FROM facts a\n LEFT JOIN activities b on b.id = a.activity_id\n WHERE ((start_time < ? and end_time > ?)\n OR (start_time > ? and start_time < ? and end_time is null)\n OR (start_time > ? and start_time < ?))\n ORDER BY start_time\n LIMIT 1\n \"\"\"", "fact", "=", "self", ".", "fetchone", "(", "query", ",", "(", "start_time", ",", "start_time", ",", "start_time", "-", "dt", ".", "timedelta", "(", "hours", "=", "12", ")", ",", "start_time", ",", "start_time", ",", "start_time", "+", "dt", ".", "timedelta", "(", "hours", "=", "12", ")", ")", ")", "end_time", "=", "None", "if", "fact", ":", "if", "start_time", ">", "fact", "[", "\"start_time\"", "]", ":", "#we are in middle of a fact - truncate it to our start", "self", ".", "execute", "(", "\"UPDATE facts SET end_time=? WHERE id=?\"", ",", "(", "start_time", ",", "fact", "[", "\"id\"", "]", ")", ")", "else", ":", "#otherwise we have found a task that is after us", "end_time", "=", "fact", "[", "\"start_time\"", "]", "return", "end_time" ]
tries to put task in the given date if there are conflicts, we will only truncate the ongoing task and replace it's end part with our activity
[ "tries", "to", "put", "task", "in", "the", "given", "date", "if", "there", "are", "conflicts", "we", "will", "only", "truncate", "the", "ongoing", "task", "and", "replace", "it", "s", "end", "part", "with", "our", "activity" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L415-L447
232,027
projecthamster/hamster
src/hamster/storage/db.py
Storage.__get_activities
def __get_activities(self, search): """returns list of activities for autocomplete, activity names converted to lowercase""" query = """ SELECT a.name AS name, b.name AS category FROM activities a LEFT JOIN categories b ON coalesce(b.id, -1) = a.category_id LEFT JOIN facts f ON a.id = f.activity_id WHERE deleted IS NULL AND a.search_name LIKE ? ESCAPE '\\' GROUP BY a.id ORDER BY max(f.start_time) DESC, lower(a.name) LIMIT 50 """ search = search.lower() search = search.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_') activities = self.fetchall(query, ('%s%%' % search, )) return activities
python
def __get_activities(self, search): """returns list of activities for autocomplete, activity names converted to lowercase""" query = """ SELECT a.name AS name, b.name AS category FROM activities a LEFT JOIN categories b ON coalesce(b.id, -1) = a.category_id LEFT JOIN facts f ON a.id = f.activity_id WHERE deleted IS NULL AND a.search_name LIKE ? ESCAPE '\\' GROUP BY a.id ORDER BY max(f.start_time) DESC, lower(a.name) LIMIT 50 """ search = search.lower() search = search.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_') activities = self.fetchall(query, ('%s%%' % search, )) return activities
[ "def", "__get_activities", "(", "self", ",", "search", ")", ":", "query", "=", "\"\"\"\n SELECT a.name AS name, b.name AS category\n FROM activities a\n LEFT JOIN categories b ON coalesce(b.id, -1) = a.category_id\n LEFT JOIN facts f ON a.id = f.activity_id\n WHERE deleted IS NULL\n AND a.search_name LIKE ? ESCAPE '\\\\'\n GROUP BY a.id\n ORDER BY max(f.start_time) DESC, lower(a.name)\n LIMIT 50\n \"\"\"", "search", "=", "search", ".", "lower", "(", ")", "search", "=", "search", ".", "replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ")", ".", "replace", "(", "'%'", ",", "'\\\\%'", ")", ".", "replace", "(", "'_'", ",", "'\\\\_'", ")", "activities", "=", "self", ".", "fetchall", "(", "query", ",", "(", "'%s%%'", "%", "search", ",", ")", ")", "return", "activities" ]
returns list of activities for autocomplete, activity names converted to lowercase
[ "returns", "list", "of", "activities", "for", "autocomplete", "activity", "names", "converted", "to", "lowercase" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L760-L779
232,028
projecthamster/hamster
src/hamster/storage/db.py
Storage.__remove_activity
def __remove_activity(self, id): """ check if we have any facts with this activity and behave accordingly if there are facts - sets activity to deleted = True else, just remove it""" query = "select count(*) as count from facts where activity_id = ?" bound_facts = self.fetchone(query, (id,))['count'] if bound_facts > 0: self.execute("UPDATE activities SET deleted = 1 WHERE id = ?", (id,)) else: self.execute("delete from activities where id = ?", (id,))
python
def __remove_activity(self, id): """ check if we have any facts with this activity and behave accordingly if there are facts - sets activity to deleted = True else, just remove it""" query = "select count(*) as count from facts where activity_id = ?" bound_facts = self.fetchone(query, (id,))['count'] if bound_facts > 0: self.execute("UPDATE activities SET deleted = 1 WHERE id = ?", (id,)) else: self.execute("delete from activities where id = ?", (id,))
[ "def", "__remove_activity", "(", "self", ",", "id", ")", ":", "query", "=", "\"select count(*) as count from facts where activity_id = ?\"", "bound_facts", "=", "self", ".", "fetchone", "(", "query", ",", "(", "id", ",", ")", ")", "[", "'count'", "]", "if", "bound_facts", ">", "0", ":", "self", ".", "execute", "(", "\"UPDATE activities SET deleted = 1 WHERE id = ?\"", ",", "(", "id", ",", ")", ")", "else", ":", "self", ".", "execute", "(", "\"delete from activities where id = ?\"", ",", "(", "id", ",", ")", ")" ]
check if we have any facts with this activity and behave accordingly if there are facts - sets activity to deleted = True else, just remove it
[ "check", "if", "we", "have", "any", "facts", "with", "this", "activity", "and", "behave", "accordingly", "if", "there", "are", "facts", "-", "sets", "activity", "to", "deleted", "=", "True", "else", "just", "remove", "it" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L781-L792
232,029
projecthamster/hamster
src/hamster/storage/db.py
Storage.__remove_category
def __remove_category(self, id): """move all activities to unsorted and remove category""" affected_query = """ SELECT id FROM facts WHERE activity_id in (SELECT id FROM activities where category_id=?) """ affected_ids = [res[0] for res in self.fetchall(affected_query, (id,))] update = "update activities set category_id = -1 where category_id = ?" self.execute(update, (id, )) self.execute("delete from categories where id = ?", (id, )) self.__remove_index(affected_ids)
python
def __remove_category(self, id): """move all activities to unsorted and remove category""" affected_query = """ SELECT id FROM facts WHERE activity_id in (SELECT id FROM activities where category_id=?) """ affected_ids = [res[0] for res in self.fetchall(affected_query, (id,))] update = "update activities set category_id = -1 where category_id = ?" self.execute(update, (id, )) self.execute("delete from categories where id = ?", (id, )) self.__remove_index(affected_ids)
[ "def", "__remove_category", "(", "self", ",", "id", ")", ":", "affected_query", "=", "\"\"\"\n SELECT id\n FROM facts\n WHERE activity_id in (SELECT id FROM activities where category_id=?)\n \"\"\"", "affected_ids", "=", "[", "res", "[", "0", "]", "for", "res", "in", "self", ".", "fetchall", "(", "affected_query", ",", "(", "id", ",", ")", ")", "]", "update", "=", "\"update activities set category_id = -1 where category_id = ?\"", "self", ".", "execute", "(", "update", ",", "(", "id", ",", ")", ")", "self", ".", "execute", "(", "\"delete from categories where id = ?\"", ",", "(", "id", ",", ")", ")", "self", ".", "__remove_index", "(", "affected_ids", ")" ]
move all activities to unsorted and remove category
[ "move", "all", "activities", "to", "unsorted", "and", "remove", "category" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L795-L810
232,030
projecthamster/hamster
src/hamster/storage/db.py
Storage.__remove_index
def __remove_index(self, ids): """remove affected ids from the index""" if not ids: return ids = ",".join((str(id) for id in ids)) self.execute("DELETE FROM fact_index where id in (%s)" % ids)
python
def __remove_index(self, ids): """remove affected ids from the index""" if not ids: return ids = ",".join((str(id) for id in ids)) self.execute("DELETE FROM fact_index where id in (%s)" % ids)
[ "def", "__remove_index", "(", "self", ",", "ids", ")", ":", "if", "not", "ids", ":", "return", "ids", "=", "\",\"", ".", "join", "(", "(", "str", "(", "id", ")", "for", "id", "in", "ids", ")", ")", "self", ".", "execute", "(", "\"DELETE FROM fact_index where id in (%s)\"", "%", "ids", ")" ]
remove affected ids from the index
[ "remove", "affected", "ids", "from", "the", "index" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L834-L840
232,031
projecthamster/hamster
src/hamster/storage/db.py
Storage.execute
def execute(self, statement, params = ()): """ execute sql statement. optionally you can give multiple statements to save on cursor creation and closure """ con = self.__con or self.connection cur = self.__cur or con.cursor() if isinstance(statement, list) == False: # we expect to receive instructions in list statement = [statement] params = [params] for state, param in zip(statement, params): logger.debug("%s %s" % (state, param)) cur.execute(state, param) if not self.__con: con.commit() cur.close() self.register_modification()
python
def execute(self, statement, params = ()): """ execute sql statement. optionally you can give multiple statements to save on cursor creation and closure """ con = self.__con or self.connection cur = self.__cur or con.cursor() if isinstance(statement, list) == False: # we expect to receive instructions in list statement = [statement] params = [params] for state, param in zip(statement, params): logger.debug("%s %s" % (state, param)) cur.execute(state, param) if not self.__con: con.commit() cur.close() self.register_modification()
[ "def", "execute", "(", "self", ",", "statement", ",", "params", "=", "(", ")", ")", ":", "con", "=", "self", ".", "__con", "or", "self", ".", "connection", "cur", "=", "self", ".", "__cur", "or", "con", ".", "cursor", "(", ")", "if", "isinstance", "(", "statement", ",", "list", ")", "==", "False", ":", "# we expect to receive instructions in list", "statement", "=", "[", "statement", "]", "params", "=", "[", "params", "]", "for", "state", ",", "param", "in", "zip", "(", "statement", ",", "params", ")", ":", "logger", ".", "debug", "(", "\"%s %s\"", "%", "(", "state", ",", "param", ")", ")", "cur", ".", "execute", "(", "state", ",", "param", ")", "if", "not", "self", ".", "__con", ":", "con", ".", "commit", "(", ")", "cur", ".", "close", "(", ")", "self", ".", "register_modification", "(", ")" ]
execute sql statement. optionally you can give multiple statements to save on cursor creation and closure
[ "execute", "sql", "statement", ".", "optionally", "you", "can", "give", "multiple", "statements", "to", "save", "on", "cursor", "creation", "and", "closure" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L913-L932
232,032
projecthamster/hamster
src/hamster/storage/db.py
Storage.run_fixtures
def run_fixtures(self): self.start_transaction() """upgrade DB to hamster version""" version = self.fetchone("SELECT version FROM version")["version"] current_version = 9 if version < 8: # working around sqlite's utf-f case sensitivity (bug 624438) # more info: http://www.gsak.net/help/hs23820.htm self.execute("ALTER TABLE activities ADD COLUMN search_name varchar2") activities = self.fetchall("select * from activities") statement = "update activities set search_name = ? where id = ?" for activity in activities: self.execute(statement, (activity['name'].lower(), activity['id'])) # same for categories self.execute("ALTER TABLE categories ADD COLUMN search_name varchar2") categories = self.fetchall("select * from categories") statement = "update categories set search_name = ? where id = ?" for category in categories: self.execute(statement, (category['name'].lower(), category['id'])) if version < 9: # adding full text search self.execute("""CREATE VIRTUAL TABLE fact_index USING fts3(id, name, category, description, tag)""") # at the happy end, update version number if version < current_version: #lock down current version self.execute("UPDATE version SET version = %d" % current_version) print("updated database from version %d to %d" % (version, current_version)) self.end_transaction()
python
def run_fixtures(self): self.start_transaction() """upgrade DB to hamster version""" version = self.fetchone("SELECT version FROM version")["version"] current_version = 9 if version < 8: # working around sqlite's utf-f case sensitivity (bug 624438) # more info: http://www.gsak.net/help/hs23820.htm self.execute("ALTER TABLE activities ADD COLUMN search_name varchar2") activities = self.fetchall("select * from activities") statement = "update activities set search_name = ? where id = ?" for activity in activities: self.execute(statement, (activity['name'].lower(), activity['id'])) # same for categories self.execute("ALTER TABLE categories ADD COLUMN search_name varchar2") categories = self.fetchall("select * from categories") statement = "update categories set search_name = ? where id = ?" for category in categories: self.execute(statement, (category['name'].lower(), category['id'])) if version < 9: # adding full text search self.execute("""CREATE VIRTUAL TABLE fact_index USING fts3(id, name, category, description, tag)""") # at the happy end, update version number if version < current_version: #lock down current version self.execute("UPDATE version SET version = %d" % current_version) print("updated database from version %d to %d" % (version, current_version)) self.end_transaction()
[ "def", "run_fixtures", "(", "self", ")", ":", "self", ".", "start_transaction", "(", ")", "version", "=", "self", ".", "fetchone", "(", "\"SELECT version FROM version\"", ")", "[", "\"version\"", "]", "current_version", "=", "9", "if", "version", "<", "8", ":", "# working around sqlite's utf-f case sensitivity (bug 624438)", "# more info: http://www.gsak.net/help/hs23820.htm", "self", ".", "execute", "(", "\"ALTER TABLE activities ADD COLUMN search_name varchar2\"", ")", "activities", "=", "self", ".", "fetchall", "(", "\"select * from activities\"", ")", "statement", "=", "\"update activities set search_name = ? where id = ?\"", "for", "activity", "in", "activities", ":", "self", ".", "execute", "(", "statement", ",", "(", "activity", "[", "'name'", "]", ".", "lower", "(", ")", ",", "activity", "[", "'id'", "]", ")", ")", "# same for categories", "self", ".", "execute", "(", "\"ALTER TABLE categories ADD COLUMN search_name varchar2\"", ")", "categories", "=", "self", ".", "fetchall", "(", "\"select * from categories\"", ")", "statement", "=", "\"update categories set search_name = ? where id = ?\"", "for", "category", "in", "categories", ":", "self", ".", "execute", "(", "statement", ",", "(", "category", "[", "'name'", "]", ".", "lower", "(", ")", ",", "category", "[", "'id'", "]", ")", ")", "if", "version", "<", "9", ":", "# adding full text search", "self", ".", "execute", "(", "\"\"\"CREATE VIRTUAL TABLE fact_index\n USING fts3(id, name, category, description, tag)\"\"\"", ")", "# at the happy end, update version number", "if", "version", "<", "current_version", ":", "#lock down current version", "self", ".", "execute", "(", "\"UPDATE version SET version = %d\"", "%", "current_version", ")", "print", "(", "\"updated database from version %d to %d\"", "%", "(", "version", ",", "current_version", ")", ")", "self", ".", "end_transaction", "(", ")" ]
upgrade DB to hamster version
[ "upgrade", "DB", "to", "hamster", "version" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/storage/db.py#L959-L995
232,033
projecthamster/hamster
src/hamster/widgets/facttree.py
FactTree.current_fact_index
def current_fact_index(self): """Current fact index in the self.facts list.""" facts_ids = [fact.id for fact in self.facts] return facts_ids.index(self.current_fact.id)
python
def current_fact_index(self): """Current fact index in the self.facts list.""" facts_ids = [fact.id for fact in self.facts] return facts_ids.index(self.current_fact.id)
[ "def", "current_fact_index", "(", "self", ")", ":", "facts_ids", "=", "[", "fact", ".", "id", "for", "fact", "in", "self", ".", "facts", "]", "return", "facts_ids", ".", "index", "(", "self", ".", "current_fact", ".", "id", ")" ]
Current fact index in the self.facts list.
[ "Current", "fact", "index", "in", "the", "self", ".", "facts", "list", "." ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/widgets/facttree.py#L258-L261
232,034
projecthamster/hamster
src/hamster/lib/graphics.py
chain
def chain(*steps): """chains the given list of functions and object animations into a callback string. Expects an interlaced list of object and params, something like: object, {params}, callable, {params}, object, {}, object, {params} Assumes that all callees accept on_complete named param. The last item in the list can omit that. XXX - figure out where to place these guys as they are quite useful """ if not steps: return def on_done(sprite=None): chain(*steps[2:]) obj, params = steps[:2] if len(steps) > 2: params['on_complete'] = on_done if callable(obj): obj(**params) else: obj.animate(**params)
python
def chain(*steps): """chains the given list of functions and object animations into a callback string. Expects an interlaced list of object and params, something like: object, {params}, callable, {params}, object, {}, object, {params} Assumes that all callees accept on_complete named param. The last item in the list can omit that. XXX - figure out where to place these guys as they are quite useful """ if not steps: return def on_done(sprite=None): chain(*steps[2:]) obj, params = steps[:2] if len(steps) > 2: params['on_complete'] = on_done if callable(obj): obj(**params) else: obj.animate(**params)
[ "def", "chain", "(", "*", "steps", ")", ":", "if", "not", "steps", ":", "return", "def", "on_done", "(", "sprite", "=", "None", ")", ":", "chain", "(", "*", "steps", "[", "2", ":", "]", ")", "obj", ",", "params", "=", "steps", "[", ":", "2", "]", "if", "len", "(", "steps", ")", ">", "2", ":", "params", "[", "'on_complete'", "]", "=", "on_done", "if", "callable", "(", "obj", ")", ":", "obj", "(", "*", "*", "params", ")", "else", ":", "obj", ".", "animate", "(", "*", "*", "params", ")" ]
chains the given list of functions and object animations into a callback string. Expects an interlaced list of object and params, something like: object, {params}, callable, {params}, object, {}, object, {params} Assumes that all callees accept on_complete named param. The last item in the list can omit that. XXX - figure out where to place these guys as they are quite useful
[ "chains", "the", "given", "list", "of", "functions", "and", "object", "animations", "into", "a", "callback", "string", "." ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L160-L185
232,035
projecthamster/hamster
src/hamster/lib/graphics.py
full_pixels
def full_pixels(space, data, gap_pixels=1): """returns the given data distributed in the space ensuring it's full pixels and with the given gap. this will result in minor sub-pixel inaccuracies. XXX - figure out where to place these guys as they are quite useful """ available = space - (len(data) - 1) * gap_pixels # 8 recs 7 gaps res = [] for i, val in enumerate(data): # convert data to 0..1 scale so we deal with fractions data_sum = sum(data[i:]) norm = val * 1.0 / data_sum w = max(int(round(available * norm)), 1) res.append(w) available -= w return res
python
def full_pixels(space, data, gap_pixels=1): """returns the given data distributed in the space ensuring it's full pixels and with the given gap. this will result in minor sub-pixel inaccuracies. XXX - figure out where to place these guys as they are quite useful """ available = space - (len(data) - 1) * gap_pixels # 8 recs 7 gaps res = [] for i, val in enumerate(data): # convert data to 0..1 scale so we deal with fractions data_sum = sum(data[i:]) norm = val * 1.0 / data_sum w = max(int(round(available * norm)), 1) res.append(w) available -= w return res
[ "def", "full_pixels", "(", "space", ",", "data", ",", "gap_pixels", "=", "1", ")", ":", "available", "=", "space", "-", "(", "len", "(", "data", ")", "-", "1", ")", "*", "gap_pixels", "# 8 recs 7 gaps", "res", "=", "[", "]", "for", "i", ",", "val", "in", "enumerate", "(", "data", ")", ":", "# convert data to 0..1 scale so we deal with fractions", "data_sum", "=", "sum", "(", "data", "[", "i", ":", "]", ")", "norm", "=", "val", "*", "1.0", "/", "data_sum", "w", "=", "max", "(", "int", "(", "round", "(", "available", "*", "norm", ")", ")", ",", "1", ")", "res", ".", "append", "(", "w", ")", "available", "-=", "w", "return", "res" ]
returns the given data distributed in the space ensuring it's full pixels and with the given gap. this will result in minor sub-pixel inaccuracies. XXX - figure out where to place these guys as they are quite useful
[ "returns", "the", "given", "data", "distributed", "in", "the", "space", "ensuring", "it", "s", "full", "pixels", "and", "with", "the", "given", "gap", ".", "this", "will", "result", "in", "minor", "sub", "-", "pixel", "inaccuracies", ".", "XXX", "-", "figure", "out", "where", "to", "place", "these", "guys", "as", "they", "are", "quite", "useful" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L187-L205
232,036
projecthamster/hamster
src/hamster/lib/graphics.py
ColorUtils.gdk
def gdk(self, color): """returns gdk.Color object of the given color""" c = self.parse(color) return gdk.Color.from_floats(c)
python
def gdk(self, color): """returns gdk.Color object of the given color""" c = self.parse(color) return gdk.Color.from_floats(c)
[ "def", "gdk", "(", "self", ",", "color", ")", ":", "c", "=", "self", ".", "parse", "(", "color", ")", "return", "gdk", ".", "Color", ".", "from_floats", "(", "c", ")" ]
returns gdk.Color object of the given color
[ "returns", "gdk", ".", "Color", "object", "of", "the", "given", "color" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L95-L98
232,037
projecthamster/hamster
src/hamster/lib/graphics.py
ColorUtils.contrast
def contrast(self, color, step): """if color is dark, will return a lighter one, otherwise darker""" hls = colorsys.rgb_to_hls(*self.rgb(color)) if self.is_light(color): return colorsys.hls_to_rgb(hls[0], hls[1] - step, hls[2]) else: return colorsys.hls_to_rgb(hls[0], hls[1] + step, hls[2])
python
def contrast(self, color, step): """if color is dark, will return a lighter one, otherwise darker""" hls = colorsys.rgb_to_hls(*self.rgb(color)) if self.is_light(color): return colorsys.hls_to_rgb(hls[0], hls[1] - step, hls[2]) else: return colorsys.hls_to_rgb(hls[0], hls[1] + step, hls[2])
[ "def", "contrast", "(", "self", ",", "color", ",", "step", ")", ":", "hls", "=", "colorsys", ".", "rgb_to_hls", "(", "*", "self", ".", "rgb", "(", "color", ")", ")", "if", "self", ".", "is_light", "(", "color", ")", ":", "return", "colorsys", ".", "hls_to_rgb", "(", "hls", "[", "0", "]", ",", "hls", "[", "1", "]", "-", "step", ",", "hls", "[", "2", "]", ")", "else", ":", "return", "colorsys", ".", "hls_to_rgb", "(", "hls", "[", "0", "]", ",", "hls", "[", "1", "]", "+", "step", ",", "hls", "[", "2", "]", ")" ]
if color is dark, will return a lighter one, otherwise darker
[ "if", "color", "is", "dark", "will", "return", "a", "lighter", "one", "otherwise", "darker" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L121-L127
232,038
projecthamster/hamster
src/hamster/lib/graphics.py
ColorUtils.mix
def mix(self, ca, cb, xb): """Mix colors. Args: ca (gdk.RGBA): first color cb (gdk.RGBA): second color xb (float): between 0.0 and 1.0 Return: gdk.RGBA: linear interpolation between ca and cb, 0 or 1 return the unaltered 1st or 2nd color respectively, as in CSS. """ r = (1 - xb) * ca.red + xb * cb.red g = (1 - xb) * ca.green + xb * cb.green b = (1 - xb) * ca.blue + xb * cb.blue a = (1 - xb) * ca.alpha + xb * cb.alpha return gdk.RGBA(red=r, green=g, blue=b, alpha=a)
python
def mix(self, ca, cb, xb): """Mix colors. Args: ca (gdk.RGBA): first color cb (gdk.RGBA): second color xb (float): between 0.0 and 1.0 Return: gdk.RGBA: linear interpolation between ca and cb, 0 or 1 return the unaltered 1st or 2nd color respectively, as in CSS. """ r = (1 - xb) * ca.red + xb * cb.red g = (1 - xb) * ca.green + xb * cb.green b = (1 - xb) * ca.blue + xb * cb.blue a = (1 - xb) * ca.alpha + xb * cb.alpha return gdk.RGBA(red=r, green=g, blue=b, alpha=a)
[ "def", "mix", "(", "self", ",", "ca", ",", "cb", ",", "xb", ")", ":", "r", "=", "(", "1", "-", "xb", ")", "*", "ca", ".", "red", "+", "xb", "*", "cb", ".", "red", "g", "=", "(", "1", "-", "xb", ")", "*", "ca", ".", "green", "+", "xb", "*", "cb", ".", "green", "b", "=", "(", "1", "-", "xb", ")", "*", "ca", ".", "blue", "+", "xb", "*", "cb", ".", "blue", "a", "=", "(", "1", "-", "xb", ")", "*", "ca", ".", "alpha", "+", "xb", "*", "cb", ".", "alpha", "return", "gdk", ".", "RGBA", "(", "red", "=", "r", ",", "green", "=", "g", ",", "blue", "=", "b", ",", "alpha", "=", "a", ")" ]
Mix colors. Args: ca (gdk.RGBA): first color cb (gdk.RGBA): second color xb (float): between 0.0 and 1.0 Return: gdk.RGBA: linear interpolation between ca and cb, 0 or 1 return the unaltered 1st or 2nd color respectively, as in CSS.
[ "Mix", "colors", "." ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L130-L147
232,039
projecthamster/hamster
src/hamster/lib/graphics.py
Graphics.set_line_style
def set_line_style(self, width = None, dash = None, dash_offset = 0): """change width and dash of a line""" if width is not None: self._add_instruction("set_line_width", width) if dash is not None: self._add_instruction("set_dash", dash, dash_offset)
python
def set_line_style(self, width = None, dash = None, dash_offset = 0): """change width and dash of a line""" if width is not None: self._add_instruction("set_line_width", width) if dash is not None: self._add_instruction("set_dash", dash, dash_offset)
[ "def", "set_line_style", "(", "self", ",", "width", "=", "None", ",", "dash", "=", "None", ",", "dash_offset", "=", "0", ")", ":", "if", "width", "is", "not", "None", ":", "self", ".", "_add_instruction", "(", "\"set_line_width\"", ",", "width", ")", "if", "dash", "is", "not", "None", ":", "self", ".", "_add_instruction", "(", "\"set_dash\"", ",", "dash", ",", "dash_offset", ")" ]
change width and dash of a line
[ "change", "width", "and", "dash", "of", "a", "line" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L328-L334
232,040
projecthamster/hamster
src/hamster/lib/graphics.py
Graphics._set_color
def _set_color(self, context, r, g, b, a): """the alpha has to changed based on the parent, so that happens at the time of drawing""" if a < 1: context.set_source_rgba(r, g, b, a) else: context.set_source_rgb(r, g, b)
python
def _set_color(self, context, r, g, b, a): """the alpha has to changed based on the parent, so that happens at the time of drawing""" if a < 1: context.set_source_rgba(r, g, b, a) else: context.set_source_rgb(r, g, b)
[ "def", "_set_color", "(", "self", ",", "context", ",", "r", ",", "g", ",", "b", ",", "a", ")", ":", "if", "a", "<", "1", ":", "context", ".", "set_source_rgba", "(", "r", ",", "g", ",", "b", ",", "a", ")", "else", ":", "context", ".", "set_source_rgb", "(", "r", ",", "g", ",", "b", ")" ]
the alpha has to changed based on the parent, so that happens at the time of drawing
[ "the", "alpha", "has", "to", "changed", "based", "on", "the", "parent", "so", "that", "happens", "at", "the", "time", "of", "drawing" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L338-L344
232,041
projecthamster/hamster
src/hamster/lib/graphics.py
Graphics.arc
def arc(self, x, y, radius, start_angle, end_angle): """draw arc going counter-clockwise from start_angle to end_angle""" self._add_instruction("arc", x, y, radius, start_angle, end_angle)
python
def arc(self, x, y, radius, start_angle, end_angle): """draw arc going counter-clockwise from start_angle to end_angle""" self._add_instruction("arc", x, y, radius, start_angle, end_angle)
[ "def", "arc", "(", "self", ",", "x", ",", "y", ",", "radius", ",", "start_angle", ",", "end_angle", ")", ":", "self", ".", "_add_instruction", "(", "\"arc\"", ",", "x", ",", "y", ",", "radius", ",", "start_angle", ",", "end_angle", ")" ]
draw arc going counter-clockwise from start_angle to end_angle
[ "draw", "arc", "going", "counter", "-", "clockwise", "from", "start_angle", "to", "end_angle" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L360-L362
232,042
projecthamster/hamster
src/hamster/lib/graphics.py
Graphics.ellipse
def ellipse(self, x, y, width, height, edges = None): """draw 'perfect' ellipse, opposed to squashed circle. works also for equilateral polygons""" # the automatic edge case is somewhat arbitrary steps = edges or max((32, width, height)) / 2 angle = 0 step = math.pi * 2 / steps points = [] while angle < math.pi * 2: points.append((width / 2.0 * math.cos(angle), height / 2.0 * math.sin(angle))) angle += step min_x = min((point[0] for point in points)) min_y = min((point[1] for point in points)) self.move_to(points[0][0] - min_x + x, points[0][1] - min_y + y) for p_x, p_y in points: self.line_to(p_x - min_x + x, p_y - min_y + y) self.line_to(points[0][0] - min_x + x, points[0][1] - min_y + y)
python
def ellipse(self, x, y, width, height, edges = None): """draw 'perfect' ellipse, opposed to squashed circle. works also for equilateral polygons""" # the automatic edge case is somewhat arbitrary steps = edges or max((32, width, height)) / 2 angle = 0 step = math.pi * 2 / steps points = [] while angle < math.pi * 2: points.append((width / 2.0 * math.cos(angle), height / 2.0 * math.sin(angle))) angle += step min_x = min((point[0] for point in points)) min_y = min((point[1] for point in points)) self.move_to(points[0][0] - min_x + x, points[0][1] - min_y + y) for p_x, p_y in points: self.line_to(p_x - min_x + x, p_y - min_y + y) self.line_to(points[0][0] - min_x + x, points[0][1] - min_y + y)
[ "def", "ellipse", "(", "self", ",", "x", ",", "y", ",", "width", ",", "height", ",", "edges", "=", "None", ")", ":", "# the automatic edge case is somewhat arbitrary", "steps", "=", "edges", "or", "max", "(", "(", "32", ",", "width", ",", "height", ")", ")", "/", "2", "angle", "=", "0", "step", "=", "math", ".", "pi", "*", "2", "/", "steps", "points", "=", "[", "]", "while", "angle", "<", "math", ".", "pi", "*", "2", ":", "points", ".", "append", "(", "(", "width", "/", "2.0", "*", "math", ".", "cos", "(", "angle", ")", ",", "height", "/", "2.0", "*", "math", ".", "sin", "(", "angle", ")", ")", ")", "angle", "+=", "step", "min_x", "=", "min", "(", "(", "point", "[", "0", "]", "for", "point", "in", "points", ")", ")", "min_y", "=", "min", "(", "(", "point", "[", "1", "]", "for", "point", "in", "points", ")", ")", "self", ".", "move_to", "(", "points", "[", "0", "]", "[", "0", "]", "-", "min_x", "+", "x", ",", "points", "[", "0", "]", "[", "1", "]", "-", "min_y", "+", "y", ")", "for", "p_x", ",", "p_y", "in", "points", ":", "self", ".", "line_to", "(", "p_x", "-", "min_x", "+", "x", ",", "p_y", "-", "min_y", "+", "y", ")", "self", ".", "line_to", "(", "points", "[", "0", "]", "[", "0", "]", "-", "min_x", "+", "x", ",", "points", "[", "0", "]", "[", "1", "]", "-", "min_y", "+", "y", ")" ]
draw 'perfect' ellipse, opposed to squashed circle. works also for equilateral polygons
[ "draw", "perfect", "ellipse", "opposed", "to", "squashed", "circle", ".", "works", "also", "for", "equilateral", "polygons" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L368-L388
232,043
projecthamster/hamster
src/hamster/lib/graphics.py
Graphics.arc_negative
def arc_negative(self, x, y, radius, start_angle, end_angle): """draw arc going clockwise from start_angle to end_angle""" self._add_instruction("arc_negative", x, y, radius, start_angle, end_angle)
python
def arc_negative(self, x, y, radius, start_angle, end_angle): """draw arc going clockwise from start_angle to end_angle""" self._add_instruction("arc_negative", x, y, radius, start_angle, end_angle)
[ "def", "arc_negative", "(", "self", ",", "x", ",", "y", ",", "radius", ",", "start_angle", ",", "end_angle", ")", ":", "self", ".", "_add_instruction", "(", "\"arc_negative\"", ",", "x", ",", "y", ",", "radius", ",", "start_angle", ",", "end_angle", ")" ]
draw arc going clockwise from start_angle to end_angle
[ "draw", "arc", "going", "clockwise", "from", "start_angle", "to", "end_angle" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L390-L392
232,044
projecthamster/hamster
src/hamster/lib/graphics.py
Graphics.rectangle
def rectangle(self, x, y, width, height, corner_radius = 0): """draw a rectangle. if corner_radius is specified, will draw rounded corners. corner_radius can be either a number or a tuple of four items to specify individually each corner, starting from top-left and going clockwise""" if corner_radius <= 0: self._add_instruction("rectangle", x, y, width, height) return # convert into 4 border and make sure that w + h are larger than 2 * corner_radius if isinstance(corner_radius, (int, float)): corner_radius = [corner_radius] * 4 corner_radius = [min(r, min(width, height) / 2) for r in corner_radius] x2, y2 = x + width, y + height self._rounded_rectangle(x, y, x2, y2, corner_radius)
python
def rectangle(self, x, y, width, height, corner_radius = 0): """draw a rectangle. if corner_radius is specified, will draw rounded corners. corner_radius can be either a number or a tuple of four items to specify individually each corner, starting from top-left and going clockwise""" if corner_radius <= 0: self._add_instruction("rectangle", x, y, width, height) return # convert into 4 border and make sure that w + h are larger than 2 * corner_radius if isinstance(corner_radius, (int, float)): corner_radius = [corner_radius] * 4 corner_radius = [min(r, min(width, height) / 2) for r in corner_radius] x2, y2 = x + width, y + height self._rounded_rectangle(x, y, x2, y2, corner_radius)
[ "def", "rectangle", "(", "self", ",", "x", ",", "y", ",", "width", ",", "height", ",", "corner_radius", "=", "0", ")", ":", "if", "corner_radius", "<=", "0", ":", "self", ".", "_add_instruction", "(", "\"rectangle\"", ",", "x", ",", "y", ",", "width", ",", "height", ")", "return", "# convert into 4 border and make sure that w + h are larger than 2 * corner_radius", "if", "isinstance", "(", "corner_radius", ",", "(", "int", ",", "float", ")", ")", ":", "corner_radius", "=", "[", "corner_radius", "]", "*", "4", "corner_radius", "=", "[", "min", "(", "r", ",", "min", "(", "width", ",", "height", ")", "/", "2", ")", "for", "r", "in", "corner_radius", "]", "x2", ",", "y2", "=", "x", "+", "width", ",", "y", "+", "height", "self", ".", "_rounded_rectangle", "(", "x", ",", "y", ",", "x2", ",", "y2", ",", "corner_radius", ")" ]
draw a rectangle. if corner_radius is specified, will draw rounded corners. corner_radius can be either a number or a tuple of four items to specify individually each corner, starting from top-left and going clockwise
[ "draw", "a", "rectangle", ".", "if", "corner_radius", "is", "specified", "will", "draw", "rounded", "corners", ".", "corner_radius", "can", "be", "either", "a", "number", "or", "a", "tuple", "of", "four", "items", "to", "specify", "individually", "each", "corner", "starting", "from", "top", "-", "left", "and", "going", "clockwise" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L400-L415
232,045
projecthamster/hamster
src/hamster/lib/graphics.py
Graphics.fill_area
def fill_area(self, x, y, width, height, color, opacity = 1): """fill rectangular area with specified color""" self.save_context() self.rectangle(x, y, width, height) self._add_instruction("clip") self.rectangle(x, y, width, height) self.fill(color, opacity) self.restore_context()
python
def fill_area(self, x, y, width, height, color, opacity = 1): """fill rectangular area with specified color""" self.save_context() self.rectangle(x, y, width, height) self._add_instruction("clip") self.rectangle(x, y, width, height) self.fill(color, opacity) self.restore_context()
[ "def", "fill_area", "(", "self", ",", "x", ",", "y", ",", "width", ",", "height", ",", "color", ",", "opacity", "=", "1", ")", ":", "self", ".", "save_context", "(", ")", "self", ".", "rectangle", "(", "x", ",", "y", ",", "width", ",", "height", ")", "self", ".", "_add_instruction", "(", "\"clip\"", ")", "self", ".", "rectangle", "(", "x", ",", "y", ",", "width", ",", "height", ")", "self", ".", "fill", "(", "color", ",", "opacity", ")", "self", ".", "restore_context", "(", ")" ]
fill rectangular area with specified color
[ "fill", "rectangular", "area", "with", "specified", "color" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L444-L451
232,046
projecthamster/hamster
src/hamster/lib/graphics.py
Graphics.fill_stroke
def fill_stroke(self, fill = None, stroke = None, opacity = 1, line_width = None): """fill and stroke the drawn area in one go""" if line_width: self.set_line_style(line_width) if fill and stroke: self.fill_preserve(fill, opacity) elif fill: self.fill(fill, opacity) if stroke: self.stroke(stroke)
python
def fill_stroke(self, fill = None, stroke = None, opacity = 1, line_width = None): """fill and stroke the drawn area in one go""" if line_width: self.set_line_style(line_width) if fill and stroke: self.fill_preserve(fill, opacity) elif fill: self.fill(fill, opacity) if stroke: self.stroke(stroke)
[ "def", "fill_stroke", "(", "self", ",", "fill", "=", "None", ",", "stroke", "=", "None", ",", "opacity", "=", "1", ",", "line_width", "=", "None", ")", ":", "if", "line_width", ":", "self", ".", "set_line_style", "(", "line_width", ")", "if", "fill", "and", "stroke", ":", "self", ".", "fill_preserve", "(", "fill", ",", "opacity", ")", "elif", "fill", ":", "self", ".", "fill", "(", "fill", ",", "opacity", ")", "if", "stroke", ":", "self", ".", "stroke", "(", "stroke", ")" ]
fill and stroke the drawn area in one go
[ "fill", "and", "stroke", "the", "drawn", "area", "in", "one", "go" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L453-L463
232,047
projecthamster/hamster
src/hamster/lib/graphics.py
Graphics.create_layout
def create_layout(self, size = None): """utility function to create layout with the default font. Size and alignment parameters are shortcuts to according functions of the pango.Layout""" if not self.context: # TODO - this is rather sloppy as far as exception goes # should explain better raise Exception("Can not create layout without existing context!") layout = pangocairo.create_layout(self.context) font_desc = pango.FontDescription(_font_desc) if size: font_desc.set_absolute_size(size * pango.SCALE) layout.set_font_description(font_desc) return layout
python
def create_layout(self, size = None): """utility function to create layout with the default font. Size and alignment parameters are shortcuts to according functions of the pango.Layout""" if not self.context: # TODO - this is rather sloppy as far as exception goes # should explain better raise Exception("Can not create layout without existing context!") layout = pangocairo.create_layout(self.context) font_desc = pango.FontDescription(_font_desc) if size: font_desc.set_absolute_size(size * pango.SCALE) layout.set_font_description(font_desc) return layout
[ "def", "create_layout", "(", "self", ",", "size", "=", "None", ")", ":", "if", "not", "self", ".", "context", ":", "# TODO - this is rather sloppy as far as exception goes", "# should explain better", "raise", "Exception", "(", "\"Can not create layout without existing context!\"", ")", "layout", "=", "pangocairo", ".", "create_layout", "(", "self", ".", "context", ")", "font_desc", "=", "pango", ".", "FontDescription", "(", "_font_desc", ")", "if", "size", ":", "font_desc", ".", "set_absolute_size", "(", "size", "*", "pango", ".", "SCALE", ")", "layout", ".", "set_font_description", "(", "font_desc", ")", "return", "layout" ]
utility function to create layout with the default font. Size and alignment parameters are shortcuts to according functions of the pango.Layout
[ "utility", "function", "to", "create", "layout", "with", "the", "default", "font", ".", "Size", "and", "alignment", "parameters", "are", "shortcuts", "to", "according", "functions", "of", "the", "pango", ".", "Layout" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L465-L479
232,048
projecthamster/hamster
src/hamster/lib/graphics.py
Graphics.show_label
def show_label(self, text, size = None, color = None, font_desc = None): """display text. unless font_desc is provided, will use system's default font""" font_desc = pango.FontDescription(font_desc or _font_desc) if color: self.set_color(color) if size: font_desc.set_absolute_size(size * pango.SCALE) self.show_layout(text, font_desc)
python
def show_label(self, text, size = None, color = None, font_desc = None): """display text. unless font_desc is provided, will use system's default font""" font_desc = pango.FontDescription(font_desc or _font_desc) if color: self.set_color(color) if size: font_desc.set_absolute_size(size * pango.SCALE) self.show_layout(text, font_desc)
[ "def", "show_label", "(", "self", ",", "text", ",", "size", "=", "None", ",", "color", "=", "None", ",", "font_desc", "=", "None", ")", ":", "font_desc", "=", "pango", ".", "FontDescription", "(", "font_desc", "or", "_font_desc", ")", "if", "color", ":", "self", ".", "set_color", "(", "color", ")", "if", "size", ":", "font_desc", ".", "set_absolute_size", "(", "size", "*", "pango", ".", "SCALE", ")", "self", ".", "show_layout", "(", "text", ",", "font_desc", ")" ]
display text. unless font_desc is provided, will use system's default font
[ "display", "text", ".", "unless", "font_desc", "is", "provided", "will", "use", "system", "s", "default", "font" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L481-L486
232,049
projecthamster/hamster
src/hamster/lib/graphics.py
Graphics._draw
def _draw(self, context, opacity): """draw accumulated instructions in context""" # if we have been moved around, we should update bounds fresh_draw = len(self.__new_instructions or []) > 0 if fresh_draw: #new stuff! self.paths = [] self.__instruction_cache = self.__new_instructions self.__new_instructions = [] else: if not self.__instruction_cache: return for instruction, args in self.__instruction_cache: if fresh_draw: if instruction in ("new_path", "stroke", "fill", "clip"): self.paths.append((instruction, "path", context.copy_path())) elif instruction in ("save", "restore", "translate", "scale", "rotate"): self.paths.append((instruction, "transform", args)) if instruction == "set_color": self._set_color(context, args[0], args[1], args[2], args[3] * opacity) elif instruction == "show_layout": self._show_layout(context, *args) elif opacity < 1 and instruction == "paint": context.paint_with_alpha(opacity) else: getattr(context, instruction)(*args)
python
def _draw(self, context, opacity): """draw accumulated instructions in context""" # if we have been moved around, we should update bounds fresh_draw = len(self.__new_instructions or []) > 0 if fresh_draw: #new stuff! self.paths = [] self.__instruction_cache = self.__new_instructions self.__new_instructions = [] else: if not self.__instruction_cache: return for instruction, args in self.__instruction_cache: if fresh_draw: if instruction in ("new_path", "stroke", "fill", "clip"): self.paths.append((instruction, "path", context.copy_path())) elif instruction in ("save", "restore", "translate", "scale", "rotate"): self.paths.append((instruction, "transform", args)) if instruction == "set_color": self._set_color(context, args[0], args[1], args[2], args[3] * opacity) elif instruction == "show_layout": self._show_layout(context, *args) elif opacity < 1 and instruction == "paint": context.paint_with_alpha(opacity) else: getattr(context, instruction)(*args)
[ "def", "_draw", "(", "self", ",", "context", ",", "opacity", ")", ":", "# if we have been moved around, we should update bounds", "fresh_draw", "=", "len", "(", "self", ".", "__new_instructions", "or", "[", "]", ")", ">", "0", "if", "fresh_draw", ":", "#new stuff!", "self", ".", "paths", "=", "[", "]", "self", ".", "__instruction_cache", "=", "self", ".", "__new_instructions", "self", ".", "__new_instructions", "=", "[", "]", "else", ":", "if", "not", "self", ".", "__instruction_cache", ":", "return", "for", "instruction", ",", "args", "in", "self", ".", "__instruction_cache", ":", "if", "fresh_draw", ":", "if", "instruction", "in", "(", "\"new_path\"", ",", "\"stroke\"", ",", "\"fill\"", ",", "\"clip\"", ")", ":", "self", ".", "paths", ".", "append", "(", "(", "instruction", ",", "\"path\"", ",", "context", ".", "copy_path", "(", ")", ")", ")", "elif", "instruction", "in", "(", "\"save\"", ",", "\"restore\"", ",", "\"translate\"", ",", "\"scale\"", ",", "\"rotate\"", ")", ":", "self", ".", "paths", ".", "append", "(", "(", "instruction", ",", "\"transform\"", ",", "args", ")", ")", "if", "instruction", "==", "\"set_color\"", ":", "self", ".", "_set_color", "(", "context", ",", "args", "[", "0", "]", ",", "args", "[", "1", "]", ",", "args", "[", "2", "]", ",", "args", "[", "3", "]", "*", "opacity", ")", "elif", "instruction", "==", "\"show_layout\"", ":", "self", ".", "_show_layout", "(", "context", ",", "*", "args", ")", "elif", "opacity", "<", "1", "and", "instruction", "==", "\"paint\"", ":", "context", ".", "paint_with_alpha", "(", "opacity", ")", "else", ":", "getattr", "(", "context", ",", "instruction", ")", "(", "*", "args", ")" ]
draw accumulated instructions in context
[ "draw", "accumulated", "instructions", "in", "context" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L538-L566
232,050
projecthamster/hamster
src/hamster/lib/graphics.py
Parent.find
def find(self, id): """breadth-first sprite search by ID""" for sprite in self.sprites: if sprite.id == id: return sprite for sprite in self.sprites: found = sprite.find(id) if found: return found
python
def find(self, id): """breadth-first sprite search by ID""" for sprite in self.sprites: if sprite.id == id: return sprite for sprite in self.sprites: found = sprite.find(id) if found: return found
[ "def", "find", "(", "self", ",", "id", ")", ":", "for", "sprite", "in", "self", ".", "sprites", ":", "if", "sprite", ".", "id", "==", "id", ":", "return", "sprite", "for", "sprite", "in", "self", ".", "sprites", ":", "found", "=", "sprite", ".", "find", "(", "id", ")", "if", "found", ":", "return", "found" ]
breadth-first sprite search by ID
[ "breadth", "-", "first", "sprite", "search", "by", "ID" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L674-L683
232,051
projecthamster/hamster
src/hamster/lib/graphics.py
Parent.traverse
def traverse(self, attr_name = None, attr_value = None): """traverse the whole sprite tree and return child sprites which have the attribute and it's set to the specified value. If falue is None, will return all sprites that have the attribute """ for sprite in self.sprites: if (attr_name is None) or \ (attr_value is None and hasattr(sprite, attr_name)) or \ (attr_value is not None and getattr(sprite, attr_name, None) == attr_value): yield sprite for child in sprite.traverse(attr_name, attr_value): yield child
python
def traverse(self, attr_name = None, attr_value = None): """traverse the whole sprite tree and return child sprites which have the attribute and it's set to the specified value. If falue is None, will return all sprites that have the attribute """ for sprite in self.sprites: if (attr_name is None) or \ (attr_value is None and hasattr(sprite, attr_name)) or \ (attr_value is not None and getattr(sprite, attr_name, None) == attr_value): yield sprite for child in sprite.traverse(attr_name, attr_value): yield child
[ "def", "traverse", "(", "self", ",", "attr_name", "=", "None", ",", "attr_value", "=", "None", ")", ":", "for", "sprite", "in", "self", ".", "sprites", ":", "if", "(", "attr_name", "is", "None", ")", "or", "(", "attr_value", "is", "None", "and", "hasattr", "(", "sprite", ",", "attr_name", ")", ")", "or", "(", "attr_value", "is", "not", "None", "and", "getattr", "(", "sprite", ",", "attr_name", ",", "None", ")", "==", "attr_value", ")", ":", "yield", "sprite", "for", "child", "in", "sprite", ".", "traverse", "(", "attr_name", ",", "attr_value", ")", ":", "yield", "child" ]
traverse the whole sprite tree and return child sprites which have the attribute and it's set to the specified value. If falue is None, will return all sprites that have the attribute
[ "traverse", "the", "whole", "sprite", "tree", "and", "return", "child", "sprites", "which", "have", "the", "attribute", "and", "it", "s", "set", "to", "the", "specified", "value", ".", "If", "falue", "is", "None", "will", "return", "all", "sprites", "that", "have", "the", "attribute" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L688-L700
232,052
projecthamster/hamster
src/hamster/lib/graphics.py
Parent.log
def log(self, *lines): """will print out the lines in console if debug is enabled for the specific sprite""" if getattr(self, "debug", False): print(dt.datetime.now().time(), end=' ') for line in lines: print(line, end=' ') print()
python
def log(self, *lines): """will print out the lines in console if debug is enabled for the specific sprite""" if getattr(self, "debug", False): print(dt.datetime.now().time(), end=' ') for line in lines: print(line, end=' ') print()
[ "def", "log", "(", "self", ",", "*", "lines", ")", ":", "if", "getattr", "(", "self", ",", "\"debug\"", ",", "False", ")", ":", "print", "(", "dt", ".", "datetime", ".", "now", "(", ")", ".", "time", "(", ")", ",", "end", "=", "' '", ")", "for", "line", "in", "lines", ":", "print", "(", "line", ",", "end", "=", "' '", ")", "print", "(", ")" ]
will print out the lines in console if debug is enabled for the specific sprite
[ "will", "print", "out", "the", "lines", "in", "console", "if", "debug", "is", "enabled", "for", "the", "specific", "sprite" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L702-L709
232,053
projecthamster/hamster
src/hamster/lib/graphics.py
Parent._add
def _add(self, sprite, index = None): """add one sprite at a time. used by add_child. split them up so that it would be possible specify the index externally""" if sprite == self: raise Exception("trying to add sprite to itself") if sprite.parent: sprite.x, sprite.y = self.from_scene_coords(*sprite.to_scene_coords()) sprite.parent.remove_child(sprite) if index is not None: self.sprites.insert(index, sprite) else: self.sprites.append(sprite) sprite.parent = self
python
def _add(self, sprite, index = None): """add one sprite at a time. used by add_child. split them up so that it would be possible specify the index externally""" if sprite == self: raise Exception("trying to add sprite to itself") if sprite.parent: sprite.x, sprite.y = self.from_scene_coords(*sprite.to_scene_coords()) sprite.parent.remove_child(sprite) if index is not None: self.sprites.insert(index, sprite) else: self.sprites.append(sprite) sprite.parent = self
[ "def", "_add", "(", "self", ",", "sprite", ",", "index", "=", "None", ")", ":", "if", "sprite", "==", "self", ":", "raise", "Exception", "(", "\"trying to add sprite to itself\"", ")", "if", "sprite", ".", "parent", ":", "sprite", ".", "x", ",", "sprite", ".", "y", "=", "self", ".", "from_scene_coords", "(", "*", "sprite", ".", "to_scene_coords", "(", ")", ")", "sprite", ".", "parent", ".", "remove_child", "(", "sprite", ")", "if", "index", "is", "not", "None", ":", "self", ".", "sprites", ".", "insert", "(", "index", ",", "sprite", ")", "else", ":", "self", ".", "sprites", ".", "append", "(", "sprite", ")", "sprite", ".", "parent", "=", "self" ]
add one sprite at a time. used by add_child. split them up so that it would be possible specify the index externally
[ "add", "one", "sprite", "at", "a", "time", ".", "used", "by", "add_child", ".", "split", "them", "up", "so", "that", "it", "would", "be", "possible", "specify", "the", "index", "externally" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L711-L725
232,054
projecthamster/hamster
src/hamster/lib/graphics.py
Parent._sort
def _sort(self): """sort sprites by z_order""" self.__dict__['_z_ordered_sprites'] = sorted(self.sprites, key=lambda sprite:sprite.z_order)
python
def _sort(self): """sort sprites by z_order""" self.__dict__['_z_ordered_sprites'] = sorted(self.sprites, key=lambda sprite:sprite.z_order)
[ "def", "_sort", "(", "self", ")", ":", "self", ".", "__dict__", "[", "'_z_ordered_sprites'", "]", "=", "sorted", "(", "self", ".", "sprites", ",", "key", "=", "lambda", "sprite", ":", "sprite", ".", "z_order", ")" ]
sort sprites by z_order
[ "sort", "sprites", "by", "z_order" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L728-L730
232,055
projecthamster/hamster
src/hamster/lib/graphics.py
Parent.add_child
def add_child(self, *sprites): """Add child sprite. Child will be nested within parent""" for sprite in sprites: self._add(sprite) self._sort() self.redraw()
python
def add_child(self, *sprites): """Add child sprite. Child will be nested within parent""" for sprite in sprites: self._add(sprite) self._sort() self.redraw()
[ "def", "add_child", "(", "self", ",", "*", "sprites", ")", ":", "for", "sprite", "in", "sprites", ":", "self", ".", "_add", "(", "sprite", ")", "self", ".", "_sort", "(", ")", "self", ".", "redraw", "(", ")" ]
Add child sprite. Child will be nested within parent
[ "Add", "child", "sprite", ".", "Child", "will", "be", "nested", "within", "parent" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L732-L737
232,056
projecthamster/hamster
src/hamster/lib/graphics.py
Parent.all_child_sprites
def all_child_sprites(self): """returns all child and grandchild sprites in a flat list""" for sprite in self.sprites: for child_sprite in sprite.all_child_sprites(): yield child_sprite yield sprite
python
def all_child_sprites(self): """returns all child and grandchild sprites in a flat list""" for sprite in self.sprites: for child_sprite in sprite.all_child_sprites(): yield child_sprite yield sprite
[ "def", "all_child_sprites", "(", "self", ")", ":", "for", "sprite", "in", "self", ".", "sprites", ":", "for", "child_sprite", "in", "sprite", ".", "all_child_sprites", "(", ")", ":", "yield", "child_sprite", "yield", "sprite" ]
returns all child and grandchild sprites in a flat list
[ "returns", "all", "child", "and", "grandchild", "sprites", "in", "a", "flat", "list" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L774-L779
232,057
projecthamster/hamster
src/hamster/lib/graphics.py
Parent.disconnect_child
def disconnect_child(self, sprite, *handlers): """disconnects from child event. if handler is not specified, will disconnect from all the child sprite events""" handlers = handlers or self._child_handlers.get(sprite, []) for handler in list(handlers): if sprite.handler_is_connected(handler): sprite.disconnect(handler) if handler in self._child_handlers.get(sprite, []): self._child_handlers[sprite].remove(handler) if not self._child_handlers[sprite]: del self._child_handlers[sprite]
python
def disconnect_child(self, sprite, *handlers): """disconnects from child event. if handler is not specified, will disconnect from all the child sprite events""" handlers = handlers or self._child_handlers.get(sprite, []) for handler in list(handlers): if sprite.handler_is_connected(handler): sprite.disconnect(handler) if handler in self._child_handlers.get(sprite, []): self._child_handlers[sprite].remove(handler) if not self._child_handlers[sprite]: del self._child_handlers[sprite]
[ "def", "disconnect_child", "(", "self", ",", "sprite", ",", "*", "handlers", ")", ":", "handlers", "=", "handlers", "or", "self", ".", "_child_handlers", ".", "get", "(", "sprite", ",", "[", "]", ")", "for", "handler", "in", "list", "(", "handlers", ")", ":", "if", "sprite", ".", "handler_is_connected", "(", "handler", ")", ":", "sprite", ".", "disconnect", "(", "handler", ")", "if", "handler", "in", "self", ".", "_child_handlers", ".", "get", "(", "sprite", ",", "[", "]", ")", ":", "self", ".", "_child_handlers", "[", "sprite", "]", ".", "remove", "(", "handler", ")", "if", "not", "self", ".", "_child_handlers", "[", "sprite", "]", ":", "del", "self", ".", "_child_handlers", "[", "sprite", "]" ]
disconnects from child event. if handler is not specified, will disconnect from all the child sprite events
[ "disconnects", "from", "child", "event", ".", "if", "handler", "is", "not", "specified", "will", "disconnect", "from", "all", "the", "child", "sprite", "events" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L807-L818
232,058
projecthamster/hamster
src/hamster/lib/graphics.py
Sprite._get_mouse_cursor
def _get_mouse_cursor(self): """Determine mouse cursor. By default look for self.mouse_cursor is defined and take that. Otherwise use gdk.CursorType.FLEUR for draggable sprites and gdk.CursorType.HAND2 for interactive sprites. Defaults to scenes cursor. """ if self.mouse_cursor is not None: return self.mouse_cursor elif self.interactive and self.draggable: return gdk.CursorType.FLEUR elif self.interactive: return gdk.CursorType.HAND2
python
def _get_mouse_cursor(self): """Determine mouse cursor. By default look for self.mouse_cursor is defined and take that. Otherwise use gdk.CursorType.FLEUR for draggable sprites and gdk.CursorType.HAND2 for interactive sprites. Defaults to scenes cursor. """ if self.mouse_cursor is not None: return self.mouse_cursor elif self.interactive and self.draggable: return gdk.CursorType.FLEUR elif self.interactive: return gdk.CursorType.HAND2
[ "def", "_get_mouse_cursor", "(", "self", ")", ":", "if", "self", ".", "mouse_cursor", "is", "not", "None", ":", "return", "self", ".", "mouse_cursor", "elif", "self", ".", "interactive", "and", "self", ".", "draggable", ":", "return", "gdk", ".", "CursorType", ".", "FLEUR", "elif", "self", ".", "interactive", ":", "return", "gdk", ".", "CursorType", ".", "HAND2" ]
Determine mouse cursor. By default look for self.mouse_cursor is defined and take that. Otherwise use gdk.CursorType.FLEUR for draggable sprites and gdk.CursorType.HAND2 for interactive sprites. Defaults to scenes cursor.
[ "Determine", "mouse", "cursor", ".", "By", "default", "look", "for", "self", ".", "mouse_cursor", "is", "defined", "and", "take", "that", ".", "Otherwise", "use", "gdk", ".", "CursorType", ".", "FLEUR", "for", "draggable", "sprites", "and", "gdk", ".", "CursorType", ".", "HAND2", "for", "interactive", "sprites", ".", "Defaults", "to", "scenes", "cursor", "." ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1026-L1037
232,059
projecthamster/hamster
src/hamster/lib/graphics.py
Sprite.bring_to_front
def bring_to_front(self): """adjusts sprite's z-order so that the sprite is on top of it's siblings""" if not self.parent: return self.z_order = self.parent._z_ordered_sprites[-1].z_order + 1
python
def bring_to_front(self): """adjusts sprite's z-order so that the sprite is on top of it's siblings""" if not self.parent: return self.z_order = self.parent._z_ordered_sprites[-1].z_order + 1
[ "def", "bring_to_front", "(", "self", ")", ":", "if", "not", "self", ".", "parent", ":", "return", "self", ".", "z_order", "=", "self", ".", "parent", ".", "_z_ordered_sprites", "[", "-", "1", "]", ".", "z_order", "+", "1" ]
adjusts sprite's z-order so that the sprite is on top of it's siblings
[ "adjusts", "sprite", "s", "z", "-", "order", "so", "that", "the", "sprite", "is", "on", "top", "of", "it", "s", "siblings" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1039-L1044
232,060
projecthamster/hamster
src/hamster/lib/graphics.py
Sprite.send_to_back
def send_to_back(self): """adjusts sprite's z-order so that the sprite is behind it's siblings""" if not self.parent: return self.z_order = self.parent._z_ordered_sprites[0].z_order - 1
python
def send_to_back(self): """adjusts sprite's z-order so that the sprite is behind it's siblings""" if not self.parent: return self.z_order = self.parent._z_ordered_sprites[0].z_order - 1
[ "def", "send_to_back", "(", "self", ")", ":", "if", "not", "self", ".", "parent", ":", "return", "self", ".", "z_order", "=", "self", ".", "parent", ".", "_z_ordered_sprites", "[", "0", "]", ".", "z_order", "-", "1" ]
adjusts sprite's z-order so that the sprite is behind it's siblings
[ "adjusts", "sprite", "s", "z", "-", "order", "so", "that", "the", "sprite", "is", "behind", "it", "s", "siblings" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1046-L1051
232,061
projecthamster/hamster
src/hamster/lib/graphics.py
Sprite.blur
def blur(self): """removes focus from the current element if it has it""" scene = self.get_scene() if scene and scene._focus_sprite == self: scene._focus_sprite = None
python
def blur(self): """removes focus from the current element if it has it""" scene = self.get_scene() if scene and scene._focus_sprite == self: scene._focus_sprite = None
[ "def", "blur", "(", "self", ")", ":", "scene", "=", "self", ".", "get_scene", "(", ")", "if", "scene", "and", "scene", ".", "_focus_sprite", "==", "self", ":", "scene", ".", "_focus_sprite", "=", "None" ]
removes focus from the current element if it has it
[ "removes", "focus", "from", "the", "current", "element", "if", "it", "has", "it" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1067-L1071
232,062
projecthamster/hamster
src/hamster/lib/graphics.py
Sprite.get_parents
def get_parents(self): """returns all the parent sprites up until scene""" res = [] parent = self.parent while parent and isinstance(parent, Scene) == False: res.insert(0, parent) parent = parent.parent return res
python
def get_parents(self): """returns all the parent sprites up until scene""" res = [] parent = self.parent while parent and isinstance(parent, Scene) == False: res.insert(0, parent) parent = parent.parent return res
[ "def", "get_parents", "(", "self", ")", ":", "res", "=", "[", "]", "parent", "=", "self", ".", "parent", "while", "parent", "and", "isinstance", "(", "parent", ",", "Scene", ")", "==", "False", ":", "res", ".", "insert", "(", "0", ",", "parent", ")", "parent", "=", "parent", ".", "parent", "return", "res" ]
returns all the parent sprites up until scene
[ "returns", "all", "the", "parent", "sprites", "up", "until", "scene" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1077-L1085
232,063
projecthamster/hamster
src/hamster/lib/graphics.py
Sprite.get_extents
def get_extents(self): """measure the extents of the sprite's graphics.""" if self._sprite_dirty: # redrawing merely because we need fresh extents of the sprite context = cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0)) context.transform(self.get_matrix()) self.emit("on-render") self.__dict__["_sprite_dirty"] = False self.graphics._draw(context, 1) if not self.graphics.paths: self.graphics._draw(cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0)), 1) if not self.graphics.paths: return None context = cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0)) # bit of a hack around the problem - looking for clip instructions in parent # so extents would not get out of it clip_extents = None for parent in self.get_parents(): context.transform(parent.get_local_matrix()) if parent.graphics.paths: clip_regions = [] for instruction, type, path in parent.graphics.paths: if instruction == "clip": context.append_path(path) context.save() context.identity_matrix() clip_regions.append(context.fill_extents()) context.restore() context.new_path() elif instruction == "restore" and clip_regions: clip_regions.pop() for ext in clip_regions: ext = get_gdk_rectangle(int(ext[0]), int(ext[1]), int(ext[2] - ext[0]), int(ext[3] - ext[1])) intersect, clip_extents = gdk.rectangle_intersect((clip_extents or ext), ext) context.transform(self.get_local_matrix()) for instruction, type, path in self.graphics.paths: if type == "path": context.append_path(path) else: getattr(context, instruction)(*path) context.identity_matrix() ext = context.path_extents() ext = get_gdk_rectangle(int(ext[0]), int(ext[1]), int(ext[2] - ext[0]), int(ext[3] - ext[1])) if clip_extents: intersect, ext = gdk.rectangle_intersect(clip_extents, ext) if not ext.width and not ext.height: ext = None self.__dict__['_stroke_context'] = context return ext
python
def get_extents(self): """measure the extents of the sprite's graphics.""" if self._sprite_dirty: # redrawing merely because we need fresh extents of the sprite context = cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0)) context.transform(self.get_matrix()) self.emit("on-render") self.__dict__["_sprite_dirty"] = False self.graphics._draw(context, 1) if not self.graphics.paths: self.graphics._draw(cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0)), 1) if not self.graphics.paths: return None context = cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0)) # bit of a hack around the problem - looking for clip instructions in parent # so extents would not get out of it clip_extents = None for parent in self.get_parents(): context.transform(parent.get_local_matrix()) if parent.graphics.paths: clip_regions = [] for instruction, type, path in parent.graphics.paths: if instruction == "clip": context.append_path(path) context.save() context.identity_matrix() clip_regions.append(context.fill_extents()) context.restore() context.new_path() elif instruction == "restore" and clip_regions: clip_regions.pop() for ext in clip_regions: ext = get_gdk_rectangle(int(ext[0]), int(ext[1]), int(ext[2] - ext[0]), int(ext[3] - ext[1])) intersect, clip_extents = gdk.rectangle_intersect((clip_extents or ext), ext) context.transform(self.get_local_matrix()) for instruction, type, path in self.graphics.paths: if type == "path": context.append_path(path) else: getattr(context, instruction)(*path) context.identity_matrix() ext = context.path_extents() ext = get_gdk_rectangle(int(ext[0]), int(ext[1]), int(ext[2] - ext[0]), int(ext[3] - ext[1])) if clip_extents: intersect, ext = gdk.rectangle_intersect(clip_extents, ext) if not ext.width and not ext.height: ext = None self.__dict__['_stroke_context'] = context return ext
[ "def", "get_extents", "(", "self", ")", ":", "if", "self", ".", "_sprite_dirty", ":", "# redrawing merely because we need fresh extents of the sprite", "context", "=", "cairo", ".", "Context", "(", "cairo", ".", "ImageSurface", "(", "cairo", ".", "FORMAT_A1", ",", "0", ",", "0", ")", ")", "context", ".", "transform", "(", "self", ".", "get_matrix", "(", ")", ")", "self", ".", "emit", "(", "\"on-render\"", ")", "self", ".", "__dict__", "[", "\"_sprite_dirty\"", "]", "=", "False", "self", ".", "graphics", ".", "_draw", "(", "context", ",", "1", ")", "if", "not", "self", ".", "graphics", ".", "paths", ":", "self", ".", "graphics", ".", "_draw", "(", "cairo", ".", "Context", "(", "cairo", ".", "ImageSurface", "(", "cairo", ".", "FORMAT_A1", ",", "0", ",", "0", ")", ")", ",", "1", ")", "if", "not", "self", ".", "graphics", ".", "paths", ":", "return", "None", "context", "=", "cairo", ".", "Context", "(", "cairo", ".", "ImageSurface", "(", "cairo", ".", "FORMAT_A1", ",", "0", ",", "0", ")", ")", "# bit of a hack around the problem - looking for clip instructions in parent", "# so extents would not get out of it", "clip_extents", "=", "None", "for", "parent", "in", "self", ".", "get_parents", "(", ")", ":", "context", ".", "transform", "(", "parent", ".", "get_local_matrix", "(", ")", ")", "if", "parent", ".", "graphics", ".", "paths", ":", "clip_regions", "=", "[", "]", "for", "instruction", ",", "type", ",", "path", "in", "parent", ".", "graphics", ".", "paths", ":", "if", "instruction", "==", "\"clip\"", ":", "context", ".", "append_path", "(", "path", ")", "context", ".", "save", "(", ")", "context", ".", "identity_matrix", "(", ")", "clip_regions", ".", "append", "(", "context", ".", "fill_extents", "(", ")", ")", "context", ".", "restore", "(", ")", "context", ".", "new_path", "(", ")", "elif", "instruction", "==", "\"restore\"", "and", "clip_regions", ":", "clip_regions", ".", "pop", "(", ")", "for", "ext", "in", "clip_regions", ":", "ext", "=", "get_gdk_rectangle", "(", "int", "(", "ext", "[", "0", "]", ")", ",", "int", "(", "ext", "[", "1", "]", ")", ",", "int", "(", "ext", "[", "2", "]", "-", "ext", "[", "0", "]", ")", ",", "int", "(", "ext", "[", "3", "]", "-", "ext", "[", "1", "]", ")", ")", "intersect", ",", "clip_extents", "=", "gdk", ".", "rectangle_intersect", "(", "(", "clip_extents", "or", "ext", ")", ",", "ext", ")", "context", ".", "transform", "(", "self", ".", "get_local_matrix", "(", ")", ")", "for", "instruction", ",", "type", ",", "path", "in", "self", ".", "graphics", ".", "paths", ":", "if", "type", "==", "\"path\"", ":", "context", ".", "append_path", "(", "path", ")", "else", ":", "getattr", "(", "context", ",", "instruction", ")", "(", "*", "path", ")", "context", ".", "identity_matrix", "(", ")", "ext", "=", "context", ".", "path_extents", "(", ")", "ext", "=", "get_gdk_rectangle", "(", "int", "(", "ext", "[", "0", "]", ")", ",", "int", "(", "ext", "[", "1", "]", ")", ",", "int", "(", "ext", "[", "2", "]", "-", "ext", "[", "0", "]", ")", ",", "int", "(", "ext", "[", "3", "]", "-", "ext", "[", "1", "]", ")", ")", "if", "clip_extents", ":", "intersect", ",", "ext", "=", "gdk", ".", "rectangle_intersect", "(", "clip_extents", ",", "ext", ")", "if", "not", "ext", ".", "width", "and", "not", "ext", ".", "height", ":", "ext", "=", "None", "self", ".", "__dict__", "[", "'_stroke_context'", "]", "=", "context", "return", "ext" ]
measure the extents of the sprite's graphics.
[ "measure", "the", "extents", "of", "the", "sprite", "s", "graphics", "." ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1088-L1152
232,064
projecthamster/hamster
src/hamster/lib/graphics.py
Sprite.check_hit
def check_hit(self, x, y): """check if the given coordinates are inside the sprite's fill or stroke path""" extents = self.get_extents() if not extents: return False if extents.x <= x <= extents.x + extents.width and extents.y <= y <= extents.y + extents.height: return self._stroke_context is None or self._stroke_context.in_fill(x, y) else: return False
python
def check_hit(self, x, y): """check if the given coordinates are inside the sprite's fill or stroke path""" extents = self.get_extents() if not extents: return False if extents.x <= x <= extents.x + extents.width and extents.y <= y <= extents.y + extents.height: return self._stroke_context is None or self._stroke_context.in_fill(x, y) else: return False
[ "def", "check_hit", "(", "self", ",", "x", ",", "y", ")", ":", "extents", "=", "self", ".", "get_extents", "(", ")", "if", "not", "extents", ":", "return", "False", "if", "extents", ".", "x", "<=", "x", "<=", "extents", ".", "x", "+", "extents", ".", "width", "and", "extents", ".", "y", "<=", "y", "<=", "extents", ".", "y", "+", "extents", ".", "height", ":", "return", "self", ".", "_stroke_context", "is", "None", "or", "self", ".", "_stroke_context", ".", "in_fill", "(", "x", ",", "y", ")", "else", ":", "return", "False" ]
check if the given coordinates are inside the sprite's fill or stroke path
[ "check", "if", "the", "given", "coordinates", "are", "inside", "the", "sprite", "s", "fill", "or", "stroke", "path" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1155-L1165
232,065
projecthamster/hamster
src/hamster/lib/graphics.py
Sprite.get_matrix
def get_matrix(self): """return sprite's current transformation matrix""" if self.parent: return self.get_local_matrix() * (self._prev_parent_matrix or self.parent.get_matrix()) else: return self.get_local_matrix()
python
def get_matrix(self): """return sprite's current transformation matrix""" if self.parent: return self.get_local_matrix() * (self._prev_parent_matrix or self.parent.get_matrix()) else: return self.get_local_matrix()
[ "def", "get_matrix", "(", "self", ")", ":", "if", "self", ".", "parent", ":", "return", "self", ".", "get_local_matrix", "(", ")", "*", "(", "self", ".", "_prev_parent_matrix", "or", "self", ".", "parent", ".", "get_matrix", "(", ")", ")", "else", ":", "return", "self", ".", "get_local_matrix", "(", ")" ]
return sprite's current transformation matrix
[ "return", "sprite", "s", "current", "transformation", "matrix" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1238-L1243
232,066
projecthamster/hamster
src/hamster/lib/graphics.py
Sprite.from_scene_coords
def from_scene_coords(self, x=0, y=0): """Converts x, y given in the scene coordinates to sprite's local ones coordinates""" matrix = self.get_matrix() matrix.invert() return matrix.transform_point(x, y)
python
def from_scene_coords(self, x=0, y=0): """Converts x, y given in the scene coordinates to sprite's local ones coordinates""" matrix = self.get_matrix() matrix.invert() return matrix.transform_point(x, y)
[ "def", "from_scene_coords", "(", "self", ",", "x", "=", "0", ",", "y", "=", "0", ")", ":", "matrix", "=", "self", ".", "get_matrix", "(", ")", "matrix", ".", "invert", "(", ")", "return", "matrix", ".", "transform_point", "(", "x", ",", "y", ")" ]
Converts x, y given in the scene coordinates to sprite's local ones coordinates
[ "Converts", "x", "y", "given", "in", "the", "scene", "coordinates", "to", "sprite", "s", "local", "ones", "coordinates" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1246-L1251
232,067
projecthamster/hamster
src/hamster/lib/graphics.py
Scene.stop_animation
def stop_animation(self, sprites): """stop animation without firing on_complete""" if isinstance(sprites, list) is False: sprites = [sprites] for sprite in sprites: self.tweener.kill_tweens(sprite)
python
def stop_animation(self, sprites): """stop animation without firing on_complete""" if isinstance(sprites, list) is False: sprites = [sprites] for sprite in sprites: self.tweener.kill_tweens(sprite)
[ "def", "stop_animation", "(", "self", ",", "sprites", ")", ":", "if", "isinstance", "(", "sprites", ",", "list", ")", "is", "False", ":", "sprites", "=", "[", "sprites", "]", "for", "sprite", "in", "sprites", ":", "self", ".", "tweener", ".", "kill_tweens", "(", "sprite", ")" ]
stop animation without firing on_complete
[ "stop", "animation", "without", "firing", "on_complete" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1950-L1956
232,068
projecthamster/hamster
src/hamster/lib/graphics.py
Scene.redraw
def redraw(self): """Queue redraw. The redraw will be performed not more often than the `framerate` allows""" if self.__drawing_queued == False: #if we are moving, then there is a timeout somewhere already self.__drawing_queued = True self._last_frame_time = dt.datetime.now() gobject.timeout_add(1000 / self.framerate, self.__redraw_loop)
python
def redraw(self): """Queue redraw. The redraw will be performed not more often than the `framerate` allows""" if self.__drawing_queued == False: #if we are moving, then there is a timeout somewhere already self.__drawing_queued = True self._last_frame_time = dt.datetime.now() gobject.timeout_add(1000 / self.framerate, self.__redraw_loop)
[ "def", "redraw", "(", "self", ")", ":", "if", "self", ".", "__drawing_queued", "==", "False", ":", "#if we are moving, then there is a timeout somewhere already", "self", ".", "__drawing_queued", "=", "True", "self", ".", "_last_frame_time", "=", "dt", ".", "datetime", ".", "now", "(", ")", "gobject", ".", "timeout_add", "(", "1000", "/", "self", ".", "framerate", ",", "self", ".", "__redraw_loop", ")" ]
Queue redraw. The redraw will be performed not more often than the `framerate` allows
[ "Queue", "redraw", ".", "The", "redraw", "will", "be", "performed", "not", "more", "often", "than", "the", "framerate", "allows" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1959-L1965
232,069
projecthamster/hamster
src/hamster/lib/graphics.py
Scene.__redraw_loop
def __redraw_loop(self): """loop until there is nothing more to tween""" self.queue_draw() # this will trigger do_expose_event when the current events have been flushed self.__drawing_queued = self.tweener and self.tweener.has_tweens() return self.__drawing_queued
python
def __redraw_loop(self): """loop until there is nothing more to tween""" self.queue_draw() # this will trigger do_expose_event when the current events have been flushed self.__drawing_queued = self.tweener and self.tweener.has_tweens() return self.__drawing_queued
[ "def", "__redraw_loop", "(", "self", ")", ":", "self", ".", "queue_draw", "(", ")", "# this will trigger do_expose_event when the current events have been flushed", "self", ".", "__drawing_queued", "=", "self", ".", "tweener", "and", "self", ".", "tweener", ".", "has_tweens", "(", ")", "return", "self", ".", "__drawing_queued" ]
loop until there is nothing more to tween
[ "loop", "until", "there", "is", "nothing", "more", "to", "tween" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1967-L1972
232,070
projecthamster/hamster
src/hamster/lib/graphics.py
Scene.all_mouse_sprites
def all_mouse_sprites(self): """Returns flat list of the sprite tree for simplified iteration""" def all_recursive(sprites): if not sprites: return for sprite in sprites: if sprite.visible: yield sprite for child in all_recursive(sprite.get_mouse_sprites()): yield child return all_recursive(self.get_mouse_sprites())
python
def all_mouse_sprites(self): """Returns flat list of the sprite tree for simplified iteration""" def all_recursive(sprites): if not sprites: return for sprite in sprites: if sprite.visible: yield sprite for child in all_recursive(sprite.get_mouse_sprites()): yield child return all_recursive(self.get_mouse_sprites())
[ "def", "all_mouse_sprites", "(", "self", ")", ":", "def", "all_recursive", "(", "sprites", ")", ":", "if", "not", "sprites", ":", "return", "for", "sprite", "in", "sprites", ":", "if", "sprite", ".", "visible", ":", "yield", "sprite", "for", "child", "in", "all_recursive", "(", "sprite", ".", "get_mouse_sprites", "(", ")", ")", ":", "yield", "child", "return", "all_recursive", "(", "self", ".", "get_mouse_sprites", "(", ")", ")" ]
Returns flat list of the sprite tree for simplified iteration
[ "Returns", "flat", "list", "of", "the", "sprite", "tree", "for", "simplified", "iteration" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L2024-L2037
232,071
projecthamster/hamster
src/hamster/lib/graphics.py
Scene.get_sprite_at_position
def get_sprite_at_position(self, x, y): """Returns the topmost visible interactive sprite for given coordinates""" over = None for sprite in self.all_mouse_sprites(): if sprite.interactive and sprite.check_hit(x, y): over = sprite return over
python
def get_sprite_at_position(self, x, y): """Returns the topmost visible interactive sprite for given coordinates""" over = None for sprite in self.all_mouse_sprites(): if sprite.interactive and sprite.check_hit(x, y): over = sprite return over
[ "def", "get_sprite_at_position", "(", "self", ",", "x", ",", "y", ")", ":", "over", "=", "None", "for", "sprite", "in", "self", ".", "all_mouse_sprites", "(", ")", ":", "if", "sprite", ".", "interactive", "and", "sprite", ".", "check_hit", "(", "x", ",", "y", ")", ":", "over", "=", "sprite", "return", "over" ]
Returns the topmost visible interactive sprite for given coordinates
[ "Returns", "the", "topmost", "visible", "interactive", "sprite", "for", "given", "coordinates" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L2040-L2047
232,072
projecthamster/hamster
src/hamster/lib/graphics.py
Scene.start_drag
def start_drag(self, sprite, cursor_x = None, cursor_y = None): """start dragging given sprite""" cursor_x, cursor_y = cursor_x or sprite.x, cursor_y or sprite.y self._mouse_down_sprite = self._drag_sprite = sprite sprite.drag_x, sprite.drag_y = self._drag_sprite.x, self._drag_sprite.y self.__drag_start_x, self.__drag_start_y = cursor_x, cursor_y self.__drag_started = True
python
def start_drag(self, sprite, cursor_x = None, cursor_y = None): """start dragging given sprite""" cursor_x, cursor_y = cursor_x or sprite.x, cursor_y or sprite.y self._mouse_down_sprite = self._drag_sprite = sprite sprite.drag_x, sprite.drag_y = self._drag_sprite.x, self._drag_sprite.y self.__drag_start_x, self.__drag_start_y = cursor_x, cursor_y self.__drag_started = True
[ "def", "start_drag", "(", "self", ",", "sprite", ",", "cursor_x", "=", "None", ",", "cursor_y", "=", "None", ")", ":", "cursor_x", ",", "cursor_y", "=", "cursor_x", "or", "sprite", ".", "x", ",", "cursor_y", "or", "sprite", ".", "y", "self", ".", "_mouse_down_sprite", "=", "self", ".", "_drag_sprite", "=", "sprite", "sprite", ".", "drag_x", ",", "sprite", ".", "drag_y", "=", "self", ".", "_drag_sprite", ".", "x", ",", "self", ".", "_drag_sprite", ".", "y", "self", ".", "__drag_start_x", ",", "self", ".", "__drag_start_y", "=", "cursor_x", ",", "cursor_y", "self", ".", "__drag_started", "=", "True" ]
start dragging given sprite
[ "start", "dragging", "given", "sprite" ]
ca5254eff53172796ddafc72226c394ed1858245
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L2158-L2165
232,073
readbeyond/aeneas
aeneas/logger.py
Logger.pretty_print
def pretty_print(self, as_list=False, show_datetime=True): """ Return a Unicode string pretty print of the log entries. :param bool as_list: if ``True``, return a list of Unicode strings, one for each entry, instead of a Unicode string :param bool show_datetime: if ``True``, show the date and time of the entries :rtype: string or list of strings """ ppl = [entry.pretty_print(show_datetime) for entry in self.entries] if as_list: return ppl return u"\n".join(ppl)
python
def pretty_print(self, as_list=False, show_datetime=True): """ Return a Unicode string pretty print of the log entries. :param bool as_list: if ``True``, return a list of Unicode strings, one for each entry, instead of a Unicode string :param bool show_datetime: if ``True``, show the date and time of the entries :rtype: string or list of strings """ ppl = [entry.pretty_print(show_datetime) for entry in self.entries] if as_list: return ppl return u"\n".join(ppl)
[ "def", "pretty_print", "(", "self", ",", "as_list", "=", "False", ",", "show_datetime", "=", "True", ")", ":", "ppl", "=", "[", "entry", ".", "pretty_print", "(", "show_datetime", ")", "for", "entry", "in", "self", ".", "entries", "]", "if", "as_list", ":", "return", "ppl", "return", "u\"\\n\"", ".", "join", "(", "ppl", ")" ]
Return a Unicode string pretty print of the log entries. :param bool as_list: if ``True``, return a list of Unicode strings, one for each entry, instead of a Unicode string :param bool show_datetime: if ``True``, show the date and time of the entries :rtype: string or list of strings
[ "Return", "a", "Unicode", "string", "pretty", "print", "of", "the", "log", "entries", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/logger.py#L130-L142
232,074
readbeyond/aeneas
aeneas/logger.py
Logger.log
def log(self, message, severity=INFO, tag=u""): """ Add a given message to the log, and return its time. :param string message: the message to be added :param severity: the severity of the message :type severity: :class:`~aeneas.logger.Logger` :param string tag: the tag associated with the message; usually, the name of the class generating the entry :rtype: datetime """ entry = _LogEntry( severity=severity, time=datetime.datetime.now(), tag=tag, indentation=self.indentation, message=self._sanitize(message) ) self.entries.append(entry) if self.tee: gf.safe_print(entry.pretty_print(show_datetime=self.tee_show_datetime)) return entry.time
python
def log(self, message, severity=INFO, tag=u""): """ Add a given message to the log, and return its time. :param string message: the message to be added :param severity: the severity of the message :type severity: :class:`~aeneas.logger.Logger` :param string tag: the tag associated with the message; usually, the name of the class generating the entry :rtype: datetime """ entry = _LogEntry( severity=severity, time=datetime.datetime.now(), tag=tag, indentation=self.indentation, message=self._sanitize(message) ) self.entries.append(entry) if self.tee: gf.safe_print(entry.pretty_print(show_datetime=self.tee_show_datetime)) return entry.time
[ "def", "log", "(", "self", ",", "message", ",", "severity", "=", "INFO", ",", "tag", "=", "u\"\"", ")", ":", "entry", "=", "_LogEntry", "(", "severity", "=", "severity", ",", "time", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ",", "tag", "=", "tag", ",", "indentation", "=", "self", ".", "indentation", ",", "message", "=", "self", ".", "_sanitize", "(", "message", ")", ")", "self", ".", "entries", ".", "append", "(", "entry", ")", "if", "self", ".", "tee", ":", "gf", ".", "safe_print", "(", "entry", ".", "pretty_print", "(", "show_datetime", "=", "self", ".", "tee_show_datetime", ")", ")", "return", "entry", ".", "time" ]
Add a given message to the log, and return its time. :param string message: the message to be added :param severity: the severity of the message :type severity: :class:`~aeneas.logger.Logger` :param string tag: the tag associated with the message; usually, the name of the class generating the entry :rtype: datetime
[ "Add", "a", "given", "message", "to", "the", "log", "and", "return", "its", "time", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/logger.py#L144-L165
232,075
readbeyond/aeneas
aeneas/logger.py
Logger.write
def write(self, path): """ Output the log to file. :param string path: the path of the log file to be written """ with io.open(path, "w", encoding="utf-8") as log_file: log_file.write(self.pretty_print())
python
def write(self, path): """ Output the log to file. :param string path: the path of the log file to be written """ with io.open(path, "w", encoding="utf-8") as log_file: log_file.write(self.pretty_print())
[ "def", "write", "(", "self", ",", "path", ")", ":", "with", "io", ".", "open", "(", "path", ",", "\"w\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "log_file", ":", "log_file", ".", "write", "(", "self", ".", "pretty_print", "(", ")", ")" ]
Output the log to file. :param string path: the path of the log file to be written
[ "Output", "the", "log", "to", "file", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/logger.py#L173-L180
232,076
readbeyond/aeneas
aeneas/logger.py
_LogEntry.pretty_print
def pretty_print(self, show_datetime=True): """ Returns a Unicode string containing the pretty printing of a given log entry. :param bool show_datetime: if ``True``, print the date and time of the entry :rtype: string """ if show_datetime: return u"[%s] %s %s%s: %s" % ( self.severity, gf.object_to_unicode(self.time), u" " * self.indentation, self.tag, self.message ) return u"[%s] %s%s: %s" % ( self.severity, u" " * self.indentation, self.tag, self.message )
python
def pretty_print(self, show_datetime=True): """ Returns a Unicode string containing the pretty printing of a given log entry. :param bool show_datetime: if ``True``, print the date and time of the entry :rtype: string """ if show_datetime: return u"[%s] %s %s%s: %s" % ( self.severity, gf.object_to_unicode(self.time), u" " * self.indentation, self.tag, self.message ) return u"[%s] %s%s: %s" % ( self.severity, u" " * self.indentation, self.tag, self.message )
[ "def", "pretty_print", "(", "self", ",", "show_datetime", "=", "True", ")", ":", "if", "show_datetime", ":", "return", "u\"[%s] %s %s%s: %s\"", "%", "(", "self", ".", "severity", ",", "gf", ".", "object_to_unicode", "(", "self", ".", "time", ")", ",", "u\" \"", "*", "self", ".", "indentation", ",", "self", ".", "tag", ",", "self", ".", "message", ")", "return", "u\"[%s] %s%s: %s\"", "%", "(", "self", ".", "severity", ",", "u\" \"", "*", "self", ".", "indentation", ",", "self", ".", "tag", ",", "self", ".", "message", ")" ]
Returns a Unicode string containing the pretty printing of a given log entry. :param bool show_datetime: if ``True``, print the date and time of the entry :rtype: string
[ "Returns", "a", "Unicode", "string", "containing", "the", "pretty", "printing", "of", "a", "given", "log", "entry", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/logger.py#L219-L240
232,077
readbeyond/aeneas
aeneas/logger.py
Loggable._log
def _log(self, message, severity=Logger.DEBUG): """ Log generic message :param string message: the message to log :param string severity: the message severity :rtype: datetime """ return self.logger.log(message, severity, self.TAG)
python
def _log(self, message, severity=Logger.DEBUG): """ Log generic message :param string message: the message to log :param string severity: the message severity :rtype: datetime """ return self.logger.log(message, severity, self.TAG)
[ "def", "_log", "(", "self", ",", "message", ",", "severity", "=", "Logger", ".", "DEBUG", ")", ":", "return", "self", ".", "logger", ".", "log", "(", "message", ",", "severity", ",", "self", ".", "TAG", ")" ]
Log generic message :param string message: the message to log :param string severity: the message severity :rtype: datetime
[ "Log", "generic", "message" ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/logger.py#L323-L331
232,078
readbeyond/aeneas
aeneas/logger.py
Loggable.log_exc
def log_exc(self, message, exc=None, critical=True, raise_type=None): """ Log exception, and possibly raise exception. :param string message: the message to log :param Exception exc: the original exception :param bool critical: if ``True``, log as :data:`aeneas.logger.Logger.CRITICAL`; otherwise as :data:`aeneas.logger.Logger.WARNING` :param Exception raise_type: if not ``None``, raise this Exception type """ log_function = self.log_crit if critical else self.log_warn log_function(message) if exc is not None: log_function([u"%s", exc]) if raise_type is not None: raise_message = message if exc is not None: raise_message = u"%s : %s" % (message, exc) raise raise_type(raise_message)
python
def log_exc(self, message, exc=None, critical=True, raise_type=None): """ Log exception, and possibly raise exception. :param string message: the message to log :param Exception exc: the original exception :param bool critical: if ``True``, log as :data:`aeneas.logger.Logger.CRITICAL`; otherwise as :data:`aeneas.logger.Logger.WARNING` :param Exception raise_type: if not ``None``, raise this Exception type """ log_function = self.log_crit if critical else self.log_warn log_function(message) if exc is not None: log_function([u"%s", exc]) if raise_type is not None: raise_message = message if exc is not None: raise_message = u"%s : %s" % (message, exc) raise raise_type(raise_message)
[ "def", "log_exc", "(", "self", ",", "message", ",", "exc", "=", "None", ",", "critical", "=", "True", ",", "raise_type", "=", "None", ")", ":", "log_function", "=", "self", ".", "log_crit", "if", "critical", "else", "self", ".", "log_warn", "log_function", "(", "message", ")", "if", "exc", "is", "not", "None", ":", "log_function", "(", "[", "u\"%s\"", ",", "exc", "]", ")", "if", "raise_type", "is", "not", "None", ":", "raise_message", "=", "message", "if", "exc", "is", "not", "None", ":", "raise_message", "=", "u\"%s : %s\"", "%", "(", "message", ",", "exc", ")", "raise", "raise_type", "(", "raise_message", ")" ]
Log exception, and possibly raise exception. :param string message: the message to log :param Exception exc: the original exception :param bool critical: if ``True``, log as :data:`aeneas.logger.Logger.CRITICAL`; otherwise as :data:`aeneas.logger.Logger.WARNING` :param Exception raise_type: if not ``None``, raise this Exception type
[ "Log", "exception", "and", "possibly", "raise", "exception", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/logger.py#L333-L351
232,079
readbeyond/aeneas
aeneas/plotter.py
Plotter.add_waveform
def add_waveform(self, waveform): """ Add a waveform to the plot. :param waveform: the waveform to be added :type waveform: :class:`~aeneas.plotter.PlotWaveform` :raises: TypeError: if ``waveform`` is not an instance of :class:`~aeneas.plotter.PlotWaveform` """ if not isinstance(waveform, PlotWaveform): self.log_exc(u"waveform must be an instance of PlotWaveform", None, True, TypeError) self.waveform = waveform self.log(u"Added waveform")
python
def add_waveform(self, waveform): """ Add a waveform to the plot. :param waveform: the waveform to be added :type waveform: :class:`~aeneas.plotter.PlotWaveform` :raises: TypeError: if ``waveform`` is not an instance of :class:`~aeneas.plotter.PlotWaveform` """ if not isinstance(waveform, PlotWaveform): self.log_exc(u"waveform must be an instance of PlotWaveform", None, True, TypeError) self.waveform = waveform self.log(u"Added waveform")
[ "def", "add_waveform", "(", "self", ",", "waveform", ")", ":", "if", "not", "isinstance", "(", "waveform", ",", "PlotWaveform", ")", ":", "self", ".", "log_exc", "(", "u\"waveform must be an instance of PlotWaveform\"", ",", "None", ",", "True", ",", "TypeError", ")", "self", ".", "waveform", "=", "waveform", "self", ".", "log", "(", "u\"Added waveform\"", ")" ]
Add a waveform to the plot. :param waveform: the waveform to be added :type waveform: :class:`~aeneas.plotter.PlotWaveform` :raises: TypeError: if ``waveform`` is not an instance of :class:`~aeneas.plotter.PlotWaveform`
[ "Add", "a", "waveform", "to", "the", "plot", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/plotter.py#L100-L111
232,080
readbeyond/aeneas
aeneas/plotter.py
Plotter.add_timescale
def add_timescale(self, timescale): """ Add a time scale to the plot. :param timescale: the timescale to be added :type timescale: :class:`~aeneas.plotter.PlotTimeScale` :raises: TypeError: if ``timescale`` is not an instance of :class:`~aeneas.plotter.PlotTimeScale` """ if not isinstance(timescale, PlotTimeScale): self.log_exc(u"timescale must be an instance of PlotTimeScale", None, True, TypeError) self.timescale = timescale self.log(u"Added timescale")
python
def add_timescale(self, timescale): """ Add a time scale to the plot. :param timescale: the timescale to be added :type timescale: :class:`~aeneas.plotter.PlotTimeScale` :raises: TypeError: if ``timescale`` is not an instance of :class:`~aeneas.plotter.PlotTimeScale` """ if not isinstance(timescale, PlotTimeScale): self.log_exc(u"timescale must be an instance of PlotTimeScale", None, True, TypeError) self.timescale = timescale self.log(u"Added timescale")
[ "def", "add_timescale", "(", "self", ",", "timescale", ")", ":", "if", "not", "isinstance", "(", "timescale", ",", "PlotTimeScale", ")", ":", "self", ".", "log_exc", "(", "u\"timescale must be an instance of PlotTimeScale\"", ",", "None", ",", "True", ",", "TypeError", ")", "self", ".", "timescale", "=", "timescale", "self", ".", "log", "(", "u\"Added timescale\"", ")" ]
Add a time scale to the plot. :param timescale: the timescale to be added :type timescale: :class:`~aeneas.plotter.PlotTimeScale` :raises: TypeError: if ``timescale`` is not an instance of :class:`~aeneas.plotter.PlotTimeScale`
[ "Add", "a", "time", "scale", "to", "the", "plot", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/plotter.py#L113-L124
232,081
readbeyond/aeneas
aeneas/plotter.py
Plotter.add_labelset
def add_labelset(self, labelset): """ Add a set of labels to the plot. :param labelset: the set of labels to be added :type labelset: :class:`~aeneas.plotter.PlotLabelset` :raises: TypeError: if ``labelset`` is not an instance of :class:`~aeneas.plotter.PlotLabelset` """ if not isinstance(labelset, PlotLabelset): self.log_exc(u"labelset must be an instance of PlotLabelset", None, True, TypeError) self.labelsets.append(labelset) self.log(u"Added labelset")
python
def add_labelset(self, labelset): """ Add a set of labels to the plot. :param labelset: the set of labels to be added :type labelset: :class:`~aeneas.plotter.PlotLabelset` :raises: TypeError: if ``labelset`` is not an instance of :class:`~aeneas.plotter.PlotLabelset` """ if not isinstance(labelset, PlotLabelset): self.log_exc(u"labelset must be an instance of PlotLabelset", None, True, TypeError) self.labelsets.append(labelset) self.log(u"Added labelset")
[ "def", "add_labelset", "(", "self", ",", "labelset", ")", ":", "if", "not", "isinstance", "(", "labelset", ",", "PlotLabelset", ")", ":", "self", ".", "log_exc", "(", "u\"labelset must be an instance of PlotLabelset\"", ",", "None", ",", "True", ",", "TypeError", ")", "self", ".", "labelsets", ".", "append", "(", "labelset", ")", "self", ".", "log", "(", "u\"Added labelset\"", ")" ]
Add a set of labels to the plot. :param labelset: the set of labels to be added :type labelset: :class:`~aeneas.plotter.PlotLabelset` :raises: TypeError: if ``labelset`` is not an instance of :class:`~aeneas.plotter.PlotLabelset`
[ "Add", "a", "set", "of", "labels", "to", "the", "plot", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/plotter.py#L126-L137
232,082
readbeyond/aeneas
aeneas/plotter.py
Plotter.draw_png
def draw_png(self, output_file_path, h_zoom=5, v_zoom=30): """ Draw the current plot to a PNG file. :param string output_path: the path of the output file to be written :param int h_zoom: the horizontal zoom :param int v_zoom: the vertical zoom :raises: ImportError: if module ``PIL`` cannot be imported :raises: OSError: if ``output_file_path`` cannot be written """ # check that output_file_path can be written if not gf.file_can_be_written(output_file_path): self.log_exc(u"Cannot write to output file '%s'" % (output_file_path), None, True, OSError) # get widths and cumulative height, in modules widths = [ls.width for ls in self.labelsets] sum_height = sum([ls.height for ls in self.labelsets]) if self.waveform is not None: widths.append(self.waveform.width) sum_height += self.waveform.height if self.timescale is not None: sum_height += self.timescale.height # in modules image_width = max(widths) image_height = sum_height # in pixels image_width_px = image_width * h_zoom image_height_px = image_height * v_zoom # build image object self.log([u"Building image with size (modules): %d %d", image_width, image_height]) self.log([u"Building image with size (px): %d %d", image_width_px, image_height_px]) image_obj = Image.new("RGB", (image_width_px, image_height_px), color=PlotterColors.AUDACITY_BACKGROUND_GREY) current_y = 0 if self.waveform is not None: self.log(u"Drawing waveform") self.waveform.draw_png(image_obj, h_zoom, v_zoom, current_y) current_y += self.waveform.height timescale_y = current_y if self.timescale is not None: # NOTE draw as the last thing # COMMENTED self.log(u"Drawing timescale") # COMMENTED self.timescale.draw_png(image_obj, h_zoom, v_zoom, current_y) current_y += self.timescale.height for labelset in self.labelsets: self.log(u"Drawing labelset") labelset.draw_png(image_obj, h_zoom, v_zoom, current_y) current_y += labelset.height if self.timescale is not None: self.log(u"Drawing timescale") self.timescale.draw_png(image_obj, h_zoom, v_zoom, timescale_y) self.log([u"Saving to file '%s'", output_file_path]) image_obj.save(output_file_path)
python
def draw_png(self, output_file_path, h_zoom=5, v_zoom=30): """ Draw the current plot to a PNG file. :param string output_path: the path of the output file to be written :param int h_zoom: the horizontal zoom :param int v_zoom: the vertical zoom :raises: ImportError: if module ``PIL`` cannot be imported :raises: OSError: if ``output_file_path`` cannot be written """ # check that output_file_path can be written if not gf.file_can_be_written(output_file_path): self.log_exc(u"Cannot write to output file '%s'" % (output_file_path), None, True, OSError) # get widths and cumulative height, in modules widths = [ls.width for ls in self.labelsets] sum_height = sum([ls.height for ls in self.labelsets]) if self.waveform is not None: widths.append(self.waveform.width) sum_height += self.waveform.height if self.timescale is not None: sum_height += self.timescale.height # in modules image_width = max(widths) image_height = sum_height # in pixels image_width_px = image_width * h_zoom image_height_px = image_height * v_zoom # build image object self.log([u"Building image with size (modules): %d %d", image_width, image_height]) self.log([u"Building image with size (px): %d %d", image_width_px, image_height_px]) image_obj = Image.new("RGB", (image_width_px, image_height_px), color=PlotterColors.AUDACITY_BACKGROUND_GREY) current_y = 0 if self.waveform is not None: self.log(u"Drawing waveform") self.waveform.draw_png(image_obj, h_zoom, v_zoom, current_y) current_y += self.waveform.height timescale_y = current_y if self.timescale is not None: # NOTE draw as the last thing # COMMENTED self.log(u"Drawing timescale") # COMMENTED self.timescale.draw_png(image_obj, h_zoom, v_zoom, current_y) current_y += self.timescale.height for labelset in self.labelsets: self.log(u"Drawing labelset") labelset.draw_png(image_obj, h_zoom, v_zoom, current_y) current_y += labelset.height if self.timescale is not None: self.log(u"Drawing timescale") self.timescale.draw_png(image_obj, h_zoom, v_zoom, timescale_y) self.log([u"Saving to file '%s'", output_file_path]) image_obj.save(output_file_path)
[ "def", "draw_png", "(", "self", ",", "output_file_path", ",", "h_zoom", "=", "5", ",", "v_zoom", "=", "30", ")", ":", "# check that output_file_path can be written", "if", "not", "gf", ".", "file_can_be_written", "(", "output_file_path", ")", ":", "self", ".", "log_exc", "(", "u\"Cannot write to output file '%s'\"", "%", "(", "output_file_path", ")", ",", "None", ",", "True", ",", "OSError", ")", "# get widths and cumulative height, in modules", "widths", "=", "[", "ls", ".", "width", "for", "ls", "in", "self", ".", "labelsets", "]", "sum_height", "=", "sum", "(", "[", "ls", ".", "height", "for", "ls", "in", "self", ".", "labelsets", "]", ")", "if", "self", ".", "waveform", "is", "not", "None", ":", "widths", ".", "append", "(", "self", ".", "waveform", ".", "width", ")", "sum_height", "+=", "self", ".", "waveform", ".", "height", "if", "self", ".", "timescale", "is", "not", "None", ":", "sum_height", "+=", "self", ".", "timescale", ".", "height", "# in modules", "image_width", "=", "max", "(", "widths", ")", "image_height", "=", "sum_height", "# in pixels", "image_width_px", "=", "image_width", "*", "h_zoom", "image_height_px", "=", "image_height", "*", "v_zoom", "# build image object", "self", ".", "log", "(", "[", "u\"Building image with size (modules): %d %d\"", ",", "image_width", ",", "image_height", "]", ")", "self", ".", "log", "(", "[", "u\"Building image with size (px): %d %d\"", ",", "image_width_px", ",", "image_height_px", "]", ")", "image_obj", "=", "Image", ".", "new", "(", "\"RGB\"", ",", "(", "image_width_px", ",", "image_height_px", ")", ",", "color", "=", "PlotterColors", ".", "AUDACITY_BACKGROUND_GREY", ")", "current_y", "=", "0", "if", "self", ".", "waveform", "is", "not", "None", ":", "self", ".", "log", "(", "u\"Drawing waveform\"", ")", "self", ".", "waveform", ".", "draw_png", "(", "image_obj", ",", "h_zoom", ",", "v_zoom", ",", "current_y", ")", "current_y", "+=", "self", ".", "waveform", ".", "height", "timescale_y", "=", "current_y", "if", "self", ".", "timescale", "is", "not", "None", ":", "# NOTE draw as the last thing", "# COMMENTED self.log(u\"Drawing timescale\")", "# COMMENTED self.timescale.draw_png(image_obj, h_zoom, v_zoom, current_y)", "current_y", "+=", "self", ".", "timescale", ".", "height", "for", "labelset", "in", "self", ".", "labelsets", ":", "self", ".", "log", "(", "u\"Drawing labelset\"", ")", "labelset", ".", "draw_png", "(", "image_obj", ",", "h_zoom", ",", "v_zoom", ",", "current_y", ")", "current_y", "+=", "labelset", ".", "height", "if", "self", ".", "timescale", "is", "not", "None", ":", "self", ".", "log", "(", "u\"Drawing timescale\"", ")", "self", ".", "timescale", ".", "draw_png", "(", "image_obj", ",", "h_zoom", ",", "v_zoom", ",", "timescale_y", ")", "self", ".", "log", "(", "[", "u\"Saving to file '%s'\"", ",", "output_file_path", "]", ")", "image_obj", ".", "save", "(", "output_file_path", ")" ]
Draw the current plot to a PNG file. :param string output_path: the path of the output file to be written :param int h_zoom: the horizontal zoom :param int v_zoom: the vertical zoom :raises: ImportError: if module ``PIL`` cannot be imported :raises: OSError: if ``output_file_path`` cannot be written
[ "Draw", "the", "current", "plot", "to", "a", "PNG", "file", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/plotter.py#L139-L191
232,083
readbeyond/aeneas
aeneas/plotter.py
PlotElement.text_bounding_box
def text_bounding_box(self, size_pt, text): """ Return the bounding box of the given text at the given font size. :param int size_pt: the font size in points :param string text: the text :rtype: tuple (width, height) """ if size_pt == 12: mult = {"h": 9, "w_digit": 5, "w_space": 2} elif size_pt == 18: mult = {"h": 14, "w_digit": 9, "w_space": 2} num_chars = len(text) return (num_chars * mult["w_digit"] + (num_chars - 1) * mult["w_space"] + 1, mult["h"])
python
def text_bounding_box(self, size_pt, text): """ Return the bounding box of the given text at the given font size. :param int size_pt: the font size in points :param string text: the text :rtype: tuple (width, height) """ if size_pt == 12: mult = {"h": 9, "w_digit": 5, "w_space": 2} elif size_pt == 18: mult = {"h": 14, "w_digit": 9, "w_space": 2} num_chars = len(text) return (num_chars * mult["w_digit"] + (num_chars - 1) * mult["w_space"] + 1, mult["h"])
[ "def", "text_bounding_box", "(", "self", ",", "size_pt", ",", "text", ")", ":", "if", "size_pt", "==", "12", ":", "mult", "=", "{", "\"h\"", ":", "9", ",", "\"w_digit\"", ":", "5", ",", "\"w_space\"", ":", "2", "}", "elif", "size_pt", "==", "18", ":", "mult", "=", "{", "\"h\"", ":", "14", ",", "\"w_digit\"", ":", "9", ",", "\"w_space\"", ":", "2", "}", "num_chars", "=", "len", "(", "text", ")", "return", "(", "num_chars", "*", "mult", "[", "\"w_digit\"", "]", "+", "(", "num_chars", "-", "1", ")", "*", "mult", "[", "\"w_space\"", "]", "+", "1", ",", "mult", "[", "\"h\"", "]", ")" ]
Return the bounding box of the given text at the given font size. :param int size_pt: the font size in points :param string text: the text :rtype: tuple (width, height)
[ "Return", "the", "bounding", "box", "of", "the", "given", "text", "at", "the", "given", "font", "size", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/plotter.py#L237-L252
232,084
readbeyond/aeneas
aeneas/plotter.py
PlotTimeScale.draw_png
def draw_png(self, image, h_zoom, v_zoom, current_y): """ Draw this time scale to PNG. :param image: the image to draw onto :param int h_zoom: the horizontal zoom :param int v_zoom: the vertical zoom :param int current_y: the current y offset, in modules :type image: :class:`PIL.Image` """ # PIL object draw = ImageDraw.Draw(image) mws = self.rconf.mws pixels_per_second = int(h_zoom / mws) current_y_px = current_y * v_zoom # create font, as tall as possible font_height_pt = 18 font = ImageFont.truetype(self.FONT_PATH, font_height_pt) # draw a tick every self.time_step seconds for i in range(0, 1 + int(self.max_time), self.time_step): # base x position begin_px = i * pixels_per_second # tick left_px = begin_px - self.TICK_WIDTH right_px = begin_px + self.TICK_WIDTH top_px = current_y_px bottom_px = current_y_px + v_zoom draw.rectangle((left_px, top_px, right_px, bottom_px), fill=PlotterColors.BLACK) # text time_text = self._time_string(i) left_px = begin_px + self.TICK_WIDTH + self.TEXT_MARGIN top_px = current_y_px + (v_zoom - self.text_bounding_box(font_height_pt, time_text)[1]) // 2 draw.text((left_px, top_px), time_text, PlotterColors.BLACK, font=font)
python
def draw_png(self, image, h_zoom, v_zoom, current_y): """ Draw this time scale to PNG. :param image: the image to draw onto :param int h_zoom: the horizontal zoom :param int v_zoom: the vertical zoom :param int current_y: the current y offset, in modules :type image: :class:`PIL.Image` """ # PIL object draw = ImageDraw.Draw(image) mws = self.rconf.mws pixels_per_second = int(h_zoom / mws) current_y_px = current_y * v_zoom # create font, as tall as possible font_height_pt = 18 font = ImageFont.truetype(self.FONT_PATH, font_height_pt) # draw a tick every self.time_step seconds for i in range(0, 1 + int(self.max_time), self.time_step): # base x position begin_px = i * pixels_per_second # tick left_px = begin_px - self.TICK_WIDTH right_px = begin_px + self.TICK_WIDTH top_px = current_y_px bottom_px = current_y_px + v_zoom draw.rectangle((left_px, top_px, right_px, bottom_px), fill=PlotterColors.BLACK) # text time_text = self._time_string(i) left_px = begin_px + self.TICK_WIDTH + self.TEXT_MARGIN top_px = current_y_px + (v_zoom - self.text_bounding_box(font_height_pt, time_text)[1]) // 2 draw.text((left_px, top_px), time_text, PlotterColors.BLACK, font=font)
[ "def", "draw_png", "(", "self", ",", "image", ",", "h_zoom", ",", "v_zoom", ",", "current_y", ")", ":", "# PIL object", "draw", "=", "ImageDraw", ".", "Draw", "(", "image", ")", "mws", "=", "self", ".", "rconf", ".", "mws", "pixels_per_second", "=", "int", "(", "h_zoom", "/", "mws", ")", "current_y_px", "=", "current_y", "*", "v_zoom", "# create font, as tall as possible", "font_height_pt", "=", "18", "font", "=", "ImageFont", ".", "truetype", "(", "self", ".", "FONT_PATH", ",", "font_height_pt", ")", "# draw a tick every self.time_step seconds", "for", "i", "in", "range", "(", "0", ",", "1", "+", "int", "(", "self", ".", "max_time", ")", ",", "self", ".", "time_step", ")", ":", "# base x position", "begin_px", "=", "i", "*", "pixels_per_second", "# tick", "left_px", "=", "begin_px", "-", "self", ".", "TICK_WIDTH", "right_px", "=", "begin_px", "+", "self", ".", "TICK_WIDTH", "top_px", "=", "current_y_px", "bottom_px", "=", "current_y_px", "+", "v_zoom", "draw", ".", "rectangle", "(", "(", "left_px", ",", "top_px", ",", "right_px", ",", "bottom_px", ")", ",", "fill", "=", "PlotterColors", ".", "BLACK", ")", "# text", "time_text", "=", "self", ".", "_time_string", "(", "i", ")", "left_px", "=", "begin_px", "+", "self", ".", "TICK_WIDTH", "+", "self", ".", "TEXT_MARGIN", "top_px", "=", "current_y_px", "+", "(", "v_zoom", "-", "self", ".", "text_bounding_box", "(", "font_height_pt", ",", "time_text", ")", "[", "1", "]", ")", "//", "2", "draw", ".", "text", "(", "(", "left_px", ",", "top_px", ")", ",", "time_text", ",", "PlotterColors", ".", "BLACK", ",", "font", "=", "font", ")" ]
Draw this time scale to PNG. :param image: the image to draw onto :param int h_zoom: the horizontal zoom :param int v_zoom: the vertical zoom :param int current_y: the current y offset, in modules :type image: :class:`PIL.Image`
[ "Draw", "this", "time", "scale", "to", "PNG", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/plotter.py#L305-L341
232,085
readbeyond/aeneas
aeneas/plotter.py
PlotWaveform.draw_png
def draw_png(self, image, h_zoom, v_zoom, current_y): """ Draw this waveform to PNG. :param image: the image to draw onto :param int h_zoom: the horizontal zoom :param int v_zoom: the vertical zoom :param int current_y: the current y offset, in modules :type image: :class:`PIL.Image` """ draw = ImageDraw.Draw(image) mws = self.rconf.mws rate = self.audio_file.audio_sample_rate samples = self.audio_file.audio_samples duration = self.audio_file.audio_length current_y_px = current_y * v_zoom half_waveform_px = (self.height // 2) * v_zoom zero_y_px = current_y_px + half_waveform_px samples_per_pixel = int(rate * mws / h_zoom) pixels_per_second = int(h_zoom / mws) windows = len(samples) // samples_per_pixel if self.label is not None: font_height_pt = 18 font = ImageFont.truetype(self.FONT_PATH, font_height_pt) draw.text((0, current_y_px), self.label, PlotterColors.BLACK, font=font) for i in range(windows): x = i * samples_per_pixel pos = numpy.clip(samples[x:(x + samples_per_pixel)], 0.0, 1.0) mpos = numpy.max(pos) * half_waveform_px if self.fast: # just draw a simple version, mirroring max positive samples draw.line((i, zero_y_px + mpos, i, zero_y_px - mpos), fill=PlotterColors.AUDACITY_DARK_BLUE, width=1) else: # draw a better version, taking min and std of positive and negative samples neg = numpy.clip(samples[x:(x + samples_per_pixel)], -1.0, 0.0) spos = numpy.std(pos) * half_waveform_px sneg = numpy.std(neg) * half_waveform_px mneg = numpy.min(neg) * half_waveform_px draw.line((i, zero_y_px - mneg, i, zero_y_px - mpos), fill=PlotterColors.AUDACITY_DARK_BLUE, width=1) draw.line((i, zero_y_px + sneg, i, zero_y_px - spos), fill=PlotterColors.AUDACITY_LIGHT_BLUE, width=1)
python
def draw_png(self, image, h_zoom, v_zoom, current_y): """ Draw this waveform to PNG. :param image: the image to draw onto :param int h_zoom: the horizontal zoom :param int v_zoom: the vertical zoom :param int current_y: the current y offset, in modules :type image: :class:`PIL.Image` """ draw = ImageDraw.Draw(image) mws = self.rconf.mws rate = self.audio_file.audio_sample_rate samples = self.audio_file.audio_samples duration = self.audio_file.audio_length current_y_px = current_y * v_zoom half_waveform_px = (self.height // 2) * v_zoom zero_y_px = current_y_px + half_waveform_px samples_per_pixel = int(rate * mws / h_zoom) pixels_per_second = int(h_zoom / mws) windows = len(samples) // samples_per_pixel if self.label is not None: font_height_pt = 18 font = ImageFont.truetype(self.FONT_PATH, font_height_pt) draw.text((0, current_y_px), self.label, PlotterColors.BLACK, font=font) for i in range(windows): x = i * samples_per_pixel pos = numpy.clip(samples[x:(x + samples_per_pixel)], 0.0, 1.0) mpos = numpy.max(pos) * half_waveform_px if self.fast: # just draw a simple version, mirroring max positive samples draw.line((i, zero_y_px + mpos, i, zero_y_px - mpos), fill=PlotterColors.AUDACITY_DARK_BLUE, width=1) else: # draw a better version, taking min and std of positive and negative samples neg = numpy.clip(samples[x:(x + samples_per_pixel)], -1.0, 0.0) spos = numpy.std(pos) * half_waveform_px sneg = numpy.std(neg) * half_waveform_px mneg = numpy.min(neg) * half_waveform_px draw.line((i, zero_y_px - mneg, i, zero_y_px - mpos), fill=PlotterColors.AUDACITY_DARK_BLUE, width=1) draw.line((i, zero_y_px + sneg, i, zero_y_px - spos), fill=PlotterColors.AUDACITY_LIGHT_BLUE, width=1)
[ "def", "draw_png", "(", "self", ",", "image", ",", "h_zoom", ",", "v_zoom", ",", "current_y", ")", ":", "draw", "=", "ImageDraw", ".", "Draw", "(", "image", ")", "mws", "=", "self", ".", "rconf", ".", "mws", "rate", "=", "self", ".", "audio_file", ".", "audio_sample_rate", "samples", "=", "self", ".", "audio_file", ".", "audio_samples", "duration", "=", "self", ".", "audio_file", ".", "audio_length", "current_y_px", "=", "current_y", "*", "v_zoom", "half_waveform_px", "=", "(", "self", ".", "height", "//", "2", ")", "*", "v_zoom", "zero_y_px", "=", "current_y_px", "+", "half_waveform_px", "samples_per_pixel", "=", "int", "(", "rate", "*", "mws", "/", "h_zoom", ")", "pixels_per_second", "=", "int", "(", "h_zoom", "/", "mws", ")", "windows", "=", "len", "(", "samples", ")", "//", "samples_per_pixel", "if", "self", ".", "label", "is", "not", "None", ":", "font_height_pt", "=", "18", "font", "=", "ImageFont", ".", "truetype", "(", "self", ".", "FONT_PATH", ",", "font_height_pt", ")", "draw", ".", "text", "(", "(", "0", ",", "current_y_px", ")", ",", "self", ".", "label", ",", "PlotterColors", ".", "BLACK", ",", "font", "=", "font", ")", "for", "i", "in", "range", "(", "windows", ")", ":", "x", "=", "i", "*", "samples_per_pixel", "pos", "=", "numpy", ".", "clip", "(", "samples", "[", "x", ":", "(", "x", "+", "samples_per_pixel", ")", "]", ",", "0.0", ",", "1.0", ")", "mpos", "=", "numpy", ".", "max", "(", "pos", ")", "*", "half_waveform_px", "if", "self", ".", "fast", ":", "# just draw a simple version, mirroring max positive samples", "draw", ".", "line", "(", "(", "i", ",", "zero_y_px", "+", "mpos", ",", "i", ",", "zero_y_px", "-", "mpos", ")", ",", "fill", "=", "PlotterColors", ".", "AUDACITY_DARK_BLUE", ",", "width", "=", "1", ")", "else", ":", "# draw a better version, taking min and std of positive and negative samples", "neg", "=", "numpy", ".", "clip", "(", "samples", "[", "x", ":", "(", "x", "+", "samples_per_pixel", ")", "]", ",", "-", "1.0", ",", "0.0", ")", "spos", "=", "numpy", ".", "std", "(", "pos", ")", "*", "half_waveform_px", "sneg", "=", "numpy", ".", "std", "(", "neg", ")", "*", "half_waveform_px", "mneg", "=", "numpy", ".", "min", "(", "neg", ")", "*", "half_waveform_px", "draw", ".", "line", "(", "(", "i", ",", "zero_y_px", "-", "mneg", ",", "i", ",", "zero_y_px", "-", "mpos", ")", ",", "fill", "=", "PlotterColors", ".", "AUDACITY_DARK_BLUE", ",", "width", "=", "1", ")", "draw", ".", "line", "(", "(", "i", ",", "zero_y_px", "+", "sneg", ",", "i", ",", "zero_y_px", "-", "spos", ")", ",", "fill", "=", "PlotterColors", ".", "AUDACITY_LIGHT_BLUE", ",", "width", "=", "1", ")" ]
Draw this waveform to PNG. :param image: the image to draw onto :param int h_zoom: the horizontal zoom :param int v_zoom: the vertical zoom :param int current_y: the current y offset, in modules :type image: :class:`PIL.Image`
[ "Draw", "this", "waveform", "to", "PNG", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/plotter.py#L524-L567
232,086
readbeyond/aeneas
aeneas/tools/run_sd.py
RunSDCLI.print_result
def print_result(self, audio_len, start, end): """ Print result of SD. :param audio_len: the length of the entire audio file, in seconds :type audio_len: float :param start: the start position of the spoken text :type start: float :param end: the end position of the spoken text :type end: float """ msg = [] zero = 0 head_len = start text_len = end - start tail_len = audio_len - end msg.append(u"") msg.append(u"Head: %.3f %.3f (%.3f)" % (zero, start, head_len)) msg.append(u"Text: %.3f %.3f (%.3f)" % (start, end, text_len)) msg.append(u"Tail: %.3f %.3f (%.3f)" % (end, audio_len, tail_len)) msg.append(u"") zero_h = gf.time_to_hhmmssmmm(0) start_h = gf.time_to_hhmmssmmm(start) end_h = gf.time_to_hhmmssmmm(end) audio_len_h = gf.time_to_hhmmssmmm(audio_len) head_len_h = gf.time_to_hhmmssmmm(head_len) text_len_h = gf.time_to_hhmmssmmm(text_len) tail_len_h = gf.time_to_hhmmssmmm(tail_len) msg.append("Head: %s %s (%s)" % (zero_h, start_h, head_len_h)) msg.append("Text: %s %s (%s)" % (start_h, end_h, text_len_h)) msg.append("Tail: %s %s (%s)" % (end_h, audio_len_h, tail_len_h)) msg.append(u"") self.print_info(u"\n".join(msg))
python
def print_result(self, audio_len, start, end): """ Print result of SD. :param audio_len: the length of the entire audio file, in seconds :type audio_len: float :param start: the start position of the spoken text :type start: float :param end: the end position of the spoken text :type end: float """ msg = [] zero = 0 head_len = start text_len = end - start tail_len = audio_len - end msg.append(u"") msg.append(u"Head: %.3f %.3f (%.3f)" % (zero, start, head_len)) msg.append(u"Text: %.3f %.3f (%.3f)" % (start, end, text_len)) msg.append(u"Tail: %.3f %.3f (%.3f)" % (end, audio_len, tail_len)) msg.append(u"") zero_h = gf.time_to_hhmmssmmm(0) start_h = gf.time_to_hhmmssmmm(start) end_h = gf.time_to_hhmmssmmm(end) audio_len_h = gf.time_to_hhmmssmmm(audio_len) head_len_h = gf.time_to_hhmmssmmm(head_len) text_len_h = gf.time_to_hhmmssmmm(text_len) tail_len_h = gf.time_to_hhmmssmmm(tail_len) msg.append("Head: %s %s (%s)" % (zero_h, start_h, head_len_h)) msg.append("Text: %s %s (%s)" % (start_h, end_h, text_len_h)) msg.append("Tail: %s %s (%s)" % (end_h, audio_len_h, tail_len_h)) msg.append(u"") self.print_info(u"\n".join(msg))
[ "def", "print_result", "(", "self", ",", "audio_len", ",", "start", ",", "end", ")", ":", "msg", "=", "[", "]", "zero", "=", "0", "head_len", "=", "start", "text_len", "=", "end", "-", "start", "tail_len", "=", "audio_len", "-", "end", "msg", ".", "append", "(", "u\"\"", ")", "msg", ".", "append", "(", "u\"Head: %.3f %.3f (%.3f)\"", "%", "(", "zero", ",", "start", ",", "head_len", ")", ")", "msg", ".", "append", "(", "u\"Text: %.3f %.3f (%.3f)\"", "%", "(", "start", ",", "end", ",", "text_len", ")", ")", "msg", ".", "append", "(", "u\"Tail: %.3f %.3f (%.3f)\"", "%", "(", "end", ",", "audio_len", ",", "tail_len", ")", ")", "msg", ".", "append", "(", "u\"\"", ")", "zero_h", "=", "gf", ".", "time_to_hhmmssmmm", "(", "0", ")", "start_h", "=", "gf", ".", "time_to_hhmmssmmm", "(", "start", ")", "end_h", "=", "gf", ".", "time_to_hhmmssmmm", "(", "end", ")", "audio_len_h", "=", "gf", ".", "time_to_hhmmssmmm", "(", "audio_len", ")", "head_len_h", "=", "gf", ".", "time_to_hhmmssmmm", "(", "head_len", ")", "text_len_h", "=", "gf", ".", "time_to_hhmmssmmm", "(", "text_len", ")", "tail_len_h", "=", "gf", ".", "time_to_hhmmssmmm", "(", "tail_len", ")", "msg", ".", "append", "(", "\"Head: %s %s (%s)\"", "%", "(", "zero_h", ",", "start_h", ",", "head_len_h", ")", ")", "msg", ".", "append", "(", "\"Text: %s %s (%s)\"", "%", "(", "start_h", ",", "end_h", ",", "text_len_h", ")", ")", "msg", ".", "append", "(", "\"Tail: %s %s (%s)\"", "%", "(", "end_h", ",", "audio_len_h", ",", "tail_len_h", ")", ")", "msg", ".", "append", "(", "u\"\"", ")", "self", ".", "print_info", "(", "u\"\\n\"", ".", "join", "(", "msg", ")", ")" ]
Print result of SD. :param audio_len: the length of the entire audio file, in seconds :type audio_len: float :param start: the start position of the spoken text :type start: float :param end: the end position of the spoken text :type end: float
[ "Print", "result", "of", "SD", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/run_sd.py#L171-L203
232,087
readbeyond/aeneas
aeneas/task.py
Task.sync_map_leaves
def sync_map_leaves(self, fragment_type=None): """ Return the list of non-empty leaves in the sync map associated with the task. If ``fragment_type`` has been specified, return only leaves of that fragment type. :param int fragment_type: type of fragment to return :rtype: list .. versionadded:: 1.7.0 """ if (self.sync_map is None) or (self.sync_map.fragments_tree is None): return [] return [f for f in self.sync_map.leaves(fragment_type)]
python
def sync_map_leaves(self, fragment_type=None): """ Return the list of non-empty leaves in the sync map associated with the task. If ``fragment_type`` has been specified, return only leaves of that fragment type. :param int fragment_type: type of fragment to return :rtype: list .. versionadded:: 1.7.0 """ if (self.sync_map is None) or (self.sync_map.fragments_tree is None): return [] return [f for f in self.sync_map.leaves(fragment_type)]
[ "def", "sync_map_leaves", "(", "self", ",", "fragment_type", "=", "None", ")", ":", "if", "(", "self", ".", "sync_map", "is", "None", ")", "or", "(", "self", ".", "sync_map", ".", "fragments_tree", "is", "None", ")", ":", "return", "[", "]", "return", "[", "f", "for", "f", "in", "self", ".", "sync_map", ".", "leaves", "(", "fragment_type", ")", "]" ]
Return the list of non-empty leaves in the sync map associated with the task. If ``fragment_type`` has been specified, return only leaves of that fragment type. :param int fragment_type: type of fragment to return :rtype: list .. versionadded:: 1.7.0
[ "Return", "the", "list", "of", "non", "-", "empty", "leaves", "in", "the", "sync", "map", "associated", "with", "the", "task", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/task.py#L149-L164
232,088
readbeyond/aeneas
aeneas/task.py
Task.output_sync_map_file
def output_sync_map_file(self, container_root_path=None): """ Output the sync map file for this task. If ``container_root_path`` is specified, the output sync map file will be created at the path obtained by joining the ``container_root_path`` and the relative path of the sync map inside the container. Otherwise, the sync map file will be created at the path ``self.sync_map_file_path_absolute``. Return the the path of the sync map file created, or ``None`` if an error occurred. :param string container_root_path: the path to the root directory for the output container :rtype: string """ if self.sync_map is None: self.log_exc(u"The sync_map object has not been set", None, True, TypeError) if (container_root_path is not None) and (self.sync_map_file_path is None): self.log_exc(u"The (internal) path of the sync map has been set", None, True, TypeError) self.log([u"container_root_path is %s", container_root_path]) self.log([u"self.sync_map_file_path is %s", self.sync_map_file_path]) self.log([u"self.sync_map_file_path_absolute is %s", self.sync_map_file_path_absolute]) if (container_root_path is not None) and (self.sync_map_file_path is not None): path = os.path.join(container_root_path, self.sync_map_file_path) elif self.sync_map_file_path_absolute: path = self.sync_map_file_path_absolute gf.ensure_parent_directory(path) self.log([u"Output sync map to %s", path]) eaf_audio_ref = self.configuration["o_eaf_audio_ref"] head_tail_format = self.configuration["o_h_t_format"] levels = self.configuration["o_levels"] smil_audio_ref = self.configuration["o_smil_audio_ref"] smil_page_ref = self.configuration["o_smil_page_ref"] sync_map_format = self.configuration["o_format"] self.log([u"eaf_audio_ref is %s", eaf_audio_ref]) self.log([u"head_tail_format is %s", head_tail_format]) self.log([u"levels is %s", levels]) self.log([u"smil_audio_ref is %s", smil_audio_ref]) self.log([u"smil_page_ref is %s", smil_page_ref]) self.log([u"sync_map_format is %s", sync_map_format]) self.log(u"Calling sync_map.write...") parameters = { gc.PPN_TASK_OS_FILE_EAF_AUDIO_REF: eaf_audio_ref, gc.PPN_TASK_OS_FILE_HEAD_TAIL_FORMAT: head_tail_format, gc.PPN_TASK_OS_FILE_LEVELS: levels, gc.PPN_TASK_OS_FILE_SMIL_AUDIO_REF: smil_audio_ref, gc.PPN_TASK_OS_FILE_SMIL_PAGE_REF: smil_page_ref, } self.sync_map.write(sync_map_format, path, parameters) self.log(u"Calling sync_map.write... done") return path
python
def output_sync_map_file(self, container_root_path=None): """ Output the sync map file for this task. If ``container_root_path`` is specified, the output sync map file will be created at the path obtained by joining the ``container_root_path`` and the relative path of the sync map inside the container. Otherwise, the sync map file will be created at the path ``self.sync_map_file_path_absolute``. Return the the path of the sync map file created, or ``None`` if an error occurred. :param string container_root_path: the path to the root directory for the output container :rtype: string """ if self.sync_map is None: self.log_exc(u"The sync_map object has not been set", None, True, TypeError) if (container_root_path is not None) and (self.sync_map_file_path is None): self.log_exc(u"The (internal) path of the sync map has been set", None, True, TypeError) self.log([u"container_root_path is %s", container_root_path]) self.log([u"self.sync_map_file_path is %s", self.sync_map_file_path]) self.log([u"self.sync_map_file_path_absolute is %s", self.sync_map_file_path_absolute]) if (container_root_path is not None) and (self.sync_map_file_path is not None): path = os.path.join(container_root_path, self.sync_map_file_path) elif self.sync_map_file_path_absolute: path = self.sync_map_file_path_absolute gf.ensure_parent_directory(path) self.log([u"Output sync map to %s", path]) eaf_audio_ref = self.configuration["o_eaf_audio_ref"] head_tail_format = self.configuration["o_h_t_format"] levels = self.configuration["o_levels"] smil_audio_ref = self.configuration["o_smil_audio_ref"] smil_page_ref = self.configuration["o_smil_page_ref"] sync_map_format = self.configuration["o_format"] self.log([u"eaf_audio_ref is %s", eaf_audio_ref]) self.log([u"head_tail_format is %s", head_tail_format]) self.log([u"levels is %s", levels]) self.log([u"smil_audio_ref is %s", smil_audio_ref]) self.log([u"smil_page_ref is %s", smil_page_ref]) self.log([u"sync_map_format is %s", sync_map_format]) self.log(u"Calling sync_map.write...") parameters = { gc.PPN_TASK_OS_FILE_EAF_AUDIO_REF: eaf_audio_ref, gc.PPN_TASK_OS_FILE_HEAD_TAIL_FORMAT: head_tail_format, gc.PPN_TASK_OS_FILE_LEVELS: levels, gc.PPN_TASK_OS_FILE_SMIL_AUDIO_REF: smil_audio_ref, gc.PPN_TASK_OS_FILE_SMIL_PAGE_REF: smil_page_ref, } self.sync_map.write(sync_map_format, path, parameters) self.log(u"Calling sync_map.write... done") return path
[ "def", "output_sync_map_file", "(", "self", ",", "container_root_path", "=", "None", ")", ":", "if", "self", ".", "sync_map", "is", "None", ":", "self", ".", "log_exc", "(", "u\"The sync_map object has not been set\"", ",", "None", ",", "True", ",", "TypeError", ")", "if", "(", "container_root_path", "is", "not", "None", ")", "and", "(", "self", ".", "sync_map_file_path", "is", "None", ")", ":", "self", ".", "log_exc", "(", "u\"The (internal) path of the sync map has been set\"", ",", "None", ",", "True", ",", "TypeError", ")", "self", ".", "log", "(", "[", "u\"container_root_path is %s\"", ",", "container_root_path", "]", ")", "self", ".", "log", "(", "[", "u\"self.sync_map_file_path is %s\"", ",", "self", ".", "sync_map_file_path", "]", ")", "self", ".", "log", "(", "[", "u\"self.sync_map_file_path_absolute is %s\"", ",", "self", ".", "sync_map_file_path_absolute", "]", ")", "if", "(", "container_root_path", "is", "not", "None", ")", "and", "(", "self", ".", "sync_map_file_path", "is", "not", "None", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "container_root_path", ",", "self", ".", "sync_map_file_path", ")", "elif", "self", ".", "sync_map_file_path_absolute", ":", "path", "=", "self", ".", "sync_map_file_path_absolute", "gf", ".", "ensure_parent_directory", "(", "path", ")", "self", ".", "log", "(", "[", "u\"Output sync map to %s\"", ",", "path", "]", ")", "eaf_audio_ref", "=", "self", ".", "configuration", "[", "\"o_eaf_audio_ref\"", "]", "head_tail_format", "=", "self", ".", "configuration", "[", "\"o_h_t_format\"", "]", "levels", "=", "self", ".", "configuration", "[", "\"o_levels\"", "]", "smil_audio_ref", "=", "self", ".", "configuration", "[", "\"o_smil_audio_ref\"", "]", "smil_page_ref", "=", "self", ".", "configuration", "[", "\"o_smil_page_ref\"", "]", "sync_map_format", "=", "self", ".", "configuration", "[", "\"o_format\"", "]", "self", ".", "log", "(", "[", "u\"eaf_audio_ref is %s\"", ",", "eaf_audio_ref", "]", ")", "self", ".", "log", "(", "[", "u\"head_tail_format is %s\"", ",", "head_tail_format", "]", ")", "self", ".", "log", "(", "[", "u\"levels is %s\"", ",", "levels", "]", ")", "self", ".", "log", "(", "[", "u\"smil_audio_ref is %s\"", ",", "smil_audio_ref", "]", ")", "self", ".", "log", "(", "[", "u\"smil_page_ref is %s\"", ",", "smil_page_ref", "]", ")", "self", ".", "log", "(", "[", "u\"sync_map_format is %s\"", ",", "sync_map_format", "]", ")", "self", ".", "log", "(", "u\"Calling sync_map.write...\"", ")", "parameters", "=", "{", "gc", ".", "PPN_TASK_OS_FILE_EAF_AUDIO_REF", ":", "eaf_audio_ref", ",", "gc", ".", "PPN_TASK_OS_FILE_HEAD_TAIL_FORMAT", ":", "head_tail_format", ",", "gc", ".", "PPN_TASK_OS_FILE_LEVELS", ":", "levels", ",", "gc", ".", "PPN_TASK_OS_FILE_SMIL_AUDIO_REF", ":", "smil_audio_ref", ",", "gc", ".", "PPN_TASK_OS_FILE_SMIL_PAGE_REF", ":", "smil_page_ref", ",", "}", "self", ".", "sync_map", ".", "write", "(", "sync_map_format", ",", "path", ",", "parameters", ")", "self", ".", "log", "(", "u\"Calling sync_map.write... done\"", ")", "return", "path" ]
Output the sync map file for this task. If ``container_root_path`` is specified, the output sync map file will be created at the path obtained by joining the ``container_root_path`` and the relative path of the sync map inside the container. Otherwise, the sync map file will be created at the path ``self.sync_map_file_path_absolute``. Return the the path of the sync map file created, or ``None`` if an error occurred. :param string container_root_path: the path to the root directory for the output container :rtype: string
[ "Output", "the", "sync", "map", "file", "for", "this", "task", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/task.py#L166-L227
232,089
readbeyond/aeneas
aeneas/task.py
Task._populate_audio_file
def _populate_audio_file(self): """ Create the ``self.audio_file`` object by reading the audio file at ``self.audio_file_path_absolute``. """ self.log(u"Populate audio file...") if self.audio_file_path_absolute is not None: self.log([u"audio_file_path_absolute is '%s'", self.audio_file_path_absolute]) self.audio_file = AudioFile( file_path=self.audio_file_path_absolute, logger=self.logger ) self.audio_file.read_properties() else: self.log(u"audio_file_path_absolute is None") self.log(u"Populate audio file... done")
python
def _populate_audio_file(self): """ Create the ``self.audio_file`` object by reading the audio file at ``self.audio_file_path_absolute``. """ self.log(u"Populate audio file...") if self.audio_file_path_absolute is not None: self.log([u"audio_file_path_absolute is '%s'", self.audio_file_path_absolute]) self.audio_file = AudioFile( file_path=self.audio_file_path_absolute, logger=self.logger ) self.audio_file.read_properties() else: self.log(u"audio_file_path_absolute is None") self.log(u"Populate audio file... done")
[ "def", "_populate_audio_file", "(", "self", ")", ":", "self", ".", "log", "(", "u\"Populate audio file...\"", ")", "if", "self", ".", "audio_file_path_absolute", "is", "not", "None", ":", "self", ".", "log", "(", "[", "u\"audio_file_path_absolute is '%s'\"", ",", "self", ".", "audio_file_path_absolute", "]", ")", "self", ".", "audio_file", "=", "AudioFile", "(", "file_path", "=", "self", ".", "audio_file_path_absolute", ",", "logger", "=", "self", ".", "logger", ")", "self", ".", "audio_file", ".", "read_properties", "(", ")", "else", ":", "self", ".", "log", "(", "u\"audio_file_path_absolute is None\"", ")", "self", ".", "log", "(", "u\"Populate audio file... done\"", ")" ]
Create the ``self.audio_file`` object by reading the audio file at ``self.audio_file_path_absolute``.
[ "Create", "the", "self", ".", "audio_file", "object", "by", "reading", "the", "audio", "file", "at", "self", ".", "audio_file_path_absolute", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/task.py#L229-L244
232,090
readbeyond/aeneas
aeneas/task.py
Task._populate_text_file
def _populate_text_file(self): """ Create the ``self.text_file`` object by reading the text file at ``self.text_file_path_absolute``. """ self.log(u"Populate text file...") if ( (self.text_file_path_absolute is not None) and (self.configuration["language"] is not None) ): # the following values might be None parameters = { gc.PPN_TASK_IS_TEXT_FILE_IGNORE_REGEX: self.configuration["i_t_ignore_regex"], gc.PPN_TASK_IS_TEXT_FILE_TRANSLITERATE_MAP: self.configuration["i_t_transliterate_map"], gc.PPN_TASK_IS_TEXT_MPLAIN_WORD_SEPARATOR: self.configuration["i_t_mplain_word_separator"], gc.PPN_TASK_IS_TEXT_MUNPARSED_L1_ID_REGEX: self.configuration["i_t_munparsed_l1_id_regex"], gc.PPN_TASK_IS_TEXT_MUNPARSED_L2_ID_REGEX: self.configuration["i_t_munparsed_l2_id_regex"], gc.PPN_TASK_IS_TEXT_MUNPARSED_L3_ID_REGEX: self.configuration["i_t_munparsed_l3_id_regex"], gc.PPN_TASK_IS_TEXT_UNPARSED_CLASS_REGEX: self.configuration["i_t_unparsed_class_regex"], gc.PPN_TASK_IS_TEXT_UNPARSED_ID_REGEX: self.configuration["i_t_unparsed_id_regex"], gc.PPN_TASK_IS_TEXT_UNPARSED_ID_SORT: self.configuration["i_t_unparsed_id_sort"], gc.PPN_TASK_OS_FILE_ID_REGEX: self.configuration["o_id_regex"] } self.text_file = TextFile( file_path=self.text_file_path_absolute, file_format=self.configuration["i_t_format"], parameters=parameters, logger=self.logger ) self.text_file.set_language(self.configuration["language"]) else: self.log(u"text_file_path_absolute and/or language is None") self.log(u"Populate text file... done")
python
def _populate_text_file(self): """ Create the ``self.text_file`` object by reading the text file at ``self.text_file_path_absolute``. """ self.log(u"Populate text file...") if ( (self.text_file_path_absolute is not None) and (self.configuration["language"] is not None) ): # the following values might be None parameters = { gc.PPN_TASK_IS_TEXT_FILE_IGNORE_REGEX: self.configuration["i_t_ignore_regex"], gc.PPN_TASK_IS_TEXT_FILE_TRANSLITERATE_MAP: self.configuration["i_t_transliterate_map"], gc.PPN_TASK_IS_TEXT_MPLAIN_WORD_SEPARATOR: self.configuration["i_t_mplain_word_separator"], gc.PPN_TASK_IS_TEXT_MUNPARSED_L1_ID_REGEX: self.configuration["i_t_munparsed_l1_id_regex"], gc.PPN_TASK_IS_TEXT_MUNPARSED_L2_ID_REGEX: self.configuration["i_t_munparsed_l2_id_regex"], gc.PPN_TASK_IS_TEXT_MUNPARSED_L3_ID_REGEX: self.configuration["i_t_munparsed_l3_id_regex"], gc.PPN_TASK_IS_TEXT_UNPARSED_CLASS_REGEX: self.configuration["i_t_unparsed_class_regex"], gc.PPN_TASK_IS_TEXT_UNPARSED_ID_REGEX: self.configuration["i_t_unparsed_id_regex"], gc.PPN_TASK_IS_TEXT_UNPARSED_ID_SORT: self.configuration["i_t_unparsed_id_sort"], gc.PPN_TASK_OS_FILE_ID_REGEX: self.configuration["o_id_regex"] } self.text_file = TextFile( file_path=self.text_file_path_absolute, file_format=self.configuration["i_t_format"], parameters=parameters, logger=self.logger ) self.text_file.set_language(self.configuration["language"]) else: self.log(u"text_file_path_absolute and/or language is None") self.log(u"Populate text file... done")
[ "def", "_populate_text_file", "(", "self", ")", ":", "self", ".", "log", "(", "u\"Populate text file...\"", ")", "if", "(", "(", "self", ".", "text_file_path_absolute", "is", "not", "None", ")", "and", "(", "self", ".", "configuration", "[", "\"language\"", "]", "is", "not", "None", ")", ")", ":", "# the following values might be None", "parameters", "=", "{", "gc", ".", "PPN_TASK_IS_TEXT_FILE_IGNORE_REGEX", ":", "self", ".", "configuration", "[", "\"i_t_ignore_regex\"", "]", ",", "gc", ".", "PPN_TASK_IS_TEXT_FILE_TRANSLITERATE_MAP", ":", "self", ".", "configuration", "[", "\"i_t_transliterate_map\"", "]", ",", "gc", ".", "PPN_TASK_IS_TEXT_MPLAIN_WORD_SEPARATOR", ":", "self", ".", "configuration", "[", "\"i_t_mplain_word_separator\"", "]", ",", "gc", ".", "PPN_TASK_IS_TEXT_MUNPARSED_L1_ID_REGEX", ":", "self", ".", "configuration", "[", "\"i_t_munparsed_l1_id_regex\"", "]", ",", "gc", ".", "PPN_TASK_IS_TEXT_MUNPARSED_L2_ID_REGEX", ":", "self", ".", "configuration", "[", "\"i_t_munparsed_l2_id_regex\"", "]", ",", "gc", ".", "PPN_TASK_IS_TEXT_MUNPARSED_L3_ID_REGEX", ":", "self", ".", "configuration", "[", "\"i_t_munparsed_l3_id_regex\"", "]", ",", "gc", ".", "PPN_TASK_IS_TEXT_UNPARSED_CLASS_REGEX", ":", "self", ".", "configuration", "[", "\"i_t_unparsed_class_regex\"", "]", ",", "gc", ".", "PPN_TASK_IS_TEXT_UNPARSED_ID_REGEX", ":", "self", ".", "configuration", "[", "\"i_t_unparsed_id_regex\"", "]", ",", "gc", ".", "PPN_TASK_IS_TEXT_UNPARSED_ID_SORT", ":", "self", ".", "configuration", "[", "\"i_t_unparsed_id_sort\"", "]", ",", "gc", ".", "PPN_TASK_OS_FILE_ID_REGEX", ":", "self", ".", "configuration", "[", "\"o_id_regex\"", "]", "}", "self", ".", "text_file", "=", "TextFile", "(", "file_path", "=", "self", ".", "text_file_path_absolute", ",", "file_format", "=", "self", ".", "configuration", "[", "\"i_t_format\"", "]", ",", "parameters", "=", "parameters", ",", "logger", "=", "self", ".", "logger", ")", "self", ".", "text_file", ".", "set_language", "(", "self", ".", "configuration", "[", "\"language\"", "]", ")", "else", ":", "self", ".", "log", "(", "u\"text_file_path_absolute and/or language is None\"", ")", "self", ".", "log", "(", "u\"Populate text file... done\"", ")" ]
Create the ``self.text_file`` object by reading the text file at ``self.text_file_path_absolute``.
[ "Create", "the", "self", ".", "text_file", "object", "by", "reading", "the", "text", "file", "at", "self", ".", "text_file_path_absolute", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/task.py#L246-L278
232,091
readbeyond/aeneas
aeneas/syncmap/smfgxml.py
SyncMapFormatGenericXML._tree_to_string
def _tree_to_string(cls, root_element, xml_declaration=True, pretty_print=True): """ Return an ``lxml`` tree as a Unicode string. """ from lxml import etree return gf.safe_unicode(etree.tostring( root_element, encoding="UTF-8", method="xml", xml_declaration=xml_declaration, pretty_print=pretty_print ))
python
def _tree_to_string(cls, root_element, xml_declaration=True, pretty_print=True): """ Return an ``lxml`` tree as a Unicode string. """ from lxml import etree return gf.safe_unicode(etree.tostring( root_element, encoding="UTF-8", method="xml", xml_declaration=xml_declaration, pretty_print=pretty_print ))
[ "def", "_tree_to_string", "(", "cls", ",", "root_element", ",", "xml_declaration", "=", "True", ",", "pretty_print", "=", "True", ")", ":", "from", "lxml", "import", "etree", "return", "gf", ".", "safe_unicode", "(", "etree", ".", "tostring", "(", "root_element", ",", "encoding", "=", "\"UTF-8\"", ",", "method", "=", "\"xml\"", ",", "xml_declaration", "=", "xml_declaration", ",", "pretty_print", "=", "pretty_print", ")", ")" ]
Return an ``lxml`` tree as a Unicode string.
[ "Return", "an", "lxml", "tree", "as", "a", "Unicode", "string", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/smfgxml.py#L63-L74
232,092
readbeyond/aeneas
aeneas/tools/abstract_cli_program.py
AbstractCLIProgram.print_generic
def print_generic(self, msg, prefix=None): """ Print a message and log it. :param msg: the message :type msg: Unicode string :param prefix: the (optional) prefix :type prefix: Unicode string """ if prefix is None: self._log(msg, Logger.INFO) else: self._log(msg, prefix) if self.use_sys: if (prefix is not None) and (prefix in self.PREFIX_TO_PRINT_FUNCTION): self.PREFIX_TO_PRINT_FUNCTION[prefix](msg) else: gf.safe_print(msg)
python
def print_generic(self, msg, prefix=None): """ Print a message and log it. :param msg: the message :type msg: Unicode string :param prefix: the (optional) prefix :type prefix: Unicode string """ if prefix is None: self._log(msg, Logger.INFO) else: self._log(msg, prefix) if self.use_sys: if (prefix is not None) and (prefix in self.PREFIX_TO_PRINT_FUNCTION): self.PREFIX_TO_PRINT_FUNCTION[prefix](msg) else: gf.safe_print(msg)
[ "def", "print_generic", "(", "self", ",", "msg", ",", "prefix", "=", "None", ")", ":", "if", "prefix", "is", "None", ":", "self", ".", "_log", "(", "msg", ",", "Logger", ".", "INFO", ")", "else", ":", "self", ".", "_log", "(", "msg", ",", "prefix", ")", "if", "self", ".", "use_sys", ":", "if", "(", "prefix", "is", "not", "None", ")", "and", "(", "prefix", "in", "self", ".", "PREFIX_TO_PRINT_FUNCTION", ")", ":", "self", ".", "PREFIX_TO_PRINT_FUNCTION", "[", "prefix", "]", "(", "msg", ")", "else", ":", "gf", ".", "safe_print", "(", "msg", ")" ]
Print a message and log it. :param msg: the message :type msg: Unicode string :param prefix: the (optional) prefix :type prefix: Unicode string
[ "Print", "a", "message", "and", "log", "it", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/abstract_cli_program.py#L109-L126
232,093
readbeyond/aeneas
aeneas/tools/abstract_cli_program.py
AbstractCLIProgram.print_name_version
def print_name_version(self): """ Print program name and version and exit. :rtype: int """ if self.use_sys: self.print_generic(u"%s v%s" % (self.NAME, aeneas_version)) return self.exit(self.HELP_EXIT_CODE)
python
def print_name_version(self): """ Print program name and version and exit. :rtype: int """ if self.use_sys: self.print_generic(u"%s v%s" % (self.NAME, aeneas_version)) return self.exit(self.HELP_EXIT_CODE)
[ "def", "print_name_version", "(", "self", ")", ":", "if", "self", ".", "use_sys", ":", "self", ".", "print_generic", "(", "u\"%s v%s\"", "%", "(", "self", ".", "NAME", ",", "aeneas_version", ")", ")", "return", "self", ".", "exit", "(", "self", ".", "HELP_EXIT_CODE", ")" ]
Print program name and version and exit. :rtype: int
[ "Print", "program", "name", "and", "version", "and", "exit", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/abstract_cli_program.py#L260-L268
232,094
readbeyond/aeneas
aeneas/tools/abstract_cli_program.py
AbstractCLIProgram.print_rconf_parameters
def print_rconf_parameters(self): """ Print the list of runtime configuration parameters and exit. """ if self.use_sys: self.print_info(u"Available runtime configuration parameters:") self.print_generic(u"\n" + u"\n".join(self.RCONF_PARAMETERS) + u"\n") return self.exit(self.HELP_EXIT_CODE)
python
def print_rconf_parameters(self): """ Print the list of runtime configuration parameters and exit. """ if self.use_sys: self.print_info(u"Available runtime configuration parameters:") self.print_generic(u"\n" + u"\n".join(self.RCONF_PARAMETERS) + u"\n") return self.exit(self.HELP_EXIT_CODE)
[ "def", "print_rconf_parameters", "(", "self", ")", ":", "if", "self", ".", "use_sys", ":", "self", ".", "print_info", "(", "u\"Available runtime configuration parameters:\"", ")", "self", ".", "print_generic", "(", "u\"\\n\"", "+", "u\"\\n\"", ".", "join", "(", "self", ".", "RCONF_PARAMETERS", ")", "+", "u\"\\n\"", ")", "return", "self", ".", "exit", "(", "self", ".", "HELP_EXIT_CODE", ")" ]
Print the list of runtime configuration parameters and exit.
[ "Print", "the", "list", "of", "runtime", "configuration", "parameters", "and", "exit", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/abstract_cli_program.py#L270-L277
232,095
readbeyond/aeneas
aeneas/tools/abstract_cli_program.py
AbstractCLIProgram.has_option
def has_option(self, target): """ Return ``True`` if the actual arguments include the specified ``target`` option or, if ``target`` is a list of options, at least one of them. :param target: the option or a list of options :type target: Unicode string or list of Unicode strings :rtype: bool """ if isinstance(target, list): target_set = set(target) else: target_set = set([target]) return len(target_set & set(self.actual_arguments)) > 0
python
def has_option(self, target): """ Return ``True`` if the actual arguments include the specified ``target`` option or, if ``target`` is a list of options, at least one of them. :param target: the option or a list of options :type target: Unicode string or list of Unicode strings :rtype: bool """ if isinstance(target, list): target_set = set(target) else: target_set = set([target]) return len(target_set & set(self.actual_arguments)) > 0
[ "def", "has_option", "(", "self", ",", "target", ")", ":", "if", "isinstance", "(", "target", ",", "list", ")", ":", "target_set", "=", "set", "(", "target", ")", "else", ":", "target_set", "=", "set", "(", "[", "target", "]", ")", "return", "len", "(", "target_set", "&", "set", "(", "self", ".", "actual_arguments", ")", ")", ">", "0" ]
Return ``True`` if the actual arguments include the specified ``target`` option or, if ``target`` is a list of options, at least one of them. :param target: the option or a list of options :type target: Unicode string or list of Unicode strings :rtype: bool
[ "Return", "True", "if", "the", "actual", "arguments", "include", "the", "specified", "target", "option", "or", "if", "target", "is", "a", "list", "of", "options", "at", "least", "one", "of", "them", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/abstract_cli_program.py#L387-L402
232,096
readbeyond/aeneas
aeneas/tools/abstract_cli_program.py
AbstractCLIProgram.check_c_extensions
def check_c_extensions(self, name=None): """ If C extensions cannot be run, emit a warning and return ``False``. Otherwise return ``True``. If ``name`` is not ``None``, check just the C extension with that name. :param name: the name of the Python C extension to test :type name: string :rtype: bool """ if not gf.can_run_c_extension(name=name): if name is None: self.print_warning(u"Unable to load Python C Extensions") else: self.print_warning(u"Unable to load Python C Extension %s" % (name)) self.print_warning(u"Running the slower pure Python code") self.print_warning(u"See the documentation for directions to compile the Python C Extensions") return False return True
python
def check_c_extensions(self, name=None): """ If C extensions cannot be run, emit a warning and return ``False``. Otherwise return ``True``. If ``name`` is not ``None``, check just the C extension with that name. :param name: the name of the Python C extension to test :type name: string :rtype: bool """ if not gf.can_run_c_extension(name=name): if name is None: self.print_warning(u"Unable to load Python C Extensions") else: self.print_warning(u"Unable to load Python C Extension %s" % (name)) self.print_warning(u"Running the slower pure Python code") self.print_warning(u"See the documentation for directions to compile the Python C Extensions") return False return True
[ "def", "check_c_extensions", "(", "self", ",", "name", "=", "None", ")", ":", "if", "not", "gf", ".", "can_run_c_extension", "(", "name", "=", "name", ")", ":", "if", "name", "is", "None", ":", "self", ".", "print_warning", "(", "u\"Unable to load Python C Extensions\"", ")", "else", ":", "self", ".", "print_warning", "(", "u\"Unable to load Python C Extension %s\"", "%", "(", "name", ")", ")", "self", ".", "print_warning", "(", "u\"Running the slower pure Python code\"", ")", "self", ".", "print_warning", "(", "u\"See the documentation for directions to compile the Python C Extensions\"", ")", "return", "False", "return", "True" ]
If C extensions cannot be run, emit a warning and return ``False``. Otherwise return ``True``. If ``name`` is not ``None``, check just the C extension with that name. :param name: the name of the Python C extension to test :type name: string :rtype: bool
[ "If", "C", "extensions", "cannot", "be", "run", "emit", "a", "warning", "and", "return", "False", ".", "Otherwise", "return", "True", ".", "If", "name", "is", "not", "None", "check", "just", "the", "C", "extension", "with", "that", "name", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/abstract_cli_program.py#L437-L456
232,097
readbeyond/aeneas
aeneas/tools/abstract_cli_program.py
AbstractCLIProgram.check_output_file
def check_output_file(self, path): """ If the given path cannot be written, emit an error and return ``False``. Otherwise return ``True``. :param path: the path of the output file :type path: string (path) :rtype: bool """ if not gf.file_can_be_written(path): self.print_error(u"Unable to create file '%s'" % (path)) self.print_error(u"Make sure the file path is written/escaped correctly and that you have write permission on it") return False return True
python
def check_output_file(self, path): """ If the given path cannot be written, emit an error and return ``False``. Otherwise return ``True``. :param path: the path of the output file :type path: string (path) :rtype: bool """ if not gf.file_can_be_written(path): self.print_error(u"Unable to create file '%s'" % (path)) self.print_error(u"Make sure the file path is written/escaped correctly and that you have write permission on it") return False return True
[ "def", "check_output_file", "(", "self", ",", "path", ")", ":", "if", "not", "gf", ".", "file_can_be_written", "(", "path", ")", ":", "self", ".", "print_error", "(", "u\"Unable to create file '%s'\"", "%", "(", "path", ")", ")", "self", ".", "print_error", "(", "u\"Make sure the file path is written/escaped correctly and that you have write permission on it\"", ")", "return", "False", "return", "True" ]
If the given path cannot be written, emit an error and return ``False``. Otherwise return ``True``. :param path: the path of the output file :type path: string (path) :rtype: bool
[ "If", "the", "given", "path", "cannot", "be", "written", "emit", "an", "error", "and", "return", "False", ".", "Otherwise", "return", "True", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/abstract_cli_program.py#L488-L501
232,098
readbeyond/aeneas
aeneas/tools/abstract_cli_program.py
AbstractCLIProgram.check_output_directory
def check_output_directory(self, path): """ If the given directory cannot be written, emit an error and return ``False``. Otherwise return ``True``. :param path: the path of the output directory :type path: string (path) :rtype: bool """ if not os.path.isdir(path): self.print_error(u"Directory '%s' does not exist" % (path)) return False test_file = os.path.join(path, u"file.test") if not gf.file_can_be_written(test_file): self.print_error(u"Unable to write inside directory '%s'" % (path)) self.print_error(u"Make sure the directory path is written/escaped correctly and that you have write permission on it") return False return True
python
def check_output_directory(self, path): """ If the given directory cannot be written, emit an error and return ``False``. Otherwise return ``True``. :param path: the path of the output directory :type path: string (path) :rtype: bool """ if not os.path.isdir(path): self.print_error(u"Directory '%s' does not exist" % (path)) return False test_file = os.path.join(path, u"file.test") if not gf.file_can_be_written(test_file): self.print_error(u"Unable to write inside directory '%s'" % (path)) self.print_error(u"Make sure the directory path is written/escaped correctly and that you have write permission on it") return False return True
[ "def", "check_output_directory", "(", "self", ",", "path", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "self", ".", "print_error", "(", "u\"Directory '%s' does not exist\"", "%", "(", "path", ")", ")", "return", "False", "test_file", "=", "os", ".", "path", ".", "join", "(", "path", ",", "u\"file.test\"", ")", "if", "not", "gf", ".", "file_can_be_written", "(", "test_file", ")", ":", "self", ".", "print_error", "(", "u\"Unable to write inside directory '%s'\"", "%", "(", "path", ")", ")", "self", ".", "print_error", "(", "u\"Make sure the directory path is written/escaped correctly and that you have write permission on it\"", ")", "return", "False", "return", "True" ]
If the given directory cannot be written, emit an error and return ``False``. Otherwise return ``True``. :param path: the path of the output directory :type path: string (path) :rtype: bool
[ "If", "the", "given", "directory", "cannot", "be", "written", "emit", "an", "error", "and", "return", "False", ".", "Otherwise", "return", "True", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/abstract_cli_program.py#L503-L520
232,099
readbeyond/aeneas
aeneas/container.py
Container.is_safe
def is_safe(self): """ Return ``True`` if the container can be safely extracted, that is, if all its entries are safe, ``False`` otherwise. :rtype: bool :raises: same as :func:`~aeneas.container.Container.entries` """ self.log(u"Checking if this container is safe") for entry in self.entries: if not self.is_entry_safe(entry): self.log([u"This container is not safe: found unsafe entry '%s'", entry]) return False self.log(u"This container is safe") return True
python
def is_safe(self): """ Return ``True`` if the container can be safely extracted, that is, if all its entries are safe, ``False`` otherwise. :rtype: bool :raises: same as :func:`~aeneas.container.Container.entries` """ self.log(u"Checking if this container is safe") for entry in self.entries: if not self.is_entry_safe(entry): self.log([u"This container is not safe: found unsafe entry '%s'", entry]) return False self.log(u"This container is safe") return True
[ "def", "is_safe", "(", "self", ")", ":", "self", ".", "log", "(", "u\"Checking if this container is safe\"", ")", "for", "entry", "in", "self", ".", "entries", ":", "if", "not", "self", ".", "is_entry_safe", "(", "entry", ")", ":", "self", ".", "log", "(", "[", "u\"This container is not safe: found unsafe entry '%s'\"", ",", "entry", "]", ")", "return", "False", "self", ".", "log", "(", "u\"This container is safe\"", ")", "return", "True" ]
Return ``True`` if the container can be safely extracted, that is, if all its entries are safe, ``False`` otherwise. :rtype: bool :raises: same as :func:`~aeneas.container.Container.entries`
[ "Return", "True", "if", "the", "container", "can", "be", "safely", "extracted", "that", "is", "if", "all", "its", "entries", "are", "safe", "False", "otherwise", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/container.py#L186-L200