commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 10
2.94k
| new_contents
stringlengths 21
3.18k
| subject
stringlengths 16
444
| message
stringlengths 17
2.63k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 5
43k
| ndiff
stringlengths 51
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
e12432b0c97d1ddebf16df821fe6c77bb8b6a66b | wagtail/wagtailsites/wagtail_hooks.py | wagtail/wagtailsites/wagtail_hooks.py | from django.conf.urls import include, url
from django.core import urlresolvers
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailcore import hooks
from wagtail.wagtailadmin.menu import MenuItem
from wagtail.wagtailsites import urls
def register_admin_urls():
return [
url(r'^sites/', include(urls)),
]
hooks.register('register_admin_urls', register_admin_urls)
def construct_main_menu(request, menu_items):
if request.user.is_superuser:
menu_items.append(
MenuItem(_('Sites'), urlresolvers.reverse('wagtailsites_index'), classnames='icon icon-site', order=602)
)
hooks.register('construct_main_menu', construct_main_menu)
| from django.conf.urls import include, url
from django.core import urlresolvers
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailcore import hooks
from wagtail.wagtailadmin.menu import MenuItem
from wagtail.wagtailsites import urls
@hooks.register('register_admin_urls')
def register_admin_urls():
return [
url(r'^sites/', include(urls)),
]
class SitesMenuItem(MenuItem):
def is_shown(self, request):
return request.user.is_superuser
@hooks.register('register_settings_menu_item')
def register_sites_menu_item():
return MenuItem(_('Sites'), urlresolvers.reverse('wagtailsites_index'), classnames='icon icon-site', order=602)
| Move Sites to the settings menu (and use decorator syntax for hooks) | Move Sites to the settings menu (and use decorator syntax for hooks)
| Python | bsd-3-clause | mixxorz/wagtail,wagtail/wagtail,KimGlazebrook/wagtail-experiment,gasman/wagtail,mayapurmedia/wagtail,kaedroho/wagtail,jnns/wagtail,serzans/wagtail,hanpama/wagtail,iho/wagtail,marctc/wagtail,kurtw/wagtail,nilnvoid/wagtail,nrsimha/wagtail,gasman/wagtail,jorge-marques/wagtail,Toshakins/wagtail,rsalmaso/wagtail,takeflight/wagtail,Tivix/wagtail,chimeno/wagtail,nilnvoid/wagtail,hanpama/wagtail,torchbox/wagtail,takeflight/wagtail,marctc/wagtail,hanpama/wagtail,chimeno/wagtail,iho/wagtail,taedori81/wagtail,benjaoming/wagtail,takeshineshiro/wagtail,bjesus/wagtail,hamsterbacke23/wagtail,wagtail/wagtail,Tivix/wagtail,torchbox/wagtail,Klaudit/wagtail,rv816/wagtail,m-sanders/wagtail,nealtodd/wagtail,kaedroho/wagtail,FlipperPA/wagtail,chrxr/wagtail,mayapurmedia/wagtail,nrsimha/wagtail,WQuanfeng/wagtail,zerolab/wagtail,KimGlazebrook/wagtail-experiment,benjaoming/wagtail,janusnic/wagtail,taedori81/wagtail,tangentlabs/wagtail,iho/wagtail,kurtrwall/wagtail,FlipperPA/wagtail,mephizzle/wagtail,thenewguy/wagtail,Pennebaker/wagtail,mikedingjan/wagtail,gasman/wagtail,nimasmi/wagtail,hamsterbacke23/wagtail,timorieber/wagtail,bjesus/wagtail,m-sanders/wagtail,stevenewey/wagtail,kurtrwall/wagtail,marctc/wagtail,darith27/wagtail,inonit/wagtail,mixxorz/wagtail,chrxr/wagtail,jorge-marques/wagtail,hamsterbacke23/wagtail,JoshBarr/wagtail,nutztherookie/wagtail,davecranwell/wagtail,mephizzle/wagtail,KimGlazebrook/wagtail-experiment,Tivix/wagtail,jordij/wagtail,janusnic/wagtail,mayapurmedia/wagtail,rjsproxy/wagtail,hamsterbacke23/wagtail,mixxorz/wagtail,davecranwell/wagtail,jorge-marques/wagtail,gasman/wagtail,davecranwell/wagtail,zerolab/wagtail,wagtail/wagtail,mixxorz/wagtail,dresiu/wagtail,chimeno/wagtail,kurtrwall/wagtail,mikedingjan/wagtail,timorieber/wagtail,nealtodd/wagtail,mjec/wagtail,dresiu/wagtail,serzans/wagtail,quru/wagtail,jnns/wagtail,nimasmi/wagtail,tangentlabs/wagtail,kaedroho/wagtail,bjesus/wagtail,takeshineshiro/wagtail,takeshineshiro/wagtail,nutztherookie/wagtail,dresiu/wagtail,rjsproxy/wagtail,torchbox/wagtail,kaedroho/wagtail,nutztherookie/wagtail,rv816/wagtail,kurtw/wagtail,kaedroho/wagtail,WQuanfeng/wagtail,timorieber/wagtail,quru/wagtail,Pennebaker/wagtail,kurtw/wagtail,jordij/wagtail,dresiu/wagtail,zerolab/wagtail,serzans/wagtail,Pennebaker/wagtail,thenewguy/wagtail,iho/wagtail,iansprice/wagtail,Toshakins/wagtail,gasman/wagtail,stevenewey/wagtail,m-sanders/wagtail,JoshBarr/wagtail,zerolab/wagtail,rsalmaso/wagtail,nilnvoid/wagtail,inonit/wagtail,thenewguy/wagtail,rjsproxy/wagtail,wagtail/wagtail,taedori81/wagtail,jorge-marques/wagtail,jnns/wagtail,chrxr/wagtail,Klaudit/wagtail,iansprice/wagtail,nealtodd/wagtail,takeflight/wagtail,Klaudit/wagtail,takeflight/wagtail,tangentlabs/wagtail,nutztherookie/wagtail,Klaudit/wagtail,FlipperPA/wagtail,Toshakins/wagtail,chimeno/wagtail,timorieber/wagtail,quru/wagtail,gogobook/wagtail,mixxorz/wagtail,rv816/wagtail,stevenewey/wagtail,nilnvoid/wagtail,jnns/wagtail,mikedingjan/wagtail,rjsproxy/wagtail,nimasmi/wagtail,darith27/wagtail,mayapurmedia/wagtail,takeshineshiro/wagtail,nealtodd/wagtail,wagtail/wagtail,bjesus/wagtail,mjec/wagtail,janusnic/wagtail,jordij/wagtail,thenewguy/wagtail,marctc/wagtail,rsalmaso/wagtail,zerolab/wagtail,janusnic/wagtail,kurtw/wagtail,quru/wagtail,inonit/wagtail,chrxr/wagtail,gogobook/wagtail,rv816/wagtail,FlipperPA/wagtail,darith27/wagtail,benjaoming/wagtail,taedori81/wagtail,davecranwell/wagtail,Pennebaker/wagtail,tangentlabs/wagtail,hanpama/wagtail,rsalmaso/wagtail,inonit/wagtail,nimasmi/wagtail,WQuanfeng/wagtail,stevenewey/wagtail,thenewguy/wagtail,taedori81/wagtail,m-sanders/wagtail,Toshakins/wagtail,gogobook/wagtail,iansprice/wagtail,JoshBarr/wagtail,chimeno/wagtail,jordij/wagtail,nrsimha/wagtail,Tivix/wagtail,jorge-marques/wagtail,WQuanfeng/wagtail,darith27/wagtail,mephizzle/wagtail,mephizzle/wagtail,JoshBarr/wagtail,nrsimha/wagtail,gogobook/wagtail,iansprice/wagtail,benjaoming/wagtail,mjec/wagtail,mjec/wagtail,mikedingjan/wagtail,torchbox/wagtail,rsalmaso/wagtail,kurtrwall/wagtail,dresiu/wagtail,serzans/wagtail,KimGlazebrook/wagtail-experiment | from django.conf.urls import include, url
from django.core import urlresolvers
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailcore import hooks
from wagtail.wagtailadmin.menu import MenuItem
from wagtail.wagtailsites import urls
+ @hooks.register('register_admin_urls')
def register_admin_urls():
return [
url(r'^sites/', include(urls)),
]
- hooks.register('register_admin_urls', register_admin_urls)
- def construct_main_menu(request, menu_items):
+ class SitesMenuItem(MenuItem):
+ def is_shown(self, request):
- if request.user.is_superuser:
+ return request.user.is_superuser
- menu_items.append(
- MenuItem(_('Sites'), urlresolvers.reverse('wagtailsites_index'), classnames='icon icon-site', order=602)
- )
- hooks.register('construct_main_menu', construct_main_menu)
+ @hooks.register('register_settings_menu_item')
+ def register_sites_menu_item():
+ return MenuItem(_('Sites'), urlresolvers.reverse('wagtailsites_index'), classnames='icon icon-site', order=602)
+ | Move Sites to the settings menu (and use decorator syntax for hooks) | ## Code Before:
from django.conf.urls import include, url
from django.core import urlresolvers
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailcore import hooks
from wagtail.wagtailadmin.menu import MenuItem
from wagtail.wagtailsites import urls
def register_admin_urls():
return [
url(r'^sites/', include(urls)),
]
hooks.register('register_admin_urls', register_admin_urls)
def construct_main_menu(request, menu_items):
if request.user.is_superuser:
menu_items.append(
MenuItem(_('Sites'), urlresolvers.reverse('wagtailsites_index'), classnames='icon icon-site', order=602)
)
hooks.register('construct_main_menu', construct_main_menu)
## Instruction:
Move Sites to the settings menu (and use decorator syntax for hooks)
## Code After:
from django.conf.urls import include, url
from django.core import urlresolvers
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailcore import hooks
from wagtail.wagtailadmin.menu import MenuItem
from wagtail.wagtailsites import urls
@hooks.register('register_admin_urls')
def register_admin_urls():
return [
url(r'^sites/', include(urls)),
]
class SitesMenuItem(MenuItem):
def is_shown(self, request):
return request.user.is_superuser
@hooks.register('register_settings_menu_item')
def register_sites_menu_item():
return MenuItem(_('Sites'), urlresolvers.reverse('wagtailsites_index'), classnames='icon icon-site', order=602)
|
6689858b2364a668b362a5f00d4c86e57141dc37 | numba/cuda/models.py | numba/cuda/models.py | from llvmlite import ir
from numba.core.datamodel.registry import register_default
from numba.core.extending import register_model, models
from numba.core import types
from numba.cuda.types import Dim3, GridGroup, CUDADispatcher
@register_model(Dim3)
class Dim3Model(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('x', types.int32),
('y', types.int32),
('z', types.int32)
]
super().__init__(dmm, fe_type, members)
@register_model(GridGroup)
class GridGroupModel(models.PrimitiveModel):
def __init__(self, dmm, fe_type):
be_type = ir.IntType(64)
super().__init__(dmm, fe_type, be_type)
@register_default(types.Float)
class FloatModel(models.PrimitiveModel):
def __init__(self, dmm, fe_type):
if fe_type == types.float32:
be_type = ir.FloatType()
elif fe_type == types.float16:
be_type = ir.IntType(16)
elif fe_type == types.float64:
be_type = ir.DoubleType()
else:
raise NotImplementedError(fe_type)
super(FloatModel, self).__init__(dmm, fe_type, be_type)
register_model(CUDADispatcher)(models.OpaqueModel)
| from llvmlite import ir
from numba.core.datamodel.registry import register_default
from numba.core.extending import register_model, models
from numba.core import types
from numba.cuda.types import Dim3, GridGroup, CUDADispatcher
@register_model(Dim3)
class Dim3Model(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('x', types.int32),
('y', types.int32),
('z', types.int32)
]
super().__init__(dmm, fe_type, members)
@register_model(GridGroup)
class GridGroupModel(models.PrimitiveModel):
def __init__(self, dmm, fe_type):
be_type = ir.IntType(64)
super().__init__(dmm, fe_type, be_type)
@register_default(types.Float)
class FloatModel(models.PrimitiveModel):
def __init__(self, dmm, fe_type):
if fe_type == types.float16:
be_type = ir.IntType(16)
elif fe_type == types.float32:
be_type = ir.FloatType()
elif fe_type == types.float64:
be_type = ir.DoubleType()
else:
raise NotImplementedError(fe_type)
super(FloatModel, self).__init__(dmm, fe_type, be_type)
register_model(CUDADispatcher)(models.OpaqueModel)
| Reorder FloatModel checks in ascending order | CUDA: Reorder FloatModel checks in ascending order
| Python | bsd-2-clause | cpcloud/numba,numba/numba,numba/numba,seibert/numba,cpcloud/numba,cpcloud/numba,seibert/numba,seibert/numba,cpcloud/numba,numba/numba,IntelLabs/numba,numba/numba,IntelLabs/numba,cpcloud/numba,seibert/numba,IntelLabs/numba,IntelLabs/numba,seibert/numba,IntelLabs/numba,numba/numba | from llvmlite import ir
from numba.core.datamodel.registry import register_default
from numba.core.extending import register_model, models
from numba.core import types
from numba.cuda.types import Dim3, GridGroup, CUDADispatcher
@register_model(Dim3)
class Dim3Model(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('x', types.int32),
('y', types.int32),
('z', types.int32)
]
super().__init__(dmm, fe_type, members)
@register_model(GridGroup)
class GridGroupModel(models.PrimitiveModel):
def __init__(self, dmm, fe_type):
be_type = ir.IntType(64)
super().__init__(dmm, fe_type, be_type)
@register_default(types.Float)
class FloatModel(models.PrimitiveModel):
def __init__(self, dmm, fe_type):
+ if fe_type == types.float16:
+ be_type = ir.IntType(16)
- if fe_type == types.float32:
+ elif fe_type == types.float32:
be_type = ir.FloatType()
- elif fe_type == types.float16:
- be_type = ir.IntType(16)
elif fe_type == types.float64:
be_type = ir.DoubleType()
else:
raise NotImplementedError(fe_type)
super(FloatModel, self).__init__(dmm, fe_type, be_type)
register_model(CUDADispatcher)(models.OpaqueModel)
| Reorder FloatModel checks in ascending order | ## Code Before:
from llvmlite import ir
from numba.core.datamodel.registry import register_default
from numba.core.extending import register_model, models
from numba.core import types
from numba.cuda.types import Dim3, GridGroup, CUDADispatcher
@register_model(Dim3)
class Dim3Model(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('x', types.int32),
('y', types.int32),
('z', types.int32)
]
super().__init__(dmm, fe_type, members)
@register_model(GridGroup)
class GridGroupModel(models.PrimitiveModel):
def __init__(self, dmm, fe_type):
be_type = ir.IntType(64)
super().__init__(dmm, fe_type, be_type)
@register_default(types.Float)
class FloatModel(models.PrimitiveModel):
def __init__(self, dmm, fe_type):
if fe_type == types.float32:
be_type = ir.FloatType()
elif fe_type == types.float16:
be_type = ir.IntType(16)
elif fe_type == types.float64:
be_type = ir.DoubleType()
else:
raise NotImplementedError(fe_type)
super(FloatModel, self).__init__(dmm, fe_type, be_type)
register_model(CUDADispatcher)(models.OpaqueModel)
## Instruction:
Reorder FloatModel checks in ascending order
## Code After:
from llvmlite import ir
from numba.core.datamodel.registry import register_default
from numba.core.extending import register_model, models
from numba.core import types
from numba.cuda.types import Dim3, GridGroup, CUDADispatcher
@register_model(Dim3)
class Dim3Model(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('x', types.int32),
('y', types.int32),
('z', types.int32)
]
super().__init__(dmm, fe_type, members)
@register_model(GridGroup)
class GridGroupModel(models.PrimitiveModel):
def __init__(self, dmm, fe_type):
be_type = ir.IntType(64)
super().__init__(dmm, fe_type, be_type)
@register_default(types.Float)
class FloatModel(models.PrimitiveModel):
def __init__(self, dmm, fe_type):
if fe_type == types.float16:
be_type = ir.IntType(16)
elif fe_type == types.float32:
be_type = ir.FloatType()
elif fe_type == types.float64:
be_type = ir.DoubleType()
else:
raise NotImplementedError(fe_type)
super(FloatModel, self).__init__(dmm, fe_type, be_type)
register_model(CUDADispatcher)(models.OpaqueModel)
|
4a650922ee97b9cb54b203cab9709d511487d9ff | silver/tests/factories.py | silver/tests/factories.py | """Factories for the silver app."""
# import factory
# from .. import models
| import factory
from silver.models import Provider
class ProviderFactory(factory.django.DjangoModelFactory):
class Meta:
model = Provider
| Add factory for the Provider model | Add factory for the Provider model
| Python | apache-2.0 | PressLabs/silver,PressLabs/silver,PressLabs/silver | - """Factories for the silver app."""
- # import factory
+ import factory
- # from .. import models
+ from silver.models import Provider
+
+ class ProviderFactory(factory.django.DjangoModelFactory):
+ class Meta:
+ model = Provider
+ | Add factory for the Provider model | ## Code Before:
"""Factories for the silver app."""
# import factory
# from .. import models
## Instruction:
Add factory for the Provider model
## Code After:
import factory
from silver.models import Provider
class ProviderFactory(factory.django.DjangoModelFactory):
class Meta:
model = Provider
|
d0a907872749f1bb54d6e8e160ea170059289623 | source/custom/combo.py | source/custom/combo.py |
import wx
from wx.combo import OwnerDrawnComboBox
class ComboBox(OwnerDrawnComboBox):
def __init__(self, parent, win_id, value=wx.EmptyString, pos=wx.DefaultPosition,
size=wx.DefaultSize, choices=[], style=0, validator=wx.DefaultValidator,
name=wx.ComboBoxNameStr):
OwnerDrawnComboBox.__init__(self, parent, win_id, value, pos, size, choices,
style, validator, name)
self.Default = self.GetLabel()
self.Priority = []
## Resets ComboBox to defaults
def Reset(self):
if not self.Count:
self.SetValue(self.Default)
return self.Value == self.Default
return False
|
import wx
from wx.combo import OwnerDrawnComboBox
class ComboBox(OwnerDrawnComboBox):
def __init__(self, parent, win_id=wx.ID_ANY, value=wx.EmptyString, pos=wx.DefaultPosition,
size=wx.DefaultSize, choices=[], style=0, validator=wx.DefaultValidator,
name=wx.ComboBoxNameStr):
OwnerDrawnComboBox.__init__(self, parent, win_id, value, pos, size, choices,
style, validator, name)
self.Default = self.GetLabel()
self.Priority = []
## Resets ComboBox to defaults
def Reset(self):
if not self.Count:
self.SetValue(self.Default)
return self.Value == self.Default
return False
| Set ComboBox class default ID to wx.ID_ANY | Set ComboBox class default ID to wx.ID_ANY | Python | mit | AntumDeluge/desktop_recorder,AntumDeluge/desktop_recorder |
import wx
from wx.combo import OwnerDrawnComboBox
class ComboBox(OwnerDrawnComboBox):
- def __init__(self, parent, win_id, value=wx.EmptyString, pos=wx.DefaultPosition,
+ def __init__(self, parent, win_id=wx.ID_ANY, value=wx.EmptyString, pos=wx.DefaultPosition,
size=wx.DefaultSize, choices=[], style=0, validator=wx.DefaultValidator,
name=wx.ComboBoxNameStr):
OwnerDrawnComboBox.__init__(self, parent, win_id, value, pos, size, choices,
style, validator, name)
self.Default = self.GetLabel()
self.Priority = []
## Resets ComboBox to defaults
def Reset(self):
if not self.Count:
self.SetValue(self.Default)
return self.Value == self.Default
return False
| Set ComboBox class default ID to wx.ID_ANY | ## Code Before:
import wx
from wx.combo import OwnerDrawnComboBox
class ComboBox(OwnerDrawnComboBox):
def __init__(self, parent, win_id, value=wx.EmptyString, pos=wx.DefaultPosition,
size=wx.DefaultSize, choices=[], style=0, validator=wx.DefaultValidator,
name=wx.ComboBoxNameStr):
OwnerDrawnComboBox.__init__(self, parent, win_id, value, pos, size, choices,
style, validator, name)
self.Default = self.GetLabel()
self.Priority = []
## Resets ComboBox to defaults
def Reset(self):
if not self.Count:
self.SetValue(self.Default)
return self.Value == self.Default
return False
## Instruction:
Set ComboBox class default ID to wx.ID_ANY
## Code After:
import wx
from wx.combo import OwnerDrawnComboBox
class ComboBox(OwnerDrawnComboBox):
def __init__(self, parent, win_id=wx.ID_ANY, value=wx.EmptyString, pos=wx.DefaultPosition,
size=wx.DefaultSize, choices=[], style=0, validator=wx.DefaultValidator,
name=wx.ComboBoxNameStr):
OwnerDrawnComboBox.__init__(self, parent, win_id, value, pos, size, choices,
style, validator, name)
self.Default = self.GetLabel()
self.Priority = []
## Resets ComboBox to defaults
def Reset(self):
if not self.Count:
self.SetValue(self.Default)
return self.Value == self.Default
return False
|
2560ca287e81cbefb6037e5688bfa4ef74d85149 | clock.py | clock.py | from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
scheduler = BlockingScheduler()
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier")
subprocess.run(
"notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
shell=True,
check=True)
# @scheduler.scheduled_job('interval', minutes=10)
# def timed_job_min10():
# print("Run notifier")
# subprocess.run(
# "notifier -concurrency=5 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
# shell=True,
# check=True)
scheduler.start()
| from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
scheduler = BlockingScheduler()
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier")
subprocess.check_call(
"notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
# @scheduler.scheduled_job('interval', minutes=10)
# def timed_job_min10():
# print("Run notifier")
# subprocess.run(
# "notifier -concurrency=5 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
# shell=True,
# check=True)
scheduler.start()
| Change call method for Python2.7 | Change call method for Python2.7
| Python | mit | oinume/lekcije,oinume/dmm-eikaiwa-fft,oinume/lekcije,oinume/dmm-eikaiwa-fft,oinume/lekcije,oinume/dmm-eikaiwa-fft,oinume/lekcije,oinume/lekcije,oinume/lekcije,oinume/dmm-eikaiwa-fft | from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
scheduler = BlockingScheduler()
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier")
- subprocess.run(
+ subprocess.check_call(
"notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
- shell=True,
+ shell=True)
- check=True)
# @scheduler.scheduled_job('interval', minutes=10)
# def timed_job_min10():
# print("Run notifier")
# subprocess.run(
# "notifier -concurrency=5 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
# shell=True,
# check=True)
scheduler.start()
| Change call method for Python2.7 | ## Code Before:
from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
scheduler = BlockingScheduler()
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier")
subprocess.run(
"notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
shell=True,
check=True)
# @scheduler.scheduled_job('interval', minutes=10)
# def timed_job_min10():
# print("Run notifier")
# subprocess.run(
# "notifier -concurrency=5 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
# shell=True,
# check=True)
scheduler.start()
## Instruction:
Change call method for Python2.7
## Code After:
from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
scheduler = BlockingScheduler()
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier")
subprocess.check_call(
"notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
# @scheduler.scheduled_job('interval', minutes=10)
# def timed_job_min10():
# print("Run notifier")
# subprocess.run(
# "notifier -concurrency=5 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
# shell=True,
# check=True)
scheduler.start()
|
6bb9a4ed50ad879c56cdeae0dedb49bba6780780 | matchers/volunteer.py | matchers/volunteer.py | import random
from base import BaseMatcher
class VolunteerMatcher(BaseMatcher):
dev_text = "volunteer someone"
all_text = "volunteer a dev"
dev_candidates = ['Steve', 'Arthur', 'Honza', 'Fernando', 'Nick']
all_candidates = dev_candidates + ['Craig', 'Evan']
def respond(self, message, user=None):
if self.dev_text in message.lower():
victim = random.choice(self.dev_candidates)
self.speak('%s is it' % victim)
elif self.all_text in message.lower():
victim = random.choice(self.all_candidates)
self.speak('%s is it' % victim)
| import random
from base import BaseMatcher
class VolunteerMatcher(BaseMatcher):
dev_text = "volunteer someone"
all_text = "volunteer a dev"
dev_candidates = ['sjl', 'arthurdebert', 'honza', 'fernandotakai', 'nicksergeant']
all_candidates = dev_candidates + ['cz', 'ehazlett']
def respond(self, message, user=None):
if self.dev_text in message.lower():
victim = random.choice(self.dev_candidates)
self.speak('%s is it' % victim)
elif self.all_text in message.lower():
victim = random.choice(self.all_candidates)
self.speak('%s is it' % victim)
| Use IRC Nicks instead of real names. | Use IRC Nicks instead of real names.
| Python | bsd-2-clause | honza/nigel | import random
from base import BaseMatcher
class VolunteerMatcher(BaseMatcher):
dev_text = "volunteer someone"
all_text = "volunteer a dev"
- dev_candidates = ['Steve', 'Arthur', 'Honza', 'Fernando', 'Nick']
+ dev_candidates = ['sjl', 'arthurdebert', 'honza', 'fernandotakai', 'nicksergeant']
- all_candidates = dev_candidates + ['Craig', 'Evan']
+ all_candidates = dev_candidates + ['cz', 'ehazlett']
def respond(self, message, user=None):
if self.dev_text in message.lower():
victim = random.choice(self.dev_candidates)
self.speak('%s is it' % victim)
elif self.all_text in message.lower():
victim = random.choice(self.all_candidates)
self.speak('%s is it' % victim)
| Use IRC Nicks instead of real names. | ## Code Before:
import random
from base import BaseMatcher
class VolunteerMatcher(BaseMatcher):
dev_text = "volunteer someone"
all_text = "volunteer a dev"
dev_candidates = ['Steve', 'Arthur', 'Honza', 'Fernando', 'Nick']
all_candidates = dev_candidates + ['Craig', 'Evan']
def respond(self, message, user=None):
if self.dev_text in message.lower():
victim = random.choice(self.dev_candidates)
self.speak('%s is it' % victim)
elif self.all_text in message.lower():
victim = random.choice(self.all_candidates)
self.speak('%s is it' % victim)
## Instruction:
Use IRC Nicks instead of real names.
## Code After:
import random
from base import BaseMatcher
class VolunteerMatcher(BaseMatcher):
dev_text = "volunteer someone"
all_text = "volunteer a dev"
dev_candidates = ['sjl', 'arthurdebert', 'honza', 'fernandotakai', 'nicksergeant']
all_candidates = dev_candidates + ['cz', 'ehazlett']
def respond(self, message, user=None):
if self.dev_text in message.lower():
victim = random.choice(self.dev_candidates)
self.speak('%s is it' % victim)
elif self.all_text in message.lower():
victim = random.choice(self.all_candidates)
self.speak('%s is it' % victim)
|
7016b7bb026e0fe557ca06efa81dace9999e526d | hubbot/Modules/Healthcheck.py | hubbot/Modules/Healthcheck.py | from twisted.internet import reactor, protocol
from hubbot.moduleinterface import ModuleInterface
class Echo(protocol.Protocol):
"""This is just about the simplest possible protocol"""
def dataReceived(self, data):
"""As soon as any data is received, write it back."""
self.transport.write(data)
class Healthcheck(ModuleInterface):
port = 9999
def __init__(self, bot):
self.healthcheck_server = protocol.ServerFactory()
self.healthcheck_server.protocol = Echo
super().__init__(bot)
def on_load(self):
reactor.listenTCP(self.port, self.healthcheck_server)
def on_unload(self):
reactor.stopListening(self.port)
def help(self, message):
return f"Hosts an HTTP healthcheck server on port {self.port}."
| from twisted.protocols import basic
from twisted.internet import protocol, reactor
from hubbot.moduleinterface import ModuleInterface
class HealthcheckProtocol(basic.LineReceiver):
def lineReceived(self, line):
response_body = "All is well. Ish."
self.sendLine("HTTP/1.0 200 OK".encode("UTF-8"))
self.sendLine("Content-Type: text/plain".encode("UTF-8"))
self.sendLine(f"Content-Length: {len(response_body)}\n".encode("UTF-8"))
self.transport.write(response_body)
self.transport.loseConnection()
class Healthcheck(ModuleInterface):
port = 9999
def __init__(self, bot):
self.healthcheck_server = protocol.ServerFactory()
self.healthcheck_server.protocol = HealthcheckProtocol
super().__init__(bot)
def on_load(self):
reactor.listenTCP(self.port, self.healthcheck_server)
def on_unload(self):
reactor.stopListening(self.port)
def help(self, message):
return f"Hosts an HTTP healthcheck server on port {self.port}."
| Write a slightly less dumb protocol? | Write a slightly less dumb protocol?
| Python | mit | HubbeKing/Hubbot_Twisted | + from twisted.protocols import basic
- from twisted.internet import reactor, protocol
+ from twisted.internet import protocol, reactor
from hubbot.moduleinterface import ModuleInterface
+ class HealthcheckProtocol(basic.LineReceiver):
- class Echo(protocol.Protocol):
- """This is just about the simplest possible protocol"""
-
- def dataReceived(self, data):
+ def lineReceived(self, line):
- """As soon as any data is received, write it back."""
+ response_body = "All is well. Ish."
+ self.sendLine("HTTP/1.0 200 OK".encode("UTF-8"))
+ self.sendLine("Content-Type: text/plain".encode("UTF-8"))
+ self.sendLine(f"Content-Length: {len(response_body)}\n".encode("UTF-8"))
- self.transport.write(data)
+ self.transport.write(response_body)
+ self.transport.loseConnection()
class Healthcheck(ModuleInterface):
port = 9999
def __init__(self, bot):
self.healthcheck_server = protocol.ServerFactory()
- self.healthcheck_server.protocol = Echo
+ self.healthcheck_server.protocol = HealthcheckProtocol
super().__init__(bot)
def on_load(self):
reactor.listenTCP(self.port, self.healthcheck_server)
def on_unload(self):
reactor.stopListening(self.port)
def help(self, message):
return f"Hosts an HTTP healthcheck server on port {self.port}."
| Write a slightly less dumb protocol? | ## Code Before:
from twisted.internet import reactor, protocol
from hubbot.moduleinterface import ModuleInterface
class Echo(protocol.Protocol):
"""This is just about the simplest possible protocol"""
def dataReceived(self, data):
"""As soon as any data is received, write it back."""
self.transport.write(data)
class Healthcheck(ModuleInterface):
port = 9999
def __init__(self, bot):
self.healthcheck_server = protocol.ServerFactory()
self.healthcheck_server.protocol = Echo
super().__init__(bot)
def on_load(self):
reactor.listenTCP(self.port, self.healthcheck_server)
def on_unload(self):
reactor.stopListening(self.port)
def help(self, message):
return f"Hosts an HTTP healthcheck server on port {self.port}."
## Instruction:
Write a slightly less dumb protocol?
## Code After:
from twisted.protocols import basic
from twisted.internet import protocol, reactor
from hubbot.moduleinterface import ModuleInterface
class HealthcheckProtocol(basic.LineReceiver):
def lineReceived(self, line):
response_body = "All is well. Ish."
self.sendLine("HTTP/1.0 200 OK".encode("UTF-8"))
self.sendLine("Content-Type: text/plain".encode("UTF-8"))
self.sendLine(f"Content-Length: {len(response_body)}\n".encode("UTF-8"))
self.transport.write(response_body)
self.transport.loseConnection()
class Healthcheck(ModuleInterface):
port = 9999
def __init__(self, bot):
self.healthcheck_server = protocol.ServerFactory()
self.healthcheck_server.protocol = HealthcheckProtocol
super().__init__(bot)
def on_load(self):
reactor.listenTCP(self.port, self.healthcheck_server)
def on_unload(self):
reactor.stopListening(self.port)
def help(self, message):
return f"Hosts an HTTP healthcheck server on port {self.port}."
|
0eaff91695eefcf289e31d8ca93d19ab5bbd392d | katana/expr.py | katana/expr.py | import re
class Expr(object):
def __init__(self, name, regex):
self.name = name
self.regex = regex
def on_match(self, string):
return [self.name, string]
def callback(self, _, string):
return self.on_match(string)
class Scanner(object):
def __init__(self, exprs):
self.scanner = re.Scanner([
(e.regex, e.callback) for e in exprs
])
def match(self, string):
tokens, extra = self.scanner.scan(string)
if extra:
raise ValueError
return tokens
| import re
class Expr(object):
def __init__(self, name, regex):
self.name = name
self.regex = regex
def __iter__(self):
yield self.regex
yield lambda _, token: self.on_match(token)
def on_match(self, string):
return [self.name, string]
class Scanner(object):
def __init__(self, exprs):
self.scanner = re.Scanner([
tuple(e) for e in exprs
])
def match(self, string):
tokens, extra = self.scanner.scan(string)
if extra:
raise ValueError
return tokens
| Refactor Expr object to be more self contained | Refactor Expr object to be more self contained
| Python | mit | eugene-eeo/katana | import re
class Expr(object):
def __init__(self, name, regex):
self.name = name
self.regex = regex
+ def __iter__(self):
+ yield self.regex
+ yield lambda _, token: self.on_match(token)
+
def on_match(self, string):
return [self.name, string]
-
- def callback(self, _, string):
- return self.on_match(string)
class Scanner(object):
def __init__(self, exprs):
self.scanner = re.Scanner([
- (e.regex, e.callback) for e in exprs
+ tuple(e) for e in exprs
])
def match(self, string):
tokens, extra = self.scanner.scan(string)
if extra:
raise ValueError
return tokens
| Refactor Expr object to be more self contained | ## Code Before:
import re
class Expr(object):
def __init__(self, name, regex):
self.name = name
self.regex = regex
def on_match(self, string):
return [self.name, string]
def callback(self, _, string):
return self.on_match(string)
class Scanner(object):
def __init__(self, exprs):
self.scanner = re.Scanner([
(e.regex, e.callback) for e in exprs
])
def match(self, string):
tokens, extra = self.scanner.scan(string)
if extra:
raise ValueError
return tokens
## Instruction:
Refactor Expr object to be more self contained
## Code After:
import re
class Expr(object):
def __init__(self, name, regex):
self.name = name
self.regex = regex
def __iter__(self):
yield self.regex
yield lambda _, token: self.on_match(token)
def on_match(self, string):
return [self.name, string]
class Scanner(object):
def __init__(self, exprs):
self.scanner = re.Scanner([
tuple(e) for e in exprs
])
def match(self, string):
tokens, extra = self.scanner.scan(string)
if extra:
raise ValueError
return tokens
|
ce2e5b0dc3ddafe931a902cb7aa24c3adbc246b7 | fireplace/cards/wog/neutral_legendary.py | fireplace/cards/wog/neutral_legendary.py | from ..utils import *
##
# Minions
| from ..utils import *
##
# Minions
class OG_122:
"Mukla, Tyrant of the Vale"
play = Give(CONTROLLER, "EX1_014t") * 2
class OG_318:
"Hogger, Doom of Elwynn"
events = SELF_DAMAGE.on(Summon(CONTROLLER, "OG_318t"))
class OG_338:
"Nat, the Darkfisher"
events = BeginTurn(OPPONENT).on(COINFLIP & Draw(OPPONENT))
| Implement corrupted Mukla, Hogger and Nat | Implement corrupted Mukla, Hogger and Nat
| Python | agpl-3.0 | beheh/fireplace,NightKev/fireplace,jleclanche/fireplace | from ..utils import *
##
# Minions
+ class OG_122:
+ "Mukla, Tyrant of the Vale"
+ play = Give(CONTROLLER, "EX1_014t") * 2
+
+
+ class OG_318:
+ "Hogger, Doom of Elwynn"
+ events = SELF_DAMAGE.on(Summon(CONTROLLER, "OG_318t"))
+
+
+ class OG_338:
+ "Nat, the Darkfisher"
+ events = BeginTurn(OPPONENT).on(COINFLIP & Draw(OPPONENT))
+ | Implement corrupted Mukla, Hogger and Nat | ## Code Before:
from ..utils import *
##
# Minions
## Instruction:
Implement corrupted Mukla, Hogger and Nat
## Code After:
from ..utils import *
##
# Minions
class OG_122:
"Mukla, Tyrant of the Vale"
play = Give(CONTROLLER, "EX1_014t") * 2
class OG_318:
"Hogger, Doom of Elwynn"
events = SELF_DAMAGE.on(Summon(CONTROLLER, "OG_318t"))
class OG_338:
"Nat, the Darkfisher"
events = BeginTurn(OPPONENT).on(COINFLIP & Draw(OPPONENT))
|
5ed9e43ec451aca9bdca4391bd35934e5fe4aea3 | huts/management/commands/dumphutsjson.py | huts/management/commands/dumphutsjson.py | from django.core.management.base import BaseCommand
from huts.utils import export
class Command(BaseCommand):
args = ''
help = 'Dumps the huts, agencies, and regions in the json api format.'
def handle(self, *args, **options):
print(export.db_as_json().encode('utf-8'))
| from optparse import make_option
from django.core.management.base import BaseCommand
from huts.utils import export
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
'--file',
help='Write to file instead of stdout'
),
)
help = 'Dumps the huts, agencies, and regions in the json api format.'
def handle(self, *args, **options):
out = options['file'] or self.stdout
out.write(export.db_as_json().encode('utf-8'))
| Update command to take file argument | Update command to take file argument
| Python | mit | dylanfprice/hutmap,dylanfprice/hutmap,dylanfprice/hutmap,muescha/hutmap,muescha/hutmap,dylanfprice/hutmap,muescha/hutmap,muescha/hutmap | + from optparse import make_option
+
from django.core.management.base import BaseCommand
from huts.utils import export
+
class Command(BaseCommand):
- args = ''
+ option_list = BaseCommand.option_list + (
+ make_option(
+ '--file',
+ help='Write to file instead of stdout'
+ ),
+ )
help = 'Dumps the huts, agencies, and regions in the json api format.'
def handle(self, *args, **options):
+ out = options['file'] or self.stdout
- print(export.db_as_json().encode('utf-8'))
+ out.write(export.db_as_json().encode('utf-8'))
| Update command to take file argument | ## Code Before:
from django.core.management.base import BaseCommand
from huts.utils import export
class Command(BaseCommand):
args = ''
help = 'Dumps the huts, agencies, and regions in the json api format.'
def handle(self, *args, **options):
print(export.db_as_json().encode('utf-8'))
## Instruction:
Update command to take file argument
## Code After:
from optparse import make_option
from django.core.management.base import BaseCommand
from huts.utils import export
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
'--file',
help='Write to file instead of stdout'
),
)
help = 'Dumps the huts, agencies, and regions in the json api format.'
def handle(self, *args, **options):
out = options['file'] or self.stdout
out.write(export.db_as_json().encode('utf-8'))
|
2d3e52567d7d361428ce93d02cc42ecaddacab6c | tests/test_commands.py | tests/test_commands.py |
from couchapp import commands
from couchapp.errors import AppError
from mock import Mock, patch
from nose.tools import raises
@patch('couchapp.commands.document')
def test_init_dest(mock_doc):
commands.init(None, None, '/tmp/mk')
mock_doc.assert_called_once_with('/tmp/mk', create=True)
@patch('os.getcwd', return_value='/mock_dir')
@patch('couchapp.commands.document')
def test_init_dest_auto(mock_doc, mock_cwd):
commands.init(None, None)
mock_doc.assert_called_once_with('/mock_dir', create=True)
@raises(AppError)
@patch('os.getcwd', return_value=None)
@patch('couchapp.commands.document')
def test_init_dest_auto(mock_doc, mock_cwd):
commands.init(None, None)
|
from couchapp import commands
from couchapp.errors import AppError
from mock import Mock, patch
from nose.tools import raises
@patch('couchapp.commands.document')
def test_init_dest(mock_doc):
commands.init(None, None, '/tmp/mk')
mock_doc.assert_called_once_with('/tmp/mk', create=True)
@patch('os.getcwd', return_value='/mock_dir')
@patch('couchapp.commands.document')
def test_init_dest_auto(mock_doc, mock_cwd):
commands.init(None, None)
mock_doc.assert_called_once_with('/mock_dir', create=True)
@raises(AppError)
@patch('os.getcwd', return_value=None)
@patch('couchapp.commands.document')
def test_init_dest_none(mock_doc, mock_cwd):
commands.init(None, None)
def test_push_outside():
'''
$ couchapp push /path/to/app
'''
pass
@patch('couchapp.commands.document', return_value='{"status": "ok"}')
def test_push_export_outside(mock_doc):
'''
$ couchapp push --export /path/to/app
'''
conf = Mock(name='conf')
appdir = '/mock_dir'
commands.push(conf, None, appdir, export=True)
mock_doc.assert_called_once_with(appdir, create=False, docid=None)
conf.update.assert_called_once_with(appdir)
@patch('couchapp.commands.document', return_value='{"status": "ok"}')
def test_push_export_inside(mock_doc):
'''
In the app dir::
$ couchapp push --export
'''
conf = Mock(name='conf')
appdir = '/mock_dir'
commands.push(conf, appdir, export=True)
mock_doc.assert_called_once_with(appdir, create=False, docid=None)
conf.update.assert_called_once_with(appdir)
| Test cases for push with export flag | Test cases for push with export flag
| Python | apache-2.0 | couchapp/couchapp,h4ki/couchapp,couchapp/couchapp,couchapp/couchapp,h4ki/couchapp,h4ki/couchapp,couchapp/couchapp,h4ki/couchapp |
from couchapp import commands
from couchapp.errors import AppError
from mock import Mock, patch
from nose.tools import raises
@patch('couchapp.commands.document')
def test_init_dest(mock_doc):
commands.init(None, None, '/tmp/mk')
mock_doc.assert_called_once_with('/tmp/mk', create=True)
@patch('os.getcwd', return_value='/mock_dir')
@patch('couchapp.commands.document')
def test_init_dest_auto(mock_doc, mock_cwd):
commands.init(None, None)
mock_doc.assert_called_once_with('/mock_dir', create=True)
@raises(AppError)
@patch('os.getcwd', return_value=None)
@patch('couchapp.commands.document')
- def test_init_dest_auto(mock_doc, mock_cwd):
+ def test_init_dest_none(mock_doc, mock_cwd):
commands.init(None, None)
+
+ def test_push_outside():
+ '''
+ $ couchapp push /path/to/app
+ '''
+ pass
+
+
+ @patch('couchapp.commands.document', return_value='{"status": "ok"}')
+ def test_push_export_outside(mock_doc):
+ '''
+ $ couchapp push --export /path/to/app
+ '''
+ conf = Mock(name='conf')
+ appdir = '/mock_dir'
+
+ commands.push(conf, None, appdir, export=True)
+ mock_doc.assert_called_once_with(appdir, create=False, docid=None)
+ conf.update.assert_called_once_with(appdir)
+
+
+ @patch('couchapp.commands.document', return_value='{"status": "ok"}')
+ def test_push_export_inside(mock_doc):
+ '''
+ In the app dir::
+
+ $ couchapp push --export
+ '''
+ conf = Mock(name='conf')
+ appdir = '/mock_dir'
+
+ commands.push(conf, appdir, export=True)
+ mock_doc.assert_called_once_with(appdir, create=False, docid=None)
+ conf.update.assert_called_once_with(appdir)
+ | Test cases for push with export flag | ## Code Before:
from couchapp import commands
from couchapp.errors import AppError
from mock import Mock, patch
from nose.tools import raises
@patch('couchapp.commands.document')
def test_init_dest(mock_doc):
commands.init(None, None, '/tmp/mk')
mock_doc.assert_called_once_with('/tmp/mk', create=True)
@patch('os.getcwd', return_value='/mock_dir')
@patch('couchapp.commands.document')
def test_init_dest_auto(mock_doc, mock_cwd):
commands.init(None, None)
mock_doc.assert_called_once_with('/mock_dir', create=True)
@raises(AppError)
@patch('os.getcwd', return_value=None)
@patch('couchapp.commands.document')
def test_init_dest_auto(mock_doc, mock_cwd):
commands.init(None, None)
## Instruction:
Test cases for push with export flag
## Code After:
from couchapp import commands
from couchapp.errors import AppError
from mock import Mock, patch
from nose.tools import raises
@patch('couchapp.commands.document')
def test_init_dest(mock_doc):
commands.init(None, None, '/tmp/mk')
mock_doc.assert_called_once_with('/tmp/mk', create=True)
@patch('os.getcwd', return_value='/mock_dir')
@patch('couchapp.commands.document')
def test_init_dest_auto(mock_doc, mock_cwd):
commands.init(None, None)
mock_doc.assert_called_once_with('/mock_dir', create=True)
@raises(AppError)
@patch('os.getcwd', return_value=None)
@patch('couchapp.commands.document')
def test_init_dest_none(mock_doc, mock_cwd):
commands.init(None, None)
def test_push_outside():
'''
$ couchapp push /path/to/app
'''
pass
@patch('couchapp.commands.document', return_value='{"status": "ok"}')
def test_push_export_outside(mock_doc):
'''
$ couchapp push --export /path/to/app
'''
conf = Mock(name='conf')
appdir = '/mock_dir'
commands.push(conf, None, appdir, export=True)
mock_doc.assert_called_once_with(appdir, create=False, docid=None)
conf.update.assert_called_once_with(appdir)
@patch('couchapp.commands.document', return_value='{"status": "ok"}')
def test_push_export_inside(mock_doc):
'''
In the app dir::
$ couchapp push --export
'''
conf = Mock(name='conf')
appdir = '/mock_dir'
commands.push(conf, appdir, export=True)
mock_doc.assert_called_once_with(appdir, create=False, docid=None)
conf.update.assert_called_once_with(appdir)
|
9dc253b79d885ca205b557f88fca6fa35bd8fe21 | tests/test_selector.py | tests/test_selector.py | from contextlib import contextmanager
from scell import Selector
from pytest import raises, fixture
def test_select(selector):
res = list(selector.select())
assert res
for event in res:
assert event.ready
def test_select_empty():
sel = Selector()
assert list(sel.select()) == []
def test_unregister(selector):
for fp in list(selector):
selector.unregister(fp)
assert not selector
def test_info(selector):
for fp in selector:
assert selector.info(fp).wants_read
assert selector.info(0) is None
def test_callbacks(selector):
res = selector.select()
exp = len(selector)
assert sum(m.callback() for m in res) == exp
def test_ready(selector):
ready = list(selector.ready())
assert ready
for event in ready:
assert event.ready
class TestScoped(object):
@fixture
def sel(self):
return Selector()
def test_peaceful(self, sel, handles):
with sel.scoped(handles) as monitors:
r = list(sel.ready())
for ev in r:
assert ev.monitored in monitors
assert ev.fp in handles
assert r
assert not sel
def test_exception(self, sel, handles):
with raises(NameError):
with sel.scoped(handles) as _:
raise NameError
assert not sel
| from contextlib import contextmanager
from scell import Selector
from pytest import raises, fixture
def test_select(selector):
res = list(selector.select())
assert res
for event in res:
assert event.ready
def test_select_empty():
sel = Selector()
assert list(sel.select()) == []
def test_unregister(selector):
for fp in list(selector):
selector.unregister(fp)
assert not selector
def test_info(selector):
for fp in selector:
assert selector.info(fp).wants_read
assert selector.info(0) is None
def test_callbacks(selector):
res = selector.select()
exp = len(selector)
assert sum(m.callback() for m in res) == exp
def test_ready(selector):
ready = list(selector.ready())
assert ready
for event in ready:
assert event.ready
class TestScoped(object):
@fixture
def sel(self):
return Selector()
def test_peaceful(self, sel, handles):
with sel.scoped(handles) as monitors:
r = set(k.fp for k in sel.ready())
assert r == set(handles)
assert not sel
def test_exception(self, sel, handles):
with raises(NameError):
with sel.scoped(handles) as _:
raise NameError
assert not sel
| Make Selector.scope test more rigorous | Make Selector.scope test more rigorous
| Python | mit | eugene-eeo/scell | from contextlib import contextmanager
from scell import Selector
from pytest import raises, fixture
def test_select(selector):
res = list(selector.select())
assert res
for event in res:
assert event.ready
def test_select_empty():
sel = Selector()
assert list(sel.select()) == []
def test_unregister(selector):
for fp in list(selector):
selector.unregister(fp)
assert not selector
def test_info(selector):
for fp in selector:
assert selector.info(fp).wants_read
assert selector.info(0) is None
def test_callbacks(selector):
res = selector.select()
exp = len(selector)
assert sum(m.callback() for m in res) == exp
def test_ready(selector):
ready = list(selector.ready())
assert ready
for event in ready:
assert event.ready
class TestScoped(object):
@fixture
def sel(self):
return Selector()
def test_peaceful(self, sel, handles):
with sel.scoped(handles) as monitors:
- r = list(sel.ready())
+ r = set(k.fp for k in sel.ready())
+ assert r == set(handles)
- for ev in r:
- assert ev.monitored in monitors
- assert ev.fp in handles
- assert r
assert not sel
def test_exception(self, sel, handles):
with raises(NameError):
with sel.scoped(handles) as _:
raise NameError
assert not sel
| Make Selector.scope test more rigorous | ## Code Before:
from contextlib import contextmanager
from scell import Selector
from pytest import raises, fixture
def test_select(selector):
res = list(selector.select())
assert res
for event in res:
assert event.ready
def test_select_empty():
sel = Selector()
assert list(sel.select()) == []
def test_unregister(selector):
for fp in list(selector):
selector.unregister(fp)
assert not selector
def test_info(selector):
for fp in selector:
assert selector.info(fp).wants_read
assert selector.info(0) is None
def test_callbacks(selector):
res = selector.select()
exp = len(selector)
assert sum(m.callback() for m in res) == exp
def test_ready(selector):
ready = list(selector.ready())
assert ready
for event in ready:
assert event.ready
class TestScoped(object):
@fixture
def sel(self):
return Selector()
def test_peaceful(self, sel, handles):
with sel.scoped(handles) as monitors:
r = list(sel.ready())
for ev in r:
assert ev.monitored in monitors
assert ev.fp in handles
assert r
assert not sel
def test_exception(self, sel, handles):
with raises(NameError):
with sel.scoped(handles) as _:
raise NameError
assert not sel
## Instruction:
Make Selector.scope test more rigorous
## Code After:
from contextlib import contextmanager
from scell import Selector
from pytest import raises, fixture
def test_select(selector):
res = list(selector.select())
assert res
for event in res:
assert event.ready
def test_select_empty():
sel = Selector()
assert list(sel.select()) == []
def test_unregister(selector):
for fp in list(selector):
selector.unregister(fp)
assert not selector
def test_info(selector):
for fp in selector:
assert selector.info(fp).wants_read
assert selector.info(0) is None
def test_callbacks(selector):
res = selector.select()
exp = len(selector)
assert sum(m.callback() for m in res) == exp
def test_ready(selector):
ready = list(selector.ready())
assert ready
for event in ready:
assert event.ready
class TestScoped(object):
@fixture
def sel(self):
return Selector()
def test_peaceful(self, sel, handles):
with sel.scoped(handles) as monitors:
r = set(k.fp for k in sel.ready())
assert r == set(handles)
assert not sel
def test_exception(self, sel, handles):
with raises(NameError):
with sel.scoped(handles) as _:
raise NameError
assert not sel
|
7520e1285af36292def45f892808841e78cc4a2b | bloop/index.py | bloop/index.py | missing = object()
class GlobalSecondaryIndex(object):
def __init__(self, hash_key=None, range_key=None,
write_units=1, read_units=1, name=missing):
self._model_name = None
self._backing_name = name
self.write_units = write_units
self.read_units = read_units
self.hash_key = hash_key
self.range_key = range_key
@property
def model_name(self):
''' Name of the model's attr that references self '''
return self._model_name
@property
def dynamo_name(self):
if self._backing_name is missing:
return self.model_name
return self._backing_name
| class Index(object):
def __init__(self, write_units=1, read_units=1, name=None, range_key=None):
self._model_name = None
self._dynamo_name = name
self.write_units = write_units
self.read_units = read_units
self.range_key = range_key
@property
def model_name(self):
''' Name of the model's attr that references self '''
return self._model_name
@model_name.setter
def model_name(self, value):
if self._model_name is not None:
raise AttributeError("{} model_name already set to '{}'".format(
self.__class__.__name__, self._model_name))
self._model_name = value
@property
def dynamo_name(self):
if self._dynamo_name is None:
return self.model_name
return self._dynamo_name
class GlobalSecondaryIndex(Index):
def __init__(self, hash_key=None, **kwargs):
super().__init__(**kwargs)
self.hash_key = hash_key
class LocalSecondaryIndex(Index):
''' when constructing a model, you MUST set this index's model attr. '''
@property
def hash_key(self):
hash_column = self.model.__meta__['dynamo.table.hash_key']
return hash_column.dynamo_name
| Refactor GSI, LSI to use base Index class | Refactor GSI, LSI to use base Index class
| Python | mit | numberoverzero/bloop,numberoverzero/bloop | + class Index(object):
+ def __init__(self, write_units=1, read_units=1, name=None, range_key=None):
- missing = object()
-
-
- class GlobalSecondaryIndex(object):
- def __init__(self, hash_key=None, range_key=None,
- write_units=1, read_units=1, name=missing):
self._model_name = None
- self._backing_name = name
+ self._dynamo_name = name
self.write_units = write_units
self.read_units = read_units
- self.hash_key = hash_key
self.range_key = range_key
@property
def model_name(self):
''' Name of the model's attr that references self '''
return self._model_name
+ @model_name.setter
+ def model_name(self, value):
+ if self._model_name is not None:
+ raise AttributeError("{} model_name already set to '{}'".format(
+ self.__class__.__name__, self._model_name))
+ self._model_name = value
+
@property
def dynamo_name(self):
- if self._backing_name is missing:
+ if self._dynamo_name is None:
return self.model_name
- return self._backing_name
+ return self._dynamo_name
+
+ class GlobalSecondaryIndex(Index):
+ def __init__(self, hash_key=None, **kwargs):
+ super().__init__(**kwargs)
+ self.hash_key = hash_key
+
+
+ class LocalSecondaryIndex(Index):
+ ''' when constructing a model, you MUST set this index's model attr. '''
+ @property
+ def hash_key(self):
+ hash_column = self.model.__meta__['dynamo.table.hash_key']
+ return hash_column.dynamo_name
+ | Refactor GSI, LSI to use base Index class | ## Code Before:
missing = object()
class GlobalSecondaryIndex(object):
def __init__(self, hash_key=None, range_key=None,
write_units=1, read_units=1, name=missing):
self._model_name = None
self._backing_name = name
self.write_units = write_units
self.read_units = read_units
self.hash_key = hash_key
self.range_key = range_key
@property
def model_name(self):
''' Name of the model's attr that references self '''
return self._model_name
@property
def dynamo_name(self):
if self._backing_name is missing:
return self.model_name
return self._backing_name
## Instruction:
Refactor GSI, LSI to use base Index class
## Code After:
class Index(object):
def __init__(self, write_units=1, read_units=1, name=None, range_key=None):
self._model_name = None
self._dynamo_name = name
self.write_units = write_units
self.read_units = read_units
self.range_key = range_key
@property
def model_name(self):
''' Name of the model's attr that references self '''
return self._model_name
@model_name.setter
def model_name(self, value):
if self._model_name is not None:
raise AttributeError("{} model_name already set to '{}'".format(
self.__class__.__name__, self._model_name))
self._model_name = value
@property
def dynamo_name(self):
if self._dynamo_name is None:
return self.model_name
return self._dynamo_name
class GlobalSecondaryIndex(Index):
def __init__(self, hash_key=None, **kwargs):
super().__init__(**kwargs)
self.hash_key = hash_key
class LocalSecondaryIndex(Index):
''' when constructing a model, you MUST set this index's model attr. '''
@property
def hash_key(self):
hash_column = self.model.__meta__['dynamo.table.hash_key']
return hash_column.dynamo_name
|
db4ccce9e418a1227532bde8834ca682bc873609 | system/t04_mirror/show.py | system/t04_mirror/show.py | from lib import BaseTest
class ShowMirror1Test(BaseTest):
"""
show mirror: regular mirror
"""
fixtureCmds = ["aptly mirror create mirror1 http://mirror.yandex.ru/debian/ wheezy"]
runCmd = "aptly mirror show mirror1"
class ShowMirror2Test(BaseTest):
"""
show mirror: missing mirror
"""
runCmd = "aptly mirror show mirror-xx"
expectedCode = 1
class ShowMirror3Test(BaseTest):
"""
show mirror: regular mirror with packages
"""
fixtureDB = True
runCmd = "aptly mirror show --with-packages wheezy-contrib"
| from lib import BaseTest
import re
class ShowMirror1Test(BaseTest):
"""
show mirror: regular mirror
"""
fixtureCmds = ["aptly mirror create mirror1 http://mirror.yandex.ru/debian/ wheezy"]
runCmd = "aptly mirror show mirror1"
class ShowMirror2Test(BaseTest):
"""
show mirror: missing mirror
"""
runCmd = "aptly mirror show mirror-xx"
expectedCode = 1
class ShowMirror3Test(BaseTest):
"""
show mirror: regular mirror with packages
"""
fixtureDB = True
runCmd = "aptly mirror show --with-packages wheezy-contrib"
outputMatchPrepare = lambda _, s: re.sub(r"Last update: [0-9:A-Za-z -]+\n", "", s)
| Remove updated at while comparing. | Remove updated at while comparing.
| Python | mit | gearmover/aptly,bsundsrud/aptly,adfinis-forks/aptly,vincentbernat/aptly,gdbdzgd/aptly,ceocoder/aptly,adfinis-forks/aptly,seaninspace/aptly,neolynx/aptly,scalp42/aptly,gdbdzgd/aptly,sobczyk/aptly,neolynx/aptly,scalp42/aptly,aptly-dev/aptly,seaninspace/aptly,aptly-dev/aptly,bsundsrud/aptly,gdbdzgd/aptly,bankonme/aptly,adfinis-forks/aptly,sobczyk/aptly,seaninspace/aptly,vincentbernat/aptly,smira/aptly,jola5/aptly,scalp42/aptly,smira/aptly,ceocoder/aptly,gearmover/aptly,bankonme/aptly,bsundsrud/aptly,vincentbernat/aptly,ceocoder/aptly,jola5/aptly,jola5/aptly,aptly-dev/aptly,gearmover/aptly,sobczyk/aptly,neolynx/aptly,smira/aptly,bankonme/aptly | from lib import BaseTest
+ import re
class ShowMirror1Test(BaseTest):
"""
show mirror: regular mirror
"""
fixtureCmds = ["aptly mirror create mirror1 http://mirror.yandex.ru/debian/ wheezy"]
runCmd = "aptly mirror show mirror1"
class ShowMirror2Test(BaseTest):
"""
show mirror: missing mirror
"""
runCmd = "aptly mirror show mirror-xx"
expectedCode = 1
class ShowMirror3Test(BaseTest):
"""
show mirror: regular mirror with packages
"""
fixtureDB = True
runCmd = "aptly mirror show --with-packages wheezy-contrib"
+ outputMatchPrepare = lambda _, s: re.sub(r"Last update: [0-9:A-Za-z -]+\n", "", s)
| Remove updated at while comparing. | ## Code Before:
from lib import BaseTest
class ShowMirror1Test(BaseTest):
"""
show mirror: regular mirror
"""
fixtureCmds = ["aptly mirror create mirror1 http://mirror.yandex.ru/debian/ wheezy"]
runCmd = "aptly mirror show mirror1"
class ShowMirror2Test(BaseTest):
"""
show mirror: missing mirror
"""
runCmd = "aptly mirror show mirror-xx"
expectedCode = 1
class ShowMirror3Test(BaseTest):
"""
show mirror: regular mirror with packages
"""
fixtureDB = True
runCmd = "aptly mirror show --with-packages wheezy-contrib"
## Instruction:
Remove updated at while comparing.
## Code After:
from lib import BaseTest
import re
class ShowMirror1Test(BaseTest):
"""
show mirror: regular mirror
"""
fixtureCmds = ["aptly mirror create mirror1 http://mirror.yandex.ru/debian/ wheezy"]
runCmd = "aptly mirror show mirror1"
class ShowMirror2Test(BaseTest):
"""
show mirror: missing mirror
"""
runCmd = "aptly mirror show mirror-xx"
expectedCode = 1
class ShowMirror3Test(BaseTest):
"""
show mirror: regular mirror with packages
"""
fixtureDB = True
runCmd = "aptly mirror show --with-packages wheezy-contrib"
outputMatchPrepare = lambda _, s: re.sub(r"Last update: [0-9:A-Za-z -]+\n", "", s)
|
1e8c094c0f806b624a41447446676c1f2ac3590d | tools/debug_adapter.py | tools/debug_adapter.py | import sys
if 'darwin' in sys.platform:
sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python')
sys.path.append('.')
import adapter
adapter.main.run_tcp_server()
| import sys
import subprocess
import string
out = subprocess.check_output(['lldb', '-P'])
sys.path.append(string.strip(out))
sys.path.append('.')
import adapter
adapter.main.run_tcp_server()
| Fix adapter debugging on Linux. | Fix adapter debugging on Linux.
| Python | mit | vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb | import sys
- if 'darwin' in sys.platform:
- sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python')
+ import subprocess
+ import string
+
+ out = subprocess.check_output(['lldb', '-P'])
+ sys.path.append(string.strip(out))
sys.path.append('.')
import adapter
adapter.main.run_tcp_server()
| Fix adapter debugging on Linux. | ## Code Before:
import sys
if 'darwin' in sys.platform:
sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python')
sys.path.append('.')
import adapter
adapter.main.run_tcp_server()
## Instruction:
Fix adapter debugging on Linux.
## Code After:
import sys
import subprocess
import string
out = subprocess.check_output(['lldb', '-P'])
sys.path.append(string.strip(out))
sys.path.append('.')
import adapter
adapter.main.run_tcp_server()
|
73e8864e745ca75c2ea327b53244c9f2f4183e1a | lambda_function.py | lambda_function.py | from StringIO import StringIO
import boto3
from dmr_marc_users_cs750 import (
get_users, get_groups,
write_contacts_csv,
write_contacts_xlsx
)
def s3_contacts(contacts, bucket, key):
s3 = boto3.client('s3')
o = StringIO()
if key.endswith('.csv'):
t = 'text/csv'
write_contacts_csv(contacts, o)
elif key.endswith('.xlsx'):
t = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
write_contacts_xlsx(contacts, o)
s3.put_object(
Bucket=bucket, Key=key,
Body=o.getvalue(), ContentType=t, ACL='public-read')
o.close()
def lambda_handler(event=None, context=None):
users = get_users()
groups = get_groups()
s3_contacts(contacts=users, bucket='dmr-contacts', key='DMR_contacts.csv')
s3_contacts(contacts=groups+users,
bucket='dmr-contacts', key='contacts-dci.xlsx')
if __name__ == '__main__':
lambda_handler()
| from StringIO import StringIO
import boto3
from dmr_marc_users_cs750 import (
get_users, get_groups,
write_contacts_csv,
write_contacts_xlsx,
)
from dmrx_most_heard_n0gsg import (
get_users as get_most_heard,
write_n0gsg_csv,
)
def s3_contacts(contacts, bucket, key):
s3 = boto3.client('s3')
o = StringIO()
if key.endswith('.csv'):
t = 'text/csv'
if key.startswith('N0GSG/'):
write_n0gsg_csv(contacts, o)
else:
write_contacts_csv(contacts, o)
elif key.endswith('.xlsx'):
t = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
write_contacts_xlsx(contacts, o)
s3.put_object(
Bucket=bucket, Key=key,
Body=o.getvalue(), ContentType=t, ACL='public-read')
o.close()
def lambda_handler(event=None, context=None):
marc = get_users()
dmrx = get_most_heard()
groups = get_groups()
s3_contacts(contacts=marc, bucket='dmr-contacts',
key='CS750/DMR_contacts.csv')
s3_contacts(contacts=groups+marc, bucket='dmr-contacts',
key='CS750/dci-bm-marc.xlsx')
s3_contacts(contacts=dmrx, bucket='dmr-contacts',
key='N0GSG/dmrx-most-heard.csv')
if __name__ == '__main__':
lambda_handler()
| Add N0GSG DMRX MostHeard to AWS Lambda function | Add N0GSG DMRX MostHeard to AWS Lambda function
| Python | apache-2.0 | ajorg/DMR_contacts | from StringIO import StringIO
import boto3
from dmr_marc_users_cs750 import (
get_users, get_groups,
write_contacts_csv,
- write_contacts_xlsx
+ write_contacts_xlsx,
+ )
+ from dmrx_most_heard_n0gsg import (
+ get_users as get_most_heard,
+ write_n0gsg_csv,
)
def s3_contacts(contacts, bucket, key):
s3 = boto3.client('s3')
o = StringIO()
if key.endswith('.csv'):
t = 'text/csv'
+ if key.startswith('N0GSG/'):
+ write_n0gsg_csv(contacts, o)
+ else:
- write_contacts_csv(contacts, o)
+ write_contacts_csv(contacts, o)
elif key.endswith('.xlsx'):
t = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
write_contacts_xlsx(contacts, o)
s3.put_object(
Bucket=bucket, Key=key,
Body=o.getvalue(), ContentType=t, ACL='public-read')
o.close()
def lambda_handler(event=None, context=None):
- users = get_users()
+ marc = get_users()
+ dmrx = get_most_heard()
groups = get_groups()
- s3_contacts(contacts=users, bucket='dmr-contacts', key='DMR_contacts.csv')
+ s3_contacts(contacts=marc, bucket='dmr-contacts',
-
- s3_contacts(contacts=groups+users,
- bucket='dmr-contacts', key='contacts-dci.xlsx')
+ key='CS750/DMR_contacts.csv')
+ s3_contacts(contacts=groups+marc, bucket='dmr-contacts',
+ key='CS750/dci-bm-marc.xlsx')
+ s3_contacts(contacts=dmrx, bucket='dmr-contacts',
+ key='N0GSG/dmrx-most-heard.csv')
if __name__ == '__main__':
lambda_handler()
| Add N0GSG DMRX MostHeard to AWS Lambda function | ## Code Before:
from StringIO import StringIO
import boto3
from dmr_marc_users_cs750 import (
get_users, get_groups,
write_contacts_csv,
write_contacts_xlsx
)
def s3_contacts(contacts, bucket, key):
s3 = boto3.client('s3')
o = StringIO()
if key.endswith('.csv'):
t = 'text/csv'
write_contacts_csv(contacts, o)
elif key.endswith('.xlsx'):
t = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
write_contacts_xlsx(contacts, o)
s3.put_object(
Bucket=bucket, Key=key,
Body=o.getvalue(), ContentType=t, ACL='public-read')
o.close()
def lambda_handler(event=None, context=None):
users = get_users()
groups = get_groups()
s3_contacts(contacts=users, bucket='dmr-contacts', key='DMR_contacts.csv')
s3_contacts(contacts=groups+users,
bucket='dmr-contacts', key='contacts-dci.xlsx')
if __name__ == '__main__':
lambda_handler()
## Instruction:
Add N0GSG DMRX MostHeard to AWS Lambda function
## Code After:
from StringIO import StringIO
import boto3
from dmr_marc_users_cs750 import (
get_users, get_groups,
write_contacts_csv,
write_contacts_xlsx,
)
from dmrx_most_heard_n0gsg import (
get_users as get_most_heard,
write_n0gsg_csv,
)
def s3_contacts(contacts, bucket, key):
s3 = boto3.client('s3')
o = StringIO()
if key.endswith('.csv'):
t = 'text/csv'
if key.startswith('N0GSG/'):
write_n0gsg_csv(contacts, o)
else:
write_contacts_csv(contacts, o)
elif key.endswith('.xlsx'):
t = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
write_contacts_xlsx(contacts, o)
s3.put_object(
Bucket=bucket, Key=key,
Body=o.getvalue(), ContentType=t, ACL='public-read')
o.close()
def lambda_handler(event=None, context=None):
marc = get_users()
dmrx = get_most_heard()
groups = get_groups()
s3_contacts(contacts=marc, bucket='dmr-contacts',
key='CS750/DMR_contacts.csv')
s3_contacts(contacts=groups+marc, bucket='dmr-contacts',
key='CS750/dci-bm-marc.xlsx')
s3_contacts(contacts=dmrx, bucket='dmr-contacts',
key='N0GSG/dmrx-most-heard.csv')
if __name__ == '__main__':
lambda_handler()
|
6dfb0c1ea4fb3d12d14a07d0e831eb32f3b2f340 | yaml_argparse.py | yaml_argparse.py | import argparse
import yaml
def parse_arguments_based_on_yaml(yaml_file):
with open(yaml_file) as f:
yaml_data = yaml.load(f)
# to start with, support only a single parameter
key = list(yaml_data.keys())[0]
value = yaml_data[key]
parser = argparse.ArgumentParser()
parser.add_argument("-{}".format(key), default=value)
args = parser.parse_args()
return args
| import argparse
import yaml
def parse_arguments_based_on_yaml(yaml_file):
with open(yaml_file) as f:
yaml_data = yaml.load(f)
parser = argparse.ArgumentParser()
for key, value in yaml_data.items():
parser.add_argument("-{}".format(key), default=value)
args = parser.parse_args()
return args
| Implement creating arguments for multiple strings | Implement creating arguments for multiple strings
| Python | mit | krasch/yaml_argparse,krasch/quickargs | import argparse
import yaml
def parse_arguments_based_on_yaml(yaml_file):
with open(yaml_file) as f:
yaml_data = yaml.load(f)
- # to start with, support only a single parameter
- key = list(yaml_data.keys())[0]
- value = yaml_data[key]
parser = argparse.ArgumentParser()
+ for key, value in yaml_data.items():
- parser.add_argument("-{}".format(key), default=value)
+ parser.add_argument("-{}".format(key), default=value)
args = parser.parse_args()
return args
| Implement creating arguments for multiple strings | ## Code Before:
import argparse
import yaml
def parse_arguments_based_on_yaml(yaml_file):
with open(yaml_file) as f:
yaml_data = yaml.load(f)
# to start with, support only a single parameter
key = list(yaml_data.keys())[0]
value = yaml_data[key]
parser = argparse.ArgumentParser()
parser.add_argument("-{}".format(key), default=value)
args = parser.parse_args()
return args
## Instruction:
Implement creating arguments for multiple strings
## Code After:
import argparse
import yaml
def parse_arguments_based_on_yaml(yaml_file):
with open(yaml_file) as f:
yaml_data = yaml.load(f)
parser = argparse.ArgumentParser()
for key, value in yaml_data.items():
parser.add_argument("-{}".format(key), default=value)
args = parser.parse_args()
return args
|
eae4b06bd798eab3a46bdd5b7452411bb7fb02e1 | dashcam.py | dashcam.py |
import pygame
import picamera
import os
os.putenv('SDL_VIDEODRIVER', 'fbcon')
os.putenv('SDL_FBDEV' , '/dev/fb1')
os.putenv('SDL_MOUSEDRV' , 'TSLIB')
os.putenv('SDL_MOUSEDEV' , '/dev/input/touchscreen')
pygame.init()
pygame.mouse.set_visible(False)
screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
|
import pygame
import picamera
import os
import sys
import io
os.putenv('SDL_VIDEODRIVER', 'fbcon')
os.putenv('SDL_FBDEV' , '/dev/fb1')
os.putenv('SDL_MOUSEDRV' , 'TSLIB')
os.putenv('SDL_MOUSEDEV' , '/dev/input/touchscreen')
size = width, height = 320, 240
pygame.init()
pygame.mouse.set_visible(False)
screen = pygame.display.set_mode(size)
go_button = pygame.image.load("/home/pi/bike_dashcam/media/go.bmp")
| Update dascham with pygame GO button load | Update dascham with pygame GO button load
| Python | mit | the-raspberry-pi-guy/bike_dashcam,the-raspberry-pi-guy/bike_dashcam |
import pygame
import picamera
import os
+ import sys
+ import io
os.putenv('SDL_VIDEODRIVER', 'fbcon')
os.putenv('SDL_FBDEV' , '/dev/fb1')
os.putenv('SDL_MOUSEDRV' , 'TSLIB')
os.putenv('SDL_MOUSEDEV' , '/dev/input/touchscreen')
+ size = width, height = 320, 240
+
pygame.init()
pygame.mouse.set_visible(False)
- screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
+ screen = pygame.display.set_mode(size)
+ go_button = pygame.image.load("/home/pi/bike_dashcam/media/go.bmp")
+
+
+ | Update dascham with pygame GO button load | ## Code Before:
import pygame
import picamera
import os
os.putenv('SDL_VIDEODRIVER', 'fbcon')
os.putenv('SDL_FBDEV' , '/dev/fb1')
os.putenv('SDL_MOUSEDRV' , 'TSLIB')
os.putenv('SDL_MOUSEDEV' , '/dev/input/touchscreen')
pygame.init()
pygame.mouse.set_visible(False)
screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
## Instruction:
Update dascham with pygame GO button load
## Code After:
import pygame
import picamera
import os
import sys
import io
os.putenv('SDL_VIDEODRIVER', 'fbcon')
os.putenv('SDL_FBDEV' , '/dev/fb1')
os.putenv('SDL_MOUSEDRV' , 'TSLIB')
os.putenv('SDL_MOUSEDEV' , '/dev/input/touchscreen')
size = width, height = 320, 240
pygame.init()
pygame.mouse.set_visible(False)
screen = pygame.display.set_mode(size)
go_button = pygame.image.load("/home/pi/bike_dashcam/media/go.bmp")
|
b35d4292e50e8a8dc56635bddeac5a1fc42a5d19 | tveebot_tracker/source.py | tveebot_tracker/source.py | from abc import ABC, abstractmethod
class TVShowNotFound(Exception):
""" Raised when a reference does not match any TV Show available """
class EpisodeSource(ABC):
"""
Abstract base class to define the interface for and episode source.
An episode source is used by the tracker to obtain episode files. A
source is usually based on a feed that provides links to TV Show's
episodes.
Every source has its own protocol to obtain the information and it uses
its own format to present that information. Implementations of this
interface are responsible for implementing the details of how to obtain
the episode files' information and present them to the tracker.
"""
# Called by the tracker when it wants to get the episodes available for
# a specific TVShow
@abstractmethod
def get_episodes_for(self, tvshow_reference: str) -> list:
"""
Retrieve all available episode files corresponding to the specified
TV show. Multiple files for the same episode may be retrieved.
The TV show to obtain the episodes from is identified by some reference
that uniquely identifies it within the episode source in question.
:param tvshow_reference: reference that uniquely identifies the TV show
to get the episodes for
:return: a list containing all episode files available for the specified
TV Show. An empty list if none is found.
:raise TVShowNotFound: if the specified reference does not match to any
TV show available
"""
| from abc import ABC, abstractmethod
class TVShowNotFound(Exception):
""" Raised when a reference does not match any TV Show available """
class EpisodeSource(ABC):
"""
Abstract base class to define the interface for and episode source.
An episode source is used by the tracker to obtain episode files. A
source is usually based on a feed that provides links to TV Show's
episodes.
Every source has its own protocol to obtain the information and it uses
its own format to present that information. Implementations of this
interface are responsible for implementing the details of how to obtain
the episode files' information and present them to the tracker.
"""
# Called by the tracker when it wants to get the episodes available for
# a specific TVShow
@abstractmethod
def fetch(self, tvshow_reference: str) -> list:
"""
Fetches all available episode files, corresponding to the specified
TV show. Multiple files for the same episode may be retrieved.
The TV show to obtain the episodes from is identified by some reference
that uniquely identifies it within the episode source in question.
:param tvshow_reference: reference that uniquely identifies the TV show
to get the episodes for
:return: a list containing all episode files available for the specified
TV Show. An empty list if none is found.
:raise TVShowNotFound: if the specified reference does not match to any
TV show available
"""
| Rename Source's get_episodes_for() method to fetch() | Rename Source's get_episodes_for() method to fetch()
| Python | mit | tveebot/tracker | from abc import ABC, abstractmethod
class TVShowNotFound(Exception):
""" Raised when a reference does not match any TV Show available """
class EpisodeSource(ABC):
"""
Abstract base class to define the interface for and episode source.
An episode source is used by the tracker to obtain episode files. A
source is usually based on a feed that provides links to TV Show's
episodes.
Every source has its own protocol to obtain the information and it uses
its own format to present that information. Implementations of this
interface are responsible for implementing the details of how to obtain
the episode files' information and present them to the tracker.
"""
# Called by the tracker when it wants to get the episodes available for
# a specific TVShow
@abstractmethod
- def get_episodes_for(self, tvshow_reference: str) -> list:
+ def fetch(self, tvshow_reference: str) -> list:
"""
- Retrieve all available episode files corresponding to the specified
+ Fetches all available episode files, corresponding to the specified
TV show. Multiple files for the same episode may be retrieved.
The TV show to obtain the episodes from is identified by some reference
that uniquely identifies it within the episode source in question.
:param tvshow_reference: reference that uniquely identifies the TV show
to get the episodes for
:return: a list containing all episode files available for the specified
TV Show. An empty list if none is found.
:raise TVShowNotFound: if the specified reference does not match to any
TV show available
"""
| Rename Source's get_episodes_for() method to fetch() | ## Code Before:
from abc import ABC, abstractmethod
class TVShowNotFound(Exception):
""" Raised when a reference does not match any TV Show available """
class EpisodeSource(ABC):
"""
Abstract base class to define the interface for and episode source.
An episode source is used by the tracker to obtain episode files. A
source is usually based on a feed that provides links to TV Show's
episodes.
Every source has its own protocol to obtain the information and it uses
its own format to present that information. Implementations of this
interface are responsible for implementing the details of how to obtain
the episode files' information and present them to the tracker.
"""
# Called by the tracker when it wants to get the episodes available for
# a specific TVShow
@abstractmethod
def get_episodes_for(self, tvshow_reference: str) -> list:
"""
Retrieve all available episode files corresponding to the specified
TV show. Multiple files for the same episode may be retrieved.
The TV show to obtain the episodes from is identified by some reference
that uniquely identifies it within the episode source in question.
:param tvshow_reference: reference that uniquely identifies the TV show
to get the episodes for
:return: a list containing all episode files available for the specified
TV Show. An empty list if none is found.
:raise TVShowNotFound: if the specified reference does not match to any
TV show available
"""
## Instruction:
Rename Source's get_episodes_for() method to fetch()
## Code After:
from abc import ABC, abstractmethod
class TVShowNotFound(Exception):
""" Raised when a reference does not match any TV Show available """
class EpisodeSource(ABC):
"""
Abstract base class to define the interface for and episode source.
An episode source is used by the tracker to obtain episode files. A
source is usually based on a feed that provides links to TV Show's
episodes.
Every source has its own protocol to obtain the information and it uses
its own format to present that information. Implementations of this
interface are responsible for implementing the details of how to obtain
the episode files' information and present them to the tracker.
"""
# Called by the tracker when it wants to get the episodes available for
# a specific TVShow
@abstractmethod
def fetch(self, tvshow_reference: str) -> list:
"""
Fetches all available episode files, corresponding to the specified
TV show. Multiple files for the same episode may be retrieved.
The TV show to obtain the episodes from is identified by some reference
that uniquely identifies it within the episode source in question.
:param tvshow_reference: reference that uniquely identifies the TV show
to get the episodes for
:return: a list containing all episode files available for the specified
TV Show. An empty list if none is found.
:raise TVShowNotFound: if the specified reference does not match to any
TV show available
"""
|
30c21806dcc347326d6ac51be2adac9ff637f241 | day20/part1.py | day20/part1.py | ranges = []
for line in open('input.txt', 'r'):
ranges.append(tuple(map(int, line.split('-'))))
ranges.sort()
lowest = 0
for l, r in ranges:
if l <= lowest <= r:
lowest = r + 1
print(lowest)
input()
| ranges = []
for line in open('input.txt', 'r'):
ranges.append(tuple(map(int, line.split('-'))))
ranges.sort()
lowest = 0
for l, r in ranges:
if l > lowest:
break
if lowest <= r:
lowest = r + 1
print(lowest)
input()
| Break the loop at the first gap | Break the loop at the first gap
| Python | unlicense | ultramega/adventofcode2016 | ranges = []
for line in open('input.txt', 'r'):
ranges.append(tuple(map(int, line.split('-'))))
ranges.sort()
lowest = 0
for l, r in ranges:
+ if l > lowest:
+ break
- if l <= lowest <= r:
+ if lowest <= r:
lowest = r + 1
print(lowest)
input()
| Break the loop at the first gap | ## Code Before:
ranges = []
for line in open('input.txt', 'r'):
ranges.append(tuple(map(int, line.split('-'))))
ranges.sort()
lowest = 0
for l, r in ranges:
if l <= lowest <= r:
lowest = r + 1
print(lowest)
input()
## Instruction:
Break the loop at the first gap
## Code After:
ranges = []
for line in open('input.txt', 'r'):
ranges.append(tuple(map(int, line.split('-'))))
ranges.sort()
lowest = 0
for l, r in ranges:
if l > lowest:
break
if lowest <= r:
lowest = r + 1
print(lowest)
input()
|
4a75df6e253401cbed7b31e1882211946f02093a | src/ggrc/__init__.py | src/ggrc/__init__.py |
from .bootstrap import db, logger
|
from ggrc.bootstrap import db
__all__ = [
db
]
| Remove logger from ggrc init | Remove logger from ggrc init
The logger from ggrc init is never used and should be removed.
| Python | apache-2.0 | selahssea/ggrc-core,NejcZupec/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,j0gurt/ggrc-core,NejcZupec/ggrc-core,j0gurt/ggrc-core,NejcZupec/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,josthkko/ggrc-core,josthkko/ggrc-core,selahssea/ggrc-core,NejcZupec/ggrc-core,kr41/ggrc-core,j0gurt/ggrc-core,kr41/ggrc-core,kr41/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,andrei-karalionak/ggrc-core,edofic/ggrc-core,VinnieJohns/ggrc-core,edofic/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,edofic/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,andrei-karalionak/ggrc-core,kr41/ggrc-core,edofic/ggrc-core,andrei-karalionak/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core |
- from .bootstrap import db, logger
+ from ggrc.bootstrap import db
+ __all__ = [
+ db
+ ]
+ | Remove logger from ggrc init | ## Code Before:
from .bootstrap import db, logger
## Instruction:
Remove logger from ggrc init
## Code After:
from ggrc.bootstrap import db
__all__ = [
db
]
|
3885fcbb31393f936bc58842dc06bdc9ffe55151 | fabfile.py | fabfile.py |
from fabric.api import env, run, sudo, task
from fabric.context_managers import cd, prefix
env.use_ssh_config = True
home = '~/jarvis2'
@task
def pull_code():
with cd(home):
run('git pull --rebase')
@task
def update_dependencies():
with prefix('workon jarvis2'):
run('pip install --use-mirrors -r %s/requirements.txt' % (home,))
@task
def restart_server():
sudo('/etc/init.d/uwsgi restart', pty=False)
@task
def restart_client():
run('pkill -x midori')
@task(default=True)
def deploy(update_deps=False):
pull_code()
if update_deps:
update_dependencies()
restart_server()
restart_client()
@task
def full_deploy():
deploy(True)
|
from fabric.api import env, run, sudo, task
from fabric.context_managers import cd, prefix
from fabric.contrib.project import rsync_project
env.use_ssh_config = True
home = '~/jarvis2'
@task
def pull_code():
with cd(home):
run('git pull --rebase')
@task
def push_code():
rsync_project(local_dir='.', remote_dir=home, exclude=('.git', '.vagrant'),
extra_opts='--filter=":- .gitignore"')
@task
def update_dependencies():
with prefix('workon jarvis2'):
run(('pip install --quiet --use-mirrors --upgrade'
' -r {home}/requirements.txt').format(home=home))
@task
def restart_server():
sudo('/etc/init.d/uwsgi restart', pty=False)
@task
def restart_client():
run('pkill -x midori')
@task(default=True)
def deploy(update_deps=False):
push_code()
if update_deps:
update_dependencies()
restart_server()
restart_client()
@task
def full_deploy():
deploy(True)
| Add task for pushing code with rsync | Add task for pushing code with rsync
| Python | mit | Foxboron/Frank,mpolden/jarvis2,martinp/jarvis2,Foxboron/Frank,mpolden/jarvis2,mpolden/jarvis2,martinp/jarvis2,Foxboron/Frank,martinp/jarvis2 |
from fabric.api import env, run, sudo, task
from fabric.context_managers import cd, prefix
+ from fabric.contrib.project import rsync_project
env.use_ssh_config = True
home = '~/jarvis2'
@task
def pull_code():
with cd(home):
run('git pull --rebase')
@task
+ def push_code():
+ rsync_project(local_dir='.', remote_dir=home, exclude=('.git', '.vagrant'),
+ extra_opts='--filter=":- .gitignore"')
+
+
+ @task
def update_dependencies():
with prefix('workon jarvis2'):
- run('pip install --use-mirrors -r %s/requirements.txt' % (home,))
+ run(('pip install --quiet --use-mirrors --upgrade'
+ ' -r {home}/requirements.txt').format(home=home))
@task
def restart_server():
sudo('/etc/init.d/uwsgi restart', pty=False)
@task
def restart_client():
run('pkill -x midori')
@task(default=True)
def deploy(update_deps=False):
- pull_code()
+ push_code()
if update_deps:
update_dependencies()
restart_server()
restart_client()
@task
def full_deploy():
deploy(True)
| Add task for pushing code with rsync | ## Code Before:
from fabric.api import env, run, sudo, task
from fabric.context_managers import cd, prefix
env.use_ssh_config = True
home = '~/jarvis2'
@task
def pull_code():
with cd(home):
run('git pull --rebase')
@task
def update_dependencies():
with prefix('workon jarvis2'):
run('pip install --use-mirrors -r %s/requirements.txt' % (home,))
@task
def restart_server():
sudo('/etc/init.d/uwsgi restart', pty=False)
@task
def restart_client():
run('pkill -x midori')
@task(default=True)
def deploy(update_deps=False):
pull_code()
if update_deps:
update_dependencies()
restart_server()
restart_client()
@task
def full_deploy():
deploy(True)
## Instruction:
Add task for pushing code with rsync
## Code After:
from fabric.api import env, run, sudo, task
from fabric.context_managers import cd, prefix
from fabric.contrib.project import rsync_project
env.use_ssh_config = True
home = '~/jarvis2'
@task
def pull_code():
with cd(home):
run('git pull --rebase')
@task
def push_code():
rsync_project(local_dir='.', remote_dir=home, exclude=('.git', '.vagrant'),
extra_opts='--filter=":- .gitignore"')
@task
def update_dependencies():
with prefix('workon jarvis2'):
run(('pip install --quiet --use-mirrors --upgrade'
' -r {home}/requirements.txt').format(home=home))
@task
def restart_server():
sudo('/etc/init.d/uwsgi restart', pty=False)
@task
def restart_client():
run('pkill -x midori')
@task(default=True)
def deploy(update_deps=False):
push_code()
if update_deps:
update_dependencies()
restart_server()
restart_client()
@task
def full_deploy():
deploy(True)
|
decb1699fe036c55d33c7d3b77a834cf8c3ee785 | RPLCD/__init__.py | RPLCD/__init__.py | from .common import Alignment, CursorMode, ShiftMode, BacklightMode
from .contextmanagers import cursor, cleared
| import warnings
from .common import Alignment, CursorMode, ShiftMode, BacklightMode
from .contextmanagers import cursor, cleared
from .gpio import CharLCD as GpioCharLCD
class CharLCD(GpioCharLCD):
def __init__(self, *args, **kwargs):
warnings.warn("Using RPLCD.CharLCD directly is deprecated. " +
"Use RPLCD.gpio.CharLCD instead!", DeprecationWarning)
super(CharLCD, self).__init__(*args, **kwargs)
| Add backwards compatible CharLCD wrapper | Add backwards compatible CharLCD wrapper
| Python | mit | GoranLundberg/RPLCD,thijstriemstra/RPLCD,dbrgn/RPLCD,paulenuta/RPLCD | + import warnings
+
from .common import Alignment, CursorMode, ShiftMode, BacklightMode
from .contextmanagers import cursor, cleared
+ from .gpio import CharLCD as GpioCharLCD
+ class CharLCD(GpioCharLCD):
+ def __init__(self, *args, **kwargs):
+ warnings.warn("Using RPLCD.CharLCD directly is deprecated. " +
+ "Use RPLCD.gpio.CharLCD instead!", DeprecationWarning)
+ super(CharLCD, self).__init__(*args, **kwargs)
+ | Add backwards compatible CharLCD wrapper | ## Code Before:
from .common import Alignment, CursorMode, ShiftMode, BacklightMode
from .contextmanagers import cursor, cleared
## Instruction:
Add backwards compatible CharLCD wrapper
## Code After:
import warnings
from .common import Alignment, CursorMode, ShiftMode, BacklightMode
from .contextmanagers import cursor, cleared
from .gpio import CharLCD as GpioCharLCD
class CharLCD(GpioCharLCD):
def __init__(self, *args, **kwargs):
warnings.warn("Using RPLCD.CharLCD directly is deprecated. " +
"Use RPLCD.gpio.CharLCD instead!", DeprecationWarning)
super(CharLCD, self).__init__(*args, **kwargs)
|
d3675b777dc95f296f26bdd9b8b05311ceac6ba5 | cyder/core/system/migrations/0006_rename_table_from_system_key_value_to_system_kv.py | cyder/core/system/migrations/0006_rename_table_from_system_key_value_to_system_kv.py | from south.db import db
from south.v2 import SchemaMigration
class Migration(SchemaMigration):
def forwards(self, orm):
db.rename_table('system_key_value', 'system_kv')
def backwards(self, orm):
db.rename_table('system_kv', 'system_key_value')
| import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
db.rename_table('system_key_value', 'system_kv')
def backwards(self, orm):
db.rename_table('system_kv', 'system_key_value')
models = {
'system.system': {
'Meta': {'object_name': 'System', 'db_table': "'system'"},
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'system.systemkeyvalue': {
'Meta': {'unique_together': "(('key', 'value', 'system'),)", 'object_name': 'SystemKeyValue', 'db_table': "'system_kv'"},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_quoted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'system': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['system.System']"}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '255'})
}
}
complete_apps = ['system']
| Add ORM freeze thing to SystemKeyValue migration | Add ORM freeze thing to SystemKeyValue migration
| Python | bsd-3-clause | akeym/cyder,murrown/cyder,zeeman/cyder,akeym/cyder,OSU-Net/cyder,murrown/cyder,OSU-Net/cyder,OSU-Net/cyder,zeeman/cyder,akeym/cyder,murrown/cyder,zeeman/cyder,drkitty/cyder,zeeman/cyder,drkitty/cyder,akeym/cyder,drkitty/cyder,murrown/cyder,drkitty/cyder,OSU-Net/cyder | + import datetime
from south.db import db
from south.v2 import SchemaMigration
+ from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
db.rename_table('system_key_value', 'system_kv')
def backwards(self, orm):
db.rename_table('system_kv', 'system_key_value')
+ models = {
+ 'system.system': {
+ 'Meta': {'object_name': 'System', 'db_table': "'system'"},
+ 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
+ },
+ 'system.systemkeyvalue': {
+ 'Meta': {'unique_together': "(('key', 'value', 'system'),)", 'object_name': 'SystemKeyValue', 'db_table': "'system_kv'"},
+ 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'is_quoted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+ 'key': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
+ 'system': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['system.System']"}),
+ 'value': ('django.db.models.fields.CharField', [], {'max_length': '255'})
+ }
+ }
+
+ complete_apps = ['system']
+ | Add ORM freeze thing to SystemKeyValue migration | ## Code Before:
from south.db import db
from south.v2 import SchemaMigration
class Migration(SchemaMigration):
def forwards(self, orm):
db.rename_table('system_key_value', 'system_kv')
def backwards(self, orm):
db.rename_table('system_kv', 'system_key_value')
## Instruction:
Add ORM freeze thing to SystemKeyValue migration
## Code After:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
db.rename_table('system_key_value', 'system_kv')
def backwards(self, orm):
db.rename_table('system_kv', 'system_key_value')
models = {
'system.system': {
'Meta': {'object_name': 'System', 'db_table': "'system'"},
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'system.systemkeyvalue': {
'Meta': {'unique_together': "(('key', 'value', 'system'),)", 'object_name': 'SystemKeyValue', 'db_table': "'system_kv'"},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_quoted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'system': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['system.System']"}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '255'})
}
}
complete_apps = ['system']
|
442f0df33b91fced038e2c497e6c03e0f82f55b2 | qtpy/QtTest.py | qtpy/QtTest.py |
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError
if PYQT5:
from PyQt5.QtTest import QTest
elif PYQT4:
from PyQt4.QtTest import QTest as OldQTest
class QTest(OldQTest):
@staticmethod
def qWaitForWindowActive(QWidget):
OldQTest.qWaitForWindowShown(QWidget)
elif PYSIDE:
raise ImportError('QtTest support is incomplete for PySide')
else:
raise PythonQtError('No Qt bindings could be found')
|
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError
if PYQT5:
from PyQt5.QtTest import QTest
elif PYQT4:
from PyQt4.QtTest import QTest as OldQTest
class QTest(OldQTest):
@staticmethod
def qWaitForWindowActive(QWidget):
OldQTest.qWaitForWindowShown(QWidget)
elif PYSIDE:
from PySide.QtTest import QTest
else:
raise PythonQtError('No Qt bindings could be found')
| Add support for QTest with PySide | Add support for QTest with PySide | Python | mit | spyder-ide/qtpy,davvid/qtpy,goanpeca/qtpy,davvid/qtpy,goanpeca/qtpy |
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError
if PYQT5:
from PyQt5.QtTest import QTest
elif PYQT4:
from PyQt4.QtTest import QTest as OldQTest
class QTest(OldQTest):
@staticmethod
def qWaitForWindowActive(QWidget):
OldQTest.qWaitForWindowShown(QWidget)
elif PYSIDE:
- raise ImportError('QtTest support is incomplete for PySide')
+ from PySide.QtTest import QTest
else:
raise PythonQtError('No Qt bindings could be found')
| Add support for QTest with PySide | ## Code Before:
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError
if PYQT5:
from PyQt5.QtTest import QTest
elif PYQT4:
from PyQt4.QtTest import QTest as OldQTest
class QTest(OldQTest):
@staticmethod
def qWaitForWindowActive(QWidget):
OldQTest.qWaitForWindowShown(QWidget)
elif PYSIDE:
raise ImportError('QtTest support is incomplete for PySide')
else:
raise PythonQtError('No Qt bindings could be found')
## Instruction:
Add support for QTest with PySide
## Code After:
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError
if PYQT5:
from PyQt5.QtTest import QTest
elif PYQT4:
from PyQt4.QtTest import QTest as OldQTest
class QTest(OldQTest):
@staticmethod
def qWaitForWindowActive(QWidget):
OldQTest.qWaitForWindowShown(QWidget)
elif PYSIDE:
from PySide.QtTest import QTest
else:
raise PythonQtError('No Qt bindings could be found')
|
3a0cf1f6114d6c80909f90fe122b026908200b0a | IPython/nbconvert/exporters/markdown.py | IPython/nbconvert/exporters/markdown.py | """Markdown Exporter class"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from IPython.config import Config
from .templateexporter import TemplateExporter
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class MarkdownExporter(TemplateExporter):
"""
Exports to a markdown document (.md)
"""
def _file_extension_default(self):
return 'md'
def _template_file_default(self):
return 'markdown'
output_mimetype = 'text/markdown'
def _raw_mimetypes_default(self):
return ['text/markdown', 'text/html', '']
@property
def default_config(self):
c = Config({
'NbConvertBase': {
'display_data_priority': ['html', 'application/pdf', 'svg', 'latex', 'png', 'jpg', 'jpeg' , 'text']
},
'ExtractOutputPreprocessor': {
'enabled':True}
})
c.merge(super(MarkdownExporter,self).default_config)
return c
| """Markdown Exporter class"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from IPython.config import Config
from .templateexporter import TemplateExporter
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class MarkdownExporter(TemplateExporter):
"""
Exports to a markdown document (.md)
"""
def _file_extension_default(self):
return 'md'
def _template_file_default(self):
return 'markdown'
output_mimetype = 'text/markdown'
def _raw_mimetypes_default(self):
return ['text/markdown', 'text/html', '']
@property
def default_config(self):
c = Config({'ExtractOutputPreprocessor':{'enabled':True}})
c.merge(super(MarkdownExporter,self).default_config)
return c
| Revert "Removed Javascript from Markdown by adding display priority to def config." | Revert "Removed Javascript from Markdown by adding display priority to def config."
This reverts commit 58e05f9625c60f8deba9ddf1c74dba73e8ea7dd1.
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | """Markdown Exporter class"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from IPython.config import Config
from .templateexporter import TemplateExporter
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class MarkdownExporter(TemplateExporter):
"""
Exports to a markdown document (.md)
"""
def _file_extension_default(self):
return 'md'
def _template_file_default(self):
return 'markdown'
output_mimetype = 'text/markdown'
def _raw_mimetypes_default(self):
return ['text/markdown', 'text/html', '']
@property
def default_config(self):
+ c = Config({'ExtractOutputPreprocessor':{'enabled':True}})
- c = Config({
- 'NbConvertBase': {
- 'display_data_priority': ['html', 'application/pdf', 'svg', 'latex', 'png', 'jpg', 'jpeg' , 'text']
- },
- 'ExtractOutputPreprocessor': {
- 'enabled':True}
- })
c.merge(super(MarkdownExporter,self).default_config)
return c
| Revert "Removed Javascript from Markdown by adding display priority to def config." | ## Code Before:
"""Markdown Exporter class"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from IPython.config import Config
from .templateexporter import TemplateExporter
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class MarkdownExporter(TemplateExporter):
"""
Exports to a markdown document (.md)
"""
def _file_extension_default(self):
return 'md'
def _template_file_default(self):
return 'markdown'
output_mimetype = 'text/markdown'
def _raw_mimetypes_default(self):
return ['text/markdown', 'text/html', '']
@property
def default_config(self):
c = Config({
'NbConvertBase': {
'display_data_priority': ['html', 'application/pdf', 'svg', 'latex', 'png', 'jpg', 'jpeg' , 'text']
},
'ExtractOutputPreprocessor': {
'enabled':True}
})
c.merge(super(MarkdownExporter,self).default_config)
return c
## Instruction:
Revert "Removed Javascript from Markdown by adding display priority to def config."
## Code After:
"""Markdown Exporter class"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from IPython.config import Config
from .templateexporter import TemplateExporter
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class MarkdownExporter(TemplateExporter):
"""
Exports to a markdown document (.md)
"""
def _file_extension_default(self):
return 'md'
def _template_file_default(self):
return 'markdown'
output_mimetype = 'text/markdown'
def _raw_mimetypes_default(self):
return ['text/markdown', 'text/html', '']
@property
def default_config(self):
c = Config({'ExtractOutputPreprocessor':{'enabled':True}})
c.merge(super(MarkdownExporter,self).default_config)
return c
|
b922273cb4786e72dbf018b33100814e2a462ebe | examples/list_stats.py | examples/list_stats.py | import sys
import os
import operator
sys.path.insert(1, os.path.abspath('..'))
from wsinfo import Info
cnt = 0
max_cnt = 100
servers = {}
with open("urls.txt", "r") as f:
for url in f.readlines():
url = url[:-1]
try:
w = Info(url)
if w.server != "":
if not w.server in servers:
servers[w.server] = 1
else:
servers[w.server] += 1
print("{:35} {:15} {:3} {:15}".format(
w._url, w.ip, w.http_status_code, w.server))
except Exception as e:
print("{:30} {}".format(url, e))
cnt += 1
if cnt >= max_cnt:
break
print("="*80)
print("Web server ranking:")
rank = sorted(servers.items(), key=operator.itemgetter(1), reverse=True)
for n in range(10):
print("#{:2} {} ({})".format(n+1, rank[n][0], rank[n][1]))
|
import sys
import os
import operator
sys.path.insert(1, os.path.abspath('..'))
from wsinfo import Info
cnt = 0
max_cnt = 100
servers = {}
with open("urls.txt", "r") as f:
for url in f.readlines():
url = url[:-1]
try:
w = Info(url)
if w.server != "":
if not w.server in servers:
servers[w.server] = 1
else:
servers[w.server] += 1
print("{:35} {:15} {:3} {:15}".format(
w._url, w.ip, w.http_status_code, w.server))
except Exception as e:
print("{:35} {}".format(url, e))
cnt += 1
if cnt >= max_cnt:
break
print("="*80)
print("Web server ranking:")
rank = sorted(servers.items(), key=operator.itemgetter(1), reverse=True)
for n in range(len(rank)):
print("#{:2} {} ({})".format(n+1, rank[n][0], rank[n][1]))
| Add encoding line for Python 3 | Fix: Add encoding line for Python 3
| Python | mit | linusg/wsinfo | +
import sys
import os
import operator
sys.path.insert(1, os.path.abspath('..'))
from wsinfo import Info
cnt = 0
max_cnt = 100
servers = {}
with open("urls.txt", "r") as f:
for url in f.readlines():
url = url[:-1]
try:
w = Info(url)
if w.server != "":
if not w.server in servers:
servers[w.server] = 1
else:
servers[w.server] += 1
print("{:35} {:15} {:3} {:15}".format(
w._url, w.ip, w.http_status_code, w.server))
except Exception as e:
- print("{:30} {}".format(url, e))
+ print("{:35} {}".format(url, e))
cnt += 1
if cnt >= max_cnt:
break
print("="*80)
print("Web server ranking:")
rank = sorted(servers.items(), key=operator.itemgetter(1), reverse=True)
- for n in range(10):
+ for n in range(len(rank)):
print("#{:2} {} ({})".format(n+1, rank[n][0], rank[n][1]))
| Add encoding line for Python 3 | ## Code Before:
import sys
import os
import operator
sys.path.insert(1, os.path.abspath('..'))
from wsinfo import Info
cnt = 0
max_cnt = 100
servers = {}
with open("urls.txt", "r") as f:
for url in f.readlines():
url = url[:-1]
try:
w = Info(url)
if w.server != "":
if not w.server in servers:
servers[w.server] = 1
else:
servers[w.server] += 1
print("{:35} {:15} {:3} {:15}".format(
w._url, w.ip, w.http_status_code, w.server))
except Exception as e:
print("{:30} {}".format(url, e))
cnt += 1
if cnt >= max_cnt:
break
print("="*80)
print("Web server ranking:")
rank = sorted(servers.items(), key=operator.itemgetter(1), reverse=True)
for n in range(10):
print("#{:2} {} ({})".format(n+1, rank[n][0], rank[n][1]))
## Instruction:
Add encoding line for Python 3
## Code After:
import sys
import os
import operator
sys.path.insert(1, os.path.abspath('..'))
from wsinfo import Info
cnt = 0
max_cnt = 100
servers = {}
with open("urls.txt", "r") as f:
for url in f.readlines():
url = url[:-1]
try:
w = Info(url)
if w.server != "":
if not w.server in servers:
servers[w.server] = 1
else:
servers[w.server] += 1
print("{:35} {:15} {:3} {:15}".format(
w._url, w.ip, w.http_status_code, w.server))
except Exception as e:
print("{:35} {}".format(url, e))
cnt += 1
if cnt >= max_cnt:
break
print("="*80)
print("Web server ranking:")
rank = sorted(servers.items(), key=operator.itemgetter(1), reverse=True)
for n in range(len(rank)):
print("#{:2} {} ({})".format(n+1, rank[n][0], rank[n][1]))
|
8c34cc43d23e0d97c531e1aa5d2339693db554e0 | projects/projectdl.py | projects/projectdl.py |
from bs4 import BeautifulSoup
import requests
r = requests.get("https://projects.archlinux.org/")
soup = BeautifulSoup(r.text)
repos = soup.select(".sublevel-repo a")
repo_names = []
for repo in repos:
repo_name = repo.string
if repo_name[-4:] == ".git":
repo_name = repo_name[:-4]
repo_names.append(repo_name)
with open("projects.txt", mode = "w", encoding = "utf-8") as projects_file:
for repo_name in repo_names:
projects_file.write(repo_name + "\n")
|
from bs4 import BeautifulSoup
import requests
import simplediff
from pprint import pprint
r = requests.get("https://projects.archlinux.org/")
soup = BeautifulSoup(r.text)
repos = soup.select(".sublevel-repo a")
with open("projects.txt", mode = "r", encoding = "utf-8") as projects_file:
cur_repos = projects_file.readlines()
new_repos = []
for repo in repos:
repo_name = repo.string
if repo_name[-4:] == ".git":
repo_name = repo_name[:-4]
new_repos.append(repo_name + "\n")
repo_diff = simplediff.string_diff(''.join(cur_repos), ''.join(new_repos))
added = []
removed = []
for (diff_type, values) in repo_diff:
if diff_type == "+":
added.extend(values)
elif diff_type == "-":
removed.extend(values)
if added:
print("Added:")
pprint(added)
if removed:
print("Removed:")
pprint(removed)
if added or removed:
with open("projects.txt", mode = "w", encoding = "utf-8") as projects_file:
for repo_name in new_repos:
projects_file.write(repo_name)
else:
print("No projects were added or removed.")
| Update project downloader to do diffs before overwriting | Update project downloader to do diffs before overwriting
| Python | unlicense | djmattyg007/archlinux,djmattyg007/archlinux |
from bs4 import BeautifulSoup
import requests
+ import simplediff
+ from pprint import pprint
r = requests.get("https://projects.archlinux.org/")
soup = BeautifulSoup(r.text)
repos = soup.select(".sublevel-repo a")
- repo_names = []
+ with open("projects.txt", mode = "r", encoding = "utf-8") as projects_file:
+ cur_repos = projects_file.readlines()
+
+ new_repos = []
for repo in repos:
repo_name = repo.string
if repo_name[-4:] == ".git":
repo_name = repo_name[:-4]
- repo_names.append(repo_name)
+ new_repos.append(repo_name + "\n")
- with open("projects.txt", mode = "w", encoding = "utf-8") as projects_file:
- for repo_name in repo_names:
- projects_file.write(repo_name + "\n")
+ repo_diff = simplediff.string_diff(''.join(cur_repos), ''.join(new_repos))
+ added = []
+ removed = []
+ for (diff_type, values) in repo_diff:
+ if diff_type == "+":
+ added.extend(values)
+ elif diff_type == "-":
+ removed.extend(values)
+ if added:
+ print("Added:")
+ pprint(added)
+ if removed:
+ print("Removed:")
+ pprint(removed)
+
+ if added or removed:
+ with open("projects.txt", mode = "w", encoding = "utf-8") as projects_file:
+ for repo_name in new_repos:
+ projects_file.write(repo_name)
+ else:
+ print("No projects were added or removed.")
+ | Update project downloader to do diffs before overwriting | ## Code Before:
from bs4 import BeautifulSoup
import requests
r = requests.get("https://projects.archlinux.org/")
soup = BeautifulSoup(r.text)
repos = soup.select(".sublevel-repo a")
repo_names = []
for repo in repos:
repo_name = repo.string
if repo_name[-4:] == ".git":
repo_name = repo_name[:-4]
repo_names.append(repo_name)
with open("projects.txt", mode = "w", encoding = "utf-8") as projects_file:
for repo_name in repo_names:
projects_file.write(repo_name + "\n")
## Instruction:
Update project downloader to do diffs before overwriting
## Code After:
from bs4 import BeautifulSoup
import requests
import simplediff
from pprint import pprint
r = requests.get("https://projects.archlinux.org/")
soup = BeautifulSoup(r.text)
repos = soup.select(".sublevel-repo a")
with open("projects.txt", mode = "r", encoding = "utf-8") as projects_file:
cur_repos = projects_file.readlines()
new_repos = []
for repo in repos:
repo_name = repo.string
if repo_name[-4:] == ".git":
repo_name = repo_name[:-4]
new_repos.append(repo_name + "\n")
repo_diff = simplediff.string_diff(''.join(cur_repos), ''.join(new_repos))
added = []
removed = []
for (diff_type, values) in repo_diff:
if diff_type == "+":
added.extend(values)
elif diff_type == "-":
removed.extend(values)
if added:
print("Added:")
pprint(added)
if removed:
print("Removed:")
pprint(removed)
if added or removed:
with open("projects.txt", mode = "w", encoding = "utf-8") as projects_file:
for repo_name in new_repos:
projects_file.write(repo_name)
else:
print("No projects were added or removed.")
|
14e98bc2038f50f38244550a1fa7ec3f836ed5f3 | http/online_checker.py | http/online_checker.py | import http.client
def __is_online(domain, sub_path, response_status, response_reason):
conn = http.client.HTTPSConnection(domain, timeout=1)
conn.request("HEAD", sub_path)
response = conn.getresponse()
conn.close()
return (response.status == response_status) and (response.reason == response_reason)
def is_rm_doc_online():
return __is_online("docs.rainmeter.net", "/manual-beta/", 200, "OK")
def is_gh_online():
return __is_online("github.com", "/", 200, "OK")
def is_gh_raw_online():
"""
Check if the raw content delivery from Github is online.
It is routed to 301 and Moved Permanently because per standard it is routed to github.com
because it natively only accepts real content paths.
We do not follow reroutes else it would be 200 OK on github.com but we already have another method to check for that
and Github.com is on a different service than the content delivery.
"""
return __is_online("raw.githubusercontent.com", "/", 301, "Moved Permanently")
|
import http.client
def __is_online(domain, sub_path, response_status, response_reason):
conn = http.client.HTTPSConnection(domain, timeout=1)
conn.request("HEAD", sub_path)
response = conn.getresponse()
conn.close()
return (response.status == response_status) and (response.reason == response_reason)
def is_rm_doc_online():
"""
Check if the Rainmeter documentation page is online.
The Rainmeter online documentation is required to synchronize the local model
with the latest online version. These information are stored and parsed
to display them as a tooltip on special constructs.
"""
return __is_online("docs.rainmeter.net", "/manual-beta/", 200, "OK")
def is_gh_online():
"""
Check if GitHub is online.
The different services of GitHub are running in seperat services
and thus just being GitHub online does not mean,
that required parts are online.
"""
return __is_online("github.com", "/", 200, "OK")
def is_gh_raw_online():
"""
Check if the raw content delivery from Github is online.
It is routed to 301 and Moved Permanently because per standard it is routed to github.com
because it natively only accepts real content paths.
We do not follow reroutes else it would be 200 OK on github.com but we already have another method to check for that
and Github.com is on a different service than the content delivery.
"""
return __is_online("raw.githubusercontent.com", "/", 301, "Moved Permanently")
| Add docstring to online checker | Add docstring to online checker
| Python | mit | thatsIch/sublime-rainmeter | +
+
import http.client
def __is_online(domain, sub_path, response_status, response_reason):
conn = http.client.HTTPSConnection(domain, timeout=1)
conn.request("HEAD", sub_path)
response = conn.getresponse()
conn.close()
return (response.status == response_status) and (response.reason == response_reason)
def is_rm_doc_online():
+ """
+ Check if the Rainmeter documentation page is online.
+
+ The Rainmeter online documentation is required to synchronize the local model
+ with the latest online version. These information are stored and parsed
+ to display them as a tooltip on special constructs.
+ """
return __is_online("docs.rainmeter.net", "/manual-beta/", 200, "OK")
def is_gh_online():
+ """
+ Check if GitHub is online.
+
+ The different services of GitHub are running in seperat services
+ and thus just being GitHub online does not mean,
+ that required parts are online.
+ """
return __is_online("github.com", "/", 200, "OK")
def is_gh_raw_online():
"""
Check if the raw content delivery from Github is online.
It is routed to 301 and Moved Permanently because per standard it is routed to github.com
because it natively only accepts real content paths.
We do not follow reroutes else it would be 200 OK on github.com but we already have another method to check for that
and Github.com is on a different service than the content delivery.
"""
return __is_online("raw.githubusercontent.com", "/", 301, "Moved Permanently")
| Add docstring to online checker | ## Code Before:
import http.client
def __is_online(domain, sub_path, response_status, response_reason):
conn = http.client.HTTPSConnection(domain, timeout=1)
conn.request("HEAD", sub_path)
response = conn.getresponse()
conn.close()
return (response.status == response_status) and (response.reason == response_reason)
def is_rm_doc_online():
return __is_online("docs.rainmeter.net", "/manual-beta/", 200, "OK")
def is_gh_online():
return __is_online("github.com", "/", 200, "OK")
def is_gh_raw_online():
"""
Check if the raw content delivery from Github is online.
It is routed to 301 and Moved Permanently because per standard it is routed to github.com
because it natively only accepts real content paths.
We do not follow reroutes else it would be 200 OK on github.com but we already have another method to check for that
and Github.com is on a different service than the content delivery.
"""
return __is_online("raw.githubusercontent.com", "/", 301, "Moved Permanently")
## Instruction:
Add docstring to online checker
## Code After:
import http.client
def __is_online(domain, sub_path, response_status, response_reason):
conn = http.client.HTTPSConnection(domain, timeout=1)
conn.request("HEAD", sub_path)
response = conn.getresponse()
conn.close()
return (response.status == response_status) and (response.reason == response_reason)
def is_rm_doc_online():
"""
Check if the Rainmeter documentation page is online.
The Rainmeter online documentation is required to synchronize the local model
with the latest online version. These information are stored and parsed
to display them as a tooltip on special constructs.
"""
return __is_online("docs.rainmeter.net", "/manual-beta/", 200, "OK")
def is_gh_online():
"""
Check if GitHub is online.
The different services of GitHub are running in seperat services
and thus just being GitHub online does not mean,
that required parts are online.
"""
return __is_online("github.com", "/", 200, "OK")
def is_gh_raw_online():
"""
Check if the raw content delivery from Github is online.
It is routed to 301 and Moved Permanently because per standard it is routed to github.com
because it natively only accepts real content paths.
We do not follow reroutes else it would be 200 OK on github.com but we already have another method to check for that
and Github.com is on a different service than the content delivery.
"""
return __is_online("raw.githubusercontent.com", "/", 301, "Moved Permanently")
|
bda756847e31e97eb8363f48bed67035a3f46d67 | settings/travis.py | settings/travis.py | from defaults import *
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.postgresql_psycopg2',
'ENGINE': 'django.contrib.gis.db.backends.postgis',
# 'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'atlas_test',
'USER': 'postgres',
'PASSWORD': '',
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.simple_backend.SimpleEngine'
}
}
| from defaults import *
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.postgresql_psycopg2',
'ENGINE': 'django.contrib.gis.db.backends.postgis',
# 'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'atlas_test',
'USER': 'postgres',
'PASSWORD': '',
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'storybase_geo.search.backends.Solr2155Engine',
'URL': 'http://localhost:8080/solr3',
},
}
| Use Solr for testing with Travis CI | Use Solr for testing with Travis CI
| Python | mit | denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase | from defaults import *
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.postgresql_psycopg2',
'ENGINE': 'django.contrib.gis.db.backends.postgis',
# 'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'atlas_test',
'USER': 'postgres',
'PASSWORD': '',
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
HAYSTACK_CONNECTIONS = {
'default': {
- 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine'
+ 'ENGINE': 'storybase_geo.search.backends.Solr2155Engine',
+ 'URL': 'http://localhost:8080/solr3',
- }
+ },
}
| Use Solr for testing with Travis CI | ## Code Before:
from defaults import *
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.postgresql_psycopg2',
'ENGINE': 'django.contrib.gis.db.backends.postgis',
# 'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'atlas_test',
'USER': 'postgres',
'PASSWORD': '',
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.simple_backend.SimpleEngine'
}
}
## Instruction:
Use Solr for testing with Travis CI
## Code After:
from defaults import *
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.postgresql_psycopg2',
'ENGINE': 'django.contrib.gis.db.backends.postgis',
# 'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'atlas_test',
'USER': 'postgres',
'PASSWORD': '',
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'storybase_geo.search.backends.Solr2155Engine',
'URL': 'http://localhost:8080/solr3',
},
}
|
080e4336675ea29b28b63698e5a0e77e91d54a2b | exercises/acronym/acronym_test.py | exercises/acronym/acronym_test.py | import unittest
from acronym import abbreviate
# test cases adapted from `x-common//canonical-data.json` @ version: 1.0.0
class AcronymTest(unittest.TestCase):
def test_basic(self):
self.assertEqual(abbreviate('Portable Network Graphics'), 'PNG')
def test_lowercase_words(self):
self.assertEqual(abbreviate('Ruby on Rails'), 'ROR')
def test_camelcase(self):
self.assertEqual(abbreviate('HyperText Markup Language'), 'HTML')
def test_punctuation(self):
self.assertEqual(abbreviate('First In, First Out'), 'FIFO')
def test_all_caps_words(self):
self.assertEqual(abbreviate('PHP: Hypertext Preprocessor'), 'PHP')
def test_non_acronym_all_caps_word(self):
self.assertEqual(abbreviate('GNU Image Manipulation Program'), 'GIMP')
def test_hyphenated(self):
self.assertEqual(
abbreviate('Complementary metal-oxide semiconductor'), 'CMOS')
if __name__ == '__main__':
unittest.main()
| import unittest
from acronym import abbreviate
# test cases adapted from `x-common//canonical-data.json` @ version: 1.1.0
class AcronymTest(unittest.TestCase):
def test_basic(self):
self.assertEqual(abbreviate('Portable Network Graphics'), 'PNG')
def test_lowercase_words(self):
self.assertEqual(abbreviate('Ruby on Rails'), 'ROR')
def test_punctuation(self):
self.assertEqual(abbreviate('First In, First Out'), 'FIFO')
def test_all_caps_words(self):
self.assertEqual(abbreviate('PHP: Hypertext Preprocessor'), 'PHP')
def test_non_acronym_all_caps_word(self):
self.assertEqual(abbreviate('GNU Image Manipulation Program'), 'GIMP')
def test_hyphenated(self):
self.assertEqual(
abbreviate('Complementary metal-oxide semiconductor'), 'CMOS')
if __name__ == '__main__':
unittest.main()
| Remove test with mixed-case word | acronym: Remove test with mixed-case word
see: https://github.com/exercism/x-common/pull/788
| Python | mit | jmluy/xpython,smalley/python,exercism/xpython,exercism/python,smalley/python,jmluy/xpython,pheanex/xpython,pheanex/xpython,exercism/xpython,behrtam/xpython,exercism/python,N-Parsons/exercism-python,N-Parsons/exercism-python,mweb/python,mweb/python,behrtam/xpython | import unittest
from acronym import abbreviate
- # test cases adapted from `x-common//canonical-data.json` @ version: 1.0.0
+ # test cases adapted from `x-common//canonical-data.json` @ version: 1.1.0
class AcronymTest(unittest.TestCase):
def test_basic(self):
self.assertEqual(abbreviate('Portable Network Graphics'), 'PNG')
def test_lowercase_words(self):
self.assertEqual(abbreviate('Ruby on Rails'), 'ROR')
-
- def test_camelcase(self):
- self.assertEqual(abbreviate('HyperText Markup Language'), 'HTML')
def test_punctuation(self):
self.assertEqual(abbreviate('First In, First Out'), 'FIFO')
def test_all_caps_words(self):
self.assertEqual(abbreviate('PHP: Hypertext Preprocessor'), 'PHP')
def test_non_acronym_all_caps_word(self):
self.assertEqual(abbreviate('GNU Image Manipulation Program'), 'GIMP')
def test_hyphenated(self):
self.assertEqual(
abbreviate('Complementary metal-oxide semiconductor'), 'CMOS')
if __name__ == '__main__':
unittest.main()
| Remove test with mixed-case word | ## Code Before:
import unittest
from acronym import abbreviate
# test cases adapted from `x-common//canonical-data.json` @ version: 1.0.0
class AcronymTest(unittest.TestCase):
def test_basic(self):
self.assertEqual(abbreviate('Portable Network Graphics'), 'PNG')
def test_lowercase_words(self):
self.assertEqual(abbreviate('Ruby on Rails'), 'ROR')
def test_camelcase(self):
self.assertEqual(abbreviate('HyperText Markup Language'), 'HTML')
def test_punctuation(self):
self.assertEqual(abbreviate('First In, First Out'), 'FIFO')
def test_all_caps_words(self):
self.assertEqual(abbreviate('PHP: Hypertext Preprocessor'), 'PHP')
def test_non_acronym_all_caps_word(self):
self.assertEqual(abbreviate('GNU Image Manipulation Program'), 'GIMP')
def test_hyphenated(self):
self.assertEqual(
abbreviate('Complementary metal-oxide semiconductor'), 'CMOS')
if __name__ == '__main__':
unittest.main()
## Instruction:
Remove test with mixed-case word
## Code After:
import unittest
from acronym import abbreviate
# test cases adapted from `x-common//canonical-data.json` @ version: 1.1.0
class AcronymTest(unittest.TestCase):
def test_basic(self):
self.assertEqual(abbreviate('Portable Network Graphics'), 'PNG')
def test_lowercase_words(self):
self.assertEqual(abbreviate('Ruby on Rails'), 'ROR')
def test_punctuation(self):
self.assertEqual(abbreviate('First In, First Out'), 'FIFO')
def test_all_caps_words(self):
self.assertEqual(abbreviate('PHP: Hypertext Preprocessor'), 'PHP')
def test_non_acronym_all_caps_word(self):
self.assertEqual(abbreviate('GNU Image Manipulation Program'), 'GIMP')
def test_hyphenated(self):
self.assertEqual(
abbreviate('Complementary metal-oxide semiconductor'), 'CMOS')
if __name__ == '__main__':
unittest.main()
|
124489e979ed9d913b97ff688ce65d678579e638 | morse_modem.py | morse_modem.py | import cProfile
from demodulate.cfg import *
from demodulate.detect_tone import *
from demodulate.element_resolve import *
from gen_test import *
if __name__ == "__main__":
#gen_test_data()
data = gen_test_data()
#print len(data)/SAMPLE_FREQ
#cProfile.run('detect_tone(data)')
#print detect_tone(data)
element_resolve(*detect_tone(data))
| import cProfile
from demodulate.cfg import *
from demodulate.detect_tone import *
from demodulate.element_resolve import *
from gen_tone import *
import random
if __name__ == "__main__":
WPM = random.uniform(2,20)
pattern = [1,0,1,1,1,0,0,0,0,0,0,0] # morse code 'A'
#gen_test_data()
data = gen_tone(pattern)
#print len(data)/SAMPLE_FREQ
#cProfile.run('detect_tone(data)')
#print detect_tone(data)
element_resolve(*detect_tone(data))
| Add tone generation arguments to gen_tone | Add tone generation arguments to gen_tone
| Python | mit | nickodell/morse-code | import cProfile
from demodulate.cfg import *
from demodulate.detect_tone import *
from demodulate.element_resolve import *
- from gen_test import *
+ from gen_tone import *
+ import random
- if __name__ == "__main__":
+ if __name__ == "__main__":
+ WPM = random.uniform(2,20)
+ pattern = [1,0,1,1,1,0,0,0,0,0,0,0] # morse code 'A'
#gen_test_data()
- data = gen_test_data()
+ data = gen_tone(pattern)
#print len(data)/SAMPLE_FREQ
#cProfile.run('detect_tone(data)')
#print detect_tone(data)
element_resolve(*detect_tone(data))
| Add tone generation arguments to gen_tone | ## Code Before:
import cProfile
from demodulate.cfg import *
from demodulate.detect_tone import *
from demodulate.element_resolve import *
from gen_test import *
if __name__ == "__main__":
#gen_test_data()
data = gen_test_data()
#print len(data)/SAMPLE_FREQ
#cProfile.run('detect_tone(data)')
#print detect_tone(data)
element_resolve(*detect_tone(data))
## Instruction:
Add tone generation arguments to gen_tone
## Code After:
import cProfile
from demodulate.cfg import *
from demodulate.detect_tone import *
from demodulate.element_resolve import *
from gen_tone import *
import random
if __name__ == "__main__":
WPM = random.uniform(2,20)
pattern = [1,0,1,1,1,0,0,0,0,0,0,0] # morse code 'A'
#gen_test_data()
data = gen_tone(pattern)
#print len(data)/SAMPLE_FREQ
#cProfile.run('detect_tone(data)')
#print detect_tone(data)
element_resolve(*detect_tone(data))
|
f39f7d64ba8ca8051b24407811239f960cc6f561 | lib/collect/backend.py | lib/collect/backend.py | import lib.collect.config as config
if config.BACKEND == 'dynamodb':
import lib.collect.backends.dymamodb as api
else:
import lib.collect.backends.localfs as api
| import lib.collect.config as config
try:
if config.BACKEND == 'dynamodb':
import lib.collect.backends.dymamodb as api
else:
import lib.collect.backends.localfs as api
except AttributeError:
import lib.collect.backends.localfs as api
| Fix bug in module selection. | Fix bug in module selection.
| Python | mit | ic/mark0 | import lib.collect.config as config
+ try:
- if config.BACKEND == 'dynamodb':
+ if config.BACKEND == 'dynamodb':
- import lib.collect.backends.dymamodb as api
+ import lib.collect.backends.dymamodb as api
- else:
+ else:
+ import lib.collect.backends.localfs as api
+ except AttributeError:
import lib.collect.backends.localfs as api
| Fix bug in module selection. | ## Code Before:
import lib.collect.config as config
if config.BACKEND == 'dynamodb':
import lib.collect.backends.dymamodb as api
else:
import lib.collect.backends.localfs as api
## Instruction:
Fix bug in module selection.
## Code After:
import lib.collect.config as config
try:
if config.BACKEND == 'dynamodb':
import lib.collect.backends.dymamodb as api
else:
import lib.collect.backends.localfs as api
except AttributeError:
import lib.collect.backends.localfs as api
|
f6bff4e5360ba2c0379c129a111d333ee718c1d3 | datafeeds/usfirst_event_teams_parser.py | datafeeds/usfirst_event_teams_parser.py | import re
from BeautifulSoup import BeautifulSoup
from datafeeds.parser_base import ParserBase
class UsfirstEventTeamsParser(ParserBase):
@classmethod
def parse(self, html):
"""
Find what Teams are attending an Event, and return their team_numbers.
"""
teamRe = re.compile(r'whats-going-on/team/FRC/[A-Za-z0-9=&;\-:]*?">\d+')
teamNumberRe = re.compile(r'\d+$')
tpidRe = re.compile(r'\d+')
teams = list()
for teamResult in teamRe.findall(html):
team = dict()
team["team_number"] = int(teamNumberRe.findall(teamResult)[0])
team["first_tpid"] = int(tpidRe.findall(teamResult)[0])
teams.append(team)
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)
more_pages = soup.find('a', {'title': 'Go to next page'}) is not None
return teams, more_pages
| import re
from BeautifulSoup import BeautifulSoup
from datafeeds.parser_base import ParserBase
class UsfirstEventTeamsParser(ParserBase):
@classmethod
def parse(self, html):
"""
Find what Teams are attending an Event, and return their team_numbers.
"""
teamRe = re.compile(r'whats-going-on\/team\/(\d*)\?ProgramCode=FRC">(\d*)')
teams = list()
for first_tpid, team_number in teamRe.findall(html):
team = dict()
team["first_tpid"] = int(first_tpid)
team["team_number"] = int(team_number)
teams.append(team)
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)
more_pages = soup.find('a', {'title': 'Go to next page'}) is not None
return teams, more_pages
| Fix event teams parser for new format | Fix event teams parser for new format
| Python | mit | the-blue-alliance/the-blue-alliance,jaredhasenklein/the-blue-alliance,nwalters512/the-blue-alliance,nwalters512/the-blue-alliance,bdaroz/the-blue-alliance,1fish2/the-blue-alliance,synth3tk/the-blue-alliance,jaredhasenklein/the-blue-alliance,bdaroz/the-blue-alliance,nwalters512/the-blue-alliance,tsteward/the-blue-alliance,jaredhasenklein/the-blue-alliance,the-blue-alliance/the-blue-alliance,the-blue-alliance/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,fangeugene/the-blue-alliance,bvisness/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,synth3tk/the-blue-alliance,josephbisch/the-blue-alliance,phil-lopreiato/the-blue-alliance,nwalters512/the-blue-alliance,bdaroz/the-blue-alliance,josephbisch/the-blue-alliance,the-blue-alliance/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,bdaroz/the-blue-alliance,tsteward/the-blue-alliance,1fish2/the-blue-alliance,bvisness/the-blue-alliance,jaredhasenklein/the-blue-alliance,bvisness/the-blue-alliance,the-blue-alliance/the-blue-alliance,1fish2/the-blue-alliance,synth3tk/the-blue-alliance,tsteward/the-blue-alliance,tsteward/the-blue-alliance,1fish2/the-blue-alliance,nwalters512/the-blue-alliance,bdaroz/the-blue-alliance,1fish2/the-blue-alliance,synth3tk/the-blue-alliance,josephbisch/the-blue-alliance,bvisness/the-blue-alliance,phil-lopreiato/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance,phil-lopreiato/the-blue-alliance,phil-lopreiato/the-blue-alliance,jaredhasenklein/the-blue-alliance,bvisness/the-blue-alliance,josephbisch/the-blue-alliance,verycumbersome/the-blue-alliance,josephbisch/the-blue-alliance,the-blue-alliance/the-blue-alliance,tsteward/the-blue-alliance,1fish2/the-blue-alliance,phil-lopreiato/the-blue-alliance,nwalters512/the-blue-alliance,fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,josephbisch/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,fangeugene/the-blue-alliance,bvisness/the-blue-alliance,phil-lopreiato/the-blue-alliance,verycumbersome/the-blue-alliance,verycumbersome/the-blue-alliance | import re
from BeautifulSoup import BeautifulSoup
from datafeeds.parser_base import ParserBase
class UsfirstEventTeamsParser(ParserBase):
@classmethod
def parse(self, html):
"""
Find what Teams are attending an Event, and return their team_numbers.
"""
+ teamRe = re.compile(r'whats-going-on\/team\/(\d*)\?ProgramCode=FRC">(\d*)')
- teamRe = re.compile(r'whats-going-on/team/FRC/[A-Za-z0-9=&;\-:]*?">\d+')
- teamNumberRe = re.compile(r'\d+$')
- tpidRe = re.compile(r'\d+')
teams = list()
- for teamResult in teamRe.findall(html):
+ for first_tpid, team_number in teamRe.findall(html):
team = dict()
+ team["first_tpid"] = int(first_tpid)
- team["team_number"] = int(teamNumberRe.findall(teamResult)[0])
+ team["team_number"] = int(team_number)
- team["first_tpid"] = int(tpidRe.findall(teamResult)[0])
teams.append(team)
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)
more_pages = soup.find('a', {'title': 'Go to next page'}) is not None
return teams, more_pages
| Fix event teams parser for new format | ## Code Before:
import re
from BeautifulSoup import BeautifulSoup
from datafeeds.parser_base import ParserBase
class UsfirstEventTeamsParser(ParserBase):
@classmethod
def parse(self, html):
"""
Find what Teams are attending an Event, and return their team_numbers.
"""
teamRe = re.compile(r'whats-going-on/team/FRC/[A-Za-z0-9=&;\-:]*?">\d+')
teamNumberRe = re.compile(r'\d+$')
tpidRe = re.compile(r'\d+')
teams = list()
for teamResult in teamRe.findall(html):
team = dict()
team["team_number"] = int(teamNumberRe.findall(teamResult)[0])
team["first_tpid"] = int(tpidRe.findall(teamResult)[0])
teams.append(team)
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)
more_pages = soup.find('a', {'title': 'Go to next page'}) is not None
return teams, more_pages
## Instruction:
Fix event teams parser for new format
## Code After:
import re
from BeautifulSoup import BeautifulSoup
from datafeeds.parser_base import ParserBase
class UsfirstEventTeamsParser(ParserBase):
@classmethod
def parse(self, html):
"""
Find what Teams are attending an Event, and return their team_numbers.
"""
teamRe = re.compile(r'whats-going-on\/team\/(\d*)\?ProgramCode=FRC">(\d*)')
teams = list()
for first_tpid, team_number in teamRe.findall(html):
team = dict()
team["first_tpid"] = int(first_tpid)
team["team_number"] = int(team_number)
teams.append(team)
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)
more_pages = soup.find('a', {'title': 'Go to next page'}) is not None
return teams, more_pages
|
b80726a5a36480b4146fc4df89ad96a738aa2091 | waitress/settings/__init__.py | waitress/settings/__init__.py | import os
if os.getenv('OPENSHIFT_REPO_DIR'):
from .staging import *
elif os.getenv('TRAVIS_CI'):
from .testing import *
else:
from .development import * | import os
if os.getenv('OPENSHIFT_REPO_DIR'):
from .staging import *
elif os.getenv('TRAVIS_CI'):
from .testing import *
elif os.getenv('HEROKU'):
from .production import *
else:
from .development import * | Use production settings in Heroku | [fix] Use production settings in Heroku
| Python | mit | waitress-andela/waitress,andela-osule/waitress,andela-osule/waitress,andela-osule/waitress,waitress-andela/waitress,waitress-andela/waitress | import os
if os.getenv('OPENSHIFT_REPO_DIR'):
from .staging import *
elif os.getenv('TRAVIS_CI'):
from .testing import *
+ elif os.getenv('HEROKU'):
+ from .production import *
else:
from .development import * | Use production settings in Heroku | ## Code Before:
import os
if os.getenv('OPENSHIFT_REPO_DIR'):
from .staging import *
elif os.getenv('TRAVIS_CI'):
from .testing import *
else:
from .development import *
## Instruction:
Use production settings in Heroku
## Code After:
import os
if os.getenv('OPENSHIFT_REPO_DIR'):
from .staging import *
elif os.getenv('TRAVIS_CI'):
from .testing import *
elif os.getenv('HEROKU'):
from .production import *
else:
from .development import * |
814684225140231de25dc7ee616c6bfa73b312ee | addons/hr/__terp__.py | addons/hr/__terp__.py | {
"name" : "Human Resources",
"version" : "1.0",
"author" : "Tiny",
"category" : "Generic Modules/Human Resources",
"website" : "http://tinyerp.com/module_hr.html",
"description": """
Module for human resource management. You can manage:
* Employees and hierarchies
* Work hours sheets
* Attendances and sign in/out system
* Holidays
Different reports are also provided, mainly for attendance statistics.
""",
"depends" : ["base"],
"init_xml" : [],
"demo_xml" : [
"hr_demo.xml",
"hr_bel_holidays_2005.xml",
"hr_department_demo.xml"
],
"update_xml" : [
"hr_view.xml",
"hr_report.xml",
"hr_wizard.xml",
"hr_department_view.xml"
],
"active": False,
"installable": True
}
| {
"name" : "Human Resources",
"version" : "1.0",
"author" : "Tiny",
"category" : "Generic Modules/Human Resources",
"website" : "http://tinyerp.com/module_hr.html",
"description": """
Module for human resource management. You can manage:
* Employees and hierarchies
* Work hours sheets
* Attendances and sign in/out system
* Holidays
Different reports are also provided, mainly for attendance statistics.
""",
"depends" : ["base"],
"init_xml" : [],
"demo_xml" : [
"hr_demo.xml",
"hr_bel_holidays_2005.xml",
"hr_department_demo.xml"
],
"update_xml" : [
"hr_view.xml",
"hr_report.xml",
"hr_wizard.xml",
"hr_department_view.xml",
"hr_security.xml"
],
"active": False,
"installable": True
}
| Add hr_security.xml file entry in update_xml section | Add hr_security.xml file entry in update_xml section
bzr revid: [email protected] | Python | agpl-3.0 | VielSoft/odoo,naousse/odoo,tarzan0820/odoo,BT-ojossen/odoo,leoliujie/odoo,Danisan/odoo-1,ehirt/odoo,odooindia/odoo,ThinkOpen-Solutions/odoo,bakhtout/odoo-educ,ingadhoc/odoo,naousse/odoo,datenbetrieb/odoo,charbeljc/OCB,sysadminmatmoz/OCB,cysnake4713/odoo,arthru/OpenUpgrade,bwrsandman/OpenUpgrade,ovnicraft/odoo,sysadminmatmoz/OCB,Adel-Magebinary/odoo,realsaiko/odoo,OpusVL/odoo,inspyration/odoo,tvibliani/odoo,ClearCorp-dev/odoo,rschnapka/odoo,jusdng/odoo,florentx/OpenUpgrade,blaggacao/OpenUpgrade,CopeX/odoo,ChanduERP/odoo,JCA-Developpement/Odoo,ThinkOpen-Solutions/odoo,mustafat/odoo-1,synconics/odoo,ovnicraft/odoo,Ichag/odoo,dalegregory/odoo,guerrerocarlos/odoo,hbrunn/OpenUpgrade,hoatle/odoo,ojengwa/odoo,juanalfonsopr/odoo,demon-ru/iml-crm,nexiles/odoo,rschnapka/odoo,ujjwalwahi/odoo,sv-dev1/odoo,fuselock/odoo,hifly/OpenUpgrade,arthru/OpenUpgrade,joshuajan/odoo,Grirrane/odoo,Codefans-fan/odoo,srsman/odoo,steedos/odoo,mkieszek/odoo,bakhtout/odoo-educ,leoliujie/odoo,poljeff/odoo,fuselock/odoo,fjbatresv/odoo,tvibliani/odoo,abstract-open-solutions/OCB,pedrobaeza/OpenUpgrade,VitalPet/odoo,osvalr/odoo,nitinitprof/odoo,rdeheele/odoo,joshuajan/odoo,hanicker/odoo,GauravSahu/odoo,dsfsdgsbngfggb/odoo,draugiskisprendimai/odoo,apocalypsebg/odoo,joariasl/odoo,MarcosCommunity/odoo,mszewczy/odoo,diagramsoftware/odoo,abstract-open-solutions/OCB,JonathanStein/odoo,OpusVL/odoo,Adel-Magebinary/odoo,brijeshkesariya/odoo,fuhongliang/odoo,OpenPymeMx/OCB,dkubiak789/odoo,gsmartway/odoo,SerpentCS/odoo,rubencabrera/odoo,ApuliaSoftware/odoo,Gitlab11/odoo,patmcb/odoo,gsmartway/odoo,rgeleta/odoo,janocat/odoo,frouty/odoogoeen,SAM-IT-SA/odoo,apanju/odoo,ClearCorp-dev/odoo,frouty/odoogoeen,guewen/OpenUpgrade,tvtsoft/odoo8,nagyistoce/odoo-dev-odoo,makinacorpus/odoo,x111ong/odoo,dkubiak789/odoo,ygol/odoo,bguillot/OpenUpgrade,ehirt/odoo,laslabs/odoo,hopeall/odoo,florentx/OpenUpgrade,jolevq/odoopub,vnsofthe/odoo,OpenUpgrade/OpenUpgrade,luiseduardohdbackup/odoo,mvaled/OpenUpgrade,oliverhr/odoo,dezynetechnologies/odoo,naousse/odoo,dllsf/odootest,ccomb/OpenUpgrade,guerrerocarlos/odoo,markeTIC/OCB,lsinfo/odoo,fgesora/odoo,jiangzhixiao/odoo,shaufi10/odoo,fevxie/odoo,alqfahad/odoo,gdgellatly/OCB1,spadae22/odoo,nagyistoce/odoo-dev-odoo,Endika/odoo,andreparames/odoo,ovnicraft/odoo,omprakasha/odoo,Nowheresly/odoo,MarcosCommunity/odoo,QianBIG/odoo,mkieszek/odoo,simongoffin/website_version,florentx/OpenUpgrade,sebalix/OpenUpgrade,leorochael/odoo,apanju/GMIO_Odoo,realsaiko/odoo,gvb/odoo,florian-dacosta/OpenUpgrade,slevenhagen/odoo,naousse/odoo,abstract-open-solutions/OCB,hubsaysnuaa/odoo,nuncjo/odoo,prospwro/odoo,colinnewell/odoo,ShineFan/odoo,QianBIG/odoo,jesramirez/odoo,nhomar/odoo-mirror,makinacorpus/odoo,OSSESAC/odoopubarquiluz,draugiskisprendimai/odoo,cloud9UG/odoo,odoousers2014/odoo,gvb/odoo,Drooids/odoo,BT-astauder/odoo,vrenaville/ngo-addons-backport,bplancher/odoo,blaggacao/OpenUpgrade,optima-ict/odoo,MarcosCommunity/odoo,realsaiko/odoo,ThinkOpen-Solutions/odoo,collex100/odoo,stephen144/odoo,nexiles/odoo,jaxkodex/odoo,fjbatresv/odoo,patmcb/odoo,markeTIC/OCB,dariemp/odoo,FlorianLudwig/odoo,ThinkOpen-Solutions/odoo,salaria/odoo,stephen144/odoo,laslabs/odoo,laslabs/odoo,lombritz/odoo,demon-ru/iml-crm,gvb/odoo,pedrobaeza/odoo,rahuldhote/odoo,osvalr/odoo,javierTerry/odoo,glovebx/odoo,jiangzhixiao/odoo,NL66278/OCB,markeTIC/OCB,collex100/odoo,rowemoore/odoo,jusdng/odoo,GauravSahu/odoo,BT-rmartin/odoo,Drooids/odoo,mustafat/odoo-1,rahuldhote/odoo,FlorianLudwig/odoo,markeTIC/OCB,nagyistoce/odoo-dev-odoo,ShineFan/odoo,dariemp/odoo,CubicERP/odoo,mvaled/OpenUpgrade,andreparames/odoo,kybriainfotech/iSocioCRM,grap/OpenUpgrade,jaxkodex/odoo,Bachaco-ve/odoo,slevenhagen/odoo-npg,slevenhagen/odoo-npg,factorlibre/OCB,gdgellatly/OCB1,Noviat/odoo,hmen89/odoo,CatsAndDogsbvba/odoo,GauravSahu/odoo,oihane/odoo,podemos-info/odoo,luiseduardohdbackup/odoo,kybriainfotech/iSocioCRM,havt/odoo,BT-rmartin/odoo,ihsanudin/odoo,provaleks/o8,apanju/GMIO_Odoo,VielSoft/odoo,vnsofthe/odoo,shaufi/odoo,slevenhagen/odoo,colinnewell/odoo,juanalfonsopr/odoo,wangjun/odoo,mvaled/OpenUpgrade,funkring/fdoo,Nowheresly/odoo,havt/odoo,TRESCLOUD/odoopub,mlaitinen/odoo,papouso/odoo,acshan/odoo,fevxie/odoo,kittiu/odoo,sebalix/OpenUpgrade,nexiles/odoo,Elico-Corp/odoo_OCB,wangjun/odoo,bakhtout/odoo-educ,fjbatresv/odoo,grap/OpenUpgrade,vnsofthe/odoo,ccomb/OpenUpgrade,codekaki/odoo,microcom/odoo,slevenhagen/odoo-npg,sebalix/OpenUpgrade,minhtuancn/odoo,ygol/odoo,tangyiyong/odoo,nuncjo/odoo,acshan/odoo,tangyiyong/odoo,jesramirez/odoo,sergio-incaser/odoo,Noviat/odoo,nuuuboo/odoo,hip-odoo/odoo,shingonoide/odoo,savoirfairelinux/OpenUpgrade,rgeleta/odoo,arthru/OpenUpgrade,Adel-Magebinary/odoo,Ernesto99/odoo,leoliujie/odoo,synconics/odoo,lombritz/odoo,lgscofield/odoo,jiangzhixiao/odoo,bwrsandman/OpenUpgrade,tangyiyong/odoo,fgesora/odoo,luistorresm/odoo,tinkhaven-organization/odoo,tvtsoft/odoo8,jpshort/odoo,Danisan/odoo-1,rschnapka/odoo,kybriainfotech/iSocioCRM,dfang/odoo,Elico-Corp/odoo_OCB,tinkerthaler/odoo,bkirui/odoo,ccomb/OpenUpgrade,jeasoft/odoo,cloud9UG/odoo,SAM-IT-SA/odoo,feroda/odoo,abenzbiria/clients_odoo,JCA-Developpement/Odoo,guerrerocarlos/odoo,OpenPymeMx/OCB,Daniel-CA/odoo,apanju/odoo,ramitalat/odoo,frouty/odoogoeen,zchking/odoo,prospwro/odoo,slevenhagen/odoo,ramadhane/odoo,bplancher/odoo,Kilhog/odoo,hifly/OpenUpgrade,gavin-feng/odoo,NeovaHealth/odoo,cloud9UG/odoo,markeTIC/OCB,prospwro/odoo,dfang/odoo,patmcb/odoo,ojengwa/odoo,jpshort/odoo,fossoult/odoo,Ernesto99/odoo,ojengwa/odoo,joariasl/odoo,grap/OCB,dgzurita/odoo,kybriainfotech/iSocioCRM,ovnicraft/odoo,Grirrane/odoo,Noviat/odoo,dariemp/odoo,Gitlab11/odoo,nhomar/odoo,apanju/GMIO_Odoo,dfang/odoo,Elico-Corp/odoo_OCB,dfang/odoo,gdgellatly/OCB1,ygol/odoo,jeasoft/odoo,makinacorpus/odoo,alqfahad/odoo,NeovaHealth/odoo,sysadminmatmoz/OCB,Antiun/odoo,ovnicraft/odoo,x111ong/odoo,luistorresm/odoo,idncom/odoo,dezynetechnologies/odoo,shivam1111/odoo,gdgellatly/OCB1,ehirt/odoo,ingadhoc/odoo,blaggacao/OpenUpgrade,dkubiak789/odoo,jiachenning/odoo,gsmartway/odoo,cedk/odoo,codekaki/odoo,nhomar/odoo,KontorConsulting/odoo,diagramsoftware/odoo,ramadhane/odoo,storm-computers/odoo,kirca/OpenUpgrade,stonegithubs/odoo,goliveirab/odoo,nuuuboo/odoo,n0m4dz/odoo,microcom/odoo,OpenUpgrade-dev/OpenUpgrade,blaggacao/OpenUpgrade,frouty/odoo_oph,rubencabrera/odoo,simongoffin/website_version,leorochael/odoo,sinbazhou/odoo,klunwebale/odoo,nhomar/odoo-mirror,rubencabrera/odoo,abdellatifkarroum/odoo,alhashash/odoo,oasiswork/odoo,ChanduERP/odoo,lgscofield/odoo,sadleader/odoo,oliverhr/odoo,odootr/odoo,windedge/odoo,matrixise/odoo,vrenaville/ngo-addons-backport,incaser/odoo-odoo,odoo-turkiye/odoo,dkubiak789/odoo,CatsAndDogsbvba/odoo,tvtsoft/odoo8,jiachenning/odoo,rschnapka/odoo,Daniel-CA/odoo,savoirfairelinux/OpenUpgrade,sve-odoo/odoo,fuselock/odoo,matrixise/odoo,hopeall/odoo,JonathanStein/odoo,Eric-Zhong/odoo,draugiskisprendimai/odoo,cpyou/odoo,Noviat/odoo,bkirui/odoo,Grirrane/odoo,guewen/OpenUpgrade,andreparames/odoo,osvalr/odoo,jesramirez/odoo,funkring/fdoo,avoinsystems/odoo,ecosoft-odoo/odoo,OSSESAC/odoopubarquiluz,brijeshkesariya/odoo,csrocha/OpenUpgrade,BT-rmartin/odoo,damdam-s/OpenUpgrade,alexcuellar/odoo,JGarcia-Panach/odoo,hifly/OpenUpgrade,papouso/odoo,abenzbiria/clients_odoo,oasiswork/odoo,bealdav/OpenUpgrade,highco-groupe/odoo,aviciimaxwell/odoo,KontorConsulting/odoo,hassoon3/odoo,shaufi/odoo,AuyaJackie/odoo,credativUK/OCB,VitalPet/odoo,n0m4dz/odoo,cpyou/odoo,Endika/odoo,alhashash/odoo,provaleks/o8,Danisan/odoo-1,OpenUpgrade-dev/OpenUpgrade,pedrobaeza/odoo,srimai/odoo,dfang/odoo,grap/OCB,savoirfairelinux/odoo,Elico-Corp/odoo_OCB,rowemoore/odoo,QianBIG/odoo,incaser/odoo-odoo,joariasl/odoo,VitalPet/odoo,jeasoft/odoo,colinnewell/odoo,CopeX/odoo,alexcuellar/odoo,PongPi/isl-odoo,makinacorpus/odoo,mszewczy/odoo,lightcn/odoo,goliveirab/odoo,tarzan0820/odoo,christophlsa/odoo,avoinsystems/odoo,blaggacao/OpenUpgrade,deKupini/erp,fdvarela/odoo8,Adel-Magebinary/odoo,FlorianLudwig/odoo,bealdav/OpenUpgrade,stonegithubs/odoo,ramadhane/odoo,Codefans-fan/odoo,charbeljc/OCB,JonathanStein/odoo,christophlsa/odoo,x111ong/odoo,Drooids/odoo,takis/odoo,rschnapka/odoo,avoinsystems/odoo,cpyou/odoo,ThinkOpen-Solutions/odoo,chiragjogi/odoo,JonathanStein/odoo,doomsterinc/odoo,tinkerthaler/odoo,podemos-info/odoo,storm-computers/odoo,kybriainfotech/iSocioCRM,guewen/OpenUpgrade,Kilhog/odoo,pedrobaeza/OpenUpgrade,funkring/fdoo,OpenUpgrade/OpenUpgrade,grap/OCB,thanhacun/odoo,gorjuce/odoo,ClearCorp-dev/odoo,apocalypsebg/odoo,gvb/odoo,shaufi/odoo,omprakasha/odoo,mlaitinen/odoo,hanicker/odoo,pedrobaeza/OpenUpgrade,jesramirez/odoo,lombritz/odoo,jaxkodex/odoo,PongPi/isl-odoo,apocalypsebg/odoo,OpenUpgrade-dev/OpenUpgrade,SerpentCS/odoo,gavin-feng/odoo,OpenUpgrade-dev/OpenUpgrade,sv-dev1/odoo,factorlibre/OCB,idncom/odoo,alhashash/odoo,odootr/odoo,lsinfo/odoo,OpenUpgrade/OpenUpgrade,mustafat/odoo-1,BT-fgarbely/odoo,jeasoft/odoo,javierTerry/odoo,doomsterinc/odoo,MarcosCommunity/odoo,charbeljc/OCB,pplatek/odoo,papouso/odoo,guewen/OpenUpgrade,idncom/odoo,steedos/odoo,Grirrane/odoo,NeovaHealth/odoo,fevxie/odoo,sergio-incaser/odoo,ehirt/odoo,bobisme/odoo,RafaelTorrealba/odoo,OpenPymeMx/OCB,datenbetrieb/odoo,eino-makitalo/odoo,lsinfo/odoo,leorochael/odoo,dalegregory/odoo,patmcb/odoo,virgree/odoo,ygol/odoo,odooindia/odoo,jolevq/odoopub,mkieszek/odoo,JonathanStein/odoo,VitalPet/odoo,brijeshkesariya/odoo,VitalPet/odoo,shaufi10/odoo,srimai/odoo,matrixise/odoo,bakhtout/odoo-educ,mmbtba/odoo,alhashash/odoo,dariemp/odoo,tvtsoft/odoo8,luiseduardohdbackup/odoo,sysadminmatmoz/OCB,JonathanStein/odoo,ApuliaSoftware/odoo,gavin-feng/odoo,cpyou/odoo,odoo-turkiye/odoo,steedos/odoo,factorlibre/OCB,jusdng/odoo,Endika/odoo,Nick-OpusVL/odoo,pedrobaeza/OpenUpgrade,Maspear/odoo,dgzurita/odoo,waytai/odoo,fossoult/odoo,frouty/odoogoeen,KontorConsulting/odoo,acshan/odoo,frouty/odoogoeen,florentx/OpenUpgrade,leorochael/odoo,Kilhog/odoo,jusdng/odoo,draugiskisprendimai/odoo,takis/odoo,idncom/odoo,srimai/odoo,chiragjogi/odoo,windedge/odoo,fdvarela/odoo8,lgscofield/odoo,Kilhog/odoo,rschnapka/odoo,thanhacun/odoo,shingonoide/odoo,luiseduardohdbackup/odoo,ujjwalwahi/odoo,mustafat/odoo-1,cpyou/odoo,microcom/odoo,NL66278/OCB,bwrsandman/OpenUpgrade,simongoffin/website_version,alexcuellar/odoo,Danisan/odoo-1,jusdng/odoo,mlaitinen/odoo,funkring/fdoo,feroda/odoo,BT-ojossen/odoo,minhtuancn/odoo,aviciimaxwell/odoo,codekaki/odoo,VitalPet/odoo,OpenPymeMx/OCB,savoirfairelinux/OpenUpgrade,dezynetechnologies/odoo,ecosoft-odoo/odoo,pplatek/odoo,numerigraphe/odoo,NL66278/OCB,joariasl/odoo,hoatle/odoo,grap/OCB,fossoult/odoo,xzYue/odoo,jiachenning/odoo,fuselock/odoo,pedrobaeza/OpenUpgrade,apanju/odoo,agrista/odoo-saas,kirca/OpenUpgrade,synconics/odoo,gavin-feng/odoo,fdvarela/odoo8,synconics/odoo,grap/OCB,acshan/odoo,optima-ict/odoo,odootr/odoo,vnsofthe/odoo,lightcn/odoo,andreparames/odoo,gorjuce/odoo,wangjun/odoo,markeTIC/OCB,dezynetechnologies/odoo,Antiun/odoo,eino-makitalo/odoo,gsmartway/odoo,oasiswork/odoo,ShineFan/odoo,frouty/odoo_oph,matrixise/odoo,oliverhr/odoo,naousse/odoo,charbeljc/OCB,shivam1111/odoo,mvaled/OpenUpgrade,minhtuancn/odoo,sadleader/odoo,inspyration/odoo,bguillot/OpenUpgrade,hip-odoo/odoo,kittiu/odoo,steedos/odoo,tvtsoft/odoo8,Danisan/odoo-1,incaser/odoo-odoo,javierTerry/odoo,hoatle/odoo,stonegithubs/odoo,pedrobaeza/odoo,christophlsa/odoo,nitinitprof/odoo,sinbazhou/odoo,shivam1111/odoo,vnsofthe/odoo,srsman/odoo,apanju/GMIO_Odoo,BT-ojossen/odoo,jeasoft/odoo,tangyiyong/odoo,JCA-Developpement/Odoo,lsinfo/odoo,lgscofield/odoo,nhomar/odoo,dkubiak789/odoo,SerpentCS/odoo,rdeheele/odoo,factorlibre/OCB,rahuldhote/odoo,storm-computers/odoo,srsman/odoo,lightcn/odoo,CatsAndDogsbvba/odoo,JGarcia-Panach/odoo,gsmartway/odoo,odoousers2014/odoo,apocalypsebg/odoo,fossoult/odoo,OpenPymeMx/OCB,RafaelTorrealba/odoo,aviciimaxwell/odoo,credativUK/OCB,sinbazhou/odoo,hubsaysnuaa/odoo,ihsanudin/odoo,luiseduardohdbackup/odoo,damdam-s/OpenUpgrade,RafaelTorrealba/odoo,jaxkodex/odoo,Grirrane/odoo,collex100/odoo,Ernesto99/odoo,synconics/odoo,tangyiyong/odoo,tarzan0820/odoo,ramadhane/odoo,glovebx/odoo,synconics/odoo,lightcn/odoo,camptocamp/ngo-addons-backport,thanhacun/odoo,goliveirab/odoo,savoirfairelinux/odoo,florian-dacosta/OpenUpgrade,fuhongliang/odoo,bakhtout/odoo-educ,Endika/odoo,bwrsandman/OpenUpgrade,tinkerthaler/odoo,diagramsoftware/odoo,ubic135/odoo-design,thanhacun/odoo,ecosoft-odoo/odoo,mmbtba/odoo,camptocamp/ngo-addons-backport,shaufi/odoo,KontorConsulting/odoo,lgscofield/odoo,xujb/odoo,vrenaville/ngo-addons-backport,cdrooom/odoo,dgzurita/odoo,optima-ict/odoo,rahuldhote/odoo,shivam1111/odoo,leoliujie/odoo,Daniel-CA/odoo,ApuliaSoftware/odoo,OpenPymeMx/OCB,sadleader/odoo,JCA-Developpement/Odoo,microcom/odoo,sergio-incaser/odoo,factorlibre/OCB,RafaelTorrealba/odoo,srimai/odoo,ojengwa/odoo,christophlsa/odoo,lsinfo/odoo,dezynetechnologies/odoo,odoo-turkiye/odoo,fevxie/odoo,mustafat/odoo-1,Bachaco-ve/odoo,TRESCLOUD/odoopub,laslabs/odoo,sebalix/OpenUpgrade,n0m4dz/odoo,makinacorpus/odoo,waytai/odoo,ApuliaSoftware/odoo,aviciimaxwell/odoo,eino-makitalo/odoo,oasiswork/odoo,OpenUpgrade/OpenUpgrade,SerpentCS/odoo,florian-dacosta/OpenUpgrade,rgeleta/odoo,srsman/odoo,tarzan0820/odoo,odootr/odoo,tarzan0820/odoo,xzYue/odoo,dalegregory/odoo,OSSESAC/odoopubarquiluz,provaleks/o8,feroda/odoo,hifly/OpenUpgrade,Grirrane/odoo,frouty/odoogoeen,zchking/odoo,xzYue/odoo,cysnake4713/odoo,TRESCLOUD/odoopub,slevenhagen/odoo,javierTerry/odoo,ccomb/OpenUpgrade,shaufi/odoo,CopeX/odoo,nhomar/odoo,hoatle/odoo,nuuuboo/odoo,elmerdpadilla/iv,bplancher/odoo,ecosoft-odoo/odoo,waytai/odoo,diagramsoftware/odoo,csrocha/OpenUpgrade,pedrobaeza/OpenUpgrade,numerigraphe/odoo,poljeff/odoo,charbeljc/OCB,syci/OCB,cloud9UG/odoo,steedos/odoo,hopeall/odoo,havt/odoo,mlaitinen/odoo,rubencabrera/odoo,klunwebale/odoo,poljeff/odoo,cdrooom/odoo,nuuuboo/odoo,bkirui/odoo,osvalr/odoo,Nick-OpusVL/odoo,csrocha/OpenUpgrade,pedrobaeza/odoo,massot/odoo,dgzurita/odoo,gorjuce/odoo,bobisme/odoo,shivam1111/odoo,AuyaJackie/odoo,rubencabrera/odoo,draugiskisprendimai/odoo,dalegregory/odoo,windedge/odoo,christophlsa/odoo,bwrsandman/OpenUpgrade,hassoon3/odoo,rdeheele/odoo,ShineFan/odoo,bwrsandman/OpenUpgrade,jiangzhixiao/odoo,hmen89/odoo,vrenaville/ngo-addons-backport,savoirfairelinux/odoo,slevenhagen/odoo,nitinitprof/odoo,CopeX/odoo,oihane/odoo,shaufi10/odoo,ihsanudin/odoo,Nowheresly/odoo,Drooids/odoo,credativUK/OCB,glovebx/odoo,frouty/odoo_oph,gdgellatly/OCB1,Eric-Zhong/odoo,papouso/odoo,Antiun/odoo,oliverhr/odoo,odoousers2014/odoo,CopeX/odoo,spadae22/odoo,oliverhr/odoo,provaleks/o8,acshan/odoo,tinkhaven-organization/odoo,cedk/odoo,Endika/OpenUpgrade,ChanduERP/odoo,MarcosCommunity/odoo,idncom/odoo,camptocamp/ngo-addons-backport,BT-astauder/odoo,abstract-open-solutions/OCB,hopeall/odoo,SerpentCS/odoo,ujjwalwahi/odoo,guerrerocarlos/odoo,sve-odoo/odoo,camptocamp/ngo-addons-backport,Antiun/odoo,joariasl/odoo,sergio-incaser/odoo,juanalfonsopr/odoo,NL66278/OCB,Noviat/odoo,waytai/odoo,lightcn/odoo,kittiu/odoo,wangjun/odoo,abenzbiria/clients_odoo,Nick-OpusVL/odoo,demon-ru/iml-crm,mszewczy/odoo,massot/odoo,osvalr/odoo,odoo-turkiye/odoo,JGarcia-Panach/odoo,dkubiak789/odoo,brijeshkesariya/odoo,bealdav/OpenUpgrade,hmen89/odoo,janocat/odoo,savoirfairelinux/OpenUpgrade,tangyiyong/odoo,mustafat/odoo-1,kittiu/odoo,fjbatresv/odoo,fuhongliang/odoo,oihane/odoo,odoo-turkiye/odoo,csrocha/OpenUpgrade,bguillot/OpenUpgrade,TRESCLOUD/odoopub,nagyistoce/odoo-dev-odoo,apocalypsebg/odoo,arthru/OpenUpgrade,abenzbiria/clients_odoo,nagyistoce/odoo-dev-odoo,tinkhaven-organization/odoo,jaxkodex/odoo,mszewczy/odoo,ojengwa/odoo,Ernesto99/odoo,Gitlab11/odoo,nhomar/odoo-mirror,patmcb/odoo,Nick-OpusVL/odoo,chiragjogi/odoo,kittiu/odoo,gorjuce/odoo,mmbtba/odoo,dariemp/odoo,podemos-info/odoo,takis/odoo,kifcaliph/odoo,datenbetrieb/odoo,OpenUpgrade-dev/OpenUpgrade,tarzan0820/odoo,BT-rmartin/odoo,Codefans-fan/odoo,podemos-info/odoo,Endika/OpenUpgrade,ramitalat/odoo,odooindia/odoo,eino-makitalo/odoo,juanalfonsopr/odoo,alexteodor/odoo,cedk/odoo,gdgellatly/OCB1,papouso/odoo,hbrunn/OpenUpgrade,joariasl/odoo,sebalix/OpenUpgrade,leorochael/odoo,n0m4dz/odoo,leoliujie/odoo,provaleks/o8,0k/odoo,alexteodor/odoo,OpenPymeMx/OCB,Elico-Corp/odoo_OCB,ccomb/OpenUpgrade,bealdav/OpenUpgrade,PongPi/isl-odoo,nuncjo/odoo,hassoon3/odoo,Gitlab11/odoo,rgeleta/odoo,Codefans-fan/odoo,optima-ict/odoo,hoatle/odoo,SerpentCS/odoo,rahuldhote/odoo,tvtsoft/odoo8,salaria/odoo,bealdav/OpenUpgrade,windedge/odoo,avoinsystems/odoo,cedk/odoo,tinkhaven-organization/odoo,abdellatifkarroum/odoo,microcom/odoo,provaleks/o8,funkring/fdoo,klunwebale/odoo,grap/OpenUpgrade,dalegregory/odoo,fuselock/odoo,virgree/odoo,blaggacao/OpenUpgrade,OpenUpgrade/OpenUpgrade,mkieszek/odoo,ecosoft-odoo/odoo,sadleader/odoo,sinbazhou/odoo,grap/OCB,camptocamp/ngo-addons-backport,waytai/odoo,juanalfonsopr/odoo,QianBIG/odoo,abdellatifkarroum/odoo,GauravSahu/odoo,bobisme/odoo,PongPi/isl-odoo,agrista/odoo-saas,JGarcia-Panach/odoo,bwrsandman/OpenUpgrade,fgesora/odoo,highco-groupe/odoo,credativUK/OCB,codekaki/odoo,bguillot/OpenUpgrade,draugiskisprendimai/odoo,simongoffin/website_version,Ichag/odoo,pedrobaeza/OpenUpgrade,ramitalat/odoo,hip-odoo/odoo,luiseduardohdbackup/odoo,ygol/odoo,Nick-OpusVL/odoo,incaser/odoo-odoo,janocat/odoo,klunwebale/odoo,feroda/odoo,shaufi10/odoo,eino-makitalo/odoo,camptocamp/ngo-addons-backport,tinkerthaler/odoo,jeasoft/odoo,Codefans-fan/odoo,Eric-Zhong/odoo,avoinsystems/odoo,apanju/GMIO_Odoo,cloud9UG/odoo,nagyistoce/odoo-dev-odoo,savoirfairelinux/OpenUpgrade,shaufi/odoo,pplatek/odoo,goliveirab/odoo,hubsaysnuaa/odoo,prospwro/odoo,erkrishna9/odoo,sebalix/OpenUpgrade,MarcosCommunity/odoo,BT-fgarbely/odoo,papouso/odoo,BT-fgarbely/odoo,ShineFan/odoo,shingonoide/odoo,odootr/odoo,datenbetrieb/odoo,jfpla/odoo,gvb/odoo,sergio-incaser/odoo,juanalfonsopr/odoo,Elico-Corp/odoo_OCB,florian-dacosta/OpenUpgrade,nuuuboo/odoo,gsmartway/odoo,savoirfairelinux/odoo,elmerdpadilla/iv,ingadhoc/odoo,hassoon3/odoo,janocat/odoo,ihsanudin/odoo,erkrishna9/odoo,massot/odoo,Maspear/odoo,bplancher/odoo,dezynetechnologies/odoo,tinkerthaler/odoo,Endika/odoo,savoirfairelinux/odoo,Gitlab11/odoo,kifcaliph/odoo,shingonoide/odoo,colinnewell/odoo,apanju/odoo,Ichag/odoo,fgesora/odoo,dsfsdgsbngfggb/odoo,waytai/odoo,srimai/odoo,naousse/odoo,Antiun/odoo,abstract-open-solutions/OCB,alhashash/odoo,fgesora/odoo,SAM-IT-SA/odoo,sinbazhou/odoo,incaser/odoo-odoo,OSSESAC/odoopubarquiluz,srsman/odoo,xujb/odoo,guewen/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,VielSoft/odoo,omprakasha/odoo,omprakasha/odoo,srimai/odoo,alqfahad/odoo,gdgellatly/OCB1,mszewczy/odoo,sysadminmatmoz/OCB,FlorianLudwig/odoo,odoo-turkiye/odoo,Kilhog/odoo,frouty/odoogoeen,datenbetrieb/odoo,leoliujie/odoo,GauravSahu/odoo,mmbtba/odoo,agrista/odoo-saas,cysnake4713/odoo,stephen144/odoo,bobisme/odoo,x111ong/odoo,poljeff/odoo,bobisme/odoo,factorlibre/OCB,vrenaville/ngo-addons-backport,colinnewell/odoo,AuyaJackie/odoo,xujb/odoo,rahuldhote/odoo,oihane/odoo,stephen144/odoo,salaria/odoo,BT-rmartin/odoo,JCA-Developpement/Odoo,Bachaco-ve/odoo,nitinitprof/odoo,florian-dacosta/OpenUpgrade,camptocamp/ngo-addons-backport,sve-odoo/odoo,addition-it-solutions/project-all,lombritz/odoo,ramadhane/odoo,jiangzhixiao/odoo,fuhongliang/odoo,fevxie/odoo,FlorianLudwig/odoo,alexteodor/odoo,tinkhaven-organization/odoo,hip-odoo/odoo,CopeX/odoo,hopeall/odoo,dsfsdgsbngfggb/odoo,frouty/odoo_oph,alexteodor/odoo,hassoon3/odoo,dsfsdgsbngfggb/odoo,JGarcia-Panach/odoo,oihane/odoo,juanalfonsopr/odoo,apocalypsebg/odoo,GauravSahu/odoo,BT-ojossen/odoo,xzYue/odoo,thanhacun/odoo,syci/OCB,alhashash/odoo,SAM-IT-SA/odoo,hubsaysnuaa/odoo,SAM-IT-SA/odoo,aviciimaxwell/odoo,idncom/odoo,addition-it-solutions/project-all,Gitlab11/odoo,oasiswork/odoo,christophlsa/odoo,ramadhane/odoo,frouty/odoo_oph,gorjuce/odoo,Nowheresly/odoo,bakhtout/odoo-educ,joshuajan/odoo,jolevq/odoopub,nuuuboo/odoo,SAM-IT-SA/odoo,nhomar/odoo-mirror,OpenUpgrade/OpenUpgrade,vrenaville/ngo-addons-backport,jaxkodex/odoo,javierTerry/odoo,draugiskisprendimai/odoo,goliveirab/odoo,tinkhaven-organization/odoo,omprakasha/odoo,BT-astauder/odoo,rowemoore/odoo,Bachaco-ve/odoo,acshan/odoo,salaria/odoo,dkubiak789/odoo,credativUK/OCB,colinnewell/odoo,gavin-feng/odoo,collex100/odoo,0k/OpenUpgrade,xujb/odoo,minhtuancn/odoo,hanicker/odoo,ubic135/odoo-design,BT-rmartin/odoo,dllsf/odootest,codekaki/odoo,QianBIG/odoo,bkirui/odoo,nhomar/odoo-mirror,inspyration/odoo,ihsanudin/odoo,KontorConsulting/odoo,fjbatresv/odoo,stephen144/odoo,abstract-open-solutions/OCB,n0m4dz/odoo,savoirfairelinux/OpenUpgrade,sinbazhou/odoo,grap/OpenUpgrade,BT-ojossen/odoo,shivam1111/odoo,fuhongliang/odoo,tarzan0820/odoo,credativUK/OCB,Maspear/odoo,funkring/fdoo,fjbatresv/odoo,Maspear/odoo,NeovaHealth/odoo,minhtuancn/odoo,apanju/odoo,shaufi10/odoo,dezynetechnologies/odoo,Endika/odoo,kybriainfotech/iSocioCRM,janocat/odoo,ChanduERP/odoo,elmerdpadilla/iv,hbrunn/OpenUpgrade,highco-groupe/odoo,numerigraphe/odoo,sve-odoo/odoo,poljeff/odoo,ApuliaSoftware/odoo,jfpla/odoo,abdellatifkarroum/odoo,srimai/odoo,dllsf/odootest,alqfahad/odoo,Drooids/odoo,alexcuellar/odoo,kybriainfotech/iSocioCRM,addition-it-solutions/project-all,hip-odoo/odoo,syci/OCB,sv-dev1/odoo,Noviat/odoo,ChanduERP/odoo,gavin-feng/odoo,VielSoft/odoo,odoousers2014/odoo,ujjwalwahi/odoo,n0m4dz/odoo,janocat/odoo,shingonoide/odoo,jiachenning/odoo,sysadminmatmoz/OCB,mszewczy/odoo,doomsterinc/odoo,hoatle/odoo,dsfsdgsbngfggb/odoo,JGarcia-Panach/odoo,matrixise/odoo,nitinitprof/odoo,havt/odoo,jpshort/odoo,cedk/odoo,nhomar/odoo,lgscofield/odoo,jpshort/odoo,joariasl/odoo,oihane/odoo,rowemoore/odoo,luistorresm/odoo,chiragjogi/odoo,virgree/odoo,rgeleta/odoo,factorlibre/OCB,ChanduERP/odoo,oasiswork/odoo,ingadhoc/odoo,Eric-Zhong/odoo,0k/OpenUpgrade,hopeall/odoo,bakhtout/odoo-educ,salaria/odoo,gorjuce/odoo,ujjwalwahi/odoo,odoo-turkiye/odoo,bplancher/odoo,ccomb/OpenUpgrade,patmcb/odoo,JGarcia-Panach/odoo,vnsofthe/odoo,spadae22/odoo,mvaled/OpenUpgrade,thanhacun/odoo,dsfsdgsbngfggb/odoo,naousse/odoo,Adel-Magebinary/odoo,PongPi/isl-odoo,MarcosCommunity/odoo,Danisan/odoo-1,cedk/odoo,numerigraphe/odoo,patmcb/odoo,steedos/odoo,x111ong/odoo,avoinsystems/odoo,provaleks/o8,Drooids/odoo,jiachenning/odoo,0k/odoo,pplatek/odoo,hifly/OpenUpgrade,cdrooom/odoo,AuyaJackie/odoo,hifly/OpenUpgrade,takis/odoo,Ichag/odoo,nexiles/odoo,rdeheele/odoo,arthru/OpenUpgrade,x111ong/odoo,nexiles/odoo,Daniel-CA/odoo,poljeff/odoo,kirca/OpenUpgrade,savoirfairelinux/odoo,jfpla/odoo,Adel-Magebinary/odoo,luiseduardohdbackup/odoo,jeasoft/odoo,Ernesto99/odoo,RafaelTorrealba/odoo,lgscofield/odoo,jesramirez/odoo,tvibliani/odoo,salaria/odoo,slevenhagen/odoo-npg,steedos/odoo,fevxie/odoo,srsman/odoo,florian-dacosta/OpenUpgrade,odoousers2014/odoo,BT-fgarbely/odoo,mmbtba/odoo,kirca/OpenUpgrade,nitinitprof/odoo,jpshort/odoo,mkieszek/odoo,ihsanudin/odoo,hanicker/odoo,ThinkOpen-Solutions/odoo,incaser/odoo-odoo,florentx/OpenUpgrade,poljeff/odoo,ovnicraft/odoo,janocat/odoo,Endika/OpenUpgrade,mmbtba/odoo,VielSoft/odoo,dalegregory/odoo,Codefans-fan/odoo,cedk/odoo,Gitlab11/odoo,feroda/odoo,Eric-Zhong/odoo,Danisan/odoo-1,CubicERP/odoo,datenbetrieb/odoo,BT-astauder/odoo,pplatek/odoo,tangyiyong/odoo,storm-computers/odoo,numerigraphe/odoo,csrocha/OpenUpgrade,stephen144/odoo,pedrobaeza/odoo,stonegithubs/odoo,brijeshkesariya/odoo,feroda/odoo,Bachaco-ve/odoo,osvalr/odoo,hassoon3/odoo,shingonoide/odoo,grap/OCB,lightcn/odoo,grap/OCB,chiragjogi/odoo,dalegregory/odoo,GauravSahu/odoo,camptocamp/ngo-addons-backport,addition-it-solutions/project-all,bobisme/odoo,leorochael/odoo,fuhongliang/odoo,odootr/odoo,windedge/odoo,hanicker/odoo,frouty/odoogoeen,abenzbiria/clients_odoo,abstract-open-solutions/OCB,dgzurita/odoo,storm-computers/odoo,bplancher/odoo,ojengwa/odoo,wangjun/odoo,RafaelTorrealba/odoo,spadae22/odoo,hubsaysnuaa/odoo,demon-ru/iml-crm,xzYue/odoo,kifcaliph/odoo,stonegithubs/odoo,ygol/odoo,avoinsystems/odoo,xzYue/odoo,ojengwa/odoo,lightcn/odoo,oasiswork/odoo,alqfahad/odoo,grap/OpenUpgrade,dsfsdgsbngfggb/odoo,ClearCorp-dev/odoo,ovnicraft/odoo,andreparames/odoo,csrocha/OpenUpgrade,kifcaliph/odoo,andreparames/odoo,javierTerry/odoo,Endika/OpenUpgrade,RafaelTorrealba/odoo,ApuliaSoftware/odoo,luistorresm/odoo,hubsaysnuaa/odoo,alqfahad/odoo,odooindia/odoo,Daniel-CA/odoo,ApuliaSoftware/odoo,PongPi/isl-odoo,nuncjo/odoo,syci/OCB,jfpla/odoo,alexteodor/odoo,kifcaliph/odoo,tvibliani/odoo,numerigraphe/odoo,klunwebale/odoo,hanicker/odoo,rschnapka/odoo,fuhongliang/odoo,doomsterinc/odoo,fevxie/odoo,tvibliani/odoo,eino-makitalo/odoo,hopeall/odoo,jusdng/odoo,damdam-s/OpenUpgrade,deKupini/erp,0k/OpenUpgrade,MarcosCommunity/odoo,ramitalat/odoo,blaggacao/OpenUpgrade,abdellatifkarroum/odoo,idncom/odoo,slevenhagen/odoo-npg,xujb/odoo,gorjuce/odoo,takis/odoo,havt/odoo,fgesora/odoo,nexiles/odoo,zchking/odoo,stonegithubs/odoo,addition-it-solutions/project-all,realsaiko/odoo,Adel-Magebinary/odoo,microcom/odoo,hbrunn/OpenUpgrade,jusdng/odoo,CubicERP/odoo,csrocha/OpenUpgrade,goliveirab/odoo,kirca/OpenUpgrade,chiragjogi/odoo,Eric-Zhong/odoo,guewen/OpenUpgrade,jiangzhixiao/odoo,wangjun/odoo,omprakasha/odoo,diagramsoftware/odoo,sv-dev1/odoo,ubic135/odoo-design,massot/odoo,hifly/OpenUpgrade,bguillot/OpenUpgrade,slevenhagen/odoo-npg,dgzurita/odoo,glovebx/odoo,brijeshkesariya/odoo,syci/OCB,abdellatifkarroum/odoo,takis/odoo,hmen89/odoo,JonathanStein/odoo,fossoult/odoo,nuuuboo/odoo,datenbetrieb/odoo,havt/odoo,dfang/odoo,virgree/odoo,simongoffin/website_version,ehirt/odoo,mvaled/OpenUpgrade,alqfahad/odoo,Antiun/odoo,BT-fgarbely/odoo,BT-fgarbely/odoo,ShineFan/odoo,oliverhr/odoo,fjbatresv/odoo,ccomb/OpenUpgrade,rowemoore/odoo,rdeheele/odoo,fuselock/odoo,sv-dev1/odoo,Maspear/odoo,tinkhaven-organization/odoo,agrista/odoo-saas,Endika/OpenUpgrade,damdam-s/OpenUpgrade,Endika/odoo,luistorresm/odoo,glovebx/odoo,nuncjo/odoo,doomsterinc/odoo,Bachaco-ve/odoo,0k/OpenUpgrade,shaufi10/odoo,codekaki/odoo,numerigraphe/odoo,sebalix/OpenUpgrade,mlaitinen/odoo,gdgellatly/OCB1,odootr/odoo,tinkerthaler/odoo,salaria/odoo,ramitalat/odoo,mmbtba/odoo,apanju/GMIO_Odoo,eino-makitalo/odoo,dgzurita/odoo,nuncjo/odoo,jpshort/odoo,gvb/odoo,podemos-info/odoo,lombritz/odoo,VitalPet/odoo,guerrerocarlos/odoo,fdvarela/odoo8,sinbazhou/odoo,lombritz/odoo,hanicker/odoo,ingadhoc/odoo,NeovaHealth/odoo,TRESCLOUD/odoopub,mvaled/OpenUpgrade,damdam-s/OpenUpgrade,OpusVL/odoo,ingadhoc/odoo,spadae22/odoo,ecosoft-odoo/odoo,fgesora/odoo,ChanduERP/odoo,CubicERP/odoo,x111ong/odoo,0k/odoo,podemos-info/odoo,kittiu/odoo,deKupini/erp,rahuldhote/odoo,ramitalat/odoo,prospwro/odoo,stonegithubs/odoo,zchking/odoo,incaser/odoo-odoo,alexcuellar/odoo,omprakasha/odoo,cloud9UG/odoo,SAM-IT-SA/odoo,mlaitinen/odoo,vrenaville/ngo-addons-backport,rowemoore/odoo,Kilhog/odoo,cysnake4713/odoo,joshuajan/odoo,CubicERP/odoo,windedge/odoo,hmen89/odoo,collex100/odoo,0k/odoo,n0m4dz/odoo,slevenhagen/odoo,jeasoft/odoo,leorochael/odoo,AuyaJackie/odoo,pedrobaeza/odoo,inspyration/odoo,nuncjo/odoo,PongPi/isl-odoo,kirca/OpenUpgrade,Nowheresly/odoo,fdvarela/odoo8,ehirt/odoo,chiragjogi/odoo,VielSoft/odoo,syci/OCB,sve-odoo/odoo,ecosoft-odoo/odoo,Eric-Zhong/odoo,Daniel-CA/odoo,minhtuancn/odoo,tvibliani/odoo,erkrishna9/odoo,aviciimaxwell/odoo,ujjwalwahi/odoo,charbeljc/OCB,shaufi/odoo,fossoult/odoo,gvb/odoo,vrenaville/ngo-addons-backport,acshan/odoo,FlorianLudwig/odoo,bguillot/OpenUpgrade,takis/odoo,ehirt/odoo,slevenhagen/odoo,guerrerocarlos/odoo,bkirui/odoo,addition-it-solutions/project-all,klunwebale/odoo,OpenPymeMx/OCB,rgeleta/odoo,Drooids/odoo,SerpentCS/odoo,jfpla/odoo,massot/odoo,CubicERP/odoo,BT-rmartin/odoo,alexcuellar/odoo,colinnewell/odoo,fossoult/odoo,minhtuancn/odoo,FlorianLudwig/odoo,ClearCorp-dev/odoo,christophlsa/odoo,lsinfo/odoo,zchking/odoo,apocalypsebg/odoo,jaxkodex/odoo,Daniel-CA/odoo,kirca/OpenUpgrade,aviciimaxwell/odoo,0k/OpenUpgrade,waytai/odoo,cdrooom/odoo,dariemp/odoo,Codefans-fan/odoo,frouty/odoo_oph,codekaki/odoo,optima-ict/odoo,prospwro/odoo,prospwro/odoo,doomsterinc/odoo,Kilhog/odoo,OpenUpgrade/OpenUpgrade,BT-fgarbely/odoo,tinkerthaler/odoo,feroda/odoo,Endika/OpenUpgrade,fuselock/odoo,bealdav/OpenUpgrade,Nowheresly/odoo,Ernesto99/odoo,mkieszek/odoo,CubicERP/odoo,pplatek/odoo,nagyistoce/odoo-dev-odoo,deKupini/erp,apanju/odoo,BT-ojossen/odoo,florentx/OpenUpgrade,tvibliani/odoo,funkring/fdoo,guewen/OpenUpgrade,highco-groupe/odoo,Nick-OpusVL/odoo,apanju/GMIO_Odoo,elmerdpadilla/iv,highco-groupe/odoo,synconics/odoo,apanju/odoo,papouso/odoo,diagramsoftware/odoo,cysnake4713/odoo,CatsAndDogsbvba/odoo,realsaiko/odoo,NeovaHealth/odoo,NeovaHealth/odoo,leoliujie/odoo,diagramsoftware/odoo,bguillot/OpenUpgrade,ramadhane/odoo,thanhacun/odoo,Ichag/odoo,Ichag/odoo,abdellatifkarroum/odoo,guerrerocarlos/odoo,agrista/odoo-saas,xujb/odoo,damdam-s/OpenUpgrade,sergio-incaser/odoo,Endika/OpenUpgrade,joshuajan/odoo,hbrunn/OpenUpgrade,VielSoft/odoo,bkirui/odoo,deKupini/erp,ubic135/odoo-design,erkrishna9/odoo,demon-ru/iml-crm,Nick-OpusVL/odoo,nhomar/odoo,lsinfo/odoo,srsman/odoo,rowemoore/odoo,collex100/odoo,ujjwalwahi/odoo,kittiu/odoo,nitinitprof/odoo,slevenhagen/odoo-npg,zchking/odoo,virgree/odoo,ihsanudin/odoo,elmerdpadilla/iv,ingadhoc/odoo,shaufi10/odoo,spadae22/odoo,klunwebale/odoo,OSSESAC/odoopubarquiluz,virgree/odoo,NL66278/OCB,oihane/odoo,0k/odoo,VitalPet/odoo,oliverhr/odoo,zchking/odoo,hip-odoo/odoo,sv-dev1/odoo,glovebx/odoo,mlaitinen/odoo,jolevq/odoopub,hubsaysnuaa/odoo,hbrunn/OpenUpgrade,Antiun/odoo,Ernesto99/odoo,AuyaJackie/odoo,javierTerry/odoo,joshuajan/odoo,grap/OpenUpgrade,odoousers2014/odoo,OSSESAC/odoopubarquiluz,credativUK/OCB,shivam1111/odoo,dllsf/odootest,goliveirab/odoo,gavin-feng/odoo,CopeX/odoo,AuyaJackie/odoo,luistorresm/odoo,glovebx/odoo,ubic135/odoo-design,Bachaco-ve/odoo,laslabs/odoo,CatsAndDogsbvba/odoo,rschnapka/odoo,ygol/odoo,collex100/odoo,lombritz/odoo,ThinkOpen-Solutions/odoo,QianBIG/odoo,storm-computers/odoo,0k/OpenUpgrade,sv-dev1/odoo,shingonoide/odoo,markeTIC/OCB,spadae22/odoo,KontorConsulting/odoo,sadleader/odoo,gsmartway/odoo,osvalr/odoo,BT-astauder/odoo,xzYue/odoo,Nowheresly/odoo,virgree/odoo,arthru/OpenUpgrade,Maspear/odoo,erkrishna9/odoo,mszewczy/odoo,makinacorpus/odoo,wangjun/odoo,jiangzhixiao/odoo,codekaki/odoo,cloud9UG/odoo,sysadminmatmoz/OCB,rubencabrera/odoo,Maspear/odoo,optima-ict/odoo,bkirui/odoo,doomsterinc/odoo,vnsofthe/odoo,dllsf/odootest,laslabs/odoo,grap/OpenUpgrade,Ichag/odoo,mustafat/odoo-1,damdam-s/OpenUpgrade,credativUK/OCB,BT-ojossen/odoo,xujb/odoo,alexcuellar/odoo,charbeljc/OCB,rgeleta/odoo,rubencabrera/odoo,nexiles/odoo,havt/odoo,CatsAndDogsbvba/odoo,makinacorpus/odoo,KontorConsulting/odoo,CatsAndDogsbvba/odoo,ShineFan/odoo,OpusVL/odoo,windedge/odoo,bobisme/odoo,dariemp/odoo,Noviat/odoo,jfpla/odoo,jfpla/odoo,jpshort/odoo,jolevq/odoopub,andreparames/odoo,odooindia/odoo,hoatle/odoo,pplatek/odoo,jiachenning/odoo,podemos-info/odoo,luistorresm/odoo,brijeshkesariya/odoo | {
"name" : "Human Resources",
"version" : "1.0",
"author" : "Tiny",
"category" : "Generic Modules/Human Resources",
"website" : "http://tinyerp.com/module_hr.html",
"description": """
Module for human resource management. You can manage:
* Employees and hierarchies
* Work hours sheets
* Attendances and sign in/out system
* Holidays
Different reports are also provided, mainly for attendance statistics.
""",
"depends" : ["base"],
"init_xml" : [],
"demo_xml" : [
"hr_demo.xml",
"hr_bel_holidays_2005.xml",
"hr_department_demo.xml"
],
"update_xml" : [
"hr_view.xml",
"hr_report.xml",
"hr_wizard.xml",
- "hr_department_view.xml"
+ "hr_department_view.xml",
+ "hr_security.xml"
],
"active": False,
"installable": True
}
| Add hr_security.xml file entry in update_xml section | ## Code Before:
{
"name" : "Human Resources",
"version" : "1.0",
"author" : "Tiny",
"category" : "Generic Modules/Human Resources",
"website" : "http://tinyerp.com/module_hr.html",
"description": """
Module for human resource management. You can manage:
* Employees and hierarchies
* Work hours sheets
* Attendances and sign in/out system
* Holidays
Different reports are also provided, mainly for attendance statistics.
""",
"depends" : ["base"],
"init_xml" : [],
"demo_xml" : [
"hr_demo.xml",
"hr_bel_holidays_2005.xml",
"hr_department_demo.xml"
],
"update_xml" : [
"hr_view.xml",
"hr_report.xml",
"hr_wizard.xml",
"hr_department_view.xml"
],
"active": False,
"installable": True
}
## Instruction:
Add hr_security.xml file entry in update_xml section
## Code After:
{
"name" : "Human Resources",
"version" : "1.0",
"author" : "Tiny",
"category" : "Generic Modules/Human Resources",
"website" : "http://tinyerp.com/module_hr.html",
"description": """
Module for human resource management. You can manage:
* Employees and hierarchies
* Work hours sheets
* Attendances and sign in/out system
* Holidays
Different reports are also provided, mainly for attendance statistics.
""",
"depends" : ["base"],
"init_xml" : [],
"demo_xml" : [
"hr_demo.xml",
"hr_bel_holidays_2005.xml",
"hr_department_demo.xml"
],
"update_xml" : [
"hr_view.xml",
"hr_report.xml",
"hr_wizard.xml",
"hr_department_view.xml",
"hr_security.xml"
],
"active": False,
"installable": True
}
|
164a80ce3bcffad0e233426830c712cddd2f750b | thefederation/apps.py | thefederation/apps.py | import datetime
import sys
import django_rq
from django.apps import AppConfig
class TheFederationConfig(AppConfig):
name = "thefederation"
verbose_name = "The Federation"
def ready(self):
# Only register tasks if RQ Scheduler process
if "rqscheduler" not in sys.argv:
return
from thefederation.social import make_daily_post
from thefederation.tasks import aggregate_daily_stats
from thefederation.tasks import clean_duplicate_nodes
from thefederation.tasks import poll_nodes
scheduler = django_rq.get_scheduler()
# Delete any existing jobs in the scheduler when the app starts up
for job in scheduler.get_jobs():
job.delete()
scheduler.schedule(
scheduled_time=datetime.datetime.utcnow(),
func=aggregate_daily_stats,
interval=5500,
queue_name='high',
)
scheduler.cron(
'0 10 * * *',
func=make_daily_post,
queue_name='high',
)
scheduler.cron(
'18 4 * * *',
func=clean_duplicate_nodes,
queue_name='medium',
)
scheduler.schedule(
scheduled_time=datetime.datetime.utcnow(),
func=poll_nodes,
interval=10800,
queue_name='medium',
)
| import datetime
import sys
import django_rq
from django.apps import AppConfig
class TheFederationConfig(AppConfig):
name = "thefederation"
verbose_name = "The Federation"
def ready(self):
# Only register tasks if RQ Scheduler process
if "rqscheduler" not in sys.argv:
return
from thefederation.social import make_daily_post
from thefederation.tasks import aggregate_daily_stats
from thefederation.tasks import clean_duplicate_nodes
from thefederation.tasks import poll_nodes
scheduler = django_rq.get_scheduler()
# Delete any existing jobs in the scheduler when the app starts up
for job in scheduler.get_jobs():
job.delete()
scheduler.schedule(
scheduled_time=datetime.datetime.utcnow(),
func=aggregate_daily_stats,
interval=5500,
queue_name='high',
)
scheduler.cron(
'0 10 * * *',
func=make_daily_post,
queue_name='high',
)
scheduler.cron(
'18 4 * * *',
func=clean_duplicate_nodes,
queue_name='medium',
timeout=3600,
)
scheduler.schedule(
scheduled_time=datetime.datetime.utcnow(),
func=poll_nodes,
interval=10800,
queue_name='medium',
)
| Increase timeout of clean_duplicate_nodes job | Increase timeout of clean_duplicate_nodes job
| Python | agpl-3.0 | jaywink/diaspora-hub,jaywink/diaspora-hub,jaywink/the-federation.info,jaywink/diaspora-hub,jaywink/the-federation.info,jaywink/the-federation.info | import datetime
import sys
import django_rq
from django.apps import AppConfig
class TheFederationConfig(AppConfig):
name = "thefederation"
verbose_name = "The Federation"
def ready(self):
# Only register tasks if RQ Scheduler process
if "rqscheduler" not in sys.argv:
return
from thefederation.social import make_daily_post
from thefederation.tasks import aggregate_daily_stats
from thefederation.tasks import clean_duplicate_nodes
from thefederation.tasks import poll_nodes
scheduler = django_rq.get_scheduler()
# Delete any existing jobs in the scheduler when the app starts up
for job in scheduler.get_jobs():
job.delete()
scheduler.schedule(
scheduled_time=datetime.datetime.utcnow(),
func=aggregate_daily_stats,
interval=5500,
queue_name='high',
)
scheduler.cron(
'0 10 * * *',
func=make_daily_post,
queue_name='high',
)
scheduler.cron(
'18 4 * * *',
func=clean_duplicate_nodes,
queue_name='medium',
+ timeout=3600,
)
scheduler.schedule(
scheduled_time=datetime.datetime.utcnow(),
func=poll_nodes,
interval=10800,
queue_name='medium',
)
| Increase timeout of clean_duplicate_nodes job | ## Code Before:
import datetime
import sys
import django_rq
from django.apps import AppConfig
class TheFederationConfig(AppConfig):
name = "thefederation"
verbose_name = "The Federation"
def ready(self):
# Only register tasks if RQ Scheduler process
if "rqscheduler" not in sys.argv:
return
from thefederation.social import make_daily_post
from thefederation.tasks import aggregate_daily_stats
from thefederation.tasks import clean_duplicate_nodes
from thefederation.tasks import poll_nodes
scheduler = django_rq.get_scheduler()
# Delete any existing jobs in the scheduler when the app starts up
for job in scheduler.get_jobs():
job.delete()
scheduler.schedule(
scheduled_time=datetime.datetime.utcnow(),
func=aggregate_daily_stats,
interval=5500,
queue_name='high',
)
scheduler.cron(
'0 10 * * *',
func=make_daily_post,
queue_name='high',
)
scheduler.cron(
'18 4 * * *',
func=clean_duplicate_nodes,
queue_name='medium',
)
scheduler.schedule(
scheduled_time=datetime.datetime.utcnow(),
func=poll_nodes,
interval=10800,
queue_name='medium',
)
## Instruction:
Increase timeout of clean_duplicate_nodes job
## Code After:
import datetime
import sys
import django_rq
from django.apps import AppConfig
class TheFederationConfig(AppConfig):
name = "thefederation"
verbose_name = "The Federation"
def ready(self):
# Only register tasks if RQ Scheduler process
if "rqscheduler" not in sys.argv:
return
from thefederation.social import make_daily_post
from thefederation.tasks import aggregate_daily_stats
from thefederation.tasks import clean_duplicate_nodes
from thefederation.tasks import poll_nodes
scheduler = django_rq.get_scheduler()
# Delete any existing jobs in the scheduler when the app starts up
for job in scheduler.get_jobs():
job.delete()
scheduler.schedule(
scheduled_time=datetime.datetime.utcnow(),
func=aggregate_daily_stats,
interval=5500,
queue_name='high',
)
scheduler.cron(
'0 10 * * *',
func=make_daily_post,
queue_name='high',
)
scheduler.cron(
'18 4 * * *',
func=clean_duplicate_nodes,
queue_name='medium',
timeout=3600,
)
scheduler.schedule(
scheduled_time=datetime.datetime.utcnow(),
func=poll_nodes,
interval=10800,
queue_name='medium',
)
|
0cdfabf24c01920617535205dfcdba7a187b4d32 | doc/_ext/saltdocs.py | doc/_ext/saltdocs.py | def setup(app):
"""Additions and customizations to Sphinx that are useful for documenting
the Salt project.
"""
app.add_crossref_type(directivename="conf_master", rolename="conf_master",
indextemplate="pair: %s; conf/master")
app.add_crossref_type(directivename="conf_minion", rolename="conf_minion",
indextemplate="pair: %s; conf/minion")
| def setup(app):
"""Additions and customizations to Sphinx that are useful for documenting
the Salt project.
"""
app.add_crossref_type(directivename="conf_master", rolename="conf_master",
indextemplate="pair: %s; conf/master")
app.add_crossref_type(directivename="conf_minion", rolename="conf_minion",
indextemplate="pair: %s; conf/minion")
app.add_crossref_type(directivename="conf-log", rolename="conf-log",
indextemplate="pair: %s; conf/logging")
| Allow the `conf-log` role to link to the logging documentation. | Allow the `conf-log` role to link to the logging documentation.
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | def setup(app):
"""Additions and customizations to Sphinx that are useful for documenting
the Salt project.
"""
app.add_crossref_type(directivename="conf_master", rolename="conf_master",
indextemplate="pair: %s; conf/master")
app.add_crossref_type(directivename="conf_minion", rolename="conf_minion",
indextemplate="pair: %s; conf/minion")
+ app.add_crossref_type(directivename="conf-log", rolename="conf-log",
+ indextemplate="pair: %s; conf/logging")
| Allow the `conf-log` role to link to the logging documentation. | ## Code Before:
def setup(app):
"""Additions and customizations to Sphinx that are useful for documenting
the Salt project.
"""
app.add_crossref_type(directivename="conf_master", rolename="conf_master",
indextemplate="pair: %s; conf/master")
app.add_crossref_type(directivename="conf_minion", rolename="conf_minion",
indextemplate="pair: %s; conf/minion")
## Instruction:
Allow the `conf-log` role to link to the logging documentation.
## Code After:
def setup(app):
"""Additions and customizations to Sphinx that are useful for documenting
the Salt project.
"""
app.add_crossref_type(directivename="conf_master", rolename="conf_master",
indextemplate="pair: %s; conf/master")
app.add_crossref_type(directivename="conf_minion", rolename="conf_minion",
indextemplate="pair: %s; conf/minion")
app.add_crossref_type(directivename="conf-log", rolename="conf-log",
indextemplate="pair: %s; conf/logging")
|
db2d0b2f7277f21ce2f500dc0cc4837258fdd200 | traceview/__init__.py | traceview/__init__.py |
__title__ = 'traceview'
__version__ = '0.1.0'
__author__ = 'Daniel Riti'
__license__ = 'MIT'
from .request import Request
import resources
class TraceView(object):
""" Provides access to TraceView API resources.
:param api_key: The TraceView API access key.
"""
def __init__(self, api_key):
self.api_key = api_key
self.organization = resources.Organization(self.api_key)
self.apps = resources.App(self.api_key)
|
__title__ = 'traceview'
__version__ = '0.1.0'
__author__ = 'Daniel Riti'
__license__ = 'MIT'
from .request import Request
import resources
class TraceView(object):
""" Provides access to TraceView API resources.
:param api_key: The TraceView API access key.
"""
def __init__(self, api_key):
self.api_key = api_key
self.organization = resources.Organization(self.api_key)
self.apps = resources.App(self.api_key)
self.layers = resources.Layer(self.api_key)
| Add layers object attribute to TraceView. | Add layers object attribute to TraceView.
| Python | mit | danriti/python-traceview |
__title__ = 'traceview'
__version__ = '0.1.0'
__author__ = 'Daniel Riti'
__license__ = 'MIT'
from .request import Request
import resources
class TraceView(object):
""" Provides access to TraceView API resources.
:param api_key: The TraceView API access key.
"""
def __init__(self, api_key):
self.api_key = api_key
self.organization = resources.Organization(self.api_key)
self.apps = resources.App(self.api_key)
+ self.layers = resources.Layer(self.api_key)
| Add layers object attribute to TraceView. | ## Code Before:
__title__ = 'traceview'
__version__ = '0.1.0'
__author__ = 'Daniel Riti'
__license__ = 'MIT'
from .request import Request
import resources
class TraceView(object):
""" Provides access to TraceView API resources.
:param api_key: The TraceView API access key.
"""
def __init__(self, api_key):
self.api_key = api_key
self.organization = resources.Organization(self.api_key)
self.apps = resources.App(self.api_key)
## Instruction:
Add layers object attribute to TraceView.
## Code After:
__title__ = 'traceview'
__version__ = '0.1.0'
__author__ = 'Daniel Riti'
__license__ = 'MIT'
from .request import Request
import resources
class TraceView(object):
""" Provides access to TraceView API resources.
:param api_key: The TraceView API access key.
"""
def __init__(self, api_key):
self.api_key = api_key
self.organization = resources.Organization(self.api_key)
self.apps = resources.App(self.api_key)
self.layers = resources.Layer(self.api_key)
|
7f62587e099b9ef59731b6387030431b09f663f9 | bot_chucky/helpers.py | bot_chucky/helpers.py | """ Helper classes """
import facebook
import requests as r
class FacebookData:
def __init__(self, token):
"""
:param token: Facebook Page token
:param _api: Instance of the GraphAPI object
"""
self.token = token
self._api = facebook.GraphAPI(self.token)
def get_user_name(self, _id):
"""
:param _id: find user object by _id
:return: first name of user, type -> str
"""
if not isinstance(_id, str):
raise ValueError('id must be a str')
user = self._api.get_object(_id)
return user['first_name'] if user else None
class WeatherData:
"""
Class which collect weather data
"""
def __init__(self, api_token):
"""
:param api_token: Open Weather TOKEN
"""
self.token = api_token
def get_current_weather(self, city_name):
"""
:param city_name: Open weather API, find by city name
:return dictionary object with information
for example:
{'weather': [{'id': 800, 'main': 'Clear', 'description': 'clear sky'}]}
"""
api_url = f'http://api.openweathermap.org' \
f'/data/2.5/weather?q={city_name}&APPID={self.token}'
info = r.get(api_url).json()
return info
| """ Helper classes """
import facebook
import requests as r
class FacebookData:
def __init__(self, token):
"""
:param token: Facebook Page token
:param _api: Instance of the GraphAPI object
"""
self.token = token
self._api = facebook.GraphAPI(self.token)
def get_user_name(self, _id):
"""
:param _id: find user object by _id
:return: first name of user, type -> str
"""
if not isinstance(_id, str):
raise ValueError('id must be a str')
user = self._api.get_object(_id)
return user['first_name'] if user else None
class WeatherData:
"""
Class which collect weather data
"""
def __init__(self, api_token):
"""
:param api_token: Open Weather TOKEN
"""
self.token = api_token
def get_current_weather(self, city_name):
"""
:param city_name: Open weather API, find by city name
:return dictionary object with information
for example:
{'weather': [{'id': 800, 'main': 'Clear', 'description': 'clear sky'}]}
"""
api_url = f'http://api.openweathermap.org' \
f'/data/2.5/weather?q={city_name}&APPID={self.token}'
info = r.get(api_url).json()
return info
class StackOverFlowData:
params = {}
def get_answer_by_title(self, title):
pass
| Add StackOverFlowData, not completed yet | Add StackOverFlowData, not completed yet
| Python | mit | MichaelYusko/Bot-Chucky | """ Helper classes """
import facebook
import requests as r
class FacebookData:
def __init__(self, token):
"""
:param token: Facebook Page token
:param _api: Instance of the GraphAPI object
"""
self.token = token
self._api = facebook.GraphAPI(self.token)
def get_user_name(self, _id):
"""
:param _id: find user object by _id
:return: first name of user, type -> str
"""
if not isinstance(_id, str):
raise ValueError('id must be a str')
user = self._api.get_object(_id)
return user['first_name'] if user else None
class WeatherData:
"""
Class which collect weather data
"""
def __init__(self, api_token):
"""
:param api_token: Open Weather TOKEN
"""
self.token = api_token
def get_current_weather(self, city_name):
"""
:param city_name: Open weather API, find by city name
:return dictionary object with information
for example:
{'weather': [{'id': 800, 'main': 'Clear', 'description': 'clear sky'}]}
"""
api_url = f'http://api.openweathermap.org' \
f'/data/2.5/weather?q={city_name}&APPID={self.token}'
info = r.get(api_url).json()
return info
+
+ class StackOverFlowData:
+ params = {}
+
+ def get_answer_by_title(self, title):
+ pass
+ | Add StackOverFlowData, not completed yet | ## Code Before:
""" Helper classes """
import facebook
import requests as r
class FacebookData:
def __init__(self, token):
"""
:param token: Facebook Page token
:param _api: Instance of the GraphAPI object
"""
self.token = token
self._api = facebook.GraphAPI(self.token)
def get_user_name(self, _id):
"""
:param _id: find user object by _id
:return: first name of user, type -> str
"""
if not isinstance(_id, str):
raise ValueError('id must be a str')
user = self._api.get_object(_id)
return user['first_name'] if user else None
class WeatherData:
"""
Class which collect weather data
"""
def __init__(self, api_token):
"""
:param api_token: Open Weather TOKEN
"""
self.token = api_token
def get_current_weather(self, city_name):
"""
:param city_name: Open weather API, find by city name
:return dictionary object with information
for example:
{'weather': [{'id': 800, 'main': 'Clear', 'description': 'clear sky'}]}
"""
api_url = f'http://api.openweathermap.org' \
f'/data/2.5/weather?q={city_name}&APPID={self.token}'
info = r.get(api_url).json()
return info
## Instruction:
Add StackOverFlowData, not completed yet
## Code After:
""" Helper classes """
import facebook
import requests as r
class FacebookData:
def __init__(self, token):
"""
:param token: Facebook Page token
:param _api: Instance of the GraphAPI object
"""
self.token = token
self._api = facebook.GraphAPI(self.token)
def get_user_name(self, _id):
"""
:param _id: find user object by _id
:return: first name of user, type -> str
"""
if not isinstance(_id, str):
raise ValueError('id must be a str')
user = self._api.get_object(_id)
return user['first_name'] if user else None
class WeatherData:
"""
Class which collect weather data
"""
def __init__(self, api_token):
"""
:param api_token: Open Weather TOKEN
"""
self.token = api_token
def get_current_weather(self, city_name):
"""
:param city_name: Open weather API, find by city name
:return dictionary object with information
for example:
{'weather': [{'id': 800, 'main': 'Clear', 'description': 'clear sky'}]}
"""
api_url = f'http://api.openweathermap.org' \
f'/data/2.5/weather?q={city_name}&APPID={self.token}'
info = r.get(api_url).json()
return info
class StackOverFlowData:
params = {}
def get_answer_by_title(self, title):
pass
|
a45942894ace282883da3afa10f6739d30943764 | dewbrick/majesticapi.py | dewbrick/majesticapi.py | import argparse
import json
import os
import requests
BASE_URL = "https://api.majestic.com/api/json"
BASE_PARAMS = {'app_api_key': os.environ.get('THEAPIKEY')}
def get(cmd, params):
querydict = {'cmd': cmd}
querydict.update(BASE_PARAMS)
querydict.update(params)
response = requests.get(BASE_URL, params=querydict)
return json.loads(response.text)
def getIndexItemInfo(site):
cmd = 'GetIndexItemInfo'
params = {'items': '2',
'item0': site,
'item1': 'chrishannam.co.uk',
'datasource': 'fresh'}
responsedata = get(cmd, params)
if responsedata['Code'] == 'OK':
data = responsedata['DataTables']['Results']['Data'][0]
for data in responsedata['DataTables']['Results']['Data']:
yield {
'speed': data['OutDomainsExternal'] + 1,
'power': data['OutLinksExternal'] + 1,
'agility': data['OutLinksInternal'] + 1,
'strength': data['RefDomainsEDU'] + 1,
'smell': data['CitationFlow'] + 1,
}
else:
yield {}
def run():
parser = argparse.ArgumentParser(description="a test thing")
parser.add_argument('url')
args = parser.parse_args()
results = getIndexItemInfo(args.url)
for result in results:
print(result)
if __name__ == '__main__':
run()
| import argparse
import json
import os
import requests
BASE_URL = "https://api.majestic.com/api/json"
BASE_PARAMS = {'app_api_key': os.environ.get('THEAPIKEY')}
def get(cmd, params):
querydict = {'cmd': cmd}
querydict.update(BASE_PARAMS)
querydict.update(params)
response = requests.get(BASE_URL, params=querydict)
return json.loads(response.text)
def getIndexItemInfo(sitelist):
cmd = 'GetIndexItemInfo'
params = {'items': len(sitelist),
'datasource': 'fresh'}
items = {'item{0}'.format(i): site for i, site in enumerate(sitelist)}
params.update(items)
responsedata = get(cmd, params)
if responsedata['Code'] == 'OK':
for data in responsedata['DataTables']['Results']['Data']:
yield {
'speed': data['OutDomainsExternal'] + 1,
'power': data['OutLinksExternal'] + 1,
'agility': data['OutLinksInternal'] + 1,
'strength': data['RefDomainsEDU'] + 1,
'smell': data['CitationFlow'] + 1,
}
else:
yield {}
def run():
parser = argparse.ArgumentParser(description="a test thing")
parser.add_argument('urls', nargs='+')
args = parser.parse_args()
results = getIndexItemInfo(args.urls)
for result in results:
print(result)
if __name__ == '__main__':
run()
| Handle multiple sites in single request. | Handle multiple sites in single request.
| Python | apache-2.0 | ohmygourd/dewbrick,ohmygourd/dewbrick,ohmygourd/dewbrick | import argparse
import json
import os
import requests
BASE_URL = "https://api.majestic.com/api/json"
BASE_PARAMS = {'app_api_key': os.environ.get('THEAPIKEY')}
def get(cmd, params):
querydict = {'cmd': cmd}
querydict.update(BASE_PARAMS)
querydict.update(params)
response = requests.get(BASE_URL, params=querydict)
return json.loads(response.text)
- def getIndexItemInfo(site):
+ def getIndexItemInfo(sitelist):
+
cmd = 'GetIndexItemInfo'
- params = {'items': '2',
+ params = {'items': len(sitelist),
- 'item0': site,
- 'item1': 'chrishannam.co.uk',
'datasource': 'fresh'}
+ items = {'item{0}'.format(i): site for i, site in enumerate(sitelist)}
+ params.update(items)
+
responsedata = get(cmd, params)
if responsedata['Code'] == 'OK':
- data = responsedata['DataTables']['Results']['Data'][0]
for data in responsedata['DataTables']['Results']['Data']:
yield {
'speed': data['OutDomainsExternal'] + 1,
'power': data['OutLinksExternal'] + 1,
'agility': data['OutLinksInternal'] + 1,
'strength': data['RefDomainsEDU'] + 1,
'smell': data['CitationFlow'] + 1,
}
else:
yield {}
def run():
parser = argparse.ArgumentParser(description="a test thing")
- parser.add_argument('url')
+ parser.add_argument('urls', nargs='+')
args = parser.parse_args()
- results = getIndexItemInfo(args.url)
+ results = getIndexItemInfo(args.urls)
for result in results:
print(result)
if __name__ == '__main__':
run()
| Handle multiple sites in single request. | ## Code Before:
import argparse
import json
import os
import requests
BASE_URL = "https://api.majestic.com/api/json"
BASE_PARAMS = {'app_api_key': os.environ.get('THEAPIKEY')}
def get(cmd, params):
querydict = {'cmd': cmd}
querydict.update(BASE_PARAMS)
querydict.update(params)
response = requests.get(BASE_URL, params=querydict)
return json.loads(response.text)
def getIndexItemInfo(site):
cmd = 'GetIndexItemInfo'
params = {'items': '2',
'item0': site,
'item1': 'chrishannam.co.uk',
'datasource': 'fresh'}
responsedata = get(cmd, params)
if responsedata['Code'] == 'OK':
data = responsedata['DataTables']['Results']['Data'][0]
for data in responsedata['DataTables']['Results']['Data']:
yield {
'speed': data['OutDomainsExternal'] + 1,
'power': data['OutLinksExternal'] + 1,
'agility': data['OutLinksInternal'] + 1,
'strength': data['RefDomainsEDU'] + 1,
'smell': data['CitationFlow'] + 1,
}
else:
yield {}
def run():
parser = argparse.ArgumentParser(description="a test thing")
parser.add_argument('url')
args = parser.parse_args()
results = getIndexItemInfo(args.url)
for result in results:
print(result)
if __name__ == '__main__':
run()
## Instruction:
Handle multiple sites in single request.
## Code After:
import argparse
import json
import os
import requests
BASE_URL = "https://api.majestic.com/api/json"
BASE_PARAMS = {'app_api_key': os.environ.get('THEAPIKEY')}
def get(cmd, params):
querydict = {'cmd': cmd}
querydict.update(BASE_PARAMS)
querydict.update(params)
response = requests.get(BASE_URL, params=querydict)
return json.loads(response.text)
def getIndexItemInfo(sitelist):
cmd = 'GetIndexItemInfo'
params = {'items': len(sitelist),
'datasource': 'fresh'}
items = {'item{0}'.format(i): site for i, site in enumerate(sitelist)}
params.update(items)
responsedata = get(cmd, params)
if responsedata['Code'] == 'OK':
for data in responsedata['DataTables']['Results']['Data']:
yield {
'speed': data['OutDomainsExternal'] + 1,
'power': data['OutLinksExternal'] + 1,
'agility': data['OutLinksInternal'] + 1,
'strength': data['RefDomainsEDU'] + 1,
'smell': data['CitationFlow'] + 1,
}
else:
yield {}
def run():
parser = argparse.ArgumentParser(description="a test thing")
parser.add_argument('urls', nargs='+')
args = parser.parse_args()
results = getIndexItemInfo(args.urls)
for result in results:
print(result)
if __name__ == '__main__':
run()
|
3446db734ce669e98f8cdeedbabf13dac62c777f | edgedb/lang/build.py | edgedb/lang/build.py | import os.path
from distutils.command import build
class build(build.build):
def _compile_parsers(self):
import parsing
import edgedb
import edgedb.server.main
edgedb.server.main.init_import_system()
import edgedb.lang.edgeql.parser.grammar.single as edgeql_spec
import edgedb.lang.edgeql.parser.grammar.block as edgeql_spec2
import edgedb.server.pgsql.parser.pgsql as pgsql_spec
import edgedb.lang.schema.parser.grammar.declarations as schema_spec
import edgedb.lang.graphql.parser.grammar.document as graphql_spec
base_path = os.path.dirname(
os.path.dirname(os.path.dirname(__file__)))
for spec in (edgeql_spec, edgeql_spec2, pgsql_spec,
schema_spec, graphql_spec):
subpath = os.path.dirname(spec.__file__)[len(base_path) + 1:]
cache_dir = os.path.join(self.build_lib, subpath)
os.makedirs(cache_dir)
cache = os.path.join(
cache_dir, spec.__name__.rpartition('.')[2] + '.pickle')
parsing.Spec(spec, pickleFile=cache, verbose=True)
def run(self, *args, **kwargs):
super().run(*args, **kwargs)
self._compile_parsers()
| import os.path
from distutils.command import build
class build(build.build):
def _compile_parsers(self):
import parsing
import edgedb
import edgedb.server.main
edgedb.server.main.init_import_system()
import edgedb.lang.edgeql.parser.grammar.single as edgeql_spec
import edgedb.lang.edgeql.parser.grammar.block as edgeql_spec2
import edgedb.server.pgsql.parser.pgsql as pgsql_spec
import edgedb.lang.schema.parser.grammar.declarations as schema_spec
import edgedb.lang.graphql.parser.grammar.document as graphql_spec
base_path = os.path.dirname(
os.path.dirname(os.path.dirname(__file__)))
for spec in (edgeql_spec, edgeql_spec2, pgsql_spec,
schema_spec, graphql_spec):
subpath = os.path.dirname(spec.__file__)[len(base_path) + 1:]
cache_dir = os.path.join(self.build_lib, subpath)
os.makedirs(cache_dir, exist_ok=True)
cache = os.path.join(
cache_dir, spec.__name__.rpartition('.')[2] + '.pickle')
parsing.Spec(spec, pickleFile=cache, verbose=True)
def run(self, *args, **kwargs):
super().run(*args, **kwargs)
self._compile_parsers()
| Fix the creation of parser cache directory | setup.py: Fix the creation of parser cache directory
| Python | apache-2.0 | edgedb/edgedb,edgedb/edgedb,edgedb/edgedb | import os.path
from distutils.command import build
class build(build.build):
def _compile_parsers(self):
import parsing
import edgedb
import edgedb.server.main
edgedb.server.main.init_import_system()
import edgedb.lang.edgeql.parser.grammar.single as edgeql_spec
import edgedb.lang.edgeql.parser.grammar.block as edgeql_spec2
import edgedb.server.pgsql.parser.pgsql as pgsql_spec
import edgedb.lang.schema.parser.grammar.declarations as schema_spec
import edgedb.lang.graphql.parser.grammar.document as graphql_spec
base_path = os.path.dirname(
os.path.dirname(os.path.dirname(__file__)))
for spec in (edgeql_spec, edgeql_spec2, pgsql_spec,
schema_spec, graphql_spec):
subpath = os.path.dirname(spec.__file__)[len(base_path) + 1:]
cache_dir = os.path.join(self.build_lib, subpath)
- os.makedirs(cache_dir)
+ os.makedirs(cache_dir, exist_ok=True)
cache = os.path.join(
cache_dir, spec.__name__.rpartition('.')[2] + '.pickle')
parsing.Spec(spec, pickleFile=cache, verbose=True)
def run(self, *args, **kwargs):
super().run(*args, **kwargs)
self._compile_parsers()
| Fix the creation of parser cache directory | ## Code Before:
import os.path
from distutils.command import build
class build(build.build):
def _compile_parsers(self):
import parsing
import edgedb
import edgedb.server.main
edgedb.server.main.init_import_system()
import edgedb.lang.edgeql.parser.grammar.single as edgeql_spec
import edgedb.lang.edgeql.parser.grammar.block as edgeql_spec2
import edgedb.server.pgsql.parser.pgsql as pgsql_spec
import edgedb.lang.schema.parser.grammar.declarations as schema_spec
import edgedb.lang.graphql.parser.grammar.document as graphql_spec
base_path = os.path.dirname(
os.path.dirname(os.path.dirname(__file__)))
for spec in (edgeql_spec, edgeql_spec2, pgsql_spec,
schema_spec, graphql_spec):
subpath = os.path.dirname(spec.__file__)[len(base_path) + 1:]
cache_dir = os.path.join(self.build_lib, subpath)
os.makedirs(cache_dir)
cache = os.path.join(
cache_dir, spec.__name__.rpartition('.')[2] + '.pickle')
parsing.Spec(spec, pickleFile=cache, verbose=True)
def run(self, *args, **kwargs):
super().run(*args, **kwargs)
self._compile_parsers()
## Instruction:
Fix the creation of parser cache directory
## Code After:
import os.path
from distutils.command import build
class build(build.build):
def _compile_parsers(self):
import parsing
import edgedb
import edgedb.server.main
edgedb.server.main.init_import_system()
import edgedb.lang.edgeql.parser.grammar.single as edgeql_spec
import edgedb.lang.edgeql.parser.grammar.block as edgeql_spec2
import edgedb.server.pgsql.parser.pgsql as pgsql_spec
import edgedb.lang.schema.parser.grammar.declarations as schema_spec
import edgedb.lang.graphql.parser.grammar.document as graphql_spec
base_path = os.path.dirname(
os.path.dirname(os.path.dirname(__file__)))
for spec in (edgeql_spec, edgeql_spec2, pgsql_spec,
schema_spec, graphql_spec):
subpath = os.path.dirname(spec.__file__)[len(base_path) + 1:]
cache_dir = os.path.join(self.build_lib, subpath)
os.makedirs(cache_dir, exist_ok=True)
cache = os.path.join(
cache_dir, spec.__name__.rpartition('.')[2] + '.pickle')
parsing.Spec(spec, pickleFile=cache, verbose=True)
def run(self, *args, **kwargs):
super().run(*args, **kwargs)
self._compile_parsers()
|
3421fe2542a5b71f6b604e30f2c800400b5e40d8 | datawire/store/common.py | datawire/store/common.py | import json
from datawire.views.util import JSONEncoder
class Store(object):
def __init__(self, url):
self.url = url
def store(self, frame):
urn = frame.get('urn')
data = json.dumps(frame, cls=JSONEncoder)
return self._store(urn, data)
def load(self, urn):
data = self._load(urn)
if data is not None:
data = json.loads(data)
return data
| import json
from datawire.views.util import JSONEncoder
class Store(object):
def __init__(self, url):
self.url = url
def store(self, frame):
urn = frame.get('urn')
data = JSONEncoder().encode(frame)
return self._store(urn, data)
def load(self, urn):
data = self._load(urn)
if data is not None:
data = json.loads(data)
return data
| Fix encoding of store serialisation. | Fix encoding of store serialisation. | Python | mit | arc64/datawi.re,arc64/datawi.re,arc64/datawi.re | import json
from datawire.views.util import JSONEncoder
class Store(object):
def __init__(self, url):
self.url = url
def store(self, frame):
urn = frame.get('urn')
- data = json.dumps(frame, cls=JSONEncoder)
+ data = JSONEncoder().encode(frame)
return self._store(urn, data)
def load(self, urn):
data = self._load(urn)
if data is not None:
data = json.loads(data)
return data
| Fix encoding of store serialisation. | ## Code Before:
import json
from datawire.views.util import JSONEncoder
class Store(object):
def __init__(self, url):
self.url = url
def store(self, frame):
urn = frame.get('urn')
data = json.dumps(frame, cls=JSONEncoder)
return self._store(urn, data)
def load(self, urn):
data = self._load(urn)
if data is not None:
data = json.loads(data)
return data
## Instruction:
Fix encoding of store serialisation.
## Code After:
import json
from datawire.views.util import JSONEncoder
class Store(object):
def __init__(self, url):
self.url = url
def store(self, frame):
urn = frame.get('urn')
data = JSONEncoder().encode(frame)
return self._store(urn, data)
def load(self, urn):
data = self._load(urn)
if data is not None:
data = json.loads(data)
return data
|
9131a9f2349261900f056c1f920307b0fce176ad | icekit/plugins/image/content_plugins.py | icekit/plugins/image/content_plugins.py | from django.utils.translation import ugettext_lazy as _
from fluent_contents.extensions import ContentPlugin, plugin_pool
from . import models
@plugin_pool.register
class ImagePlugin(ContentPlugin):
model = models.ImageItem
category = _('Image')
render_template = 'icekit/plugins/image/default.html'
raw_id_fields = ['image', ]
| from django.utils.translation import ugettext_lazy as _
from django.template import loader
from fluent_contents.extensions import ContentPlugin, plugin_pool
from . import models
@plugin_pool.register
class ImagePlugin(ContentPlugin):
model = models.ImageItem
category = _('Image')
raw_id_fields = ['image', ]
def get_render_template(self, request, instance, **kwargs):
template = loader.select_template([
'icekit/plugins/image/%s_%s.html' % (
type(instance.parent)._meta.app_label,
type(instance.parent)._meta.model_name
),
'icekit/plugins/image/%s.html' % type(
instance.parent)._meta.app_label,
'icekit/plugins/image/default.html'])
return template.name
| Implement per-app/model template overrides for ImagePlugin. | Implement per-app/model template overrides for ImagePlugin.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit | from django.utils.translation import ugettext_lazy as _
+ from django.template import loader
from fluent_contents.extensions import ContentPlugin, plugin_pool
from . import models
@plugin_pool.register
class ImagePlugin(ContentPlugin):
model = models.ImageItem
category = _('Image')
- render_template = 'icekit/plugins/image/default.html'
raw_id_fields = ['image', ]
+ def get_render_template(self, request, instance, **kwargs):
+ template = loader.select_template([
+ 'icekit/plugins/image/%s_%s.html' % (
+ type(instance.parent)._meta.app_label,
+ type(instance.parent)._meta.model_name
+ ),
+ 'icekit/plugins/image/%s.html' % type(
+ instance.parent)._meta.app_label,
+ 'icekit/plugins/image/default.html'])
+ return template.name
+ | Implement per-app/model template overrides for ImagePlugin. | ## Code Before:
from django.utils.translation import ugettext_lazy as _
from fluent_contents.extensions import ContentPlugin, plugin_pool
from . import models
@plugin_pool.register
class ImagePlugin(ContentPlugin):
model = models.ImageItem
category = _('Image')
render_template = 'icekit/plugins/image/default.html'
raw_id_fields = ['image', ]
## Instruction:
Implement per-app/model template overrides for ImagePlugin.
## Code After:
from django.utils.translation import ugettext_lazy as _
from django.template import loader
from fluent_contents.extensions import ContentPlugin, plugin_pool
from . import models
@plugin_pool.register
class ImagePlugin(ContentPlugin):
model = models.ImageItem
category = _('Image')
raw_id_fields = ['image', ]
def get_render_template(self, request, instance, **kwargs):
template = loader.select_template([
'icekit/plugins/image/%s_%s.html' % (
type(instance.parent)._meta.app_label,
type(instance.parent)._meta.model_name
),
'icekit/plugins/image/%s.html' % type(
instance.parent)._meta.app_label,
'icekit/plugins/image/default.html'])
return template.name
|
6058bc795563d482ce1672b3eb933e1c409c6ac8 | setup.py | setup.py | from distutils.core import setup
setup(
name='Juju XaaS CLI',
version='0.1.0',
author='Justin SB',
author_email='[email protected]',
packages=['jxaas'],
url='http://pypi.python.org/pypi/jxaas/',
license='LICENSE.txt',
description='CLI for Juju XaaS.',
long_description=open('README.md').read(),
install_requires=[
],
scripts=[
'bin/jxaas'
]
) | from distutils.core import setup
setup(
name='Juju XaaS CLI',
version='0.1.0',
author='Justin SB',
author_email='[email protected]',
packages=['jxaas'],
url='http://pypi.python.org/pypi/jxaas/',
license='LICENSE.txt',
description='CLI for Juju XaaS.',
long_description=open('README.md').read(),
install_requires=[
'cliff'
],
scripts=[
'bin/jxaas'
]
) | Add cliff as a requirement | Add cliff as a requirement
| Python | apache-2.0 | jxaas/cli | from distutils.core import setup
setup(
name='Juju XaaS CLI',
version='0.1.0',
author='Justin SB',
author_email='[email protected]',
packages=['jxaas'],
url='http://pypi.python.org/pypi/jxaas/',
license='LICENSE.txt',
description='CLI for Juju XaaS.',
long_description=open('README.md').read(),
install_requires=[
+ 'cliff'
],
scripts=[
'bin/jxaas'
]
) | Add cliff as a requirement | ## Code Before:
from distutils.core import setup
setup(
name='Juju XaaS CLI',
version='0.1.0',
author='Justin SB',
author_email='[email protected]',
packages=['jxaas'],
url='http://pypi.python.org/pypi/jxaas/',
license='LICENSE.txt',
description='CLI for Juju XaaS.',
long_description=open('README.md').read(),
install_requires=[
],
scripts=[
'bin/jxaas'
]
)
## Instruction:
Add cliff as a requirement
## Code After:
from distutils.core import setup
setup(
name='Juju XaaS CLI',
version='0.1.0',
author='Justin SB',
author_email='[email protected]',
packages=['jxaas'],
url='http://pypi.python.org/pypi/jxaas/',
license='LICENSE.txt',
description='CLI for Juju XaaS.',
long_description=open('README.md').read(),
install_requires=[
'cliff'
],
scripts=[
'bin/jxaas'
]
) |
31691ca909fe0b1816d89bb4ccf69974eca882a6 | allauth/app_settings.py | allauth/app_settings.py | import django
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS
def check_context_processors():
allauth_ctx = 'allauth.socialaccount.context_processors.socialaccount'
ctx_present = False
if django.VERSION < (1, 8,):
if allauth_ctx in settings.TEMPLATE_CONTEXT_PROCESSORS:
ctx_present = True
else:
for engine in settings.TEMPLATES:
if allauth_ctx in engine.get('OPTIONS', {})\
.get('context_processors', []):
ctx_present = True
break
if not ctx_present:
excmsg = ("socialaccount context processor "
"not found in settings.TEMPLATE_CONTEXT_PROCESSORS."
"See settings.py instructions here: "
"https://github.com/pennersr/django-allauth#installation")
raise ImproperlyConfigured(excmsg)
if SOCIALACCOUNT_ENABLED:
check_context_processors()
LOGIN_REDIRECT_URL = getattr(settings, 'LOGIN_REDIRECT_URL', '/')
USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
| import django
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django import template
SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS
def check_context_processors():
allauth_ctx = 'allauth.socialaccount.context_processors.socialaccount'
ctx_present = False
if django.VERSION < (1, 8,):
if allauth_ctx in settings.TEMPLATE_CONTEXT_PROCESSORS:
ctx_present = True
else:
for engine in template.engines.templates.values():
if allauth_ctx in engine.get('OPTIONS', {})\
.get('context_processors', []):
ctx_present = True
break
if not ctx_present:
excmsg = ("socialaccount context processor "
"not found in settings.TEMPLATE_CONTEXT_PROCESSORS."
"See settings.py instructions here: "
"https://github.com/pennersr/django-allauth#installation")
raise ImproperlyConfigured(excmsg)
if SOCIALACCOUNT_ENABLED:
check_context_processors()
LOGIN_REDIRECT_URL = getattr(settings, 'LOGIN_REDIRECT_URL', '/')
USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
| Fix for checking the context processors on Django 1.8 | Fix for checking the context processors on Django 1.8
If the user has not migrated their settings file to use the new TEMPLATES
method in Django 1.8, settings.TEMPLATES is an empty list.
Instead, if we check django.templates.engines it will be populated with the
automatically migrated data from settings.TEMPLATE*.
| Python | mit | cudadog/django-allauth,bitcity/django-allauth,petersanchez/django-allauth,bittner/django-allauth,manran/django-allauth,jscott1989/django-allauth,petersanchez/django-allauth,JshWright/django-allauth,italomaia/django-allauth,yarbelk/django-allauth,pankeshang/django-allauth,sih4sing5hong5/django-allauth,ZachLiuGIS/django-allauth,fabiocerqueira/django-allauth,aexeagmbh/django-allauth,dincamihai/django-allauth,italomaia/django-allauth,jscott1989/django-allauth,wli/django-allauth,80vs90/django-allauth,agriffis/django-allauth,igorgai/django-allauth,rsalmaso/django-allauth,spool/django-allauth,7WebPages/django-allauth,pennersr/django-allauth,ankitjain87/django-allauth,neo/django-allauth,yarbelk/django-allauth,pankeshang/django-allauth,agriffis/django-allauth,beswarm/django-allauth,manran/django-allauth,lmorchard/django-allauth,concentricsky/django-allauth,bopo/django-allauth,bitcity/django-allauth,hanasoo/django-allauth,aexeagmbh/django-allauth,github-account-because-they-want-it/django-allauth,erueloi/django-allauth,vuchau/django-allauth,bjorand/django-allauth,janusnic/django-allauth,janusnic/django-allauth,payamsm/django-allauth,SakuradaJun/django-allauth,rulz/django-allauth,davidrenne/django-allauth,beswarm/django-allauth,erueloi/django-allauth,alacritythief/django-allauth,wli/django-allauth,zhangziang/django-allauth,concentricsky/django-allauth,willharris/django-allauth,github-account-because-they-want-it/django-allauth,pankeshang/django-allauth,tigeraniya/django-allauth,github-account-because-they-want-it/django-allauth,kingofsystem/django-allauth,joshowen/django-allauth,bjorand/django-allauth,bitcity/django-allauth,kingofsystem/django-allauth,pztrick/django-allauth,ashwoods/django-allauth,alacritythief/django-allauth,fuzzpedal/django-allauth,hanasoo/django-allauth,tigeraniya/django-allauth,pennersr/django-allauth,beswarm/django-allauth,7WebPages/django-allauth,tigeraniya/django-allauth,avsd/django-allauth,janusnic/django-allauth,jscott1989/django-allauth,carltongibson/django-allauth,dincamihai/django-allauth,ashwoods/django-allauth,rulz/django-allauth,wayward710/django-allauth,owais/django-allauth,patricio-astudillo/django-allauth,80vs90/django-allauth,moreati/django-allauth,dincamihai/django-allauth,lmorchard/django-allauth,fabiocerqueira/django-allauth,italomaia/django-allauth,JshWright/django-allauth,lukeburden/django-allauth,payamsm/django-allauth,socialsweethearts/django-allauth,pranjalpatil/django-allauth,patricio-astudillo/django-allauth,zhangziang/django-allauth,nimbis/django-allauth,nimbis/django-allauth,davidrenne/django-allauth,rsalmaso/django-allauth,80vs90/django-allauth,AltSchool/django-allauth,joshowen/django-allauth,lukeburden/django-allauth,bopo/django-allauth,joshowen/django-allauth,AltSchool/django-allauth,aexeagmbh/django-allauth,carltongibson/django-allauth,sih4sing5hong5/django-allauth,hanasoo/django-allauth,igorgai/django-allauth,jwhitlock/django-allauth,payamsm/django-allauth,zhangziang/django-allauth,fuzzpedal/django-allauth,alacritythief/django-allauth,ZachLiuGIS/django-allauth,rsalmaso/django-allauth,cudadog/django-allauth,vuchau/django-allauth,wayward710/django-allauth,avsd/django-allauth,pranjalpatil/django-allauth,spool/django-allauth,petersanchez/django-allauth,wayward710/django-allauth,JshWright/django-allauth,sih4sing5hong5/django-allauth,owais/django-allauth,kingofsystem/django-allauth,7WebPages/django-allauth,concentricsky/django-allauth,ankitjain87/django-allauth,neo/django-allauth,lukeburden/django-allauth,SakuradaJun/django-allauth,willharris/django-allauth,yarbelk/django-allauth,agriffis/django-allauth,bopo/django-allauth,AltSchool/django-allauth,moreati/django-allauth,vuchau/django-allauth,pennersr/django-allauth,pztrick/django-allauth,erueloi/django-allauth,fabiocerqueira/django-allauth,davidrenne/django-allauth,pranjalpatil/django-allauth,pztrick/django-allauth,fuzzpedal/django-allauth,socialsweethearts/django-allauth,bittner/django-allauth,ZachLiuGIS/django-allauth,spool/django-allauth,lmorchard/django-allauth,carltongibson/django-allauth,ankitjain87/django-allauth,moreati/django-allauth,neo/django-allauth,cudadog/django-allauth,socialsweethearts/django-allauth,owais/django-allauth,ashwoods/django-allauth,rulz/django-allauth,jwhitlock/django-allauth,manran/django-allauth,SakuradaJun/django-allauth,nimbis/django-allauth,jwhitlock/django-allauth,patricio-astudillo/django-allauth,wli/django-allauth,avsd/django-allauth,bittner/django-allauth,willharris/django-allauth,igorgai/django-allauth,bjorand/django-allauth | import django
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
+ from django import template
SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS
def check_context_processors():
allauth_ctx = 'allauth.socialaccount.context_processors.socialaccount'
ctx_present = False
if django.VERSION < (1, 8,):
if allauth_ctx in settings.TEMPLATE_CONTEXT_PROCESSORS:
ctx_present = True
else:
- for engine in settings.TEMPLATES:
+ for engine in template.engines.templates.values():
if allauth_ctx in engine.get('OPTIONS', {})\
.get('context_processors', []):
ctx_present = True
break
if not ctx_present:
excmsg = ("socialaccount context processor "
"not found in settings.TEMPLATE_CONTEXT_PROCESSORS."
"See settings.py instructions here: "
"https://github.com/pennersr/django-allauth#installation")
raise ImproperlyConfigured(excmsg)
if SOCIALACCOUNT_ENABLED:
check_context_processors()
LOGIN_REDIRECT_URL = getattr(settings, 'LOGIN_REDIRECT_URL', '/')
USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
| Fix for checking the context processors on Django 1.8 | ## Code Before:
import django
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS
def check_context_processors():
allauth_ctx = 'allauth.socialaccount.context_processors.socialaccount'
ctx_present = False
if django.VERSION < (1, 8,):
if allauth_ctx in settings.TEMPLATE_CONTEXT_PROCESSORS:
ctx_present = True
else:
for engine in settings.TEMPLATES:
if allauth_ctx in engine.get('OPTIONS', {})\
.get('context_processors', []):
ctx_present = True
break
if not ctx_present:
excmsg = ("socialaccount context processor "
"not found in settings.TEMPLATE_CONTEXT_PROCESSORS."
"See settings.py instructions here: "
"https://github.com/pennersr/django-allauth#installation")
raise ImproperlyConfigured(excmsg)
if SOCIALACCOUNT_ENABLED:
check_context_processors()
LOGIN_REDIRECT_URL = getattr(settings, 'LOGIN_REDIRECT_URL', '/')
USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
## Instruction:
Fix for checking the context processors on Django 1.8
## Code After:
import django
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django import template
SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS
def check_context_processors():
allauth_ctx = 'allauth.socialaccount.context_processors.socialaccount'
ctx_present = False
if django.VERSION < (1, 8,):
if allauth_ctx in settings.TEMPLATE_CONTEXT_PROCESSORS:
ctx_present = True
else:
for engine in template.engines.templates.values():
if allauth_ctx in engine.get('OPTIONS', {})\
.get('context_processors', []):
ctx_present = True
break
if not ctx_present:
excmsg = ("socialaccount context processor "
"not found in settings.TEMPLATE_CONTEXT_PROCESSORS."
"See settings.py instructions here: "
"https://github.com/pennersr/django-allauth#installation")
raise ImproperlyConfigured(excmsg)
if SOCIALACCOUNT_ENABLED:
check_context_processors()
LOGIN_REDIRECT_URL = getattr(settings, 'LOGIN_REDIRECT_URL', '/')
USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
|
f941989ef9663ebbb3ba33709dd3c723c86bd2cc | action_log/views.py | action_log/views.py | from __future__ import unicode_literals
import json
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from .models import ActionRecord
@csrf_exempt
def get_action_records(request):
action = request.GET.get('action', None)
limit = int(request.GET.get('limit', 0))
max_limit = settings.ACTION_LOG_QUERY_LIMIT
if request.user.is_superuser:
max_limit = settings.ACTION_LOG_ADMIN_QUERY_LIMIT
if (limit == 0) and (max_limit == 0):
limit = 0
elif limit == 0:
limit = max_limit
elif limit > max_limit:
limit = max_limit
# filter out records
records = ActionRecord.objects.all()
if action is not None:
records = records.filter(action_type__name=action)
if limit != 0:
records = records.all()[:limit]
return HttpResponse(
json.dumps([
record.dump(settings.ACTION_LOG_ALOWED_FIELDS)
for record in records
]), content_type='application/json'
)
| from __future__ import unicode_literals
import json
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from .models import ActionRecord
@csrf_exempt
def get_action_records(request):
action = request.GET.get('action', None)
limit = int(request.GET.get('limit', 0))
max_limit = settings.ACTION_LOG_QUERY_LIMIT
if request.user.is_superuser:
max_limit = settings.ACTION_LOG_ADMIN_QUERY_LIMIT
if (limit == 0) and (max_limit == 0):
limit = 0
elif limit == 0:
limit = max_limit
elif limit > max_limit:
limit = max_limit
# filter out records
records = ActionRecord.objects.all().order_by('-id')
if action is not None:
records = records.filter(action_type__name=action)
if limit != 0:
records = records.all()[:limit]
return HttpResponse(
json.dumps([
record.dump(settings.ACTION_LOG_ALOWED_FIELDS)
for record in records
]), content_type='application/json'
)
| Make it DESC order by id. | Make it DESC order by id.
| Python | mit | bradojevic/django-action-log | from __future__ import unicode_literals
import json
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from .models import ActionRecord
@csrf_exempt
def get_action_records(request):
action = request.GET.get('action', None)
limit = int(request.GET.get('limit', 0))
max_limit = settings.ACTION_LOG_QUERY_LIMIT
if request.user.is_superuser:
max_limit = settings.ACTION_LOG_ADMIN_QUERY_LIMIT
if (limit == 0) and (max_limit == 0):
limit = 0
elif limit == 0:
limit = max_limit
elif limit > max_limit:
limit = max_limit
# filter out records
- records = ActionRecord.objects.all()
+ records = ActionRecord.objects.all().order_by('-id')
if action is not None:
records = records.filter(action_type__name=action)
if limit != 0:
records = records.all()[:limit]
return HttpResponse(
json.dumps([
record.dump(settings.ACTION_LOG_ALOWED_FIELDS)
for record in records
]), content_type='application/json'
)
| Make it DESC order by id. | ## Code Before:
from __future__ import unicode_literals
import json
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from .models import ActionRecord
@csrf_exempt
def get_action_records(request):
action = request.GET.get('action', None)
limit = int(request.GET.get('limit', 0))
max_limit = settings.ACTION_LOG_QUERY_LIMIT
if request.user.is_superuser:
max_limit = settings.ACTION_LOG_ADMIN_QUERY_LIMIT
if (limit == 0) and (max_limit == 0):
limit = 0
elif limit == 0:
limit = max_limit
elif limit > max_limit:
limit = max_limit
# filter out records
records = ActionRecord.objects.all()
if action is not None:
records = records.filter(action_type__name=action)
if limit != 0:
records = records.all()[:limit]
return HttpResponse(
json.dumps([
record.dump(settings.ACTION_LOG_ALOWED_FIELDS)
for record in records
]), content_type='application/json'
)
## Instruction:
Make it DESC order by id.
## Code After:
from __future__ import unicode_literals
import json
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from .models import ActionRecord
@csrf_exempt
def get_action_records(request):
action = request.GET.get('action', None)
limit = int(request.GET.get('limit', 0))
max_limit = settings.ACTION_LOG_QUERY_LIMIT
if request.user.is_superuser:
max_limit = settings.ACTION_LOG_ADMIN_QUERY_LIMIT
if (limit == 0) and (max_limit == 0):
limit = 0
elif limit == 0:
limit = max_limit
elif limit > max_limit:
limit = max_limit
# filter out records
records = ActionRecord.objects.all().order_by('-id')
if action is not None:
records = records.filter(action_type__name=action)
if limit != 0:
records = records.all()[:limit]
return HttpResponse(
json.dumps([
record.dump(settings.ACTION_LOG_ALOWED_FIELDS)
for record in records
]), content_type='application/json'
)
|
21f08d30bf23056ea3e4fc9804715a57a8978c02 | gitdir/host/localhost.py | gitdir/host/localhost.py | import gitdir.host
class LocalHost(gitdir.host.Host):
def __iter__(self):
for repo_dir in sorted(self.dir.iterdir()):
if repo_dir.is_dir():
yield self.repo(repo_dir.name)
def __repr__(self):
return 'gitdir.host.localhost.LocalHost()'
def __str__(self):
return 'localhost'
def clone(self, repo_spec):
repo_dir = self.repo_path(repo_spec)
if not repo_dir.exists():
raise ValueError('No such repo on localhost: {!r}'.format(repo_spec))
return super().clone(repo_spec)
def clone_stage(self, repo_spec):
repo_dir = self.repo_path(repo_spec)
if not repo_dir.exists():
raise ValueError('No such repo on localhost: {!r}'.format(repo_spec))
return super().clone_stage(repo_spec)
def repo_remote(self, repo_spec, stage=False):
return '/opt/git/localhost/{}/{}.git'.format(repo_spec, repo_spec)
| import gitdir.host
class LocalHost(gitdir.host.Host):
def __iter__(self):
for repo_dir in sorted(self.dir.iterdir()):
if repo_dir.is_dir():
yield self.repo(repo_dir.name)
def __repr__(self):
return 'gitdir.host.localhost.LocalHost()'
def __str__(self):
return 'localhost'
def clone(self, repo_spec, *, branch=None):
repo_dir = self.repo_path(repo_spec)
if not repo_dir.exists():
raise ValueError('No such repo on localhost: {!r}'.format(repo_spec))
return super().clone(repo_spec, branch=branch)
def clone_stage(self, repo_spec):
repo_dir = self.repo_path(repo_spec)
if not repo_dir.exists():
raise ValueError('No such repo on localhost: {!r}'.format(repo_spec))
return super().clone_stage(repo_spec)
def repo_remote(self, repo_spec, stage=False):
return '/opt/git/localhost/{}/{}.git'.format(repo_spec, repo_spec)
| Add support for branch arg to LocalHost.clone | Add support for branch arg to LocalHost.clone
| Python | mit | fenhl/gitdir | import gitdir.host
class LocalHost(gitdir.host.Host):
def __iter__(self):
for repo_dir in sorted(self.dir.iterdir()):
if repo_dir.is_dir():
yield self.repo(repo_dir.name)
def __repr__(self):
return 'gitdir.host.localhost.LocalHost()'
def __str__(self):
return 'localhost'
- def clone(self, repo_spec):
+ def clone(self, repo_spec, *, branch=None):
repo_dir = self.repo_path(repo_spec)
if not repo_dir.exists():
raise ValueError('No such repo on localhost: {!r}'.format(repo_spec))
- return super().clone(repo_spec)
+ return super().clone(repo_spec, branch=branch)
def clone_stage(self, repo_spec):
repo_dir = self.repo_path(repo_spec)
if not repo_dir.exists():
raise ValueError('No such repo on localhost: {!r}'.format(repo_spec))
return super().clone_stage(repo_spec)
def repo_remote(self, repo_spec, stage=False):
return '/opt/git/localhost/{}/{}.git'.format(repo_spec, repo_spec)
| Add support for branch arg to LocalHost.clone | ## Code Before:
import gitdir.host
class LocalHost(gitdir.host.Host):
def __iter__(self):
for repo_dir in sorted(self.dir.iterdir()):
if repo_dir.is_dir():
yield self.repo(repo_dir.name)
def __repr__(self):
return 'gitdir.host.localhost.LocalHost()'
def __str__(self):
return 'localhost'
def clone(self, repo_spec):
repo_dir = self.repo_path(repo_spec)
if not repo_dir.exists():
raise ValueError('No such repo on localhost: {!r}'.format(repo_spec))
return super().clone(repo_spec)
def clone_stage(self, repo_spec):
repo_dir = self.repo_path(repo_spec)
if not repo_dir.exists():
raise ValueError('No such repo on localhost: {!r}'.format(repo_spec))
return super().clone_stage(repo_spec)
def repo_remote(self, repo_spec, stage=False):
return '/opt/git/localhost/{}/{}.git'.format(repo_spec, repo_spec)
## Instruction:
Add support for branch arg to LocalHost.clone
## Code After:
import gitdir.host
class LocalHost(gitdir.host.Host):
def __iter__(self):
for repo_dir in sorted(self.dir.iterdir()):
if repo_dir.is_dir():
yield self.repo(repo_dir.name)
def __repr__(self):
return 'gitdir.host.localhost.LocalHost()'
def __str__(self):
return 'localhost'
def clone(self, repo_spec, *, branch=None):
repo_dir = self.repo_path(repo_spec)
if not repo_dir.exists():
raise ValueError('No such repo on localhost: {!r}'.format(repo_spec))
return super().clone(repo_spec, branch=branch)
def clone_stage(self, repo_spec):
repo_dir = self.repo_path(repo_spec)
if not repo_dir.exists():
raise ValueError('No such repo on localhost: {!r}'.format(repo_spec))
return super().clone_stage(repo_spec)
def repo_remote(self, repo_spec, stage=False):
return '/opt/git/localhost/{}/{}.git'.format(repo_spec, repo_spec)
|
838895500f8046b06718c184a4e8b12b42add516 | wp2hugo.py | wp2hugo.py |
import sys
from pprint import pprint
from lxml import etree
import html2text
from wp_parser import WordpressXMLParser
from hugo_printer import HugoPrinter
def main():
wp_xml_parser = WordpressXMLParser(sys.argv[1])
meta = wp_xml_parser.get_meta()
cats = wp_xml_parser.get_categories()
tags = wp_xml_parser.get_tags()
posts = wp_xml_parser.get_public_posts()
drafts = wp_xml_parser.get_drafts()
pprint(posts[-1])
if __name__ == '__main__':
main()
|
import sys
from pprint import pprint
from lxml import etree
import html2text
from wp_parser import WordpressXMLParser
from hugo_printer import HugoPrinter
def main():
wp_xml_parser = WordpressXMLParser(sys.argv[1])
wp_site_info = {
"meta": wp_xml_parser.get_meta(),
"cats": wp_xml_parser.get_categories(),
"tags": wp_xml_parser.get_tags(),
"posts": wp_xml_parser.get_public_posts(),
"drafts": wp_xml_parser.get_drafts(),
}
hugo_printer = HugoPrinter(**wp_site_info)
hugo_printer.gen_config()
if __name__ == '__main__':
main()
| Call HugoPrinter to save config file | Call HugoPrinter to save config file
| Python | mit | hzmangel/wp2hugo |
import sys
from pprint import pprint
from lxml import etree
import html2text
from wp_parser import WordpressXMLParser
from hugo_printer import HugoPrinter
def main():
wp_xml_parser = WordpressXMLParser(sys.argv[1])
+ wp_site_info = {
- meta = wp_xml_parser.get_meta()
+ "meta": wp_xml_parser.get_meta(),
- cats = wp_xml_parser.get_categories()
+ "cats": wp_xml_parser.get_categories(),
- tags = wp_xml_parser.get_tags()
+ "tags": wp_xml_parser.get_tags(),
- posts = wp_xml_parser.get_public_posts()
+ "posts": wp_xml_parser.get_public_posts(),
- drafts = wp_xml_parser.get_drafts()
+ "drafts": wp_xml_parser.get_drafts(),
+ }
- pprint(posts[-1])
+ hugo_printer = HugoPrinter(**wp_site_info)
+ hugo_printer.gen_config()
if __name__ == '__main__':
main()
| Call HugoPrinter to save config file | ## Code Before:
import sys
from pprint import pprint
from lxml import etree
import html2text
from wp_parser import WordpressXMLParser
from hugo_printer import HugoPrinter
def main():
wp_xml_parser = WordpressXMLParser(sys.argv[1])
meta = wp_xml_parser.get_meta()
cats = wp_xml_parser.get_categories()
tags = wp_xml_parser.get_tags()
posts = wp_xml_parser.get_public_posts()
drafts = wp_xml_parser.get_drafts()
pprint(posts[-1])
if __name__ == '__main__':
main()
## Instruction:
Call HugoPrinter to save config file
## Code After:
import sys
from pprint import pprint
from lxml import etree
import html2text
from wp_parser import WordpressXMLParser
from hugo_printer import HugoPrinter
def main():
wp_xml_parser = WordpressXMLParser(sys.argv[1])
wp_site_info = {
"meta": wp_xml_parser.get_meta(),
"cats": wp_xml_parser.get_categories(),
"tags": wp_xml_parser.get_tags(),
"posts": wp_xml_parser.get_public_posts(),
"drafts": wp_xml_parser.get_drafts(),
}
hugo_printer = HugoPrinter(**wp_site_info)
hugo_printer.gen_config()
if __name__ == '__main__':
main()
|
71fef8b9696d79f7d6fd024320bc23ce1b7425f3 | greatbigcrane/preferences/models.py | greatbigcrane/preferences/models.py |
from django.db import models
class Preference(models.Model):
name = models.CharField(max_length=32, unique=True)
value = models.CharField(max_length=512)
|
from django.db import models
class PreferenceManager(models.Manager):
def get_preference(self, name, default=None):
try:
value = Preference.objects.get(name="projects_directory").value
except Preference.DoesNotExist:
return default
class Preference(models.Model):
name = models.CharField(max_length=32, unique=True)
value = models.CharField(max_length=512)
objects = PreferenceManager()
| Add a manager to make getting preferences prettier. | Add a manager to make getting preferences prettier.
| Python | apache-2.0 | pnomolos/greatbigcrane,pnomolos/greatbigcrane |
from django.db import models
+
+ class PreferenceManager(models.Manager):
+ def get_preference(self, name, default=None):
+ try:
+ value = Preference.objects.get(name="projects_directory").value
+ except Preference.DoesNotExist:
+ return default
class Preference(models.Model):
name = models.CharField(max_length=32, unique=True)
value = models.CharField(max_length=512)
+ objects = PreferenceManager()
| Add a manager to make getting preferences prettier. | ## Code Before:
from django.db import models
class Preference(models.Model):
name = models.CharField(max_length=32, unique=True)
value = models.CharField(max_length=512)
## Instruction:
Add a manager to make getting preferences prettier.
## Code After:
from django.db import models
class PreferenceManager(models.Manager):
def get_preference(self, name, default=None):
try:
value = Preference.objects.get(name="projects_directory").value
except Preference.DoesNotExist:
return default
class Preference(models.Model):
name = models.CharField(max_length=32, unique=True)
value = models.CharField(max_length=512)
objects = PreferenceManager()
|
018acc1817cedf8985ffc81e4fe7e98d85a644da | instructions/base.py | instructions/base.py | class InstructionBase(object):
BEFORE=None
AFTER=None
def __init__(self, search_string):
self.search_string = search_string
@property
def search_string(self):
return self._search_string
@search_string.setter
def search_string(self, value):
if value.startswith(self.INSTRUCTION):
self._search_string = value[(len(self.INSTRUCTION) + 1):]
else:
self._search_string = value
def __str__(self):
return self.INSTRUCTION + " " + self.search_string
def run(self, inputcontainer):
return (None, False)
def _search(self, inputcontainer):
text = inputcontainer.get_at_pointer()
if text == inputcontainer.EOF:
return inputcontainer.EOF
offset = text.find(self.search_string)
if offset == -1:
return inputcontainer.EOF
else:
return offset
def _copy(self, inputcontainer):
text = inputcontainer.get_at_pointer()
offset = self._search(inputcontainer)
if offset == inputcontainer.EOF:
inputcontainer.move_to_eof()
else:
inputcontainer.move_pointer(offset)
text = text[:offset]
return text
def _if(self, inputcontainer):
text = inputcontainer.get_at_pointer()
if text.startswith(self.search_string):
return True
else:
return False
| class InstructionBase(object):
BEFORE=None
AFTER=None
def __init__(self, search_string):
self.search_string = search_string
@property
def search_string(self):
return self._search_string
@search_string.setter
def search_string(self, value):
if value.startswith(self.INSTRUCTION):
temp = value[(len(self.INSTRUCTION) + 1):]
else:
temp = value
self._search_string = temp.replace("\\n", "\n")
def __str__(self):
return self.INSTRUCTION + " " + self.search_string
def run(self, inputcontainer):
return (None, False)
def _search(self, inputcontainer):
text = inputcontainer.get_at_pointer()
if text == inputcontainer.EOF:
return inputcontainer.EOF
offset = text.find(self.search_string)
if offset == -1:
return inputcontainer.EOF
else:
return offset
def _copy(self, inputcontainer):
text = inputcontainer.get_at_pointer()
offset = self._search(inputcontainer)
if offset == inputcontainer.EOF:
inputcontainer.move_to_eof()
else:
inputcontainer.move_pointer(offset)
text = text[:offset]
return text
def _if(self, inputcontainer):
text = inputcontainer.get_at_pointer()
if text.startswith(self.search_string):
return True
else:
return False
| Add hack to allow specifying newlines in scripts | Add hack to allow specifying newlines in scripts
| Python | unlicense | djmattyg007/IdiotScript | class InstructionBase(object):
BEFORE=None
AFTER=None
def __init__(self, search_string):
self.search_string = search_string
@property
def search_string(self):
return self._search_string
@search_string.setter
def search_string(self, value):
if value.startswith(self.INSTRUCTION):
- self._search_string = value[(len(self.INSTRUCTION) + 1):]
+ temp = value[(len(self.INSTRUCTION) + 1):]
else:
- self._search_string = value
+ temp = value
+ self._search_string = temp.replace("\\n", "\n")
def __str__(self):
return self.INSTRUCTION + " " + self.search_string
def run(self, inputcontainer):
return (None, False)
def _search(self, inputcontainer):
text = inputcontainer.get_at_pointer()
if text == inputcontainer.EOF:
return inputcontainer.EOF
offset = text.find(self.search_string)
if offset == -1:
return inputcontainer.EOF
else:
return offset
def _copy(self, inputcontainer):
text = inputcontainer.get_at_pointer()
offset = self._search(inputcontainer)
if offset == inputcontainer.EOF:
inputcontainer.move_to_eof()
else:
inputcontainer.move_pointer(offset)
text = text[:offset]
return text
def _if(self, inputcontainer):
text = inputcontainer.get_at_pointer()
if text.startswith(self.search_string):
return True
else:
return False
| Add hack to allow specifying newlines in scripts | ## Code Before:
class InstructionBase(object):
BEFORE=None
AFTER=None
def __init__(self, search_string):
self.search_string = search_string
@property
def search_string(self):
return self._search_string
@search_string.setter
def search_string(self, value):
if value.startswith(self.INSTRUCTION):
self._search_string = value[(len(self.INSTRUCTION) + 1):]
else:
self._search_string = value
def __str__(self):
return self.INSTRUCTION + " " + self.search_string
def run(self, inputcontainer):
return (None, False)
def _search(self, inputcontainer):
text = inputcontainer.get_at_pointer()
if text == inputcontainer.EOF:
return inputcontainer.EOF
offset = text.find(self.search_string)
if offset == -1:
return inputcontainer.EOF
else:
return offset
def _copy(self, inputcontainer):
text = inputcontainer.get_at_pointer()
offset = self._search(inputcontainer)
if offset == inputcontainer.EOF:
inputcontainer.move_to_eof()
else:
inputcontainer.move_pointer(offset)
text = text[:offset]
return text
def _if(self, inputcontainer):
text = inputcontainer.get_at_pointer()
if text.startswith(self.search_string):
return True
else:
return False
## Instruction:
Add hack to allow specifying newlines in scripts
## Code After:
class InstructionBase(object):
BEFORE=None
AFTER=None
def __init__(self, search_string):
self.search_string = search_string
@property
def search_string(self):
return self._search_string
@search_string.setter
def search_string(self, value):
if value.startswith(self.INSTRUCTION):
temp = value[(len(self.INSTRUCTION) + 1):]
else:
temp = value
self._search_string = temp.replace("\\n", "\n")
def __str__(self):
return self.INSTRUCTION + " " + self.search_string
def run(self, inputcontainer):
return (None, False)
def _search(self, inputcontainer):
text = inputcontainer.get_at_pointer()
if text == inputcontainer.EOF:
return inputcontainer.EOF
offset = text.find(self.search_string)
if offset == -1:
return inputcontainer.EOF
else:
return offset
def _copy(self, inputcontainer):
text = inputcontainer.get_at_pointer()
offset = self._search(inputcontainer)
if offset == inputcontainer.EOF:
inputcontainer.move_to_eof()
else:
inputcontainer.move_pointer(offset)
text = text[:offset]
return text
def _if(self, inputcontainer):
text = inputcontainer.get_at_pointer()
if text.startswith(self.search_string):
return True
else:
return False
|
ed0f115e600a564117ed540e7692e0efccf5826b | server/nso.py | server/nso.py | from flask import request, Response
from .base import *
from server import app
import requests
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
@app.route('/nso')
def get_nso_events():
r = requests.get("http://www.nso.upenn.edu/event-calendar.rss")
split = r.text.split("\n")
filtered = [i if "<pubDate" not in i else "<pubDate>Wed, 02 Aug 2016 08:00:00 EST</pubDate>" for i in split]
output = "\n".join(filtered)
return Response(output, mimetype="text/xml")
| from flask import request, Response
from .base import *
from server import app
import requests
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
@app.route('/nso')
def get_nso_events():
r = requests.get("http://www.nso.upenn.edu/event-calendar.rss")
split = r.text.split("\n")
filtered = [i if "<pubDate" not in i else "<pubDate>Wed, 02 Aug 2016 08:00:00 EST</pubDate>" for i in split]
filtered = [i if ("<title" not in i or "NSO Event Calendar" in i) else changeTitle(i) for i in filtered]
output = "\n".join(filtered)
return Response(output, mimetype="text/xml")
def changeTitle(a):
index = a.index("event") + 17
a = subFour(a,index)
if a[index+6] == '-':
a = subFour(a,index + 18)
return a
def subFour(string, index):
val = string[index:index+6]
new_val = str(int(val) - 40000)
if len(new_val) < 6:
new_val = "0" + new_val
return string.replace(val, new_val)
| Set time back four hours to EST | Set time back four hours to EST
| Python | mit | pennlabs/penn-mobile-server,pennlabs/penn-mobile-server | from flask import request, Response
from .base import *
from server import app
import requests
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
@app.route('/nso')
def get_nso_events():
r = requests.get("http://www.nso.upenn.edu/event-calendar.rss")
split = r.text.split("\n")
- filtered = [i if "<pubDate" not in i else "<pubDate>Wed, 02 Aug 2016 08:00:00 EST</pubDate>" for i in split]
+ filtered = [i if "<pubDate" not in i else "<pubDate>Wed, 02 Aug 2016 08:00:00 EST</pubDate>" for i in split]
+ filtered = [i if ("<title" not in i or "NSO Event Calendar" in i) else changeTitle(i) for i in filtered]
output = "\n".join(filtered)
return Response(output, mimetype="text/xml")
+ def changeTitle(a):
+ index = a.index("event") + 17
+ a = subFour(a,index)
+ if a[index+6] == '-':
+ a = subFour(a,index + 18)
+ return a
+
+ def subFour(string, index):
+ val = string[index:index+6]
+ new_val = str(int(val) - 40000)
+ if len(new_val) < 6:
+ new_val = "0" + new_val
+ return string.replace(val, new_val)
+
+ | Set time back four hours to EST | ## Code Before:
from flask import request, Response
from .base import *
from server import app
import requests
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
@app.route('/nso')
def get_nso_events():
r = requests.get("http://www.nso.upenn.edu/event-calendar.rss")
split = r.text.split("\n")
filtered = [i if "<pubDate" not in i else "<pubDate>Wed, 02 Aug 2016 08:00:00 EST</pubDate>" for i in split]
output = "\n".join(filtered)
return Response(output, mimetype="text/xml")
## Instruction:
Set time back four hours to EST
## Code After:
from flask import request, Response
from .base import *
from server import app
import requests
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
@app.route('/nso')
def get_nso_events():
r = requests.get("http://www.nso.upenn.edu/event-calendar.rss")
split = r.text.split("\n")
filtered = [i if "<pubDate" not in i else "<pubDate>Wed, 02 Aug 2016 08:00:00 EST</pubDate>" for i in split]
filtered = [i if ("<title" not in i or "NSO Event Calendar" in i) else changeTitle(i) for i in filtered]
output = "\n".join(filtered)
return Response(output, mimetype="text/xml")
def changeTitle(a):
index = a.index("event") + 17
a = subFour(a,index)
if a[index+6] == '-':
a = subFour(a,index + 18)
return a
def subFour(string, index):
val = string[index:index+6]
new_val = str(int(val) - 40000)
if len(new_val) < 6:
new_val = "0" + new_val
return string.replace(val, new_val)
|
01b03d46d32dd7f9e027220df0681c4f82fe7217 | cumulusci/conftest.py | cumulusci/conftest.py | from pytest import fixture
from cumulusci.core.github import get_github_api
@fixture
def gh_api():
return get_github_api("TestOwner", "TestRepo")
| import os
from pytest import fixture
from cumulusci.core.github import get_github_api
@fixture
def gh_api():
return get_github_api("TestOwner", "TestRepo")
@fixture(scope="class", autouse=True)
def restore_cwd():
d = os.getcwd()
try:
yield
finally:
os.chdir(d)
| Add pytest fixture to avoid leakage of cwd changes | Add pytest fixture to avoid leakage of cwd changes
| Python | bsd-3-clause | SalesforceFoundation/CumulusCI,SalesforceFoundation/CumulusCI | + import os
+
from pytest import fixture
from cumulusci.core.github import get_github_api
@fixture
def gh_api():
return get_github_api("TestOwner", "TestRepo")
+
+ @fixture(scope="class", autouse=True)
+ def restore_cwd():
+ d = os.getcwd()
+ try:
+ yield
+ finally:
+ os.chdir(d)
+ | Add pytest fixture to avoid leakage of cwd changes | ## Code Before:
from pytest import fixture
from cumulusci.core.github import get_github_api
@fixture
def gh_api():
return get_github_api("TestOwner", "TestRepo")
## Instruction:
Add pytest fixture to avoid leakage of cwd changes
## Code After:
import os
from pytest import fixture
from cumulusci.core.github import get_github_api
@fixture
def gh_api():
return get_github_api("TestOwner", "TestRepo")
@fixture(scope="class", autouse=True)
def restore_cwd():
d = os.getcwd()
try:
yield
finally:
os.chdir(d)
|
1d55fe7b1f4f3d70da6867ef7465ac44f8d2da38 | keyring/tests/backends/test_OS_X.py | keyring/tests/backends/test_OS_X.py | import sys
from ..test_backend import BackendBasicTests
from ..py30compat import unittest
from keyring.backends import OS_X
def is_osx_keychain_supported():
return sys.platform in ('mac','darwin')
@unittest.skipUnless(is_osx_keychain_supported(),
"Need OS X")
class OSXKeychainTestCase(BackendBasicTests, unittest.TestCase):
def init_keyring(self):
return OS_X.Keyring()
@unittest.expectedFailure
def test_delete_present(self):
"""Not implemented"""
super(OSXKeychainTestCase, self).test_delete_present()
class SecurityCommandTestCase(unittest.TestCase):
def test_SecurityCommand(self):
self.assertEqual(OS_X.SecurityCommand('get'), 'get-generic-password')
self.assertEqual(OS_X.SecurityCommand('set', 'internet'), 'set-internet-password')
| import sys
from ..test_backend import BackendBasicTests
from ..py30compat import unittest
from keyring.backends import OS_X
def is_osx_keychain_supported():
return sys.platform in ('mac','darwin')
@unittest.skipUnless(is_osx_keychain_supported(),
"Need OS X")
class OSXKeychainTestCase(BackendBasicTests, unittest.TestCase):
def init_keyring(self):
return OS_X.Keyring()
class SecurityCommandTestCase(unittest.TestCase):
def test_SecurityCommand(self):
self.assertEqual(OS_X.SecurityCommand('get'), 'get-generic-password')
self.assertEqual(OS_X.SecurityCommand('set', 'internet'), 'set-internet-password')
| Test passes on OS X | Test passes on OS X
| Python | mit | jaraco/keyring | import sys
from ..test_backend import BackendBasicTests
from ..py30compat import unittest
from keyring.backends import OS_X
def is_osx_keychain_supported():
return sys.platform in ('mac','darwin')
@unittest.skipUnless(is_osx_keychain_supported(),
"Need OS X")
class OSXKeychainTestCase(BackendBasicTests, unittest.TestCase):
def init_keyring(self):
return OS_X.Keyring()
- @unittest.expectedFailure
- def test_delete_present(self):
- """Not implemented"""
- super(OSXKeychainTestCase, self).test_delete_present()
-
class SecurityCommandTestCase(unittest.TestCase):
def test_SecurityCommand(self):
self.assertEqual(OS_X.SecurityCommand('get'), 'get-generic-password')
self.assertEqual(OS_X.SecurityCommand('set', 'internet'), 'set-internet-password')
| Test passes on OS X | ## Code Before:
import sys
from ..test_backend import BackendBasicTests
from ..py30compat import unittest
from keyring.backends import OS_X
def is_osx_keychain_supported():
return sys.platform in ('mac','darwin')
@unittest.skipUnless(is_osx_keychain_supported(),
"Need OS X")
class OSXKeychainTestCase(BackendBasicTests, unittest.TestCase):
def init_keyring(self):
return OS_X.Keyring()
@unittest.expectedFailure
def test_delete_present(self):
"""Not implemented"""
super(OSXKeychainTestCase, self).test_delete_present()
class SecurityCommandTestCase(unittest.TestCase):
def test_SecurityCommand(self):
self.assertEqual(OS_X.SecurityCommand('get'), 'get-generic-password')
self.assertEqual(OS_X.SecurityCommand('set', 'internet'), 'set-internet-password')
## Instruction:
Test passes on OS X
## Code After:
import sys
from ..test_backend import BackendBasicTests
from ..py30compat import unittest
from keyring.backends import OS_X
def is_osx_keychain_supported():
return sys.platform in ('mac','darwin')
@unittest.skipUnless(is_osx_keychain_supported(),
"Need OS X")
class OSXKeychainTestCase(BackendBasicTests, unittest.TestCase):
def init_keyring(self):
return OS_X.Keyring()
class SecurityCommandTestCase(unittest.TestCase):
def test_SecurityCommand(self):
self.assertEqual(OS_X.SecurityCommand('get'), 'get-generic-password')
self.assertEqual(OS_X.SecurityCommand('set', 'internet'), 'set-internet-password')
|
e55c5b80d67edcde6c6f31665f39ebfb70660bc1 | scripts/update_lookup_stats.py | scripts/update_lookup_stats.py |
import re
from contextlib import closing
from acoustid.script import run_script
from acoustid.data.stats import update_lookup_stats
def main(script, opts, args):
db = script.engine.connect()
redis = script.redis
for key, count in redis.hgetall('lookups').iteritems():
count = int(count)
date, hour, application_id, type = key.split(':')
if not count:
# the only way this could be 0 is if we already processed it and
# nothing touched it since then, so it's safe to delete
redis.hdel('lookups', key)
else:
update_lookup_stats(db, application_id, date, hour, type, count)
redis.hincrby('lookups', key, -count)
run_script(main)
|
import re
import urllib
import urllib2
from contextlib import closing
from acoustid.script import run_script
from acoustid.data.stats import update_lookup_stats
def call_internal_api(func, **kwargs):
url = script.config.cluster.base_master_url.rstrip('/') + '/v2/internal/' + func
data = dict(kwargs)
data['secret'] = script.config.cluster.secret
urllib2.urlopen(url, urllib.urlencode(data))
def main(script, opts, args):
db = script.engine.connect()
redis = script.redis
for key, count in redis.hgetall('lookups').iteritems():
count = int(count)
date, hour, application_id, type = key.split(':')
if not count:
# the only way this could be 0 is if we already processed it and
# nothing touched it since then, so it's safe to delete
redis.hdel('lookups', key)
else:
if script.config.cluster.role == 'master':
update_lookup_stats(db, application_id, date, hour, type, count)
else:
call_internal_api('update_lookup_stats', date=date, hour=hour,
application_id=application_id, type=type, count=count)
redis.hincrby('lookups', key, -count)
run_script(main)
| Handle lookup stats update on a slave server | Handle lookup stats update on a slave server
| Python | mit | lalinsky/acoustid-server,lalinsky/acoustid-server,lalinsky/acoustid-server,lalinsky/acoustid-server |
import re
+ import urllib
+ import urllib2
from contextlib import closing
from acoustid.script import run_script
from acoustid.data.stats import update_lookup_stats
+
+
+ def call_internal_api(func, **kwargs):
+ url = script.config.cluster.base_master_url.rstrip('/') + '/v2/internal/' + func
+ data = dict(kwargs)
+ data['secret'] = script.config.cluster.secret
+ urllib2.urlopen(url, urllib.urlencode(data))
def main(script, opts, args):
db = script.engine.connect()
redis = script.redis
for key, count in redis.hgetall('lookups').iteritems():
count = int(count)
date, hour, application_id, type = key.split(':')
if not count:
# the only way this could be 0 is if we already processed it and
# nothing touched it since then, so it's safe to delete
redis.hdel('lookups', key)
else:
+ if script.config.cluster.role == 'master':
- update_lookup_stats(db, application_id, date, hour, type, count)
+ update_lookup_stats(db, application_id, date, hour, type, count)
+ else:
+ call_internal_api('update_lookup_stats', date=date, hour=hour,
+ application_id=application_id, type=type, count=count)
redis.hincrby('lookups', key, -count)
run_script(main)
| Handle lookup stats update on a slave server | ## Code Before:
import re
from contextlib import closing
from acoustid.script import run_script
from acoustid.data.stats import update_lookup_stats
def main(script, opts, args):
db = script.engine.connect()
redis = script.redis
for key, count in redis.hgetall('lookups').iteritems():
count = int(count)
date, hour, application_id, type = key.split(':')
if not count:
# the only way this could be 0 is if we already processed it and
# nothing touched it since then, so it's safe to delete
redis.hdel('lookups', key)
else:
update_lookup_stats(db, application_id, date, hour, type, count)
redis.hincrby('lookups', key, -count)
run_script(main)
## Instruction:
Handle lookup stats update on a slave server
## Code After:
import re
import urllib
import urllib2
from contextlib import closing
from acoustid.script import run_script
from acoustid.data.stats import update_lookup_stats
def call_internal_api(func, **kwargs):
url = script.config.cluster.base_master_url.rstrip('/') + '/v2/internal/' + func
data = dict(kwargs)
data['secret'] = script.config.cluster.secret
urllib2.urlopen(url, urllib.urlencode(data))
def main(script, opts, args):
db = script.engine.connect()
redis = script.redis
for key, count in redis.hgetall('lookups').iteritems():
count = int(count)
date, hour, application_id, type = key.split(':')
if not count:
# the only way this could be 0 is if we already processed it and
# nothing touched it since then, so it's safe to delete
redis.hdel('lookups', key)
else:
if script.config.cluster.role == 'master':
update_lookup_stats(db, application_id, date, hour, type, count)
else:
call_internal_api('update_lookup_stats', date=date, hour=hour,
application_id=application_id, type=type, count=count)
redis.hincrby('lookups', key, -count)
run_script(main)
|
a797f4862ccfdb84ff87f0f64a6abdc405823215 | tests/app/na_celery/test_email_tasks.py | tests/app/na_celery/test_email_tasks.py | from app.na_celery.email_tasks import send_emails
class WhenProcessingSendEmailsTask:
def it_calls_send_email_to_task(self, mocker, db, db_session, sample_admin_user, sample_email):
mock_send_email = mocker.patch('app.na_celery.email_tasks.send_email')
send_emails(sample_email.id)
assert mock_send_email.call_args[0][0] == '[email protected]'
assert mock_send_email.call_args[0][1] == 'workshop: test title'
def it_sends_an_email_to_members_up_to_email_limit(self):
pass
def it_does_not_send_an_email_if_not_between_start_and_expiry(self):
pass
def it_sends_email_with_correct_template(self):
pass
| from app.na_celery.email_tasks import send_emails
class WhenProcessingSendEmailsTask:
def it_calls_send_email_to_task(self, mocker, db, db_session, sample_email, sample_member):
mock_send_email = mocker.patch('app.na_celery.email_tasks.send_email', return_value=200)
send_emails(sample_email.id)
assert mock_send_email.call_args[0][0] == sample_member.email
assert mock_send_email.call_args[0][1] == 'workshop: test title'
def it_sends_an_email_to_members_up_to_email_limit(self):
pass
def it_does_not_send_an_email_if_not_between_start_and_expiry(self):
pass
def it_sends_email_with_correct_template(self):
pass
| Update email task test for members | Update email task test for members
| Python | mit | NewAcropolis/api,NewAcropolis/api,NewAcropolis/api | from app.na_celery.email_tasks import send_emails
class WhenProcessingSendEmailsTask:
- def it_calls_send_email_to_task(self, mocker, db, db_session, sample_admin_user, sample_email):
+ def it_calls_send_email_to_task(self, mocker, db, db_session, sample_email, sample_member):
- mock_send_email = mocker.patch('app.na_celery.email_tasks.send_email')
+ mock_send_email = mocker.patch('app.na_celery.email_tasks.send_email', return_value=200)
send_emails(sample_email.id)
- assert mock_send_email.call_args[0][0] == '[email protected]'
+ assert mock_send_email.call_args[0][0] == sample_member.email
assert mock_send_email.call_args[0][1] == 'workshop: test title'
def it_sends_an_email_to_members_up_to_email_limit(self):
pass
def it_does_not_send_an_email_if_not_between_start_and_expiry(self):
pass
def it_sends_email_with_correct_template(self):
pass
| Update email task test for members | ## Code Before:
from app.na_celery.email_tasks import send_emails
class WhenProcessingSendEmailsTask:
def it_calls_send_email_to_task(self, mocker, db, db_session, sample_admin_user, sample_email):
mock_send_email = mocker.patch('app.na_celery.email_tasks.send_email')
send_emails(sample_email.id)
assert mock_send_email.call_args[0][0] == '[email protected]'
assert mock_send_email.call_args[0][1] == 'workshop: test title'
def it_sends_an_email_to_members_up_to_email_limit(self):
pass
def it_does_not_send_an_email_if_not_between_start_and_expiry(self):
pass
def it_sends_email_with_correct_template(self):
pass
## Instruction:
Update email task test for members
## Code After:
from app.na_celery.email_tasks import send_emails
class WhenProcessingSendEmailsTask:
def it_calls_send_email_to_task(self, mocker, db, db_session, sample_email, sample_member):
mock_send_email = mocker.patch('app.na_celery.email_tasks.send_email', return_value=200)
send_emails(sample_email.id)
assert mock_send_email.call_args[0][0] == sample_member.email
assert mock_send_email.call_args[0][1] == 'workshop: test title'
def it_sends_an_email_to_members_up_to_email_limit(self):
pass
def it_does_not_send_an_email_if_not_between_start_and_expiry(self):
pass
def it_sends_email_with_correct_template(self):
pass
|
05fc957280fecbc99c8f58897a06e23dcc4b9453 | elections/uk/forms.py | elections/uk/forms.py |
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import ValidationError
from candidates.mapit import BaseMapItException
from popolo.models import Area
from compat import text_type
from .mapit import get_areas_from_postcode
class PostcodeForm(forms.Form):
q = forms.CharField(
label='Enter a candidate name or postcode',
max_length=200,
widget=forms.TextInput(attrs={'placeholder': 'Enter a name'})
)
def clean_postcode(self):
postcode = self.cleaned_data['postcode']
try:
# Go to MapIt to check if this postcode is valid and
# contained in a constituency. (If it's valid then the
# result is cached, so this doesn't cause a double lookup.)
get_areas_from_postcode(postcode)
except BaseMapItException as e:
raise ValidationError(text_type(e))
return postcode
|
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import ValidationError
from candidates.mapit import BaseMapItException
from popolo.models import Area
from compat import text_type
from .mapit import get_areas_from_postcode
class PostcodeForm(forms.Form):
q = forms.CharField(
label='Enter a candidate name or postcode',
max_length=200,
widget=forms.TextInput(attrs={'placeholder': 'Enter a name'})
)
def clean_q(self):
postcode = self.cleaned_data['q']
try:
# Go to MapIt to check if this postcode is valid and
# contained in a constituency. (If it's valid then the
# result is cached, so this doesn't cause a double lookup.)
get_areas_from_postcode(postcode)
except BaseMapItException as e:
raise ValidationError(text_type(e))
return postcode
| Fix the postcode form so that it's actually validating the input | Fix the postcode form so that it's actually validating the input
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative |
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import ValidationError
from candidates.mapit import BaseMapItException
from popolo.models import Area
from compat import text_type
from .mapit import get_areas_from_postcode
class PostcodeForm(forms.Form):
q = forms.CharField(
label='Enter a candidate name or postcode',
max_length=200,
widget=forms.TextInput(attrs={'placeholder': 'Enter a name'})
)
- def clean_postcode(self):
+ def clean_q(self):
- postcode = self.cleaned_data['postcode']
+ postcode = self.cleaned_data['q']
try:
# Go to MapIt to check if this postcode is valid and
# contained in a constituency. (If it's valid then the
# result is cached, so this doesn't cause a double lookup.)
get_areas_from_postcode(postcode)
except BaseMapItException as e:
raise ValidationError(text_type(e))
return postcode
| Fix the postcode form so that it's actually validating the input | ## Code Before:
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import ValidationError
from candidates.mapit import BaseMapItException
from popolo.models import Area
from compat import text_type
from .mapit import get_areas_from_postcode
class PostcodeForm(forms.Form):
q = forms.CharField(
label='Enter a candidate name or postcode',
max_length=200,
widget=forms.TextInput(attrs={'placeholder': 'Enter a name'})
)
def clean_postcode(self):
postcode = self.cleaned_data['postcode']
try:
# Go to MapIt to check if this postcode is valid and
# contained in a constituency. (If it's valid then the
# result is cached, so this doesn't cause a double lookup.)
get_areas_from_postcode(postcode)
except BaseMapItException as e:
raise ValidationError(text_type(e))
return postcode
## Instruction:
Fix the postcode form so that it's actually validating the input
## Code After:
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import ValidationError
from candidates.mapit import BaseMapItException
from popolo.models import Area
from compat import text_type
from .mapit import get_areas_from_postcode
class PostcodeForm(forms.Form):
q = forms.CharField(
label='Enter a candidate name or postcode',
max_length=200,
widget=forms.TextInput(attrs={'placeholder': 'Enter a name'})
)
def clean_q(self):
postcode = self.cleaned_data['q']
try:
# Go to MapIt to check if this postcode is valid and
# contained in a constituency. (If it's valid then the
# result is cached, so this doesn't cause a double lookup.)
get_areas_from_postcode(postcode)
except BaseMapItException as e:
raise ValidationError(text_type(e))
return postcode
|
5a7b3e024eba2e279ada9aa33352046ab35b28f5 | tests/test_io.py | tests/test_io.py | """ Test the virtual IO system. """
from StringIO import StringIO
import sys
import os
from mock import call
from mock import patch
import pytest
sys.path.append(os.path.join('..', '..', 'snake'))
from snake.vm import System
@pytest.fixture()
def system():
""" Fixture to load a new VM. """
return System()
def test_io_load_file(system):
""" Test loading a file. """
test_file = StringIO("hello world")
system.load_file(test_file)
assert system.get_input() == 'hello world'
def test_io_stdout(system):
""" Test IO output. """
with patch('__builtin__.print') as mock_print:
system.stdout('hello world')
mock_print.assert_has_calls([
call('hello world')
])
| """ Test the virtual IO system. """
from io import BytesIO
import sys
import os
from mock import call
from mock import patch
import pytest
sys.path.append(os.path.join('..', '..', 'snake'))
from snake.vm import System
@pytest.fixture()
def system():
""" Fixture to load a new VM. """
return System()
def test_io_load_file(system):
""" Test loading a file. """
test_file = BytesIO("hello world")
system.load_file(test_file)
assert system.get_input() == 'hello world'
def test_io_stdout(system):
""" Test IO output. """
with patch('__builtin__.print') as mock_print:
system.stdout('hello world')
mock_print.assert_has_calls([
call('hello world')
])
| Remove StringIO in favor of BytesIO. | Remove StringIO in favor of BytesIO.
| Python | bsd-3-clause | travcunn/snake-vm | """ Test the virtual IO system. """
- from StringIO import StringIO
+ from io import BytesIO
import sys
import os
from mock import call
from mock import patch
import pytest
sys.path.append(os.path.join('..', '..', 'snake'))
from snake.vm import System
@pytest.fixture()
def system():
""" Fixture to load a new VM. """
return System()
def test_io_load_file(system):
""" Test loading a file. """
- test_file = StringIO("hello world")
+ test_file = BytesIO("hello world")
system.load_file(test_file)
assert system.get_input() == 'hello world'
def test_io_stdout(system):
""" Test IO output. """
with patch('__builtin__.print') as mock_print:
system.stdout('hello world')
mock_print.assert_has_calls([
call('hello world')
])
| Remove StringIO in favor of BytesIO. | ## Code Before:
""" Test the virtual IO system. """
from StringIO import StringIO
import sys
import os
from mock import call
from mock import patch
import pytest
sys.path.append(os.path.join('..', '..', 'snake'))
from snake.vm import System
@pytest.fixture()
def system():
""" Fixture to load a new VM. """
return System()
def test_io_load_file(system):
""" Test loading a file. """
test_file = StringIO("hello world")
system.load_file(test_file)
assert system.get_input() == 'hello world'
def test_io_stdout(system):
""" Test IO output. """
with patch('__builtin__.print') as mock_print:
system.stdout('hello world')
mock_print.assert_has_calls([
call('hello world')
])
## Instruction:
Remove StringIO in favor of BytesIO.
## Code After:
""" Test the virtual IO system. """
from io import BytesIO
import sys
import os
from mock import call
from mock import patch
import pytest
sys.path.append(os.path.join('..', '..', 'snake'))
from snake.vm import System
@pytest.fixture()
def system():
""" Fixture to load a new VM. """
return System()
def test_io_load_file(system):
""" Test loading a file. """
test_file = BytesIO("hello world")
system.load_file(test_file)
assert system.get_input() == 'hello world'
def test_io_stdout(system):
""" Test IO output. """
with patch('__builtin__.print') as mock_print:
system.stdout('hello world')
mock_print.assert_has_calls([
call('hello world')
])
|
07d2ffe3c14a6c908a7bf138f40ba8d49bf7b2c3 | examples/plot_grow.py | examples/plot_grow.py |
# Code source: Óscar Nájera
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 2, 100)
y = np.exp(x)
plt.plot(x, y)
plt.xlabel('$x$')
plt.ylabel('$exp(x)$')
plt.show()
|
# Code source: Óscar Nájera
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 2, 100)
y = np.exp(x)
plt.figure()
plt.plot(x, y)
plt.xlabel('$x$')
plt.ylabel('$\exp(x)$')
plt.figure()
plt.plot(x, -np.exp(-x))
plt.xlabel('$x$')
plt.ylabel('$-\exp(-x)$')
plt.show()
| Update example for image stacking CSS instuction | Update example for image stacking CSS instuction
| Python | bsd-3-clause | lesteve/sphinx-gallery,Eric89GXL/sphinx-gallery,sphinx-gallery/sphinx-gallery,Titan-C/sphinx-gallery,lesteve/sphinx-gallery,Titan-C/sphinx-gallery,Eric89GXL/sphinx-gallery,sphinx-gallery/sphinx-gallery |
# Code source: Óscar Nájera
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 2, 100)
y = np.exp(x)
+ plt.figure()
plt.plot(x, y)
plt.xlabel('$x$')
- plt.ylabel('$exp(x)$')
+ plt.ylabel('$\exp(x)$')
+
+ plt.figure()
+ plt.plot(x, -np.exp(-x))
+ plt.xlabel('$x$')
+ plt.ylabel('$-\exp(-x)$')
+
+
plt.show()
| Update example for image stacking CSS instuction | ## Code Before:
# Code source: Óscar Nájera
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 2, 100)
y = np.exp(x)
plt.plot(x, y)
plt.xlabel('$x$')
plt.ylabel('$exp(x)$')
plt.show()
## Instruction:
Update example for image stacking CSS instuction
## Code After:
# Code source: Óscar Nájera
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 2, 100)
y = np.exp(x)
plt.figure()
plt.plot(x, y)
plt.xlabel('$x$')
plt.ylabel('$\exp(x)$')
plt.figure()
plt.plot(x, -np.exp(-x))
plt.xlabel('$x$')
plt.ylabel('$-\exp(-x)$')
plt.show()
|
be517c8df23826d343b187a4a5cc3d1f81a06b53 | test/framework/utils.py | test/framework/utils.py |
import os, re
from os.path import join as jp
from .config import flow_graph_root_dir
_http_re = re.compile(r'https?://[^/]*/')
def replace_host_port(contains_url):
return _http_re.sub('http://x.x/', contains_url)
def flow_graph_dir(flow_name):
"""
Put the generated graph in the workspace root if running from Jenkins
If running from commandline put it under config.flow_graph_root_dir/flow_name
return: dir-name
"""
return '.' if os.environ.get('JOB_NAME') else jp(flow_graph_root_dir, flow_name)
|
import os, re
from os.path import join as jp
from .config import flow_graph_root_dir
_http_re = re.compile(r'https?://.*?/job/')
def replace_host_port(contains_url):
return _http_re.sub('http://x.x/job/', contains_url)
def flow_graph_dir(flow_name):
"""
Put the generated graph in the workspace root if running from Jenkins
If running from commandline put it under config.flow_graph_root_dir/flow_name
return: dir-name
"""
return '.' if os.environ.get('JOB_NAME') else jp(flow_graph_root_dir, flow_name)
| Test framework fix - url replacing handles jenkins url with 'prefix' | Test framework fix - url replacing handles jenkins url with 'prefix'
| Python | bsd-3-clause | lhupfeldt/jenkinsflow,lhupfeldt/jenkinsflow,lhupfeldt/jenkinsflow,lhupfeldt/jenkinsflow,lechat/jenkinsflow,lechat/jenkinsflow,lechat/jenkinsflow,lechat/jenkinsflow |
import os, re
from os.path import join as jp
from .config import flow_graph_root_dir
- _http_re = re.compile(r'https?://[^/]*/')
+ _http_re = re.compile(r'https?://.*?/job/')
def replace_host_port(contains_url):
- return _http_re.sub('http://x.x/', contains_url)
+ return _http_re.sub('http://x.x/job/', contains_url)
def flow_graph_dir(flow_name):
"""
Put the generated graph in the workspace root if running from Jenkins
If running from commandline put it under config.flow_graph_root_dir/flow_name
return: dir-name
"""
return '.' if os.environ.get('JOB_NAME') else jp(flow_graph_root_dir, flow_name)
| Test framework fix - url replacing handles jenkins url with 'prefix' | ## Code Before:
import os, re
from os.path import join as jp
from .config import flow_graph_root_dir
_http_re = re.compile(r'https?://[^/]*/')
def replace_host_port(contains_url):
return _http_re.sub('http://x.x/', contains_url)
def flow_graph_dir(flow_name):
"""
Put the generated graph in the workspace root if running from Jenkins
If running from commandline put it under config.flow_graph_root_dir/flow_name
return: dir-name
"""
return '.' if os.environ.get('JOB_NAME') else jp(flow_graph_root_dir, flow_name)
## Instruction:
Test framework fix - url replacing handles jenkins url with 'prefix'
## Code After:
import os, re
from os.path import join as jp
from .config import flow_graph_root_dir
_http_re = re.compile(r'https?://.*?/job/')
def replace_host_port(contains_url):
return _http_re.sub('http://x.x/job/', contains_url)
def flow_graph_dir(flow_name):
"""
Put the generated graph in the workspace root if running from Jenkins
If running from commandline put it under config.flow_graph_root_dir/flow_name
return: dir-name
"""
return '.' if os.environ.get('JOB_NAME') else jp(flow_graph_root_dir, flow_name)
|
7418079606a6e24cb0dccfa148b47c3f736e985f | zou/app/blueprints/persons/resources.py | zou/app/blueprints/persons/resources.py | from flask import abort
from flask_restful import Resource, reqparse
from flask_jwt_extended import jwt_required
from zou.app.services import persons_service
from zou.app.utils import auth, permissions
class NewPersonResource(Resource):
@jwt_required
def post(self):
permissions.check_admin_permissions()
data = self.get_arguments()
person = persons_service.create_person(
data["email"],
auth.encrypt_password("default"),
data["first_name"],
data["last_name"],
data["phone"]
)
return person, 201
def get_arguments(self):
parser = reqparse.RequestParser()
parser.add_argument(
"email",
help="The email is required.",
required=True
)
parser.add_argument(
"first_name",
help="The first name is required.",
required=True
)
parser.add_argument(
"last_name",
help="The last name is required.",
required=True
)
parser.add_argument("phone", default="")
args = parser.parse_args()
return args
| from flask import abort
from flask_restful import Resource, reqparse
from flask_jwt_extended import jwt_required
from zou.app.services import persons_service
from zou.app.utils import auth, permissions
class NewPersonResource(Resource):
@jwt_required
def post(self):
permissions.check_admin_permissions()
data = self.get_arguments()
person = persons_service.create_person(
data["email"],
auth.encrypt_password("default"),
data["first_name"],
data["last_name"],
data["phone"],
role=data["role"]
)
return person, 201
def get_arguments(self):
parser = reqparse.RequestParser()
parser.add_argument(
"email",
help="The email is required.",
required=True
)
parser.add_argument(
"first_name",
help="The first name is required.",
required=True
)
parser.add_argument(
"last_name",
help="The last name is required.",
required=True
)
parser.add_argument("phone", default="")
parser.add_argument("role", default="user")
args = parser.parse_args()
return args
| Allow to set role while creating a person | Allow to set role while creating a person
| Python | agpl-3.0 | cgwire/zou | from flask import abort
from flask_restful import Resource, reqparse
from flask_jwt_extended import jwt_required
from zou.app.services import persons_service
from zou.app.utils import auth, permissions
class NewPersonResource(Resource):
@jwt_required
def post(self):
permissions.check_admin_permissions()
data = self.get_arguments()
person = persons_service.create_person(
data["email"],
auth.encrypt_password("default"),
data["first_name"],
data["last_name"],
- data["phone"]
+ data["phone"],
+ role=data["role"]
)
return person, 201
def get_arguments(self):
parser = reqparse.RequestParser()
parser.add_argument(
"email",
help="The email is required.",
required=True
)
parser.add_argument(
"first_name",
help="The first name is required.",
required=True
)
parser.add_argument(
"last_name",
help="The last name is required.",
required=True
)
parser.add_argument("phone", default="")
+ parser.add_argument("role", default="user")
args = parser.parse_args()
return args
| Allow to set role while creating a person | ## Code Before:
from flask import abort
from flask_restful import Resource, reqparse
from flask_jwt_extended import jwt_required
from zou.app.services import persons_service
from zou.app.utils import auth, permissions
class NewPersonResource(Resource):
@jwt_required
def post(self):
permissions.check_admin_permissions()
data = self.get_arguments()
person = persons_service.create_person(
data["email"],
auth.encrypt_password("default"),
data["first_name"],
data["last_name"],
data["phone"]
)
return person, 201
def get_arguments(self):
parser = reqparse.RequestParser()
parser.add_argument(
"email",
help="The email is required.",
required=True
)
parser.add_argument(
"first_name",
help="The first name is required.",
required=True
)
parser.add_argument(
"last_name",
help="The last name is required.",
required=True
)
parser.add_argument("phone", default="")
args = parser.parse_args()
return args
## Instruction:
Allow to set role while creating a person
## Code After:
from flask import abort
from flask_restful import Resource, reqparse
from flask_jwt_extended import jwt_required
from zou.app.services import persons_service
from zou.app.utils import auth, permissions
class NewPersonResource(Resource):
@jwt_required
def post(self):
permissions.check_admin_permissions()
data = self.get_arguments()
person = persons_service.create_person(
data["email"],
auth.encrypt_password("default"),
data["first_name"],
data["last_name"],
data["phone"],
role=data["role"]
)
return person, 201
def get_arguments(self):
parser = reqparse.RequestParser()
parser.add_argument(
"email",
help="The email is required.",
required=True
)
parser.add_argument(
"first_name",
help="The first name is required.",
required=True
)
parser.add_argument(
"last_name",
help="The last name is required.",
required=True
)
parser.add_argument("phone", default="")
parser.add_argument("role", default="user")
args = parser.parse_args()
return args
|
a95b1b2b5331e4248fe1d80244c763df4d3aca41 | taiga/urls.py | taiga/urls.py |
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from .routers import router
admin.autodiscover()
urlpatterns = patterns('',
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^admin/', include(admin.site.urls)),
)
def mediafiles_urlpatterns():
"""
Method for serve media files with runserver.
"""
_media_url = settings.MEDIA_URL
if _media_url.startswith('/'):
_media_url = _media_url[1:]
from django.views.static import serve
return patterns('',
(r'^%s(?P<path>.*)$' % 'media', serve,
{'document_root': settings.MEDIA_ROOT})
)
urlpatterns += staticfiles_urlpatterns()
urlpatterns += mediafiles_urlpatterns()
|
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from .routers import router
admin.autodiscover()
urlpatterns = patterns('',
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^admin/', include(admin.site.urls)),
)
def mediafiles_urlpatterns():
"""
Method for serve media files with runserver.
"""
_media_url = settings.MEDIA_URL
if _media_url.startswith('/'):
_media_url = _media_url[1:]
from django.views.static import serve
return patterns('',
(r'^%s(?P<path>.*)$' % 'media', serve,
{'document_root': settings.MEDIA_ROOT})
)
urlpatterns += staticfiles_urlpatterns(prefix="/static/")
urlpatterns += mediafiles_urlpatterns()
| Set prefix to static url patterm call | Set prefix to static url patterm call
| Python | agpl-3.0 | jeffdwyatt/taiga-back,bdang2012/taiga-back-casting,WALR/taiga-back,seanchen/taiga-back,gam-phon/taiga-back,EvgeneOskin/taiga-back,CoolCloud/taiga-back,WALR/taiga-back,Rademade/taiga-back,seanchen/taiga-back,taigaio/taiga-back,astronaut1712/taiga-back,astronaut1712/taiga-back,taigaio/taiga-back,xdevelsistemas/taiga-back-community,coopsource/taiga-back,astagi/taiga-back,coopsource/taiga-back,CMLL/taiga-back,gauravjns/taiga-back,Rademade/taiga-back,EvgeneOskin/taiga-back,dycodedev/taiga-back,CMLL/taiga-back,astagi/taiga-back,dayatz/taiga-back,19kestier/taiga-back,19kestier/taiga-back,coopsource/taiga-back,obimod/taiga-back,rajiteh/taiga-back,crr0004/taiga-back,bdang2012/taiga-back-casting,gauravjns/taiga-back,gam-phon/taiga-back,forging2012/taiga-back,CoolCloud/taiga-back,astagi/taiga-back,19kestier/taiga-back,CoolCloud/taiga-back,bdang2012/taiga-back-casting,dayatz/taiga-back,Rademade/taiga-back,forging2012/taiga-back,dycodedev/taiga-back,jeffdwyatt/taiga-back,taigaio/taiga-back,dayatz/taiga-back,crr0004/taiga-back,xdevelsistemas/taiga-back-community,Tigerwhit4/taiga-back,Tigerwhit4/taiga-back,obimod/taiga-back,Zaneh-/bearded-tribble-back,jeffdwyatt/taiga-back,crr0004/taiga-back,rajiteh/taiga-back,Zaneh-/bearded-tribble-back,obimod/taiga-back,rajiteh/taiga-back,dycodedev/taiga-back,bdang2012/taiga-back-casting,frt-arch/taiga-back,dycodedev/taiga-back,joshisa/taiga-back,Zaneh-/bearded-tribble-back,astronaut1712/taiga-back,forging2012/taiga-back,CoolCloud/taiga-back,Rademade/taiga-back,Tigerwhit4/taiga-back,gauravjns/taiga-back,CMLL/taiga-back,WALR/taiga-back,joshisa/taiga-back,obimod/taiga-back,jeffdwyatt/taiga-back,forging2012/taiga-back,astagi/taiga-back,xdevelsistemas/taiga-back-community,gauravjns/taiga-back,coopsource/taiga-back,joshisa/taiga-back,crr0004/taiga-back,EvgeneOskin/taiga-back,EvgeneOskin/taiga-back,frt-arch/taiga-back,CMLL/taiga-back,seanchen/taiga-back,gam-phon/taiga-back,gam-phon/taiga-back,Tigerwhit4/taiga-back,Rademade/taiga-back,frt-arch/taiga-back,seanchen/taiga-back,WALR/taiga-back,astronaut1712/taiga-back,joshisa/taiga-back,rajiteh/taiga-back |
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from .routers import router
admin.autodiscover()
urlpatterns = patterns('',
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^admin/', include(admin.site.urls)),
)
def mediafiles_urlpatterns():
"""
Method for serve media files with runserver.
"""
_media_url = settings.MEDIA_URL
if _media_url.startswith('/'):
_media_url = _media_url[1:]
from django.views.static import serve
return patterns('',
(r'^%s(?P<path>.*)$' % 'media', serve,
{'document_root': settings.MEDIA_ROOT})
)
- urlpatterns += staticfiles_urlpatterns()
+ urlpatterns += staticfiles_urlpatterns(prefix="/static/")
urlpatterns += mediafiles_urlpatterns()
| Set prefix to static url patterm call | ## Code Before:
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from .routers import router
admin.autodiscover()
urlpatterns = patterns('',
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^admin/', include(admin.site.urls)),
)
def mediafiles_urlpatterns():
"""
Method for serve media files with runserver.
"""
_media_url = settings.MEDIA_URL
if _media_url.startswith('/'):
_media_url = _media_url[1:]
from django.views.static import serve
return patterns('',
(r'^%s(?P<path>.*)$' % 'media', serve,
{'document_root': settings.MEDIA_ROOT})
)
urlpatterns += staticfiles_urlpatterns()
urlpatterns += mediafiles_urlpatterns()
## Instruction:
Set prefix to static url patterm call
## Code After:
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from .routers import router
admin.autodiscover()
urlpatterns = patterns('',
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^admin/', include(admin.site.urls)),
)
def mediafiles_urlpatterns():
"""
Method for serve media files with runserver.
"""
_media_url = settings.MEDIA_URL
if _media_url.startswith('/'):
_media_url = _media_url[1:]
from django.views.static import serve
return patterns('',
(r'^%s(?P<path>.*)$' % 'media', serve,
{'document_root': settings.MEDIA_ROOT})
)
urlpatterns += staticfiles_urlpatterns(prefix="/static/")
urlpatterns += mediafiles_urlpatterns()
|
31af4bf93b8177e8ac03ef96bec926551b40fdcb | cogs/common/types.py | cogs/common/types.py |
from multidict import MultiDictProxy as Cookies # Type of aiohttp.web.BaseRequest.cookies
from sqlalchemy.orm import Session as DBSession # Return from sqlalchemy.orm.sessionmaker
|
from aiohttp.web import Application # aiohttp web server application
from multidict import MultiDictProxy as Cookies # Type of aiohttp.web.BaseRequest.cookies
from sqlalchemy.orm import Session as DBSession # Return from sqlalchemy.orm.sessionmaker
| Add aiohttp.web.Application into type aliases | Add aiohttp.web.Application into type aliases
| Python | agpl-3.0 | wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp |
+ from aiohttp.web import Application # aiohttp web server application
from multidict import MultiDictProxy as Cookies # Type of aiohttp.web.BaseRequest.cookies
from sqlalchemy.orm import Session as DBSession # Return from sqlalchemy.orm.sessionmaker
| Add aiohttp.web.Application into type aliases | ## Code Before:
from multidict import MultiDictProxy as Cookies # Type of aiohttp.web.BaseRequest.cookies
from sqlalchemy.orm import Session as DBSession # Return from sqlalchemy.orm.sessionmaker
## Instruction:
Add aiohttp.web.Application into type aliases
## Code After:
from aiohttp.web import Application # aiohttp web server application
from multidict import MultiDictProxy as Cookies # Type of aiohttp.web.BaseRequest.cookies
from sqlalchemy.orm import Session as DBSession # Return from sqlalchemy.orm.sessionmaker
|
d495d9500377bad5c7ccfd15037fb4d03fd7bff3 | videolog/user.py | videolog/user.py | from datetime import datetime
import time
import json
from videolog.core import Videolog
class User(Videolog):
def find_videos(self, user):
content = self._make_request('GET', '/usuario/%s/videos.json' % user)
usuario = json.loads(content)
response = []
for video in usuario['usuario']['videos']:
video['criacao'] = datetime.strptime(video['criacao'], "%Y-%m-%dT%H:%M:%S")
video["duracao"] = time.strptime("00:00:05", "%H:%M:%S")
if video['mobile'].lower() == "s":
video['mobile'] = True
else:
video['mobile'] = False
response.append(video)
return response | from datetime import datetime
import time
import json
from videolog.core import Videolog
class User(Videolog):
def find_videos(self, user, privacy=None):
path = '/usuario/%s/videos.json' % user
if privacy is not None:
path = "%s?privacidade=%s" % (path, privacy)
content = self._make_request('GET', path)
usuario = json.loads(content)
response = []
for video in usuario['usuario']['videos']:
video['criacao'] = datetime.strptime(video['criacao'], "%Y-%m-%dT%H:%M:%S")
video["duracao"] = time.strptime("00:00:05", "%H:%M:%S")
if video['mobile'].lower() == "s":
video['mobile'] = True
else:
video['mobile'] = False
response.append(video)
return response | Add privacy parameter to User.find_videos | Add privacy parameter to User.find_videos
| Python | mit | rcmachado/pyvideolog | from datetime import datetime
import time
import json
from videolog.core import Videolog
class User(Videolog):
- def find_videos(self, user):
+ def find_videos(self, user, privacy=None):
- content = self._make_request('GET', '/usuario/%s/videos.json' % user)
+ path = '/usuario/%s/videos.json' % user
+ if privacy is not None:
+ path = "%s?privacidade=%s" % (path, privacy)
+
+ content = self._make_request('GET', path)
usuario = json.loads(content)
response = []
for video in usuario['usuario']['videos']:
video['criacao'] = datetime.strptime(video['criacao'], "%Y-%m-%dT%H:%M:%S")
video["duracao"] = time.strptime("00:00:05", "%H:%M:%S")
if video['mobile'].lower() == "s":
video['mobile'] = True
else:
video['mobile'] = False
response.append(video)
return response | Add privacy parameter to User.find_videos | ## Code Before:
from datetime import datetime
import time
import json
from videolog.core import Videolog
class User(Videolog):
def find_videos(self, user):
content = self._make_request('GET', '/usuario/%s/videos.json' % user)
usuario = json.loads(content)
response = []
for video in usuario['usuario']['videos']:
video['criacao'] = datetime.strptime(video['criacao'], "%Y-%m-%dT%H:%M:%S")
video["duracao"] = time.strptime("00:00:05", "%H:%M:%S")
if video['mobile'].lower() == "s":
video['mobile'] = True
else:
video['mobile'] = False
response.append(video)
return response
## Instruction:
Add privacy parameter to User.find_videos
## Code After:
from datetime import datetime
import time
import json
from videolog.core import Videolog
class User(Videolog):
def find_videos(self, user, privacy=None):
path = '/usuario/%s/videos.json' % user
if privacy is not None:
path = "%s?privacidade=%s" % (path, privacy)
content = self._make_request('GET', path)
usuario = json.loads(content)
response = []
for video in usuario['usuario']['videos']:
video['criacao'] = datetime.strptime(video['criacao'], "%Y-%m-%dT%H:%M:%S")
video["duracao"] = time.strptime("00:00:05", "%H:%M:%S")
if video['mobile'].lower() == "s":
video['mobile'] = True
else:
video['mobile'] = False
response.append(video)
return response |
9d1a53fea17dfc8d48324e510273259615fbee01 | pivoteer/writer/hosts.py | pivoteer/writer/hosts.py | import dateutil.parser
from pivoteer.writer.core import CsvWriter
from core.lookups import geolocate_ip
class HostCsvWriter(CsvWriter):
"""
A CsvWriter implementation for IndicatorRecord objects with a record type of "HR" (Host Record)
"""
def __init__(self, writer):
"""
Create a new CsvWriter for Host Records using the given writer.
:param writer: The writer
"""
super(HostCsvWriter, self).__init__(writer)
def create_header(self):
return ["Date", "Source", "Domain", "IP", "IP Location", "First Seen", "Last Seen"]
def create_rows(self, record):
if record is not None:
yield [record["info_date"],
record["get_info_source_display"],
record["domain"],
record["ip"],
record["location"]["country"],
record["firstseen"],
record["lastseen"]]
| import dateutil.parser
from pivoteer.writer.core import CsvWriter
from core.lookups import geolocate_ip
class HostCsvWriter(CsvWriter):
"""
A CsvWriter implementation for IndicatorRecord objects with a record type of "HR" (Host Record)
"""
def __init__(self, writer):
"""
Create a new CsvWriter for Host Records using the given writer.
:param writer: The writer
"""
super(HostCsvWriter, self).__init__(writer)
def create_header(self):
return ["Date", "Source", "Domain", "IP", "IP Location", "First Seen", "Last Seen"]
def create_rows(self, record):
if record is not None:
yield [record["info_date"],
record["get_info_source_display"],
record["info"]["domain"],
record["info"]["ip"],
record["location"]["country"],
record["info"]["firstseen"],
record["info"]["lastseen"]]
| Update historical export with latest data model changes | Update historical export with latest data model changes
| Python | mit | LindaTNguyen/RAPID,LindaTNguyen/RAPID,gdit-cnd/RAPID,gdit-cnd/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID,LindaTNguyen/RAPID,gdit-cnd/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID | import dateutil.parser
from pivoteer.writer.core import CsvWriter
from core.lookups import geolocate_ip
class HostCsvWriter(CsvWriter):
"""
A CsvWriter implementation for IndicatorRecord objects with a record type of "HR" (Host Record)
"""
def __init__(self, writer):
"""
Create a new CsvWriter for Host Records using the given writer.
:param writer: The writer
"""
super(HostCsvWriter, self).__init__(writer)
def create_header(self):
return ["Date", "Source", "Domain", "IP", "IP Location", "First Seen", "Last Seen"]
def create_rows(self, record):
if record is not None:
yield [record["info_date"],
record["get_info_source_display"],
- record["domain"],
+ record["info"]["domain"],
- record["ip"],
+ record["info"]["ip"],
record["location"]["country"],
- record["firstseen"],
+ record["info"]["firstseen"],
- record["lastseen"]]
+ record["info"]["lastseen"]]
| Update historical export with latest data model changes | ## Code Before:
import dateutil.parser
from pivoteer.writer.core import CsvWriter
from core.lookups import geolocate_ip
class HostCsvWriter(CsvWriter):
"""
A CsvWriter implementation for IndicatorRecord objects with a record type of "HR" (Host Record)
"""
def __init__(self, writer):
"""
Create a new CsvWriter for Host Records using the given writer.
:param writer: The writer
"""
super(HostCsvWriter, self).__init__(writer)
def create_header(self):
return ["Date", "Source", "Domain", "IP", "IP Location", "First Seen", "Last Seen"]
def create_rows(self, record):
if record is not None:
yield [record["info_date"],
record["get_info_source_display"],
record["domain"],
record["ip"],
record["location"]["country"],
record["firstseen"],
record["lastseen"]]
## Instruction:
Update historical export with latest data model changes
## Code After:
import dateutil.parser
from pivoteer.writer.core import CsvWriter
from core.lookups import geolocate_ip
class HostCsvWriter(CsvWriter):
"""
A CsvWriter implementation for IndicatorRecord objects with a record type of "HR" (Host Record)
"""
def __init__(self, writer):
"""
Create a new CsvWriter for Host Records using the given writer.
:param writer: The writer
"""
super(HostCsvWriter, self).__init__(writer)
def create_header(self):
return ["Date", "Source", "Domain", "IP", "IP Location", "First Seen", "Last Seen"]
def create_rows(self, record):
if record is not None:
yield [record["info_date"],
record["get_info_source_display"],
record["info"]["domain"],
record["info"]["ip"],
record["location"]["country"],
record["info"]["firstseen"],
record["info"]["lastseen"]]
|
06eabe9986edfb3c26b2faebb9e07ede72e4781d | wush/utils.py | wush/utils.py | import rq
import redis
import django
from django.conf import settings
REDIS_CLIENT = redis.Redis(settings.REDIS_HOST, settings.REDIS_PORT, db=0)
class CustomJob(rq.job.Job):
def _unpickle_data(self):
django.setup()
super(CustomJob, self)._unpickle_data()
class CustomQueue(rq.Queue):
def __init__(self, *args, **kwargs):
kwargs["connection"] = REDIS_CLIENT
kwargs["job_class"] = CustomJob
super(CustomQueue, self).__init__(*args, **kwargs)
| import rq
import redis
import django
from django.conf import settings
REDIS_CLIENT = redis.Redis(settings.REDIS_HOST, settings.REDIS_PORT, db=0)
class CustomJob(rq.job.Job):
def _unpickle_data(self):
django.setup()
super(CustomJob, self)._unpickle_data()
class CustomQueue(rq.Queue):
job_class = CustomJob
def __init__(self, *args, **kwargs):
kwargs["connection"] = REDIS_CLIENT
super(CustomQueue, self).__init__(*args, **kwargs)
| Use the existing class property job_class. | Use the existing class property job_class.
| Python | mit | theju/wush | import rq
import redis
import django
from django.conf import settings
REDIS_CLIENT = redis.Redis(settings.REDIS_HOST, settings.REDIS_PORT, db=0)
class CustomJob(rq.job.Job):
def _unpickle_data(self):
django.setup()
super(CustomJob, self)._unpickle_data()
class CustomQueue(rq.Queue):
+ job_class = CustomJob
+
def __init__(self, *args, **kwargs):
kwargs["connection"] = REDIS_CLIENT
- kwargs["job_class"] = CustomJob
super(CustomQueue, self).__init__(*args, **kwargs)
| Use the existing class property job_class. | ## Code Before:
import rq
import redis
import django
from django.conf import settings
REDIS_CLIENT = redis.Redis(settings.REDIS_HOST, settings.REDIS_PORT, db=0)
class CustomJob(rq.job.Job):
def _unpickle_data(self):
django.setup()
super(CustomJob, self)._unpickle_data()
class CustomQueue(rq.Queue):
def __init__(self, *args, **kwargs):
kwargs["connection"] = REDIS_CLIENT
kwargs["job_class"] = CustomJob
super(CustomQueue, self).__init__(*args, **kwargs)
## Instruction:
Use the existing class property job_class.
## Code After:
import rq
import redis
import django
from django.conf import settings
REDIS_CLIENT = redis.Redis(settings.REDIS_HOST, settings.REDIS_PORT, db=0)
class CustomJob(rq.job.Job):
def _unpickle_data(self):
django.setup()
super(CustomJob, self)._unpickle_data()
class CustomQueue(rq.Queue):
job_class = CustomJob
def __init__(self, *args, **kwargs):
kwargs["connection"] = REDIS_CLIENT
super(CustomQueue, self).__init__(*args, **kwargs)
|
5c3900e12216164712c9e7fe7ea064e70fae8d1b | enumfields/enums.py | enumfields/enums.py | import inspect
from django.utils.encoding import force_bytes, python_2_unicode_compatible
from enum import Enum as BaseEnum, EnumMeta as BaseEnumMeta
import six
class EnumMeta(BaseEnumMeta):
def __new__(cls, name, bases, attrs):
Labels = attrs.get('Labels')
if Labels is not None and inspect.isclass(Labels):
del attrs['Labels']
obj = BaseEnumMeta.__new__(cls, name, bases, attrs)
for m in obj:
try:
m.label = getattr(Labels, m.name)
except AttributeError:
m.label = m.name.replace('_', ' ').title()
return obj
@python_2_unicode_compatible
class Enum(six.with_metaclass(EnumMeta, BaseEnum)):
@classmethod
def choices(cls):
"""
Returns a list formatted for use as field choices.
(See https://docs.djangoproject.com/en/dev/ref/models/fields/#choices)
"""
return tuple((m.value, m.label) for m in cls)
def __str__(self):
"""
Show our label when Django uses the Enum for displaying in a view
"""
return force_bytes(self.label)
| import inspect
from django.utils.encoding import force_bytes, python_2_unicode_compatible
from enum import Enum as BaseEnum, EnumMeta as BaseEnumMeta
import six
class EnumMeta(BaseEnumMeta):
def __new__(cls, name, bases, attrs):
Labels = attrs.get('Labels')
if Labels is not None and inspect.isclass(Labels):
del attrs['Labels']
if hasattr(attrs, '_member_names'):
attrs._member_names.remove('Labels')
obj = BaseEnumMeta.__new__(cls, name, bases, attrs)
for m in obj:
try:
m.label = getattr(Labels, m.name)
except AttributeError:
m.label = m.name.replace('_', ' ').title()
return obj
@python_2_unicode_compatible
class Enum(six.with_metaclass(EnumMeta, BaseEnum)):
@classmethod
def choices(cls):
"""
Returns a list formatted for use as field choices.
(See https://docs.djangoproject.com/en/dev/ref/models/fields/#choices)
"""
return tuple((m.value, m.label) for m in cls)
def __str__(self):
"""
Show our label when Django uses the Enum for displaying in a view
"""
return force_bytes(self.label)
| Fix 'Labels' class in Python 3. | Fix 'Labels' class in Python 3.
In Python 3, the attrs dict will already be an _EnumDict, which has a
separate list of member names (in Python 2, it is still a plain dict at this
point).
| Python | mit | suutari-ai/django-enumfields,jackyyf/django-enumfields,bxm156/django-enumfields,jessamynsmith/django-enumfields | import inspect
from django.utils.encoding import force_bytes, python_2_unicode_compatible
from enum import Enum as BaseEnum, EnumMeta as BaseEnumMeta
import six
class EnumMeta(BaseEnumMeta):
def __new__(cls, name, bases, attrs):
Labels = attrs.get('Labels')
if Labels is not None and inspect.isclass(Labels):
del attrs['Labels']
+ if hasattr(attrs, '_member_names'):
+ attrs._member_names.remove('Labels')
obj = BaseEnumMeta.__new__(cls, name, bases, attrs)
for m in obj:
try:
m.label = getattr(Labels, m.name)
except AttributeError:
m.label = m.name.replace('_', ' ').title()
return obj
@python_2_unicode_compatible
class Enum(six.with_metaclass(EnumMeta, BaseEnum)):
@classmethod
def choices(cls):
"""
Returns a list formatted for use as field choices.
(See https://docs.djangoproject.com/en/dev/ref/models/fields/#choices)
"""
return tuple((m.value, m.label) for m in cls)
def __str__(self):
"""
Show our label when Django uses the Enum for displaying in a view
"""
return force_bytes(self.label)
| Fix 'Labels' class in Python 3. | ## Code Before:
import inspect
from django.utils.encoding import force_bytes, python_2_unicode_compatible
from enum import Enum as BaseEnum, EnumMeta as BaseEnumMeta
import six
class EnumMeta(BaseEnumMeta):
def __new__(cls, name, bases, attrs):
Labels = attrs.get('Labels')
if Labels is not None and inspect.isclass(Labels):
del attrs['Labels']
obj = BaseEnumMeta.__new__(cls, name, bases, attrs)
for m in obj:
try:
m.label = getattr(Labels, m.name)
except AttributeError:
m.label = m.name.replace('_', ' ').title()
return obj
@python_2_unicode_compatible
class Enum(six.with_metaclass(EnumMeta, BaseEnum)):
@classmethod
def choices(cls):
"""
Returns a list formatted for use as field choices.
(See https://docs.djangoproject.com/en/dev/ref/models/fields/#choices)
"""
return tuple((m.value, m.label) for m in cls)
def __str__(self):
"""
Show our label when Django uses the Enum for displaying in a view
"""
return force_bytes(self.label)
## Instruction:
Fix 'Labels' class in Python 3.
## Code After:
import inspect
from django.utils.encoding import force_bytes, python_2_unicode_compatible
from enum import Enum as BaseEnum, EnumMeta as BaseEnumMeta
import six
class EnumMeta(BaseEnumMeta):
def __new__(cls, name, bases, attrs):
Labels = attrs.get('Labels')
if Labels is not None and inspect.isclass(Labels):
del attrs['Labels']
if hasattr(attrs, '_member_names'):
attrs._member_names.remove('Labels')
obj = BaseEnumMeta.__new__(cls, name, bases, attrs)
for m in obj:
try:
m.label = getattr(Labels, m.name)
except AttributeError:
m.label = m.name.replace('_', ' ').title()
return obj
@python_2_unicode_compatible
class Enum(six.with_metaclass(EnumMeta, BaseEnum)):
@classmethod
def choices(cls):
"""
Returns a list formatted for use as field choices.
(See https://docs.djangoproject.com/en/dev/ref/models/fields/#choices)
"""
return tuple((m.value, m.label) for m in cls)
def __str__(self):
"""
Show our label when Django uses the Enum for displaying in a view
"""
return force_bytes(self.label)
|
e0d811f5146ba2c97af3da4ac904db4d16b5d9bb | python/ctci_big_o.py | python/ctci_big_o.py | p = int(input().strip())
for a0 in range(p):
n = int(input().strip())
| from collections import deque
class Sieve(object):
def __init__(self, upper_bound):
self.upper_bound = upper_bound + 1
self.primes = []
self.populate_primes()
# print("Primes " + str(self.primes))
def is_prime(self, potential_prime):
return potential_prime in self.primes
def populate_primes(self,):
remaining = deque(range(2, self.upper_bound))
while remaining:
prime = remaining.popleft()
self.primes.append(prime)
for multiple in self.multiples(prime):
if multiple in remaining:
remaining.remove(multiple)
def multiples(self, num):
return range(num, self.upper_bound, num)
NUM_CASES = int(input().strip())
TEST_CASES = []
for _ in range(NUM_CASES):
TEST_CASES.append(int(input().strip()))
# print("Max: " + str(max(TEST_CASES)))
SIEVE = Sieve(max(TEST_CASES))
for test_case in TEST_CASES:
if SIEVE.is_prime(test_case):
print("Prime")
else:
print("Not prime")
| Solve all test cases but 2 | Solve all test cases but 2
| Python | mit | rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank | + from collections import deque
- p = int(input().strip())
- for a0 in range(p):
- n = int(input().strip())
+
+ class Sieve(object):
+
+ def __init__(self, upper_bound):
+ self.upper_bound = upper_bound + 1
+ self.primes = []
+ self.populate_primes()
+ # print("Primes " + str(self.primes))
+
+ def is_prime(self, potential_prime):
+ return potential_prime in self.primes
+
+ def populate_primes(self,):
+ remaining = deque(range(2, self.upper_bound))
+ while remaining:
+ prime = remaining.popleft()
+ self.primes.append(prime)
+ for multiple in self.multiples(prime):
+ if multiple in remaining:
+ remaining.remove(multiple)
+
+ def multiples(self, num):
+ return range(num, self.upper_bound, num)
+
+
+ NUM_CASES = int(input().strip())
+ TEST_CASES = []
+ for _ in range(NUM_CASES):
+ TEST_CASES.append(int(input().strip()))
+
+ # print("Max: " + str(max(TEST_CASES)))
+ SIEVE = Sieve(max(TEST_CASES))
+ for test_case in TEST_CASES:
+ if SIEVE.is_prime(test_case):
+ print("Prime")
+ else:
+ print("Not prime")
+ | Solve all test cases but 2 | ## Code Before:
p = int(input().strip())
for a0 in range(p):
n = int(input().strip())
## Instruction:
Solve all test cases but 2
## Code After:
from collections import deque
class Sieve(object):
def __init__(self, upper_bound):
self.upper_bound = upper_bound + 1
self.primes = []
self.populate_primes()
# print("Primes " + str(self.primes))
def is_prime(self, potential_prime):
return potential_prime in self.primes
def populate_primes(self,):
remaining = deque(range(2, self.upper_bound))
while remaining:
prime = remaining.popleft()
self.primes.append(prime)
for multiple in self.multiples(prime):
if multiple in remaining:
remaining.remove(multiple)
def multiples(self, num):
return range(num, self.upper_bound, num)
NUM_CASES = int(input().strip())
TEST_CASES = []
for _ in range(NUM_CASES):
TEST_CASES.append(int(input().strip()))
# print("Max: " + str(max(TEST_CASES)))
SIEVE = Sieve(max(TEST_CASES))
for test_case in TEST_CASES:
if SIEVE.is_prime(test_case):
print("Prime")
else:
print("Not prime")
|
ed92a324cceddce96f2cff51a103c6ca15f62d8e | asterix/test.py | asterix/test.py | """ Utility functions to help testing. """
from unittest.mock import Mock
class dummy(object):
def __init__(self):
self.components = {}
def get(self, name, default):
if name not in self.components:
self.components[name] = Mock()
return self.components[name]
class dummy_master(object):
def __init__(self):
setattr(self, "__components", dummy())
| """ Utility functions to help testing. """
from unittest.mock import Mock
class dummy(object):
def __init__(self):
self.components = {}
def get(self, name, default=None):
if name not in self.components:
self.components[name] = Mock()
return self.components[name]
class dummy_master(object):
def __init__(self):
setattr(self, "__components", dummy())
def get(self, name):
return self.__components.components.get(name)
| Add facade to mocked components | Add facade to mocked components
| Python | mit | hkupty/asterix | """ Utility functions to help testing. """
from unittest.mock import Mock
class dummy(object):
def __init__(self):
self.components = {}
- def get(self, name, default):
+ def get(self, name, default=None):
if name not in self.components:
self.components[name] = Mock()
return self.components[name]
class dummy_master(object):
def __init__(self):
setattr(self, "__components", dummy())
+ def get(self, name):
+ return self.__components.components.get(name)
+ | Add facade to mocked components | ## Code Before:
""" Utility functions to help testing. """
from unittest.mock import Mock
class dummy(object):
def __init__(self):
self.components = {}
def get(self, name, default):
if name not in self.components:
self.components[name] = Mock()
return self.components[name]
class dummy_master(object):
def __init__(self):
setattr(self, "__components", dummy())
## Instruction:
Add facade to mocked components
## Code After:
""" Utility functions to help testing. """
from unittest.mock import Mock
class dummy(object):
def __init__(self):
self.components = {}
def get(self, name, default=None):
if name not in self.components:
self.components[name] = Mock()
return self.components[name]
class dummy_master(object):
def __init__(self):
setattr(self, "__components", dummy())
def get(self, name):
return self.__components.components.get(name)
|
adc92c01ef72cd937de7448da515caf6c2704cc3 | app/task.py | app/task.py | from mongoengine import Document, DateTimeField, EmailField, IntField, \
ReferenceField, StringField
import datetime, enum
class Priority(enum.IntEnum):
LOW = 0,
MIDDLE = 1,
HIGH = 2
"""
This defines the basic model for a Task as we want it to be stored in the
MongoDB.
"""
class Task(Document):
title = StringField(max_length=150, required=True)
description = StringField(max_length=800, required=True)
creator = EmailField(max_length=120, required=True)
assigne = EmailField(max_length=120, required=True)
created_at = DateTimeField(default=datetime.datetime.now, required=True)
closed_at = DateTimeField(required=False)
status = IntField(default=0, required=True)
priority = IntField(default=Priority.LOW, required=True)
| from mongoengine import Document, DateTimeField, EmailField, IntField, \
ReferenceField, StringField
import datetime, enum
class Priority(enum.IntEnum):
LOW = 0,
MIDDLE = 1,
HIGH = 2
"""
This defines the basic model for a Task as we want it to be stored in the
MongoDB.
"""
class Task(Document):
title = StringField(max_length=150, required=True)
description = StringField(max_length=800, required=True)
creator = EmailField(max_length=120, required=True)
assigne = EmailField(max_length=120, required=True)
created_at = DateTimeField(default=datetime.datetime.now, required=True)
status = IntField(default=0, required=True)
priority = IntField(default=Priority.LOW, required=True)
| Remove closed_at field from Task model | Remove closed_at field from Task model
| Python | mit | Zillolo/lazy-todo | from mongoengine import Document, DateTimeField, EmailField, IntField, \
ReferenceField, StringField
import datetime, enum
class Priority(enum.IntEnum):
LOW = 0,
MIDDLE = 1,
HIGH = 2
"""
This defines the basic model for a Task as we want it to be stored in the
MongoDB.
"""
class Task(Document):
title = StringField(max_length=150, required=True)
description = StringField(max_length=800, required=True)
creator = EmailField(max_length=120, required=True)
assigne = EmailField(max_length=120, required=True)
created_at = DateTimeField(default=datetime.datetime.now, required=True)
- closed_at = DateTimeField(required=False)
status = IntField(default=0, required=True)
priority = IntField(default=Priority.LOW, required=True)
| Remove closed_at field from Task model | ## Code Before:
from mongoengine import Document, DateTimeField, EmailField, IntField, \
ReferenceField, StringField
import datetime, enum
class Priority(enum.IntEnum):
LOW = 0,
MIDDLE = 1,
HIGH = 2
"""
This defines the basic model for a Task as we want it to be stored in the
MongoDB.
"""
class Task(Document):
title = StringField(max_length=150, required=True)
description = StringField(max_length=800, required=True)
creator = EmailField(max_length=120, required=True)
assigne = EmailField(max_length=120, required=True)
created_at = DateTimeField(default=datetime.datetime.now, required=True)
closed_at = DateTimeField(required=False)
status = IntField(default=0, required=True)
priority = IntField(default=Priority.LOW, required=True)
## Instruction:
Remove closed_at field from Task model
## Code After:
from mongoengine import Document, DateTimeField, EmailField, IntField, \
ReferenceField, StringField
import datetime, enum
class Priority(enum.IntEnum):
LOW = 0,
MIDDLE = 1,
HIGH = 2
"""
This defines the basic model for a Task as we want it to be stored in the
MongoDB.
"""
class Task(Document):
title = StringField(max_length=150, required=True)
description = StringField(max_length=800, required=True)
creator = EmailField(max_length=120, required=True)
assigne = EmailField(max_length=120, required=True)
created_at = DateTimeField(default=datetime.datetime.now, required=True)
status = IntField(default=0, required=True)
priority = IntField(default=Priority.LOW, required=True)
|
435d5d21c2bd2b14998fd206035cc93fd897f6c8 | tests/testclasses.py | tests/testclasses.py | from datetime import datetime
import unittest
from normalize import (
JsonCollectionProperty,
JsonProperty,
JsonRecord,
Record,
RecordList,
)
class MockChildRecord(JsonRecord):
name = JsonProperty()
class MockDelegateJsonRecord(JsonRecord):
other = JsonProperty()
class MockJsonRecord(JsonRecord):
name = JsonProperty()
age = JsonProperty(isa=int)
seen = JsonProperty(
json_name='last_seen', isa=datetime,
coerce=lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S'),
)
children = JsonCollectionProperty(of=MockChildRecord)
class MockUnsanitizedJsonRecord(JsonRecord):
count = JsonProperty(isa=int)
last_updated = JsonProperty(
isa=datetime,
coerce=lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S'),
extraneous=False,
)
class MockRecordList(RecordList):
record_cls = MockUnsanitizedJsonRecord
def all_diff_types_equal(record, diff_type):
"""
Returns True if the given Record's DiffType and Record's Properties'
DiffTypes are the same as the specified DiffType.
"""
if record.diff_type != diff_type:
return False
for field_name, prop in record._fields.iteritems():
prop_diff_type = prop.get_diff_info(record).diff_type
# Property doesn't have a DiffType
if prop_diff_type is None:
continue
if prop_diff_type != diff_type:
return False
prop_value = getattr(record, field_name)
if isinstance(prop_value, Record):
if not all_diff_types_equal(prop_value, diff_type):
return False
#elif isinstance(prop_value, JsonCollectionProperty):
#if not all(all_diff_types_equal(v, diff_type)
# for v in prop_value):
#return False
return True
class StructableTestCase(unittest.TestCase):
def assertAllDiffTypesEqual(self, record, diff_type):
self.assertTrue(all_diff_types_equal(record, diff_type))
| from datetime import datetime
import unittest
from normalize import (
JsonCollectionProperty,
JsonProperty,
JsonRecord,
Record,
RecordList,
)
class MockChildRecord(JsonRecord):
name = JsonProperty()
class MockDelegateJsonRecord(JsonRecord):
other = JsonProperty()
class MockJsonRecord(JsonRecord):
name = JsonProperty()
age = JsonProperty(isa=int)
seen = JsonProperty(
json_name='last_seen', isa=datetime,
coerce=lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S'),
)
children = JsonCollectionProperty(of=MockChildRecord)
class MockExtraneousJsonRecord(JsonRecord):
count = JsonProperty(isa=int)
last_updated = JsonProperty(
isa=datetime,
coerce=lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S'),
extraneous=False,
)
class MockRecordList(RecordList):
itemtype = MockExtraneousJsonRecord
| Remove some traces of this module's predecessor | Remove some traces of this module's predecessor
| Python | mit | samv/normalize,tomo-otsuka/normalize,hearsaycorp/normalize | from datetime import datetime
import unittest
from normalize import (
JsonCollectionProperty,
JsonProperty,
JsonRecord,
Record,
RecordList,
)
class MockChildRecord(JsonRecord):
name = JsonProperty()
class MockDelegateJsonRecord(JsonRecord):
other = JsonProperty()
class MockJsonRecord(JsonRecord):
name = JsonProperty()
age = JsonProperty(isa=int)
seen = JsonProperty(
json_name='last_seen', isa=datetime,
coerce=lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S'),
)
children = JsonCollectionProperty(of=MockChildRecord)
- class MockUnsanitizedJsonRecord(JsonRecord):
+ class MockExtraneousJsonRecord(JsonRecord):
count = JsonProperty(isa=int)
last_updated = JsonProperty(
isa=datetime,
coerce=lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S'),
extraneous=False,
)
class MockRecordList(RecordList):
- record_cls = MockUnsanitizedJsonRecord
+ itemtype = MockExtraneousJsonRecord
-
- def all_diff_types_equal(record, diff_type):
- """
- Returns True if the given Record's DiffType and Record's Properties'
- DiffTypes are the same as the specified DiffType.
- """
- if record.diff_type != diff_type:
- return False
-
- for field_name, prop in record._fields.iteritems():
- prop_diff_type = prop.get_diff_info(record).diff_type
-
- # Property doesn't have a DiffType
- if prop_diff_type is None:
- continue
-
- if prop_diff_type != diff_type:
- return False
- prop_value = getattr(record, field_name)
- if isinstance(prop_value, Record):
- if not all_diff_types_equal(prop_value, diff_type):
- return False
- #elif isinstance(prop_value, JsonCollectionProperty):
- #if not all(all_diff_types_equal(v, diff_type)
- # for v in prop_value):
- #return False
-
- return True
-
-
- class StructableTestCase(unittest.TestCase):
- def assertAllDiffTypesEqual(self, record, diff_type):
- self.assertTrue(all_diff_types_equal(record, diff_type))
- | Remove some traces of this module's predecessor | ## Code Before:
from datetime import datetime
import unittest
from normalize import (
JsonCollectionProperty,
JsonProperty,
JsonRecord,
Record,
RecordList,
)
class MockChildRecord(JsonRecord):
name = JsonProperty()
class MockDelegateJsonRecord(JsonRecord):
other = JsonProperty()
class MockJsonRecord(JsonRecord):
name = JsonProperty()
age = JsonProperty(isa=int)
seen = JsonProperty(
json_name='last_seen', isa=datetime,
coerce=lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S'),
)
children = JsonCollectionProperty(of=MockChildRecord)
class MockUnsanitizedJsonRecord(JsonRecord):
count = JsonProperty(isa=int)
last_updated = JsonProperty(
isa=datetime,
coerce=lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S'),
extraneous=False,
)
class MockRecordList(RecordList):
record_cls = MockUnsanitizedJsonRecord
def all_diff_types_equal(record, diff_type):
"""
Returns True if the given Record's DiffType and Record's Properties'
DiffTypes are the same as the specified DiffType.
"""
if record.diff_type != diff_type:
return False
for field_name, prop in record._fields.iteritems():
prop_diff_type = prop.get_diff_info(record).diff_type
# Property doesn't have a DiffType
if prop_diff_type is None:
continue
if prop_diff_type != diff_type:
return False
prop_value = getattr(record, field_name)
if isinstance(prop_value, Record):
if not all_diff_types_equal(prop_value, diff_type):
return False
#elif isinstance(prop_value, JsonCollectionProperty):
#if not all(all_diff_types_equal(v, diff_type)
# for v in prop_value):
#return False
return True
class StructableTestCase(unittest.TestCase):
def assertAllDiffTypesEqual(self, record, diff_type):
self.assertTrue(all_diff_types_equal(record, diff_type))
## Instruction:
Remove some traces of this module's predecessor
## Code After:
from datetime import datetime
import unittest
from normalize import (
JsonCollectionProperty,
JsonProperty,
JsonRecord,
Record,
RecordList,
)
class MockChildRecord(JsonRecord):
name = JsonProperty()
class MockDelegateJsonRecord(JsonRecord):
other = JsonProperty()
class MockJsonRecord(JsonRecord):
name = JsonProperty()
age = JsonProperty(isa=int)
seen = JsonProperty(
json_name='last_seen', isa=datetime,
coerce=lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S'),
)
children = JsonCollectionProperty(of=MockChildRecord)
class MockExtraneousJsonRecord(JsonRecord):
count = JsonProperty(isa=int)
last_updated = JsonProperty(
isa=datetime,
coerce=lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S'),
extraneous=False,
)
class MockRecordList(RecordList):
itemtype = MockExtraneousJsonRecord
|
e53c572af6f9ee2808ef682cfcfc842fe650ab4b | gribapi/__init__.py | gribapi/__init__.py | from .gribapi import * # noqa
from .gribapi import __version__
from .gribapi import bindings_version
| from .gribapi import * # noqa
from .gribapi import __version__
from .gribapi import bindings_version
# The minimum required version for the ecCodes package
min_reqd_version_str = '2.14.0'
min_reqd_version_int = 21400
if lib.grib_get_api_version() < min_reqd_version_int:
raise RuntimeError('ecCodes %s or higher is required. You are running version %s' % (
min_reqd_version_str, __version__))
| Check minimum required version of ecCodes engine | Check minimum required version of ecCodes engine
| Python | apache-2.0 | ecmwf/eccodes-python,ecmwf/eccodes-python | from .gribapi import * # noqa
from .gribapi import __version__
from .gribapi import bindings_version
+ # The minimum required version for the ecCodes package
+ min_reqd_version_str = '2.14.0'
+ min_reqd_version_int = 21400
+
+ if lib.grib_get_api_version() < min_reqd_version_int:
+ raise RuntimeError('ecCodes %s or higher is required. You are running version %s' % (
+ min_reqd_version_str, __version__))
+ | Check minimum required version of ecCodes engine | ## Code Before:
from .gribapi import * # noqa
from .gribapi import __version__
from .gribapi import bindings_version
## Instruction:
Check minimum required version of ecCodes engine
## Code After:
from .gribapi import * # noqa
from .gribapi import __version__
from .gribapi import bindings_version
# The minimum required version for the ecCodes package
min_reqd_version_str = '2.14.0'
min_reqd_version_int = 21400
if lib.grib_get_api_version() < min_reqd_version_int:
raise RuntimeError('ecCodes %s or higher is required. You are running version %s' % (
min_reqd_version_str, __version__))
|
da5479f4db905ea632009728864793812d56be81 | test/test_bill_history.py | test/test_bill_history.py | import unittest
import bill_info
import fixtures
import datetime
class BillHistory(unittest.TestCase):
def test_normal_enacted_bill(self):
history = fixtures.bill("hr3590-111")['history']
self.assertEqual(history['house_passage_result'], 'pass')
self.assertEqual(self.to_date(history['house_passage_result_at']), "2010-03-21 22:48")
self.assertEqual(history['senate_passage_result'], 'pass')
self.assertEqual(self.to_date(history['senate_passage_result_at']), "2009-12-24 00:00")
self.assertEqual(history['vetoed'], False)
self.assertEqual(history['awaiting_signature'], False)
self.assertEqual(history['enacted'], True)
self.assertEqual(self.to_date(history["enacted_at"]), "2010-03-23 00:00")
def to_date(self, time):
return datetime.datetime.strftime(time, "%Y-%m-%d %H:%M") | import unittest
import bill_info
import fixtures
import datetime
class BillHistory(unittest.TestCase):
def test_normal_enacted_bill(self):
history = fixtures.bill("hr3590-111")['history']
self.assertEqual(history['house_passage_result'], 'pass')
self.assertEqual(self.to_date(history['house_passage_result_at']), "2010-03-21 22:48")
self.assertEqual(history['senate_passage_result'], 'pass')
self.assertEqual(self.to_date(history['senate_passage_result_at']), "2009-12-24")
self.assertEqual(history['vetoed'], False)
self.assertEqual(history['awaiting_signature'], False)
self.assertEqual(history['enacted'], True)
self.assertEqual(self.to_date(history["enacted_at"]), "2010-03-23")
def to_date(self, time):
if isinstance(time, str):
return time
else:
return datetime.datetime.strftime(time, "%Y-%m-%d %H:%M") | Fix failing test since switching to use bare dates and not full timestamps when appropriate | Fix failing test since switching to use bare dates and not full timestamps when appropriate
| Python | cc0-1.0 | boblannon/congress,Nolawee/congress,Nolawee/congress,chriscondon/billtext,sunlightlabs/congress-opencongress,boblannon/congress,chriscondon/billtext,unitedstates/congress,sunlightlabs/congress-opencongress,unitedstates/congress | import unittest
import bill_info
import fixtures
import datetime
class BillHistory(unittest.TestCase):
def test_normal_enacted_bill(self):
history = fixtures.bill("hr3590-111")['history']
self.assertEqual(history['house_passage_result'], 'pass')
self.assertEqual(self.to_date(history['house_passage_result_at']), "2010-03-21 22:48")
self.assertEqual(history['senate_passage_result'], 'pass')
- self.assertEqual(self.to_date(history['senate_passage_result_at']), "2009-12-24 00:00")
+ self.assertEqual(self.to_date(history['senate_passage_result_at']), "2009-12-24")
self.assertEqual(history['vetoed'], False)
self.assertEqual(history['awaiting_signature'], False)
self.assertEqual(history['enacted'], True)
- self.assertEqual(self.to_date(history["enacted_at"]), "2010-03-23 00:00")
+ self.assertEqual(self.to_date(history["enacted_at"]), "2010-03-23")
def to_date(self, time):
+ if isinstance(time, str):
+ return time
+ else:
- return datetime.datetime.strftime(time, "%Y-%m-%d %H:%M")
+ return datetime.datetime.strftime(time, "%Y-%m-%d %H:%M") | Fix failing test since switching to use bare dates and not full timestamps when appropriate | ## Code Before:
import unittest
import bill_info
import fixtures
import datetime
class BillHistory(unittest.TestCase):
def test_normal_enacted_bill(self):
history = fixtures.bill("hr3590-111")['history']
self.assertEqual(history['house_passage_result'], 'pass')
self.assertEqual(self.to_date(history['house_passage_result_at']), "2010-03-21 22:48")
self.assertEqual(history['senate_passage_result'], 'pass')
self.assertEqual(self.to_date(history['senate_passage_result_at']), "2009-12-24 00:00")
self.assertEqual(history['vetoed'], False)
self.assertEqual(history['awaiting_signature'], False)
self.assertEqual(history['enacted'], True)
self.assertEqual(self.to_date(history["enacted_at"]), "2010-03-23 00:00")
def to_date(self, time):
return datetime.datetime.strftime(time, "%Y-%m-%d %H:%M")
## Instruction:
Fix failing test since switching to use bare dates and not full timestamps when appropriate
## Code After:
import unittest
import bill_info
import fixtures
import datetime
class BillHistory(unittest.TestCase):
def test_normal_enacted_bill(self):
history = fixtures.bill("hr3590-111")['history']
self.assertEqual(history['house_passage_result'], 'pass')
self.assertEqual(self.to_date(history['house_passage_result_at']), "2010-03-21 22:48")
self.assertEqual(history['senate_passage_result'], 'pass')
self.assertEqual(self.to_date(history['senate_passage_result_at']), "2009-12-24")
self.assertEqual(history['vetoed'], False)
self.assertEqual(history['awaiting_signature'], False)
self.assertEqual(history['enacted'], True)
self.assertEqual(self.to_date(history["enacted_at"]), "2010-03-23")
def to_date(self, time):
if isinstance(time, str):
return time
else:
return datetime.datetime.strftime(time, "%Y-%m-%d %H:%M") |
61a4743b62914559fea18a945f7a780e1394da2f | test/test_export_flow.py | test/test_export_flow.py | import netlib.tutils
from libmproxy import flow_export
from . import tutils
req_get = netlib.tutils.treq(
method='GET',
headers=None,
content=None,
)
req_post = netlib.tutils.treq(
method='POST',
headers=None,
)
def test_request_simple():
flow = tutils.tflow(req=req_get)
assert flow_export.curl_command(flow)
flow = tutils.tflow(req=req_post)
assert flow_export.curl_command(flow)
| import netlib.tutils
from libmproxy import flow_export
from . import tutils
req_get = netlib.tutils.treq(
method='GET',
content=None,
)
req_post = netlib.tutils.treq(
method='POST',
headers=None,
)
req_patch = netlib.tutils.treq(
method='PATCH',
path=b"/path?query=param",
)
def test_curl_command():
flow = tutils.tflow(req=req_get)
result = """curl -H 'header:qvalue' 'http://address/path'"""
assert flow_export.curl_command(flow) == result
flow = tutils.tflow(req=req_post)
result = """curl -X POST 'http://address/path' --data-binary 'content'"""
assert flow_export.curl_command(flow) == result
flow = tutils.tflow(req=req_patch)
result = """curl -H 'header:qvalue' -X PATCH 'http://address/path?query=param' --data-binary 'content'"""
assert flow_export.curl_command(flow) == result
| Test exact return value of flow_export.curl_command | Test exact return value of flow_export.curl_command
| Python | mit | jvillacorta/mitmproxy,tdickers/mitmproxy,ddworken/mitmproxy,StevenVanAcker/mitmproxy,cortesi/mitmproxy,vhaupert/mitmproxy,tdickers/mitmproxy,mosajjal/mitmproxy,mosajjal/mitmproxy,fimad/mitmproxy,fimad/mitmproxy,ujjwal96/mitmproxy,vhaupert/mitmproxy,dwfreed/mitmproxy,ParthGanatra/mitmproxy,xaxa89/mitmproxy,mhils/mitmproxy,mhils/mitmproxy,tdickers/mitmproxy,StevenVanAcker/mitmproxy,mitmproxy/mitmproxy,ikoz/mitmproxy,dufferzafar/mitmproxy,mitmproxy/mitmproxy,tdickers/mitmproxy,vhaupert/mitmproxy,StevenVanAcker/mitmproxy,Kriechi/mitmproxy,zlorb/mitmproxy,gzzhanghao/mitmproxy,ikoz/mitmproxy,MatthewShao/mitmproxy,mhils/mitmproxy,mosajjal/mitmproxy,gzzhanghao/mitmproxy,mitmproxy/mitmproxy,xaxa89/mitmproxy,cortesi/mitmproxy,ujjwal96/mitmproxy,jvillacorta/mitmproxy,ddworken/mitmproxy,MatthewShao/mitmproxy,cortesi/mitmproxy,laurmurclar/mitmproxy,zlorb/mitmproxy,dwfreed/mitmproxy,dwfreed/mitmproxy,laurmurclar/mitmproxy,dwfreed/mitmproxy,mitmproxy/mitmproxy,mosajjal/mitmproxy,dufferzafar/mitmproxy,Kriechi/mitmproxy,dufferzafar/mitmproxy,ikoz/mitmproxy,jvillacorta/mitmproxy,ikoz/mitmproxy,mhils/mitmproxy,MatthewShao/mitmproxy,gzzhanghao/mitmproxy,ujjwal96/mitmproxy,ujjwal96/mitmproxy,gzzhanghao/mitmproxy,cortesi/mitmproxy,laurmurclar/mitmproxy,ParthGanatra/mitmproxy,mitmproxy/mitmproxy,zlorb/mitmproxy,fimad/mitmproxy,zlorb/mitmproxy,xaxa89/mitmproxy,mhils/mitmproxy,StevenVanAcker/mitmproxy,Kriechi/mitmproxy,vhaupert/mitmproxy,laurmurclar/mitmproxy,ParthGanatra/mitmproxy,fimad/mitmproxy,Kriechi/mitmproxy,dufferzafar/mitmproxy,ddworken/mitmproxy,ParthGanatra/mitmproxy,jvillacorta/mitmproxy,ddworken/mitmproxy,xaxa89/mitmproxy,MatthewShao/mitmproxy | import netlib.tutils
from libmproxy import flow_export
from . import tutils
req_get = netlib.tutils.treq(
method='GET',
- headers=None,
content=None,
)
req_post = netlib.tutils.treq(
method='POST',
headers=None,
)
+ req_patch = netlib.tutils.treq(
+ method='PATCH',
+ path=b"/path?query=param",
+ )
- def test_request_simple():
+
+ def test_curl_command():
flow = tutils.tflow(req=req_get)
+ result = """curl -H 'header:qvalue' 'http://address/path'"""
- assert flow_export.curl_command(flow)
+ assert flow_export.curl_command(flow) == result
flow = tutils.tflow(req=req_post)
+ result = """curl -X POST 'http://address/path' --data-binary 'content'"""
- assert flow_export.curl_command(flow)
+ assert flow_export.curl_command(flow) == result
+ flow = tutils.tflow(req=req_patch)
+ result = """curl -H 'header:qvalue' -X PATCH 'http://address/path?query=param' --data-binary 'content'"""
+ assert flow_export.curl_command(flow) == result
+
+ | Test exact return value of flow_export.curl_command | ## Code Before:
import netlib.tutils
from libmproxy import flow_export
from . import tutils
req_get = netlib.tutils.treq(
method='GET',
headers=None,
content=None,
)
req_post = netlib.tutils.treq(
method='POST',
headers=None,
)
def test_request_simple():
flow = tutils.tflow(req=req_get)
assert flow_export.curl_command(flow)
flow = tutils.tflow(req=req_post)
assert flow_export.curl_command(flow)
## Instruction:
Test exact return value of flow_export.curl_command
## Code After:
import netlib.tutils
from libmproxy import flow_export
from . import tutils
req_get = netlib.tutils.treq(
method='GET',
content=None,
)
req_post = netlib.tutils.treq(
method='POST',
headers=None,
)
req_patch = netlib.tutils.treq(
method='PATCH',
path=b"/path?query=param",
)
def test_curl_command():
flow = tutils.tflow(req=req_get)
result = """curl -H 'header:qvalue' 'http://address/path'"""
assert flow_export.curl_command(flow) == result
flow = tutils.tflow(req=req_post)
result = """curl -X POST 'http://address/path' --data-binary 'content'"""
assert flow_export.curl_command(flow) == result
flow = tutils.tflow(req=req_patch)
result = """curl -H 'header:qvalue' -X PATCH 'http://address/path?query=param' --data-binary 'content'"""
assert flow_export.curl_command(flow) == result
|
37cb987503f336362d629619f6f39165f4d8e212 | utils/snippets.py | utils/snippets.py |
import sys
import os
import datetime
snippet_map = {
'date' : datetime.datetime.now().strftime('%b %d %G %I:%M%p '),
'time' : datetime.datetime.now().strftime('%I:%M%p '),
}
keys = '\n'.join(snippet_map.keys())
result = os.popen('printf "%s" | rofi -dmenu ' % keys)
selected_key = result.read().strip()
os.system('xdotool type --clearmodifiers -- "%s"' % str(snippet_map[selected_key]))
|
import sys
import os
import datetime
snippet_map = {
'date' : datetime.datetime.now().strftime('%b %d %G %I:%M%p '),
'time' : datetime.datetime.now().strftime('%I:%M%p '),
'sign' : 'Best,\nSameer',
}
keys = '\n'.join(snippet_map.keys())
result = os.popen('printf "%s" | rofi -dmenu ' % keys)
selected_key = result.read().strip()
os.system('sleep 0.1; xdotool type --clearmodifiers "$(printf "%s")"' % str(snippet_map[selected_key]))
| Update snippet script to work with newlines. | Update snippet script to work with newlines.
| Python | mit | sam33r/dotfiles,sam33r/dotfiles,sam33r/dotfiles,sam33r/dotfiles |
import sys
import os
import datetime
snippet_map = {
'date' : datetime.datetime.now().strftime('%b %d %G %I:%M%p '),
'time' : datetime.datetime.now().strftime('%I:%M%p '),
+ 'sign' : 'Best,\nSameer',
}
keys = '\n'.join(snippet_map.keys())
result = os.popen('printf "%s" | rofi -dmenu ' % keys)
selected_key = result.read().strip()
- os.system('xdotool type --clearmodifiers -- "%s"' % str(snippet_map[selected_key]))
+ os.system('sleep 0.1; xdotool type --clearmodifiers "$(printf "%s")"' % str(snippet_map[selected_key]))
+
+ | Update snippet script to work with newlines. | ## Code Before:
import sys
import os
import datetime
snippet_map = {
'date' : datetime.datetime.now().strftime('%b %d %G %I:%M%p '),
'time' : datetime.datetime.now().strftime('%I:%M%p '),
}
keys = '\n'.join(snippet_map.keys())
result = os.popen('printf "%s" | rofi -dmenu ' % keys)
selected_key = result.read().strip()
os.system('xdotool type --clearmodifiers -- "%s"' % str(snippet_map[selected_key]))
## Instruction:
Update snippet script to work with newlines.
## Code After:
import sys
import os
import datetime
snippet_map = {
'date' : datetime.datetime.now().strftime('%b %d %G %I:%M%p '),
'time' : datetime.datetime.now().strftime('%I:%M%p '),
'sign' : 'Best,\nSameer',
}
keys = '\n'.join(snippet_map.keys())
result = os.popen('printf "%s" | rofi -dmenu ' % keys)
selected_key = result.read().strip()
os.system('sleep 0.1; xdotool type --clearmodifiers "$(printf "%s")"' % str(snippet_map[selected_key]))
|
95a6f1fa9e5153d337a3590cea8c7918c88c63e0 | openedx/core/djangoapps/embargo/admin.py | openedx/core/djangoapps/embargo/admin.py | import textwrap
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .forms import IPFilterForm, RestrictedCourseForm
from .models import CountryAccessRule, IPFilter, RestrictedCourse
class IPFilterAdmin(ConfigurationModelAdmin):
"""Admin for blacklisting/whitelisting specific IP addresses"""
form = IPFilterForm
fieldsets = (
(None, {
'fields': ('enabled', 'whitelist', 'blacklist'),
'description': textwrap.dedent("""Enter specific IP addresses to explicitly
whitelist (not block) or blacklist (block) in the appropriate box below.
Separate IP addresses with a comma. Do not surround with quotes.
""")
}),
)
class CountryAccessRuleInline(admin.StackedInline):
"""Inline editor for country access rules. """
model = CountryAccessRule
extra = 1
def has_delete_permission(self, request, obj=None):
return True
class RestrictedCourseAdmin(admin.ModelAdmin):
"""Admin for configuring course restrictions. """
inlines = [CountryAccessRuleInline]
form = RestrictedCourseForm
admin.site.register(IPFilter, IPFilterAdmin)
admin.site.register(RestrictedCourse, RestrictedCourseAdmin)
| import textwrap
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .forms import IPFilterForm, RestrictedCourseForm
from .models import CountryAccessRule, IPFilter, RestrictedCourse
class IPFilterAdmin(ConfigurationModelAdmin):
"""Admin for blacklisting/whitelisting specific IP addresses"""
form = IPFilterForm
fieldsets = (
(None, {
'fields': ('enabled', 'whitelist', 'blacklist'),
'description': textwrap.dedent("""Enter specific IP addresses to explicitly
whitelist (not block) or blacklist (block) in the appropriate box below.
Separate IP addresses with a comma. Do not surround with quotes.
""")
}),
)
class CountryAccessRuleInline(admin.StackedInline):
"""Inline editor for country access rules. """
model = CountryAccessRule
extra = 1
def has_delete_permission(self, request, obj=None):
return True
class RestrictedCourseAdmin(admin.ModelAdmin):
"""Admin for configuring course restrictions. """
inlines = [CountryAccessRuleInline]
form = RestrictedCourseForm
search_fields = ('course_key',)
admin.site.register(IPFilter, IPFilterAdmin)
admin.site.register(RestrictedCourse, RestrictedCourseAdmin)
| Allow searching restricted courses by key | Allow searching restricted courses by key
| Python | agpl-3.0 | a-parhom/edx-platform,a-parhom/edx-platform,a-parhom/edx-platform,edx/edx-platform,msegado/edx-platform,philanthropy-u/edx-platform,edx-solutions/edx-platform,cpennington/edx-platform,eduNEXT/edx-platform,eduNEXT/edunext-platform,eduNEXT/edx-platform,arbrandes/edx-platform,jolyonb/edx-platform,EDUlib/edx-platform,mitocw/edx-platform,angelapper/edx-platform,ESOedX/edx-platform,mitocw/edx-platform,ESOedX/edx-platform,philanthropy-u/edx-platform,EDUlib/edx-platform,edx/edx-platform,edx/edx-platform,edx-solutions/edx-platform,ESOedX/edx-platform,jolyonb/edx-platform,arbrandes/edx-platform,stvstnfrd/edx-platform,appsembler/edx-platform,cpennington/edx-platform,msegado/edx-platform,stvstnfrd/edx-platform,stvstnfrd/edx-platform,msegado/edx-platform,EDUlib/edx-platform,jolyonb/edx-platform,angelapper/edx-platform,appsembler/edx-platform,mitocw/edx-platform,arbrandes/edx-platform,msegado/edx-platform,jolyonb/edx-platform,eduNEXT/edx-platform,philanthropy-u/edx-platform,ESOedX/edx-platform,eduNEXT/edunext-platform,stvstnfrd/edx-platform,edx/edx-platform,angelapper/edx-platform,arbrandes/edx-platform,edx-solutions/edx-platform,eduNEXT/edx-platform,eduNEXT/edunext-platform,angelapper/edx-platform,EDUlib/edx-platform,a-parhom/edx-platform,cpennington/edx-platform,appsembler/edx-platform,cpennington/edx-platform,edx-solutions/edx-platform,msegado/edx-platform,mitocw/edx-platform,philanthropy-u/edx-platform,appsembler/edx-platform,eduNEXT/edunext-platform | import textwrap
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .forms import IPFilterForm, RestrictedCourseForm
from .models import CountryAccessRule, IPFilter, RestrictedCourse
class IPFilterAdmin(ConfigurationModelAdmin):
"""Admin for blacklisting/whitelisting specific IP addresses"""
form = IPFilterForm
fieldsets = (
(None, {
'fields': ('enabled', 'whitelist', 'blacklist'),
'description': textwrap.dedent("""Enter specific IP addresses to explicitly
whitelist (not block) or blacklist (block) in the appropriate box below.
Separate IP addresses with a comma. Do not surround with quotes.
""")
}),
)
class CountryAccessRuleInline(admin.StackedInline):
"""Inline editor for country access rules. """
model = CountryAccessRule
extra = 1
def has_delete_permission(self, request, obj=None):
return True
class RestrictedCourseAdmin(admin.ModelAdmin):
"""Admin for configuring course restrictions. """
inlines = [CountryAccessRuleInline]
form = RestrictedCourseForm
+ search_fields = ('course_key',)
admin.site.register(IPFilter, IPFilterAdmin)
admin.site.register(RestrictedCourse, RestrictedCourseAdmin)
| Allow searching restricted courses by key | ## Code Before:
import textwrap
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .forms import IPFilterForm, RestrictedCourseForm
from .models import CountryAccessRule, IPFilter, RestrictedCourse
class IPFilterAdmin(ConfigurationModelAdmin):
"""Admin for blacklisting/whitelisting specific IP addresses"""
form = IPFilterForm
fieldsets = (
(None, {
'fields': ('enabled', 'whitelist', 'blacklist'),
'description': textwrap.dedent("""Enter specific IP addresses to explicitly
whitelist (not block) or blacklist (block) in the appropriate box below.
Separate IP addresses with a comma. Do not surround with quotes.
""")
}),
)
class CountryAccessRuleInline(admin.StackedInline):
"""Inline editor for country access rules. """
model = CountryAccessRule
extra = 1
def has_delete_permission(self, request, obj=None):
return True
class RestrictedCourseAdmin(admin.ModelAdmin):
"""Admin for configuring course restrictions. """
inlines = [CountryAccessRuleInline]
form = RestrictedCourseForm
admin.site.register(IPFilter, IPFilterAdmin)
admin.site.register(RestrictedCourse, RestrictedCourseAdmin)
## Instruction:
Allow searching restricted courses by key
## Code After:
import textwrap
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .forms import IPFilterForm, RestrictedCourseForm
from .models import CountryAccessRule, IPFilter, RestrictedCourse
class IPFilterAdmin(ConfigurationModelAdmin):
"""Admin for blacklisting/whitelisting specific IP addresses"""
form = IPFilterForm
fieldsets = (
(None, {
'fields': ('enabled', 'whitelist', 'blacklist'),
'description': textwrap.dedent("""Enter specific IP addresses to explicitly
whitelist (not block) or blacklist (block) in the appropriate box below.
Separate IP addresses with a comma. Do not surround with quotes.
""")
}),
)
class CountryAccessRuleInline(admin.StackedInline):
"""Inline editor for country access rules. """
model = CountryAccessRule
extra = 1
def has_delete_permission(self, request, obj=None):
return True
class RestrictedCourseAdmin(admin.ModelAdmin):
"""Admin for configuring course restrictions. """
inlines = [CountryAccessRuleInline]
form = RestrictedCourseForm
search_fields = ('course_key',)
admin.site.register(IPFilter, IPFilterAdmin)
admin.site.register(RestrictedCourse, RestrictedCourseAdmin)
|
8b6d285f60caa77677aaf3076642a47c525a3b24 | parsers/nmapingest.py | parsers/nmapingest.py | import pandas as pd
import logging, os
import IPy as IP
log = logging.getLogger(__name__)
df3 = pd.read_csv('nmap.tsv', delimiter='\t')
df3.columns = ['host_and_fingerprint', 'port']
df3['host_and_fingerprint'] = df3['host_and_fingerprint'].map(lambda x: x.lstrip('Host:').rstrip(''))
df3['port'] = df3['port'].map(lambda x: x.lstrip('Ports:').rstrip(''))
df3_hostfp = df3[['host_and_fingerprint']]
#df3_hostfp_check = df3.applymap(lambda x: IP(df3_hostfp).iptype())
df3['ip'] = df3['host_and_fingerprint'].apply(lambda x: x.split(' ')[1])
#df3['host_and_fingerprint'] = df3['host_and_fingerprint'].apply(lambda x: IP(df3_hostfp).iptype())
print (df3_hostfp_check)
#def logwrite():
#df3 = df3.to_csv('nmap.csv', index=None, encoding='utf-8')
| import pandas as pd
import logging, os
import IPy as IP
log = logging.getLogger(__name__)
df3 = pd.read_csv('data/nmap/nmap.tsv', delimiter='\t')
df3.columns = ['host_and_fingerprint', 'port']
df3['host_and_fingerprint'] = df3['host_and_fingerprint'].map(lambda x: x.lstrip('Host:').rstrip(''))
df3['port'] = df3['port'].map(lambda x: x.lstrip('Ports:').rstrip(''))
#df3_hostfp_check = df3.applymap(lambda x: IP(df3_hostfp).iptype())
df3['ip'] = df3['host_and_fingerprint'].apply(lambda x: x.split(' ')[1])
#df3['host_and_fingerprint'] = df3['host_and_fingerprint'].apply(lambda x: IP(df3_hostfp).iptype())
print (df3)
#def logwrite():
#df3 = df3.to_csv('nmap.csv', index=None, encoding='utf-8')
| Fix problem lines in nmap parsing. | Fix problem lines in nmap parsing.
| Python | apache-2.0 | jzadeh/chiron-elk | import pandas as pd
import logging, os
import IPy as IP
-
log = logging.getLogger(__name__)
-
- df3 = pd.read_csv('nmap.tsv', delimiter='\t')
+ df3 = pd.read_csv('data/nmap/nmap.tsv', delimiter='\t')
df3.columns = ['host_and_fingerprint', 'port']
df3['host_and_fingerprint'] = df3['host_and_fingerprint'].map(lambda x: x.lstrip('Host:').rstrip(''))
df3['port'] = df3['port'].map(lambda x: x.lstrip('Ports:').rstrip(''))
- df3_hostfp = df3[['host_and_fingerprint']]
#df3_hostfp_check = df3.applymap(lambda x: IP(df3_hostfp).iptype())
df3['ip'] = df3['host_and_fingerprint'].apply(lambda x: x.split(' ')[1])
#df3['host_and_fingerprint'] = df3['host_and_fingerprint'].apply(lambda x: IP(df3_hostfp).iptype())
- print (df3_hostfp_check)
+ print (df3)
#def logwrite():
#df3 = df3.to_csv('nmap.csv', index=None, encoding='utf-8')
| Fix problem lines in nmap parsing. | ## Code Before:
import pandas as pd
import logging, os
import IPy as IP
log = logging.getLogger(__name__)
df3 = pd.read_csv('nmap.tsv', delimiter='\t')
df3.columns = ['host_and_fingerprint', 'port']
df3['host_and_fingerprint'] = df3['host_and_fingerprint'].map(lambda x: x.lstrip('Host:').rstrip(''))
df3['port'] = df3['port'].map(lambda x: x.lstrip('Ports:').rstrip(''))
df3_hostfp = df3[['host_and_fingerprint']]
#df3_hostfp_check = df3.applymap(lambda x: IP(df3_hostfp).iptype())
df3['ip'] = df3['host_and_fingerprint'].apply(lambda x: x.split(' ')[1])
#df3['host_and_fingerprint'] = df3['host_and_fingerprint'].apply(lambda x: IP(df3_hostfp).iptype())
print (df3_hostfp_check)
#def logwrite():
#df3 = df3.to_csv('nmap.csv', index=None, encoding='utf-8')
## Instruction:
Fix problem lines in nmap parsing.
## Code After:
import pandas as pd
import logging, os
import IPy as IP
log = logging.getLogger(__name__)
df3 = pd.read_csv('data/nmap/nmap.tsv', delimiter='\t')
df3.columns = ['host_and_fingerprint', 'port']
df3['host_and_fingerprint'] = df3['host_and_fingerprint'].map(lambda x: x.lstrip('Host:').rstrip(''))
df3['port'] = df3['port'].map(lambda x: x.lstrip('Ports:').rstrip(''))
#df3_hostfp_check = df3.applymap(lambda x: IP(df3_hostfp).iptype())
df3['ip'] = df3['host_and_fingerprint'].apply(lambda x: x.split(' ')[1])
#df3['host_and_fingerprint'] = df3['host_and_fingerprint'].apply(lambda x: IP(df3_hostfp).iptype())
print (df3)
#def logwrite():
#df3 = df3.to_csv('nmap.csv', index=None, encoding='utf-8')
|
4ddce41a126395141738f4cd02b2c0589f0f1577 | test/utils.py | test/utils.py | from contextlib import contextmanager
import sys
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
@contextmanager
def captured_output():
"""Allows to safely capture stdout and stderr in a context manager."""
new_out, new_err = StringIO(), StringIO()
old_out, old_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = new_out, new_err
yield sys.stdout, sys.stderr
finally:
sys.stdout, sys.stderr = old_out, old_err
| from contextlib import contextmanager
import sys
from io import StringIO
@contextmanager
def captured_output():
"""Allows to safely capture stdout and stderr in a context manager."""
new_out, new_err = StringIO(), StringIO()
old_out, old_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = new_out, new_err
yield sys.stdout, sys.stderr
finally:
sys.stdout, sys.stderr = old_out, old_err
| Remove conditional import for py2 support | Remove conditional import for py2 support
| Python | mit | bertrandvidal/parse_this | from contextlib import contextmanager
import sys
- try:
- from StringIO import StringIO
- except ImportError:
- from io import StringIO
+ from io import StringIO
@contextmanager
def captured_output():
"""Allows to safely capture stdout and stderr in a context manager."""
new_out, new_err = StringIO(), StringIO()
old_out, old_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = new_out, new_err
yield sys.stdout, sys.stderr
finally:
sys.stdout, sys.stderr = old_out, old_err
| Remove conditional import for py2 support | ## Code Before:
from contextlib import contextmanager
import sys
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
@contextmanager
def captured_output():
"""Allows to safely capture stdout and stderr in a context manager."""
new_out, new_err = StringIO(), StringIO()
old_out, old_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = new_out, new_err
yield sys.stdout, sys.stderr
finally:
sys.stdout, sys.stderr = old_out, old_err
## Instruction:
Remove conditional import for py2 support
## Code After:
from contextlib import contextmanager
import sys
from io import StringIO
@contextmanager
def captured_output():
"""Allows to safely capture stdout and stderr in a context manager."""
new_out, new_err = StringIO(), StringIO()
old_out, old_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = new_out, new_err
yield sys.stdout, sys.stderr
finally:
sys.stdout, sys.stderr = old_out, old_err
|
6be3a40010b7256cb5b8fadfe4ef40b6c5691a06 | jungle/session.py | jungle/session.py | import boto3
def create_session(profile_name):
if not profile_name:
return boto3
else:
return boto3.Session(profile_name=profile_name)
| import sys
import boto3
import botocore
import click
def create_session(profile_name):
if profile_name is None:
return boto3
else:
try:
session = boto3.Session(profile_name=profile_name)
return session
except botocore.exceptions.ProfileNotFound as e:
click.echo("Invalid profile name: {0}".format(profile_name, e), err=True)
sys.exit(2)
| Add error message when wrong AWS Profile Name is given | Add error message when wrong AWS Profile Name is given
| Python | mit | achiku/jungle | + import sys
+
import boto3
+ import botocore
+ import click
def create_session(profile_name):
- if not profile_name:
+ if profile_name is None:
return boto3
else:
+ try:
- return boto3.Session(profile_name=profile_name)
+ session = boto3.Session(profile_name=profile_name)
+ return session
+ except botocore.exceptions.ProfileNotFound as e:
+ click.echo("Invalid profile name: {0}".format(profile_name, e), err=True)
+ sys.exit(2)
| Add error message when wrong AWS Profile Name is given | ## Code Before:
import boto3
def create_session(profile_name):
if not profile_name:
return boto3
else:
return boto3.Session(profile_name=profile_name)
## Instruction:
Add error message when wrong AWS Profile Name is given
## Code After:
import sys
import boto3
import botocore
import click
def create_session(profile_name):
if profile_name is None:
return boto3
else:
try:
session = boto3.Session(profile_name=profile_name)
return session
except botocore.exceptions.ProfileNotFound as e:
click.echo("Invalid profile name: {0}".format(profile_name, e), err=True)
sys.exit(2)
|
a71c6c03b02a15674fac0995d120f5c2180e8767 | plugin/floo/sublime.py | plugin/floo/sublime.py | from collections import defaultdict
import time
TIMEOUTS = defaultdict(list)
def windows(*args, **kwargs):
return []
def set_timeout(func, timeout, *args, **kwargs):
then = time.time() + timeout
TIMEOUTS[then].append(lambda: func(*args, **kwargs))
def call_timeouts():
now = time.time()
to_remove = []
for t, timeouts in TIMEOUTS.items():
if now >= t:
for timeout in timeouts:
timeout()
to_remove.append(t)
for k in to_remove:
del TIMEOUTS[k]
def error_message(*args, **kwargs):
print(args, kwargs)
class Region(object):
def __init__(*args, **kwargs):
pass
| from collections import defaultdict
import time
TIMEOUTS = defaultdict(list)
def windows(*args, **kwargs):
return []
def set_timeout(func, timeout, *args, **kwargs):
then = time.time() + (timeout / 1000.0)
TIMEOUTS[then].append(lambda: func(*args, **kwargs))
def call_timeouts():
now = time.time()
to_remove = []
for t, timeouts in TIMEOUTS.items():
if now >= t:
for timeout in timeouts:
timeout()
to_remove.append(t)
for k in to_remove:
del TIMEOUTS[k]
def error_message(*args, **kwargs):
print(args, kwargs)
class Region(object):
def __init__(*args, **kwargs):
pass
| Fix off by 1000 error | Fix off by 1000 error
| Python | apache-2.0 | Floobits/floobits-neovim,Floobits/floobits-neovim-old,Floobits/floobits-vim | from collections import defaultdict
import time
TIMEOUTS = defaultdict(list)
def windows(*args, **kwargs):
return []
def set_timeout(func, timeout, *args, **kwargs):
- then = time.time() + timeout
+ then = time.time() + (timeout / 1000.0)
TIMEOUTS[then].append(lambda: func(*args, **kwargs))
def call_timeouts():
now = time.time()
to_remove = []
for t, timeouts in TIMEOUTS.items():
if now >= t:
for timeout in timeouts:
timeout()
to_remove.append(t)
for k in to_remove:
del TIMEOUTS[k]
def error_message(*args, **kwargs):
print(args, kwargs)
class Region(object):
def __init__(*args, **kwargs):
pass
| Fix off by 1000 error | ## Code Before:
from collections import defaultdict
import time
TIMEOUTS = defaultdict(list)
def windows(*args, **kwargs):
return []
def set_timeout(func, timeout, *args, **kwargs):
then = time.time() + timeout
TIMEOUTS[then].append(lambda: func(*args, **kwargs))
def call_timeouts():
now = time.time()
to_remove = []
for t, timeouts in TIMEOUTS.items():
if now >= t:
for timeout in timeouts:
timeout()
to_remove.append(t)
for k in to_remove:
del TIMEOUTS[k]
def error_message(*args, **kwargs):
print(args, kwargs)
class Region(object):
def __init__(*args, **kwargs):
pass
## Instruction:
Fix off by 1000 error
## Code After:
from collections import defaultdict
import time
TIMEOUTS = defaultdict(list)
def windows(*args, **kwargs):
return []
def set_timeout(func, timeout, *args, **kwargs):
then = time.time() + (timeout / 1000.0)
TIMEOUTS[then].append(lambda: func(*args, **kwargs))
def call_timeouts():
now = time.time()
to_remove = []
for t, timeouts in TIMEOUTS.items():
if now >= t:
for timeout in timeouts:
timeout()
to_remove.append(t)
for k in to_remove:
del TIMEOUTS[k]
def error_message(*args, **kwargs):
print(args, kwargs)
class Region(object):
def __init__(*args, **kwargs):
pass
|
d0e7c8ec73e36d6391ec57802e6186608196901a | aldryn_apphooks_config/templatetags/namespace_extras.py | aldryn_apphooks_config/templatetags/namespace_extras.py |
from django import template
from django.core import urlresolvers
from ..utils import get_app_instance
register = template.Library()
@register.simple_tag(takes_context=True)
def namespace_url(context, view_name, *args, **kwargs):
"""
Returns an absolute URL matching given view with its parameters.
"""
namespace, config = get_app_instance(context['request'])
if not 'current_app' in kwargs:
kwargs['current_app'] = namespace
return urlresolvers.reverse('%s:%s' % (config.namespace, view_name),
args=args,
kwargs=kwargs)
|
from django import template
from django.core import urlresolvers
from ..utils import get_app_instance
register = template.Library()
@register.simple_tag(takes_context=True)
def namespace_url(context, view_name, *args, **kwargs):
"""
Returns an absolute URL matching given view with its parameters.
"""
namespace, config = get_app_instance(context['request'])
if not 'current_app' in kwargs:
kwargs['current_app'] = namespace
return urlresolvers.reverse(
'{0:s}:{1:s}'.format(config.namespace, view_name),
args=args,
kwargs=kwargs)
| Use string.format for performance reasons | Use string.format for performance reasons
| Python | bsd-3-clause | aldryn/aldryn-apphooks-config,aldryn/aldryn-apphooks-config,aldryn/aldryn-apphooks-config |
from django import template
from django.core import urlresolvers
from ..utils import get_app_instance
register = template.Library()
@register.simple_tag(takes_context=True)
def namespace_url(context, view_name, *args, **kwargs):
"""
Returns an absolute URL matching given view with its parameters.
"""
namespace, config = get_app_instance(context['request'])
if not 'current_app' in kwargs:
kwargs['current_app'] = namespace
- return urlresolvers.reverse('%s:%s' % (config.namespace, view_name),
- args=args,
- kwargs=kwargs)
+ return urlresolvers.reverse(
+ '{0:s}:{1:s}'.format(config.namespace, view_name),
+ args=args,
+ kwargs=kwargs)
| Use string.format for performance reasons | ## Code Before:
from django import template
from django.core import urlresolvers
from ..utils import get_app_instance
register = template.Library()
@register.simple_tag(takes_context=True)
def namespace_url(context, view_name, *args, **kwargs):
"""
Returns an absolute URL matching given view with its parameters.
"""
namespace, config = get_app_instance(context['request'])
if not 'current_app' in kwargs:
kwargs['current_app'] = namespace
return urlresolvers.reverse('%s:%s' % (config.namespace, view_name),
args=args,
kwargs=kwargs)
## Instruction:
Use string.format for performance reasons
## Code After:
from django import template
from django.core import urlresolvers
from ..utils import get_app_instance
register = template.Library()
@register.simple_tag(takes_context=True)
def namespace_url(context, view_name, *args, **kwargs):
"""
Returns an absolute URL matching given view with its parameters.
"""
namespace, config = get_app_instance(context['request'])
if not 'current_app' in kwargs:
kwargs['current_app'] = namespace
return urlresolvers.reverse(
'{0:s}:{1:s}'.format(config.namespace, view_name),
args=args,
kwargs=kwargs)
|
d68bdfe0b89137efc6b0c167663a0edf7decb4cd | nashvegas/management/commands/syncdb.py | nashvegas/management/commands/syncdb.py | from django.core.management import call_command
from django.core.management.commands.syncdb import Command as SyncDBCommand
class Command(SyncDBCommand):
def handle_noargs(self, **options):
# Run migrations first
if options.get('database'):
databases = [options.get('database')]
else:
databases = None
call_command("upgradedb",
do_execute=True,
databases=databases,
interactive=options.get('interactive'),
verbosity=options.get('verbosity'),
)
# Follow up with a syncdb on anything that wasnt included in migrations
# (this catches things like test-only models)
super(Command, self).handle_noargs(**options)
| from django.core.management import call_command
from django.core.management.commands.syncdb import Command as SyncDBCommand
class Command(SyncDBCommand):
def handle_noargs(self, **options):
# Run migrations first
if options.get("database"):
databases = [options.get("database")]
else:
databases = None
call_command("upgradedb",
do_execute=True,
databases=databases,
interactive=options.get("interactive"),
verbosity=options.get("verbosity"),
)
# Follow up with a syncdb on anything that wasnt included in migrations
# (this catches things like test-only models)
super(Command, self).handle_noargs(**options)
| Update style to be consistent with project | Update style to be consistent with project | Python | mit | dcramer/nashvegas,iivvoo/nashvegas,paltman/nashvegas,paltman-archive/nashvegas,jonathanchu/nashvegas | from django.core.management import call_command
from django.core.management.commands.syncdb import Command as SyncDBCommand
class Command(SyncDBCommand):
def handle_noargs(self, **options):
# Run migrations first
- if options.get('database'):
+ if options.get("database"):
- databases = [options.get('database')]
+ databases = [options.get("database")]
else:
databases = None
-
+
call_command("upgradedb",
do_execute=True,
databases=databases,
- interactive=options.get('interactive'),
+ interactive=options.get("interactive"),
- verbosity=options.get('verbosity'),
+ verbosity=options.get("verbosity"),
)
-
+
# Follow up with a syncdb on anything that wasnt included in migrations
# (this catches things like test-only models)
super(Command, self).handle_noargs(**options)
| Update style to be consistent with project | ## Code Before:
from django.core.management import call_command
from django.core.management.commands.syncdb import Command as SyncDBCommand
class Command(SyncDBCommand):
def handle_noargs(self, **options):
# Run migrations first
if options.get('database'):
databases = [options.get('database')]
else:
databases = None
call_command("upgradedb",
do_execute=True,
databases=databases,
interactive=options.get('interactive'),
verbosity=options.get('verbosity'),
)
# Follow up with a syncdb on anything that wasnt included in migrations
# (this catches things like test-only models)
super(Command, self).handle_noargs(**options)
## Instruction:
Update style to be consistent with project
## Code After:
from django.core.management import call_command
from django.core.management.commands.syncdb import Command as SyncDBCommand
class Command(SyncDBCommand):
def handle_noargs(self, **options):
# Run migrations first
if options.get("database"):
databases = [options.get("database")]
else:
databases = None
call_command("upgradedb",
do_execute=True,
databases=databases,
interactive=options.get("interactive"),
verbosity=options.get("verbosity"),
)
# Follow up with a syncdb on anything that wasnt included in migrations
# (this catches things like test-only models)
super(Command, self).handle_noargs(**options)
|
6c98f48acd3cc91faeee2d6e24784275eedbd1ea | saw-remote-api/python/tests/saw/test_basic_java.py | saw-remote-api/python/tests/saw/test_basic_java.py | import unittest
from pathlib import Path
import saw_client as saw
from saw_client.jvm import Contract, java_int, cryptol
class Add(Contract):
def __init__(self) -> None:
super().__init__()
def specification(self) -> None:
x = self.fresh_var(java_int, "x")
y = self.fresh_var(java_int, "y")
self.execute_func(x, y)
self.returns(cryptol("(+)")(x,y))
class AddTest(unittest.TestCase):
def test_add(self):
saw.connect(reset_server=True)
if __name__ == "__main__": saw.view(saw.LogResults())
cls = saw.jvm_load_class("Add")
result = saw.jvm_verify(cls, 'add', Add())
self.assertIs(result.is_success(), True)
if __name__ == "__main__":
unittest.main()
| import unittest
from pathlib import Path
import saw_client as saw
from saw_client.jvm import Contract, java_int, cryptol
class Add(Contract):
def __init__(self) -> None:
super().__init__()
def specification(self) -> None:
x = self.fresh_var(java_int, "x")
y = self.fresh_var(java_int, "y")
self.execute_func(x, y)
self.returns(cryptol("(+)")(x,y))
class Double(Contract):
def __init__(self) -> None:
super().__init__()
def specification(self) -> None:
x = self.fresh_var(java_int, "x")
self.execute_func(x)
self.returns(cryptol("(+)")(x,x))
class AddTest(unittest.TestCase):
def test_add(self):
saw.connect(reset_server=True)
if __name__ == "__main__": saw.view(saw.LogResults())
cls = saw.jvm_load_class("Add")
add_result1 = saw.jvm_verify(cls, 'add', Add())
self.assertIs(add_result1.is_success(), True)
add_result2 = saw.jvm_assume(cls, 'add', Add())
self.assertIs(add_result2.is_success(), True)
dbl_result1 = saw.jvm_verify(cls, 'dbl', Double(), lemmas=[add_result1])
self.assertIs(dbl_result1.is_success(), True)
dbl_result2 = saw.jvm_verify(cls, 'dbl', Double(), lemmas=[add_result2])
self.assertIs(dbl_result2.is_success(), True)
if __name__ == "__main__":
unittest.main()
| Test assumption, composition for RPC Java proofs | Test assumption, composition for RPC Java proofs
| Python | bsd-3-clause | GaloisInc/saw-script,GaloisInc/saw-script,GaloisInc/saw-script,GaloisInc/saw-script,GaloisInc/saw-script | import unittest
from pathlib import Path
import saw_client as saw
from saw_client.jvm import Contract, java_int, cryptol
class Add(Contract):
def __init__(self) -> None:
super().__init__()
def specification(self) -> None:
x = self.fresh_var(java_int, "x")
y = self.fresh_var(java_int, "y")
self.execute_func(x, y)
self.returns(cryptol("(+)")(x,y))
+ class Double(Contract):
+ def __init__(self) -> None:
+ super().__init__()
+
+ def specification(self) -> None:
+ x = self.fresh_var(java_int, "x")
+
+ self.execute_func(x)
+
+ self.returns(cryptol("(+)")(x,x))
+
class AddTest(unittest.TestCase):
def test_add(self):
saw.connect(reset_server=True)
if __name__ == "__main__": saw.view(saw.LogResults())
cls = saw.jvm_load_class("Add")
- result = saw.jvm_verify(cls, 'add', Add())
+ add_result1 = saw.jvm_verify(cls, 'add', Add())
- self.assertIs(result.is_success(), True)
+ self.assertIs(add_result1.is_success(), True)
+ add_result2 = saw.jvm_assume(cls, 'add', Add())
+ self.assertIs(add_result2.is_success(), True)
+
+ dbl_result1 = saw.jvm_verify(cls, 'dbl', Double(), lemmas=[add_result1])
+ self.assertIs(dbl_result1.is_success(), True)
+ dbl_result2 = saw.jvm_verify(cls, 'dbl', Double(), lemmas=[add_result2])
+ self.assertIs(dbl_result2.is_success(), True)
if __name__ == "__main__":
unittest.main()
| Test assumption, composition for RPC Java proofs | ## Code Before:
import unittest
from pathlib import Path
import saw_client as saw
from saw_client.jvm import Contract, java_int, cryptol
class Add(Contract):
def __init__(self) -> None:
super().__init__()
def specification(self) -> None:
x = self.fresh_var(java_int, "x")
y = self.fresh_var(java_int, "y")
self.execute_func(x, y)
self.returns(cryptol("(+)")(x,y))
class AddTest(unittest.TestCase):
def test_add(self):
saw.connect(reset_server=True)
if __name__ == "__main__": saw.view(saw.LogResults())
cls = saw.jvm_load_class("Add")
result = saw.jvm_verify(cls, 'add', Add())
self.assertIs(result.is_success(), True)
if __name__ == "__main__":
unittest.main()
## Instruction:
Test assumption, composition for RPC Java proofs
## Code After:
import unittest
from pathlib import Path
import saw_client as saw
from saw_client.jvm import Contract, java_int, cryptol
class Add(Contract):
def __init__(self) -> None:
super().__init__()
def specification(self) -> None:
x = self.fresh_var(java_int, "x")
y = self.fresh_var(java_int, "y")
self.execute_func(x, y)
self.returns(cryptol("(+)")(x,y))
class Double(Contract):
def __init__(self) -> None:
super().__init__()
def specification(self) -> None:
x = self.fresh_var(java_int, "x")
self.execute_func(x)
self.returns(cryptol("(+)")(x,x))
class AddTest(unittest.TestCase):
def test_add(self):
saw.connect(reset_server=True)
if __name__ == "__main__": saw.view(saw.LogResults())
cls = saw.jvm_load_class("Add")
add_result1 = saw.jvm_verify(cls, 'add', Add())
self.assertIs(add_result1.is_success(), True)
add_result2 = saw.jvm_assume(cls, 'add', Add())
self.assertIs(add_result2.is_success(), True)
dbl_result1 = saw.jvm_verify(cls, 'dbl', Double(), lemmas=[add_result1])
self.assertIs(dbl_result1.is_success(), True)
dbl_result2 = saw.jvm_verify(cls, 'dbl', Double(), lemmas=[add_result2])
self.assertIs(dbl_result2.is_success(), True)
if __name__ == "__main__":
unittest.main()
|
1541af9052d9c12fb3d23832838fce69fcc02761 | pywal/export_colors.py | pywal/export_colors.py | import os
import pathlib
from pywal.settings import CACHE_DIR, TEMPLATE_DIR
from pywal import util
def template(colors, input_file):
"""Read template file, substitute markers and
save the file elsewhere."""
template_file = pathlib.Path(TEMPLATE_DIR).joinpath(input_file)
export_file = pathlib.Path(CACHE_DIR).joinpath(input_file)
# Import the template.
with open(template_file) as file:
template_data = file.readlines()
# Format the markers.
template_data = "".join(template_data).format(**colors)
# Export the template.
with open(export_file, "w") as file:
file.write(template_data)
def export_all_templates(colors):
"""Export all template files."""
# Merge both dicts.
colors["colors"].update(colors["special"])
# pylint: disable=W0106
[template(colors["colors"], file.name)
for file in os.scandir(TEMPLATE_DIR)]
| import os
import pathlib
from pywal.settings import CACHE_DIR, TEMPLATE_DIR
from pywal import util
def template(colors, input_file):
"""Read template file, substitute markers and
save the file elsewhere."""
template_file = pathlib.Path(TEMPLATE_DIR).joinpath(input_file)
export_file = pathlib.Path(CACHE_DIR).joinpath(input_file)
# Import the template.
with open(template_file) as file:
template_data = file.readlines()
# Format the markers.
template_data = "".join(template_data).format(**colors)
# Export the template.
with open(export_file, "w") as file:
file.write(template_data)
def export_all_templates(colors):
"""Export all template files."""
# Exclude these templates from the loop.
# The excluded templates need color
# conversion or other intervention.
exclude = ["colors-putty.reg"]
# Merge both dicts.
colors["colors"].update(colors["special"])
# Convert colors to other format.
colors_rgb = {k: util.hex_to_rgb(v) for k, v in colors["colors"].items()}
# pylint: disable=W0106
[template(colors["colors"], file.name)
for file in os.scandir(TEMPLATE_DIR)
if file not in exclude]
# Call 'putty' manually since it needs RGB colors.
template(colors_rgb, "colors-putty.reg")
| Convert colors to rgb for putty. | colors: Convert colors to rgb for putty.
| Python | mit | dylanaraps/pywal,dylanaraps/pywal,dylanaraps/pywal | import os
import pathlib
from pywal.settings import CACHE_DIR, TEMPLATE_DIR
from pywal import util
def template(colors, input_file):
"""Read template file, substitute markers and
save the file elsewhere."""
template_file = pathlib.Path(TEMPLATE_DIR).joinpath(input_file)
export_file = pathlib.Path(CACHE_DIR).joinpath(input_file)
# Import the template.
with open(template_file) as file:
template_data = file.readlines()
# Format the markers.
template_data = "".join(template_data).format(**colors)
# Export the template.
with open(export_file, "w") as file:
file.write(template_data)
def export_all_templates(colors):
"""Export all template files."""
+ # Exclude these templates from the loop.
+ # The excluded templates need color
+ # conversion or other intervention.
+ exclude = ["colors-putty.reg"]
+
# Merge both dicts.
colors["colors"].update(colors["special"])
+ # Convert colors to other format.
+ colors_rgb = {k: util.hex_to_rgb(v) for k, v in colors["colors"].items()}
+
# pylint: disable=W0106
[template(colors["colors"], file.name)
- for file in os.scandir(TEMPLATE_DIR)]
+ for file in os.scandir(TEMPLATE_DIR)
+ if file not in exclude]
+ # Call 'putty' manually since it needs RGB colors.
+ template(colors_rgb, "colors-putty.reg")
+ | Convert colors to rgb for putty. | ## Code Before:
import os
import pathlib
from pywal.settings import CACHE_DIR, TEMPLATE_DIR
from pywal import util
def template(colors, input_file):
"""Read template file, substitute markers and
save the file elsewhere."""
template_file = pathlib.Path(TEMPLATE_DIR).joinpath(input_file)
export_file = pathlib.Path(CACHE_DIR).joinpath(input_file)
# Import the template.
with open(template_file) as file:
template_data = file.readlines()
# Format the markers.
template_data = "".join(template_data).format(**colors)
# Export the template.
with open(export_file, "w") as file:
file.write(template_data)
def export_all_templates(colors):
"""Export all template files."""
# Merge both dicts.
colors["colors"].update(colors["special"])
# pylint: disable=W0106
[template(colors["colors"], file.name)
for file in os.scandir(TEMPLATE_DIR)]
## Instruction:
Convert colors to rgb for putty.
## Code After:
import os
import pathlib
from pywal.settings import CACHE_DIR, TEMPLATE_DIR
from pywal import util
def template(colors, input_file):
"""Read template file, substitute markers and
save the file elsewhere."""
template_file = pathlib.Path(TEMPLATE_DIR).joinpath(input_file)
export_file = pathlib.Path(CACHE_DIR).joinpath(input_file)
# Import the template.
with open(template_file) as file:
template_data = file.readlines()
# Format the markers.
template_data = "".join(template_data).format(**colors)
# Export the template.
with open(export_file, "w") as file:
file.write(template_data)
def export_all_templates(colors):
"""Export all template files."""
# Exclude these templates from the loop.
# The excluded templates need color
# conversion or other intervention.
exclude = ["colors-putty.reg"]
# Merge both dicts.
colors["colors"].update(colors["special"])
# Convert colors to other format.
colors_rgb = {k: util.hex_to_rgb(v) for k, v in colors["colors"].items()}
# pylint: disable=W0106
[template(colors["colors"], file.name)
for file in os.scandir(TEMPLATE_DIR)
if file not in exclude]
# Call 'putty' manually since it needs RGB colors.
template(colors_rgb, "colors-putty.reg")
|
6fa924d73df148ad3cfe41b01e277d944071e4dd | equajson.py | equajson.py | from __future__ import print_function
import os
import sys
import json
def pretty_print(equation):
print(equation["description"]["terse"])
eqn_dict = equation["unicode-pretty-print"]
equation_text = eqn_dict["multiline"]
for line in equation_text:
print(line)
if "parameters" in eqn_dict:
print("where:")
for param, param_dict in eqn_dict["parameters"].iteritems():
label = param_dict["label"]
print(param,'=',label)
def main(query):
here = sys.path[0]
json_dir = os.path.join(here, 'equajson')
for filename in os.listdir(json_dir):
if not filename.endswith('.json'):
continue
filepath = os.path.join(json_dir, filename)
with open(filepath) as json_file:
try:
equation = json.load(json_file)
except ValueError:
sys.stderr.write("Invalid JSON for file: `{}'\n".format(json_file.name))
continue # try the next file
description = equation["description"]["verbose"]
if query.lower() in description.lower():
pretty_print(equation)
if __name__ == '__main__':
num_args = len(sys.argv) - 1
if num_args != 1:
sys.stderr.write("Usage: python "+sys.argv[0]+" query"+'\n')
sys.exit(1)
main(sys.argv[1])
| from __future__ import print_function
import os
import sys
import json
def pretty_print(equation):
print(equation["description"]["terse"])
eqn_dict = equation["unicode-pretty-print"]
equation_text = eqn_dict["multiline"]
for line in equation_text:
print(line)
if "parameters" in eqn_dict:
print("where:")
for param, param_dict in eqn_dict["parameters"].iteritems():
label = param_dict["label"]
print(param,'=',label)
def main(query):
here = sys.path[0]
json_dir = os.path.join(here, 'equajson')
for filename in os.listdir(json_dir):
if not filename.endswith('.json'):
continue
filepath = os.path.join(json_dir, filename)
with open(filepath) as json_file:
try:
equation = json.load(json_file)
except ValueError:
sys.stderr.write("Invalid JSON for file: `{}'\n".format(json_file.name))
continue # try the next file
description = equation["description"]["verbose"]
if query.lower() in description.lower():
pretty_print(equation)
print()
if __name__ == '__main__':
num_args = len(sys.argv) - 1
if num_args != 1:
sys.stderr.write("Usage: python "+sys.argv[0]+" query"+'\n')
sys.exit(1)
main(sys.argv[1])
| Add a line between outputs. | Add a line between outputs.
| Python | mit | nbeaver/equajson | from __future__ import print_function
import os
import sys
import json
def pretty_print(equation):
print(equation["description"]["terse"])
eqn_dict = equation["unicode-pretty-print"]
equation_text = eqn_dict["multiline"]
for line in equation_text:
print(line)
if "parameters" in eqn_dict:
print("where:")
for param, param_dict in eqn_dict["parameters"].iteritems():
label = param_dict["label"]
print(param,'=',label)
def main(query):
here = sys.path[0]
json_dir = os.path.join(here, 'equajson')
for filename in os.listdir(json_dir):
if not filename.endswith('.json'):
continue
filepath = os.path.join(json_dir, filename)
with open(filepath) as json_file:
try:
equation = json.load(json_file)
except ValueError:
sys.stderr.write("Invalid JSON for file: `{}'\n".format(json_file.name))
continue # try the next file
description = equation["description"]["verbose"]
if query.lower() in description.lower():
pretty_print(equation)
+ print()
if __name__ == '__main__':
num_args = len(sys.argv) - 1
if num_args != 1:
sys.stderr.write("Usage: python "+sys.argv[0]+" query"+'\n')
sys.exit(1)
main(sys.argv[1])
| Add a line between outputs. | ## Code Before:
from __future__ import print_function
import os
import sys
import json
def pretty_print(equation):
print(equation["description"]["terse"])
eqn_dict = equation["unicode-pretty-print"]
equation_text = eqn_dict["multiline"]
for line in equation_text:
print(line)
if "parameters" in eqn_dict:
print("where:")
for param, param_dict in eqn_dict["parameters"].iteritems():
label = param_dict["label"]
print(param,'=',label)
def main(query):
here = sys.path[0]
json_dir = os.path.join(here, 'equajson')
for filename in os.listdir(json_dir):
if not filename.endswith('.json'):
continue
filepath = os.path.join(json_dir, filename)
with open(filepath) as json_file:
try:
equation = json.load(json_file)
except ValueError:
sys.stderr.write("Invalid JSON for file: `{}'\n".format(json_file.name))
continue # try the next file
description = equation["description"]["verbose"]
if query.lower() in description.lower():
pretty_print(equation)
if __name__ == '__main__':
num_args = len(sys.argv) - 1
if num_args != 1:
sys.stderr.write("Usage: python "+sys.argv[0]+" query"+'\n')
sys.exit(1)
main(sys.argv[1])
## Instruction:
Add a line between outputs.
## Code After:
from __future__ import print_function
import os
import sys
import json
def pretty_print(equation):
print(equation["description"]["terse"])
eqn_dict = equation["unicode-pretty-print"]
equation_text = eqn_dict["multiline"]
for line in equation_text:
print(line)
if "parameters" in eqn_dict:
print("where:")
for param, param_dict in eqn_dict["parameters"].iteritems():
label = param_dict["label"]
print(param,'=',label)
def main(query):
here = sys.path[0]
json_dir = os.path.join(here, 'equajson')
for filename in os.listdir(json_dir):
if not filename.endswith('.json'):
continue
filepath = os.path.join(json_dir, filename)
with open(filepath) as json_file:
try:
equation = json.load(json_file)
except ValueError:
sys.stderr.write("Invalid JSON for file: `{}'\n".format(json_file.name))
continue # try the next file
description = equation["description"]["verbose"]
if query.lower() in description.lower():
pretty_print(equation)
print()
if __name__ == '__main__':
num_args = len(sys.argv) - 1
if num_args != 1:
sys.stderr.write("Usage: python "+sys.argv[0]+" query"+'\n')
sys.exit(1)
main(sys.argv[1])
|
8fb15f3a072d516e477449c2b751226494ee14c5 | perfkitbenchmarker/benchmarks/__init__.py | perfkitbenchmarker/benchmarks/__init__.py | """Contains all benchmark imports and a list of benchmarks."""
import pkgutil
def _LoadModules():
result = []
for importer, modname, ispkg in pkgutil.iter_modules(__path__):
result.append(importer.find_module(modname).load_module(modname))
return result
BENCHMARKS = _LoadModules()
|
import importlib
import pkgutil
def _LoadModulesForPath(path, package_prefix=None):
"""Load all modules on 'path', with prefix 'package_prefix'.
Example usage:
_LoadModulesForPath(__path__, __name__)
Args:
path: Path containing python modules.
package_prefix: prefix (e.g., package name) to prefix all modules.
'path' and 'package_prefix' will be joined with a '.'.
Yields:
Imported modules.
"""
prefix = ''
if package_prefix:
prefix = package_prefix + '.'
module_iter = pkgutil.iter_modules(path, prefix=prefix)
for _, modname, ispkg in module_iter:
if not ispkg:
yield importlib.import_module(modname)
def _LoadBenchmarks():
return list(_LoadModulesForPath(__path__, __name__))
BENCHMARKS = _LoadBenchmarks()
| Fix a bug in dynamic benchmark loading. | Fix a bug in dynamic benchmark loading.
perfkitbenchmarker/benchmarks/__init__.py used ImpImporter.load_module
to import benchmarks, which caused an error when they were later
imported directly by an import statement. Switched to 'importlib' to resolve.
| Python | apache-2.0 | GoogleCloudPlatform/PerfKitBenchmarker,lleszczu/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,msurovcak/PerfKitBenchmarker,tvansteenburgh/PerfKitBenchmarker,ksasi/PerfKitBenchmarker,juju-solutions/PerfKitBenchmarker,gablg1/PerfKitBenchmarker,juju-solutions/PerfKitBenchmarker,msurovcak/PerfKitBenchmarker,syed/PerfKitBenchmarker,askdaddy/PerfKitBenchmarker,ehankland/PerfKitBenchmarker,AdamIsrael/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,ksasi/PerfKitBenchmarker,askdaddy/PerfKitBenchmarker,meteorfox/PerfKitBenchmarker,meteorfox/PerfKitBenchmarker,tvansteenburgh/PerfKitBenchmarker,lleszczu/PerfKitBenchmarker,kivio/PerfKitBenchmarker,syed/PerfKitBenchmarker,mateusz-blaszkowski/PerfKitBenchmarker,ehankland/PerfKitBenchmarker,AdamIsrael/PerfKitBenchmarker,kivio/PerfKitBenchmarker,mateusz-blaszkowski/PerfKitBenchmarker,emaeliena/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,emaeliena/PerfKitBenchmarker,gablg1/PerfKitBenchmarker | - """Contains all benchmark imports and a list of benchmarks."""
+ import importlib
import pkgutil
- def _LoadModules():
- result = []
- for importer, modname, ispkg in pkgutil.iter_modules(__path__):
- result.append(importer.find_module(modname).load_module(modname))
- return result
+ def _LoadModulesForPath(path, package_prefix=None):
+ """Load all modules on 'path', with prefix 'package_prefix'.
+
+ Example usage:
+ _LoadModulesForPath(__path__, __name__)
+
+ Args:
+ path: Path containing python modules.
+ package_prefix: prefix (e.g., package name) to prefix all modules.
+ 'path' and 'package_prefix' will be joined with a '.'.
+ Yields:
+ Imported modules.
+ """
+ prefix = ''
+ if package_prefix:
+ prefix = package_prefix + '.'
+ module_iter = pkgutil.iter_modules(path, prefix=prefix)
+ for _, modname, ispkg in module_iter:
+ if not ispkg:
+ yield importlib.import_module(modname)
- BENCHMARKS = _LoadModules()
+ def _LoadBenchmarks():
+ return list(_LoadModulesForPath(__path__, __name__))
+
+ BENCHMARKS = _LoadBenchmarks()
+ | Fix a bug in dynamic benchmark loading. | ## Code Before:
"""Contains all benchmark imports and a list of benchmarks."""
import pkgutil
def _LoadModules():
result = []
for importer, modname, ispkg in pkgutil.iter_modules(__path__):
result.append(importer.find_module(modname).load_module(modname))
return result
BENCHMARKS = _LoadModules()
## Instruction:
Fix a bug in dynamic benchmark loading.
## Code After:
import importlib
import pkgutil
def _LoadModulesForPath(path, package_prefix=None):
"""Load all modules on 'path', with prefix 'package_prefix'.
Example usage:
_LoadModulesForPath(__path__, __name__)
Args:
path: Path containing python modules.
package_prefix: prefix (e.g., package name) to prefix all modules.
'path' and 'package_prefix' will be joined with a '.'.
Yields:
Imported modules.
"""
prefix = ''
if package_prefix:
prefix = package_prefix + '.'
module_iter = pkgutil.iter_modules(path, prefix=prefix)
for _, modname, ispkg in module_iter:
if not ispkg:
yield importlib.import_module(modname)
def _LoadBenchmarks():
return list(_LoadModulesForPath(__path__, __name__))
BENCHMARKS = _LoadBenchmarks()
|
167ca3f2a91cd20f38b32ab204855a1e86785c67 | st2common/st2common/constants/meta.py | st2common/st2common/constants/meta.py |
from __future__ import absolute_import
import yaml
try:
from yaml import CSafeLoader as YamlSafeLoader
except ImportError:
from yaml import SafeLoader as YamlSafeLoader
__all__ = ["ALLOWED_EXTS", "PARSER_FUNCS"]
# NOTE: We utilize CSafeLoader if available since it uses C extensions and is faster.
def yaml_safe_load(stream):
return yaml.load(stream, Loader=YamlSafeLoader)
ALLOWED_EXTS = [".yaml", ".yml"]
PARSER_FUNCS = {".yml": yaml_safe_load, ".yaml": yaml_safe_load}
|
from __future__ import absolute_import
import yaml
try:
from yaml import CSafeLoader as YamlSafeLoader
except ImportError:
from yaml import SafeLoader as YamlSafeLoader
__all__ = ["ALLOWED_EXTS", "PARSER_FUNCS"]
# NOTE: We utilize CSafeLoader if available since it uses C extensions and is faster.
#
# SafeLoader / CSafeLoader are both safe to use and don't allow loading arbitrary Python objects.
#
# That's the actual class which is used internally by ``yaml.safe_load()``, but we can't use that
# method directly since we want to use C extension if available (CSafeLoader) for faster parsing.
#
# See pyyaml docs for details https://pyyaml.org/wiki/PyYAMLDocumentation
def yaml_safe_load(stream):
return yaml.load(stream, Loader=YamlSafeLoader)
ALLOWED_EXTS = [".yaml", ".yml"]
PARSER_FUNCS = {".yml": yaml_safe_load, ".yaml": yaml_safe_load}
| Add a comment to custom yaml_safe_load() method. | Add a comment to custom yaml_safe_load() method.
| Python | apache-2.0 | StackStorm/st2,StackStorm/st2,Plexxi/st2,StackStorm/st2,nzlosh/st2,StackStorm/st2,Plexxi/st2,Plexxi/st2,Plexxi/st2,nzlosh/st2,nzlosh/st2,nzlosh/st2 |
from __future__ import absolute_import
import yaml
try:
from yaml import CSafeLoader as YamlSafeLoader
except ImportError:
from yaml import SafeLoader as YamlSafeLoader
__all__ = ["ALLOWED_EXTS", "PARSER_FUNCS"]
# NOTE: We utilize CSafeLoader if available since it uses C extensions and is faster.
+ #
+ # SafeLoader / CSafeLoader are both safe to use and don't allow loading arbitrary Python objects.
+ #
+ # That's the actual class which is used internally by ``yaml.safe_load()``, but we can't use that
+ # method directly since we want to use C extension if available (CSafeLoader) for faster parsing.
+ #
+ # See pyyaml docs for details https://pyyaml.org/wiki/PyYAMLDocumentation
def yaml_safe_load(stream):
return yaml.load(stream, Loader=YamlSafeLoader)
ALLOWED_EXTS = [".yaml", ".yml"]
PARSER_FUNCS = {".yml": yaml_safe_load, ".yaml": yaml_safe_load}
| Add a comment to custom yaml_safe_load() method. | ## Code Before:
from __future__ import absolute_import
import yaml
try:
from yaml import CSafeLoader as YamlSafeLoader
except ImportError:
from yaml import SafeLoader as YamlSafeLoader
__all__ = ["ALLOWED_EXTS", "PARSER_FUNCS"]
# NOTE: We utilize CSafeLoader if available since it uses C extensions and is faster.
def yaml_safe_load(stream):
return yaml.load(stream, Loader=YamlSafeLoader)
ALLOWED_EXTS = [".yaml", ".yml"]
PARSER_FUNCS = {".yml": yaml_safe_load, ".yaml": yaml_safe_load}
## Instruction:
Add a comment to custom yaml_safe_load() method.
## Code After:
from __future__ import absolute_import
import yaml
try:
from yaml import CSafeLoader as YamlSafeLoader
except ImportError:
from yaml import SafeLoader as YamlSafeLoader
__all__ = ["ALLOWED_EXTS", "PARSER_FUNCS"]
# NOTE: We utilize CSafeLoader if available since it uses C extensions and is faster.
#
# SafeLoader / CSafeLoader are both safe to use and don't allow loading arbitrary Python objects.
#
# That's the actual class which is used internally by ``yaml.safe_load()``, but we can't use that
# method directly since we want to use C extension if available (CSafeLoader) for faster parsing.
#
# See pyyaml docs for details https://pyyaml.org/wiki/PyYAMLDocumentation
def yaml_safe_load(stream):
return yaml.load(stream, Loader=YamlSafeLoader)
ALLOWED_EXTS = [".yaml", ".yml"]
PARSER_FUNCS = {".yml": yaml_safe_load, ".yaml": yaml_safe_load}
|
7a281be50ba1fc59281a76470776fa9c8efdfd54 | pijobs/scrolljob.py | pijobs/scrolljob.py | import scrollphat
from pijobs.scrollphatjob import ScrollphatJob
class ScrollJob(ScrollphatJob):
def default_options(self):
opts = {
'brightness': 2,
'interval': 0.1,
'sleep': 1.0,
}
return opts
def init(self):
self.set_brightness()
self.write_message()
def write_message(self):
message = self.parse_message()
scrollphat.write_string(message, 11)
def message(self):
return self.options['message']
def parse_message(self):
message = self.message() + ' '
if self.options['upper'] == True:
message = message.upper()
return message
def run(self):
length = scrollphat.buffer_len()
if self.options['loop'] == True:
counter = 0
while True:
self.scroll()
counter += 1
if counter % length == 0:
time.sleep(self.options['sleep'])
else:
for i in range(length):
self.scroll()
self.sleep()
def scroll(self):
scrollphat.scroll()
self.sleep_interval()
| import scrollphat
from pijobs.scrollphatjob import ScrollphatJob
class ScrollJob(ScrollphatJob):
def default_options(self):
opts = {
'brightness': 2,
'interval': 0.1,
'sleep': 1.0,
}
return opts
def init(self):
self.set_brightness()
self.set_rotate()
self.write_message()
def write_message(self):
message = self.parse_message()
scrollphat.write_string(message, 11)
def message(self):
return self.options['message']
def parse_message(self):
message = self.message() + ' '
if self.options['upper'] == True:
message = message.upper()
return message
def run(self):
length = scrollphat.buffer_len()
if self.options['loop'] == True:
counter = 0
while True:
self.scroll()
counter += 1
if counter % length == 0:
time.sleep(self.options['sleep'])
else:
for i in range(length):
self.scroll()
self.sleep()
def scroll(self):
scrollphat.scroll()
self.sleep_interval()
| Add back rotatation for scroll job. | Add back rotatation for scroll job.
| Python | mit | ollej/piapi,ollej/piapi | import scrollphat
from pijobs.scrollphatjob import ScrollphatJob
class ScrollJob(ScrollphatJob):
def default_options(self):
opts = {
'brightness': 2,
'interval': 0.1,
'sleep': 1.0,
}
return opts
def init(self):
self.set_brightness()
+ self.set_rotate()
self.write_message()
def write_message(self):
message = self.parse_message()
scrollphat.write_string(message, 11)
def message(self):
return self.options['message']
def parse_message(self):
message = self.message() + ' '
if self.options['upper'] == True:
message = message.upper()
return message
def run(self):
length = scrollphat.buffer_len()
if self.options['loop'] == True:
counter = 0
while True:
self.scroll()
counter += 1
if counter % length == 0:
time.sleep(self.options['sleep'])
else:
for i in range(length):
self.scroll()
self.sleep()
def scroll(self):
scrollphat.scroll()
self.sleep_interval()
| Add back rotatation for scroll job. | ## Code Before:
import scrollphat
from pijobs.scrollphatjob import ScrollphatJob
class ScrollJob(ScrollphatJob):
def default_options(self):
opts = {
'brightness': 2,
'interval': 0.1,
'sleep': 1.0,
}
return opts
def init(self):
self.set_brightness()
self.write_message()
def write_message(self):
message = self.parse_message()
scrollphat.write_string(message, 11)
def message(self):
return self.options['message']
def parse_message(self):
message = self.message() + ' '
if self.options['upper'] == True:
message = message.upper()
return message
def run(self):
length = scrollphat.buffer_len()
if self.options['loop'] == True:
counter = 0
while True:
self.scroll()
counter += 1
if counter % length == 0:
time.sleep(self.options['sleep'])
else:
for i in range(length):
self.scroll()
self.sleep()
def scroll(self):
scrollphat.scroll()
self.sleep_interval()
## Instruction:
Add back rotatation for scroll job.
## Code After:
import scrollphat
from pijobs.scrollphatjob import ScrollphatJob
class ScrollJob(ScrollphatJob):
def default_options(self):
opts = {
'brightness': 2,
'interval': 0.1,
'sleep': 1.0,
}
return opts
def init(self):
self.set_brightness()
self.set_rotate()
self.write_message()
def write_message(self):
message = self.parse_message()
scrollphat.write_string(message, 11)
def message(self):
return self.options['message']
def parse_message(self):
message = self.message() + ' '
if self.options['upper'] == True:
message = message.upper()
return message
def run(self):
length = scrollphat.buffer_len()
if self.options['loop'] == True:
counter = 0
while True:
self.scroll()
counter += 1
if counter % length == 0:
time.sleep(self.options['sleep'])
else:
for i in range(length):
self.scroll()
self.sleep()
def scroll(self):
scrollphat.scroll()
self.sleep_interval()
|
592ffbcd7fbbc29bfd377b5abadb39aa29f1c88d | foyer/tests/conftest.py | foyer/tests/conftest.py | import pytest
@pytest.fixture(scope="session")
def initdir(tmpdir):
tmpdir.chdir()
| import pytest
@pytest.fixture(autouse=True)
def initdir(tmpdir):
tmpdir.chdir()
| Switch from scope="session" to autouse=True | Switch from scope="session" to autouse=True
| Python | mit | iModels/foyer,mosdef-hub/foyer,mosdef-hub/foyer,iModels/foyer | import pytest
- @pytest.fixture(scope="session")
+ @pytest.fixture(autouse=True)
def initdir(tmpdir):
tmpdir.chdir()
| Switch from scope="session" to autouse=True | ## Code Before:
import pytest
@pytest.fixture(scope="session")
def initdir(tmpdir):
tmpdir.chdir()
## Instruction:
Switch from scope="session" to autouse=True
## Code After:
import pytest
@pytest.fixture(autouse=True)
def initdir(tmpdir):
tmpdir.chdir()
|
693dc9d8448740e1a1c4543cc3a91e3769fa7a3e | pySPM/utils/plot.py | pySPM/utils/plot.py | import numpy as np
import matplotlib.pyplot as plt
def plotMask(ax, mask, color, **kargs):
import copy
m = np.ma.masked_array(mask, ~mask)
palette = copy.copy(plt.cm.gray)
palette.set_over(color, 1.0)
ax.imshow(m, cmap=palette, vmin=0, vmax=0.5, **kargs)
def Xdist(ax,left, right, y, color='r', linestyle=':', fmt='.2f', xtransf=lambda x: x, **kargs):
ax.axvline(left,color=color, linestyle=linestyle)
ax.axvline(right,color=color, linestyle=linestyle)
s = "{:"+fmt+"}"+kargs.get('unit','')
ax.annotate(s.format(xtransf(right-left)),(.5*(left+right),y),(0,2),textcoords='offset pixels',va='bottom',ha='center')
ax.annotate("",(left,y),(right,y),arrowprops=dict(arrowstyle=kargs.get('arrowstyle','<->'))) | import numpy as np
import matplotlib.pyplot as plt
def plotMask(ax, mask, color, **kargs):
import copy
m = np.ma.masked_array(mask, ~mask)
palette = copy.copy(plt.cm.gray)
palette.set_over(color, 1.0)
ax.imshow(m, cmap=palette, vmin=0, vmax=0.5, **kargs)
def Xdist(ax,left, right, y, color='r', linestyle=':', fmt='.2f', xtransf=lambda x: x, **kargs):
ax.axvline(left,color=color, linestyle=linestyle)
ax.axvline(right,color=color, linestyle=linestyle)
s = "{:"+fmt+"}"+kargs.get('unit','')
ax.annotate(s.format(xtransf(right-left)),(.5*(left+right),y),(0,2),textcoords='offset pixels',va='bottom',ha='center')
ax.annotate("",(left,y),(right,y),arrowprops=dict(arrowstyle=kargs.get('arrowstyle','<->')))
def DualPlot(ax, col1='C0',col2='C1'):
axb = ax.twinx()
axb.spines['left'].set_color(col1)
axb.spines['right'].set_color(col2)
ax.yaxis.label.set_color(col1)
axb.yaxis.label.set_color(col2)
ax.tick_params(axis='y', colors=col1)
axb.tick_params(axis='y', colors=col2)
return axb | Add helper function to create a DualPlot | Add helper function to create a DualPlot
| Python | apache-2.0 | scholi/pySPM | import numpy as np
import matplotlib.pyplot as plt
def plotMask(ax, mask, color, **kargs):
import copy
m = np.ma.masked_array(mask, ~mask)
palette = copy.copy(plt.cm.gray)
palette.set_over(color, 1.0)
ax.imshow(m, cmap=palette, vmin=0, vmax=0.5, **kargs)
def Xdist(ax,left, right, y, color='r', linestyle=':', fmt='.2f', xtransf=lambda x: x, **kargs):
ax.axvline(left,color=color, linestyle=linestyle)
ax.axvline(right,color=color, linestyle=linestyle)
s = "{:"+fmt+"}"+kargs.get('unit','')
ax.annotate(s.format(xtransf(right-left)),(.5*(left+right),y),(0,2),textcoords='offset pixels',va='bottom',ha='center')
ax.annotate("",(left,y),(right,y),arrowprops=dict(arrowstyle=kargs.get('arrowstyle','<->')))
+
+ def DualPlot(ax, col1='C0',col2='C1'):
+ axb = ax.twinx()
+ axb.spines['left'].set_color(col1)
+ axb.spines['right'].set_color(col2)
+ ax.yaxis.label.set_color(col1)
+ axb.yaxis.label.set_color(col2)
+ ax.tick_params(axis='y', colors=col1)
+ axb.tick_params(axis='y', colors=col2)
+ return axb | Add helper function to create a DualPlot | ## Code Before:
import numpy as np
import matplotlib.pyplot as plt
def plotMask(ax, mask, color, **kargs):
import copy
m = np.ma.masked_array(mask, ~mask)
palette = copy.copy(plt.cm.gray)
palette.set_over(color, 1.0)
ax.imshow(m, cmap=palette, vmin=0, vmax=0.5, **kargs)
def Xdist(ax,left, right, y, color='r', linestyle=':', fmt='.2f', xtransf=lambda x: x, **kargs):
ax.axvline(left,color=color, linestyle=linestyle)
ax.axvline(right,color=color, linestyle=linestyle)
s = "{:"+fmt+"}"+kargs.get('unit','')
ax.annotate(s.format(xtransf(right-left)),(.5*(left+right),y),(0,2),textcoords='offset pixels',va='bottom',ha='center')
ax.annotate("",(left,y),(right,y),arrowprops=dict(arrowstyle=kargs.get('arrowstyle','<->')))
## Instruction:
Add helper function to create a DualPlot
## Code After:
import numpy as np
import matplotlib.pyplot as plt
def plotMask(ax, mask, color, **kargs):
import copy
m = np.ma.masked_array(mask, ~mask)
palette = copy.copy(plt.cm.gray)
palette.set_over(color, 1.0)
ax.imshow(m, cmap=palette, vmin=0, vmax=0.5, **kargs)
def Xdist(ax,left, right, y, color='r', linestyle=':', fmt='.2f', xtransf=lambda x: x, **kargs):
ax.axvline(left,color=color, linestyle=linestyle)
ax.axvline(right,color=color, linestyle=linestyle)
s = "{:"+fmt+"}"+kargs.get('unit','')
ax.annotate(s.format(xtransf(right-left)),(.5*(left+right),y),(0,2),textcoords='offset pixels',va='bottom',ha='center')
ax.annotate("",(left,y),(right,y),arrowprops=dict(arrowstyle=kargs.get('arrowstyle','<->')))
def DualPlot(ax, col1='C0',col2='C1'):
axb = ax.twinx()
axb.spines['left'].set_color(col1)
axb.spines['right'].set_color(col2)
ax.yaxis.label.set_color(col1)
axb.yaxis.label.set_color(col2)
ax.tick_params(axis='y', colors=col1)
axb.tick_params(axis='y', colors=col2)
return axb |
2bd551d7fa8da9d7641998a5515fba634d65bc56 | comics/feedback/views.py | comics/feedback/views.py | from django.conf import settings
from django.core.mail import mail_admins
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from comics.feedback.forms import FeedbackForm
def feedback(request):
"""Mail feedback to ADMINS"""
if request.method == 'POST':
form = FeedbackForm(request.POST)
if form.is_valid():
subject = 'Feedback from %s' % settings.COMICS_SITE_TITLE
message = form.cleaned_data['message']
mail_admins(subject, message)
return HttpResponseRedirect(reverse('feedback-thanks'))
else:
form = FeedbackForm()
return render(request, 'feedback/form.html', {'feedback_form': form})
def feedback_thanks(request):
"""Display form submit confirmation page"""
return render(request, 'feedback/thanks.html')
| from django.conf import settings
from django.core.mail import mail_admins
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from comics.feedback.forms import FeedbackForm
def feedback(request):
"""Mail feedback to ADMINS"""
if request.method == 'POST':
form = FeedbackForm(request.POST)
if form.is_valid():
subject = 'Feedback from %s' % settings.COMICS_SITE_TITLE
message = form.cleaned_data['message']
metadata = 'Client IP address: %s\n' % request.META['REMOTE_ADDR']
metadata += 'User agent: %s\n' % request.META['HTTP_USER_AGENT']
if request.user.is_authenticated():
metadata += 'User: %s <%s>\n' % (
request.user.username, request.user.email)
else:
metadata += 'User: anonymous\n'
message = '%s\n\n%s' % (message, metadata)
mail_admins(subject, message)
return HttpResponseRedirect(reverse('feedback-thanks'))
else:
form = FeedbackForm()
return render(request, 'feedback/form.html', {'feedback_form': form})
def feedback_thanks(request):
"""Display form submit confirmation page"""
return render(request, 'feedback/thanks.html')
| Add user information to feedback emails | Add user information to feedback emails
| Python | agpl-3.0 | jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics,datagutten/comics,jodal/comics | from django.conf import settings
from django.core.mail import mail_admins
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from comics.feedback.forms import FeedbackForm
def feedback(request):
"""Mail feedback to ADMINS"""
if request.method == 'POST':
form = FeedbackForm(request.POST)
if form.is_valid():
subject = 'Feedback from %s' % settings.COMICS_SITE_TITLE
message = form.cleaned_data['message']
+
+ metadata = 'Client IP address: %s\n' % request.META['REMOTE_ADDR']
+ metadata += 'User agent: %s\n' % request.META['HTTP_USER_AGENT']
+ if request.user.is_authenticated():
+ metadata += 'User: %s <%s>\n' % (
+ request.user.username, request.user.email)
+ else:
+ metadata += 'User: anonymous\n'
+ message = '%s\n\n%s' % (message, metadata)
+
mail_admins(subject, message)
return HttpResponseRedirect(reverse('feedback-thanks'))
else:
form = FeedbackForm()
return render(request, 'feedback/form.html', {'feedback_form': form})
def feedback_thanks(request):
"""Display form submit confirmation page"""
return render(request, 'feedback/thanks.html')
| Add user information to feedback emails | ## Code Before:
from django.conf import settings
from django.core.mail import mail_admins
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from comics.feedback.forms import FeedbackForm
def feedback(request):
"""Mail feedback to ADMINS"""
if request.method == 'POST':
form = FeedbackForm(request.POST)
if form.is_valid():
subject = 'Feedback from %s' % settings.COMICS_SITE_TITLE
message = form.cleaned_data['message']
mail_admins(subject, message)
return HttpResponseRedirect(reverse('feedback-thanks'))
else:
form = FeedbackForm()
return render(request, 'feedback/form.html', {'feedback_form': form})
def feedback_thanks(request):
"""Display form submit confirmation page"""
return render(request, 'feedback/thanks.html')
## Instruction:
Add user information to feedback emails
## Code After:
from django.conf import settings
from django.core.mail import mail_admins
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from comics.feedback.forms import FeedbackForm
def feedback(request):
"""Mail feedback to ADMINS"""
if request.method == 'POST':
form = FeedbackForm(request.POST)
if form.is_valid():
subject = 'Feedback from %s' % settings.COMICS_SITE_TITLE
message = form.cleaned_data['message']
metadata = 'Client IP address: %s\n' % request.META['REMOTE_ADDR']
metadata += 'User agent: %s\n' % request.META['HTTP_USER_AGENT']
if request.user.is_authenticated():
metadata += 'User: %s <%s>\n' % (
request.user.username, request.user.email)
else:
metadata += 'User: anonymous\n'
message = '%s\n\n%s' % (message, metadata)
mail_admins(subject, message)
return HttpResponseRedirect(reverse('feedback-thanks'))
else:
form = FeedbackForm()
return render(request, 'feedback/form.html', {'feedback_form': form})
def feedback_thanks(request):
"""Display form submit confirmation page"""
return render(request, 'feedback/thanks.html')
|
c7ab4bc8e0b3dbdd305a7a156ef58dddaa37296c | pystorm/__init__.py | pystorm/__init__.py | from .component import Component, Tuple
from .bolt import BatchingBolt, Bolt, TicklessBatchingBolt
from .spout import Spout
__all__ = [
'BatchingBolt',
'Bolt',
'Component',
'Spout',
'TicklessBatchingBolt',
'Tuple',
]
| '''
pystorm is a production-tested Storm multi-lang implementation for Python
It is mostly intended to be used by other libraries (e.g., streamparse).
'''
from .component import Component, Tuple
from .bolt import BatchingBolt, Bolt, TicklessBatchingBolt
from .spout import Spout
from .version import __version__, VERSION
__all__ = [
'BatchingBolt',
'Bolt',
'Component',
'Spout',
'TicklessBatchingBolt',
'Tuple',
]
| Add VERSION and __version__ directly to pystorm namespace | Add VERSION and __version__ directly to pystorm namespace
| Python | apache-2.0 | pystorm/pystorm | + '''
+ pystorm is a production-tested Storm multi-lang implementation for Python
+
+ It is mostly intended to be used by other libraries (e.g., streamparse).
+ '''
+
from .component import Component, Tuple
from .bolt import BatchingBolt, Bolt, TicklessBatchingBolt
from .spout import Spout
+ from .version import __version__, VERSION
__all__ = [
'BatchingBolt',
'Bolt',
'Component',
'Spout',
'TicklessBatchingBolt',
'Tuple',
]
| Add VERSION and __version__ directly to pystorm namespace | ## Code Before:
from .component import Component, Tuple
from .bolt import BatchingBolt, Bolt, TicklessBatchingBolt
from .spout import Spout
__all__ = [
'BatchingBolt',
'Bolt',
'Component',
'Spout',
'TicklessBatchingBolt',
'Tuple',
]
## Instruction:
Add VERSION and __version__ directly to pystorm namespace
## Code After:
'''
pystorm is a production-tested Storm multi-lang implementation for Python
It is mostly intended to be used by other libraries (e.g., streamparse).
'''
from .component import Component, Tuple
from .bolt import BatchingBolt, Bolt, TicklessBatchingBolt
from .spout import Spout
from .version import __version__, VERSION
__all__ = [
'BatchingBolt',
'Bolt',
'Component',
'Spout',
'TicklessBatchingBolt',
'Tuple',
]
|
eb0aeda225cc7c0aef85559857de4cca35b77efd | ratemyflight/urls.py | ratemyflight/urls.py |
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
urlpatterns = patterns("ratemyflight.views",
url("^api/airport/list/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$",
"airports_for_boundary", name="airports_for_boundary"),
url("^api/flight/list/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$",
"flights_for_boundary", name="flights_for_boundary"),
url("^$", "home", name="home"),
)
|
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
urlpatterns = patterns("ratemyflight.views",
url("^api/airport/boundary/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$",
"airports_for_boundary", name="airports_for_boundary"),
url("^api/flight/boundary/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$",
"flights_for_boundary", name="flights_for_boundary"),
url("^api/flight/airline/(?P<iata_code>.*)/$",
"flights_for_airline", name="flights_for_airline"),
url("^api/flight/username/(?P<username>.*)/$",
"flights_for_username", name="flights_for_username"),
url("^api/flight/recent/$", "recent_flights", name="recent_flights"),
url("^$", "home", name="home"),
)
| Clean up URLS for API and point final URLS to views. | Clean up URLS for API and point final URLS to views.
| Python | bsd-2-clause | stephenmcd/ratemyflight,stephenmcd/ratemyflight |
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
urlpatterns = patterns("ratemyflight.views",
- url("^api/airport/list/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$",
+ url("^api/airport/boundary/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$",
"airports_for_boundary", name="airports_for_boundary"),
- url("^api/flight/list/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$",
+ url("^api/flight/boundary/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$",
"flights_for_boundary", name="flights_for_boundary"),
+ url("^api/flight/airline/(?P<iata_code>.*)/$",
+ "flights_for_airline", name="flights_for_airline"),
+ url("^api/flight/username/(?P<username>.*)/$",
+ "flights_for_username", name="flights_for_username"),
+ url("^api/flight/recent/$", "recent_flights", name="recent_flights"),
url("^$", "home", name="home"),
)
| Clean up URLS for API and point final URLS to views. | ## Code Before:
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
urlpatterns = patterns("ratemyflight.views",
url("^api/airport/list/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$",
"airports_for_boundary", name="airports_for_boundary"),
url("^api/flight/list/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$",
"flights_for_boundary", name="flights_for_boundary"),
url("^$", "home", name="home"),
)
## Instruction:
Clean up URLS for API and point final URLS to views.
## Code After:
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
urlpatterns = patterns("ratemyflight.views",
url("^api/airport/boundary/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$",
"airports_for_boundary", name="airports_for_boundary"),
url("^api/flight/boundary/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$",
"flights_for_boundary", name="flights_for_boundary"),
url("^api/flight/airline/(?P<iata_code>.*)/$",
"flights_for_airline", name="flights_for_airline"),
url("^api/flight/username/(?P<username>.*)/$",
"flights_for_username", name="flights_for_username"),
url("^api/flight/recent/$", "recent_flights", name="recent_flights"),
url("^$", "home", name="home"),
)
|
1775782f100f9db9ad101a19887ba95fbc36a6e9 | backend/project_name/celerybeat_schedule.py | backend/project_name/celerybeat_schedule.py | from celery.schedules import crontab
CELERYBEAT_SCHEDULE = {
# Internal tasks
"clearsessions": {"schedule": crontab(hour=3, minute=0), "task": "users.tasks.clearsessions"},
}
| from celery.schedules import crontab # pylint:disable=import-error,no-name-in-module
CELERYBEAT_SCHEDULE = {
# Internal tasks
"clearsessions": {"schedule": crontab(hour=3, minute=0), "task": "users.tasks.clearsessions"},
}
| Disable prospector on celery.schedules import | Disable prospector on celery.schedules import
| Python | mit | vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate | - from celery.schedules import crontab
+ from celery.schedules import crontab # pylint:disable=import-error,no-name-in-module
CELERYBEAT_SCHEDULE = {
# Internal tasks
"clearsessions": {"schedule": crontab(hour=3, minute=0), "task": "users.tasks.clearsessions"},
}
| Disable prospector on celery.schedules import | ## Code Before:
from celery.schedules import crontab
CELERYBEAT_SCHEDULE = {
# Internal tasks
"clearsessions": {"schedule": crontab(hour=3, minute=0), "task": "users.tasks.clearsessions"},
}
## Instruction:
Disable prospector on celery.schedules import
## Code After:
from celery.schedules import crontab # pylint:disable=import-error,no-name-in-module
CELERYBEAT_SCHEDULE = {
# Internal tasks
"clearsessions": {"schedule": crontab(hour=3, minute=0), "task": "users.tasks.clearsessions"},
}
|
691e3581f1602714fba33f6dcb139f32e0507d23 | packages/syft/src/syft/core/node/common/node_table/setup.py | packages/syft/src/syft/core/node/common/node_table/setup.py | from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
# relative
from . import Base
class SetupConfig(Base):
__tablename__ = "setup"
id = Column(Integer(), primary_key=True, autoincrement=True)
domain_name = Column(String(255), default="")
node_id = Column(String(32), default="")
def __str__(self) -> str:
return f"<Domain Name: {self.domain_name}>"
def create_setup(id: int, domain_name: str, node_id: str) -> SetupConfig:
return SetupConfig(id=id, domain_name=domain_name, node_id=node_id)
| from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import Boolean
# relative
from . import Base
class SetupConfig(Base):
__tablename__ = "setup"
id = Column(Integer(), primary_key=True, autoincrement=True)
domain_name = Column(String(255), default="")
description = Column(String(255), default="")
contact = Column(String(255), default="")
daa = Column(Boolean(), default=False)
node_id = Column(String(32), default="")
def __str__(self) -> str:
return f"<Domain Name: {self.domain_name}>"
def create_setup(id: int, domain_name: str, node_id: str) -> SetupConfig:
return SetupConfig(id=id, domain_name=domain_name, node_id=node_id)
| ADD description / contact / daa fields | ADD description / contact / daa fields
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
+ from sqlalchemy import Boolean
# relative
from . import Base
class SetupConfig(Base):
__tablename__ = "setup"
id = Column(Integer(), primary_key=True, autoincrement=True)
domain_name = Column(String(255), default="")
+ description = Column(String(255), default="")
+ contact = Column(String(255), default="")
+ daa = Column(Boolean(), default=False)
node_id = Column(String(32), default="")
def __str__(self) -> str:
return f"<Domain Name: {self.domain_name}>"
def create_setup(id: int, domain_name: str, node_id: str) -> SetupConfig:
return SetupConfig(id=id, domain_name=domain_name, node_id=node_id)
| ADD description / contact / daa fields | ## Code Before:
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
# relative
from . import Base
class SetupConfig(Base):
__tablename__ = "setup"
id = Column(Integer(), primary_key=True, autoincrement=True)
domain_name = Column(String(255), default="")
node_id = Column(String(32), default="")
def __str__(self) -> str:
return f"<Domain Name: {self.domain_name}>"
def create_setup(id: int, domain_name: str, node_id: str) -> SetupConfig:
return SetupConfig(id=id, domain_name=domain_name, node_id=node_id)
## Instruction:
ADD description / contact / daa fields
## Code After:
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import Boolean
# relative
from . import Base
class SetupConfig(Base):
__tablename__ = "setup"
id = Column(Integer(), primary_key=True, autoincrement=True)
domain_name = Column(String(255), default="")
description = Column(String(255), default="")
contact = Column(String(255), default="")
daa = Column(Boolean(), default=False)
node_id = Column(String(32), default="")
def __str__(self) -> str:
return f"<Domain Name: {self.domain_name}>"
def create_setup(id: int, domain_name: str, node_id: str) -> SetupConfig:
return SetupConfig(id=id, domain_name=domain_name, node_id=node_id)
|
b5e368437a600d78e22a53abe53c0103b20daa24 | _python/main/migrations/0003_auto_20191029_2015.py | _python/main/migrations/0003_auto_20191029_2015.py |
from django.db import migrations, models
import main.models
class Migration(migrations.Migration):
dependencies = [
('main', '0002_auto_20191007_1639'),
]
operations = [
migrations.AlterField(
model_name='contentnode',
name='headnote',
field=main.models.SanitizingTextField(blank=True, null=True),
),
migrations.AlterField(
model_name='default',
name='url',
field=models.URLField(max_length=1024),
),
migrations.AlterField(
model_name='textblock',
name='content',
field=main.models.SanitizingCharField(max_length=5242880),
),
]
|
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0002_auto_20191007_1639'),
]
operations = [
migrations.AlterField(
model_name='default',
name='url',
field=models.URLField(max_length=1024),
),
]
| Repair migration, which was a no-op in SQL and was 'faked' anyway. | Repair migration, which was a no-op in SQL and was 'faked' anyway.
| Python | agpl-3.0 | harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o |
from django.db import migrations, models
- import main.models
class Migration(migrations.Migration):
dependencies = [
('main', '0002_auto_20191007_1639'),
]
operations = [
migrations.AlterField(
- model_name='contentnode',
- name='headnote',
- field=main.models.SanitizingTextField(blank=True, null=True),
- ),
- migrations.AlterField(
model_name='default',
name='url',
field=models.URLField(max_length=1024),
),
- migrations.AlterField(
- model_name='textblock',
- name='content',
- field=main.models.SanitizingCharField(max_length=5242880),
- ),
]
| Repair migration, which was a no-op in SQL and was 'faked' anyway. | ## Code Before:
from django.db import migrations, models
import main.models
class Migration(migrations.Migration):
dependencies = [
('main', '0002_auto_20191007_1639'),
]
operations = [
migrations.AlterField(
model_name='contentnode',
name='headnote',
field=main.models.SanitizingTextField(blank=True, null=True),
),
migrations.AlterField(
model_name='default',
name='url',
field=models.URLField(max_length=1024),
),
migrations.AlterField(
model_name='textblock',
name='content',
field=main.models.SanitizingCharField(max_length=5242880),
),
]
## Instruction:
Repair migration, which was a no-op in SQL and was 'faked' anyway.
## Code After:
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0002_auto_20191007_1639'),
]
operations = [
migrations.AlterField(
model_name='default',
name='url',
field=models.URLField(max_length=1024),
),
]
|
1dc2856368e5e6852b526d86a0c78c5fe10b1550 | myhronet/models.py | myhronet/models.py |
import string
from django.db import models
class Blacklist(models.Model):
domain = models.CharField(max_length=255, unique=True, null=True)
def __unicode__(self):
return self.domain
class URL(models.Model):
hashcode = models.CharField(max_length=10, unique=True,
db_index=True, null=True)
longurl = models.CharField(max_length=1024, unique=True,
db_index=True, null=True)
views = models.IntegerField(default=0)
ip = models.GenericIPAddressField(null=True)
data = models.DateTimeField(auto_now_add=True, null=True)
def save(self, *args, **kwargs):
if URL.objects.count():
last = URL.objects.latest('id').pk + 1
alphabet = string.digits + string.ascii_lowercase
base36 = ''
while last != 0:
last, i = divmod(last, len(alphabet))
base36 = alphabet[i] + base36
self.hashcode = base36
else:
self.hashcode = '1'
return super(URL, self).save(*args, **kwargs)
def short_url(self, request):
return ''.join([
request.scheme,
'://', request.get_host(),
'/', self.hashcode,
])
def __unicode__(self):
return ' - '.join([self.hashcode, self.longurl])
|
import string
from django.db import models
class Blacklist(models.Model):
domain = models.CharField(max_length=255, unique=True, null=True)
def __unicode__(self):
return self.domain
class URL(models.Model):
hashcode = models.CharField(max_length=10, unique=True,
db_index=True, null=True)
longurl = models.CharField(max_length=1024, unique=True,
db_index=True, null=True)
views = models.IntegerField(default=0)
ip = models.GenericIPAddressField(null=True)
data = models.DateTimeField(auto_now_add=True, null=True)
def save(self, *args, **kwargs):
if not self.pk:
if URL.objects.count():
last = URL.objects.latest('id').pk + 1
alphabet = string.digits + string.ascii_lowercase
base36 = ''
while last != 0:
last, i = divmod(last, len(alphabet))
base36 = alphabet[i] + base36
self.hashcode = base36
else:
self.hashcode = '1'
return super(URL, self).save(*args, **kwargs)
def short_url(self, request):
return ''.join([
request.scheme,
'://', request.get_host(),
'/', self.hashcode,
])
def __unicode__(self):
return ' - '.join([self.hashcode, self.longurl])
| Fix hashcode generation for existing URLs | Fix hashcode generation for existing URLs
| Python | mit | myhro/myhronet,myhro/myhronet |
import string
from django.db import models
class Blacklist(models.Model):
domain = models.CharField(max_length=255, unique=True, null=True)
def __unicode__(self):
return self.domain
class URL(models.Model):
hashcode = models.CharField(max_length=10, unique=True,
db_index=True, null=True)
longurl = models.CharField(max_length=1024, unique=True,
db_index=True, null=True)
views = models.IntegerField(default=0)
ip = models.GenericIPAddressField(null=True)
data = models.DateTimeField(auto_now_add=True, null=True)
def save(self, *args, **kwargs):
+ if not self.pk:
- if URL.objects.count():
+ if URL.objects.count():
- last = URL.objects.latest('id').pk + 1
+ last = URL.objects.latest('id').pk + 1
- alphabet = string.digits + string.ascii_lowercase
+ alphabet = string.digits + string.ascii_lowercase
- base36 = ''
+ base36 = ''
- while last != 0:
+ while last != 0:
- last, i = divmod(last, len(alphabet))
+ last, i = divmod(last, len(alphabet))
- base36 = alphabet[i] + base36
+ base36 = alphabet[i] + base36
- self.hashcode = base36
+ self.hashcode = base36
- else:
+ else:
- self.hashcode = '1'
+ self.hashcode = '1'
return super(URL, self).save(*args, **kwargs)
def short_url(self, request):
return ''.join([
request.scheme,
'://', request.get_host(),
'/', self.hashcode,
])
def __unicode__(self):
return ' - '.join([self.hashcode, self.longurl])
| Fix hashcode generation for existing URLs | ## Code Before:
import string
from django.db import models
class Blacklist(models.Model):
domain = models.CharField(max_length=255, unique=True, null=True)
def __unicode__(self):
return self.domain
class URL(models.Model):
hashcode = models.CharField(max_length=10, unique=True,
db_index=True, null=True)
longurl = models.CharField(max_length=1024, unique=True,
db_index=True, null=True)
views = models.IntegerField(default=0)
ip = models.GenericIPAddressField(null=True)
data = models.DateTimeField(auto_now_add=True, null=True)
def save(self, *args, **kwargs):
if URL.objects.count():
last = URL.objects.latest('id').pk + 1
alphabet = string.digits + string.ascii_lowercase
base36 = ''
while last != 0:
last, i = divmod(last, len(alphabet))
base36 = alphabet[i] + base36
self.hashcode = base36
else:
self.hashcode = '1'
return super(URL, self).save(*args, **kwargs)
def short_url(self, request):
return ''.join([
request.scheme,
'://', request.get_host(),
'/', self.hashcode,
])
def __unicode__(self):
return ' - '.join([self.hashcode, self.longurl])
## Instruction:
Fix hashcode generation for existing URLs
## Code After:
import string
from django.db import models
class Blacklist(models.Model):
domain = models.CharField(max_length=255, unique=True, null=True)
def __unicode__(self):
return self.domain
class URL(models.Model):
hashcode = models.CharField(max_length=10, unique=True,
db_index=True, null=True)
longurl = models.CharField(max_length=1024, unique=True,
db_index=True, null=True)
views = models.IntegerField(default=0)
ip = models.GenericIPAddressField(null=True)
data = models.DateTimeField(auto_now_add=True, null=True)
def save(self, *args, **kwargs):
if not self.pk:
if URL.objects.count():
last = URL.objects.latest('id').pk + 1
alphabet = string.digits + string.ascii_lowercase
base36 = ''
while last != 0:
last, i = divmod(last, len(alphabet))
base36 = alphabet[i] + base36
self.hashcode = base36
else:
self.hashcode = '1'
return super(URL, self).save(*args, **kwargs)
def short_url(self, request):
return ''.join([
request.scheme,
'://', request.get_host(),
'/', self.hashcode,
])
def __unicode__(self):
return ' - '.join([self.hashcode, self.longurl])
|
1cad9ab61148173b0f61971805b3e6203da3050d | faker/providers/en_CA/ssn.py | faker/providers/en_CA/ssn.py | from __future__ import unicode_literals
from ..ssn import Provider as SsnProvider
class Provider(SsnProvider):
ssn_formats = ("### ### ###",)
@classmethod
def ssn(cls):
return cls.bothify(cls.random_element(cls.ssn_formats)) | from __future__ import unicode_literals
from ..ssn import Provider as SsnProvider
import random
class Provider(SsnProvider):
#in order to create a valid SIN we need to provide a number that passes a simple modified Luhn Algorithmn checksum
#this function essentially reverses the checksum steps to create a random valid SIN (Social Insurance Number)
@classmethod
def ssn(cls):
#create an array of 8 elements initialized randomly
digits = random.sample(range(10), 8)
# All of the digits must sum to a multiple of 10.
# sum the first 8 and set 9th to the value to get to a multiple of 10
digits.append(10 - (sum(digits) % 10))
#digits is now the digital root of the number we want multiplied by the magic number 121 212 121
#reverse the multiplication which occurred on every other element
for i in range(1, len(digits), 2):
if digits[i] % 2 == 0:
digits[i] = (digits[i] / 2)
else:
digits[i] = (digits[i] + 9) / 2
#build the resulting SIN string
sin = ""
for i in range(0, len(digits), 1):
sin += str(digits[i])
#add a space to make it conform to normal standards in Canada
if i % 3 == 2:
sin += " "
#finally return our random but valid SIN
return sin
| Update Canada SSN/SIN provider to create a valid number | Update Canada SSN/SIN provider to create a valid number
The first revision generated a random number in the correct format.
This commit creates a SIN number that passes the checksum as described
here http://http://en.wikipedia.org/wiki/Social_Insurance_Number
| Python | mit | jaredculp/faker,trtd/faker,xfxf/faker-python,HAYASAKA-Ryosuke/faker,johnraz/faker,joke2k/faker,joke2k/faker,venmo/faker,ericchaves/faker,xfxf/faker-1,GLMeece/faker,danhuss/faker,beetleman/faker,thedrow/faker,meganlkm/faker,yiliaofan/faker,MaryanMorel/faker | from __future__ import unicode_literals
from ..ssn import Provider as SsnProvider
+ import random
class Provider(SsnProvider):
- ssn_formats = ("### ### ###",)
+ #in order to create a valid SIN we need to provide a number that passes a simple modified Luhn Algorithmn checksum
+ #this function essentially reverses the checksum steps to create a random valid SIN (Social Insurance Number)
@classmethod
def ssn(cls):
- return cls.bothify(cls.random_element(cls.ssn_formats))
+
+ #create an array of 8 elements initialized randomly
+ digits = random.sample(range(10), 8)
+
+ # All of the digits must sum to a multiple of 10.
+ # sum the first 8 and set 9th to the value to get to a multiple of 10
+ digits.append(10 - (sum(digits) % 10))
+
+ #digits is now the digital root of the number we want multiplied by the magic number 121 212 121
+ #reverse the multiplication which occurred on every other element
+ for i in range(1, len(digits), 2):
+ if digits[i] % 2 == 0:
+ digits[i] = (digits[i] / 2)
+ else:
+ digits[i] = (digits[i] + 9) / 2
+
+ #build the resulting SIN string
+ sin = ""
+ for i in range(0, len(digits), 1):
+ sin += str(digits[i])
+ #add a space to make it conform to normal standards in Canada
+ if i % 3 == 2:
+ sin += " "
+
+ #finally return our random but valid SIN
+ return sin
+
+ | Update Canada SSN/SIN provider to create a valid number | ## Code Before:
from __future__ import unicode_literals
from ..ssn import Provider as SsnProvider
class Provider(SsnProvider):
ssn_formats = ("### ### ###",)
@classmethod
def ssn(cls):
return cls.bothify(cls.random_element(cls.ssn_formats))
## Instruction:
Update Canada SSN/SIN provider to create a valid number
## Code After:
from __future__ import unicode_literals
from ..ssn import Provider as SsnProvider
import random
class Provider(SsnProvider):
#in order to create a valid SIN we need to provide a number that passes a simple modified Luhn Algorithmn checksum
#this function essentially reverses the checksum steps to create a random valid SIN (Social Insurance Number)
@classmethod
def ssn(cls):
#create an array of 8 elements initialized randomly
digits = random.sample(range(10), 8)
# All of the digits must sum to a multiple of 10.
# sum the first 8 and set 9th to the value to get to a multiple of 10
digits.append(10 - (sum(digits) % 10))
#digits is now the digital root of the number we want multiplied by the magic number 121 212 121
#reverse the multiplication which occurred on every other element
for i in range(1, len(digits), 2):
if digits[i] % 2 == 0:
digits[i] = (digits[i] / 2)
else:
digits[i] = (digits[i] + 9) / 2
#build the resulting SIN string
sin = ""
for i in range(0, len(digits), 1):
sin += str(digits[i])
#add a space to make it conform to normal standards in Canada
if i % 3 == 2:
sin += " "
#finally return our random but valid SIN
return sin
|
dd1ed907532526a4a70694c46918136ca6d93277 | nqueens/nqueens.py | nqueens/nqueens.py | from nqueens.chessboard import Chessboard
from nqueens.printer import Printer
from nqueens.solver import Solver
board = Chessboard.create(8)
solver = Solver.create(board)
solution = solver.solve()
if solution is not None:
printer = Printer.create(solution)
printer.printBoard()
| import os
import sys
import getopt
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from nqueens.chessboard import Chessboard
from nqueens.printer import Printer
from nqueens.solver import Solver
def main():
try:
n = parse_command_line()
except ValueError as e:
print("Error: " + str(e))
print("Usage: nqueens.py <n>")
sys.exit(1)
solution = solve_for(n)
if solution is None:
print("No solution found")
else:
print_solution(solution)
def parse_command_line():
try:
opts, args = getopt.getopt(sys.argv[1:], "", [])
except getopt.GetoptError:
raise ValueError("Could not parse command line")
if len(args) == 0:
raise ValueError("No arguments supplied")
if len(args) > 1:
raise ValueError("Too many arguments supplied")
n = args[0]
if not n.isdigit() or int(n) < 1:
raise ValueError("n must be a positive number")
return int(n)
def solve_for(n):
board = Chessboard.create(n)
solver = Solver.create(board)
return solver.solve()
def print_solution(solution):
printer = Printer.create(solution)
printer.printBoard()
if __name__ == '__main__':
sys.exit(main())
| Add ability to run problems from command line | Add ability to run problems from command line
| Python | mit | stevecshanks/nqueens | + import os
+ import sys
+ import getopt
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from nqueens.chessboard import Chessboard
from nqueens.printer import Printer
from nqueens.solver import Solver
+ def main():
+ try:
+ n = parse_command_line()
+ except ValueError as e:
+ print("Error: " + str(e))
+ print("Usage: nqueens.py <n>")
+ sys.exit(1)
+ solution = solve_for(n)
+ if solution is None:
+ print("No solution found")
+ else:
+ print_solution(solution)
+
+
+ def parse_command_line():
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], "", [])
+ except getopt.GetoptError:
+ raise ValueError("Could not parse command line")
+ if len(args) == 0:
+ raise ValueError("No arguments supplied")
+ if len(args) > 1:
+ raise ValueError("Too many arguments supplied")
+ n = args[0]
+ if not n.isdigit() or int(n) < 1:
+ raise ValueError("n must be a positive number")
+ return int(n)
+
+
+ def solve_for(n):
- board = Chessboard.create(8)
+ board = Chessboard.create(n)
- solver = Solver.create(board)
+ solver = Solver.create(board)
- solution = solver.solve()
- if solution is not None:
+ return solver.solve()
+
+
+ def print_solution(solution):
printer = Printer.create(solution)
printer.printBoard()
+
+ if __name__ == '__main__':
+ sys.exit(main())
+ | Add ability to run problems from command line | ## Code Before:
from nqueens.chessboard import Chessboard
from nqueens.printer import Printer
from nqueens.solver import Solver
board = Chessboard.create(8)
solver = Solver.create(board)
solution = solver.solve()
if solution is not None:
printer = Printer.create(solution)
printer.printBoard()
## Instruction:
Add ability to run problems from command line
## Code After:
import os
import sys
import getopt
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from nqueens.chessboard import Chessboard
from nqueens.printer import Printer
from nqueens.solver import Solver
def main():
try:
n = parse_command_line()
except ValueError as e:
print("Error: " + str(e))
print("Usage: nqueens.py <n>")
sys.exit(1)
solution = solve_for(n)
if solution is None:
print("No solution found")
else:
print_solution(solution)
def parse_command_line():
try:
opts, args = getopt.getopt(sys.argv[1:], "", [])
except getopt.GetoptError:
raise ValueError("Could not parse command line")
if len(args) == 0:
raise ValueError("No arguments supplied")
if len(args) > 1:
raise ValueError("Too many arguments supplied")
n = args[0]
if not n.isdigit() or int(n) < 1:
raise ValueError("n must be a positive number")
return int(n)
def solve_for(n):
board = Chessboard.create(n)
solver = Solver.create(board)
return solver.solve()
def print_solution(solution):
printer = Printer.create(solution)
printer.printBoard()
if __name__ == '__main__':
sys.exit(main())
|
c9cc5585e030951a09687c6a61a489ec51f83446 | cr2/plotter/__init__.py | cr2/plotter/__init__.py | """Init Module for the Plotter Code"""
import pandas as pd
from LinePlot import LinePlot
| """Init Module for the Plotter Code"""
import pandas as pd
from LinePlot import LinePlot
import AttrConf
def register_forwarding_arg(arg_name):
"""Allows the user to register args to
be forwarded to matplotlib
"""
if arg_name not in AttrConf.ARGS_TO_FORWARD:
AttrConf.ARGS_TO_FORWARD.append(arg_name)
def unregister_forwarding_arg(arg_name):
"""Unregisters arg_name from being passed to
plotter matplotlib calls
"""
try:
AttrConf.ARGS_TO_FORWARD.remove(arg_name)
except ValueError:
pass
| Enable user specified arg forwarding to matplotlib | plotter: Enable user specified arg forwarding to matplotlib
This change allows the user to register args for forwarding to
matplotlib and also unregister the same.
Change-Id: If53dab43dd4a2f530b3d1faf35582206ac925740
Signed-off-by: Kapileshwar Singh <[email protected]>
| Python | apache-2.0 | JaviMerino/trappy,joelagnel/trappy,bjackman/trappy,derkling/trappy,ARM-software/trappy,sinkap/trappy,JaviMerino/trappy,joelagnel/trappy,ARM-software/trappy,derkling/trappy,bjackman/trappy,sinkap/trappy,ARM-software/trappy,ARM-software/trappy,bjackman/trappy,sinkap/trappy,joelagnel/trappy,sinkap/trappy,JaviMerino/trappy,bjackman/trappy,derkling/trappy,joelagnel/trappy | """Init Module for the Plotter Code"""
import pandas as pd
from LinePlot import LinePlot
+ import AttrConf
+
+ def register_forwarding_arg(arg_name):
+ """Allows the user to register args to
+ be forwarded to matplotlib
+ """
+ if arg_name not in AttrConf.ARGS_TO_FORWARD:
+ AttrConf.ARGS_TO_FORWARD.append(arg_name)
+
+ def unregister_forwarding_arg(arg_name):
+ """Unregisters arg_name from being passed to
+ plotter matplotlib calls
+ """
+ try:
+ AttrConf.ARGS_TO_FORWARD.remove(arg_name)
+ except ValueError:
+ pass
+ | Enable user specified arg forwarding to matplotlib | ## Code Before:
"""Init Module for the Plotter Code"""
import pandas as pd
from LinePlot import LinePlot
## Instruction:
Enable user specified arg forwarding to matplotlib
## Code After:
"""Init Module for the Plotter Code"""
import pandas as pd
from LinePlot import LinePlot
import AttrConf
def register_forwarding_arg(arg_name):
"""Allows the user to register args to
be forwarded to matplotlib
"""
if arg_name not in AttrConf.ARGS_TO_FORWARD:
AttrConf.ARGS_TO_FORWARD.append(arg_name)
def unregister_forwarding_arg(arg_name):
"""Unregisters arg_name from being passed to
plotter matplotlib calls
"""
try:
AttrConf.ARGS_TO_FORWARD.remove(arg_name)
except ValueError:
pass
|
Subsets and Splits