prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>py_choose.py<|end_file_name|><|fim▁begin|> #<pycode(py_choose)> class Choose: """ Choose - class for choose() with callbacks """ def __init__(self, list, title, flags=0, deflt=1, icon=37): self.list = list self.title = title self.flags = flags self.x0 = -1 self.x1 = -1 self.y0 = -1 self.y1 = -1 self.width = -1 self.deflt = deflt self.icon = icon # HACK: Add a circular reference for non-modal choosers. This prevents the GC # from collecting the class object the callbacks need. Unfortunately this means # that the class will never be collected, unless refhack is set to None explicitly. if (flags & Choose2.CH_MODAL) == 0: self.refhack = self def sizer(self): """ Callback: sizer - returns the length of the list """ return len(self.list) def getl(self, n): """ Callback: getl - get one item from the list """ if n == 0: return self.title if n <= self.sizer(): return str(self.list[n-1]) else: return "<Empty>" def ins(self): pass def update(self, n): pass def edit(self, n): pass def enter(self, n): print "enter(%d) called" % n def destroy(self): pass def get_icon(self, n): <|fim_middle|> def choose(self): """ choose - Display the choose dialogue """ old = set_script_timeout(0) n = _idaapi.choose_choose( self, self.flags, self.x0, self.y0, self.x1, self.y1, self.width, self.deflt, self.icon) set_script_timeout(old) return n #</pycode(py_choose)> <|fim▁end|>
pass
<|file_name|>py_choose.py<|end_file_name|><|fim▁begin|> #<pycode(py_choose)> class Choose: """ Choose - class for choose() with callbacks """ def __init__(self, list, title, flags=0, deflt=1, icon=37): self.list = list self.title = title self.flags = flags self.x0 = -1 self.x1 = -1 self.y0 = -1 self.y1 = -1 self.width = -1 self.deflt = deflt self.icon = icon # HACK: Add a circular reference for non-modal choosers. This prevents the GC # from collecting the class object the callbacks need. Unfortunately this means # that the class will never be collected, unless refhack is set to None explicitly. if (flags & Choose2.CH_MODAL) == 0: self.refhack = self def sizer(self): """ Callback: sizer - returns the length of the list """ return len(self.list) def getl(self, n): """ Callback: getl - get one item from the list """ if n == 0: return self.title if n <= self.sizer(): return str(self.list[n-1]) else: return "<Empty>" def ins(self): pass def update(self, n): pass def edit(self, n): pass def enter(self, n): print "enter(%d) called" % n def destroy(self): pass def get_icon(self, n): pass def choose(self): <|fim_middle|> #</pycode(py_choose)> <|fim▁end|>
""" choose - Display the choose dialogue """ old = set_script_timeout(0) n = _idaapi.choose_choose( self, self.flags, self.x0, self.y0, self.x1, self.y1, self.width, self.deflt, self.icon) set_script_timeout(old) return n
<|file_name|>py_choose.py<|end_file_name|><|fim▁begin|> #<pycode(py_choose)> class Choose: """ Choose - class for choose() with callbacks """ def __init__(self, list, title, flags=0, deflt=1, icon=37): self.list = list self.title = title self.flags = flags self.x0 = -1 self.x1 = -1 self.y0 = -1 self.y1 = -1 self.width = -1 self.deflt = deflt self.icon = icon # HACK: Add a circular reference for non-modal choosers. This prevents the GC # from collecting the class object the callbacks need. Unfortunately this means # that the class will never be collected, unless refhack is set to None explicitly. if (flags & Choose2.CH_MODAL) == 0: <|fim_middle|> def sizer(self): """ Callback: sizer - returns the length of the list """ return len(self.list) def getl(self, n): """ Callback: getl - get one item from the list """ if n == 0: return self.title if n <= self.sizer(): return str(self.list[n-1]) else: return "<Empty>" def ins(self): pass def update(self, n): pass def edit(self, n): pass def enter(self, n): print "enter(%d) called" % n def destroy(self): pass def get_icon(self, n): pass def choose(self): """ choose - Display the choose dialogue """ old = set_script_timeout(0) n = _idaapi.choose_choose( self, self.flags, self.x0, self.y0, self.x1, self.y1, self.width, self.deflt, self.icon) set_script_timeout(old) return n #</pycode(py_choose)> <|fim▁end|>
self.refhack = self
<|file_name|>py_choose.py<|end_file_name|><|fim▁begin|> #<pycode(py_choose)> class Choose: """ Choose - class for choose() with callbacks """ def __init__(self, list, title, flags=0, deflt=1, icon=37): self.list = list self.title = title self.flags = flags self.x0 = -1 self.x1 = -1 self.y0 = -1 self.y1 = -1 self.width = -1 self.deflt = deflt self.icon = icon # HACK: Add a circular reference for non-modal choosers. This prevents the GC # from collecting the class object the callbacks need. Unfortunately this means # that the class will never be collected, unless refhack is set to None explicitly. if (flags & Choose2.CH_MODAL) == 0: self.refhack = self def sizer(self): """ Callback: sizer - returns the length of the list """ return len(self.list) def getl(self, n): """ Callback: getl - get one item from the list """ if n == 0: <|fim_middle|> if n <= self.sizer(): return str(self.list[n-1]) else: return "<Empty>" def ins(self): pass def update(self, n): pass def edit(self, n): pass def enter(self, n): print "enter(%d) called" % n def destroy(self): pass def get_icon(self, n): pass def choose(self): """ choose - Display the choose dialogue """ old = set_script_timeout(0) n = _idaapi.choose_choose( self, self.flags, self.x0, self.y0, self.x1, self.y1, self.width, self.deflt, self.icon) set_script_timeout(old) return n #</pycode(py_choose)> <|fim▁end|>
return self.title
<|file_name|>py_choose.py<|end_file_name|><|fim▁begin|> #<pycode(py_choose)> class Choose: """ Choose - class for choose() with callbacks """ def __init__(self, list, title, flags=0, deflt=1, icon=37): self.list = list self.title = title self.flags = flags self.x0 = -1 self.x1 = -1 self.y0 = -1 self.y1 = -1 self.width = -1 self.deflt = deflt self.icon = icon # HACK: Add a circular reference for non-modal choosers. This prevents the GC # from collecting the class object the callbacks need. Unfortunately this means # that the class will never be collected, unless refhack is set to None explicitly. if (flags & Choose2.CH_MODAL) == 0: self.refhack = self def sizer(self): """ Callback: sizer - returns the length of the list """ return len(self.list) def getl(self, n): """ Callback: getl - get one item from the list """ if n == 0: return self.title if n <= self.sizer(): <|fim_middle|> else: return "<Empty>" def ins(self): pass def update(self, n): pass def edit(self, n): pass def enter(self, n): print "enter(%d) called" % n def destroy(self): pass def get_icon(self, n): pass def choose(self): """ choose - Display the choose dialogue """ old = set_script_timeout(0) n = _idaapi.choose_choose( self, self.flags, self.x0, self.y0, self.x1, self.y1, self.width, self.deflt, self.icon) set_script_timeout(old) return n #</pycode(py_choose)> <|fim▁end|>
return str(self.list[n-1])
<|file_name|>py_choose.py<|end_file_name|><|fim▁begin|> #<pycode(py_choose)> class Choose: """ Choose - class for choose() with callbacks """ def __init__(self, list, title, flags=0, deflt=1, icon=37): self.list = list self.title = title self.flags = flags self.x0 = -1 self.x1 = -1 self.y0 = -1 self.y1 = -1 self.width = -1 self.deflt = deflt self.icon = icon # HACK: Add a circular reference for non-modal choosers. This prevents the GC # from collecting the class object the callbacks need. Unfortunately this means # that the class will never be collected, unless refhack is set to None explicitly. if (flags & Choose2.CH_MODAL) == 0: self.refhack = self def sizer(self): """ Callback: sizer - returns the length of the list """ return len(self.list) def getl(self, n): """ Callback: getl - get one item from the list """ if n == 0: return self.title if n <= self.sizer(): return str(self.list[n-1]) else: <|fim_middle|> def ins(self): pass def update(self, n): pass def edit(self, n): pass def enter(self, n): print "enter(%d) called" % n def destroy(self): pass def get_icon(self, n): pass def choose(self): """ choose - Display the choose dialogue """ old = set_script_timeout(0) n = _idaapi.choose_choose( self, self.flags, self.x0, self.y0, self.x1, self.y1, self.width, self.deflt, self.icon) set_script_timeout(old) return n #</pycode(py_choose)> <|fim▁end|>
return "<Empty>"
<|file_name|>py_choose.py<|end_file_name|><|fim▁begin|> #<pycode(py_choose)> class Choose: """ Choose - class for choose() with callbacks """ def <|fim_middle|>(self, list, title, flags=0, deflt=1, icon=37): self.list = list self.title = title self.flags = flags self.x0 = -1 self.x1 = -1 self.y0 = -1 self.y1 = -1 self.width = -1 self.deflt = deflt self.icon = icon # HACK: Add a circular reference for non-modal choosers. This prevents the GC # from collecting the class object the callbacks need. Unfortunately this means # that the class will never be collected, unless refhack is set to None explicitly. if (flags & Choose2.CH_MODAL) == 0: self.refhack = self def sizer(self): """ Callback: sizer - returns the length of the list """ return len(self.list) def getl(self, n): """ Callback: getl - get one item from the list """ if n == 0: return self.title if n <= self.sizer(): return str(self.list[n-1]) else: return "<Empty>" def ins(self): pass def update(self, n): pass def edit(self, n): pass def enter(self, n): print "enter(%d) called" % n def destroy(self): pass def get_icon(self, n): pass def choose(self): """ choose - Display the choose dialogue """ old = set_script_timeout(0) n = _idaapi.choose_choose( self, self.flags, self.x0, self.y0, self.x1, self.y1, self.width, self.deflt, self.icon) set_script_timeout(old) return n #</pycode(py_choose)> <|fim▁end|>
__init__
<|file_name|>py_choose.py<|end_file_name|><|fim▁begin|> #<pycode(py_choose)> class Choose: """ Choose - class for choose() with callbacks """ def __init__(self, list, title, flags=0, deflt=1, icon=37): self.list = list self.title = title self.flags = flags self.x0 = -1 self.x1 = -1 self.y0 = -1 self.y1 = -1 self.width = -1 self.deflt = deflt self.icon = icon # HACK: Add a circular reference for non-modal choosers. This prevents the GC # from collecting the class object the callbacks need. Unfortunately this means # that the class will never be collected, unless refhack is set to None explicitly. if (flags & Choose2.CH_MODAL) == 0: self.refhack = self def <|fim_middle|>(self): """ Callback: sizer - returns the length of the list """ return len(self.list) def getl(self, n): """ Callback: getl - get one item from the list """ if n == 0: return self.title if n <= self.sizer(): return str(self.list[n-1]) else: return "<Empty>" def ins(self): pass def update(self, n): pass def edit(self, n): pass def enter(self, n): print "enter(%d) called" % n def destroy(self): pass def get_icon(self, n): pass def choose(self): """ choose - Display the choose dialogue """ old = set_script_timeout(0) n = _idaapi.choose_choose( self, self.flags, self.x0, self.y0, self.x1, self.y1, self.width, self.deflt, self.icon) set_script_timeout(old) return n #</pycode(py_choose)> <|fim▁end|>
sizer
<|file_name|>py_choose.py<|end_file_name|><|fim▁begin|> #<pycode(py_choose)> class Choose: """ Choose - class for choose() with callbacks """ def __init__(self, list, title, flags=0, deflt=1, icon=37): self.list = list self.title = title self.flags = flags self.x0 = -1 self.x1 = -1 self.y0 = -1 self.y1 = -1 self.width = -1 self.deflt = deflt self.icon = icon # HACK: Add a circular reference for non-modal choosers. This prevents the GC # from collecting the class object the callbacks need. Unfortunately this means # that the class will never be collected, unless refhack is set to None explicitly. if (flags & Choose2.CH_MODAL) == 0: self.refhack = self def sizer(self): """ Callback: sizer - returns the length of the list """ return len(self.list) def <|fim_middle|>(self, n): """ Callback: getl - get one item from the list """ if n == 0: return self.title if n <= self.sizer(): return str(self.list[n-1]) else: return "<Empty>" def ins(self): pass def update(self, n): pass def edit(self, n): pass def enter(self, n): print "enter(%d) called" % n def destroy(self): pass def get_icon(self, n): pass def choose(self): """ choose - Display the choose dialogue """ old = set_script_timeout(0) n = _idaapi.choose_choose( self, self.flags, self.x0, self.y0, self.x1, self.y1, self.width, self.deflt, self.icon) set_script_timeout(old) return n #</pycode(py_choose)> <|fim▁end|>
getl
<|file_name|>py_choose.py<|end_file_name|><|fim▁begin|> #<pycode(py_choose)> class Choose: """ Choose - class for choose() with callbacks """ def __init__(self, list, title, flags=0, deflt=1, icon=37): self.list = list self.title = title self.flags = flags self.x0 = -1 self.x1 = -1 self.y0 = -1 self.y1 = -1 self.width = -1 self.deflt = deflt self.icon = icon # HACK: Add a circular reference for non-modal choosers. This prevents the GC # from collecting the class object the callbacks need. Unfortunately this means # that the class will never be collected, unless refhack is set to None explicitly. if (flags & Choose2.CH_MODAL) == 0: self.refhack = self def sizer(self): """ Callback: sizer - returns the length of the list """ return len(self.list) def getl(self, n): """ Callback: getl - get one item from the list """ if n == 0: return self.title if n <= self.sizer(): return str(self.list[n-1]) else: return "<Empty>" def <|fim_middle|>(self): pass def update(self, n): pass def edit(self, n): pass def enter(self, n): print "enter(%d) called" % n def destroy(self): pass def get_icon(self, n): pass def choose(self): """ choose - Display the choose dialogue """ old = set_script_timeout(0) n = _idaapi.choose_choose( self, self.flags, self.x0, self.y0, self.x1, self.y1, self.width, self.deflt, self.icon) set_script_timeout(old) return n #</pycode(py_choose)> <|fim▁end|>
ins
<|file_name|>py_choose.py<|end_file_name|><|fim▁begin|> #<pycode(py_choose)> class Choose: """ Choose - class for choose() with callbacks """ def __init__(self, list, title, flags=0, deflt=1, icon=37): self.list = list self.title = title self.flags = flags self.x0 = -1 self.x1 = -1 self.y0 = -1 self.y1 = -1 self.width = -1 self.deflt = deflt self.icon = icon # HACK: Add a circular reference for non-modal choosers. This prevents the GC # from collecting the class object the callbacks need. Unfortunately this means # that the class will never be collected, unless refhack is set to None explicitly. if (flags & Choose2.CH_MODAL) == 0: self.refhack = self def sizer(self): """ Callback: sizer - returns the length of the list """ return len(self.list) def getl(self, n): """ Callback: getl - get one item from the list """ if n == 0: return self.title if n <= self.sizer(): return str(self.list[n-1]) else: return "<Empty>" def ins(self): pass def <|fim_middle|>(self, n): pass def edit(self, n): pass def enter(self, n): print "enter(%d) called" % n def destroy(self): pass def get_icon(self, n): pass def choose(self): """ choose - Display the choose dialogue """ old = set_script_timeout(0) n = _idaapi.choose_choose( self, self.flags, self.x0, self.y0, self.x1, self.y1, self.width, self.deflt, self.icon) set_script_timeout(old) return n #</pycode(py_choose)> <|fim▁end|>
update
<|file_name|>py_choose.py<|end_file_name|><|fim▁begin|> #<pycode(py_choose)> class Choose: """ Choose - class for choose() with callbacks """ def __init__(self, list, title, flags=0, deflt=1, icon=37): self.list = list self.title = title self.flags = flags self.x0 = -1 self.x1 = -1 self.y0 = -1 self.y1 = -1 self.width = -1 self.deflt = deflt self.icon = icon # HACK: Add a circular reference for non-modal choosers. This prevents the GC # from collecting the class object the callbacks need. Unfortunately this means # that the class will never be collected, unless refhack is set to None explicitly. if (flags & Choose2.CH_MODAL) == 0: self.refhack = self def sizer(self): """ Callback: sizer - returns the length of the list """ return len(self.list) def getl(self, n): """ Callback: getl - get one item from the list """ if n == 0: return self.title if n <= self.sizer(): return str(self.list[n-1]) else: return "<Empty>" def ins(self): pass def update(self, n): pass def <|fim_middle|>(self, n): pass def enter(self, n): print "enter(%d) called" % n def destroy(self): pass def get_icon(self, n): pass def choose(self): """ choose - Display the choose dialogue """ old = set_script_timeout(0) n = _idaapi.choose_choose( self, self.flags, self.x0, self.y0, self.x1, self.y1, self.width, self.deflt, self.icon) set_script_timeout(old) return n #</pycode(py_choose)> <|fim▁end|>
edit
<|file_name|>py_choose.py<|end_file_name|><|fim▁begin|> #<pycode(py_choose)> class Choose: """ Choose - class for choose() with callbacks """ def __init__(self, list, title, flags=0, deflt=1, icon=37): self.list = list self.title = title self.flags = flags self.x0 = -1 self.x1 = -1 self.y0 = -1 self.y1 = -1 self.width = -1 self.deflt = deflt self.icon = icon # HACK: Add a circular reference for non-modal choosers. This prevents the GC # from collecting the class object the callbacks need. Unfortunately this means # that the class will never be collected, unless refhack is set to None explicitly. if (flags & Choose2.CH_MODAL) == 0: self.refhack = self def sizer(self): """ Callback: sizer - returns the length of the list """ return len(self.list) def getl(self, n): """ Callback: getl - get one item from the list """ if n == 0: return self.title if n <= self.sizer(): return str(self.list[n-1]) else: return "<Empty>" def ins(self): pass def update(self, n): pass def edit(self, n): pass def <|fim_middle|>(self, n): print "enter(%d) called" % n def destroy(self): pass def get_icon(self, n): pass def choose(self): """ choose - Display the choose dialogue """ old = set_script_timeout(0) n = _idaapi.choose_choose( self, self.flags, self.x0, self.y0, self.x1, self.y1, self.width, self.deflt, self.icon) set_script_timeout(old) return n #</pycode(py_choose)> <|fim▁end|>
enter
<|file_name|>py_choose.py<|end_file_name|><|fim▁begin|> #<pycode(py_choose)> class Choose: """ Choose - class for choose() with callbacks """ def __init__(self, list, title, flags=0, deflt=1, icon=37): self.list = list self.title = title self.flags = flags self.x0 = -1 self.x1 = -1 self.y0 = -1 self.y1 = -1 self.width = -1 self.deflt = deflt self.icon = icon # HACK: Add a circular reference for non-modal choosers. This prevents the GC # from collecting the class object the callbacks need. Unfortunately this means # that the class will never be collected, unless refhack is set to None explicitly. if (flags & Choose2.CH_MODAL) == 0: self.refhack = self def sizer(self): """ Callback: sizer - returns the length of the list """ return len(self.list) def getl(self, n): """ Callback: getl - get one item from the list """ if n == 0: return self.title if n <= self.sizer(): return str(self.list[n-1]) else: return "<Empty>" def ins(self): pass def update(self, n): pass def edit(self, n): pass def enter(self, n): print "enter(%d) called" % n def <|fim_middle|>(self): pass def get_icon(self, n): pass def choose(self): """ choose - Display the choose dialogue """ old = set_script_timeout(0) n = _idaapi.choose_choose( self, self.flags, self.x0, self.y0, self.x1, self.y1, self.width, self.deflt, self.icon) set_script_timeout(old) return n #</pycode(py_choose)> <|fim▁end|>
destroy
<|file_name|>py_choose.py<|end_file_name|><|fim▁begin|> #<pycode(py_choose)> class Choose: """ Choose - class for choose() with callbacks """ def __init__(self, list, title, flags=0, deflt=1, icon=37): self.list = list self.title = title self.flags = flags self.x0 = -1 self.x1 = -1 self.y0 = -1 self.y1 = -1 self.width = -1 self.deflt = deflt self.icon = icon # HACK: Add a circular reference for non-modal choosers. This prevents the GC # from collecting the class object the callbacks need. Unfortunately this means # that the class will never be collected, unless refhack is set to None explicitly. if (flags & Choose2.CH_MODAL) == 0: self.refhack = self def sizer(self): """ Callback: sizer - returns the length of the list """ return len(self.list) def getl(self, n): """ Callback: getl - get one item from the list """ if n == 0: return self.title if n <= self.sizer(): return str(self.list[n-1]) else: return "<Empty>" def ins(self): pass def update(self, n): pass def edit(self, n): pass def enter(self, n): print "enter(%d) called" % n def destroy(self): pass def <|fim_middle|>(self, n): pass def choose(self): """ choose - Display the choose dialogue """ old = set_script_timeout(0) n = _idaapi.choose_choose( self, self.flags, self.x0, self.y0, self.x1, self.y1, self.width, self.deflt, self.icon) set_script_timeout(old) return n #</pycode(py_choose)> <|fim▁end|>
get_icon
<|file_name|>py_choose.py<|end_file_name|><|fim▁begin|> #<pycode(py_choose)> class Choose: """ Choose - class for choose() with callbacks """ def __init__(self, list, title, flags=0, deflt=1, icon=37): self.list = list self.title = title self.flags = flags self.x0 = -1 self.x1 = -1 self.y0 = -1 self.y1 = -1 self.width = -1 self.deflt = deflt self.icon = icon # HACK: Add a circular reference for non-modal choosers. This prevents the GC # from collecting the class object the callbacks need. Unfortunately this means # that the class will never be collected, unless refhack is set to None explicitly. if (flags & Choose2.CH_MODAL) == 0: self.refhack = self def sizer(self): """ Callback: sizer - returns the length of the list """ return len(self.list) def getl(self, n): """ Callback: getl - get one item from the list """ if n == 0: return self.title if n <= self.sizer(): return str(self.list[n-1]) else: return "<Empty>" def ins(self): pass def update(self, n): pass def edit(self, n): pass def enter(self, n): print "enter(%d) called" % n def destroy(self): pass def get_icon(self, n): pass def <|fim_middle|>(self): """ choose - Display the choose dialogue """ old = set_script_timeout(0) n = _idaapi.choose_choose( self, self.flags, self.x0, self.y0, self.x1, self.y1, self.width, self.deflt, self.icon) set_script_timeout(old) return n #</pycode(py_choose)> <|fim▁end|>
choose
<|file_name|>0004_auto_20151003_2033.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations <|fim▁hole|> dependencies = [ ('organizations', '0002_migrate_locations_to_facilities'), ('notifications', '0003_auto_20150912_2049'), ] operations = [ migrations.AlterField( model_name='notification', name='location', field=models.ForeignKey(verbose_name='facility', to='organizations.Facility'), ), migrations.RenameField( model_name='notification', old_name='location', new_name='facility', ), migrations.AlterField( model_name='notification', name='facility', field=models.ForeignKey(to='organizations.Facility'), ), ]<|fim▁end|>
class Migration(migrations.Migration):
<|file_name|>0004_auto_20151003_2033.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): <|fim_middle|> <|fim▁end|>
dependencies = [ ('organizations', '0002_migrate_locations_to_facilities'), ('notifications', '0003_auto_20150912_2049'), ] operations = [ migrations.AlterField( model_name='notification', name='location', field=models.ForeignKey(verbose_name='facility', to='organizations.Facility'), ), migrations.RenameField( model_name='notification', old_name='location', new_name='facility', ), migrations.AlterField( model_name='notification', name='facility', field=models.ForeignKey(to='organizations.Facility'), ), ]
<|file_name|>models.py<|end_file_name|><|fim▁begin|>#coding=utf-8 from django.db import models from django.contrib.auth.models import User class Activity(models.Model): owner = models.ForeignKey(User, null=False)<|fim▁hole|> activity = models.ForeignKey(Activity, null=False) description = models.TextField() photo = models.ImageField()<|fim▁end|>
text = models.CharField(max_length=20, unique=True) class Dessert(models.Model):
<|file_name|>models.py<|end_file_name|><|fim▁begin|>#coding=utf-8 from django.db import models from django.contrib.auth.models import User class Activity(models.Model): <|fim_middle|> class Dessert(models.Model): activity = models.ForeignKey(Activity, null=False) description = models.TextField() photo = models.ImageField() <|fim▁end|>
owner = models.ForeignKey(User, null=False) text = models.CharField(max_length=20, unique=True)
<|file_name|>models.py<|end_file_name|><|fim▁begin|>#coding=utf-8 from django.db import models from django.contrib.auth.models import User class Activity(models.Model): owner = models.ForeignKey(User, null=False) text = models.CharField(max_length=20, unique=True) class Dessert(models.Model): <|fim_middle|> <|fim▁end|>
activity = models.ForeignKey(Activity, null=False) description = models.TextField() photo = models.ImageField()
<|file_name|>ex1.py<|end_file_name|><|fim▁begin|><|fim▁hole|>import pandas as pd adv = pd.read_csv('Advertising.csv') tv_budget_x = adv.TV.tolist() print(tv_budget_x)<|fim▁end|>
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError:<|fim▁hole|> mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks)<|fim▁end|>
os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError):
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths <|fim_middle|> def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources)
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): <|fim_middle|> def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile])
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): <|fim_middle|> def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ])
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): <|fim_middle|> def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources)
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): <|fim_middle|> def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile)
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): <|fim_middle|> <|fim▁end|>
options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks)
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): <|fim_middle|> mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): <|fim_middle|> elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
mlog.warning('Media file "%s" did not exist in C directory' % m) continue
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: <|fim_middle|> else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): <|fim_middle|> try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
os.makedirs(os.path.dirname(outfile), exist_ok=True)
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one <|fim_middle|> mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
infile = c_infile
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): <|fim_middle|> shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
os.makedirs(os.path.dirname(outfile), exist_ok=True)
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: <|fim_middle|> if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
langs = read_linguas(src_subdir)
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': <|fim_middle|> elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
build_pot(src_subdir, options.project_id, sources)
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': <|fim_middle|> elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs)
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': <|fim_middle|> elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
if langs: build_translations(src_subdir, build_subdir, langs)
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: <|fim_middle|> elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
build_translations(src_subdir, build_subdir, langs)
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': <|fim_middle|> <|fim▁end|>
install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks)
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: <|fim_middle|> install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs)
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def <|fim_middle|>(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
build_pot
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def <|fim_middle|>(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
update_po
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def <|fim_middle|>(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
build_translations
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def <|fim_middle|>(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
merge_translations
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def <|fim_middle|>(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def run(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
install_help
<|file_name|>yelphelper.py<|end_file_name|><|fim▁begin|># Copyright 2016 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import shutil import argparse from .. import mlog from ..mesonlib import has_path_sep from . import destdir_join from .gettext import read_linguas parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--id', dest='project_id') parser.add_argument('--subdir', dest='subdir') parser.add_argument('--installdir', dest='install_dir') parser.add_argument('--sources', dest='sources') parser.add_argument('--media', dest='media', default='') parser.add_argument('--langs', dest='langs', default='') parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False) def build_pot(srcdir, project_id, sources): # Must be relative paths sources = [os.path.join('C', source) for source in sources] outfile = os.path.join(srcdir, project_id + '.pot') subprocess.call(['itstool', '-o', outfile] + sources) def update_po(srcdir, project_id, langs): potfile = os.path.join(srcdir, project_id + '.pot') for lang in langs: pofile = os.path.join(srcdir, lang, lang + '.po') subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile]) def build_translations(srcdir, blddir, langs): for lang in langs: outdir = os.path.join(blddir, lang) os.makedirs(outdir, exist_ok=True) subprocess.call([ 'msgfmt', os.path.join(srcdir, lang, lang + '.po'), '-o', os.path.join(outdir, lang + '.gmo') ]) def merge_translations(blddir, sources, langs): for lang in langs: subprocess.call([ 'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'), '-o', os.path.join(blddir, lang) ] + sources) def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks): c_install_dir = os.path.join(install_dir, 'C', project_id) for lang in langs + ['C']: indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id)) os.makedirs(indir, exist_ok=True) for source in sources: infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source) outfile = os.path.join(indir, source) mlog.log('Installing %s to %s' % (infile, outfile)) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) for m in media: infile = os.path.join(srcdir, lang, m) outfile = os.path.join(indir, m) c_infile = os.path.join(srcdir, 'C', m) if not os.path.exists(infile): if not os.path.exists(c_infile): mlog.warning('Media file "%s" did not exist in C directory' % m) continue elif symlinks: srcfile = os.path.join(c_install_dir, m) mlog.log('Symlinking %s to %s.' % (outfile, srcfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) try: try: os.symlink(srcfile, outfile) except FileExistsError: os.remove(outfile) os.symlink(srcfile, outfile) continue except (NotImplementedError, OSError): mlog.warning('Symlinking not supported, falling back to copying') infile = c_infile else: # Lang doesn't have media file so copy it over 'C' one infile = c_infile mlog.log('Installing %s to %s' % (infile, outfile)) if has_path_sep(m): os.makedirs(os.path.dirname(outfile), exist_ok=True) shutil.copyfile(infile, outfile) shutil.copystat(infile, outfile) def <|fim_middle|>(args): options = parser.parse_args(args) langs = options.langs.split('@@') if options.langs else [] media = options.media.split('@@') if options.media else [] sources = options.sources.split('@@') destdir = os.environ.get('DESTDIR', '') src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir) build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir) abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources] if not langs: langs = read_linguas(src_subdir) if options.command == 'pot': build_pot(src_subdir, options.project_id, sources) elif options.command == 'update-po': build_pot(src_subdir, options.project_id, sources) update_po(src_subdir, options.project_id, langs) elif options.command == 'build': if langs: build_translations(src_subdir, build_subdir, langs) elif options.command == 'install': install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir) if langs: build_translations(src_subdir, build_subdir, langs) merge_translations(build_subdir, abs_sources, langs) install_help(src_subdir, build_subdir, sources, media, langs, install_dir, destdir, options.project_id, options.symlinks) <|fim▁end|>
run
<|file_name|>setup.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*- # # Copyright (c) 2017 mooncake. All Rights Reserved #### # @brief # @author Eric Yue ( [email protected] ) # @version 0.0.1 from distutils.core import setup V = "0.7" setup( name = 'mooncake_utils', packages = ['mooncake_utils'], version = V,<|fim▁hole|> url = 'https://github.com/ericyue/mooncake_utils', download_url = 'https://github.com/ericyue/mooncake_utils/archive/%s.zip' % V, keywords = ['utils','data','machine-learning'], # arbitrary keywords classifiers = [], )<|fim▁end|>
description = 'just a useful utils for mooncake personal project.', author = 'mooncake', author_email = '[email protected]',
<|file_name|>python.py<|end_file_name|><|fim▁begin|>""" Python Blueprint ================ Does not install python itself, only develop and setup tools. Contains pip helper for other blueprints to use. **Fabric environment:** .. code-block:: yaml blueprints: - blues.python """ from fabric.decorators import task from refabric.api import run, info from refabric.context_managers import sudo from . import debian __all__ = ['setup']<|fim▁hole|> pip_log_file = '/tmp/pip.log' @task def setup(): """ Install python develop tools """ install() def install(): with sudo(): info('Install python dependencies') debian.apt_get('install', 'python-dev', 'python-setuptools') run('easy_install pip') run('touch {}'.format(pip_log_file)) debian.chmod(pip_log_file, mode=777) pip('install', 'setuptools', '--upgrade') def pip(command, *options): info('Running pip {}', command) run('pip {0} {1} -v --log={2} --log-file={2}'.format(command, ' '.join(options), pip_log_file))<|fim▁end|>
<|file_name|>python.py<|end_file_name|><|fim▁begin|>""" Python Blueprint ================ Does not install python itself, only develop and setup tools. Contains pip helper for other blueprints to use. **Fabric environment:** .. code-block:: yaml blueprints: - blues.python """ from fabric.decorators import task from refabric.api import run, info from refabric.context_managers import sudo from . import debian __all__ = ['setup'] pip_log_file = '/tmp/pip.log' @task def setup(): <|fim_middle|> def install(): with sudo(): info('Install python dependencies') debian.apt_get('install', 'python-dev', 'python-setuptools') run('easy_install pip') run('touch {}'.format(pip_log_file)) debian.chmod(pip_log_file, mode=777) pip('install', 'setuptools', '--upgrade') def pip(command, *options): info('Running pip {}', command) run('pip {0} {1} -v --log={2} --log-file={2}'.format(command, ' '.join(options), pip_log_file)) <|fim▁end|>
""" Install python develop tools """ install()
<|file_name|>python.py<|end_file_name|><|fim▁begin|>""" Python Blueprint ================ Does not install python itself, only develop and setup tools. Contains pip helper for other blueprints to use. **Fabric environment:** .. code-block:: yaml blueprints: - blues.python """ from fabric.decorators import task from refabric.api import run, info from refabric.context_managers import sudo from . import debian __all__ = ['setup'] pip_log_file = '/tmp/pip.log' @task def setup(): """ Install python develop tools """ install() def install(): <|fim_middle|> def pip(command, *options): info('Running pip {}', command) run('pip {0} {1} -v --log={2} --log-file={2}'.format(command, ' '.join(options), pip_log_file)) <|fim▁end|>
with sudo(): info('Install python dependencies') debian.apt_get('install', 'python-dev', 'python-setuptools') run('easy_install pip') run('touch {}'.format(pip_log_file)) debian.chmod(pip_log_file, mode=777) pip('install', 'setuptools', '--upgrade')
<|file_name|>python.py<|end_file_name|><|fim▁begin|>""" Python Blueprint ================ Does not install python itself, only develop and setup tools. Contains pip helper for other blueprints to use. **Fabric environment:** .. code-block:: yaml blueprints: - blues.python """ from fabric.decorators import task from refabric.api import run, info from refabric.context_managers import sudo from . import debian __all__ = ['setup'] pip_log_file = '/tmp/pip.log' @task def setup(): """ Install python develop tools """ install() def install(): with sudo(): info('Install python dependencies') debian.apt_get('install', 'python-dev', 'python-setuptools') run('easy_install pip') run('touch {}'.format(pip_log_file)) debian.chmod(pip_log_file, mode=777) pip('install', 'setuptools', '--upgrade') def pip(command, *options): <|fim_middle|> <|fim▁end|>
info('Running pip {}', command) run('pip {0} {1} -v --log={2} --log-file={2}'.format(command, ' '.join(options), pip_log_file))
<|file_name|>python.py<|end_file_name|><|fim▁begin|>""" Python Blueprint ================ Does not install python itself, only develop and setup tools. Contains pip helper for other blueprints to use. **Fabric environment:** .. code-block:: yaml blueprints: - blues.python """ from fabric.decorators import task from refabric.api import run, info from refabric.context_managers import sudo from . import debian __all__ = ['setup'] pip_log_file = '/tmp/pip.log' @task def <|fim_middle|>(): """ Install python develop tools """ install() def install(): with sudo(): info('Install python dependencies') debian.apt_get('install', 'python-dev', 'python-setuptools') run('easy_install pip') run('touch {}'.format(pip_log_file)) debian.chmod(pip_log_file, mode=777) pip('install', 'setuptools', '--upgrade') def pip(command, *options): info('Running pip {}', command) run('pip {0} {1} -v --log={2} --log-file={2}'.format(command, ' '.join(options), pip_log_file)) <|fim▁end|>
setup
<|file_name|>python.py<|end_file_name|><|fim▁begin|>""" Python Blueprint ================ Does not install python itself, only develop and setup tools. Contains pip helper for other blueprints to use. **Fabric environment:** .. code-block:: yaml blueprints: - blues.python """ from fabric.decorators import task from refabric.api import run, info from refabric.context_managers import sudo from . import debian __all__ = ['setup'] pip_log_file = '/tmp/pip.log' @task def setup(): """ Install python develop tools """ install() def <|fim_middle|>(): with sudo(): info('Install python dependencies') debian.apt_get('install', 'python-dev', 'python-setuptools') run('easy_install pip') run('touch {}'.format(pip_log_file)) debian.chmod(pip_log_file, mode=777) pip('install', 'setuptools', '--upgrade') def pip(command, *options): info('Running pip {}', command) run('pip {0} {1} -v --log={2} --log-file={2}'.format(command, ' '.join(options), pip_log_file)) <|fim▁end|>
install
<|file_name|>python.py<|end_file_name|><|fim▁begin|>""" Python Blueprint ================ Does not install python itself, only develop and setup tools. Contains pip helper for other blueprints to use. **Fabric environment:** .. code-block:: yaml blueprints: - blues.python """ from fabric.decorators import task from refabric.api import run, info from refabric.context_managers import sudo from . import debian __all__ = ['setup'] pip_log_file = '/tmp/pip.log' @task def setup(): """ Install python develop tools """ install() def install(): with sudo(): info('Install python dependencies') debian.apt_get('install', 'python-dev', 'python-setuptools') run('easy_install pip') run('touch {}'.format(pip_log_file)) debian.chmod(pip_log_file, mode=777) pip('install', 'setuptools', '--upgrade') def <|fim_middle|>(command, *options): info('Running pip {}', command) run('pip {0} {1} -v --log={2} --log-file={2}'.format(command, ' '.join(options), pip_log_file)) <|fim▁end|>
pip
<|file_name|>minimal_example.py<|end_file_name|><|fim▁begin|>""" Loads hyperspy as a regular python library, creates a spectrum with random numbers and plots it to a file"""<|fim▁hole|> s = hs.signals.Spectrum(np.random.rand(1024)) s.plot() plt.savefig("testSpectrum.png")<|fim▁end|>
import hyperspy.api as hs import numpy as np import matplotlib.pyplot as plt
<|file_name|>voter_star_on_save_doc.py<|end_file_name|><|fim▁begin|># apis_v1/documentation_source/voter_star_on_save_doc.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- def voter_star_on_save_doc_template_values(url_root): """ Show documentation about voterStarOnSave """ required_query_parameter_list = [ { 'name': 'api_key', 'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string 'description': 'The unique key provided to any organization using the WeVoteServer APIs', }, { 'name': 'voter_device_id', 'value': 'string', # boolean, integer, long, string 'description': 'An 88 character unique identifier linked to a voter record on the server', }, { 'name': 'kind_of_ballot_item', 'value': 'string', # boolean, integer, long, string 'description': 'What is the type of ballot item for which we are saving the \'on\' status? ' '(kind_of_ballot_item is either "OFFICE", "CANDIDATE", "POLITICIAN" or "MEASURE")', }, { 'name': 'ballot_item_id', 'value': 'integer', # boolean, integer, long, string 'description': 'The unique internal identifier for this ballot_item ' '(either ballot_item_id OR ballot_item_we_vote_id required -- not both. ' 'If it exists, ballot_item_id is used instead of ballot_item_we_vote_id)', }, { 'name': 'ballot_item_we_vote_id', 'value': 'string', # boolean, integer, long, string 'description': 'The unique identifier for this ballot_item across all networks ' '(either ballot_item_id OR ballot_item_we_vote_id required -- not both. ' 'NOTE: In the future we might support other identifiers used in the industry.', }, ] optional_query_parameter_list = [ ] potential_status_codes_list = [ { 'code': 'VALID_VOTER_DEVICE_ID_MISSING', 'description': 'Cannot proceed. A valid voter_device_id parameter was not included.', }, { 'code': 'VALID_VOTER_ID_MISSING', 'description': 'Cannot proceed. Missing voter_id while trying to save.', }, { 'code': 'STAR_ON_OFFICE CREATE/UPDATE ITEM_STARRED', 'description': '', }, { 'code': 'STAR_ON_CANDIDATE CREATE/UPDATE ITEM_STARRED',<|fim▁hole|> { 'code': 'STAR_ON_MEASURE CREATE/UPDATE ITEM_STARRED', 'description': '', }, ] try_now_link_variables_dict = { 'kind_of_ballot_item': 'CANDIDATE', 'ballot_item_id': '5655', } api_response = '{\n' \ ' "status": string (description of what happened),\n' \ ' "success": boolean (did the save happen?),\n' \ ' "ballot_item_id": integer,\n' \ ' "ballot_item_we_vote_id": string,\n' \ ' "kind_of_ballot_item": string (CANDIDATE, MEASURE),\n' \ '}' template_values = { 'api_name': 'voterStarOnSave', 'api_slug': 'voterStarOnSave', 'api_introduction': "Save or create private 'star on' state for the current voter for a measure, an office or candidate.", 'try_now_link': 'apis_v1:voterStarOnSaveView', 'try_now_link_variables_dict': try_now_link_variables_dict, 'url_root': url_root, 'get_or_post': 'GET', 'required_query_parameter_list': required_query_parameter_list, 'optional_query_parameter_list': optional_query_parameter_list, 'api_response': api_response, 'api_response_notes': "", 'potential_status_codes_list': potential_status_codes_list, } return template_values<|fim▁end|>
'description': '', },
<|file_name|>voter_star_on_save_doc.py<|end_file_name|><|fim▁begin|># apis_v1/documentation_source/voter_star_on_save_doc.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- def voter_star_on_save_doc_template_values(url_root): <|fim_middle|> <|fim▁end|>
""" Show documentation about voterStarOnSave """ required_query_parameter_list = [ { 'name': 'api_key', 'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string 'description': 'The unique key provided to any organization using the WeVoteServer APIs', }, { 'name': 'voter_device_id', 'value': 'string', # boolean, integer, long, string 'description': 'An 88 character unique identifier linked to a voter record on the server', }, { 'name': 'kind_of_ballot_item', 'value': 'string', # boolean, integer, long, string 'description': 'What is the type of ballot item for which we are saving the \'on\' status? ' '(kind_of_ballot_item is either "OFFICE", "CANDIDATE", "POLITICIAN" or "MEASURE")', }, { 'name': 'ballot_item_id', 'value': 'integer', # boolean, integer, long, string 'description': 'The unique internal identifier for this ballot_item ' '(either ballot_item_id OR ballot_item_we_vote_id required -- not both. ' 'If it exists, ballot_item_id is used instead of ballot_item_we_vote_id)', }, { 'name': 'ballot_item_we_vote_id', 'value': 'string', # boolean, integer, long, string 'description': 'The unique identifier for this ballot_item across all networks ' '(either ballot_item_id OR ballot_item_we_vote_id required -- not both. ' 'NOTE: In the future we might support other identifiers used in the industry.', }, ] optional_query_parameter_list = [ ] potential_status_codes_list = [ { 'code': 'VALID_VOTER_DEVICE_ID_MISSING', 'description': 'Cannot proceed. A valid voter_device_id parameter was not included.', }, { 'code': 'VALID_VOTER_ID_MISSING', 'description': 'Cannot proceed. Missing voter_id while trying to save.', }, { 'code': 'STAR_ON_OFFICE CREATE/UPDATE ITEM_STARRED', 'description': '', }, { 'code': 'STAR_ON_CANDIDATE CREATE/UPDATE ITEM_STARRED', 'description': '', }, { 'code': 'STAR_ON_MEASURE CREATE/UPDATE ITEM_STARRED', 'description': '', }, ] try_now_link_variables_dict = { 'kind_of_ballot_item': 'CANDIDATE', 'ballot_item_id': '5655', } api_response = '{\n' \ ' "status": string (description of what happened),\n' \ ' "success": boolean (did the save happen?),\n' \ ' "ballot_item_id": integer,\n' \ ' "ballot_item_we_vote_id": string,\n' \ ' "kind_of_ballot_item": string (CANDIDATE, MEASURE),\n' \ '}' template_values = { 'api_name': 'voterStarOnSave', 'api_slug': 'voterStarOnSave', 'api_introduction': "Save or create private 'star on' state for the current voter for a measure, an office or candidate.", 'try_now_link': 'apis_v1:voterStarOnSaveView', 'try_now_link_variables_dict': try_now_link_variables_dict, 'url_root': url_root, 'get_or_post': 'GET', 'required_query_parameter_list': required_query_parameter_list, 'optional_query_parameter_list': optional_query_parameter_list, 'api_response': api_response, 'api_response_notes': "", 'potential_status_codes_list': potential_status_codes_list, } return template_values
<|file_name|>voter_star_on_save_doc.py<|end_file_name|><|fim▁begin|># apis_v1/documentation_source/voter_star_on_save_doc.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- def <|fim_middle|>(url_root): """ Show documentation about voterStarOnSave """ required_query_parameter_list = [ { 'name': 'api_key', 'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string 'description': 'The unique key provided to any organization using the WeVoteServer APIs', }, { 'name': 'voter_device_id', 'value': 'string', # boolean, integer, long, string 'description': 'An 88 character unique identifier linked to a voter record on the server', }, { 'name': 'kind_of_ballot_item', 'value': 'string', # boolean, integer, long, string 'description': 'What is the type of ballot item for which we are saving the \'on\' status? ' '(kind_of_ballot_item is either "OFFICE", "CANDIDATE", "POLITICIAN" or "MEASURE")', }, { 'name': 'ballot_item_id', 'value': 'integer', # boolean, integer, long, string 'description': 'The unique internal identifier for this ballot_item ' '(either ballot_item_id OR ballot_item_we_vote_id required -- not both. ' 'If it exists, ballot_item_id is used instead of ballot_item_we_vote_id)', }, { 'name': 'ballot_item_we_vote_id', 'value': 'string', # boolean, integer, long, string 'description': 'The unique identifier for this ballot_item across all networks ' '(either ballot_item_id OR ballot_item_we_vote_id required -- not both. ' 'NOTE: In the future we might support other identifiers used in the industry.', }, ] optional_query_parameter_list = [ ] potential_status_codes_list = [ { 'code': 'VALID_VOTER_DEVICE_ID_MISSING', 'description': 'Cannot proceed. A valid voter_device_id parameter was not included.', }, { 'code': 'VALID_VOTER_ID_MISSING', 'description': 'Cannot proceed. Missing voter_id while trying to save.', }, { 'code': 'STAR_ON_OFFICE CREATE/UPDATE ITEM_STARRED', 'description': '', }, { 'code': 'STAR_ON_CANDIDATE CREATE/UPDATE ITEM_STARRED', 'description': '', }, { 'code': 'STAR_ON_MEASURE CREATE/UPDATE ITEM_STARRED', 'description': '', }, ] try_now_link_variables_dict = { 'kind_of_ballot_item': 'CANDIDATE', 'ballot_item_id': '5655', } api_response = '{\n' \ ' "status": string (description of what happened),\n' \ ' "success": boolean (did the save happen?),\n' \ ' "ballot_item_id": integer,\n' \ ' "ballot_item_we_vote_id": string,\n' \ ' "kind_of_ballot_item": string (CANDIDATE, MEASURE),\n' \ '}' template_values = { 'api_name': 'voterStarOnSave', 'api_slug': 'voterStarOnSave', 'api_introduction': "Save or create private 'star on' state for the current voter for a measure, an office or candidate.", 'try_now_link': 'apis_v1:voterStarOnSaveView', 'try_now_link_variables_dict': try_now_link_variables_dict, 'url_root': url_root, 'get_or_post': 'GET', 'required_query_parameter_list': required_query_parameter_list, 'optional_query_parameter_list': optional_query_parameter_list, 'api_response': api_response, 'api_response_notes': "", 'potential_status_codes_list': potential_status_codes_list, } return template_values <|fim▁end|>
voter_star_on_save_doc_template_values
<|file_name|>impl1.py<|end_file_name|><|fim▁begin|>## mostly copied from: http://norvig.com/spell-correct.html import sys, random import re, collections, time TXT_FILE=''; BUF_DIR='';<|fim▁hole|>NWORDS=None; def words(text): return re.findall('[a-z]+', text) def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model alphabet = 'abcdefghijklmnopqrstuvwxyz' def edits1(word): splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] inserts = [a + c + b for a, b in splits for c in alphabet] return set(deletes + transposes + replaces + inserts) def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) def known(words): return set(w for w in words if w in NWORDS) def correct(word): candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=NWORDS.get) ####################################################################################### if __name__ == '__main__': TXT_FILE = sys.argv[1] t0 = time.clock() o_words = words(file(TXT_FILE).read()) NWORDS = train(o_words) #print time.clock() - t0, " seconds build time" #print "dictionary size: %d" %len(NWORDS) et1 = time.clock() - t0 t_count = 10 rl = o_words[0:t_count] #random.sample(o_words, t_count) orl = [''.join(random.sample(word, len(word))) for word in o_words] t1 = time.clock() r_count = 10 for i in range(0, r_count): for w1, w2 in zip(rl, orl): correct(w1); correct(w2) et2 = (time.clock() - t1)/t_count/r_count/2 print '%d\t%f\t%f' %(len(NWORDS), et1, et2) ####################################################################################### print 'Done'<|fim▁end|>
<|file_name|>impl1.py<|end_file_name|><|fim▁begin|>## mostly copied from: http://norvig.com/spell-correct.html import sys, random import re, collections, time TXT_FILE=''; BUF_DIR=''; NWORDS=None; def words(text): <|fim_middle|> def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model alphabet = 'abcdefghijklmnopqrstuvwxyz' def edits1(word): splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] inserts = [a + c + b for a, b in splits for c in alphabet] return set(deletes + transposes + replaces + inserts) def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) def known(words): return set(w for w in words if w in NWORDS) def correct(word): candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=NWORDS.get) ####################################################################################### if __name__ == '__main__': TXT_FILE = sys.argv[1] t0 = time.clock() o_words = words(file(TXT_FILE).read()) NWORDS = train(o_words) #print time.clock() - t0, " seconds build time" #print "dictionary size: %d" %len(NWORDS) et1 = time.clock() - t0 t_count = 10 rl = o_words[0:t_count] #random.sample(o_words, t_count) orl = [''.join(random.sample(word, len(word))) for word in o_words] t1 = time.clock() r_count = 10 for i in range(0, r_count): for w1, w2 in zip(rl, orl): correct(w1); correct(w2) et2 = (time.clock() - t1)/t_count/r_count/2 print '%d\t%f\t%f' %(len(NWORDS), et1, et2) ####################################################################################### print 'Done' <|fim▁end|>
return re.findall('[a-z]+', text)
<|file_name|>impl1.py<|end_file_name|><|fim▁begin|>## mostly copied from: http://norvig.com/spell-correct.html import sys, random import re, collections, time TXT_FILE=''; BUF_DIR=''; NWORDS=None; def words(text): return re.findall('[a-z]+', text) def train(features): <|fim_middle|> alphabet = 'abcdefghijklmnopqrstuvwxyz' def edits1(word): splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] inserts = [a + c + b for a, b in splits for c in alphabet] return set(deletes + transposes + replaces + inserts) def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) def known(words): return set(w for w in words if w in NWORDS) def correct(word): candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=NWORDS.get) ####################################################################################### if __name__ == '__main__': TXT_FILE = sys.argv[1] t0 = time.clock() o_words = words(file(TXT_FILE).read()) NWORDS = train(o_words) #print time.clock() - t0, " seconds build time" #print "dictionary size: %d" %len(NWORDS) et1 = time.clock() - t0 t_count = 10 rl = o_words[0:t_count] #random.sample(o_words, t_count) orl = [''.join(random.sample(word, len(word))) for word in o_words] t1 = time.clock() r_count = 10 for i in range(0, r_count): for w1, w2 in zip(rl, orl): correct(w1); correct(w2) et2 = (time.clock() - t1)/t_count/r_count/2 print '%d\t%f\t%f' %(len(NWORDS), et1, et2) ####################################################################################### print 'Done' <|fim▁end|>
model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model
<|file_name|>impl1.py<|end_file_name|><|fim▁begin|>## mostly copied from: http://norvig.com/spell-correct.html import sys, random import re, collections, time TXT_FILE=''; BUF_DIR=''; NWORDS=None; def words(text): return re.findall('[a-z]+', text) def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model alphabet = 'abcdefghijklmnopqrstuvwxyz' def edits1(word): <|fim_middle|> def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) def known(words): return set(w for w in words if w in NWORDS) def correct(word): candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=NWORDS.get) ####################################################################################### if __name__ == '__main__': TXT_FILE = sys.argv[1] t0 = time.clock() o_words = words(file(TXT_FILE).read()) NWORDS = train(o_words) #print time.clock() - t0, " seconds build time" #print "dictionary size: %d" %len(NWORDS) et1 = time.clock() - t0 t_count = 10 rl = o_words[0:t_count] #random.sample(o_words, t_count) orl = [''.join(random.sample(word, len(word))) for word in o_words] t1 = time.clock() r_count = 10 for i in range(0, r_count): for w1, w2 in zip(rl, orl): correct(w1); correct(w2) et2 = (time.clock() - t1)/t_count/r_count/2 print '%d\t%f\t%f' %(len(NWORDS), et1, et2) ####################################################################################### print 'Done' <|fim▁end|>
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] inserts = [a + c + b for a, b in splits for c in alphabet] return set(deletes + transposes + replaces + inserts)
<|file_name|>impl1.py<|end_file_name|><|fim▁begin|>## mostly copied from: http://norvig.com/spell-correct.html import sys, random import re, collections, time TXT_FILE=''; BUF_DIR=''; NWORDS=None; def words(text): return re.findall('[a-z]+', text) def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model alphabet = 'abcdefghijklmnopqrstuvwxyz' def edits1(word): splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] inserts = [a + c + b for a, b in splits for c in alphabet] return set(deletes + transposes + replaces + inserts) def known_edits2(word): <|fim_middle|> def known(words): return set(w for w in words if w in NWORDS) def correct(word): candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=NWORDS.get) ####################################################################################### if __name__ == '__main__': TXT_FILE = sys.argv[1] t0 = time.clock() o_words = words(file(TXT_FILE).read()) NWORDS = train(o_words) #print time.clock() - t0, " seconds build time" #print "dictionary size: %d" %len(NWORDS) et1 = time.clock() - t0 t_count = 10 rl = o_words[0:t_count] #random.sample(o_words, t_count) orl = [''.join(random.sample(word, len(word))) for word in o_words] t1 = time.clock() r_count = 10 for i in range(0, r_count): for w1, w2 in zip(rl, orl): correct(w1); correct(w2) et2 = (time.clock() - t1)/t_count/r_count/2 print '%d\t%f\t%f' %(len(NWORDS), et1, et2) ####################################################################################### print 'Done' <|fim▁end|>
return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)
<|file_name|>impl1.py<|end_file_name|><|fim▁begin|>## mostly copied from: http://norvig.com/spell-correct.html import sys, random import re, collections, time TXT_FILE=''; BUF_DIR=''; NWORDS=None; def words(text): return re.findall('[a-z]+', text) def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model alphabet = 'abcdefghijklmnopqrstuvwxyz' def edits1(word): splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] inserts = [a + c + b for a, b in splits for c in alphabet] return set(deletes + transposes + replaces + inserts) def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) def known(words): <|fim_middle|> def correct(word): candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=NWORDS.get) ####################################################################################### if __name__ == '__main__': TXT_FILE = sys.argv[1] t0 = time.clock() o_words = words(file(TXT_FILE).read()) NWORDS = train(o_words) #print time.clock() - t0, " seconds build time" #print "dictionary size: %d" %len(NWORDS) et1 = time.clock() - t0 t_count = 10 rl = o_words[0:t_count] #random.sample(o_words, t_count) orl = [''.join(random.sample(word, len(word))) for word in o_words] t1 = time.clock() r_count = 10 for i in range(0, r_count): for w1, w2 in zip(rl, orl): correct(w1); correct(w2) et2 = (time.clock() - t1)/t_count/r_count/2 print '%d\t%f\t%f' %(len(NWORDS), et1, et2) ####################################################################################### print 'Done' <|fim▁end|>
return set(w for w in words if w in NWORDS)
<|file_name|>impl1.py<|end_file_name|><|fim▁begin|>## mostly copied from: http://norvig.com/spell-correct.html import sys, random import re, collections, time TXT_FILE=''; BUF_DIR=''; NWORDS=None; def words(text): return re.findall('[a-z]+', text) def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model alphabet = 'abcdefghijklmnopqrstuvwxyz' def edits1(word): splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] inserts = [a + c + b for a, b in splits for c in alphabet] return set(deletes + transposes + replaces + inserts) def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) def known(words): return set(w for w in words if w in NWORDS) def correct(word): <|fim_middle|> ####################################################################################### if __name__ == '__main__': TXT_FILE = sys.argv[1] t0 = time.clock() o_words = words(file(TXT_FILE).read()) NWORDS = train(o_words) #print time.clock() - t0, " seconds build time" #print "dictionary size: %d" %len(NWORDS) et1 = time.clock() - t0 t_count = 10 rl = o_words[0:t_count] #random.sample(o_words, t_count) orl = [''.join(random.sample(word, len(word))) for word in o_words] t1 = time.clock() r_count = 10 for i in range(0, r_count): for w1, w2 in zip(rl, orl): correct(w1); correct(w2) et2 = (time.clock() - t1)/t_count/r_count/2 print '%d\t%f\t%f' %(len(NWORDS), et1, et2) ####################################################################################### print 'Done' <|fim▁end|>
candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=NWORDS.get)
<|file_name|>impl1.py<|end_file_name|><|fim▁begin|>## mostly copied from: http://norvig.com/spell-correct.html import sys, random import re, collections, time TXT_FILE=''; BUF_DIR=''; NWORDS=None; def words(text): return re.findall('[a-z]+', text) def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model alphabet = 'abcdefghijklmnopqrstuvwxyz' def edits1(word): splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] inserts = [a + c + b for a, b in splits for c in alphabet] return set(deletes + transposes + replaces + inserts) def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) def known(words): return set(w for w in words if w in NWORDS) def correct(word): candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=NWORDS.get) ####################################################################################### if __name__ == '__main__': <|fim_middle|> ####################################################################################### print 'Done' <|fim▁end|>
TXT_FILE = sys.argv[1] t0 = time.clock() o_words = words(file(TXT_FILE).read()) NWORDS = train(o_words) #print time.clock() - t0, " seconds build time" #print "dictionary size: %d" %len(NWORDS) et1 = time.clock() - t0 t_count = 10 rl = o_words[0:t_count] #random.sample(o_words, t_count) orl = [''.join(random.sample(word, len(word))) for word in o_words] t1 = time.clock() r_count = 10 for i in range(0, r_count): for w1, w2 in zip(rl, orl): correct(w1); correct(w2) et2 = (time.clock() - t1)/t_count/r_count/2 print '%d\t%f\t%f' %(len(NWORDS), et1, et2)
<|file_name|>impl1.py<|end_file_name|><|fim▁begin|>## mostly copied from: http://norvig.com/spell-correct.html import sys, random import re, collections, time TXT_FILE=''; BUF_DIR=''; NWORDS=None; def <|fim_middle|>(text): return re.findall('[a-z]+', text) def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model alphabet = 'abcdefghijklmnopqrstuvwxyz' def edits1(word): splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] inserts = [a + c + b for a, b in splits for c in alphabet] return set(deletes + transposes + replaces + inserts) def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) def known(words): return set(w for w in words if w in NWORDS) def correct(word): candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=NWORDS.get) ####################################################################################### if __name__ == '__main__': TXT_FILE = sys.argv[1] t0 = time.clock() o_words = words(file(TXT_FILE).read()) NWORDS = train(o_words) #print time.clock() - t0, " seconds build time" #print "dictionary size: %d" %len(NWORDS) et1 = time.clock() - t0 t_count = 10 rl = o_words[0:t_count] #random.sample(o_words, t_count) orl = [''.join(random.sample(word, len(word))) for word in o_words] t1 = time.clock() r_count = 10 for i in range(0, r_count): for w1, w2 in zip(rl, orl): correct(w1); correct(w2) et2 = (time.clock() - t1)/t_count/r_count/2 print '%d\t%f\t%f' %(len(NWORDS), et1, et2) ####################################################################################### print 'Done' <|fim▁end|>
words
<|file_name|>impl1.py<|end_file_name|><|fim▁begin|>## mostly copied from: http://norvig.com/spell-correct.html import sys, random import re, collections, time TXT_FILE=''; BUF_DIR=''; NWORDS=None; def words(text): return re.findall('[a-z]+', text) def <|fim_middle|>(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model alphabet = 'abcdefghijklmnopqrstuvwxyz' def edits1(word): splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] inserts = [a + c + b for a, b in splits for c in alphabet] return set(deletes + transposes + replaces + inserts) def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) def known(words): return set(w for w in words if w in NWORDS) def correct(word): candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=NWORDS.get) ####################################################################################### if __name__ == '__main__': TXT_FILE = sys.argv[1] t0 = time.clock() o_words = words(file(TXT_FILE).read()) NWORDS = train(o_words) #print time.clock() - t0, " seconds build time" #print "dictionary size: %d" %len(NWORDS) et1 = time.clock() - t0 t_count = 10 rl = o_words[0:t_count] #random.sample(o_words, t_count) orl = [''.join(random.sample(word, len(word))) for word in o_words] t1 = time.clock() r_count = 10 for i in range(0, r_count): for w1, w2 in zip(rl, orl): correct(w1); correct(w2) et2 = (time.clock() - t1)/t_count/r_count/2 print '%d\t%f\t%f' %(len(NWORDS), et1, et2) ####################################################################################### print 'Done' <|fim▁end|>
train
<|file_name|>impl1.py<|end_file_name|><|fim▁begin|>## mostly copied from: http://norvig.com/spell-correct.html import sys, random import re, collections, time TXT_FILE=''; BUF_DIR=''; NWORDS=None; def words(text): return re.findall('[a-z]+', text) def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model alphabet = 'abcdefghijklmnopqrstuvwxyz' def <|fim_middle|>(word): splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] inserts = [a + c + b for a, b in splits for c in alphabet] return set(deletes + transposes + replaces + inserts) def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) def known(words): return set(w for w in words if w in NWORDS) def correct(word): candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=NWORDS.get) ####################################################################################### if __name__ == '__main__': TXT_FILE = sys.argv[1] t0 = time.clock() o_words = words(file(TXT_FILE).read()) NWORDS = train(o_words) #print time.clock() - t0, " seconds build time" #print "dictionary size: %d" %len(NWORDS) et1 = time.clock() - t0 t_count = 10 rl = o_words[0:t_count] #random.sample(o_words, t_count) orl = [''.join(random.sample(word, len(word))) for word in o_words] t1 = time.clock() r_count = 10 for i in range(0, r_count): for w1, w2 in zip(rl, orl): correct(w1); correct(w2) et2 = (time.clock() - t1)/t_count/r_count/2 print '%d\t%f\t%f' %(len(NWORDS), et1, et2) ####################################################################################### print 'Done' <|fim▁end|>
edits1
<|file_name|>impl1.py<|end_file_name|><|fim▁begin|>## mostly copied from: http://norvig.com/spell-correct.html import sys, random import re, collections, time TXT_FILE=''; BUF_DIR=''; NWORDS=None; def words(text): return re.findall('[a-z]+', text) def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model alphabet = 'abcdefghijklmnopqrstuvwxyz' def edits1(word): splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] inserts = [a + c + b for a, b in splits for c in alphabet] return set(deletes + transposes + replaces + inserts) def <|fim_middle|>(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) def known(words): return set(w for w in words if w in NWORDS) def correct(word): candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=NWORDS.get) ####################################################################################### if __name__ == '__main__': TXT_FILE = sys.argv[1] t0 = time.clock() o_words = words(file(TXT_FILE).read()) NWORDS = train(o_words) #print time.clock() - t0, " seconds build time" #print "dictionary size: %d" %len(NWORDS) et1 = time.clock() - t0 t_count = 10 rl = o_words[0:t_count] #random.sample(o_words, t_count) orl = [''.join(random.sample(word, len(word))) for word in o_words] t1 = time.clock() r_count = 10 for i in range(0, r_count): for w1, w2 in zip(rl, orl): correct(w1); correct(w2) et2 = (time.clock() - t1)/t_count/r_count/2 print '%d\t%f\t%f' %(len(NWORDS), et1, et2) ####################################################################################### print 'Done' <|fim▁end|>
known_edits2
<|file_name|>impl1.py<|end_file_name|><|fim▁begin|>## mostly copied from: http://norvig.com/spell-correct.html import sys, random import re, collections, time TXT_FILE=''; BUF_DIR=''; NWORDS=None; def words(text): return re.findall('[a-z]+', text) def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model alphabet = 'abcdefghijklmnopqrstuvwxyz' def edits1(word): splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] inserts = [a + c + b for a, b in splits for c in alphabet] return set(deletes + transposes + replaces + inserts) def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) def <|fim_middle|>(words): return set(w for w in words if w in NWORDS) def correct(word): candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=NWORDS.get) ####################################################################################### if __name__ == '__main__': TXT_FILE = sys.argv[1] t0 = time.clock() o_words = words(file(TXT_FILE).read()) NWORDS = train(o_words) #print time.clock() - t0, " seconds build time" #print "dictionary size: %d" %len(NWORDS) et1 = time.clock() - t0 t_count = 10 rl = o_words[0:t_count] #random.sample(o_words, t_count) orl = [''.join(random.sample(word, len(word))) for word in o_words] t1 = time.clock() r_count = 10 for i in range(0, r_count): for w1, w2 in zip(rl, orl): correct(w1); correct(w2) et2 = (time.clock() - t1)/t_count/r_count/2 print '%d\t%f\t%f' %(len(NWORDS), et1, et2) ####################################################################################### print 'Done' <|fim▁end|>
known
<|file_name|>impl1.py<|end_file_name|><|fim▁begin|>## mostly copied from: http://norvig.com/spell-correct.html import sys, random import re, collections, time TXT_FILE=''; BUF_DIR=''; NWORDS=None; def words(text): return re.findall('[a-z]+', text) def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model alphabet = 'abcdefghijklmnopqrstuvwxyz' def edits1(word): splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] inserts = [a + c + b for a, b in splits for c in alphabet] return set(deletes + transposes + replaces + inserts) def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) def known(words): return set(w for w in words if w in NWORDS) def <|fim_middle|>(word): candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=NWORDS.get) ####################################################################################### if __name__ == '__main__': TXT_FILE = sys.argv[1] t0 = time.clock() o_words = words(file(TXT_FILE).read()) NWORDS = train(o_words) #print time.clock() - t0, " seconds build time" #print "dictionary size: %d" %len(NWORDS) et1 = time.clock() - t0 t_count = 10 rl = o_words[0:t_count] #random.sample(o_words, t_count) orl = [''.join(random.sample(word, len(word))) for word in o_words] t1 = time.clock() r_count = 10 for i in range(0, r_count): for w1, w2 in zip(rl, orl): correct(w1); correct(w2) et2 = (time.clock() - t1)/t_count/r_count/2 print '%d\t%f\t%f' %(len(NWORDS), et1, et2) ####################################################################################### print 'Done' <|fim▁end|>
correct
<|file_name|>l10n-fetch-po-files.py<|end_file_name|><|fim▁begin|>import os import re import subprocess # Copied from Trojita """Fetch the .po files from KDE's SVN for GCompris Run me from GCompris's top-level directory. """ SVN_PATH = "svn://anonsvn.kde.org/home/kde/trunk/l10n-kf5/" SOURCE_PO_PATH = "/messages/kdereview/gcompris_qt.po" OUTPUT_PO_PATH = "./po/" OUTPUT_PO_PATTERN = "gcompris_%s.po" fixer = re.compile(r'^#~\| ', re.MULTILINE) re_empty_msgid = re.compile('^msgid ""$', re.MULTILINE) re_empty_line = re.compile('^$', re.MULTILINE) re_has_qt_contexts = re.compile('X-Qt-Contexts: true\\n') if not os.path.exists(OUTPUT_PO_PATH): os.mkdir(OUTPUT_PO_PATH) all_languages = subprocess.check_output(['svn', 'cat', SVN_PATH + 'subdirs'], stderr=subprocess.STDOUT) all_languages = [x.strip() for x in all_languages.split("\n") if len(x)] all_languages.remove("x-test") for lang in all_languages: try: raw_data = subprocess.check_output(['svn', 'cat', SVN_PATH + lang + SOURCE_PO_PATH], stderr=subprocess.PIPE) (transformed, subs) = fixer.subn('# ~| ', raw_data) pos1 = re_empty_msgid.search(transformed).start() pos2 = re_empty_line.search(transformed).start() if re_has_qt_contexts.search(transformed, pos1, pos2) is None: transformed = transformed[:pos2] + \ '"X-Qt-Contexts: true\\n"\n' + \ transformed[pos2:] subs = subs + 1 if (subs > 0): print "Fetched %s (and performed %d cleanups)" % (lang, subs) else: print "Fetched %s" % lang file(OUTPUT_PO_PATH + OUTPUT_PO_PATTERN % lang, "wb").write(transformed) except subprocess.CalledProcessError: print "No data for %s" % lang<|fim▁hole|># Inform qmake about the updated file list #os.utime("CMakeLists.txt", None)<|fim▁end|>
<|file_name|>l10n-fetch-po-files.py<|end_file_name|><|fim▁begin|>import os import re import subprocess # Copied from Trojita """Fetch the .po files from KDE's SVN for GCompris Run me from GCompris's top-level directory. """ SVN_PATH = "svn://anonsvn.kde.org/home/kde/trunk/l10n-kf5/" SOURCE_PO_PATH = "/messages/kdereview/gcompris_qt.po" OUTPUT_PO_PATH = "./po/" OUTPUT_PO_PATTERN = "gcompris_%s.po" fixer = re.compile(r'^#~\| ', re.MULTILINE) re_empty_msgid = re.compile('^msgid ""$', re.MULTILINE) re_empty_line = re.compile('^$', re.MULTILINE) re_has_qt_contexts = re.compile('X-Qt-Contexts: true\\n') if not os.path.exists(OUTPUT_PO_PATH): <|fim_middle|> all_languages = subprocess.check_output(['svn', 'cat', SVN_PATH + 'subdirs'], stderr=subprocess.STDOUT) all_languages = [x.strip() for x in all_languages.split("\n") if len(x)] all_languages.remove("x-test") for lang in all_languages: try: raw_data = subprocess.check_output(['svn', 'cat', SVN_PATH + lang + SOURCE_PO_PATH], stderr=subprocess.PIPE) (transformed, subs) = fixer.subn('# ~| ', raw_data) pos1 = re_empty_msgid.search(transformed).start() pos2 = re_empty_line.search(transformed).start() if re_has_qt_contexts.search(transformed, pos1, pos2) is None: transformed = transformed[:pos2] + \ '"X-Qt-Contexts: true\\n"\n' + \ transformed[pos2:] subs = subs + 1 if (subs > 0): print "Fetched %s (and performed %d cleanups)" % (lang, subs) else: print "Fetched %s" % lang file(OUTPUT_PO_PATH + OUTPUT_PO_PATTERN % lang, "wb").write(transformed) except subprocess.CalledProcessError: print "No data for %s" % lang # Inform qmake about the updated file list #os.utime("CMakeLists.txt", None) <|fim▁end|>
os.mkdir(OUTPUT_PO_PATH)
<|file_name|>l10n-fetch-po-files.py<|end_file_name|><|fim▁begin|>import os import re import subprocess # Copied from Trojita """Fetch the .po files from KDE's SVN for GCompris Run me from GCompris's top-level directory. """ SVN_PATH = "svn://anonsvn.kde.org/home/kde/trunk/l10n-kf5/" SOURCE_PO_PATH = "/messages/kdereview/gcompris_qt.po" OUTPUT_PO_PATH = "./po/" OUTPUT_PO_PATTERN = "gcompris_%s.po" fixer = re.compile(r'^#~\| ', re.MULTILINE) re_empty_msgid = re.compile('^msgid ""$', re.MULTILINE) re_empty_line = re.compile('^$', re.MULTILINE) re_has_qt_contexts = re.compile('X-Qt-Contexts: true\\n') if not os.path.exists(OUTPUT_PO_PATH): os.mkdir(OUTPUT_PO_PATH) all_languages = subprocess.check_output(['svn', 'cat', SVN_PATH + 'subdirs'], stderr=subprocess.STDOUT) all_languages = [x.strip() for x in all_languages.split("\n") if len(x)] all_languages.remove("x-test") for lang in all_languages: try: raw_data = subprocess.check_output(['svn', 'cat', SVN_PATH + lang + SOURCE_PO_PATH], stderr=subprocess.PIPE) (transformed, subs) = fixer.subn('# ~| ', raw_data) pos1 = re_empty_msgid.search(transformed).start() pos2 = re_empty_line.search(transformed).start() if re_has_qt_contexts.search(transformed, pos1, pos2) is None: <|fim_middle|> if (subs > 0): print "Fetched %s (and performed %d cleanups)" % (lang, subs) else: print "Fetched %s" % lang file(OUTPUT_PO_PATH + OUTPUT_PO_PATTERN % lang, "wb").write(transformed) except subprocess.CalledProcessError: print "No data for %s" % lang # Inform qmake about the updated file list #os.utime("CMakeLists.txt", None) <|fim▁end|>
transformed = transformed[:pos2] + \ '"X-Qt-Contexts: true\\n"\n' + \ transformed[pos2:] subs = subs + 1
<|file_name|>l10n-fetch-po-files.py<|end_file_name|><|fim▁begin|>import os import re import subprocess # Copied from Trojita """Fetch the .po files from KDE's SVN for GCompris Run me from GCompris's top-level directory. """ SVN_PATH = "svn://anonsvn.kde.org/home/kde/trunk/l10n-kf5/" SOURCE_PO_PATH = "/messages/kdereview/gcompris_qt.po" OUTPUT_PO_PATH = "./po/" OUTPUT_PO_PATTERN = "gcompris_%s.po" fixer = re.compile(r'^#~\| ', re.MULTILINE) re_empty_msgid = re.compile('^msgid ""$', re.MULTILINE) re_empty_line = re.compile('^$', re.MULTILINE) re_has_qt_contexts = re.compile('X-Qt-Contexts: true\\n') if not os.path.exists(OUTPUT_PO_PATH): os.mkdir(OUTPUT_PO_PATH) all_languages = subprocess.check_output(['svn', 'cat', SVN_PATH + 'subdirs'], stderr=subprocess.STDOUT) all_languages = [x.strip() for x in all_languages.split("\n") if len(x)] all_languages.remove("x-test") for lang in all_languages: try: raw_data = subprocess.check_output(['svn', 'cat', SVN_PATH + lang + SOURCE_PO_PATH], stderr=subprocess.PIPE) (transformed, subs) = fixer.subn('# ~| ', raw_data) pos1 = re_empty_msgid.search(transformed).start() pos2 = re_empty_line.search(transformed).start() if re_has_qt_contexts.search(transformed, pos1, pos2) is None: transformed = transformed[:pos2] + \ '"X-Qt-Contexts: true\\n"\n' + \ transformed[pos2:] subs = subs + 1 if (subs > 0): <|fim_middle|> else: print "Fetched %s" % lang file(OUTPUT_PO_PATH + OUTPUT_PO_PATTERN % lang, "wb").write(transformed) except subprocess.CalledProcessError: print "No data for %s" % lang # Inform qmake about the updated file list #os.utime("CMakeLists.txt", None) <|fim▁end|>
print "Fetched %s (and performed %d cleanups)" % (lang, subs)
<|file_name|>l10n-fetch-po-files.py<|end_file_name|><|fim▁begin|>import os import re import subprocess # Copied from Trojita """Fetch the .po files from KDE's SVN for GCompris Run me from GCompris's top-level directory. """ SVN_PATH = "svn://anonsvn.kde.org/home/kde/trunk/l10n-kf5/" SOURCE_PO_PATH = "/messages/kdereview/gcompris_qt.po" OUTPUT_PO_PATH = "./po/" OUTPUT_PO_PATTERN = "gcompris_%s.po" fixer = re.compile(r'^#~\| ', re.MULTILINE) re_empty_msgid = re.compile('^msgid ""$', re.MULTILINE) re_empty_line = re.compile('^$', re.MULTILINE) re_has_qt_contexts = re.compile('X-Qt-Contexts: true\\n') if not os.path.exists(OUTPUT_PO_PATH): os.mkdir(OUTPUT_PO_PATH) all_languages = subprocess.check_output(['svn', 'cat', SVN_PATH + 'subdirs'], stderr=subprocess.STDOUT) all_languages = [x.strip() for x in all_languages.split("\n") if len(x)] all_languages.remove("x-test") for lang in all_languages: try: raw_data = subprocess.check_output(['svn', 'cat', SVN_PATH + lang + SOURCE_PO_PATH], stderr=subprocess.PIPE) (transformed, subs) = fixer.subn('# ~| ', raw_data) pos1 = re_empty_msgid.search(transformed).start() pos2 = re_empty_line.search(transformed).start() if re_has_qt_contexts.search(transformed, pos1, pos2) is None: transformed = transformed[:pos2] + \ '"X-Qt-Contexts: true\\n"\n' + \ transformed[pos2:] subs = subs + 1 if (subs > 0): print "Fetched %s (and performed %d cleanups)" % (lang, subs) else: <|fim_middle|> file(OUTPUT_PO_PATH + OUTPUT_PO_PATTERN % lang, "wb").write(transformed) except subprocess.CalledProcessError: print "No data for %s" % lang # Inform qmake about the updated file list #os.utime("CMakeLists.txt", None) <|fim▁end|>
print "Fetched %s" % lang
<|file_name|>bitten.py<|end_file_name|><|fim▁begin|>import codecs unicode_string = "Hello Python 3 String" bytes_object = b"Hello Python 3 Bytes" print(unicode_string, type(unicode_string)) print(bytes_object, type(bytes_object)) #decode to unicode_string ux = str(object=bytes_object, encoding="utf-8", errors="strict") print(ux, type(ux)) ux = bytes_object.decode(encoding="utf-8", errors="strict") print(ux, type(ux)) hex_bytes = codecs.encode(b"Binary Object", "hex_codec") def string_to_bytes( text ): return bin(int.from_bytes(text.encode(), 'big')) def bytes_to_string( btext ): #btext = int('0b110100001100101011011000110110001101111', 2) return btext.to_bytes((btext.bit_length() + 7) // 8, 'big').decode() def char_to_bytes(char): return bin(ord(char)) def encodes(text): bext = text.encode(encoding="utf-8") enc_bext = codecs.encode(bext, "hex_codec") return enc_bext.decode("utf-8") def decodes(): pass<|fim▁hole|> print( encodes("walla") )<|fim▁end|>
if __name__ == "__main__":
<|file_name|>bitten.py<|end_file_name|><|fim▁begin|>import codecs unicode_string = "Hello Python 3 String" bytes_object = b"Hello Python 3 Bytes" print(unicode_string, type(unicode_string)) print(bytes_object, type(bytes_object)) #decode to unicode_string ux = str(object=bytes_object, encoding="utf-8", errors="strict") print(ux, type(ux)) ux = bytes_object.decode(encoding="utf-8", errors="strict") print(ux, type(ux)) hex_bytes = codecs.encode(b"Binary Object", "hex_codec") def string_to_bytes( text ): <|fim_middle|> def bytes_to_string( btext ): #btext = int('0b110100001100101011011000110110001101111', 2) return btext.to_bytes((btext.bit_length() + 7) // 8, 'big').decode() def char_to_bytes(char): return bin(ord(char)) def encodes(text): bext = text.encode(encoding="utf-8") enc_bext = codecs.encode(bext, "hex_codec") return enc_bext.decode("utf-8") def decodes(): pass if __name__ == "__main__": print( encodes("walla") ) <|fim▁end|>
return bin(int.from_bytes(text.encode(), 'big'))
<|file_name|>bitten.py<|end_file_name|><|fim▁begin|>import codecs unicode_string = "Hello Python 3 String" bytes_object = b"Hello Python 3 Bytes" print(unicode_string, type(unicode_string)) print(bytes_object, type(bytes_object)) #decode to unicode_string ux = str(object=bytes_object, encoding="utf-8", errors="strict") print(ux, type(ux)) ux = bytes_object.decode(encoding="utf-8", errors="strict") print(ux, type(ux)) hex_bytes = codecs.encode(b"Binary Object", "hex_codec") def string_to_bytes( text ): return bin(int.from_bytes(text.encode(), 'big')) def bytes_to_string( btext ): #btext = int('0b110100001100101011011000110110001101111', 2) <|fim_middle|> def char_to_bytes(char): return bin(ord(char)) def encodes(text): bext = text.encode(encoding="utf-8") enc_bext = codecs.encode(bext, "hex_codec") return enc_bext.decode("utf-8") def decodes(): pass if __name__ == "__main__": print( encodes("walla") ) <|fim▁end|>
return btext.to_bytes((btext.bit_length() + 7) // 8, 'big').decode()
<|file_name|>bitten.py<|end_file_name|><|fim▁begin|>import codecs unicode_string = "Hello Python 3 String" bytes_object = b"Hello Python 3 Bytes" print(unicode_string, type(unicode_string)) print(bytes_object, type(bytes_object)) #decode to unicode_string ux = str(object=bytes_object, encoding="utf-8", errors="strict") print(ux, type(ux)) ux = bytes_object.decode(encoding="utf-8", errors="strict") print(ux, type(ux)) hex_bytes = codecs.encode(b"Binary Object", "hex_codec") def string_to_bytes( text ): return bin(int.from_bytes(text.encode(), 'big')) def bytes_to_string( btext ): #btext = int('0b110100001100101011011000110110001101111', 2) return btext.to_bytes((btext.bit_length() + 7) // 8, 'big').decode() def char_to_bytes(char): <|fim_middle|> def encodes(text): bext = text.encode(encoding="utf-8") enc_bext = codecs.encode(bext, "hex_codec") return enc_bext.decode("utf-8") def decodes(): pass if __name__ == "__main__": print( encodes("walla") ) <|fim▁end|>
return bin(ord(char))
<|file_name|>bitten.py<|end_file_name|><|fim▁begin|>import codecs unicode_string = "Hello Python 3 String" bytes_object = b"Hello Python 3 Bytes" print(unicode_string, type(unicode_string)) print(bytes_object, type(bytes_object)) #decode to unicode_string ux = str(object=bytes_object, encoding="utf-8", errors="strict") print(ux, type(ux)) ux = bytes_object.decode(encoding="utf-8", errors="strict") print(ux, type(ux)) hex_bytes = codecs.encode(b"Binary Object", "hex_codec") def string_to_bytes( text ): return bin(int.from_bytes(text.encode(), 'big')) def bytes_to_string( btext ): #btext = int('0b110100001100101011011000110110001101111', 2) return btext.to_bytes((btext.bit_length() + 7) // 8, 'big').decode() def char_to_bytes(char): return bin(ord(char)) def encodes(text): <|fim_middle|> def decodes(): pass if __name__ == "__main__": print( encodes("walla") ) <|fim▁end|>
bext = text.encode(encoding="utf-8") enc_bext = codecs.encode(bext, "hex_codec") return enc_bext.decode("utf-8")
<|file_name|>bitten.py<|end_file_name|><|fim▁begin|>import codecs unicode_string = "Hello Python 3 String" bytes_object = b"Hello Python 3 Bytes" print(unicode_string, type(unicode_string)) print(bytes_object, type(bytes_object)) #decode to unicode_string ux = str(object=bytes_object, encoding="utf-8", errors="strict") print(ux, type(ux)) ux = bytes_object.decode(encoding="utf-8", errors="strict") print(ux, type(ux)) hex_bytes = codecs.encode(b"Binary Object", "hex_codec") def string_to_bytes( text ): return bin(int.from_bytes(text.encode(), 'big')) def bytes_to_string( btext ): #btext = int('0b110100001100101011011000110110001101111', 2) return btext.to_bytes((btext.bit_length() + 7) // 8, 'big').decode() def char_to_bytes(char): return bin(ord(char)) def encodes(text): bext = text.encode(encoding="utf-8") enc_bext = codecs.encode(bext, "hex_codec") return enc_bext.decode("utf-8") def decodes(): <|fim_middle|> if __name__ == "__main__": print( encodes("walla") ) <|fim▁end|>
pass
<|file_name|>bitten.py<|end_file_name|><|fim▁begin|>import codecs unicode_string = "Hello Python 3 String" bytes_object = b"Hello Python 3 Bytes" print(unicode_string, type(unicode_string)) print(bytes_object, type(bytes_object)) #decode to unicode_string ux = str(object=bytes_object, encoding="utf-8", errors="strict") print(ux, type(ux)) ux = bytes_object.decode(encoding="utf-8", errors="strict") print(ux, type(ux)) hex_bytes = codecs.encode(b"Binary Object", "hex_codec") def string_to_bytes( text ): return bin(int.from_bytes(text.encode(), 'big')) def bytes_to_string( btext ): #btext = int('0b110100001100101011011000110110001101111', 2) return btext.to_bytes((btext.bit_length() + 7) // 8, 'big').decode() def char_to_bytes(char): return bin(ord(char)) def encodes(text): bext = text.encode(encoding="utf-8") enc_bext = codecs.encode(bext, "hex_codec") return enc_bext.decode("utf-8") def decodes(): pass if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
print( encodes("walla") )
<|file_name|>bitten.py<|end_file_name|><|fim▁begin|>import codecs unicode_string = "Hello Python 3 String" bytes_object = b"Hello Python 3 Bytes" print(unicode_string, type(unicode_string)) print(bytes_object, type(bytes_object)) #decode to unicode_string ux = str(object=bytes_object, encoding="utf-8", errors="strict") print(ux, type(ux)) ux = bytes_object.decode(encoding="utf-8", errors="strict") print(ux, type(ux)) hex_bytes = codecs.encode(b"Binary Object", "hex_codec") def <|fim_middle|>( text ): return bin(int.from_bytes(text.encode(), 'big')) def bytes_to_string( btext ): #btext = int('0b110100001100101011011000110110001101111', 2) return btext.to_bytes((btext.bit_length() + 7) // 8, 'big').decode() def char_to_bytes(char): return bin(ord(char)) def encodes(text): bext = text.encode(encoding="utf-8") enc_bext = codecs.encode(bext, "hex_codec") return enc_bext.decode("utf-8") def decodes(): pass if __name__ == "__main__": print( encodes("walla") ) <|fim▁end|>
string_to_bytes
<|file_name|>bitten.py<|end_file_name|><|fim▁begin|>import codecs unicode_string = "Hello Python 3 String" bytes_object = b"Hello Python 3 Bytes" print(unicode_string, type(unicode_string)) print(bytes_object, type(bytes_object)) #decode to unicode_string ux = str(object=bytes_object, encoding="utf-8", errors="strict") print(ux, type(ux)) ux = bytes_object.decode(encoding="utf-8", errors="strict") print(ux, type(ux)) hex_bytes = codecs.encode(b"Binary Object", "hex_codec") def string_to_bytes( text ): return bin(int.from_bytes(text.encode(), 'big')) def <|fim_middle|>( btext ): #btext = int('0b110100001100101011011000110110001101111', 2) return btext.to_bytes((btext.bit_length() + 7) // 8, 'big').decode() def char_to_bytes(char): return bin(ord(char)) def encodes(text): bext = text.encode(encoding="utf-8") enc_bext = codecs.encode(bext, "hex_codec") return enc_bext.decode("utf-8") def decodes(): pass if __name__ == "__main__": print( encodes("walla") ) <|fim▁end|>
bytes_to_string
<|file_name|>bitten.py<|end_file_name|><|fim▁begin|>import codecs unicode_string = "Hello Python 3 String" bytes_object = b"Hello Python 3 Bytes" print(unicode_string, type(unicode_string)) print(bytes_object, type(bytes_object)) #decode to unicode_string ux = str(object=bytes_object, encoding="utf-8", errors="strict") print(ux, type(ux)) ux = bytes_object.decode(encoding="utf-8", errors="strict") print(ux, type(ux)) hex_bytes = codecs.encode(b"Binary Object", "hex_codec") def string_to_bytes( text ): return bin(int.from_bytes(text.encode(), 'big')) def bytes_to_string( btext ): #btext = int('0b110100001100101011011000110110001101111', 2) return btext.to_bytes((btext.bit_length() + 7) // 8, 'big').decode() def <|fim_middle|>(char): return bin(ord(char)) def encodes(text): bext = text.encode(encoding="utf-8") enc_bext = codecs.encode(bext, "hex_codec") return enc_bext.decode("utf-8") def decodes(): pass if __name__ == "__main__": print( encodes("walla") ) <|fim▁end|>
char_to_bytes
<|file_name|>bitten.py<|end_file_name|><|fim▁begin|>import codecs unicode_string = "Hello Python 3 String" bytes_object = b"Hello Python 3 Bytes" print(unicode_string, type(unicode_string)) print(bytes_object, type(bytes_object)) #decode to unicode_string ux = str(object=bytes_object, encoding="utf-8", errors="strict") print(ux, type(ux)) ux = bytes_object.decode(encoding="utf-8", errors="strict") print(ux, type(ux)) hex_bytes = codecs.encode(b"Binary Object", "hex_codec") def string_to_bytes( text ): return bin(int.from_bytes(text.encode(), 'big')) def bytes_to_string( btext ): #btext = int('0b110100001100101011011000110110001101111', 2) return btext.to_bytes((btext.bit_length() + 7) // 8, 'big').decode() def char_to_bytes(char): return bin(ord(char)) def <|fim_middle|>(text): bext = text.encode(encoding="utf-8") enc_bext = codecs.encode(bext, "hex_codec") return enc_bext.decode("utf-8") def decodes(): pass if __name__ == "__main__": print( encodes("walla") ) <|fim▁end|>
encodes
<|file_name|>bitten.py<|end_file_name|><|fim▁begin|>import codecs unicode_string = "Hello Python 3 String" bytes_object = b"Hello Python 3 Bytes" print(unicode_string, type(unicode_string)) print(bytes_object, type(bytes_object)) #decode to unicode_string ux = str(object=bytes_object, encoding="utf-8", errors="strict") print(ux, type(ux)) ux = bytes_object.decode(encoding="utf-8", errors="strict") print(ux, type(ux)) hex_bytes = codecs.encode(b"Binary Object", "hex_codec") def string_to_bytes( text ): return bin(int.from_bytes(text.encode(), 'big')) def bytes_to_string( btext ): #btext = int('0b110100001100101011011000110110001101111', 2) return btext.to_bytes((btext.bit_length() + 7) // 8, 'big').decode() def char_to_bytes(char): return bin(ord(char)) def encodes(text): bext = text.encode(encoding="utf-8") enc_bext = codecs.encode(bext, "hex_codec") return enc_bext.decode("utf-8") def <|fim_middle|>(): pass if __name__ == "__main__": print( encodes("walla") ) <|fim▁end|>
decodes
<|file_name|>0040_remove_itemtype_key.py<|end_file_name|><|fim▁begin|>from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('kirppu', '0039_counter_private_key'), ]<|fim▁hole|> operations = [ migrations.AlterUniqueTogether( name='itemtype', unique_together={('event', 'order')}, ), migrations.RemoveField( model_name='itemtype', name='key', ), ]<|fim▁end|>
<|file_name|>0040_remove_itemtype_key.py<|end_file_name|><|fim▁begin|>from django.db import migrations class Migration(migrations.Migration): <|fim_middle|> <|fim▁end|>
dependencies = [ ('kirppu', '0039_counter_private_key'), ] operations = [ migrations.AlterUniqueTogether( name='itemtype', unique_together={('event', 'order')}, ), migrations.RemoveField( model_name='itemtype', name='key', ), ]
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point<|fim▁hole|> for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return<|fim▁end|>
for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key)
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): <|fim_middle|> def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
"""Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): <|fim_middle|> class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
"""If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): <|fim_middle|> return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
"""Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs)
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): <|fim_middle|> class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
""" This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results)
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): <|fim_middle|> def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
"""Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): <|fim_middle|> def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
"""Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results