commit
stringlengths 40
40
| old_file
stringlengths 5
117
| new_file
stringlengths 5
117
| old_contents
stringlengths 0
1.93k
| new_contents
stringlengths 19
3.3k
| subject
stringlengths 17
320
| message
stringlengths 18
3.28k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 7
42.4k
| completion
stringlengths 152
6.66k
| prompt
stringlengths 21
3.65k
|
---|---|---|---|---|---|---|---|---|---|---|---|
f4fa2d526f6f9c8b972c20ac073ed8f0682871ea | indra/tools/disambiguate.py | indra/tools/disambiguate.py | import logging
from collections import defaultdict
from indra.literature.elsevier_client import logger as elsevier_logger
from indra.literature import pubmed_client, pmc_client, elsevier_client
logger = logging.getLogger('disambiguate')
# the elsevier_client will log messages that it is safe to ignore
elsevier_logger.setLevel(logging.WARNING)
def get_fulltexts_from_entrez(hgnc_name):
pmids = pubmed_client.get_ids_for_gene(hgnc_name)
articles = (pubmed_client.get_article_xml(pmid) for pmid in pmids)
fulltexts = [_universal_extract_text(article) for article in articles]
return fulltexts
def _universal_extract_text(xml):
# first try to parse the xml as if it came from elsevier. if we do not
# have valid elsevier xml this will throw an exception.
# the text extraction function in the pmc client may not throw an
# exception when parsing elsevier xml, silently processing the xml
# incorrectly
try:
fulltext = elsevier_client.extract_text(xml)
except Exception:
try:
fulltext = pmc_client.extract_text(xml)
except Exception:
# fall back by returning input string unmodified
fulltext = xml
return fulltext
def _get_text_from_pmids(pmids):
pmc_content = set(pubmed_client.filter_pmids(pmids))
pmc_ids = (pmc_client.id_lookup(pmid, idtype='pmid')['pmcid']
for pmid in pmc_content)
pmc_xmls = (pmc_client.get_xml(pmc_id) for pmc_id in pmc_ids)
pmc_texts = set(_universal_extract_text(xml) for xml in pmc_xmls)
other_content = set(pmids) - pmc_content
ids = (pmc_client.id_lookup(pmid, idtype='pmid') for pmid in pmids)
elsevier_content = (elsevier_client.download_article_from_id(pmid)
for pmid in pmids)
| Add unfinished scripts that assist in deft disambiguation | Add unfinished scripts that assist in deft disambiguation
git history was completley farbed through carelessness. the original deft
branch was deleted and a new branch was created
| Python | bsd-2-clause | bgyori/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/indra,pvtodorov/indra,johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,sorgerlab/belpy,pvtodorov/indra,bgyori/indra,sorgerlab/belpy,pvtodorov/indra,johnbachman/belpy,johnbachman/indra,johnbachman/belpy,johnbachman/belpy,bgyori/indra | <REPLACE_OLD> <REPLACE_NEW> import logging
from collections import defaultdict
from indra.literature.elsevier_client import logger as elsevier_logger
from indra.literature import pubmed_client, pmc_client, elsevier_client
logger = logging.getLogger('disambiguate')
# the elsevier_client will log messages that it is safe to ignore
elsevier_logger.setLevel(logging.WARNING)
def get_fulltexts_from_entrez(hgnc_name):
pmids = pubmed_client.get_ids_for_gene(hgnc_name)
articles = (pubmed_client.get_article_xml(pmid) for pmid in pmids)
fulltexts = [_universal_extract_text(article) for article in articles]
return fulltexts
def _universal_extract_text(xml):
# first try to parse the xml as if it came from elsevier. if we do not
# have valid elsevier xml this will throw an exception.
# the text extraction function in the pmc client may not throw an
# exception when parsing elsevier xml, silently processing the xml
# incorrectly
try:
fulltext = elsevier_client.extract_text(xml)
except Exception:
try:
fulltext = pmc_client.extract_text(xml)
except Exception:
# fall back by returning input string unmodified
fulltext = xml
return fulltext
def _get_text_from_pmids(pmids):
pmc_content = set(pubmed_client.filter_pmids(pmids))
pmc_ids = (pmc_client.id_lookup(pmid, idtype='pmid')['pmcid']
for pmid in pmc_content)
pmc_xmls = (pmc_client.get_xml(pmc_id) for pmc_id in pmc_ids)
pmc_texts = set(_universal_extract_text(xml) for xml in pmc_xmls)
other_content = set(pmids) - pmc_content
ids = (pmc_client.id_lookup(pmid, idtype='pmid') for pmid in pmids)
elsevier_content = (elsevier_client.download_article_from_id(pmid)
for pmid in pmids)
<REPLACE_END> <|endoftext|> import logging
from collections import defaultdict
from indra.literature.elsevier_client import logger as elsevier_logger
from indra.literature import pubmed_client, pmc_client, elsevier_client
logger = logging.getLogger('disambiguate')
# the elsevier_client will log messages that it is safe to ignore
elsevier_logger.setLevel(logging.WARNING)
def get_fulltexts_from_entrez(hgnc_name):
pmids = pubmed_client.get_ids_for_gene(hgnc_name)
articles = (pubmed_client.get_article_xml(pmid) for pmid in pmids)
fulltexts = [_universal_extract_text(article) for article in articles]
return fulltexts
def _universal_extract_text(xml):
# first try to parse the xml as if it came from elsevier. if we do not
# have valid elsevier xml this will throw an exception.
# the text extraction function in the pmc client may not throw an
# exception when parsing elsevier xml, silently processing the xml
# incorrectly
try:
fulltext = elsevier_client.extract_text(xml)
except Exception:
try:
fulltext = pmc_client.extract_text(xml)
except Exception:
# fall back by returning input string unmodified
fulltext = xml
return fulltext
def _get_text_from_pmids(pmids):
pmc_content = set(pubmed_client.filter_pmids(pmids))
pmc_ids = (pmc_client.id_lookup(pmid, idtype='pmid')['pmcid']
for pmid in pmc_content)
pmc_xmls = (pmc_client.get_xml(pmc_id) for pmc_id in pmc_ids)
pmc_texts = set(_universal_extract_text(xml) for xml in pmc_xmls)
other_content = set(pmids) - pmc_content
ids = (pmc_client.id_lookup(pmid, idtype='pmid') for pmid in pmids)
elsevier_content = (elsevier_client.download_article_from_id(pmid)
for pmid in pmids)
| Add unfinished scripts that assist in deft disambiguation
git history was completley farbed through carelessness. the original deft
branch was deleted and a new branch was created
|
|
6ee4cd2ace969365a4898e3f89944e8ddbdca1c8 | wolme/wallet/models.py | wolme/wallet/models.py | from __future__ import unicode_literals
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext as _
@python_2_unicode_compatible
class Tag(models.Model):
slug = models.SlugField(unique=True)
description = models.TextField(null=True, blank=True)
def __str__(self):
return self.slug
@python_2_unicode_compatible
class Wallet(models.Model):
CURRENCIES = (
("EUR", "EUR"),
)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='wallets')
label = models.CharField(max_length=100)
description = models.TextField(null=True, blank=True)
currency = models.CharField(max_length=3, null=False, blank=False, choices=CURRENCIES)
def __str__(self):
return "{} ({})".format(self.label, self.currency)
@python_2_unicode_compatible
class Movement(models.Model):
wallet = models.ForeignKey(Wallet, related_name="movements")
date = models.DateTimeField()
amount = models.DecimalField(max_digits=11, decimal_places=2)
tags = models.ManyToManyField(Tag, related_name="movements")
def __str__(self):
return "{} - {:.2f} for {} on {}".format(
self.type, self.amount, self.wallet, self.date)
| from __future__ import unicode_literals
from django.conf import settings
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext as _
@python_2_unicode_compatible
class Tag(models.Model):
slug = models.SlugField(unique=True)
description = models.TextField(null=True, blank=True)
def __str__(self):
return self.slug
@python_2_unicode_compatible
class Wallet(models.Model):
CURRENCIES = (
("EUR", "EUR"),
)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='wallets')
label = models.CharField(max_length=100)
description = models.TextField(null=True, blank=True)
currency = models.CharField(max_length=3, null=False, blank=False, choices=CURRENCIES)
def __str__(self):
return "{} ({})".format(self.label, self.currency)
@python_2_unicode_compatible
class Movement(models.Model):
wallet = models.ForeignKey(Wallet, related_name="movements")
date = models.DateTimeField(default=timezone.now())
amount = models.DecimalField(max_digits=11, decimal_places=2)
tags = models.ManyToManyField(Tag, related_name="movements")
def __str__(self):
return "{} - {:.2f} for {} on {}".format(
self.type, self.amount, self.wallet, self.date)
| Add default to movement date | Add default to movement date
| Python | bsd-2-clause | synasius/wolme | <INSERT> django.utils import timezone
from <INSERT_END> <REPLACE_OLD> models.DateTimeField()
<REPLACE_NEW> models.DateTimeField(default=timezone.now())
<REPLACE_END> <|endoftext|> from __future__ import unicode_literals
from django.conf import settings
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext as _
@python_2_unicode_compatible
class Tag(models.Model):
slug = models.SlugField(unique=True)
description = models.TextField(null=True, blank=True)
def __str__(self):
return self.slug
@python_2_unicode_compatible
class Wallet(models.Model):
CURRENCIES = (
("EUR", "EUR"),
)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='wallets')
label = models.CharField(max_length=100)
description = models.TextField(null=True, blank=True)
currency = models.CharField(max_length=3, null=False, blank=False, choices=CURRENCIES)
def __str__(self):
return "{} ({})".format(self.label, self.currency)
@python_2_unicode_compatible
class Movement(models.Model):
wallet = models.ForeignKey(Wallet, related_name="movements")
date = models.DateTimeField(default=timezone.now())
amount = models.DecimalField(max_digits=11, decimal_places=2)
tags = models.ManyToManyField(Tag, related_name="movements")
def __str__(self):
return "{} - {:.2f} for {} on {}".format(
self.type, self.amount, self.wallet, self.date)
| Add default to movement date
from __future__ import unicode_literals
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext as _
@python_2_unicode_compatible
class Tag(models.Model):
slug = models.SlugField(unique=True)
description = models.TextField(null=True, blank=True)
def __str__(self):
return self.slug
@python_2_unicode_compatible
class Wallet(models.Model):
CURRENCIES = (
("EUR", "EUR"),
)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='wallets')
label = models.CharField(max_length=100)
description = models.TextField(null=True, blank=True)
currency = models.CharField(max_length=3, null=False, blank=False, choices=CURRENCIES)
def __str__(self):
return "{} ({})".format(self.label, self.currency)
@python_2_unicode_compatible
class Movement(models.Model):
wallet = models.ForeignKey(Wallet, related_name="movements")
date = models.DateTimeField()
amount = models.DecimalField(max_digits=11, decimal_places=2)
tags = models.ManyToManyField(Tag, related_name="movements")
def __str__(self):
return "{} - {:.2f} for {} on {}".format(
self.type, self.amount, self.wallet, self.date)
|
1245e0aeaf5cd37e6f6c5c0feddbedededd3a458 | tests/test_crypto.py | tests/test_crypto.py | from __future__ import absolute_import, division, print_function, unicode_literals
import os
import base64
import credsmash.aes_ctr
import credsmash.aes_gcm
class DummyKeyService(object):
def generate_key_data(self, number_of_bytes):
key = os.urandom(int(number_of_bytes))
return key, base64.b64encode(key)
def decrypt(self, encoded_key):
return base64.b64decode(encoded_key)
def test_aes_ctr_legacy():
"""
Basic test to ensure `cryptography` is installed/working
"""
key_service = DummyKeyService()
plaintext = b'abcdefghi'
material = credsmash.aes_ctr.seal_aes_ctr_legacy(
key_service,
plaintext
)
recovered_plaintext = credsmash.aes_ctr.open_aes_ctr_legacy(
key_service, material
)
assert plaintext == recovered_plaintext
def test_aes_ctr():
key_service = DummyKeyService()
plaintext = b'abcdefghi'
material = credsmash.aes_ctr.seal_aes_ctr(
key_service,
plaintext
)
recovered_plaintext = credsmash.aes_ctr.open_aes_ctr(
key_service, material
)
assert plaintext == recovered_plaintext
def test_aes_gcm():
key_service = DummyKeyService()
plaintext = b'abcdefghi'
material = credsmash.aes_gcm.seal_aes_gcm(
key_service,
plaintext
)
recovered_plaintext = credsmash.aes_gcm.open_aes_gcm(
key_service, material
)
assert plaintext == recovered_plaintext
| Add test to show crypto working | Add test to show crypto working
| Python | apache-2.0 | 3stack-software/credsmash | <REPLACE_OLD> <REPLACE_NEW> from __future__ import absolute_import, division, print_function, unicode_literals
import os
import base64
import credsmash.aes_ctr
import credsmash.aes_gcm
class DummyKeyService(object):
def generate_key_data(self, number_of_bytes):
key = os.urandom(int(number_of_bytes))
return key, base64.b64encode(key)
def decrypt(self, encoded_key):
return base64.b64decode(encoded_key)
def test_aes_ctr_legacy():
"""
Basic test to ensure `cryptography` is installed/working
"""
key_service = DummyKeyService()
plaintext = b'abcdefghi'
material = credsmash.aes_ctr.seal_aes_ctr_legacy(
key_service,
plaintext
)
recovered_plaintext = credsmash.aes_ctr.open_aes_ctr_legacy(
key_service, material
)
assert plaintext == recovered_plaintext
def test_aes_ctr():
key_service = DummyKeyService()
plaintext = b'abcdefghi'
material = credsmash.aes_ctr.seal_aes_ctr(
key_service,
plaintext
)
recovered_plaintext = credsmash.aes_ctr.open_aes_ctr(
key_service, material
)
assert plaintext == recovered_plaintext
def test_aes_gcm():
key_service = DummyKeyService()
plaintext = b'abcdefghi'
material = credsmash.aes_gcm.seal_aes_gcm(
key_service,
plaintext
)
recovered_plaintext = credsmash.aes_gcm.open_aes_gcm(
key_service, material
)
assert plaintext == recovered_plaintext
<REPLACE_END> <|endoftext|> from __future__ import absolute_import, division, print_function, unicode_literals
import os
import base64
import credsmash.aes_ctr
import credsmash.aes_gcm
class DummyKeyService(object):
def generate_key_data(self, number_of_bytes):
key = os.urandom(int(number_of_bytes))
return key, base64.b64encode(key)
def decrypt(self, encoded_key):
return base64.b64decode(encoded_key)
def test_aes_ctr_legacy():
"""
Basic test to ensure `cryptography` is installed/working
"""
key_service = DummyKeyService()
plaintext = b'abcdefghi'
material = credsmash.aes_ctr.seal_aes_ctr_legacy(
key_service,
plaintext
)
recovered_plaintext = credsmash.aes_ctr.open_aes_ctr_legacy(
key_service, material
)
assert plaintext == recovered_plaintext
def test_aes_ctr():
key_service = DummyKeyService()
plaintext = b'abcdefghi'
material = credsmash.aes_ctr.seal_aes_ctr(
key_service,
plaintext
)
recovered_plaintext = credsmash.aes_ctr.open_aes_ctr(
key_service, material
)
assert plaintext == recovered_plaintext
def test_aes_gcm():
key_service = DummyKeyService()
plaintext = b'abcdefghi'
material = credsmash.aes_gcm.seal_aes_gcm(
key_service,
plaintext
)
recovered_plaintext = credsmash.aes_gcm.open_aes_gcm(
key_service, material
)
assert plaintext == recovered_plaintext
| Add test to show crypto working
|
|
a893223d4964f946d9413a17e62871e2660843a8 | flexget/plugins/input_listdir.py | flexget/plugins/input_listdir.py | import logging
from flexget.plugin import *
log = logging.getLogger('listdir')
class InputListdir:
"""
Uses local path content as an input.
Example:
listdir: /storage/movies/
"""
def validator(self):
from flexget import validator
root = validator.factory()
root.accept('path')
bundle = root.accept('list')
bundle.accept('path')
return root
def get_config(self, feed):
config = feed.config.get('listdir', None)
#if only a single path is passed turn it into a 1 element list
if isinstance(config, basestring):
config = [config]
return config
def on_feed_input(self, feed):
from flexget.feed import Entry
import os
config = self.get_config(feed)
for path in config:
for name in os.listdir(unicode(path)):
e = Entry()
e['title'] = name
e['url'] = 'file://%s' % (os.path.join(path, name))
e['location'] = os.path.join(path, name)
feed.entries.append(e)
register_plugin(InputListdir, 'listdir')
| import logging
from flexget.plugin import register_plugin
log = logging.getLogger('listdir')
class InputListdir:
"""
Uses local path content as an input.
Example:
listdir: /storage/movies/
"""
def validator(self):
from flexget import validator
root = validator.factory()
root.accept('path')
bundle = root.accept('list')
bundle.accept('path')
return root
def get_config(self, feed):
config = feed.config.get('listdir', None)
# If only a single path is passed turn it into a 1 element list
if isinstance(config, basestring):
config = [config]
return config
def on_feed_input(self, feed):
from flexget.feed import Entry
import os
config = self.get_config(feed)
for path in config:
for name in os.listdir(unicode(path)):
e = Entry()
e['title'] = name
filepath = os.path.join(path, name)
# Windows paths need an extra / prepended to them
if not filepath.startswith('/'):
filepath = '/' + filepath
e['url'] = 'file://%s' % (filepath)
e['location'] = os.path.join(path, name)
feed.entries.append(e)
register_plugin(InputListdir, 'listdir')
| Fix url of entries made by listdir on Windows. | Fix url of entries made by listdir on Windows.
git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@1586 3942dd89-8c5d-46d7-aeed-044bccf3e60c
| Python | mit | LynxyssCZ/Flexget,thalamus/Flexget,tvcsantos/Flexget,ibrahimkarahan/Flexget,patsissons/Flexget,oxc/Flexget,dsemi/Flexget,qvazzler/Flexget,poulpito/Flexget,crawln45/Flexget,Flexget/Flexget,ZefQ/Flexget,malkavi/Flexget,malkavi/Flexget,oxc/Flexget,JorisDeRieck/Flexget,crawln45/Flexget,sean797/Flexget,jawilson/Flexget,dsemi/Flexget,spencerjanssen/Flexget,ibrahimkarahan/Flexget,qvazzler/Flexget,qvazzler/Flexget,asm0dey/Flexget,Pretagonist/Flexget,ianstalk/Flexget,drwyrm/Flexget,ZefQ/Flexget,jawilson/Flexget,antivirtel/Flexget,spencerjanssen/Flexget,ratoaq2/Flexget,camon/Flexget,malkavi/Flexget,spencerjanssen/Flexget,lildadou/Flexget,tsnoam/Flexget,xfouloux/Flexget,voriux/Flexget,ratoaq2/Flexget,grrr2/Flexget,LynxyssCZ/Flexget,LynxyssCZ/Flexget,ianstalk/Flexget,X-dark/Flexget,tobinjt/Flexget,poulpito/Flexget,tarzasai/Flexget,jawilson/Flexget,OmgOhnoes/Flexget,dsemi/Flexget,qk4l/Flexget,OmgOhnoes/Flexget,patsissons/Flexget,tobinjt/Flexget,jacobmetrick/Flexget,ZefQ/Flexget,jacobmetrick/Flexget,Pretagonist/Flexget,JorisDeRieck/Flexget,crawln45/Flexget,Danfocus/Flexget,JorisDeRieck/Flexget,OmgOhnoes/Flexget,Flexget/Flexget,Pretagonist/Flexget,X-dark/Flexget,Danfocus/Flexget,LynxyssCZ/Flexget,thalamus/Flexget,tobinjt/Flexget,ianstalk/Flexget,vfrc2/Flexget,jawilson/Flexget,patsissons/Flexget,tvcsantos/Flexget,tsnoam/Flexget,tarzasai/Flexget,lildadou/Flexget,thalamus/Flexget,Flexget/Flexget,gazpachoking/Flexget,asm0dey/Flexget,antivirtel/Flexget,qk4l/Flexget,sean797/Flexget,Danfocus/Flexget,offbyone/Flexget,drwyrm/Flexget,asm0dey/Flexget,X-dark/Flexget,gazpachoking/Flexget,vfrc2/Flexget,ibrahimkarahan/Flexget,Flexget/Flexget,offbyone/Flexget,xfouloux/Flexget,lildadou/Flexget,grrr2/Flexget,antivirtel/Flexget,oxc/Flexget,tsnoam/Flexget,v17al/Flexget,offbyone/Flexget,drwyrm/Flexget,Danfocus/Flexget,v17al/Flexget,poulpito/Flexget,grrr2/Flexget,cvium/Flexget,cvium/Flexget,jacobmetrick/Flexget,sean797/Flexget,cvium/Flexget,JorisDeRieck/Flexget,tobinjt/Flexget,crawln45/Flexget,vfrc2/Flexget,tarzasai/Flexget,qk4l/Flexget,ratoaq2/Flexget,v17al/Flexget,camon/Flexget,voriux/Flexget,malkavi/Flexget,xfouloux/Flexget | <REPLACE_OLD> *
log <REPLACE_NEW> register_plugin
log <REPLACE_END> <REPLACE_OLD> input.
Example:
<REPLACE_NEW> input.
Example:
<REPLACE_END> <REPLACE_OLD> """
<REPLACE_NEW> """
<REPLACE_END> <REPLACE_OLD> root
<REPLACE_NEW> root
<REPLACE_END> <REPLACE_OLD> #if <REPLACE_NEW> # If <REPLACE_END> <REPLACE_OLD> config:
<REPLACE_NEW> config:
<REPLACE_END> <INSERT> filepath = os.path.join(path, name)
# Windows paths need an extra / prepended to them
if not filepath.startswith('/'):
filepath = '/' + filepath
<INSERT_END> <REPLACE_OLD> (os.path.join(path, name))
<REPLACE_NEW> (filepath)
<REPLACE_END> <|endoftext|> import logging
from flexget.plugin import register_plugin
log = logging.getLogger('listdir')
class InputListdir:
"""
Uses local path content as an input.
Example:
listdir: /storage/movies/
"""
def validator(self):
from flexget import validator
root = validator.factory()
root.accept('path')
bundle = root.accept('list')
bundle.accept('path')
return root
def get_config(self, feed):
config = feed.config.get('listdir', None)
# If only a single path is passed turn it into a 1 element list
if isinstance(config, basestring):
config = [config]
return config
def on_feed_input(self, feed):
from flexget.feed import Entry
import os
config = self.get_config(feed)
for path in config:
for name in os.listdir(unicode(path)):
e = Entry()
e['title'] = name
filepath = os.path.join(path, name)
# Windows paths need an extra / prepended to them
if not filepath.startswith('/'):
filepath = '/' + filepath
e['url'] = 'file://%s' % (filepath)
e['location'] = os.path.join(path, name)
feed.entries.append(e)
register_plugin(InputListdir, 'listdir')
| Fix url of entries made by listdir on Windows.
git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@1586 3942dd89-8c5d-46d7-aeed-044bccf3e60c
import logging
from flexget.plugin import *
log = logging.getLogger('listdir')
class InputListdir:
"""
Uses local path content as an input.
Example:
listdir: /storage/movies/
"""
def validator(self):
from flexget import validator
root = validator.factory()
root.accept('path')
bundle = root.accept('list')
bundle.accept('path')
return root
def get_config(self, feed):
config = feed.config.get('listdir', None)
#if only a single path is passed turn it into a 1 element list
if isinstance(config, basestring):
config = [config]
return config
def on_feed_input(self, feed):
from flexget.feed import Entry
import os
config = self.get_config(feed)
for path in config:
for name in os.listdir(unicode(path)):
e = Entry()
e['title'] = name
e['url'] = 'file://%s' % (os.path.join(path, name))
e['location'] = os.path.join(path, name)
feed.entries.append(e)
register_plugin(InputListdir, 'listdir')
|
cb4421529e9564f110b84f590f14057eda8746c8 | setup.py | setup.py | from setuptools import setup
from setuptools.command.install import install as _install
class install(_install):
def run(self):
_install.run(self)
setup(
cmdclass = { 'install' : install },
name = 'hydra',
version = '0.1',
author = 'tatsy',
author_email = '[email protected]',
url = 'https://github.com/tatsy/hydra.git',
description = 'Python HDR image processing library.',
license = 'MIT',
classifiers = [
'Development Status :: 1 - Planning',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
],
packages = [
'hydra',
'hydra.core',
'hydra.gen',
'hydra.io',
'hydra.filters',
'hydra.tonemap'
]
)
| from setuptools import setup
from setuptools.command.install import install as _install
class install(_install):
def run(self):
_install.run(self)
setup(
cmdclass = { 'install' : install },
name = 'hydra',
version = '0.1',
author = 'tatsy',
author_email = '[email protected]',
url = 'https://github.com/tatsy/hydra.git',
description = 'Python HDR image processing library.',
license = 'MIT',
classifiers = [
'Development Status :: 1 - Planning',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
],
packages = [
'hydra',
'hydra.core',
'hydra.eo',
'hydra.filters',
'hydra.gen',
'hydra.io',
'hydra.tonemap'
]
)
| Add eo to installed packages. | Add eo to installed packages.
| Python | mit | tatsy/hydra | <INSERT> 'hydra.eo',
'hydra.filters',
<INSERT_END> <DELETE> 'hydra.filters',
<DELETE_END> <|endoftext|> from setuptools import setup
from setuptools.command.install import install as _install
class install(_install):
def run(self):
_install.run(self)
setup(
cmdclass = { 'install' : install },
name = 'hydra',
version = '0.1',
author = 'tatsy',
author_email = '[email protected]',
url = 'https://github.com/tatsy/hydra.git',
description = 'Python HDR image processing library.',
license = 'MIT',
classifiers = [
'Development Status :: 1 - Planning',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
],
packages = [
'hydra',
'hydra.core',
'hydra.eo',
'hydra.filters',
'hydra.gen',
'hydra.io',
'hydra.tonemap'
]
)
| Add eo to installed packages.
from setuptools import setup
from setuptools.command.install import install as _install
class install(_install):
def run(self):
_install.run(self)
setup(
cmdclass = { 'install' : install },
name = 'hydra',
version = '0.1',
author = 'tatsy',
author_email = '[email protected]',
url = 'https://github.com/tatsy/hydra.git',
description = 'Python HDR image processing library.',
license = 'MIT',
classifiers = [
'Development Status :: 1 - Planning',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
],
packages = [
'hydra',
'hydra.core',
'hydra.gen',
'hydra.io',
'hydra.filters',
'hydra.tonemap'
]
)
|
b6c98dd016aa440f96565ceaee2716cd530beae5 | pages/search_indexes.py | pages/search_indexes.py | """Django haystack `SearchIndex` module."""
from pages.models import Page, Content
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
import datetime
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True)
title = CharField(model_attr='title')
publication_date = DateTimeField(model_attr='publication_date')
def get_queryset(self):
"""Used when the entire index for model is updated."""
return Page.objects.published()
site.register(Page, PageIndex) | """Django haystack `SearchIndex` module."""
from pages.models import Page, Content
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
import datetime
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True)
title = CharField(model_attr='title')
url = CharField(model_attr='get_absolute_url')
publication_date = DateTimeField(model_attr='publication_date')
def get_queryset(self):
"""Used when the entire index for model is updated."""
return Page.objects.published()
site.register(Page, PageIndex) | Add a url attribute to the SearchIndex for pages. | Add a url attribute to the SearchIndex for pages.
This is useful when displaying a list of search results because we
can create a link to the result without having to hit the database
for every object in the result list.
| Python | bsd-3-clause | remik/django-page-cms,akaihola/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,remik/django-page-cms,pombredanne/django-page-cms-1,pombredanne/django-page-cms-1,pombredanne/django-page-cms-1,oliciv/django-page-cms,remik/django-page-cms,remik/django-page-cms,oliciv/django-page-cms,oliciv/django-page-cms,batiste/django-page-cms | <INSERT> url = CharField(model_attr='get_absolute_url')
<INSERT_END> <|endoftext|> """Django haystack `SearchIndex` module."""
from pages.models import Page, Content
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
import datetime
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True)
title = CharField(model_attr='title')
url = CharField(model_attr='get_absolute_url')
publication_date = DateTimeField(model_attr='publication_date')
def get_queryset(self):
"""Used when the entire index for model is updated."""
return Page.objects.published()
site.register(Page, PageIndex) | Add a url attribute to the SearchIndex for pages.
This is useful when displaying a list of search results because we
can create a link to the result without having to hit the database
for every object in the result list.
"""Django haystack `SearchIndex` module."""
from pages.models import Page, Content
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
import datetime
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True)
title = CharField(model_attr='title')
publication_date = DateTimeField(model_attr='publication_date')
def get_queryset(self):
"""Used when the entire index for model is updated."""
return Page.objects.published()
site.register(Page, PageIndex) |
5827c09e3a003f53baa5abe2d2d0fc5d695d4334 | arxiv_vanity/papers/management/commands/delete_all_expired_renders.py | arxiv_vanity/papers/management/commands/delete_all_expired_renders.py | from django.core.management.base import BaseCommand, CommandError
from ...models import Render
class Command(BaseCommand):
help = 'Deletes output of all expired renders'
def handle(self, *args, **options):
for render in Render.objects.expired().iterator():
try:
render.delete_output()
except FileNotFoundError:
print(f"β Render {render.id} already deleted")
else:
print(f"β
Render {render.id} deleted")
| from django.core.management.base import BaseCommand, CommandError
from ...models import Render
class Command(BaseCommand):
help = 'Deletes output of all expired renders'
def handle(self, *args, **options):
for render in Render.objects.expired().iterator():
try:
render.delete_output()
except FileNotFoundError:
print(f"β Render {render.id} already deleted", flush=True)
else:
print(f"β
Render {render.id} deleted", flush=True)
| Add flush to delete all renders print | Add flush to delete all renders print
| Python | apache-2.0 | arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity | <REPLACE_OLD> deleted")
<REPLACE_NEW> deleted", flush=True)
<REPLACE_END> <REPLACE_OLD> deleted")
<REPLACE_NEW> deleted", flush=True)
<REPLACE_END> <|endoftext|> from django.core.management.base import BaseCommand, CommandError
from ...models import Render
class Command(BaseCommand):
help = 'Deletes output of all expired renders'
def handle(self, *args, **options):
for render in Render.objects.expired().iterator():
try:
render.delete_output()
except FileNotFoundError:
print(f"β Render {render.id} already deleted", flush=True)
else:
print(f"β
Render {render.id} deleted", flush=True)
| Add flush to delete all renders print
from django.core.management.base import BaseCommand, CommandError
from ...models import Render
class Command(BaseCommand):
help = 'Deletes output of all expired renders'
def handle(self, *args, **options):
for render in Render.objects.expired().iterator():
try:
render.delete_output()
except FileNotFoundError:
print(f"β Render {render.id} already deleted")
else:
print(f"β
Render {render.id} deleted")
|
a6049578c4dd4602aa903af262347dddf05df178 | template/module/tests/test_something.py | template/module/tests/test_something.py | # -*- coding: utf-8 -*-
# Copyright <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp.tests.common import HttpCase, TransactionCase
class SomethingCase(TransactionCase):
def setUp(self, *args, **kwargs):
super(SomethingCase, self).setUp(*args, **kwargs)
# TODO Replace this for something useful or delete this method
self.do_something_before_all_tests()
def tearDown(self, *args, **kwargs):
# TODO Replace this for something useful or delete this method
self.do_something_after_all_tests()
return super(SomethingCase, self).tearDown(*args, **kwargs)
def test_something(self):
"""First line of docstring appears in test logs.
Other lines do not.
Any method starting with ``test_`` will be tested.
"""
pass
class UICase(HttpCase):
def test_ui_web(self):
"""Test backend tests."""
self.phantom_js("/web/tests?module=module_name", "", login="admin")
def test_ui_website(self):
"""Test frontend tour."""
self.phantom_js(
url_path="/",
code="odoo.__DEBUG__.services['web.Tour']"
".run('test_module_name', 'test')",
ready="odoo.__DEBUG__.services['web.Tour'].tours.test_module_name",
login="admin")
| # -*- coding: utf-8 -*-
# Copyright <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp.tests.common import HttpCase, TransactionCase
class SomethingCase(TransactionCase):
def setUp(self, *args, **kwargs):
super(SomethingCase, self).setUp(*args, **kwargs)
# TODO Replace this for something useful or delete this method
self.do_something_before_all_tests()
def tearDown(self, *args, **kwargs):
# TODO Replace this for something useful or delete this method
self.do_something_after_all_tests()
return super(SomethingCase, self).tearDown(*args, **kwargs)
def test_something(self):
"""First line of docstring appears in test logs.
Other lines do not.
Any method starting with ``test_`` will be tested.
"""
pass
class UICase(HttpCase):
def test_ui_web(self):
"""Test backend tests."""
self.phantom_js("/web/tests?debug=assets&module=module_name", "", login="admin")
def test_ui_website(self):
"""Test frontend tour."""
self.phantom_js(
url_path="/?debug=assets",
code="odoo.__DEBUG__.services['web.Tour']"
".run('test_module_name', 'test')",
ready="odoo.__DEBUG__.services['web.Tour'].tours.test_module_name",
login="admin")
| Add debug assets to HTTP cases | [IMP] Add debug assets to HTTP cases
| Python | agpl-3.0 | Yajo/maintainer-tools,acsone/maintainer-tools,acsone/maintainer-tools,OCA/maintainer-tools,Yajo/maintainer-tools,Yajo/maintainer-tools,acsone/maintainers-tools,OCA/maintainer-tools,acsone/maintainers-tools,OCA/maintainer-tools,acsone/maintainer-tools,Yajo/maintainer-tools,OCA/maintainer-tools,acsone/maintainer-tools,acsone/maintainers-tools,gurneyalex/maintainers-tools | <REPLACE_OLD> self.phantom_js("/web/tests?module=module_name", <REPLACE_NEW> self.phantom_js("/web/tests?debug=assets&module=module_name", <REPLACE_END> <REPLACE_OLD> url_path="/",
<REPLACE_NEW> url_path="/?debug=assets",
<REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# Copyright <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp.tests.common import HttpCase, TransactionCase
class SomethingCase(TransactionCase):
def setUp(self, *args, **kwargs):
super(SomethingCase, self).setUp(*args, **kwargs)
# TODO Replace this for something useful or delete this method
self.do_something_before_all_tests()
def tearDown(self, *args, **kwargs):
# TODO Replace this for something useful or delete this method
self.do_something_after_all_tests()
return super(SomethingCase, self).tearDown(*args, **kwargs)
def test_something(self):
"""First line of docstring appears in test logs.
Other lines do not.
Any method starting with ``test_`` will be tested.
"""
pass
class UICase(HttpCase):
def test_ui_web(self):
"""Test backend tests."""
self.phantom_js("/web/tests?debug=assets&module=module_name", "", login="admin")
def test_ui_website(self):
"""Test frontend tour."""
self.phantom_js(
url_path="/?debug=assets",
code="odoo.__DEBUG__.services['web.Tour']"
".run('test_module_name', 'test')",
ready="odoo.__DEBUG__.services['web.Tour'].tours.test_module_name",
login="admin")
| [IMP] Add debug assets to HTTP cases
# -*- coding: utf-8 -*-
# Copyright <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp.tests.common import HttpCase, TransactionCase
class SomethingCase(TransactionCase):
def setUp(self, *args, **kwargs):
super(SomethingCase, self).setUp(*args, **kwargs)
# TODO Replace this for something useful or delete this method
self.do_something_before_all_tests()
def tearDown(self, *args, **kwargs):
# TODO Replace this for something useful or delete this method
self.do_something_after_all_tests()
return super(SomethingCase, self).tearDown(*args, **kwargs)
def test_something(self):
"""First line of docstring appears in test logs.
Other lines do not.
Any method starting with ``test_`` will be tested.
"""
pass
class UICase(HttpCase):
def test_ui_web(self):
"""Test backend tests."""
self.phantom_js("/web/tests?module=module_name", "", login="admin")
def test_ui_website(self):
"""Test frontend tour."""
self.phantom_js(
url_path="/",
code="odoo.__DEBUG__.services['web.Tour']"
".run('test_module_name', 'test')",
ready="odoo.__DEBUG__.services['web.Tour'].tours.test_module_name",
login="admin")
|
e641a19f16b99425aa1b15bd8524f2612b0d6bab | tests/test_registry.py | tests/test_registry.py | import pytest
from web_test_base import *
class TestIATIRegistry(WebTestBase):
urls_to_get = [
"http://iatiregistry.org/"
, "http://www.iatiregistry.org/"
, "https://iatiregistry.org/"
, "https://www.iatiregistry.org/"
]
def test_contains_links(self, loaded_request):
"""
Test that each page contains links to the defined URLs.
"""
result = self._get_links_from_page(loaded_request)
assert "http://www.aidtransparency.net/" in result
assert "http://www.iatistandard.org/" in result
| Add tests for the IATI Registry This adds a 200 response and link checks for the IATI Registry | Add tests for the IATI Registry
This adds a 200 response and link checks for the IATI Registry
| Python | mit | IATI/IATI-Website-Tests | <INSERT> import pytest
from web_test_base import *
class TestIATIRegistry(WebTestBase):
<INSERT_END> <INSERT> urls_to_get = [
"http://iatiregistry.org/"
, "http://www.iatiregistry.org/"
, "https://iatiregistry.org/"
, "https://www.iatiregistry.org/"
]
def test_contains_links(self, loaded_request):
"""
Test that each page contains links to the defined URLs.
"""
result = self._get_links_from_page(loaded_request)
assert "http://www.aidtransparency.net/" in result
assert "http://www.iatistandard.org/" in result
<INSERT_END> <|endoftext|> import pytest
from web_test_base import *
class TestIATIRegistry(WebTestBase):
urls_to_get = [
"http://iatiregistry.org/"
, "http://www.iatiregistry.org/"
, "https://iatiregistry.org/"
, "https://www.iatiregistry.org/"
]
def test_contains_links(self, loaded_request):
"""
Test that each page contains links to the defined URLs.
"""
result = self._get_links_from_page(loaded_request)
assert "http://www.aidtransparency.net/" in result
assert "http://www.iatistandard.org/" in result
| Add tests for the IATI Registry
This adds a 200 response and link checks for the IATI Registry
|
|
a8574ad9d7b7b933bb70fa47f84b3e396d058033 | src/escpos/capabilities.py | src/escpos/capabilities.py | import re
from os import path
import yaml
with open(path.join(path.dirname(__file__), 'capabilities.yml')) as f:
PROFILES = yaml.load(f)
class Profile(object):
profile_data = {}
def __init__(self, columns=None):
self.default_columns = columns
def __getattr__(self, name):
return self.profile_data[name]
def get_columns(self, font):
""" Return the number of columns for the given font.
"""
if self.default_columns:
return self.default_columns
if 'columnConfigs' in self.profile_data:
columns_def = self.columnConfigs[self.defaultColumnConfig]
elif 'columns' in self.profile_data:
columns_def = self.columns
if isinstance(columns_def, int):
return columns_def
return columns_def[font]
def get_profile(name=None, **kwargs):
if isinstance(name, Profile):
return name
clazz = get_profile_class(name or 'default')
return clazz(**kwargs)
CLASS_CACHE = {}
def get_profile_class(name):
if not name in CLASS_CACHE:
profile_data = resolve_profile_data(name)
class_name = '%sProfile' % clean(name)
new_class = type(class_name, (Profile,), {'profile_data': profile_data})
CLASS_CACHE[name] = new_class
return CLASS_CACHE[name]
def clean(s):
# Remove invalid characters
s = re.sub('[^0-9a-zA-Z_]', '', s)
# Remove leading characters until we find a letter or underscore
s = re.sub('^[^a-zA-Z_]+', '', s)
return str(s)
def resolve_profile_data(name):
data = PROFILES[name]
inherits = data.get('inherits')
if not inherits:
return data
if not isinstance(inherits, (tuple, list)):
inherits = [inherits]
merged = {}
for base in reversed(inherits):
base_data = resolve_profile_data(base)
merged.update(base_data)
merged.update(data)
return merged
| Support loading capabilites YAML into Python classes. | Support loading capabilites YAML into Python classes.
| Python | mit | python-escpos/python-escpos,braveheuel/python-escpos,belono/python-escpos | <REPLACE_OLD> <REPLACE_NEW> import re
from os import path
import yaml
with open(path.join(path.dirname(__file__), 'capabilities.yml')) as f:
PROFILES = yaml.load(f)
class Profile(object):
profile_data = {}
def __init__(self, columns=None):
self.default_columns = columns
def __getattr__(self, name):
return self.profile_data[name]
def get_columns(self, font):
""" Return the number of columns for the given font.
"""
if self.default_columns:
return self.default_columns
if 'columnConfigs' in self.profile_data:
columns_def = self.columnConfigs[self.defaultColumnConfig]
elif 'columns' in self.profile_data:
columns_def = self.columns
if isinstance(columns_def, int):
return columns_def
return columns_def[font]
def get_profile(name=None, **kwargs):
if isinstance(name, Profile):
return name
clazz = get_profile_class(name or 'default')
return clazz(**kwargs)
CLASS_CACHE = {}
def get_profile_class(name):
if not name in CLASS_CACHE:
profile_data = resolve_profile_data(name)
class_name = '%sProfile' % clean(name)
new_class = type(class_name, (Profile,), {'profile_data': profile_data})
CLASS_CACHE[name] = new_class
return CLASS_CACHE[name]
def clean(s):
# Remove invalid characters
s = re.sub('[^0-9a-zA-Z_]', '', s)
# Remove leading characters until we find a letter or underscore
s = re.sub('^[^a-zA-Z_]+', '', s)
return str(s)
def resolve_profile_data(name):
data = PROFILES[name]
inherits = data.get('inherits')
if not inherits:
return data
if not isinstance(inherits, (tuple, list)):
inherits = [inherits]
merged = {}
for base in reversed(inherits):
base_data = resolve_profile_data(base)
merged.update(base_data)
merged.update(data)
return merged
<REPLACE_END> <|endoftext|> import re
from os import path
import yaml
with open(path.join(path.dirname(__file__), 'capabilities.yml')) as f:
PROFILES = yaml.load(f)
class Profile(object):
profile_data = {}
def __init__(self, columns=None):
self.default_columns = columns
def __getattr__(self, name):
return self.profile_data[name]
def get_columns(self, font):
""" Return the number of columns for the given font.
"""
if self.default_columns:
return self.default_columns
if 'columnConfigs' in self.profile_data:
columns_def = self.columnConfigs[self.defaultColumnConfig]
elif 'columns' in self.profile_data:
columns_def = self.columns
if isinstance(columns_def, int):
return columns_def
return columns_def[font]
def get_profile(name=None, **kwargs):
if isinstance(name, Profile):
return name
clazz = get_profile_class(name or 'default')
return clazz(**kwargs)
CLASS_CACHE = {}
def get_profile_class(name):
if not name in CLASS_CACHE:
profile_data = resolve_profile_data(name)
class_name = '%sProfile' % clean(name)
new_class = type(class_name, (Profile,), {'profile_data': profile_data})
CLASS_CACHE[name] = new_class
return CLASS_CACHE[name]
def clean(s):
# Remove invalid characters
s = re.sub('[^0-9a-zA-Z_]', '', s)
# Remove leading characters until we find a letter or underscore
s = re.sub('^[^a-zA-Z_]+', '', s)
return str(s)
def resolve_profile_data(name):
data = PROFILES[name]
inherits = data.get('inherits')
if not inherits:
return data
if not isinstance(inherits, (tuple, list)):
inherits = [inherits]
merged = {}
for base in reversed(inherits):
base_data = resolve_profile_data(base)
merged.update(base_data)
merged.update(data)
return merged
| Support loading capabilites YAML into Python classes.
|
|
d251f7f97e5fc32fd41266430ed0e991109e1fbe | setup.py | setup.py | from setuptools import setup, find_packages
from dimod import __version__, __author__, __description__, __authoremail__
install_requires = ['decorator>=4.1.0']
extras_require = {'all': ['numpy']}
packages = ['dimod',
'dimod.responses',
'dimod.composites',
'dimod.samplers']
setup(
name='dimod',
version=__version__,
author=__author__,
author_email=__authoremail__,
description=__description__,
url='https://github.com/dwavesystems/dimod',
download_url='https://github.com/dwavesys/dimod/archive/0.1.1.tar.gz',
license='Apache 2.0',
packages=packages,
install_requires=install_requires,
extras_require=extras_require,
)
| from setuptools import setup, find_packages
from dimod import __version__, __author__, __description__, __authoremail__, _PY2
install_requires = ['decorator>=4.1.0']
if _PY2:
# enum is built-in for python 3
install_requires.append('enum')
extras_require = {'all': ['numpy']}
packages = ['dimod',
'dimod.responses',
'dimod.composites',
'dimod.samplers']
setup(
name='dimod',
version=__version__,
author=__author__,
author_email=__authoremail__,
description=__description__,
url='https://github.com/dwavesystems/dimod',
download_url='https://github.com/dwavesys/dimod/archive/0.1.1.tar.gz',
license='Apache 2.0',
packages=packages,
install_requires=install_requires,
extras_require=extras_require,
)
| Add enum for python2 install | Add enum for python2 install
| Python | apache-2.0 | dwavesystems/dimod,dwavesystems/dimod | <REPLACE_OLD> __authoremail__
install_requires <REPLACE_NEW> __authoremail__, _PY2
install_requires <REPLACE_END> <REPLACE_OLD> ['decorator>=4.1.0']
extras_require <REPLACE_NEW> ['decorator>=4.1.0']
if _PY2:
# enum is built-in for python 3
install_requires.append('enum')
extras_require <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages
from dimod import __version__, __author__, __description__, __authoremail__, _PY2
install_requires = ['decorator>=4.1.0']
if _PY2:
# enum is built-in for python 3
install_requires.append('enum')
extras_require = {'all': ['numpy']}
packages = ['dimod',
'dimod.responses',
'dimod.composites',
'dimod.samplers']
setup(
name='dimod',
version=__version__,
author=__author__,
author_email=__authoremail__,
description=__description__,
url='https://github.com/dwavesystems/dimod',
download_url='https://github.com/dwavesys/dimod/archive/0.1.1.tar.gz',
license='Apache 2.0',
packages=packages,
install_requires=install_requires,
extras_require=extras_require,
)
| Add enum for python2 install
from setuptools import setup, find_packages
from dimod import __version__, __author__, __description__, __authoremail__
install_requires = ['decorator>=4.1.0']
extras_require = {'all': ['numpy']}
packages = ['dimod',
'dimod.responses',
'dimod.composites',
'dimod.samplers']
setup(
name='dimod',
version=__version__,
author=__author__,
author_email=__authoremail__,
description=__description__,
url='https://github.com/dwavesystems/dimod',
download_url='https://github.com/dwavesys/dimod/archive/0.1.1.tar.gz',
license='Apache 2.0',
packages=packages,
install_requires=install_requires,
extras_require=extras_require,
)
|
d5167d8ba1b3107e5ce121eca76b5496bf8d6448 | qipipe/registration/ants/template.py | qipipe/registration/ants/template.py | import os
import logging
import envoy
from .ants_error import ANTSError
def create_template(metric, files):
"""
Builds a template from the given image files.
:param metric: the similarity metric
:param files: the image files
:return: the template file name
"""
CMD = "buildtemplateparallel.sh -d 2 -c 2 -j 4 -d 2 -s {metric} -o {output} {files}"
PREFIX = 'reg_'
SUFFIX = 'template.nii.gz'
tmpl = PREFIX + SUFFIX
if os.path.exists(tmpl):
logging.info("Registration template already exists: %s" % tmpl)
return tmpl
cmd = CMD.format(metric=metric.name, output=PREFIX, files=' '.join(files))
logging.info("Building the %s registration template with the following command:" % tmpl)
logging.info(cmd)
r = envoy.run(cmd)
if r.status_code:
logging.error("Build registration template failed with error code %d" % r.status_code)
logging.error(r.std_err)
raise ANTSError("Build registration template unsuccessful; see the log for details")
if not os.path.exists(tmpl):
logging.error("Build registration template was not created.")
raise ANTSError("Build registration template unsuccessful; see the log for details")
logging.info("Built the registration template %s." % tmpl)
return tmpl
| import os
import logging
import envoy
from .ants_error import ANTSError
def create_template(metric, files):
"""
Builds a template from the given image files.
:param metric: the similarity metric
:param files: the image files
:return: the template file name
"""
CMD = "buildtemplateparallel.sh -d 2 -c 2 -j 4 -d 2 -s {metric} -o {output} {files}"
PREFIX = 'reg_'
SUFFIX = 'template.nii.gz'
tmpl = PREFIX + SUFFIX
if os.path.exists(tmpl):
logging.info("Registration template already exists: %s" % tmpl)
return tmpl
cmd = CMD.format(metric=metric.name, output=PREFIX, files=' '.join(files))
logging.info("Building the %s registration template with the following command:" % tmpl)
logging.info(cmd[:80])
r = envoy.run(cmd)
if r.status_code:
logging.error("Build registration template failed with error code %d" % r.status_code)
logging.error(r.std_err)
raise ANTSError("Build registration template unsuccessful; see the log for details")
if not os.path.exists(tmpl):
logging.error("Build registration template was not created.")
raise ANTSError("Build registration template unsuccessful; see the log for details")
logging.info("Built the registration template %s." % tmpl)
return tmpl
| Truncate a long log message. | Truncate a long log message.
| Python | bsd-2-clause | ohsu-qin/qipipe | <REPLACE_OLD> logging.info(cmd)
<REPLACE_NEW> logging.info(cmd[:80])
<REPLACE_END> <|endoftext|> import os
import logging
import envoy
from .ants_error import ANTSError
def create_template(metric, files):
"""
Builds a template from the given image files.
:param metric: the similarity metric
:param files: the image files
:return: the template file name
"""
CMD = "buildtemplateparallel.sh -d 2 -c 2 -j 4 -d 2 -s {metric} -o {output} {files}"
PREFIX = 'reg_'
SUFFIX = 'template.nii.gz'
tmpl = PREFIX + SUFFIX
if os.path.exists(tmpl):
logging.info("Registration template already exists: %s" % tmpl)
return tmpl
cmd = CMD.format(metric=metric.name, output=PREFIX, files=' '.join(files))
logging.info("Building the %s registration template with the following command:" % tmpl)
logging.info(cmd[:80])
r = envoy.run(cmd)
if r.status_code:
logging.error("Build registration template failed with error code %d" % r.status_code)
logging.error(r.std_err)
raise ANTSError("Build registration template unsuccessful; see the log for details")
if not os.path.exists(tmpl):
logging.error("Build registration template was not created.")
raise ANTSError("Build registration template unsuccessful; see the log for details")
logging.info("Built the registration template %s." % tmpl)
return tmpl
| Truncate a long log message.
import os
import logging
import envoy
from .ants_error import ANTSError
def create_template(metric, files):
"""
Builds a template from the given image files.
:param metric: the similarity metric
:param files: the image files
:return: the template file name
"""
CMD = "buildtemplateparallel.sh -d 2 -c 2 -j 4 -d 2 -s {metric} -o {output} {files}"
PREFIX = 'reg_'
SUFFIX = 'template.nii.gz'
tmpl = PREFIX + SUFFIX
if os.path.exists(tmpl):
logging.info("Registration template already exists: %s" % tmpl)
return tmpl
cmd = CMD.format(metric=metric.name, output=PREFIX, files=' '.join(files))
logging.info("Building the %s registration template with the following command:" % tmpl)
logging.info(cmd)
r = envoy.run(cmd)
if r.status_code:
logging.error("Build registration template failed with error code %d" % r.status_code)
logging.error(r.std_err)
raise ANTSError("Build registration template unsuccessful; see the log for details")
if not os.path.exists(tmpl):
logging.error("Build registration template was not created.")
raise ANTSError("Build registration template unsuccessful; see the log for details")
logging.info("Built the registration template %s." % tmpl)
return tmpl
|
b8839302c0a4d8ada99a695f8829027fa433e05e | zerver/migrations/0232_make_archive_transaction_field_not_nullable.py | zerver/migrations/0232_make_archive_transaction_field_not_nullable.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('zerver', '0231_add_archive_transaction_model'),
]
operations = [
migrations.RunSQL("DELETE FROM zerver_archivedusermessage"),
migrations.RunSQL("DELETE FROM zerver_archivedreaction"),
migrations.RunSQL("DELETE FROM zerver_archivedsubmessage"),
migrations.RunSQL("DELETE FROM zerver_archivedattachment"),
migrations.RunSQL("DELETE FROM zerver_archivedattachment_messages"),
migrations.RunSQL("DELETE FROM zerver_archivedmessage"),
migrations.RunSQL("DELETE FROM zerver_archivetransaction"),
migrations.AlterField(
model_name='archivedmessage',
name='archive_transaction',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.ArchiveTransaction'),
),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
"""
Tables cannot have data deleted from them and be altered in a single transaction,
but we need the DELETEs to be atomic together. So we set atomic=False for the migration
in general, and run the DELETEs in one transaction, and AlterField in another.
"""
atomic = False
dependencies = [
('zerver', '0231_add_archive_transaction_model'),
]
operations = [
migrations.RunSQL("""
BEGIN;
DELETE FROM zerver_archivedusermessage;
DELETE FROM zerver_archivedreaction;
DELETE FROM zerver_archivedsubmessage;
DELETE FROM zerver_archivedattachment_messages;
DELETE FROM zerver_archivedattachment;
DELETE FROM zerver_archivedmessage;
DELETE FROM zerver_archivetransaction;
COMMIT;
"""),
migrations.AlterField(
model_name='archivedmessage',
name='archive_transaction',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.ArchiveTransaction'),
),
]
| Fix migration making archive_transaction field not null. | retention: Fix migration making archive_transaction field not null.
DELETing from archive tables and ALTERing ArchivedMessage needs to be
split into separate transactions.
zerver_archivedattachment_messages needs to be cleared out before
zerver_archivedattachment.
| Python | apache-2.0 | eeshangarg/zulip,shubhamdhama/zulip,zulip/zulip,brainwane/zulip,synicalsyntax/zulip,eeshangarg/zulip,andersk/zulip,hackerkid/zulip,hackerkid/zulip,timabbott/zulip,zulip/zulip,timabbott/zulip,synicalsyntax/zulip,tommyip/zulip,tommyip/zulip,rht/zulip,andersk/zulip,rishig/zulip,rht/zulip,timabbott/zulip,brainwane/zulip,eeshangarg/zulip,showell/zulip,rht/zulip,showell/zulip,andersk/zulip,tommyip/zulip,showell/zulip,showell/zulip,synicalsyntax/zulip,hackerkid/zulip,punchagan/zulip,shubhamdhama/zulip,rishig/zulip,brainwane/zulip,andersk/zulip,rht/zulip,brainwane/zulip,brainwane/zulip,shubhamdhama/zulip,eeshangarg/zulip,timabbott/zulip,rishig/zulip,punchagan/zulip,zulip/zulip,zulip/zulip,showell/zulip,kou/zulip,synicalsyntax/zulip,showell/zulip,timabbott/zulip,andersk/zulip,rishig/zulip,timabbott/zulip,kou/zulip,kou/zulip,brainwane/zulip,rishig/zulip,kou/zulip,eeshangarg/zulip,tommyip/zulip,showell/zulip,tommyip/zulip,shubhamdhama/zulip,punchagan/zulip,synicalsyntax/zulip,rishig/zulip,shubhamdhama/zulip,zulip/zulip,kou/zulip,shubhamdhama/zulip,eeshangarg/zulip,andersk/zulip,andersk/zulip,synicalsyntax/zulip,tommyip/zulip,shubhamdhama/zulip,kou/zulip,punchagan/zulip,rishig/zulip,tommyip/zulip,kou/zulip,hackerkid/zulip,punchagan/zulip,rht/zulip,hackerkid/zulip,rht/zulip,timabbott/zulip,punchagan/zulip,rht/zulip,synicalsyntax/zulip,brainwane/zulip,punchagan/zulip,hackerkid/zulip,hackerkid/zulip,eeshangarg/zulip,zulip/zulip,zulip/zulip | <REPLACE_OLD> django.db.models.deletion
class Migration(migrations.Migration):
<REPLACE_NEW> django.db.models.deletion
class Migration(migrations.Migration):
"""
Tables cannot have data deleted from them and be altered in a single transaction,
but we need the DELETEs to be atomic together. So we set atomic=False for the migration
in general, and run the DELETEs in one transaction, and AlterField in another.
"""
atomic = False
<REPLACE_END> <REPLACE_OLD> migrations.RunSQL("DELETE FROM zerver_archivedusermessage"),
migrations.RunSQL("DELETE FROM zerver_archivedreaction"),
migrations.RunSQL("DELETE FROM zerver_archivedsubmessage"),
migrations.RunSQL("DELETE FROM zerver_archivedattachment"),
migrations.RunSQL("DELETE FROM zerver_archivedattachment_messages"),
migrations.RunSQL("DELETE FROM zerver_archivedmessage"),
migrations.RunSQL("DELETE FROM zerver_archivetransaction"),
<REPLACE_NEW> migrations.RunSQL("""
BEGIN;
DELETE FROM zerver_archivedusermessage;
DELETE FROM zerver_archivedreaction;
DELETE FROM zerver_archivedsubmessage;
DELETE FROM zerver_archivedattachment_messages;
DELETE FROM zerver_archivedattachment;
DELETE FROM zerver_archivedmessage;
DELETE FROM zerver_archivetransaction;
COMMIT;
"""),
<REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
"""
Tables cannot have data deleted from them and be altered in a single transaction,
but we need the DELETEs to be atomic together. So we set atomic=False for the migration
in general, and run the DELETEs in one transaction, and AlterField in another.
"""
atomic = False
dependencies = [
('zerver', '0231_add_archive_transaction_model'),
]
operations = [
migrations.RunSQL("""
BEGIN;
DELETE FROM zerver_archivedusermessage;
DELETE FROM zerver_archivedreaction;
DELETE FROM zerver_archivedsubmessage;
DELETE FROM zerver_archivedattachment_messages;
DELETE FROM zerver_archivedattachment;
DELETE FROM zerver_archivedmessage;
DELETE FROM zerver_archivetransaction;
COMMIT;
"""),
migrations.AlterField(
model_name='archivedmessage',
name='archive_transaction',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.ArchiveTransaction'),
),
]
| retention: Fix migration making archive_transaction field not null.
DELETing from archive tables and ALTERing ArchivedMessage needs to be
split into separate transactions.
zerver_archivedattachment_messages needs to be cleared out before
zerver_archivedattachment.
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('zerver', '0231_add_archive_transaction_model'),
]
operations = [
migrations.RunSQL("DELETE FROM zerver_archivedusermessage"),
migrations.RunSQL("DELETE FROM zerver_archivedreaction"),
migrations.RunSQL("DELETE FROM zerver_archivedsubmessage"),
migrations.RunSQL("DELETE FROM zerver_archivedattachment"),
migrations.RunSQL("DELETE FROM zerver_archivedattachment_messages"),
migrations.RunSQL("DELETE FROM zerver_archivedmessage"),
migrations.RunSQL("DELETE FROM zerver_archivetransaction"),
migrations.AlterField(
model_name='archivedmessage',
name='archive_transaction',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.ArchiveTransaction'),
),
]
|
b6c0a85a3199499b607ebb9ecc057434a9ea2fe5 | mizani/__init__.py | mizani/__init__.py | from importlib.metadata import version, PackageNotFoundError
try:
__version__ = version('plotnine')
except PackageNotFoundError:
# package is not installed
pass
| from importlib.metadata import version, PackageNotFoundError
try:
__version__ = version('mizani')
except PackageNotFoundError:
# package is not installed
pass
| Fix version number to check for mizani | Fix version number to check for mizani
and not plotnine. Copypaste error!
| Python | bsd-3-clause | has2k1/mizani,has2k1/mizani | <REPLACE_OLD> version('plotnine')
except <REPLACE_NEW> version('mizani')
except <REPLACE_END> <|endoftext|> from importlib.metadata import version, PackageNotFoundError
try:
__version__ = version('mizani')
except PackageNotFoundError:
# package is not installed
pass
| Fix version number to check for mizani
and not plotnine. Copypaste error!
from importlib.metadata import version, PackageNotFoundError
try:
__version__ = version('plotnine')
except PackageNotFoundError:
# package is not installed
pass
|
d5ddfb8af861f02074fe113f87a6ea6b4f1bc5db | tests/child-process-sigterm-trap.py | tests/child-process-sigterm-trap.py | #!/usr/bin/env python3
from common import *
import sys, signal
# Be naughty and ignore SIGTERM to simulate hanging child
signal.signal(signal.SIGTERM, signal.SIG_IGN)
# Start a server that listens for incoming connections
try:
print_ok("child starting up on port %s" % sys.argv[1])
s = TcpServer(int(sys.argv[1]))
s.listen()
while True:
try:
s.socket, _ = s.listener.accept()
s.socket.settimeout(TIMEOUT)
except:
pass
finally:
s.cleanup()
print_ok("child exiting")
| #!/usr/bin/env python3
from common import *
import sys, signal
# Be naughty and ignore SIGTERM to simulate hanging child
signal.signal(signal.SIGTERM, signal.SIG_IGN)
# Start a server that listens for incoming connections
try:
print_ok("child starting up on port %s" % sys.argv[1])
s = TcpServer(int(sys.argv[1]))
s.listen()
while True:
try:
s.socket, _ = s.listener.accept()
s.socket.settimeout(TIMEOUT)
except:
pass
finally:
s.cleanup()
print_ok("child exiting")
| Fix formatting in child sample to match other files | Fix formatting in child sample to match other files
| Python | apache-2.0 | square/ghostunnel,square/ghostunnel | <DELETE> <DELETE_END> <DELETE> <DELETE_END> <DELETE> <DELETE_END> <DELETE> <DELETE_END> <DELETE> <DELETE_END> <DELETE> <DELETE_END> <DELETE> <DELETE_END> <DELETE> <DELETE_END> <DELETE> <DELETE_END> <DELETE> <DELETE_END> <|endoftext|> #!/usr/bin/env python3
from common import *
import sys, signal
# Be naughty and ignore SIGTERM to simulate hanging child
signal.signal(signal.SIGTERM, signal.SIG_IGN)
# Start a server that listens for incoming connections
try:
print_ok("child starting up on port %s" % sys.argv[1])
s = TcpServer(int(sys.argv[1]))
s.listen()
while True:
try:
s.socket, _ = s.listener.accept()
s.socket.settimeout(TIMEOUT)
except:
pass
finally:
s.cleanup()
print_ok("child exiting")
| Fix formatting in child sample to match other files
#!/usr/bin/env python3
from common import *
import sys, signal
# Be naughty and ignore SIGTERM to simulate hanging child
signal.signal(signal.SIGTERM, signal.SIG_IGN)
# Start a server that listens for incoming connections
try:
print_ok("child starting up on port %s" % sys.argv[1])
s = TcpServer(int(sys.argv[1]))
s.listen()
while True:
try:
s.socket, _ = s.listener.accept()
s.socket.settimeout(TIMEOUT)
except:
pass
finally:
s.cleanup()
print_ok("child exiting")
|
c54240e6d9f6393370fe94f2cd05476680cf17f2 | pygtfs/__init__.py | pygtfs/__init__.py | from .loader import append_feed, delete_feed, overwrite_feed, list_feeds
from .schedule import Schedule
from ._version import version as __version__
| import warnings
from .loader import append_feed, delete_feed, overwrite_feed, list_feeds
from .schedule import Schedule
try:
from ._version import version as __version__
except ImportError:
warnings.warn("pygtfs should be installed for the version to work")
__version__ = "0"
| Allow usage directly from the code (fix the _version import) | Allow usage directly from the code (fix the _version import)
| Python | mit | jarondl/pygtfs | <REPLACE_OLD> from <REPLACE_NEW> import warnings
from <REPLACE_END> <REPLACE_OLD> Schedule
from <REPLACE_NEW> Schedule
try:
from <REPLACE_END> <REPLACE_OLD> __version__
<REPLACE_NEW> __version__
except ImportError:
warnings.warn("pygtfs should be installed for the version to work")
__version__ = "0"
<REPLACE_END> <|endoftext|> import warnings
from .loader import append_feed, delete_feed, overwrite_feed, list_feeds
from .schedule import Schedule
try:
from ._version import version as __version__
except ImportError:
warnings.warn("pygtfs should be installed for the version to work")
__version__ = "0"
| Allow usage directly from the code (fix the _version import)
from .loader import append_feed, delete_feed, overwrite_feed, list_feeds
from .schedule import Schedule
from ._version import version as __version__
|
663f839ef539759143369f84289b6e27f21bdcce | setup.py | setup.py | #/usr/bin/env python2.6
#
# $Id: setup.py 87 2010-07-01 18:01:03Z ver $
from distutils.core import setup
description = """
The Jersey core libraries provide common abstractions used by Jersey software.
"""
def getVersion():
import os
packageSeedFile = os.path.join("src", "lib", "_version.py")
ns = {"__name__": __name__, }
execfile(packageSeedFile, ns)
return ns["version"]
version = getVersion()
setup(
name = "jersey",
version = version.short(),
description = "Jersey Core Libraries",
long_description = description,
author = "Oliver Gould", author_email = "[email protected]",
maintainer = "Jersey-Devel", maintainer_email = "[email protected]",
package_dir = {
"jersey": "src/lib",
},
packages = [
"jersey",
"jersey.cases",
],
py_modules = [
"jersey._version",
"jersey.cli", "jersey.cases.test_cli",
"jersey.inet", "jersey.cases.test_inet",
"jersey.log", "jersey.cases.test_log",
],
provides = [
"jersey",
"jersey.cli",
"jersey.log",
],
requires = [
"twisted (>=9.0.0)",
],
)
| #/usr/bin/env python2.6
#
# $Id: setup.py 87 2010-07-01 18:01:03Z ver $
from distutils.core import setup
description = """
The Jersey core libraries provide common abstractions used by Jersey software.
"""
def getVersion():
import os
packageSeedFile = os.path.join("lib", "_version.py")
ns = {"__name__": __name__, }
execfile(packageSeedFile, ns)
return ns["version"]
version = getVersion()
setup(
name = "jersey",
version = version.short(),
description = "Jersey Core Libraries",
long_description = description,
author = "Oliver Gould", author_email = "[email protected]",
maintainer = "Jersey-Devel", maintainer_email = "[email protected]",
package_dir = {
"jersey": "lib",
},
packages = [
"jersey",
"jersey.cases",
],
py_modules = [
"jersey._version",
"jersey.cli", "jersey.cases.test_cli",
"jersey.inet", "jersey.cases.test_inet",
"jersey.log", "jersey.cases.test_log",
],
provides = [
"jersey",
"jersey.cli",
"jersey.log",
],
requires = [
"twisted (>=9.0.0)",
],
)
| Use lib/ instead of src/lib. | Use lib/ instead of src/lib.
| Python | bsd-3-clause | olix0r/tx-jersey | <REPLACE_OLD> os.path.join("src", "lib", <REPLACE_NEW> os.path.join("lib", <REPLACE_END> <REPLACE_OLD> "src/lib",
<REPLACE_NEW> "lib",
<REPLACE_END> <|endoftext|> #/usr/bin/env python2.6
#
# $Id: setup.py 87 2010-07-01 18:01:03Z ver $
from distutils.core import setup
description = """
The Jersey core libraries provide common abstractions used by Jersey software.
"""
def getVersion():
import os
packageSeedFile = os.path.join("lib", "_version.py")
ns = {"__name__": __name__, }
execfile(packageSeedFile, ns)
return ns["version"]
version = getVersion()
setup(
name = "jersey",
version = version.short(),
description = "Jersey Core Libraries",
long_description = description,
author = "Oliver Gould", author_email = "[email protected]",
maintainer = "Jersey-Devel", maintainer_email = "[email protected]",
package_dir = {
"jersey": "lib",
},
packages = [
"jersey",
"jersey.cases",
],
py_modules = [
"jersey._version",
"jersey.cli", "jersey.cases.test_cli",
"jersey.inet", "jersey.cases.test_inet",
"jersey.log", "jersey.cases.test_log",
],
provides = [
"jersey",
"jersey.cli",
"jersey.log",
],
requires = [
"twisted (>=9.0.0)",
],
)
| Use lib/ instead of src/lib.
#/usr/bin/env python2.6
#
# $Id: setup.py 87 2010-07-01 18:01:03Z ver $
from distutils.core import setup
description = """
The Jersey core libraries provide common abstractions used by Jersey software.
"""
def getVersion():
import os
packageSeedFile = os.path.join("src", "lib", "_version.py")
ns = {"__name__": __name__, }
execfile(packageSeedFile, ns)
return ns["version"]
version = getVersion()
setup(
name = "jersey",
version = version.short(),
description = "Jersey Core Libraries",
long_description = description,
author = "Oliver Gould", author_email = "[email protected]",
maintainer = "Jersey-Devel", maintainer_email = "[email protected]",
package_dir = {
"jersey": "src/lib",
},
packages = [
"jersey",
"jersey.cases",
],
py_modules = [
"jersey._version",
"jersey.cli", "jersey.cases.test_cli",
"jersey.inet", "jersey.cases.test_inet",
"jersey.log", "jersey.cases.test_log",
],
provides = [
"jersey",
"jersey.cli",
"jersey.log",
],
requires = [
"twisted (>=9.0.0)",
],
)
|
4574fe87c6efa5b1b9431546f787fcf30ad0d6b6 | examples/training/train_parser.py | examples/training/train_parser.py | from __future__ import unicode_literals, print_function
import json
import pathlib
import random
import spacy
from spacy.pipeline import DependencyParser
from spacy.gold import GoldParse
from spacy.tokens import Doc
def train_parser(nlp, train_data, left_labels, right_labels):
parser = DependencyParser.blank(
nlp.vocab,
left_labels=left_labels,
right_labels=right_labels,
features=nlp.defaults.parser_features)
for itn in range(1000):
random.shuffle(train_data)
loss = 0
for words, heads, deps in train_data:
doc = nlp.make_doc(words)
gold = GoldParse(doc, heads=heads, deps=deps)
loss += parser.update(doc, gold)
parser.model.end_training()
return parser
def main(model_dir=None):
if model_dir is not None:
model_dir = pathlb.Path(model_dir)
if not model_dir.exists():
model_dir.mkdir()
assert model_dir.isdir()
nlp = spacy.load('en', tagger=False, parser=False, entity=False, vectors=False)
nlp.make_doc = lambda words: Doc(nlp.vocab, zip(words, [True]*len(words)))
train_data = [
(
['They', 'trade', 'mortgage', '-', 'backed', 'securities', '.'],
[1, 1, 4, 4, 5, 1, 1],
['nsubj', 'ROOT', 'compound', 'punct', 'nmod', 'dobj', 'punct']
),
(
['I', 'like', 'London', 'and', 'Berlin', '.'],
[1, 1, 1, 2, 2, 1],
['nsubj', 'ROOT', 'dobj', 'cc', 'conj', 'punct']
)
]
left_labels = set()
right_labels = set()
for _, heads, deps in train_data:
for i, (head, dep) in enumerate(zip(heads, deps)):
if i < head:
left_labels.add(dep)
elif i > head:
right_labels.add(dep)
parser = train_parser(nlp, train_data, sorted(left_labels), sorted(right_labels))
doc = nlp.make_doc(['I', 'like', 'securities', '.'])
with parser.step_through(doc) as state:
while not state.is_final:
action = state.predict()
state.transition(action)
#parser(doc)
for word in doc:
print(word.text, word.dep_, word.head.text)
if model_dir is not None:
with (model_dir / 'config.json').open('wb') as file_:
json.dump(parser.cfg, file_)
parser.model.dump(str(model_dir / 'model'))
if __name__ == '__main__':
main()
# I nsubj like
# like ROOT like
# securities dobj like
# . cc securities
| Add example for training parser | Add example for training parser
| Python | mit | raphael0202/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,banglakit/spaCy,spacy-io/spaCy,oroszgy/spaCy.hu,explosion/spaCy,raphael0202/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spaCy,oroszgy/spaCy.hu,honnibal/spaCy,honnibal/spaCy,Gregory-Howard/spaCy,recognai/spaCy,banglakit/spaCy,recognai/spaCy,spacy-io/spaCy,explosion/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,oroszgy/spaCy.hu,recognai/spaCy,spacy-io/spaCy,raphael0202/spaCy,honnibal/spaCy,explosion/spaCy,raphael0202/spaCy,raphael0202/spaCy,Gregory-Howard/spaCy,Gregory-Howard/spaCy,explosion/spaCy,banglakit/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,aikramer2/spaCy,oroszgy/spaCy.hu,Gregory-Howard/spaCy,honnibal/spaCy,banglakit/spaCy,recognai/spaCy,explosion/spaCy,aikramer2/spaCy,raphael0202/spaCy,banglakit/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,banglakit/spaCy | <REPLACE_OLD> <REPLACE_NEW> from __future__ import unicode_literals, print_function
import json
import pathlib
import random
import spacy
from spacy.pipeline import DependencyParser
from spacy.gold import GoldParse
from spacy.tokens import Doc
def train_parser(nlp, train_data, left_labels, right_labels):
parser = DependencyParser.blank(
nlp.vocab,
left_labels=left_labels,
right_labels=right_labels,
features=nlp.defaults.parser_features)
for itn in range(1000):
random.shuffle(train_data)
loss = 0
for words, heads, deps in train_data:
doc = nlp.make_doc(words)
gold = GoldParse(doc, heads=heads, deps=deps)
loss += parser.update(doc, gold)
parser.model.end_training()
return parser
def main(model_dir=None):
if model_dir is not None:
model_dir = pathlb.Path(model_dir)
if not model_dir.exists():
model_dir.mkdir()
assert model_dir.isdir()
nlp = spacy.load('en', tagger=False, parser=False, entity=False, vectors=False)
nlp.make_doc = lambda words: Doc(nlp.vocab, zip(words, [True]*len(words)))
train_data = [
(
['They', 'trade', 'mortgage', '-', 'backed', 'securities', '.'],
[1, 1, 4, 4, 5, 1, 1],
['nsubj', 'ROOT', 'compound', 'punct', 'nmod', 'dobj', 'punct']
),
(
['I', 'like', 'London', 'and', 'Berlin', '.'],
[1, 1, 1, 2, 2, 1],
['nsubj', 'ROOT', 'dobj', 'cc', 'conj', 'punct']
)
]
left_labels = set()
right_labels = set()
for _, heads, deps in train_data:
for i, (head, dep) in enumerate(zip(heads, deps)):
if i < head:
left_labels.add(dep)
elif i > head:
right_labels.add(dep)
parser = train_parser(nlp, train_data, sorted(left_labels), sorted(right_labels))
doc = nlp.make_doc(['I', 'like', 'securities', '.'])
with parser.step_through(doc) as state:
while not state.is_final:
action = state.predict()
state.transition(action)
#parser(doc)
for word in doc:
print(word.text, word.dep_, word.head.text)
if model_dir is not None:
with (model_dir / 'config.json').open('wb') as file_:
json.dump(parser.cfg, file_)
parser.model.dump(str(model_dir / 'model'))
if __name__ == '__main__':
main()
# I nsubj like
# like ROOT like
# securities dobj like
# . cc securities
<REPLACE_END> <|endoftext|> from __future__ import unicode_literals, print_function
import json
import pathlib
import random
import spacy
from spacy.pipeline import DependencyParser
from spacy.gold import GoldParse
from spacy.tokens import Doc
def train_parser(nlp, train_data, left_labels, right_labels):
parser = DependencyParser.blank(
nlp.vocab,
left_labels=left_labels,
right_labels=right_labels,
features=nlp.defaults.parser_features)
for itn in range(1000):
random.shuffle(train_data)
loss = 0
for words, heads, deps in train_data:
doc = nlp.make_doc(words)
gold = GoldParse(doc, heads=heads, deps=deps)
loss += parser.update(doc, gold)
parser.model.end_training()
return parser
def main(model_dir=None):
if model_dir is not None:
model_dir = pathlb.Path(model_dir)
if not model_dir.exists():
model_dir.mkdir()
assert model_dir.isdir()
nlp = spacy.load('en', tagger=False, parser=False, entity=False, vectors=False)
nlp.make_doc = lambda words: Doc(nlp.vocab, zip(words, [True]*len(words)))
train_data = [
(
['They', 'trade', 'mortgage', '-', 'backed', 'securities', '.'],
[1, 1, 4, 4, 5, 1, 1],
['nsubj', 'ROOT', 'compound', 'punct', 'nmod', 'dobj', 'punct']
),
(
['I', 'like', 'London', 'and', 'Berlin', '.'],
[1, 1, 1, 2, 2, 1],
['nsubj', 'ROOT', 'dobj', 'cc', 'conj', 'punct']
)
]
left_labels = set()
right_labels = set()
for _, heads, deps in train_data:
for i, (head, dep) in enumerate(zip(heads, deps)):
if i < head:
left_labels.add(dep)
elif i > head:
right_labels.add(dep)
parser = train_parser(nlp, train_data, sorted(left_labels), sorted(right_labels))
doc = nlp.make_doc(['I', 'like', 'securities', '.'])
with parser.step_through(doc) as state:
while not state.is_final:
action = state.predict()
state.transition(action)
#parser(doc)
for word in doc:
print(word.text, word.dep_, word.head.text)
if model_dir is not None:
with (model_dir / 'config.json').open('wb') as file_:
json.dump(parser.cfg, file_)
parser.model.dump(str(model_dir / 'model'))
if __name__ == '__main__':
main()
# I nsubj like
# like ROOT like
# securities dobj like
# . cc securities
| Add example for training parser
|
|
46cec51fa3b81da21662da5d36ccaf1f409caaea | gem/personalise/templatetags/personalise_extras.py | gem/personalise/templatetags/personalise_extras.py | from django import template
from wagtail_personalisation.adapters import get_segment_adapter
register = template.Library()
@register.simple_tag
def filter_surveys_by_segments(surveys, request):
"""Filter out surveys not in user's segments."""
user_segments = get_segment_adapter(request).get_segments()
user_segments_ids = [s.id for s in user_segments]
filetered_surveys = []
for survey in surveys:
if not survey.segment_id:
filetered_surveys.append(survey)
elif survey.segment_id in user_segments_ids:
filetered_surveys.append(survey)
return filetered_surveys
| from django import template
from wagtail_personalisation.adapters import get_segment_adapter
register = template.Library()
@register.simple_tag
def filter_surveys_by_segments(surveys, request):
"""Filter out surveys not in user's segments."""
user_segments = get_segment_adapter(request).get_segments()
user_segments_ids = [s.id for s in user_segments]
filtered_surveys = []
for survey in surveys:
if not hasattr(survey, 'segment_id') or not survey.segment_id \
or survey.segment_id in user_segments_ids:
filtered_surveys.append(survey)
return filtered_surveys
| Fix error when displaying other types of surveys | Fix error when displaying other types of surveys
| Python | bsd-2-clause | praekelt/molo-gem,praekelt/molo-gem,praekelt/molo-gem | <REPLACE_OLD> filetered_surveys <REPLACE_NEW> filtered_surveys <REPLACE_END> <REPLACE_OLD> survey.segment_id:
<REPLACE_NEW> hasattr(survey, 'segment_id') or not survey.segment_id \
<REPLACE_END> <DELETE> filetered_surveys.append(survey)
<DELETE_END> <REPLACE_OLD> elif <REPLACE_NEW> or <REPLACE_END> <REPLACE_OLD> filetered_surveys.append(survey)
<REPLACE_NEW> filtered_surveys.append(survey)
<REPLACE_END> <REPLACE_OLD> filetered_surveys
<REPLACE_NEW> filtered_surveys
<REPLACE_END> <|endoftext|> from django import template
from wagtail_personalisation.adapters import get_segment_adapter
register = template.Library()
@register.simple_tag
def filter_surveys_by_segments(surveys, request):
"""Filter out surveys not in user's segments."""
user_segments = get_segment_adapter(request).get_segments()
user_segments_ids = [s.id for s in user_segments]
filtered_surveys = []
for survey in surveys:
if not hasattr(survey, 'segment_id') or not survey.segment_id \
or survey.segment_id in user_segments_ids:
filtered_surveys.append(survey)
return filtered_surveys
| Fix error when displaying other types of surveys
from django import template
from wagtail_personalisation.adapters import get_segment_adapter
register = template.Library()
@register.simple_tag
def filter_surveys_by_segments(surveys, request):
"""Filter out surveys not in user's segments."""
user_segments = get_segment_adapter(request).get_segments()
user_segments_ids = [s.id for s in user_segments]
filetered_surveys = []
for survey in surveys:
if not survey.segment_id:
filetered_surveys.append(survey)
elif survey.segment_id in user_segments_ids:
filetered_surveys.append(survey)
return filetered_surveys
|
caf25fab4495e116303a83d52601da164b13638f | angkot/route/management/commands/export_geojson.py | angkot/route/management/commands/export_geojson.py | import sys
import os
import json
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Export Route(s) as GeoJSON'
option_list = BaseCommand.option_list + (
make_option('-o', dest='output_directory'),
)
def handle(self, *args, **kwargs):
if len(args) == 0:
raise CommandError('Please specify transportation id')
output = kwargs.get('output_directory')
tid = args[0]
self._export(tid, output)
def _export(self, tid, output=None):
t = self._get_route_or_fail(tid)
self._write(t, output)
def _get_route_or_fail(self, tid):
from angkot.route.models import Transportation
t = Transportation.objects.filter(pk=tid, active=True)
if len(t) == 0:
raise CommandError('Transportation id not found: {}'.format(tid))
return t[0]
def _write(self, t, output=None):
data = t.to_geojson()
data['properties']['legal'] = dict(
license='ODbL 1.0',
copyright='Β© AngkotWebId Contributors')
geojson = json.dumps(data, indent=4)
out = self._get_output(t, output)
out.write(geojson)
out.close()
def _get_output(self, t, output=None):
if output is None:
return sys.stdout
fname = '{} - {} - {} - {} - {}.json'.format(t.id, t.province, t.city, t.company, t.number)
path = os.path.join(output, fname)
return open(path, 'w')
| Add script to export route to GeoJSON data | Add script to export route to GeoJSON data
| Python | agpl-3.0 | angkot/angkot,angkot/angkot,angkot/angkot,angkot/angkot | <REPLACE_OLD> <REPLACE_NEW> import sys
import os
import json
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Export Route(s) as GeoJSON'
option_list = BaseCommand.option_list + (
make_option('-o', dest='output_directory'),
)
def handle(self, *args, **kwargs):
if len(args) == 0:
raise CommandError('Please specify transportation id')
output = kwargs.get('output_directory')
tid = args[0]
self._export(tid, output)
def _export(self, tid, output=None):
t = self._get_route_or_fail(tid)
self._write(t, output)
def _get_route_or_fail(self, tid):
from angkot.route.models import Transportation
t = Transportation.objects.filter(pk=tid, active=True)
if len(t) == 0:
raise CommandError('Transportation id not found: {}'.format(tid))
return t[0]
def _write(self, t, output=None):
data = t.to_geojson()
data['properties']['legal'] = dict(
license='ODbL 1.0',
copyright='Β© AngkotWebId Contributors')
geojson = json.dumps(data, indent=4)
out = self._get_output(t, output)
out.write(geojson)
out.close()
def _get_output(self, t, output=None):
if output is None:
return sys.stdout
fname = '{} - {} - {} - {} - {}.json'.format(t.id, t.province, t.city, t.company, t.number)
path = os.path.join(output, fname)
return open(path, 'w')
<REPLACE_END> <|endoftext|> import sys
import os
import json
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Export Route(s) as GeoJSON'
option_list = BaseCommand.option_list + (
make_option('-o', dest='output_directory'),
)
def handle(self, *args, **kwargs):
if len(args) == 0:
raise CommandError('Please specify transportation id')
output = kwargs.get('output_directory')
tid = args[0]
self._export(tid, output)
def _export(self, tid, output=None):
t = self._get_route_or_fail(tid)
self._write(t, output)
def _get_route_or_fail(self, tid):
from angkot.route.models import Transportation
t = Transportation.objects.filter(pk=tid, active=True)
if len(t) == 0:
raise CommandError('Transportation id not found: {}'.format(tid))
return t[0]
def _write(self, t, output=None):
data = t.to_geojson()
data['properties']['legal'] = dict(
license='ODbL 1.0',
copyright='Β© AngkotWebId Contributors')
geojson = json.dumps(data, indent=4)
out = self._get_output(t, output)
out.write(geojson)
out.close()
def _get_output(self, t, output=None):
if output is None:
return sys.stdout
fname = '{} - {} - {} - {} - {}.json'.format(t.id, t.province, t.city, t.company, t.number)
path = os.path.join(output, fname)
return open(path, 'w')
| Add script to export route to GeoJSON data
|
|
11f6fd6e2401af03730afccb14f843928c27c37a | setup.py | setup.py | from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='savu',
version='0.1',
description='Savu Python Tomography Pipeline',
long_description=readme(),
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering'
],
author='Mark Basham',
author_email='[email protected]',
license='Apache License, Version 2.0',
packages=['savu',
'savu.core',
'savu.data',
'savu.mpi_test',
'savu.mpi_test.dls',
'savu.plugins',
'savu.test'],
include_package_data=True,
zip_safe=False) | from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='savu',
version='0.1.1',
description='Savu Python Tomography Pipeline',
long_description=readme(),
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering'
],
author='Mark Basham',
author_email='[email protected]',
license='Apache License, Version 2.0',
packages=['savu',
'savu.core',
'savu.data',
'savu.mpi_test',
'savu.mpi_test.dls',
'savu.plugins',
'savu.test'],
include_package_data=True,
zip_safe=False) | Update to version 0.1.1 for the next push | Update to version 0.1.1 for the next push | Python | apache-2.0 | mjn19172/Savu,swtp1v07/Savu,mjn19172/Savu,swtp1v07/Savu,swtp1v07/Savu,swtp1v07/Savu,mjn19172/Savu,mjn19172/Savu,mjn19172/Savu | <REPLACE_OLD> version='0.1',
<REPLACE_NEW> version='0.1.1',
<REPLACE_END> <|endoftext|> from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='savu',
version='0.1.1',
description='Savu Python Tomography Pipeline',
long_description=readme(),
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering'
],
author='Mark Basham',
author_email='[email protected]',
license='Apache License, Version 2.0',
packages=['savu',
'savu.core',
'savu.data',
'savu.mpi_test',
'savu.mpi_test.dls',
'savu.plugins',
'savu.test'],
include_package_data=True,
zip_safe=False) | Update to version 0.1.1 for the next push
from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='savu',
version='0.1',
description='Savu Python Tomography Pipeline',
long_description=readme(),
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering'
],
author='Mark Basham',
author_email='[email protected]',
license='Apache License, Version 2.0',
packages=['savu',
'savu.core',
'savu.data',
'savu.mpi_test',
'savu.mpi_test.dls',
'savu.plugins',
'savu.test'],
include_package_data=True,
zip_safe=False) |
f87b10b6a6639843b68777e5346109acb44c948a | profile_compressible_solver/gaussian.py | profile_compressible_solver/gaussian.py | from firedrake import (SpatialCoordinate, dot, cross, sqrt, atan_2,
exp, as_vector, Constant, acos)
import numpy as np
class Gaussian(object):
def __init__(self,
mesh,
dir_from_center,
radial_dist,
sigma_theta,
sigma_r,
amplitude=1):
self._mesh = mesh
self._n0 = dir_from_center
self._r0 = radial_dist
self._sigma_theta = sigma_theta
self._sigma_r = sigma_r
self._amp = amplitude
self.x = SpatialCoordinate(mesh)
@property
def r(self):
x = self.x
return sqrt(x[0]**2 + x[1]**2 + x[2]**2)
@property
def theta(self):
x = self.x
n0 = self._n0
return acos(dot(x, n0) / abs(dot(x, n0)))
@property
def r_expr(self):
r = self.r
r0 = self._r0
return r - r0
@property
def expression(self):
A = self._amp
theta = self.theta
R = self.r_expr
sigma_theta = self._sigma_theta
sigma_r = self._sigma_r
return A*exp(-0.5*((theta/sigma_theta)**2 + (R/sigma_r)**2))
class MultipleGaussians(object):
def __init__(self, n_gaussians, r_earth, thickness, seed=2097152):
self._N = n_gaussians
self._R = r_earth
self._H = thickness
self._seed = seed
self._generate_random_vars()
def _generate_random_vars(self):
np.random.rand(self._seed)
ns = []
rs = []
for i in range(self._N):
nrm = 0.0
while (nrm < 0.5) or (nrm > 1.0):
n = 2*np.random.rand(3) - 1.0
nrm = np.linalg.norm(n)
ns.append(as_vector(list(n)))
rs.append(Constant(self._R + self._H * np.random.rand()))
self._random_Ns = ns
self._random_Rs = rs
def expression(self, mesh):
gs = []
for i, (n, r0) in enumerate(zip(self._random_Ns, self._random_Rs)):
sigma_theta = 1.0 - 0.5 * (i / self._N)
sigma_r = (1.0 - 0.5 * (i / self._N)) * self._H
amplitude = 1.0
g = Gaussian(mesh, n, r0, sigma_theta, sigma_r, amplitude)
gs.append(g.expression)
return sum(gs)
| Set up object to create random pressure field | Set up object to create random pressure field
| Python | mit | thomasgibson/firedrake-hybridization | <REPLACE_OLD> <REPLACE_NEW> from firedrake import (SpatialCoordinate, dot, cross, sqrt, atan_2,
exp, as_vector, Constant, acos)
import numpy as np
class Gaussian(object):
def __init__(self,
mesh,
dir_from_center,
radial_dist,
sigma_theta,
sigma_r,
amplitude=1):
self._mesh = mesh
self._n0 = dir_from_center
self._r0 = radial_dist
self._sigma_theta = sigma_theta
self._sigma_r = sigma_r
self._amp = amplitude
self.x = SpatialCoordinate(mesh)
@property
def r(self):
x = self.x
return sqrt(x[0]**2 + x[1]**2 + x[2]**2)
@property
def theta(self):
x = self.x
n0 = self._n0
return acos(dot(x, n0) / abs(dot(x, n0)))
@property
def r_expr(self):
r = self.r
r0 = self._r0
return r - r0
@property
def expression(self):
A = self._amp
theta = self.theta
R = self.r_expr
sigma_theta = self._sigma_theta
sigma_r = self._sigma_r
return A*exp(-0.5*((theta/sigma_theta)**2 + (R/sigma_r)**2))
class MultipleGaussians(object):
def __init__(self, n_gaussians, r_earth, thickness, seed=2097152):
self._N = n_gaussians
self._R = r_earth
self._H = thickness
self._seed = seed
self._generate_random_vars()
def _generate_random_vars(self):
np.random.rand(self._seed)
ns = []
rs = []
for i in range(self._N):
nrm = 0.0
while (nrm < 0.5) or (nrm > 1.0):
n = 2*np.random.rand(3) - 1.0
nrm = np.linalg.norm(n)
ns.append(as_vector(list(n)))
rs.append(Constant(self._R + self._H * np.random.rand()))
self._random_Ns = ns
self._random_Rs = rs
def expression(self, mesh):
gs = []
for i, (n, r0) in enumerate(zip(self._random_Ns, self._random_Rs)):
sigma_theta = 1.0 - 0.5 * (i / self._N)
sigma_r = (1.0 - 0.5 * (i / self._N)) * self._H
amplitude = 1.0
g = Gaussian(mesh, n, r0, sigma_theta, sigma_r, amplitude)
gs.append(g.expression)
return sum(gs)
<REPLACE_END> <|endoftext|> from firedrake import (SpatialCoordinate, dot, cross, sqrt, atan_2,
exp, as_vector, Constant, acos)
import numpy as np
class Gaussian(object):
def __init__(self,
mesh,
dir_from_center,
radial_dist,
sigma_theta,
sigma_r,
amplitude=1):
self._mesh = mesh
self._n0 = dir_from_center
self._r0 = radial_dist
self._sigma_theta = sigma_theta
self._sigma_r = sigma_r
self._amp = amplitude
self.x = SpatialCoordinate(mesh)
@property
def r(self):
x = self.x
return sqrt(x[0]**2 + x[1]**2 + x[2]**2)
@property
def theta(self):
x = self.x
n0 = self._n0
return acos(dot(x, n0) / abs(dot(x, n0)))
@property
def r_expr(self):
r = self.r
r0 = self._r0
return r - r0
@property
def expression(self):
A = self._amp
theta = self.theta
R = self.r_expr
sigma_theta = self._sigma_theta
sigma_r = self._sigma_r
return A*exp(-0.5*((theta/sigma_theta)**2 + (R/sigma_r)**2))
class MultipleGaussians(object):
def __init__(self, n_gaussians, r_earth, thickness, seed=2097152):
self._N = n_gaussians
self._R = r_earth
self._H = thickness
self._seed = seed
self._generate_random_vars()
def _generate_random_vars(self):
np.random.rand(self._seed)
ns = []
rs = []
for i in range(self._N):
nrm = 0.0
while (nrm < 0.5) or (nrm > 1.0):
n = 2*np.random.rand(3) - 1.0
nrm = np.linalg.norm(n)
ns.append(as_vector(list(n)))
rs.append(Constant(self._R + self._H * np.random.rand()))
self._random_Ns = ns
self._random_Rs = rs
def expression(self, mesh):
gs = []
for i, (n, r0) in enumerate(zip(self._random_Ns, self._random_Rs)):
sigma_theta = 1.0 - 0.5 * (i / self._N)
sigma_r = (1.0 - 0.5 * (i / self._N)) * self._H
amplitude = 1.0
g = Gaussian(mesh, n, r0, sigma_theta, sigma_r, amplitude)
gs.append(g.expression)
return sum(gs)
| Set up object to create random pressure field
|
|
3cbc6bdd5bcc480d105ce53bffd5b350b7dc8179 | setup.py | setup.py | from setuptools import setup
import os
#Function to read README
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='clipboard_memo',
version='0.1',
description='A command-line clipboard manager',
long_description=read('README.md'),
url='http://github.com/arafsheikh/clipboard-memo',
author='Sheikh Araf',
author_email='[email protected]',
license='MIT',
keywords='clipboard memo manager command-line CLI',
include_package_data=True,
entry_points='''
[console_scripts]
cmemo=clipboard_memo:main
cmemo_direct=clipboard_memo:direct_save
''',
py_modules=['clipboard_memo'],
install_requires=[
'pyperclip',
],
)
| from setuptools import setup
import os
#Function to read README
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='clipboard_memo',
version='0.1',
description='A command-line clipboard manager',
long_description=read('README.rst'),
url='http://github.com/arafsheikh/clipboard-memo',
author='Sheikh Araf',
author_email='[email protected]',
license='MIT',
keywords='clipboard memo manager command-line CLI',
include_package_data=True,
entry_points='''
[console_scripts]
cmemo=clipboard_memo:main
cmemo_direct=clipboard_memo:direct_save
''',
py_modules=['clipboard_memo'],
install_requires=[
'pyperclip',
],
)
| Use README.rst for long description | Use README.rst for long description
| Python | mit | arafsheikh/clipboard-memo | <REPLACE_OLD> long_description=read('README.md'),
<REPLACE_NEW> long_description=read('README.rst'),
<REPLACE_END> <|endoftext|> from setuptools import setup
import os
#Function to read README
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='clipboard_memo',
version='0.1',
description='A command-line clipboard manager',
long_description=read('README.rst'),
url='http://github.com/arafsheikh/clipboard-memo',
author='Sheikh Araf',
author_email='[email protected]',
license='MIT',
keywords='clipboard memo manager command-line CLI',
include_package_data=True,
entry_points='''
[console_scripts]
cmemo=clipboard_memo:main
cmemo_direct=clipboard_memo:direct_save
''',
py_modules=['clipboard_memo'],
install_requires=[
'pyperclip',
],
)
| Use README.rst for long description
from setuptools import setup
import os
#Function to read README
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='clipboard_memo',
version='0.1',
description='A command-line clipboard manager',
long_description=read('README.md'),
url='http://github.com/arafsheikh/clipboard-memo',
author='Sheikh Araf',
author_email='[email protected]',
license='MIT',
keywords='clipboard memo manager command-line CLI',
include_package_data=True,
entry_points='''
[console_scripts]
cmemo=clipboard_memo:main
cmemo_direct=clipboard_memo:direct_save
''',
py_modules=['clipboard_memo'],
install_requires=[
'pyperclip',
],
)
|
2fedb73b2c83fc7bb1b354d8b1ebd8dfe8497995 | dataportal/tests/test_examples.py | dataportal/tests/test_examples.py | import unittest
from ..examples.sample_data import (temperature_ramp, multisource_event,
image_and_scalar)
from metadatastore.api import Document
class CommonSampleDataTests(object):
def setUp(self):
pass
def test_basic_usage(self):
events = self.example.run()
# check expected types
self.assertTrue(isinstance(events, list))
self.assertTrue(isinstance(events[0], Document))
class TestTemperatureRamp(CommonSampleDataTests, unittest.TestCase):
def setUp(self):
self.example = temperature_ramp
class TestMultisourceEvent(CommonSampleDataTests, unittest.TestCase):
def setUp(self):
self.example = multisource_event
class TestImageAndScalar(CommonSampleDataTests, unittest.TestCase):
def setUp(self):
self.example = image_and_scalar
| from nose.tools import assert_true
from ..examples.sample_data import (temperature_ramp, multisource_event,
image_and_scalar)
from metadatastore.api import Document
def run_example(example):
events = example.run()
assert_true(isinstance(events, list))
assert_true(isinstance(events[0], Document))
def test_examples():
for example in [temperature_ramp, multisource_event, image_and_scalar]:
yield run_example, example
| Use generator test for examples. | REF: Use generator test for examples.
| Python | bsd-3-clause | ericdill/datamuxer,danielballan/datamuxer,NSLS-II/dataportal,tacaswell/dataportal,danielballan/dataportal,ericdill/databroker,NSLS-II/datamuxer,danielballan/datamuxer,NSLS-II/dataportal,danielballan/dataportal,ericdill/databroker,tacaswell/dataportal,ericdill/datamuxer | <INSERT> from nose.tools <INSERT_END> <REPLACE_OLD> unittest
from <REPLACE_NEW> assert_true
from <REPLACE_END> <REPLACE_OLD> Document
class CommonSampleDataTests(object):
<REPLACE_NEW> Document
def run_example(example):
<REPLACE_END> <REPLACE_OLD> def setUp(self):
<REPLACE_NEW> events = example.run()
assert_true(isinstance(events, list))
assert_true(isinstance(events[0], Document))
def test_examples():
for example in [temperature_ramp, multisource_event, image_and_scalar]:
<REPLACE_END> <REPLACE_OLD> pass
def test_basic_usage(self):
events = self.example.run()
# check expected types
self.assertTrue(isinstance(events, list))
self.assertTrue(isinstance(events[0], Document))
class TestTemperatureRamp(CommonSampleDataTests, unittest.TestCase):
def setUp(self):
self.example = temperature_ramp
class TestMultisourceEvent(CommonSampleDataTests, unittest.TestCase):
def setUp(self):
self.example = multisource_event
class TestImageAndScalar(CommonSampleDataTests, unittest.TestCase):
def setUp(self):
self.example = image_and_scalar
<REPLACE_NEW> yield run_example, example
<REPLACE_END> <|endoftext|> from nose.tools import assert_true
from ..examples.sample_data import (temperature_ramp, multisource_event,
image_and_scalar)
from metadatastore.api import Document
def run_example(example):
events = example.run()
assert_true(isinstance(events, list))
assert_true(isinstance(events[0], Document))
def test_examples():
for example in [temperature_ramp, multisource_event, image_and_scalar]:
yield run_example, example
| REF: Use generator test for examples.
import unittest
from ..examples.sample_data import (temperature_ramp, multisource_event,
image_and_scalar)
from metadatastore.api import Document
class CommonSampleDataTests(object):
def setUp(self):
pass
def test_basic_usage(self):
events = self.example.run()
# check expected types
self.assertTrue(isinstance(events, list))
self.assertTrue(isinstance(events[0], Document))
class TestTemperatureRamp(CommonSampleDataTests, unittest.TestCase):
def setUp(self):
self.example = temperature_ramp
class TestMultisourceEvent(CommonSampleDataTests, unittest.TestCase):
def setUp(self):
self.example = multisource_event
class TestImageAndScalar(CommonSampleDataTests, unittest.TestCase):
def setUp(self):
self.example = image_and_scalar
|
4705eae5d233ea573da3482541fd52778cff88ef | corehq/apps/data_interfaces/migrations/0019_remove_old_rule_models.py | corehq/apps/data_interfaces/migrations/0019_remove_old_rule_models.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-09-11 15:24
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('data_interfaces', '0018_check_for_rule_migration'),
]
operations = [
migrations.RemoveField(
model_name='automaticupdateaction',
name='rule',
),
migrations.RemoveField(
model_name='automaticupdaterulecriteria',
name='rule',
),
migrations.DeleteModel(
name='AutomaticUpdateAction',
),
migrations.DeleteModel(
name='AutomaticUpdateRuleCriteria',
),
]
| Add migration to remove old rule models | Add migration to remove old rule models
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | <INSERT> # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-09-11 15:24
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations
class Migration(migrations.Migration):
<INSERT_END> <INSERT> dependencies = [
('data_interfaces', '0018_check_for_rule_migration'),
]
operations = [
migrations.RemoveField(
model_name='automaticupdateaction',
name='rule',
),
migrations.RemoveField(
model_name='automaticupdaterulecriteria',
name='rule',
),
migrations.DeleteModel(
name='AutomaticUpdateAction',
),
migrations.DeleteModel(
name='AutomaticUpdateRuleCriteria',
),
]
<INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-09-11 15:24
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('data_interfaces', '0018_check_for_rule_migration'),
]
operations = [
migrations.RemoveField(
model_name='automaticupdateaction',
name='rule',
),
migrations.RemoveField(
model_name='automaticupdaterulecriteria',
name='rule',
),
migrations.DeleteModel(
name='AutomaticUpdateAction',
),
migrations.DeleteModel(
name='AutomaticUpdateRuleCriteria',
),
]
| Add migration to remove old rule models
|
|
056bb4adada68d96f127a7610289d874ebe0cf1b | cray_test.py | cray_test.py | # -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest
from yatest import testpost, testpage, testutility, testconfig
if __name__ == '__main__':
all_test_suites = []
all_test_suites.append(testpost.get_test_suites())
all_test_suites.append(testpage.get_test_suites())
all_test_suites.append(testutility.get_test_suites())
all_test_suites.append(testconfig.get_test_suites())
alltests = unittest.TestSuite(all_test_suites)
status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
sys.exit(status)
| # -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest
from yatest import testpost, testpage, testutility, testconfig, testgenerator, testpostmanager
if __name__ == '__main__':
all_test_suites = []
all_test_suites.append(testpost.get_test_suites())
all_test_suites.append(testpage.get_test_suites())
all_test_suites.append(testutility.get_test_suites())
all_test_suites.append(testconfig.get_test_suites())
all_test_suites.append(testgenerator.get_test_suites())
all_test_suites.append(testpostmanager.get_test_suites())
alltests = unittest.TestSuite(all_test_suites)
status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
sys.exit(status)
| Add test cases for module post_manager, refactor part of class PostManager and update TODO list. | Add test cases for module post_manager, refactor part of class PostManager and update TODO list.
| Python | mit | boluny/cray,boluny/cray | <REPLACE_OLD> testconfig
if <REPLACE_NEW> testconfig, testgenerator, testpostmanager
if <REPLACE_END> <REPLACE_OLD> all_test_suites.append(testconfig.get_test_suites())
<REPLACE_NEW> all_test_suites.append(testconfig.get_test_suites())
all_test_suites.append(testgenerator.get_test_suites())
all_test_suites.append(testpostmanager.get_test_suites())
<REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest
from yatest import testpost, testpage, testutility, testconfig, testgenerator, testpostmanager
if __name__ == '__main__':
all_test_suites = []
all_test_suites.append(testpost.get_test_suites())
all_test_suites.append(testpage.get_test_suites())
all_test_suites.append(testutility.get_test_suites())
all_test_suites.append(testconfig.get_test_suites())
all_test_suites.append(testgenerator.get_test_suites())
all_test_suites.append(testpostmanager.get_test_suites())
alltests = unittest.TestSuite(all_test_suites)
status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
sys.exit(status)
| Add test cases for module post_manager, refactor part of class PostManager and update TODO list.
# -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest
from yatest import testpost, testpage, testutility, testconfig
if __name__ == '__main__':
all_test_suites = []
all_test_suites.append(testpost.get_test_suites())
all_test_suites.append(testpage.get_test_suites())
all_test_suites.append(testutility.get_test_suites())
all_test_suites.append(testconfig.get_test_suites())
alltests = unittest.TestSuite(all_test_suites)
status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
sys.exit(status)
|
4c6fb23dd40216604f914d4f869b40d23b13bf73 | django/__init__.py | django/__init__.py | VERSION = (1, 4, 5, 'final', 0)
def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
assert version[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|c}N - for alpha, beta and rc releases
parts = 2 if version[2] == 0 else 3
main = '.'.join(str(x) for x in version[:parts])
sub = ''
if version[3] == 'alpha' and version[4] == 0:
# At the toplevel, this would cause an import loop.
from django.utils.version import get_svn_revision
svn_revision = get_svn_revision()[4:]
if svn_revision != 'unknown':
sub = '.dev%s' % svn_revision
elif version[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[version[3]] + str(version[4])
return main + sub
| VERSION = (1, 4, 6, 'alpha', 0)
def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
assert version[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|c}N - for alpha, beta and rc releases
parts = 2 if version[2] == 0 else 3
main = '.'.join(str(x) for x in version[:parts])
sub = ''
if version[3] == 'alpha' and version[4] == 0:
# At the toplevel, this would cause an import loop.
from django.utils.version import get_svn_revision
svn_revision = get_svn_revision()[4:]
if svn_revision != 'unknown':
sub = '.dev%s' % svn_revision
elif version[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[version[3]] + str(version[4])
return main + sub
| Bump version to no longer claim to be 1.4.5 final. | [1.4.x] Bump version to no longer claim to be 1.4.5 final.
| Python | bsd-3-clause | riklaunim/django-custom-multisite,riklaunim/django-custom-multisite,riklaunim/django-custom-multisite | <REPLACE_OLD> 5, 'final', <REPLACE_NEW> 6, 'alpha', <REPLACE_END> <|endoftext|> VERSION = (1, 4, 6, 'alpha', 0)
def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
assert version[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|c}N - for alpha, beta and rc releases
parts = 2 if version[2] == 0 else 3
main = '.'.join(str(x) for x in version[:parts])
sub = ''
if version[3] == 'alpha' and version[4] == 0:
# At the toplevel, this would cause an import loop.
from django.utils.version import get_svn_revision
svn_revision = get_svn_revision()[4:]
if svn_revision != 'unknown':
sub = '.dev%s' % svn_revision
elif version[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[version[3]] + str(version[4])
return main + sub
| [1.4.x] Bump version to no longer claim to be 1.4.5 final.
VERSION = (1, 4, 5, 'final', 0)
def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
assert version[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|c}N - for alpha, beta and rc releases
parts = 2 if version[2] == 0 else 3
main = '.'.join(str(x) for x in version[:parts])
sub = ''
if version[3] == 'alpha' and version[4] == 0:
# At the toplevel, this would cause an import loop.
from django.utils.version import get_svn_revision
svn_revision = get_svn_revision()[4:]
if svn_revision != 'unknown':
sub = '.dev%s' % svn_revision
elif version[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[version[3]] + str(version[4])
return main + sub
|
57d3b3cf0309222aafbd493cbdc26f30e06f05c1 | tests/test_parsing.py | tests/test_parsing.py | #!/usr/bin/env python
#encoding:utf-8
#author:dbr/Ben
#project:tvnamer
#repository:http://github.com/dbr/tvnamer
#license:Creative Commons GNU GPL v2
# http://creativecommons.org/licenses/GPL/2.0/
"""Test tvnamer's filename parser
"""
import os
import sys
from copy import copy
import unittest
sys.path.append(os.path.join(os.path.abspath(sys.path[0]), ".."))
from utils import FileParser
from test_files import files
def check_test(curtest):
"""Runs test case, used by test_generator
"""
parser = FileParser(curtest['input'])
theep = parser.parse()
assert theep.seriesname.lower() == curtest['seriesname'].lower()
assert theep.seasonnumber == curtest['seasonnumber']
assert theep.episodenumber == curtest['episodenumber']
def test_generator():
"""Generates test for each test case in test_files.py
"""
for category, testcases in files.items():
for testindex, curtest in enumerate(testcases):
cur_tester = lambda x: check_test(x)
cur_tester.description = '%s_%d' % (category, testindex)
yield (cur_tester, curtest)
if __name__ == '__main__':
import nose
nose.main()
| #!/usr/bin/env python
#encoding:utf-8
#author:dbr/Ben
#project:tvnamer
#repository:http://github.com/dbr/tvnamer
#license:Creative Commons GNU GPL v2
# http://creativecommons.org/licenses/GPL/2.0/
"""Test tvnamer's filename parser
"""
import os
import sys
from copy import copy
import unittest
sys.path.append(os.path.join(os.path.abspath(sys.path[0]), ".."))
from utils import FileParser
from test_files import files
def check_case(curtest):
"""Runs test case, used by test_generator
"""
parser = FileParser(curtest['input'])
theep = parser.parse()
assert(theep.seriesname.lower() == curtest['seriesname'].lower(),
"%s == %s" % (theep.seriesname.lower(), curtest['seriesname'].lower()))
assert (theep.seasonnumber == curtest['seasonnumber'],
"%s == %s" % (theep.seasonnumber, curtest['seasonnumber']))
assert (theep.episodenumber == curtest['episodenumber'],
"%s == %s" % (theep.episodenumber, curtest['episodenumber']))
def test_generator():
"""Generates test for each test case in test_files.py
"""
for category, testcases in files.items():
for testindex, curtest in enumerate(testcases):
cur_tester = lambda x: check_case(x)
cur_tester.description = '%s_%d' % (category, testindex)
yield (cur_tester, curtest)
if __name__ == '__main__':
import nose
nose.main()
| Fix utility being picked up as test, display expected-and-got values in assertion error | Fix utility being picked up as test, display expected-and-got values in assertion error | Python | unlicense | m42e/tvnamer,lahwaacz/tvnamer,dbr/tvnamer | <REPLACE_OLD> check_test(curtest):
<REPLACE_NEW> check_case(curtest):
<REPLACE_END> <INSERT> assert(theep.seriesname.lower() == curtest['seriesname'].lower(),
"%s == %s" % (theep.seriesname.lower(), curtest['seriesname'].lower()))
<INSERT_END> <REPLACE_OLD> theep.seriesname.lower() == curtest['seriesname'].lower()
<REPLACE_NEW> (theep.seasonnumber == curtest['seasonnumber'],
"%s == %s" % (theep.seasonnumber, curtest['seasonnumber']))
<REPLACE_END> <REPLACE_OLD> theep.seasonnumber == curtest['seasonnumber']
assert theep.episodenumber == curtest['episodenumber']
def <REPLACE_NEW> (theep.episodenumber == curtest['episodenumber'],
"%s == %s" % (theep.episodenumber, curtest['episodenumber']))
def <REPLACE_END> <REPLACE_OLD> check_test(x)
<REPLACE_NEW> check_case(x)
<REPLACE_END> <|endoftext|> #!/usr/bin/env python
#encoding:utf-8
#author:dbr/Ben
#project:tvnamer
#repository:http://github.com/dbr/tvnamer
#license:Creative Commons GNU GPL v2
# http://creativecommons.org/licenses/GPL/2.0/
"""Test tvnamer's filename parser
"""
import os
import sys
from copy import copy
import unittest
sys.path.append(os.path.join(os.path.abspath(sys.path[0]), ".."))
from utils import FileParser
from test_files import files
def check_case(curtest):
"""Runs test case, used by test_generator
"""
parser = FileParser(curtest['input'])
theep = parser.parse()
assert(theep.seriesname.lower() == curtest['seriesname'].lower(),
"%s == %s" % (theep.seriesname.lower(), curtest['seriesname'].lower()))
assert (theep.seasonnumber == curtest['seasonnumber'],
"%s == %s" % (theep.seasonnumber, curtest['seasonnumber']))
assert (theep.episodenumber == curtest['episodenumber'],
"%s == %s" % (theep.episodenumber, curtest['episodenumber']))
def test_generator():
"""Generates test for each test case in test_files.py
"""
for category, testcases in files.items():
for testindex, curtest in enumerate(testcases):
cur_tester = lambda x: check_case(x)
cur_tester.description = '%s_%d' % (category, testindex)
yield (cur_tester, curtest)
if __name__ == '__main__':
import nose
nose.main()
| Fix utility being picked up as test, display expected-and-got values in assertion error
#!/usr/bin/env python
#encoding:utf-8
#author:dbr/Ben
#project:tvnamer
#repository:http://github.com/dbr/tvnamer
#license:Creative Commons GNU GPL v2
# http://creativecommons.org/licenses/GPL/2.0/
"""Test tvnamer's filename parser
"""
import os
import sys
from copy import copy
import unittest
sys.path.append(os.path.join(os.path.abspath(sys.path[0]), ".."))
from utils import FileParser
from test_files import files
def check_test(curtest):
"""Runs test case, used by test_generator
"""
parser = FileParser(curtest['input'])
theep = parser.parse()
assert theep.seriesname.lower() == curtest['seriesname'].lower()
assert theep.seasonnumber == curtest['seasonnumber']
assert theep.episodenumber == curtest['episodenumber']
def test_generator():
"""Generates test for each test case in test_files.py
"""
for category, testcases in files.items():
for testindex, curtest in enumerate(testcases):
cur_tester = lambda x: check_test(x)
cur_tester.description = '%s_%d' % (category, testindex)
yield (cur_tester, curtest)
if __name__ == '__main__':
import nose
nose.main()
|
119025b231b0f3b9077445334fc08d1ad076abfc | generic_links/migrations/0001_initial.py | generic_links/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='GenericLink',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('object_id', models.PositiveIntegerField(db_index=True)),
('url', models.URLField()),
('title', models.CharField(max_length=200)),
('description', models.TextField(max_length=1000, null=True, blank=True)),
('created_at', models.DateTimeField(auto_now_add=True, db_index=True)),
('is_external', models.BooleanField(default=True, db_index=True)),
('content_type', models.ForeignKey(to='contenttypes.ContentType')),
('user', models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True)),
],
options={
'ordering': ('-created_at',),
'verbose_name': 'Generic Link',
'verbose_name_plural': 'Generic Links',
},
),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '__first__'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='GenericLink',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('object_id', models.PositiveIntegerField(db_index=True)),
('url', models.URLField()),
('title', models.CharField(max_length=200)),
('description', models.TextField(max_length=1000, null=True, blank=True)),
('created_at', models.DateTimeField(auto_now_add=True, db_index=True)),
('is_external', models.BooleanField(default=True, db_index=True)),
('content_type', models.ForeignKey(to='contenttypes.ContentType')),
('user', models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True)),
],
options={
'ordering': ('-created_at',),
'verbose_name': 'Generic Link',
'verbose_name_plural': 'Generic Links',
},
),
]
| Remove Django 1.8 dependency in initial migration | Remove Django 1.8 dependency in initial migration
The ('contenttypes', '0002_remove_content_type_name') migration was part of Django 1.8, replacing it with '__first__' allows the use of Django 1.7 | Python | bsd-3-clause | matagus/django-generic-links,matagus/django-generic-links | <REPLACE_OLD> '0002_remove_content_type_name'),
<REPLACE_NEW> '__first__'),
<REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '__first__'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='GenericLink',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('object_id', models.PositiveIntegerField(db_index=True)),
('url', models.URLField()),
('title', models.CharField(max_length=200)),
('description', models.TextField(max_length=1000, null=True, blank=True)),
('created_at', models.DateTimeField(auto_now_add=True, db_index=True)),
('is_external', models.BooleanField(default=True, db_index=True)),
('content_type', models.ForeignKey(to='contenttypes.ContentType')),
('user', models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True)),
],
options={
'ordering': ('-created_at',),
'verbose_name': 'Generic Link',
'verbose_name_plural': 'Generic Links',
},
),
]
| Remove Django 1.8 dependency in initial migration
The ('contenttypes', '0002_remove_content_type_name') migration was part of Django 1.8, replacing it with '__first__' allows the use of Django 1.7
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='GenericLink',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('object_id', models.PositiveIntegerField(db_index=True)),
('url', models.URLField()),
('title', models.CharField(max_length=200)),
('description', models.TextField(max_length=1000, null=True, blank=True)),
('created_at', models.DateTimeField(auto_now_add=True, db_index=True)),
('is_external', models.BooleanField(default=True, db_index=True)),
('content_type', models.ForeignKey(to='contenttypes.ContentType')),
('user', models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True)),
],
options={
'ordering': ('-created_at',),
'verbose_name': 'Generic Link',
'verbose_name_plural': 'Generic Links',
},
),
]
|
9bf1f19eefc48dbced4b6ea1cc5258518d14bceb | app/utils/http.py | app/utils/http.py | import aiofiles
import aiohttp
import aiohttp.client_exceptions
from aiopath import AsyncPath
from sanic.log import logger
EXCEPTIONS = (
aiohttp.client_exceptions.ClientConnectionError,
aiohttp.client_exceptions.InvalidURL,
aiohttp.client_exceptions.TooManyRedirects,
AssertionError,
UnicodeError,
)
async def download(url: str, path: AsyncPath) -> bool:
async with aiohttp.ClientSession() as session:
try:
async with session.get(url) as response:
if response.status == 200:
f = await aiofiles.open(path, mode="wb") # type: ignore
await f.write(await response.read())
await f.close()
return True
logger.error(f"{response.status} response from {url}")
except EXCEPTIONS as e:
message = str(e).strip("() ")
logger.error(f"Invalid response from {url}: {message}")
return False
| import asyncio
import aiofiles
import aiohttp
import aiohttp.client_exceptions
from aiopath import AsyncPath
from sanic.log import logger
EXCEPTIONS = (
aiohttp.client_exceptions.ClientConnectionError,
aiohttp.client_exceptions.InvalidURL,
aiohttp.client_exceptions.TooManyRedirects,
AssertionError,
asyncio.TimeoutError,
UnicodeError,
)
async def download(url: str, path: AsyncPath) -> bool:
async with aiohttp.ClientSession() as session:
try:
async with session.get(url, timeout=10) as response:
if response.status == 200:
f = await aiofiles.open(path, mode="wb") # type: ignore
await f.write(await response.read())
await f.close()
return True
logger.error(f"{response.status} response from {url}")
except EXCEPTIONS as e:
message = str(e).strip("() ") or e.__class__.__name__
logger.error(f"Invalid response from {url}: {message}")
return False
| Add timeout to downloading custom background images | Add timeout to downloading custom background images
| Python | mit | jacebrowning/memegen,jacebrowning/memegen | <INSERT> asyncio
import <INSERT_END> <INSERT> asyncio.TimeoutError,
<INSERT_END> <REPLACE_OLD> session.get(url) <REPLACE_NEW> session.get(url, timeout=10) <REPLACE_END> <REPLACE_OLD> ")
<REPLACE_NEW> ") or e.__class__.__name__
<REPLACE_END> <|endoftext|> import asyncio
import aiofiles
import aiohttp
import aiohttp.client_exceptions
from aiopath import AsyncPath
from sanic.log import logger
EXCEPTIONS = (
aiohttp.client_exceptions.ClientConnectionError,
aiohttp.client_exceptions.InvalidURL,
aiohttp.client_exceptions.TooManyRedirects,
AssertionError,
asyncio.TimeoutError,
UnicodeError,
)
async def download(url: str, path: AsyncPath) -> bool:
async with aiohttp.ClientSession() as session:
try:
async with session.get(url, timeout=10) as response:
if response.status == 200:
f = await aiofiles.open(path, mode="wb") # type: ignore
await f.write(await response.read())
await f.close()
return True
logger.error(f"{response.status} response from {url}")
except EXCEPTIONS as e:
message = str(e).strip("() ") or e.__class__.__name__
logger.error(f"Invalid response from {url}: {message}")
return False
| Add timeout to downloading custom background images
import aiofiles
import aiohttp
import aiohttp.client_exceptions
from aiopath import AsyncPath
from sanic.log import logger
EXCEPTIONS = (
aiohttp.client_exceptions.ClientConnectionError,
aiohttp.client_exceptions.InvalidURL,
aiohttp.client_exceptions.TooManyRedirects,
AssertionError,
UnicodeError,
)
async def download(url: str, path: AsyncPath) -> bool:
async with aiohttp.ClientSession() as session:
try:
async with session.get(url) as response:
if response.status == 200:
f = await aiofiles.open(path, mode="wb") # type: ignore
await f.write(await response.read())
await f.close()
return True
logger.error(f"{response.status} response from {url}")
except EXCEPTIONS as e:
message = str(e).strip("() ")
logger.error(f"Invalid response from {url}: {message}")
return False
|
06d1039ccbf4653c2f285528b2ab058edca2ff1f | py/test/selenium/webdriver/common/proxy_tests.py | py/test/selenium/webdriver/common/proxy_tests.py | #!/usr/bin/python
# Copyright 2012 Software Freedom Conservancy.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS.
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from selenium.webdriver.common.proxy import Proxy
class ProxyTests(unittest.TestCase):
def testCanAddToDesiredCapabilities(self):
desired_capabilities = {}
proxy = Proxy()
proxy.http_proxy = 'some.url:1234'
proxy.add_to_capabilities(desired_capabilities)
expected_capabilities = {
'proxy': {
'proxyType': 'manual',
'httpProxy': 'some.url:1234'
}
}
self.assertEqual(expected_capabilities, desired_capabilities)
| #!/usr/bin/python
# Copyright 2012 Software Freedom Conservancy.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS.
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from selenium.webdriver.common.proxy import Proxy
class ProxyTests(unittest.TestCase):
def testCanAddToDesiredCapabilities(self):
desired_capabilities = {}
proxy = Proxy()
proxy.http_proxy = 'some.url:1234'
proxy.add_to_capabilities(desired_capabilities)
expected_capabilities = {
'proxy': {
'proxyType': 'MANUAL',
'httpProxy': 'some.url:1234'
}
}
self.assertEqual(expected_capabilities, desired_capabilities)
| Fix test as well :) | DanielWagnerHall: Fix test as well :)
r17825
| Python | apache-2.0 | misttechnologies/selenium,markodolancic/selenium,uchida/selenium,yukaReal/selenium,mestihudson/selenium,alb-i986/selenium,jabbrwcky/selenium,krmahadevan/selenium,jabbrwcky/selenium,AutomatedTester/selenium,s2oBCN/selenium,asolntsev/selenium,twalpole/selenium,o-schneider/selenium,jsakamoto/selenium,compstak/selenium,tkurnosova/selenium,carlosroh/selenium,rovner/selenium,temyers/selenium,thanhpete/selenium,chrisblock/selenium,blueyed/selenium,actmd/selenium,chrisblock/selenium,blackboarddd/selenium,MCGallaspy/selenium,krosenvold/selenium,oddui/selenium,freynaud/selenium,dcjohnson1989/selenium,carlosroh/selenium,5hawnknight/selenium,temyers/selenium,xmhubj/selenium,Herst/selenium,lummyare/lummyare-lummy,pulkitsinghal/selenium,dkentw/selenium,jerome-jacob/selenium,mach6/selenium,SevInf/IEDriver,anshumanchatterji/selenium,zenefits/selenium,asashour/selenium,juangj/selenium,blueyed/selenium,oddui/selenium,alb-i986/selenium,Herst/selenium,oddui/selenium,Ardesco/selenium,Jarob22/selenium,RamaraoDonta/ramarao-clone,aluedeke/chromedriver,lrowe/selenium,krmahadevan/selenium,Jarob22/selenium,valfirst/selenium,Ardesco/selenium,krosenvold/selenium,aluedeke/chromedriver,zenefits/selenium,jsarenik/jajomojo-selenium,AutomatedTester/selenium,krmahadevan/selenium,livioc/selenium,petruc/selenium,TikhomirovSergey/selenium,jknguyen/josephknguyen-selenium,dimacus/selenium,MCGallaspy/selenium,skurochkin/selenium,Appdynamics/selenium,jsakamoto/selenium,lmtierney/selenium,titusfortner/selenium,sevaseva/selenium,joshmgrant/selenium,valfirst/selenium,dibagga/selenium,DrMarcII/selenium,p0deje/selenium,amar-sharma/selenium,dimacus/selenium,jsarenik/jajomojo-selenium,vveliev/selenium,isaksky/selenium,gotcha/selenium,lummyare/lummyare-test,stupidnetizen/selenium,tkurnosova/selenium,temyers/selenium,oddui/selenium,5hawnknight/selenium,yukaReal/selenium,JosephCastro/selenium,arunsingh/selenium,TheBlackTuxCorp/selenium,slongwang/selenium,isaksky/selenium,MeetMe/selenium,asolntsev/selenium,pulkitsinghal/selenium,amikey/selenium,o-schneider/selenium,o-schneider/selenium,jsakamoto/selenium,oddui/selenium,bartolkaruza/selenium,gabrielsimas/selenium,doungni/selenium,wambat/selenium,gotcha/selenium,dandv/selenium,aluedeke/chromedriver,sebady/selenium,GorK-ChO/selenium,amar-sharma/selenium,gorlemik/selenium,xmhubj/selenium,anshumanchatterji/selenium,bmannix/selenium,knorrium/selenium,tarlabs/selenium,aluedeke/chromedriver,rovner/selenium,JosephCastro/selenium,joshbruning/selenium,sri85/selenium,i17c/selenium,Herst/selenium,kalyanjvn1/selenium,bayandin/selenium,juangj/selenium,uchida/selenium,mestihudson/selenium,Dude-X/selenium,AutomatedTester/selenium,carsonmcdonald/selenium,gurayinan/selenium,lukeis/selenium,tbeadle/selenium,jknguyen/josephknguyen-selenium,dimacus/selenium,markodolancic/selenium,pulkitsinghal/selenium,valfirst/selenium,livioc/selenium,customcommander/selenium,xsyntrex/selenium,mestihudson/selenium,markodolancic/selenium,twalpole/selenium,manuelpirez/selenium,isaksky/selenium,kalyanjvn1/selenium,compstak/selenium,dbo/selenium,sankha93/selenium,mach6/selenium,skurochkin/selenium,freynaud/selenium,dandv/selenium,alexec/selenium,alb-i986/selenium,asolntsev/selenium,DrMarcII/selenium,bayandin/selenium,sebady/selenium,chrsmithdemos/selenium,TikhomirovSergey/selenium,sri85/selenium,vveliev/selenium,lummyare/lummyare-lummy,sag-enorman/selenium,doungni/selenium,lilredindy/selenium,Sravyaksr/selenium,freynaud/selenium,anshumanchatterji/selenium,gurayinan/selenium,dimacus/selenium,lmtierney/selenium,telefonicaid/selenium,TikhomirovSergey/selenium,Dude-X/selenium,sag-enorman/selenium,blackboarddd/selenium,orange-tv-blagnac/selenium,chrsmithdemos/selenium,manuelpirez/selenium,oddui/selenium,MCGallaspy/selenium,slongwang/selenium,Jarob22/selenium,asolntsev/selenium,onedox/selenium,arunsingh/selenium,sri85/selenium,lilredindy/selenium,JosephCastro/selenium,Jarob22/selenium,amikey/selenium,TheBlackTuxCorp/selenium,dcjohnson1989/selenium,carlosroh/selenium,clavery/selenium,Ardesco/selenium,bartolkaruza/selenium,p0deje/selenium,vveliev/selenium,AutomatedTester/selenium,denis-vilyuzhanin/selenium-fastview,5hawnknight/selenium,compstak/selenium,asolntsev/selenium,lummyare/lummyare-test,vinay-qa/vinayit-android-server-apk,orange-tv-blagnac/selenium,livioc/selenium,joshmgrant/selenium,carsonmcdonald/selenium,zenefits/selenium,houchj/selenium,carlosroh/selenium,compstak/selenium,manuelpirez/selenium,lummyare/lummyare-test,joshbruning/selenium,aluedeke/chromedriver,minhthuanit/selenium,houchj/selenium,gotcha/selenium,meksh/selenium,AutomatedTester/selenium,compstak/selenium,bartolkaruza/selenium,dibagga/selenium,mach6/selenium,chrsmithdemos/selenium,JosephCastro/selenium,dibagga/selenium,xsyntrex/selenium,mach6/selenium,sevaseva/selenium,anshumanchatterji/selenium,davehunt/selenium,blackboarddd/selenium,vinay-qa/vinayit-android-server-apk,dbo/selenium,onedox/selenium,carlosroh/selenium,tbeadle/selenium,blackboarddd/selenium,SeleniumHQ/selenium,SevInf/IEDriver,xsyntrex/selenium,dimacus/selenium,MCGallaspy/selenium,onedox/selenium,actmd/selenium,BlackSmith/selenium,tkurnosova/selenium,sag-enorman/selenium,stupidnetizen/selenium,meksh/selenium,lummyare/lummyare-lummy,gregerrag/selenium,krmahadevan/selenium,AutomatedTester/selenium,SevInf/IEDriver,sankha93/selenium,s2oBCN/selenium,5hawnknight/selenium,mojwang/selenium,RamaraoDonta/ramarao-clone,s2oBCN/selenium,mojwang/selenium,gabrielsimas/selenium,denis-vilyuzhanin/selenium-fastview,rplevka/selenium,o-schneider/selenium,blueyed/selenium,actmd/selenium,eric-stanley/selenium,joshbruning/selenium,sevaseva/selenium,bmannix/selenium,dcjohnson1989/selenium,davehunt/selenium,dbo/selenium,Appdynamics/selenium,JosephCastro/selenium,xmhubj/selenium,lukeis/selenium,rrussell39/selenium,slongwang/selenium,Dude-X/selenium,dibagga/selenium,MCGallaspy/selenium,TheBlackTuxCorp/selenium,dimacus/selenium,Herst/selenium,i17c/selenium,TheBlackTuxCorp/selenium,kalyanjvn1/selenium,lrowe/selenium,o-schneider/selenium,krmahadevan/selenium,dkentw/selenium,amikey/selenium,chrsmithdemos/selenium,sevaseva/selenium,Sravyaksr/selenium,davehunt/selenium,uchida/selenium,lummyare/lummyare-test,MeetMe/selenium,lilredindy/selenium,5hawnknight/selenium,krosenvold/selenium,gabrielsimas/selenium,stupidnetizen/selenium,manuelpirez/selenium,SouWilliams/selenium,doungni/selenium,amikey/selenium,livioc/selenium,minhthuanit/selenium,BlackSmith/selenium,lrowe/selenium,RamaraoDonta/ramarao-clone,gemini-testing/selenium,lmtierney/selenium,onedox/selenium,Appdynamics/selenium,customcommander/selenium,xsyntrex/selenium,compstak/selenium,zenefits/selenium,titusfortner/selenium,SeleniumHQ/selenium,rovner/selenium,twalpole/selenium,orange-tv-blagnac/selenium,Sravyaksr/selenium,jknguyen/josephknguyen-selenium,SevInf/IEDriver,bartolkaruza/selenium,Dude-X/selenium,onedox/selenium,TikhomirovSergey/selenium,jsakamoto/selenium,p0deje/selenium,meksh/selenium,oddui/selenium,isaksky/selenium,stupidnetizen/selenium,stupidnetizen/selenium,titusfortner/selenium,SeleniumHQ/selenium,vveliev/selenium,dibagga/selenium,joshmgrant/selenium,lilredindy/selenium,mestihudson/selenium,blackboarddd/selenium,lrowe/selenium,tarlabs/selenium,gregerrag/selenium,blueyed/selenium,jabbrwcky/selenium,vveliev/selenium,TheBlackTuxCorp/selenium,lilredindy/selenium,valfirst/selenium,Tom-Trumper/selenium,temyers/selenium,meksh/selenium,freynaud/selenium,TikhomirovSergey/selenium,clavery/selenium,temyers/selenium,sag-enorman/selenium,Appdynamics/selenium,asashour/selenium,SeleniumHQ/selenium,gabrielsimas/selenium,mojwang/selenium,blueyed/selenium,Dude-X/selenium,alb-i986/selenium,SouWilliams/selenium,petruc/selenium,s2oBCN/selenium,bmannix/selenium,davehunt/selenium,lummyare/lummyare-lummy,jerome-jacob/selenium,p0deje/selenium,gabrielsimas/selenium,doungni/selenium,rovner/selenium,oddui/selenium,sri85/selenium,mach6/selenium,onedox/selenium,lmtierney/selenium,vinay-qa/vinayit-android-server-apk,dandv/selenium,TikhomirovSergey/selenium,arunsingh/selenium,valfirst/selenium,rplevka/selenium,lilredindy/selenium,gorlemik/selenium,gorlemik/selenium,rrussell39/selenium,eric-stanley/selenium,gemini-testing/selenium,bayandin/selenium,misttechnologies/selenium,gurayinan/selenium,p0deje/selenium,houchj/selenium,RamaraoDonta/ramarao-clone,tarlabs/selenium,lilredindy/selenium,Herst/selenium,gregerrag/selenium,houchj/selenium,bayandin/selenium,dandv/selenium,SouWilliams/selenium,amikey/selenium,clavery/selenium,chrsmithdemos/selenium,SeleniumHQ/selenium,thanhpete/selenium,xsyntrex/selenium,arunsingh/selenium,Tom-Trumper/selenium,tbeadle/selenium,customcommander/selenium,mach6/selenium,zenefits/selenium,pulkitsinghal/selenium,jsarenik/jajomojo-selenium,mojwang/selenium,carsonmcdonald/selenium,zenefits/selenium,sri85/selenium,dcjohnson1989/selenium,livioc/selenium,Tom-Trumper/selenium,sankha93/selenium,clavery/selenium,kalyanjvn1/selenium,gemini-testing/selenium,xmhubj/selenium,soundcloud/selenium,temyers/selenium,dcjohnson1989/selenium,tarlabs/selenium,DrMarcII/selenium,Jarob22/selenium,eric-stanley/selenium,alexec/selenium,carsonmcdonald/selenium,anshumanchatterji/selenium,quoideneuf/selenium,i17c/selenium,yukaReal/selenium,bmannix/selenium,amar-sharma/selenium,actmd/selenium,bartolkaruza/selenium,gregerrag/selenium,gemini-testing/selenium,Sravyaksr/selenium,mojwang/selenium,krmahadevan/selenium,joshmgrant/selenium,lrowe/selenium,rovner/selenium,blueyed/selenium,asashour/selenium,s2oBCN/selenium,kalyanjvn1/selenium,lummyare/lummyare-lummy,tarlabs/selenium,markodolancic/selenium,chrsmithdemos/selenium,alexec/selenium,minhthuanit/selenium,asashour/selenium,misttechnologies/selenium,titusfortner/selenium,xsyntrex/selenium,i17c/selenium,skurochkin/selenium,manuelpirez/selenium,quoideneuf/selenium,slongwang/selenium,HtmlUnit/selenium,isaksky/selenium,compstak/selenium,BlackSmith/selenium,Appdynamics/selenium,wambat/selenium,tbeadle/selenium,dimacus/selenium,SeleniumHQ/selenium,xmhubj/selenium,DrMarcII/selenium,lrowe/selenium,joshbruning/selenium,joshbruning/selenium,MCGallaspy/selenium,bayandin/selenium,joshmgrant/selenium,bmannix/selenium,JosephCastro/selenium,s2oBCN/selenium,MCGallaspy/selenium,slongwang/selenium,sankha93/selenium,tkurnosova/selenium,isaksky/selenium,juangj/selenium,krmahadevan/selenium,GorK-ChO/selenium,minhthuanit/selenium,joshuaduffy/selenium,rrussell39/selenium,uchida/selenium,chrsmithdemos/selenium,davehunt/selenium,Jarob22/selenium,titusfortner/selenium,rplevka/selenium,Dude-X/selenium,minhthuanit/selenium,lummyare/lummyare-lummy,freynaud/selenium,RamaraoDonta/ramarao-clone,dandv/selenium,Herst/selenium,amar-sharma/selenium,bartolkaruza/selenium,s2oBCN/selenium,o-schneider/selenium,isaksky/selenium,knorrium/selenium,MeetMe/selenium,dibagga/selenium,onedox/selenium,bmannix/selenium,DrMarcII/selenium,alexec/selenium,HtmlUnit/selenium,rovner/selenium,mestihudson/selenium,customcommander/selenium,asashour/selenium,orange-tv-blagnac/selenium,GorK-ChO/selenium,skurochkin/selenium,telefonicaid/selenium,joshbruning/selenium,Sravyaksr/selenium,rplevka/selenium,houchj/selenium,isaksky/selenium,gemini-testing/selenium,vveliev/selenium,gabrielsimas/selenium,titusfortner/selenium,arunsingh/selenium,soundcloud/selenium,knorrium/selenium,rovner/selenium,sri85/selenium,chrisblock/selenium,titusfortner/selenium,blueyed/selenium,quoideneuf/selenium,dcjohnson1989/selenium,mestihudson/selenium,jknguyen/josephknguyen-selenium,jsakamoto/selenium,minhthuanit/selenium,Jarob22/selenium,sri85/selenium,quoideneuf/selenium,slongwang/selenium,rrussell39/selenium,GorK-ChO/selenium,Herst/selenium,Tom-Trumper/selenium,jknguyen/josephknguyen-selenium,dimacus/selenium,kalyanjvn1/selenium,gabrielsimas/selenium,thanhpete/selenium,davehunt/selenium,i17c/selenium,tkurnosova/selenium,BlackSmith/selenium,sankha93/selenium,rplevka/selenium,yukaReal/selenium,i17c/selenium,krosenvold/selenium,alb-i986/selenium,lummyare/lummyare-test,sebady/selenium,thanhpete/selenium,xmhubj/selenium,carsonmcdonald/selenium,DrMarcII/selenium,livioc/selenium,soundcloud/selenium,wambat/selenium,vinay-qa/vinayit-android-server-apk,joshmgrant/selenium,lrowe/selenium,twalpole/selenium,markodolancic/selenium,quoideneuf/selenium,davehunt/selenium,jknguyen/josephknguyen-selenium,gorlemik/selenium,RamaraoDonta/ramarao-clone,jsarenik/jajomojo-selenium,uchida/selenium,pulkitsinghal/selenium,customcommander/selenium,joshuaduffy/selenium,mach6/selenium,dkentw/selenium,krmahadevan/selenium,houchj/selenium,blueyed/selenium,sri85/selenium,eric-stanley/selenium,dcjohnson1989/selenium,SevInf/IEDriver,gotcha/selenium,jsakamoto/selenium,amar-sharma/selenium,gemini-testing/selenium,dandv/selenium,alb-i986/selenium,rrussell39/selenium,knorrium/selenium,lmtierney/selenium,minhthuanit/selenium,anshumanchatterji/selenium,gotcha/selenium,Ardesco/selenium,vveliev/selenium,asashour/selenium,gotcha/selenium,Tom-Trumper/selenium,alexec/selenium,tbeadle/selenium,orange-tv-blagnac/selenium,manuelpirez/selenium,xsyntrex/selenium,soundcloud/selenium,JosephCastro/selenium,i17c/selenium,yukaReal/selenium,jsarenik/jajomojo-selenium,titusfortner/selenium,actmd/selenium,jerome-jacob/selenium,vinay-qa/vinayit-android-server-apk,SeleniumHQ/selenium,jknguyen/josephknguyen-selenium,dcjohnson1989/selenium,sag-enorman/selenium,twalpole/selenium,petruc/selenium,gurayinan/selenium,gurayinan/selenium,HtmlUnit/selenium,livioc/selenium,jabbrwcky/selenium,gregerrag/selenium,TheBlackTuxCorp/selenium,sevaseva/selenium,MeetMe/selenium,lummyare/lummyare-test,HtmlUnit/selenium,juangj/selenium,juangj/selenium,valfirst/selenium,o-schneider/selenium,freynaud/selenium,amar-sharma/selenium,HtmlUnit/selenium,dkentw/selenium,SouWilliams/selenium,tkurnosova/selenium,SeleniumHQ/selenium,Ardesco/selenium,arunsingh/selenium,vveliev/selenium,5hawnknight/selenium,chrsmithdemos/selenium,Appdynamics/selenium,Tom-Trumper/selenium,stupidnetizen/selenium,jerome-jacob/selenium,rrussell39/selenium,gabrielsimas/selenium,minhthuanit/selenium,actmd/selenium,bartolkaruza/selenium,petruc/selenium,mestihudson/selenium,Sravyaksr/selenium,HtmlUnit/selenium,doungni/selenium,gorlemik/selenium,sevaseva/selenium,joshmgrant/selenium,chrisblock/selenium,sankha93/selenium,mojwang/selenium,bmannix/selenium,soundcloud/selenium,DrMarcII/selenium,HtmlUnit/selenium,lmtierney/selenium,dkentw/selenium,joshmgrant/selenium,arunsingh/selenium,meksh/selenium,titusfortner/selenium,pulkitsinghal/selenium,doungni/selenium,skurochkin/selenium,petruc/selenium,dbo/selenium,jsarenik/jajomojo-selenium,gregerrag/selenium,xmhubj/selenium,tbeadle/selenium,Dude-X/selenium,sankha93/selenium,manuelpirez/selenium,joshbruning/selenium,TheBlackTuxCorp/selenium,Appdynamics/selenium,doungni/selenium,jerome-jacob/selenium,asolntsev/selenium,sebady/selenium,5hawnknight/selenium,sri85/selenium,carlosroh/selenium,juangj/selenium,lilredindy/selenium,gorlemik/selenium,DrMarcII/selenium,telefonicaid/selenium,sebady/selenium,i17c/selenium,xsyntrex/selenium,knorrium/selenium,SouWilliams/selenium,juangj/selenium,gurayinan/selenium,chrsmithdemos/selenium,livioc/selenium,sankha93/selenium,bayandin/selenium,jsarenik/jajomojo-selenium,anshumanchatterji/selenium,customcommander/selenium,arunsingh/selenium,tbeadle/selenium,tbeadle/selenium,telefonicaid/selenium,tkurnosova/selenium,orange-tv-blagnac/selenium,xmhubj/selenium,zenefits/selenium,thanhpete/selenium,jabbrwcky/selenium,carlosroh/selenium,misttechnologies/selenium,gorlemik/selenium,lummyare/lummyare-test,markodolancic/selenium,TikhomirovSergey/selenium,eric-stanley/selenium,SouWilliams/selenium,BlackSmith/selenium,sag-enorman/selenium,krosenvold/selenium,rrussell39/selenium,dandv/selenium,Sravyaksr/selenium,joshuaduffy/selenium,aluedeke/chromedriver,gorlemik/selenium,anshumanchatterji/selenium,asolntsev/selenium,GorK-ChO/selenium,chrisblock/selenium,HtmlUnit/selenium,rovner/selenium,valfirst/selenium,slongwang/selenium,Ardesco/selenium,yukaReal/selenium,krosenvold/selenium,gotcha/selenium,MeetMe/selenium,quoideneuf/selenium,compstak/selenium,SevInf/IEDriver,p0deje/selenium,uchida/selenium,gabrielsimas/selenium,blackboarddd/selenium,joshuaduffy/selenium,mojwang/selenium,SeleniumHQ/selenium,p0deje/selenium,dibagga/selenium,compstak/selenium,misttechnologies/selenium,joshbruning/selenium,MCGallaspy/selenium,vinay-qa/vinayit-android-server-apk,rplevka/selenium,carsonmcdonald/selenium,dibagga/selenium,orange-tv-blagnac/selenium,sankha93/selenium,livioc/selenium,GorK-ChO/selenium,clavery/selenium,orange-tv-blagnac/selenium,clavery/selenium,tarlabs/selenium,kalyanjvn1/selenium,mestihudson/selenium,telefonicaid/selenium,tkurnosova/selenium,actmd/selenium,TheBlackTuxCorp/selenium,lilredindy/selenium,dkentw/selenium,denis-vilyuzhanin/selenium-fastview,alexec/selenium,meksh/selenium,clavery/selenium,asashour/selenium,vinay-qa/vinayit-android-server-apk,lmtierney/selenium,o-schneider/selenium,dkentw/selenium,carlosroh/selenium,telefonicaid/selenium,thanhpete/selenium,gurayinan/selenium,5hawnknight/selenium,alb-i986/selenium,jabbrwcky/selenium,arunsingh/selenium,bayandin/selenium,onedox/selenium,dkentw/selenium,petruc/selenium,petruc/selenium,freynaud/selenium,rrussell39/selenium,MCGallaspy/selenium,quoideneuf/selenium,Sravyaksr/selenium,jabbrwcky/selenium,juangj/selenium,Ardesco/selenium,rplevka/selenium,asashour/selenium,GorK-ChO/selenium,jsakamoto/selenium,markodolancic/selenium,joshuaduffy/selenium,pulkitsinghal/selenium,zenefits/selenium,s2oBCN/selenium,anshumanchatterji/selenium,BlackSmith/selenium,misttechnologies/selenium,misttechnologies/selenium,bayandin/selenium,gotcha/selenium,misttechnologies/selenium,mach6/selenium,xmhubj/selenium,chrisblock/selenium,skurochkin/selenium,RamaraoDonta/ramarao-clone,rplevka/selenium,sag-enorman/selenium,lukeis/selenium,meksh/selenium,telefonicaid/selenium,asashour/selenium,sebady/selenium,eric-stanley/selenium,petruc/selenium,Tom-Trumper/selenium,slongwang/selenium,AutomatedTester/selenium,jknguyen/josephknguyen-selenium,yukaReal/selenium,denis-vilyuzhanin/selenium-fastview,sag-enorman/selenium,i17c/selenium,joshmgrant/selenium,thanhpete/selenium,bartolkaruza/selenium,gregerrag/selenium,denis-vilyuzhanin/selenium-fastview,mach6/selenium,SouWilliams/selenium,lukeis/selenium,jsarenik/jajomojo-selenium,Herst/selenium,jabbrwcky/selenium,uchida/selenium,twalpole/selenium,carsonmcdonald/selenium,orange-tv-blagnac/selenium,knorrium/selenium,tkurnosova/selenium,stupidnetizen/selenium,gotcha/selenium,gregerrag/selenium,stupidnetizen/selenium,chrisblock/selenium,alexec/selenium,skurochkin/selenium,asolntsev/selenium,markodolancic/selenium,dbo/selenium,5hawnknight/selenium,telefonicaid/selenium,SeleniumHQ/selenium,davehunt/selenium,wambat/selenium,vinay-qa/vinayit-android-server-apk,alb-i986/selenium,tarlabs/selenium,asolntsev/selenium,amikey/selenium,isaksky/selenium,temyers/selenium,jknguyen/josephknguyen-selenium,jerome-jacob/selenium,dandv/selenium,lummyare/lummyare-lummy,amar-sharma/selenium,twalpole/selenium,houchj/selenium,joshmgrant/selenium,HtmlUnit/selenium,jerome-jacob/selenium,jsakamoto/selenium,Dude-X/selenium,jabbrwcky/selenium,BlackSmith/selenium,sebady/selenium,dibagga/selenium,blueyed/selenium,jsarenik/jajomojo-selenium,Ardesco/selenium,joshuaduffy/selenium,minhthuanit/selenium,pulkitsinghal/selenium,lummyare/lummyare-test,bmannix/selenium,MeetMe/selenium,MeetMe/selenium,soundcloud/selenium,aluedeke/chromedriver,thanhpete/selenium,alb-i986/selenium,gurayinan/selenium,rovner/selenium,lukeis/selenium,dbo/selenium,amikey/selenium,wambat/selenium,denis-vilyuzhanin/selenium-fastview,o-schneider/selenium,juangj/selenium,quoideneuf/selenium,twalpole/selenium,DrMarcII/selenium,vinay-qa/vinayit-android-server-apk,gemini-testing/selenium,SeleniumHQ/selenium,temyers/selenium,actmd/selenium,bartolkaruza/selenium,Appdynamics/selenium,meksh/selenium,alexec/selenium,mojwang/selenium,SouWilliams/selenium,denis-vilyuzhanin/selenium-fastview,lummyare/lummyare-lummy,valfirst/selenium,tarlabs/selenium,wambat/selenium,bayandin/selenium,krmahadevan/selenium,AutomatedTester/selenium,GorK-ChO/selenium,skurochkin/selenium,petruc/selenium,actmd/selenium,titusfortner/selenium,vveliev/selenium,chrisblock/selenium,freynaud/selenium,knorrium/selenium,skurochkin/selenium,dcjohnson1989/selenium,RamaraoDonta/ramarao-clone,sevaseva/selenium,houchj/selenium,gurayinan/selenium,krosenvold/selenium,lummyare/lummyare-lummy,blackboarddd/selenium,freynaud/selenium,TheBlackTuxCorp/selenium,Tom-Trumper/selenium,blackboarddd/selenium,jsakamoto/selenium,Appdynamics/selenium,customcommander/selenium,rrussell39/selenium,lukeis/selenium,kalyanjvn1/selenium,amikey/selenium,manuelpirez/selenium,dandv/selenium,aluedeke/chromedriver,wambat/selenium,RamaraoDonta/ramarao-clone,SevInf/IEDriver,SevInf/IEDriver,dbo/selenium,doungni/selenium,lmtierney/selenium,SouWilliams/selenium,Jarob22/selenium,blackboarddd/selenium,soundcloud/selenium,sebady/selenium,carsonmcdonald/selenium,oddui/selenium,twalpole/selenium,knorrium/selenium,tbeadle/selenium,TikhomirovSergey/selenium,xsyntrex/selenium,p0deje/selenium,meksh/selenium,manuelpirez/selenium,knorrium/selenium,uchida/selenium,aluedeke/chromedriver,sag-enorman/selenium,davehunt/selenium,Tom-Trumper/selenium,lukeis/selenium,eric-stanley/selenium,AutomatedTester/selenium,jerome-jacob/selenium,valfirst/selenium,wambat/selenium,customcommander/selenium,joshuaduffy/selenium,Sravyaksr/selenium,clavery/selenium,Herst/selenium,dbo/selenium,p0deje/selenium,doungni/selenium,dbo/selenium,MeetMe/selenium,lukeis/selenium,clavery/selenium,BlackSmith/selenium,HtmlUnit/selenium,eric-stanley/selenium,joshmgrant/selenium,valfirst/selenium,lrowe/selenium,sevaseva/selenium,valfirst/selenium,joshuaduffy/selenium,customcommander/selenium,soundcloud/selenium,MeetMe/selenium,gregerrag/selenium,temyers/selenium,JosephCastro/selenium,pulkitsinghal/selenium,dkentw/selenium,quoideneuf/selenium,joshbruning/selenium,TikhomirovSergey/selenium,carsonmcdonald/selenium,telefonicaid/selenium,wambat/selenium,yukaReal/selenium,slongwang/selenium,sebady/selenium,stupidnetizen/selenium,eric-stanley/selenium,dimacus/selenium,joshuaduffy/selenium,denis-vilyuzhanin/selenium-fastview,onedox/selenium,amar-sharma/selenium,GorK-ChO/selenium,rplevka/selenium,titusfortner/selenium,soundcloud/selenium,mojwang/selenium,lrowe/selenium,lummyare/lummyare-test,denis-vilyuzhanin/selenium-fastview,krosenvold/selenium,bmannix/selenium,kalyanjvn1/selenium,misttechnologies/selenium,Jarob22/selenium,JosephCastro/selenium,gorlemik/selenium,Ardesco/selenium,thanhpete/selenium,gemini-testing/selenium,carlosroh/selenium,gemini-testing/selenium,lmtierney/selenium,alexec/selenium,BlackSmith/selenium,lukeis/selenium,markodolancic/selenium,houchj/selenium,yukaReal/selenium,jerome-jacob/selenium,krosenvold/selenium,zenefits/selenium,uchida/selenium,amar-sharma/selenium,SevInf/IEDriver,sevaseva/selenium,chrisblock/selenium,amikey/selenium,mestihudson/selenium,tarlabs/selenium,s2oBCN/selenium,Dude-X/selenium | <REPLACE_OLD> 'manual',
<REPLACE_NEW> 'MANUAL',
<REPLACE_END> <|endoftext|> #!/usr/bin/python
# Copyright 2012 Software Freedom Conservancy.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS.
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from selenium.webdriver.common.proxy import Proxy
class ProxyTests(unittest.TestCase):
def testCanAddToDesiredCapabilities(self):
desired_capabilities = {}
proxy = Proxy()
proxy.http_proxy = 'some.url:1234'
proxy.add_to_capabilities(desired_capabilities)
expected_capabilities = {
'proxy': {
'proxyType': 'MANUAL',
'httpProxy': 'some.url:1234'
}
}
self.assertEqual(expected_capabilities, desired_capabilities)
| DanielWagnerHall: Fix test as well :)
r17825
#!/usr/bin/python
# Copyright 2012 Software Freedom Conservancy.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS.
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from selenium.webdriver.common.proxy import Proxy
class ProxyTests(unittest.TestCase):
def testCanAddToDesiredCapabilities(self):
desired_capabilities = {}
proxy = Proxy()
proxy.http_proxy = 'some.url:1234'
proxy.add_to_capabilities(desired_capabilities)
expected_capabilities = {
'proxy': {
'proxyType': 'manual',
'httpProxy': 'some.url:1234'
}
}
self.assertEqual(expected_capabilities, desired_capabilities)
|
ac50044c16e2302e7543923d562cca5ba715e311 | web/impact/impact/v1/events/base_history_event.py | web/impact/impact/v1/events/base_history_event.py | from abc import (
ABCMeta,
abstractmethod,
)
from impact.v1.helpers import (
STRING_FIELD,
)
class BaseHistoryEvent(object):
__metaclass__ = ABCMeta
CLASS_FIELDS = {
"event_type": STRING_FIELD,
"datetime": STRING_FIELD,
"latest_datetime": STRING_FIELD,
"description": STRING_FIELD,
}
def __init__(self):
self.earliest = None
self.latest = None
@classmethod
def all_fields(cls):
result = {}
for base_class in cls.__bases__:
if hasattr(base_class, "all_fields"):
result.update(base_class.all_fields())
if hasattr(cls, "CLASS_FIELDS"):
result.update(cls.CLASS_FIELDS)
return result
@classmethod
def event_type(cls):
return cls.EVENT_TYPE
@abstractmethod
def calc_datetimes(self):
pass # pragma: no cover
def datetime(self):
self._check_date_cache()
return self.earliest
def latest_datetime(self):
self._check_date_cache()
return self.latest
def _check_date_cache(self):
if not self.earliest and hasattr(self, "calc_datetimes"):
self.calc_datetimes()
def description(self):
return None # pragma: no cover
def serialize(self):
result = {}
for key in self.all_fields().keys():
value = getattr(self, key)()
if value is not None:
result[key] = value
return result
| from abc import (
ABCMeta,
abstractmethod,
)
from impact.v1.helpers import (
STRING_FIELD,
)
class BaseHistoryEvent(object):
__metaclass__ = ABCMeta
CLASS_FIELDS = {
"event_type": STRING_FIELD,
"datetime": STRING_FIELD,
"latest_datetime": STRING_FIELD,
"description": STRING_FIELD,
}
def __init__(self):
self.earliest = None
self.latest = None
@classmethod
def all_fields(cls):
result = {}
for base_class in cls.__bases__:
if hasattr(base_class, "all_fields"):
result.update(base_class.all_fields())
if hasattr(cls, "CLASS_FIELDS"):
result.update(cls.CLASS_FIELDS)
return result
@classmethod
def event_type(cls):
return cls.EVENT_TYPE
@abstractmethod
def calc_datetimes(self):
pass # pragma: no cover
def datetime(self):
self._check_date_cache()
return self.earliest
def latest_datetime(self):
self._check_date_cache()
return self.latest
def _check_date_cache(self):
if not self.earliest and hasattr(self, "calc_datetimes"):
self.calc_datetimes()
def description(self):
return None # pragma: no cover
def serialize(self):
result = {}
for key in self.all_fields().keys():
value = getattr(self, key).__call__()
if value is not None:
result[key] = value
return result
| Switch from () to __call__() | [AC-4857] Switch from () to __call__()
| Python | mit | masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api | <REPLACE_OLD> key)()
<REPLACE_NEW> key).__call__()
<REPLACE_END> <|endoftext|> from abc import (
ABCMeta,
abstractmethod,
)
from impact.v1.helpers import (
STRING_FIELD,
)
class BaseHistoryEvent(object):
__metaclass__ = ABCMeta
CLASS_FIELDS = {
"event_type": STRING_FIELD,
"datetime": STRING_FIELD,
"latest_datetime": STRING_FIELD,
"description": STRING_FIELD,
}
def __init__(self):
self.earliest = None
self.latest = None
@classmethod
def all_fields(cls):
result = {}
for base_class in cls.__bases__:
if hasattr(base_class, "all_fields"):
result.update(base_class.all_fields())
if hasattr(cls, "CLASS_FIELDS"):
result.update(cls.CLASS_FIELDS)
return result
@classmethod
def event_type(cls):
return cls.EVENT_TYPE
@abstractmethod
def calc_datetimes(self):
pass # pragma: no cover
def datetime(self):
self._check_date_cache()
return self.earliest
def latest_datetime(self):
self._check_date_cache()
return self.latest
def _check_date_cache(self):
if not self.earliest and hasattr(self, "calc_datetimes"):
self.calc_datetimes()
def description(self):
return None # pragma: no cover
def serialize(self):
result = {}
for key in self.all_fields().keys():
value = getattr(self, key).__call__()
if value is not None:
result[key] = value
return result
| [AC-4857] Switch from () to __call__()
from abc import (
ABCMeta,
abstractmethod,
)
from impact.v1.helpers import (
STRING_FIELD,
)
class BaseHistoryEvent(object):
__metaclass__ = ABCMeta
CLASS_FIELDS = {
"event_type": STRING_FIELD,
"datetime": STRING_FIELD,
"latest_datetime": STRING_FIELD,
"description": STRING_FIELD,
}
def __init__(self):
self.earliest = None
self.latest = None
@classmethod
def all_fields(cls):
result = {}
for base_class in cls.__bases__:
if hasattr(base_class, "all_fields"):
result.update(base_class.all_fields())
if hasattr(cls, "CLASS_FIELDS"):
result.update(cls.CLASS_FIELDS)
return result
@classmethod
def event_type(cls):
return cls.EVENT_TYPE
@abstractmethod
def calc_datetimes(self):
pass # pragma: no cover
def datetime(self):
self._check_date_cache()
return self.earliest
def latest_datetime(self):
self._check_date_cache()
return self.latest
def _check_date_cache(self):
if not self.earliest and hasattr(self, "calc_datetimes"):
self.calc_datetimes()
def description(self):
return None # pragma: no cover
def serialize(self):
result = {}
for key in self.all_fields().keys():
value = getattr(self, key)()
if value is not None:
result[key] = value
return result
|
199caafc817e4e007b2eedd307cb7bff06c029c6 | imagersite/imager_images/tests.py | imagersite/imager_images/tests.py | from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker
from imager_profile.models import ImagerProfile
from .models import Album, Photo
# Create your tests here.
| from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker
from imager_profile.models import ImagerProfile
from .models import Album, Pho
# Create your tests here.
fake = Faker()
class UserFactory(factory.Factory):
"""Create a fake user."""
class Meta:
model = User
username = factory.Sequence(lambda n: 'user{}'.format(n))
first_name = fake.first_name()
last_name = fake.last_name()
email = fake.email()
| Add a UserFactory for images test | Add a UserFactory for images test
| Python | mit | jesseklein406/django-imager,jesseklein406/django-imager,jesseklein406/django-imager | <REPLACE_OLD> Photo
# <REPLACE_NEW> Pho
# <REPLACE_END> <REPLACE_OLD> here.
<REPLACE_NEW> here.
fake = Faker()
class UserFactory(factory.Factory):
"""Create a fake user."""
class Meta:
model = User
username = factory.Sequence(lambda n: 'user{}'.format(n))
first_name = fake.first_name()
last_name = fake.last_name()
email = fake.email()
<REPLACE_END> <|endoftext|> from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker
from imager_profile.models import ImagerProfile
from .models import Album, Pho
# Create your tests here.
fake = Faker()
class UserFactory(factory.Factory):
"""Create a fake user."""
class Meta:
model = User
username = factory.Sequence(lambda n: 'user{}'.format(n))
first_name = fake.first_name()
last_name = fake.last_name()
email = fake.email()
| Add a UserFactory for images test
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker
from imager_profile.models import ImagerProfile
from .models import Album, Photo
# Create your tests here.
|
42c79ec4fb98ee0964a70fa1872b674ec74e0b4e | vumi/scripts/tests/test_db_backup.py | vumi/scripts/tests/test_db_backup.py | """Tests for vumi.scripts.db_backup."""
from twisted.trial.unittest import TestCase
from vumi.tests.utils import PersistenceMixin
from vumi.scripts.db_backup import ConfigHolder, Options
class TestConfigHolder(ConfigHolder):
def __init__(self, *args, **kwargs):
self.output = []
super(TestConfigHolder, self).__init__(*args, **kwargs)
def emit(self, s):
self.output.append(s)
def make_cfg(args):
options = Options()
options.parseOptions(args)
return TestConfigHolder(options)
class DbBackupBaseTestCase(TestCase, PersistenceMixin):
sync_persistence = True
def setUp(self):
self._persist_setUp()
# Make sure we start fresh.
self.get_redis_manager()._purge_all()
def tearDown(self):
return self._persist_tearDown()
class BackupDbCmdTestCase(DbBackupBaseTestCase):
def test_backup_db(self):
cfg = make_cfg(["backup", "db_config.yaml"])
cfg.run()
self.assertEqual(cfg.output, [
'Backing up dbs ...',
])
class RestoreDbCmdTestCase(DbBackupBaseTestCase):
def test_create_pool_range_tags(self):
cfg = make_cfg(["restore", "db_backup.json"])
cfg.run()
self.assertEqual(cfg.output, [
'Restoring dbs ...',
])
| Test skeleton for db backup scripts. | Test skeleton for db backup scripts.
| Python | bsd-3-clause | harrissoerja/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,vishwaprakashmishra/xmatrix,TouK/vumi,vishwaprakashmishra/xmatrix,TouK/vumi,TouK/vumi,harrissoerja/vumi | <REPLACE_OLD> <REPLACE_NEW> """Tests for vumi.scripts.db_backup."""
from twisted.trial.unittest import TestCase
from vumi.tests.utils import PersistenceMixin
from vumi.scripts.db_backup import ConfigHolder, Options
class TestConfigHolder(ConfigHolder):
def __init__(self, *args, **kwargs):
self.output = []
super(TestConfigHolder, self).__init__(*args, **kwargs)
def emit(self, s):
self.output.append(s)
def make_cfg(args):
options = Options()
options.parseOptions(args)
return TestConfigHolder(options)
class DbBackupBaseTestCase(TestCase, PersistenceMixin):
sync_persistence = True
def setUp(self):
self._persist_setUp()
# Make sure we start fresh.
self.get_redis_manager()._purge_all()
def tearDown(self):
return self._persist_tearDown()
class BackupDbCmdTestCase(DbBackupBaseTestCase):
def test_backup_db(self):
cfg = make_cfg(["backup", "db_config.yaml"])
cfg.run()
self.assertEqual(cfg.output, [
'Backing up dbs ...',
])
class RestoreDbCmdTestCase(DbBackupBaseTestCase):
def test_create_pool_range_tags(self):
cfg = make_cfg(["restore", "db_backup.json"])
cfg.run()
self.assertEqual(cfg.output, [
'Restoring dbs ...',
])
<REPLACE_END> <|endoftext|> """Tests for vumi.scripts.db_backup."""
from twisted.trial.unittest import TestCase
from vumi.tests.utils import PersistenceMixin
from vumi.scripts.db_backup import ConfigHolder, Options
class TestConfigHolder(ConfigHolder):
def __init__(self, *args, **kwargs):
self.output = []
super(TestConfigHolder, self).__init__(*args, **kwargs)
def emit(self, s):
self.output.append(s)
def make_cfg(args):
options = Options()
options.parseOptions(args)
return TestConfigHolder(options)
class DbBackupBaseTestCase(TestCase, PersistenceMixin):
sync_persistence = True
def setUp(self):
self._persist_setUp()
# Make sure we start fresh.
self.get_redis_manager()._purge_all()
def tearDown(self):
return self._persist_tearDown()
class BackupDbCmdTestCase(DbBackupBaseTestCase):
def test_backup_db(self):
cfg = make_cfg(["backup", "db_config.yaml"])
cfg.run()
self.assertEqual(cfg.output, [
'Backing up dbs ...',
])
class RestoreDbCmdTestCase(DbBackupBaseTestCase):
def test_create_pool_range_tags(self):
cfg = make_cfg(["restore", "db_backup.json"])
cfg.run()
self.assertEqual(cfg.output, [
'Restoring dbs ...',
])
| Test skeleton for db backup scripts.
|
|
e105b44e4c07b43c36290a8f5d703f4ff0b26953 | sqlshare_rest/util/query_queue.py | sqlshare_rest/util/query_queue.py | from sqlshare_rest.util.db import get_backend
from sqlshare_rest.models import Query
from django.utils import timezone
def process_queue():
filtered = Query.objects.filter(is_finished=False)
try:
oldest_query = filtered.order_by('id')[:1].get()
except Query.DoesNotExist:
return
backend = get_backend()
try:
res = backend.run_query(oldest_query.sql, oldest_query.owner)
except Exception as ex:
oldest_query.has_error = True
oldest_query.error = str(ex)
oldest_query.is_finished = True
oldest_query.date_finished = timezone.now()
print "Finished: ", oldest_query.date_finished
oldest_query.save()
| from sqlshare_rest.util.db import get_backend
from sqlshare_rest.models import Query
from django.utils import timezone
def process_queue():
filtered = Query.objects.filter(is_finished=False)
try:
oldest_query = filtered.order_by('id')[:1].get()
except Query.DoesNotExist:
return
backend = get_backend()
try:
res = backend.run_query(oldest_query.sql, oldest_query.owner)
except Exception as ex:
oldest_query.has_error = True
oldest_query.error = str(ex)
oldest_query.is_finished = True
oldest_query.date_finished = timezone.now()
oldest_query.save()
| Remove a print statement that was dumb and breaking python3 | Remove a print statement that was dumb and breaking python3
| Python | apache-2.0 | uw-it-aca/sqlshare-rest,uw-it-aca/sqlshare-rest,uw-it-aca/sqlshare-rest,uw-it-aca/sqlshare-rest | <DELETE> print "Finished: ", oldest_query.date_finished
<DELETE_END> <|endoftext|> from sqlshare_rest.util.db import get_backend
from sqlshare_rest.models import Query
from django.utils import timezone
def process_queue():
filtered = Query.objects.filter(is_finished=False)
try:
oldest_query = filtered.order_by('id')[:1].get()
except Query.DoesNotExist:
return
backend = get_backend()
try:
res = backend.run_query(oldest_query.sql, oldest_query.owner)
except Exception as ex:
oldest_query.has_error = True
oldest_query.error = str(ex)
oldest_query.is_finished = True
oldest_query.date_finished = timezone.now()
oldest_query.save()
| Remove a print statement that was dumb and breaking python3
from sqlshare_rest.util.db import get_backend
from sqlshare_rest.models import Query
from django.utils import timezone
def process_queue():
filtered = Query.objects.filter(is_finished=False)
try:
oldest_query = filtered.order_by('id')[:1].get()
except Query.DoesNotExist:
return
backend = get_backend()
try:
res = backend.run_query(oldest_query.sql, oldest_query.owner)
except Exception as ex:
oldest_query.has_error = True
oldest_query.error = str(ex)
oldest_query.is_finished = True
oldest_query.date_finished = timezone.now()
print "Finished: ", oldest_query.date_finished
oldest_query.save()
|
ffab86b081357fbd51e0c9676f03f4c39b65658b | emails/models.py | emails/models.py | from django.db import models
from datetime import datetime
import settings
class Email(models.Model):
''' Monitor emails sent '''
to = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='emails')
subject = models.CharField(max_length=150)
body = models.TextField()
at = models.DateTimeField(default=datetime.now)
prefetch = ['to']
def __str__(self):
return 'TO: %s, %s' % (self.to, self.subject)
@models.permalink
def get_absolute_url(self):
if self.body:
return 'email', [self.pk]
return ''
class Meta:
db_table = 'emails'
class UserSubscription(models.Model):
''' Abstract subscription model to subclass.
Add boolean fields to your subclass to make your own subscriptions
named recieve_x; e.g.: receive_newsletter, receive_alerts etc.
This will allow users to subscribe to different types of non-transactional emails.
'''
user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True)
receive_email = models.BooleanField('E-mail', default=True)
def __str__(self):
return str(self.pk)
class Meta:
abstract = True | Add a django model to save emails and specify subscriptions. | Add a django model to save emails and specify subscriptions.
| Python | bsd-3-clause | fmalina/emails,fmalina/emails | <REPLACE_OLD> <REPLACE_NEW> from django.db import models
from datetime import datetime
import settings
class Email(models.Model):
''' Monitor emails sent '''
to = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='emails')
subject = models.CharField(max_length=150)
body = models.TextField()
at = models.DateTimeField(default=datetime.now)
prefetch = ['to']
def __str__(self):
return 'TO: %s, %s' % (self.to, self.subject)
@models.permalink
def get_absolute_url(self):
if self.body:
return 'email', [self.pk]
return ''
class Meta:
db_table = 'emails'
class UserSubscription(models.Model):
''' Abstract subscription model to subclass.
Add boolean fields to your subclass to make your own subscriptions
named recieve_x; e.g.: receive_newsletter, receive_alerts etc.
This will allow users to subscribe to different types of non-transactional emails.
'''
user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True)
receive_email = models.BooleanField('E-mail', default=True)
def __str__(self):
return str(self.pk)
class Meta:
abstract = True <REPLACE_END> <|endoftext|> from django.db import models
from datetime import datetime
import settings
class Email(models.Model):
''' Monitor emails sent '''
to = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='emails')
subject = models.CharField(max_length=150)
body = models.TextField()
at = models.DateTimeField(default=datetime.now)
prefetch = ['to']
def __str__(self):
return 'TO: %s, %s' % (self.to, self.subject)
@models.permalink
def get_absolute_url(self):
if self.body:
return 'email', [self.pk]
return ''
class Meta:
db_table = 'emails'
class UserSubscription(models.Model):
''' Abstract subscription model to subclass.
Add boolean fields to your subclass to make your own subscriptions
named recieve_x; e.g.: receive_newsletter, receive_alerts etc.
This will allow users to subscribe to different types of non-transactional emails.
'''
user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True)
receive_email = models.BooleanField('E-mail', default=True)
def __str__(self):
return str(self.pk)
class Meta:
abstract = True | Add a django model to save emails and specify subscriptions.
|
|
b97842ecf1c8fa22b599353c1c7fe75fcf482702 | tests/test_utils.py | tests/test_utils.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from modeltrans.manager import (split_translated_fieldname,
transform_translatable_fields)
from modeltrans.utils import build_localized_fieldname
from tests.app.models import Blog
class UtilsTest(TestCase):
def test_split_translated_fieldname(self):
self.assertEquals(
split_translated_fieldname('title_nl'),
('title', 'nl')
)
self.assertEquals(
split_translated_fieldname('full_name_nl'),
('full_name', 'nl')
)
def test_transform_translatable_fields(self):
self.assertEquals(
transform_translatable_fields(Blog, {'title': 'bar', 'title_nl': 'foo'}),
{
'i18n': {
'title_nl': 'foo'
},
'title': 'bar'
}
)
def test_build_localized_fieldname(self):
self.assertEquals(
build_localized_fieldname('title', 'nl'),
'title_nl'
)
self.assertEquals(
build_localized_fieldname('category__name', 'nl'),
'category__name_nl'
)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from modeltrans.manager import transform_translatable_fields
from modeltrans.utils import (build_localized_fieldname,
split_translated_fieldname)
from tests.app.models import Blog
class UtilsTest(TestCase):
def test_split_translated_fieldname(self):
self.assertEquals(
split_translated_fieldname('title_nl'),
('title', 'nl')
)
self.assertEquals(
split_translated_fieldname('full_name_nl'),
('full_name', 'nl')
)
def test_transform_translatable_fields(self):
self.assertEquals(
transform_translatable_fields(Blog, {'title': 'bar', 'title_nl': 'foo'}),
{
'i18n': {
'title_nl': 'foo'
},
'title': 'bar'
}
)
def test_build_localized_fieldname(self):
self.assertEquals(
build_localized_fieldname('title', 'nl'),
'title_nl'
)
self.assertEquals(
build_localized_fieldname('category__name', 'nl'),
'category__name_nl'
)
| Use proper import from utils | Use proper import from utils
| Python | bsd-3-clause | zostera/django-modeltrans,zostera/django-modeltrans | <REPLACE_OLD> (split_translated_fieldname,
transform_translatable_fields)
from <REPLACE_NEW> transform_translatable_fields
from <REPLACE_END> <REPLACE_OLD> build_localized_fieldname
from <REPLACE_NEW> (build_localized_fieldname,
split_translated_fieldname)
from <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from modeltrans.manager import transform_translatable_fields
from modeltrans.utils import (build_localized_fieldname,
split_translated_fieldname)
from tests.app.models import Blog
class UtilsTest(TestCase):
def test_split_translated_fieldname(self):
self.assertEquals(
split_translated_fieldname('title_nl'),
('title', 'nl')
)
self.assertEquals(
split_translated_fieldname('full_name_nl'),
('full_name', 'nl')
)
def test_transform_translatable_fields(self):
self.assertEquals(
transform_translatable_fields(Blog, {'title': 'bar', 'title_nl': 'foo'}),
{
'i18n': {
'title_nl': 'foo'
},
'title': 'bar'
}
)
def test_build_localized_fieldname(self):
self.assertEquals(
build_localized_fieldname('title', 'nl'),
'title_nl'
)
self.assertEquals(
build_localized_fieldname('category__name', 'nl'),
'category__name_nl'
)
| Use proper import from utils
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from modeltrans.manager import (split_translated_fieldname,
transform_translatable_fields)
from modeltrans.utils import build_localized_fieldname
from tests.app.models import Blog
class UtilsTest(TestCase):
def test_split_translated_fieldname(self):
self.assertEquals(
split_translated_fieldname('title_nl'),
('title', 'nl')
)
self.assertEquals(
split_translated_fieldname('full_name_nl'),
('full_name', 'nl')
)
def test_transform_translatable_fields(self):
self.assertEquals(
transform_translatable_fields(Blog, {'title': 'bar', 'title_nl': 'foo'}),
{
'i18n': {
'title_nl': 'foo'
},
'title': 'bar'
}
)
def test_build_localized_fieldname(self):
self.assertEquals(
build_localized_fieldname('title', 'nl'),
'title_nl'
)
self.assertEquals(
build_localized_fieldname('category__name', 'nl'),
'category__name_nl'
)
|
e16b2de7dd7c6e0df100bba08d3a7465bbbb4424 | tests/test_service.py | tests/test_service.py | from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization, hashes
import requests
import base64
import unittest
import os
class TestPosieService(unittest.TestCase):
POSIE_URL = os.getenv('POSIE_URL', 'http://127.0.0.1:5000')
key_url = "{}/key".format(POSIE_URL)
import_url = "{}/decrypt".format(POSIE_URL)
public_key = ""
def setUp(self):
# Load public der key from http endpoint
r = requests.get(self.key_url)
key_string = base64.b64decode(r.text)
self.public_key = serialization.load_der_public_key(
key_string,
backend=default_backend()
)
def send_message(self, message):
ciphertext = self.public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None
)
)
# Ask posie to decode message
r = requests.post(self.import_url, data=base64.b64encode(ciphertext))
return r
def test_decrypt_fail_sends_400(self):
# Ask posie to decode message
r = requests.post(self.import_url, data='rubbish')
self.assertEqual(r.status_code, 400)
def test_no_content_sends_400(self):
# Ask posie to decode message
r = requests.post(self.import_url, data='')
self.assertEqual(r.status_code, 400)
def test_decrypts_message(self):
# Encrypt a message with the key
message = b"Some encrypted message"
# Ask posie to decode message
r = self.send_message(message)
# Compare to bytestring version of decrypted data
self.assertEqual(str.encode(r.text), message)
| from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
import base64
import unittest
import sys
import os
sys.path.append(os.path.abspath('../server.py'))
import server
class TestPosieService(unittest.TestCase):
def test_key_generation(self):
# Load public der key from http endpoint
key_string = base64.b64decode(server.key())
public_key = serialization.load_der_public_key(
key_string,
backend=default_backend()
)
self.assertIsNotNone(public_key)
| Remove requests and drop external tests (now in integration) | Remove requests and drop external tests (now in integration)
| Python | mit | ONSdigital/edcdi | <DELETE> cryptography.hazmat.primitives.asymmetric import padding
from <DELETE_END> <REPLACE_OLD> serialization, hashes
import requests
import <REPLACE_NEW> serialization
import <REPLACE_END> <REPLACE_OLD> os
class <REPLACE_NEW> sys
import os
sys.path.append(os.path.abspath('../server.py'))
import server
class <REPLACE_END> <DELETE> POSIE_URL = os.getenv('POSIE_URL', 'http://127.0.0.1:5000')
key_url = "{}/key".format(POSIE_URL)
import_url = "{}/decrypt".format(POSIE_URL)
public_key = ""
<DELETE_END> <REPLACE_OLD> setUp(self):
<REPLACE_NEW> test_key_generation(self):
<REPLACE_END> <REPLACE_OLD> r <REPLACE_NEW> key_string <REPLACE_END> <REPLACE_OLD> requests.get(self.key_url)
<REPLACE_NEW> base64.b64decode(server.key())
<REPLACE_END> <REPLACE_OLD> key_string = base64.b64decode(r.text)
self.public_key <REPLACE_NEW> public_key <REPLACE_END> <DELETE> def send_message(self, message):
<DELETE_END> <REPLACE_OLD> ciphertext = self.public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None
)
)
# Ask posie to decode message
r = requests.post(self.import_url, data=base64.b64encode(ciphertext))
return r
def test_decrypt_fail_sends_400(self):
# Ask posie to decode message
r = requests.post(self.import_url, data='rubbish')
self.assertEqual(r.status_code, 400)
def test_no_content_sends_400(self):
# Ask posie to decode message
r = requests.post(self.import_url, data='')
self.assertEqual(r.status_code, 400)
def test_decrypts_message(self):
# Encrypt a message with the key
message = b"Some encrypted message"
# Ask posie to decode message
r = self.send_message(message)
# Compare to bytestring version of decrypted data
self.assertEqual(str.encode(r.text), message)
<REPLACE_NEW> self.assertIsNotNone(public_key)
<REPLACE_END> <|endoftext|> from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
import base64
import unittest
import sys
import os
sys.path.append(os.path.abspath('../server.py'))
import server
class TestPosieService(unittest.TestCase):
def test_key_generation(self):
# Load public der key from http endpoint
key_string = base64.b64decode(server.key())
public_key = serialization.load_der_public_key(
key_string,
backend=default_backend()
)
self.assertIsNotNone(public_key)
| Remove requests and drop external tests (now in integration)
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization, hashes
import requests
import base64
import unittest
import os
class TestPosieService(unittest.TestCase):
POSIE_URL = os.getenv('POSIE_URL', 'http://127.0.0.1:5000')
key_url = "{}/key".format(POSIE_URL)
import_url = "{}/decrypt".format(POSIE_URL)
public_key = ""
def setUp(self):
# Load public der key from http endpoint
r = requests.get(self.key_url)
key_string = base64.b64decode(r.text)
self.public_key = serialization.load_der_public_key(
key_string,
backend=default_backend()
)
def send_message(self, message):
ciphertext = self.public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None
)
)
# Ask posie to decode message
r = requests.post(self.import_url, data=base64.b64encode(ciphertext))
return r
def test_decrypt_fail_sends_400(self):
# Ask posie to decode message
r = requests.post(self.import_url, data='rubbish')
self.assertEqual(r.status_code, 400)
def test_no_content_sends_400(self):
# Ask posie to decode message
r = requests.post(self.import_url, data='')
self.assertEqual(r.status_code, 400)
def test_decrypts_message(self):
# Encrypt a message with the key
message = b"Some encrypted message"
# Ask posie to decode message
r = self.send_message(message)
# Compare to bytestring version of decrypted data
self.assertEqual(str.encode(r.text), message)
|
18a166e0831cccd0a08f859a3533ed01d810c4ee | binarycalcs.py | binarycalcs.py | import numpy as np
import matplotlib.pyplot as plt
import astropy.units as u
from astropy.constants import G, M_sun, au
from astropy.units.core import UnitConversionError
def keplerian_binary(givenquant):
'''Return equivalency for Keplerian binary orbit.
Parameters
----------
givenquant : `~astropy.units.Quantity`
`astropy.units.Quantity` associated with the parameter of the orbit
that is fixed for this conversion (e.g. to convert between period and
semimajor axis, this should be a mass quanitity).
'''
# Finding a pythonic way to to cycle through the three potential choices
# for givenquant has been difficult. This seems to follow the rule of EAFP
# best. First I will assume that givenquant is a mass, then a semimajor
# axis, then a period.
try:
fixedmass = givenquant.to(u.solMass)
except UnitConversionError:
try:
fixedsemimajor = givenquant.to(u.AU)
except UnitConversionError:
try:
fixedperiod = givenquant.to(u.year).value
except UnitConversionError:
# If it's neither a mass, length, or year, then the wrong
# quantity was given.
raise ValueError(
"The fixed quantity must be either a mass, time interval, "
"or length.")
else:
# givenquant is a time
fromunit = u.solMass
tounit = u.AU
def fromfunction(M):
return (M * fixedperiod**2)**(1/3)
def tofunction(a):
return a**3 / fixedperiod**2
else:
# givenquant is a length
fromunit = u.solMass
tounit = u.year
def fromfunction(M):
return (fixedsemimajor**3 / M)**(1/2)
def tofunction(P):
return fixedsemimajor**3 / P**2
else:
# givenquant is a mass
fromunit = u.year
tounit = u.AU
def fromfunction(P):
return (P**2 * fixedmass)**(1/3)
def tofunction(a):
return (a**3 / fixedmass)**(1/2)
equiv = [
(fromunit, tounit, fromfunction, tofunction)]
return equiv
def calc_velocity_of_binary(masses, period, mass_ratio):
'''Returns the orbital velocity of a binary specified by mass and period.
The masses should be the total mass of the system and the period should be
the orbital period of the system.
'''
vel = ((2 * np.pi * G * masses / period)**(1/3) * mass_ratio /
(1 + mass_ratio))
try:
return vel.to(u.km/u.s)
except u.UnitConversionError as e:
raise TypeError("Arguments should be Astropy Quantities with "
"appropriate units")
| Convert between period, semimajor axis, and total mass for Keplerian orbit. | Convert between period, semimajor axis, and total mass for Keplerian orbit.
For cases where a quick and easy conversion between period and semimajor axis
is needed for some sort of binary system, this function will be able to do the
conversion relatively quickly by taking one aspect to be fixed, and doing the
rest of the conversions through the Astropy Quantitity framework.
What needs to be added now is testing guidelines.
| Python | bsd-3-clause | cactaur/astropy-utils | <REPLACE_OLD> <REPLACE_NEW> import numpy as np
import matplotlib.pyplot as plt
import astropy.units as u
from astropy.constants import G, M_sun, au
from astropy.units.core import UnitConversionError
def keplerian_binary(givenquant):
'''Return equivalency for Keplerian binary orbit.
Parameters
----------
givenquant : `~astropy.units.Quantity`
`astropy.units.Quantity` associated with the parameter of the orbit
that is fixed for this conversion (e.g. to convert between period and
semimajor axis, this should be a mass quanitity).
'''
# Finding a pythonic way to to cycle through the three potential choices
# for givenquant has been difficult. This seems to follow the rule of EAFP
# best. First I will assume that givenquant is a mass, then a semimajor
# axis, then a period.
try:
fixedmass = givenquant.to(u.solMass)
except UnitConversionError:
try:
fixedsemimajor = givenquant.to(u.AU)
except UnitConversionError:
try:
fixedperiod = givenquant.to(u.year).value
except UnitConversionError:
# If it's neither a mass, length, or year, then the wrong
# quantity was given.
raise ValueError(
"The fixed quantity must be either a mass, time interval, "
"or length.")
else:
# givenquant is a time
fromunit = u.solMass
tounit = u.AU
def fromfunction(M):
return (M * fixedperiod**2)**(1/3)
def tofunction(a):
return a**3 / fixedperiod**2
else:
# givenquant is a length
fromunit = u.solMass
tounit = u.year
def fromfunction(M):
return (fixedsemimajor**3 / M)**(1/2)
def tofunction(P):
return fixedsemimajor**3 / P**2
else:
# givenquant is a mass
fromunit = u.year
tounit = u.AU
def fromfunction(P):
return (P**2 * fixedmass)**(1/3)
def tofunction(a):
return (a**3 / fixedmass)**(1/2)
equiv = [
(fromunit, tounit, fromfunction, tofunction)]
return equiv
def calc_velocity_of_binary(masses, period, mass_ratio):
'''Returns the orbital velocity of a binary specified by mass and period.
The masses should be the total mass of the system and the period should be
the orbital period of the system.
'''
vel = ((2 * np.pi * G * masses / period)**(1/3) * mass_ratio /
(1 + mass_ratio))
try:
return vel.to(u.km/u.s)
except u.UnitConversionError as e:
raise TypeError("Arguments should be Astropy Quantities with "
"appropriate units")
<REPLACE_END> <|endoftext|> import numpy as np
import matplotlib.pyplot as plt
import astropy.units as u
from astropy.constants import G, M_sun, au
from astropy.units.core import UnitConversionError
def keplerian_binary(givenquant):
'''Return equivalency for Keplerian binary orbit.
Parameters
----------
givenquant : `~astropy.units.Quantity`
`astropy.units.Quantity` associated with the parameter of the orbit
that is fixed for this conversion (e.g. to convert between period and
semimajor axis, this should be a mass quanitity).
'''
# Finding a pythonic way to to cycle through the three potential choices
# for givenquant has been difficult. This seems to follow the rule of EAFP
# best. First I will assume that givenquant is a mass, then a semimajor
# axis, then a period.
try:
fixedmass = givenquant.to(u.solMass)
except UnitConversionError:
try:
fixedsemimajor = givenquant.to(u.AU)
except UnitConversionError:
try:
fixedperiod = givenquant.to(u.year).value
except UnitConversionError:
# If it's neither a mass, length, or year, then the wrong
# quantity was given.
raise ValueError(
"The fixed quantity must be either a mass, time interval, "
"or length.")
else:
# givenquant is a time
fromunit = u.solMass
tounit = u.AU
def fromfunction(M):
return (M * fixedperiod**2)**(1/3)
def tofunction(a):
return a**3 / fixedperiod**2
else:
# givenquant is a length
fromunit = u.solMass
tounit = u.year
def fromfunction(M):
return (fixedsemimajor**3 / M)**(1/2)
def tofunction(P):
return fixedsemimajor**3 / P**2
else:
# givenquant is a mass
fromunit = u.year
tounit = u.AU
def fromfunction(P):
return (P**2 * fixedmass)**(1/3)
def tofunction(a):
return (a**3 / fixedmass)**(1/2)
equiv = [
(fromunit, tounit, fromfunction, tofunction)]
return equiv
def calc_velocity_of_binary(masses, period, mass_ratio):
'''Returns the orbital velocity of a binary specified by mass and period.
The masses should be the total mass of the system and the period should be
the orbital period of the system.
'''
vel = ((2 * np.pi * G * masses / period)**(1/3) * mass_ratio /
(1 + mass_ratio))
try:
return vel.to(u.km/u.s)
except u.UnitConversionError as e:
raise TypeError("Arguments should be Astropy Quantities with "
"appropriate units")
| Convert between period, semimajor axis, and total mass for Keplerian orbit.
For cases where a quick and easy conversion between period and semimajor axis
is needed for some sort of binary system, this function will be able to do the
conversion relatively quickly by taking one aspect to be fixed, and doing the
rest of the conversions through the Astropy Quantitity framework.
What needs to be added now is testing guidelines.
|
|
e7aa94722c3657fb4b0dfacb4c1e432438e4670a | flexget/tests/test_move.py | flexget/tests/test_move.py | import pytest
@pytest.mark.usefixtures('tmpdir')
class TestMove:
config = """
tasks:
test_move:
mock:
- title: a movie
location: __tmp__/movie.mkv
accept_all: yes
move:
# Take advantage that path validation allows non-existent dirs if they are jinja
to: __tmp__/{{ 'newdir' }}/
"""
@pytest.mark.filecopy('movie.mkv', '__tmp__/movie.mkv')
def test_move(self, execute_task, tmpdir):
assert (tmpdir / 'movie.mkv').exists()
task = execute_task('test_move')
assert not (tmpdir / 'movie.mkv').exists()
assert (tmpdir / 'newdir/movie.mkv').exists()
| Add very basic move plugin test | Add very basic move plugin test
| Python | mit | crawln45/Flexget,ianstalk/Flexget,ianstalk/Flexget,crawln45/Flexget,Flexget/Flexget,malkavi/Flexget,Flexget/Flexget,malkavi/Flexget,ianstalk/Flexget,crawln45/Flexget,malkavi/Flexget,Flexget/Flexget,malkavi/Flexget,crawln45/Flexget,Flexget/Flexget | <INSERT> import pytest
@pytest.mark.usefixtures('tmpdir')
class TestMove:
<INSERT_END> <INSERT> config = """
tasks:
test_move:
mock:
- title: a movie
location: __tmp__/movie.mkv
accept_all: yes
move:
# Take advantage that path validation allows non-existent dirs if they are jinja
to: __tmp__/{{ 'newdir' }}/
"""
@pytest.mark.filecopy('movie.mkv', '__tmp__/movie.mkv')
def test_move(self, execute_task, tmpdir):
assert (tmpdir / 'movie.mkv').exists()
task = execute_task('test_move')
assert not (tmpdir / 'movie.mkv').exists()
assert (tmpdir / 'newdir/movie.mkv').exists()
<INSERT_END> <|endoftext|> import pytest
@pytest.mark.usefixtures('tmpdir')
class TestMove:
config = """
tasks:
test_move:
mock:
- title: a movie
location: __tmp__/movie.mkv
accept_all: yes
move:
# Take advantage that path validation allows non-existent dirs if they are jinja
to: __tmp__/{{ 'newdir' }}/
"""
@pytest.mark.filecopy('movie.mkv', '__tmp__/movie.mkv')
def test_move(self, execute_task, tmpdir):
assert (tmpdir / 'movie.mkv').exists()
task = execute_task('test_move')
assert not (tmpdir / 'movie.mkv').exists()
assert (tmpdir / 'newdir/movie.mkv').exists()
| Add very basic move plugin test
|
|
11d4763b093d0f1006051e892277d33ca273916c | setup.py | setup.py | from setuptools import setup, find_packages
import re
with open("README.rst", mode='r') as readme_file:
text=readme_file.read()
#below version code pulled from requests module
with open('__init__.py', 'r') as fd:
version_number = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
if not version_number:
raise RuntimeError('Cannot find version information')
setup(
name='pyautoupdate',
version=version_number,
packages=find_packages(),
description='Interface to allow python programs to automatically update',
long_description=text,
url='https://github.com/rlee287/pyautoupdate',
install_requires=['requests>=2.6'],
package_data={
'testing':['*.rst']},
license="LGPL 2.1"
)
| from setuptools import setup, find_packages
import re
with open("README.rst", mode='r') as readme_file:
text=readme_file.read()
#below version code pulled from requests module
with open('__init__.py', 'r') as fd:
version_number = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
if not version_number:
raise RuntimeError('Cannot find version information')
setup(
name='pyautoupdate',
version=version_number,
packages=find_packages(),
description='Interface to allow python programs to automatically update',
long_description=text,
url='https://github.com/rlee287/pyautoupdate',
install_requires=['requests'],
extras_require={
'testing': ['pytest','coverage']
},
package_data={
'testing':['*.rst']},
license="LGPL 2.1"
)
| Fix continuation whitespace and add extras_require | Fix continuation whitespace and add extras_require
| Python | lgpl-2.1 | rlee287/pyautoupdate,rlee287/pyautoupdate | <INSERT> <INSERT_END> <REPLACE_OLD> install_requires=['requests>=2.6'],
<REPLACE_NEW> install_requires=['requests'],
extras_require={
'testing': ['pytest','coverage']
},
<REPLACE_END> <|endoftext|> from setuptools import setup, find_packages
import re
with open("README.rst", mode='r') as readme_file:
text=readme_file.read()
#below version code pulled from requests module
with open('__init__.py', 'r') as fd:
version_number = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
if not version_number:
raise RuntimeError('Cannot find version information')
setup(
name='pyautoupdate',
version=version_number,
packages=find_packages(),
description='Interface to allow python programs to automatically update',
long_description=text,
url='https://github.com/rlee287/pyautoupdate',
install_requires=['requests'],
extras_require={
'testing': ['pytest','coverage']
},
package_data={
'testing':['*.rst']},
license="LGPL 2.1"
)
| Fix continuation whitespace and add extras_require
from setuptools import setup, find_packages
import re
with open("README.rst", mode='r') as readme_file:
text=readme_file.read()
#below version code pulled from requests module
with open('__init__.py', 'r') as fd:
version_number = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
if not version_number:
raise RuntimeError('Cannot find version information')
setup(
name='pyautoupdate',
version=version_number,
packages=find_packages(),
description='Interface to allow python programs to automatically update',
long_description=text,
url='https://github.com/rlee287/pyautoupdate',
install_requires=['requests>=2.6'],
package_data={
'testing':['*.rst']},
license="LGPL 2.1"
)
|
e0388a4be8b15964ce87dafcf69805619f273805 | setup.py | setup.py | from setuptools import setup
setup(name='pygraphc',
version='0.0.1',
description='Event log clustering in Python',
long_description='This package contains event log clustering method including non-graph and '
'graph-based approaches.',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Security',
],
keywords='log clustering graph anomaly',
url='http://github.com/studiawan/pygraphc/',
author='Hudan Studiawan',
author_email='[email protected]',
license='MIT',
packages=['pygraphc'],
scripts=['scripts/pygraphc'],
install_requires=[
'networkx',
'numpy',
'scipy',
'scikit-learn',
'nltk',
'Sphinx',
'numpydoc',
'TextBlob',
],
include_package_data=True,
zip_safe=False)
| from setuptools import setup
setup(name='pygraphc',
version='0.0.1',
description='Event log clustering in Python',
long_description='This package contains event log clustering method including non-graph and '
'graph-based approaches.',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Security',
],
keywords='log clustering graph anomaly',
url='http://github.com/studiawan/pygraphc/',
author='Hudan Studiawan',
author_email='[email protected]',
license='MIT',
packages=['pygraphc'],
scripts=['scripts/pygraphc'],
entry_points={
'console_scripts': ['pygraphc=scripts.pygraphc:main']
},
install_requires=[
'networkx',
'scikit-learn',
'nltk',
'Sphinx',
'numpydoc',
'TextBlob',
],
include_package_data=True,
zip_safe=False)
| Add entry_points to run executable pygraphc | Add entry_points to run executable pygraphc
| Python | mit | studiawan/pygraphc | <INSERT> entry_points={
'console_scripts': ['pygraphc=scripts.pygraphc:main']
},
<INSERT_END> <DELETE> 'numpy',
'scipy',
<DELETE_END> <|endoftext|> from setuptools import setup
setup(name='pygraphc',
version='0.0.1',
description='Event log clustering in Python',
long_description='This package contains event log clustering method including non-graph and '
'graph-based approaches.',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Security',
],
keywords='log clustering graph anomaly',
url='http://github.com/studiawan/pygraphc/',
author='Hudan Studiawan',
author_email='[email protected]',
license='MIT',
packages=['pygraphc'],
scripts=['scripts/pygraphc'],
entry_points={
'console_scripts': ['pygraphc=scripts.pygraphc:main']
},
install_requires=[
'networkx',
'scikit-learn',
'nltk',
'Sphinx',
'numpydoc',
'TextBlob',
],
include_package_data=True,
zip_safe=False)
| Add entry_points to run executable pygraphc
from setuptools import setup
setup(name='pygraphc',
version='0.0.1',
description='Event log clustering in Python',
long_description='This package contains event log clustering method including non-graph and '
'graph-based approaches.',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Security',
],
keywords='log clustering graph anomaly',
url='http://github.com/studiawan/pygraphc/',
author='Hudan Studiawan',
author_email='[email protected]',
license='MIT',
packages=['pygraphc'],
scripts=['scripts/pygraphc'],
install_requires=[
'networkx',
'numpy',
'scipy',
'scikit-learn',
'nltk',
'Sphinx',
'numpydoc',
'TextBlob',
],
include_package_data=True,
zip_safe=False)
|
de8d507e64894bdaaf036f99f179637c2660f0f1 | tests/issue0078.py | tests/issue0078.py | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 21 22:09:10 2013
@author: Jeff
"""
import logging
try: print('Logger already instantiated, named: ', logger.name)
except:
# create logger
logger = logging.getLogger()
logger.setLevel(logging.CRITICAL)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(name)s: %(levelname)s - %(message)s')
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(ch)
class foo:
def __init__(self):
self._logger = logging.getLogger(self.__class__.__name__)
self.test()
def test(self):
self._logger.debug('test4_debug')
self._logger.info('test4_info')
self._logger.warning('test4_warning')
self._logger.error('test4_error')
self._logger.critical('test4_critical')
class spam:
def __init__(self):
self._logger = logging.getLogger(self.__class__.__name__)
self.test()
def test(self):
self._logger.debug('test5_debug')
self._logger.info('test5_info')
self._logger.warning('test5_warning')
self._logger.error('test5_error')
self._logger.critical('test5_critical')
if __name__ =="__main__":
y = foo()
x = spam() | Test script show how we might use the Python logger more effectively | Test script show how we might use the Python logger more effectively
Former-commit-id: cc69a6ab3b6c61fd2f3e60bd16085b81cda84e42
Former-commit-id: 28ba0ba57de3379bd99b9f508972cd0520c04fcb | Python | mit | amdouglas/OpenPNM,amdouglas/OpenPNM,stadelmanma/OpenPNM,PMEAL/OpenPNM,TomTranter/OpenPNM | <REPLACE_OLD> <REPLACE_NEW> # -*- coding: utf-8 -*-
"""
Created on Thu Nov 21 22:09:10 2013
@author: Jeff
"""
import logging
try: print('Logger already instantiated, named: ', logger.name)
except:
# create logger
logger = logging.getLogger()
logger.setLevel(logging.CRITICAL)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(name)s: %(levelname)s - %(message)s')
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(ch)
class foo:
def __init__(self):
self._logger = logging.getLogger(self.__class__.__name__)
self.test()
def test(self):
self._logger.debug('test4_debug')
self._logger.info('test4_info')
self._logger.warning('test4_warning')
self._logger.error('test4_error')
self._logger.critical('test4_critical')
class spam:
def __init__(self):
self._logger = logging.getLogger(self.__class__.__name__)
self.test()
def test(self):
self._logger.debug('test5_debug')
self._logger.info('test5_info')
self._logger.warning('test5_warning')
self._logger.error('test5_error')
self._logger.critical('test5_critical')
if __name__ =="__main__":
y = foo()
x = spam() <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
"""
Created on Thu Nov 21 22:09:10 2013
@author: Jeff
"""
import logging
try: print('Logger already instantiated, named: ', logger.name)
except:
# create logger
logger = logging.getLogger()
logger.setLevel(logging.CRITICAL)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(name)s: %(levelname)s - %(message)s')
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(ch)
class foo:
def __init__(self):
self._logger = logging.getLogger(self.__class__.__name__)
self.test()
def test(self):
self._logger.debug('test4_debug')
self._logger.info('test4_info')
self._logger.warning('test4_warning')
self._logger.error('test4_error')
self._logger.critical('test4_critical')
class spam:
def __init__(self):
self._logger = logging.getLogger(self.__class__.__name__)
self.test()
def test(self):
self._logger.debug('test5_debug')
self._logger.info('test5_info')
self._logger.warning('test5_warning')
self._logger.error('test5_error')
self._logger.critical('test5_critical')
if __name__ =="__main__":
y = foo()
x = spam() | Test script show how we might use the Python logger more effectively
Former-commit-id: cc69a6ab3b6c61fd2f3e60bd16085b81cda84e42
Former-commit-id: 28ba0ba57de3379bd99b9f508972cd0520c04fcb
|
|
c02900e7fb8657316fa647f92c4f9ddbcedb2b7c | rma/helpers/formating.py | rma/helpers/formating.py | from math import floor
from collections import Counter
def floored_percentage(val, digits):
"""
Return string of floored value with given digits after period
:param val:
:param digits:
:return:
"""
val *= 10 ** (digits + 2)
return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits)
def pref_encoding(data):
"""
Return string with unique words in list with percentage of they frequency
:param data:
:return str:
"""
encoding_counted = Counter(data)
total = sum(encoding_counted.values())
sorted_encodings = sorted(encoding_counted.items(), key=lambda t: t[1], reverse=True)
return ' / '.join(
["{:<1} [{:<4}]".format(k, floored_percentage(v * 1.0 / total, 1)) for k, v in sorted_encodings])
def make_total_row(source, agg):
"""
Execute agg column based function for source columns. For example if you need `total` in table data:
Examples:
src = [[1,1],[1,2],[1,3]]
print(make_total_row(src, [sum, min]))
>>> [3, 1]
:param source:
:param agg:
:return:
"""
return [agg[index](value) if callable(agg[index]) else agg[index] for index, value in enumerate(zip(*source))]
| from math import floor
from collections import Counter
def floored_percentage(val, digits):
"""
Return string of floored value with given digits after period
:param val:
:param digits:
:return:
"""
val *= 10 ** (digits + 2)
return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits)
def pref_encoding(data, encoding_transform=None):
"""
Return string with unique words in list with percentage of they frequency
:param data:
:param encoding_transform:
:return str:
"""
encoding_counted = Counter(data)
total = sum(encoding_counted.values())
sorted_encodings = sorted(encoding_counted.items(), key=lambda t: t[1], reverse=True)
return ' / '.join(
["{:<1} [{:<4}]".format(encoding_transform(k) if encoding_transform else k, floored_percentage(v * 1.0 / total, 1)) for k, v in sorted_encodings])
def make_total_row(source, agg):
"""
Execute agg column based function for source columns. For example if you need `total` in table data:
Examples:
src = [[1,1],[1,2],[1,3]]
print(make_total_row(src, [sum, min]))
>>> [3, 1]
:param source:
:param agg:
:return:
"""
return [agg[index](value) if callable(agg[index]) else agg[index] for index, value in enumerate(zip(*source))]
| Add transforming function to pref_encodings | Add transforming function to pref_encodings
| Python | mit | gamenet/redis-memory-analyzer | <REPLACE_OLD> pref_encoding(data):
<REPLACE_NEW> pref_encoding(data, encoding_transform=None):
<REPLACE_END> <INSERT> :param encoding_transform:
<INSERT_END> <REPLACE_OLD> [{:<4}]".format(k, <REPLACE_NEW> [{:<4}]".format(encoding_transform(k) if encoding_transform else k, <REPLACE_END> <|endoftext|> from math import floor
from collections import Counter
def floored_percentage(val, digits):
"""
Return string of floored value with given digits after period
:param val:
:param digits:
:return:
"""
val *= 10 ** (digits + 2)
return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits)
def pref_encoding(data, encoding_transform=None):
"""
Return string with unique words in list with percentage of they frequency
:param data:
:param encoding_transform:
:return str:
"""
encoding_counted = Counter(data)
total = sum(encoding_counted.values())
sorted_encodings = sorted(encoding_counted.items(), key=lambda t: t[1], reverse=True)
return ' / '.join(
["{:<1} [{:<4}]".format(encoding_transform(k) if encoding_transform else k, floored_percentage(v * 1.0 / total, 1)) for k, v in sorted_encodings])
def make_total_row(source, agg):
"""
Execute agg column based function for source columns. For example if you need `total` in table data:
Examples:
src = [[1,1],[1,2],[1,3]]
print(make_total_row(src, [sum, min]))
>>> [3, 1]
:param source:
:param agg:
:return:
"""
return [agg[index](value) if callable(agg[index]) else agg[index] for index, value in enumerate(zip(*source))]
| Add transforming function to pref_encodings
from math import floor
from collections import Counter
def floored_percentage(val, digits):
"""
Return string of floored value with given digits after period
:param val:
:param digits:
:return:
"""
val *= 10 ** (digits + 2)
return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits)
def pref_encoding(data):
"""
Return string with unique words in list with percentage of they frequency
:param data:
:return str:
"""
encoding_counted = Counter(data)
total = sum(encoding_counted.values())
sorted_encodings = sorted(encoding_counted.items(), key=lambda t: t[1], reverse=True)
return ' / '.join(
["{:<1} [{:<4}]".format(k, floored_percentage(v * 1.0 / total, 1)) for k, v in sorted_encodings])
def make_total_row(source, agg):
"""
Execute agg column based function for source columns. For example if you need `total` in table data:
Examples:
src = [[1,1],[1,2],[1,3]]
print(make_total_row(src, [sum, min]))
>>> [3, 1]
:param source:
:param agg:
:return:
"""
return [agg[index](value) if callable(agg[index]) else agg[index] for index, value in enumerate(zip(*source))]
|
c0cc820b933913a3d5967d377f557a26ff21dcf7 | tests/test_utils.py | tests/test_utils.py | from io import UnsupportedOperation
from pilkit.exceptions import UnknownFormat, UnknownExtension
from pilkit.utils import extension_to_format, format_to_extension, FileWrapper
from nose.tools import eq_, raises
def test_extension_to_format():
eq_(extension_to_format('.jpeg'), 'JPEG')
eq_(extension_to_format('.rgba'), 'SGI')
def test_format_to_extension_no_init():
eq_(format_to_extension('PNG'), '.png')
eq_(format_to_extension('ICO'), '.ico')
@raises(UnknownFormat)
def test_unknown_format():
format_to_extension('TXT')
@raises(UnknownExtension)
def test_unknown_extension():
extension_to_format('.txt')
def test_default_extension():
"""
Ensure default extensions are honored.
Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common
JPEG extensions, it would normally be the extension we'd get for that
format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which
extensions we'd prefer, and this tests to make sure it's working.
"""
eq_(format_to_extension('JPEG'), '.jpg')
@raises(AttributeError)
def test_filewrapper():
class K(object):
def fileno(self):
raise UnsupportedOperation
FileWrapper(K()).fileno()
| from io import UnsupportedOperation
from pilkit.exceptions import UnknownFormat, UnknownExtension
from pilkit.utils import (extension_to_format, format_to_extension, FileWrapper,
save_image)
from nose.tools import eq_, raises
from tempfile import NamedTemporaryFile
from .utils import create_image
def test_extension_to_format():
eq_(extension_to_format('.jpeg'), 'JPEG')
eq_(extension_to_format('.rgba'), 'SGI')
def test_format_to_extension_no_init():
eq_(format_to_extension('PNG'), '.png')
eq_(format_to_extension('ICO'), '.ico')
@raises(UnknownFormat)
def test_unknown_format():
format_to_extension('TXT')
@raises(UnknownExtension)
def test_unknown_extension():
extension_to_format('.txt')
def test_default_extension():
"""
Ensure default extensions are honored.
Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common
JPEG extensions, it would normally be the extension we'd get for that
format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which
extensions we'd prefer, and this tests to make sure it's working.
"""
eq_(format_to_extension('JPEG'), '.jpg')
@raises(AttributeError)
def test_filewrapper():
class K(object):
def fileno(self):
raise UnsupportedOperation
FileWrapper(K()).fileno()
def test_save_with_filename():
"""
Test that ``save_image`` accepts filename strings (not just file objects).
This is a test for GH-8.
"""
im = create_image()
outfile = NamedTemporaryFile()
save_image(im, outfile.name, 'JPEG')
outfile.close()
| Test that filename string can be used with save_image | Test that filename string can be used with save_image
| Python | bsd-3-clause | kezabelle/pilkit,fladi/pilkit | <REPLACE_OLD> extension_to_format, <REPLACE_NEW> (extension_to_format, <REPLACE_END> <REPLACE_OLD> FileWrapper
from <REPLACE_NEW> FileWrapper,
save_image)
from <REPLACE_END> <REPLACE_OLD> raises
def <REPLACE_NEW> raises
from tempfile import NamedTemporaryFile
from .utils import create_image
def <REPLACE_END> <REPLACE_OLD> FileWrapper(K()).fileno()
<REPLACE_NEW> FileWrapper(K()).fileno()
def test_save_with_filename():
"""
Test that ``save_image`` accepts filename strings (not just file objects).
This is a test for GH-8.
"""
im = create_image()
outfile = NamedTemporaryFile()
save_image(im, outfile.name, 'JPEG')
outfile.close()
<REPLACE_END> <|endoftext|> from io import UnsupportedOperation
from pilkit.exceptions import UnknownFormat, UnknownExtension
from pilkit.utils import (extension_to_format, format_to_extension, FileWrapper,
save_image)
from nose.tools import eq_, raises
from tempfile import NamedTemporaryFile
from .utils import create_image
def test_extension_to_format():
eq_(extension_to_format('.jpeg'), 'JPEG')
eq_(extension_to_format('.rgba'), 'SGI')
def test_format_to_extension_no_init():
eq_(format_to_extension('PNG'), '.png')
eq_(format_to_extension('ICO'), '.ico')
@raises(UnknownFormat)
def test_unknown_format():
format_to_extension('TXT')
@raises(UnknownExtension)
def test_unknown_extension():
extension_to_format('.txt')
def test_default_extension():
"""
Ensure default extensions are honored.
Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common
JPEG extensions, it would normally be the extension we'd get for that
format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which
extensions we'd prefer, and this tests to make sure it's working.
"""
eq_(format_to_extension('JPEG'), '.jpg')
@raises(AttributeError)
def test_filewrapper():
class K(object):
def fileno(self):
raise UnsupportedOperation
FileWrapper(K()).fileno()
def test_save_with_filename():
"""
Test that ``save_image`` accepts filename strings (not just file objects).
This is a test for GH-8.
"""
im = create_image()
outfile = NamedTemporaryFile()
save_image(im, outfile.name, 'JPEG')
outfile.close()
| Test that filename string can be used with save_image
from io import UnsupportedOperation
from pilkit.exceptions import UnknownFormat, UnknownExtension
from pilkit.utils import extension_to_format, format_to_extension, FileWrapper
from nose.tools import eq_, raises
def test_extension_to_format():
eq_(extension_to_format('.jpeg'), 'JPEG')
eq_(extension_to_format('.rgba'), 'SGI')
def test_format_to_extension_no_init():
eq_(format_to_extension('PNG'), '.png')
eq_(format_to_extension('ICO'), '.ico')
@raises(UnknownFormat)
def test_unknown_format():
format_to_extension('TXT')
@raises(UnknownExtension)
def test_unknown_extension():
extension_to_format('.txt')
def test_default_extension():
"""
Ensure default extensions are honored.
Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common
JPEG extensions, it would normally be the extension we'd get for that
format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which
extensions we'd prefer, and this tests to make sure it's working.
"""
eq_(format_to_extension('JPEG'), '.jpg')
@raises(AttributeError)
def test_filewrapper():
class K(object):
def fileno(self):
raise UnsupportedOperation
FileWrapper(K()).fileno()
|
1a3ffe00bfdf8c61b4ff190beb2ee6a4e9db1412 | behave_django/environment.py | behave_django/environment.py | from django.core.management import call_command
from django.shortcuts import resolve_url
from behave_django.testcase import BehaveDjangoTestCase
def before_scenario(context, scenario):
# This is probably a hacky method of setting up the test case
# outside of a test runner. Suggestions are welcome. :)
context.test = BehaveDjangoTestCase()
context.test.setUpClass()
context.test()
# Load fixtures
if getattr(context, 'fixtures', None):
call_command('loaddata', *context.fixtures, verbosity=0)
context.base_url = context.test.live_server_url
def get_url(to=None, *args, **kwargs):
"""
URL helper attached to context with built-in reverse resolution as a
handy shortcut. Takes an absolute path, a view name, or a model
instance as an argument (as django.shortcuts.resolve_url). Examples::
context.get_url()
context.get_url('/absolute/url/here')
context.get_url('view-name')
context.get_url('view-name', 'with args', and='kwargs')
context.get_url(model_instance)
"""
return context.base_url + (
resolve_url(to, *args, **kwargs) if to else '')
context.get_url = get_url
def after_scenario(context, scenario):
context.test.tearDownClass()
del context.test
| from django.core.management import call_command
try:
from django.shortcuts import resolve_url
except ImportError:
import warnings
warnings.warn("URL path supported only in get_url() with Django < 1.5")
resolve_url = lambda to, *args, **kwargs: to
from behave_django.testcase import BehaveDjangoTestCase
def before_scenario(context, scenario):
# This is probably a hacky method of setting up the test case
# outside of a test runner. Suggestions are welcome. :)
context.test = BehaveDjangoTestCase()
context.test.setUpClass()
context.test()
# Load fixtures
if getattr(context, 'fixtures', None):
call_command('loaddata', *context.fixtures, verbosity=0)
context.base_url = context.test.live_server_url
def get_url(to=None, *args, **kwargs):
"""
URL helper attached to context with built-in reverse resolution as a
handy shortcut. Takes an absolute path, a view name, or a model
instance as an argument (as django.shortcuts.resolve_url). Examples::
context.get_url()
context.get_url('/absolute/url/here')
context.get_url('view-name')
context.get_url('view-name', 'with args', and='kwargs')
context.get_url(model_instance)
"""
return context.base_url + (
resolve_url(to, *args, **kwargs) if to else '')
context.get_url = get_url
def after_scenario(context, scenario):
context.test.tearDownClass()
del context.test
| Support Django < 1.5 with a simplified version of `get_url()` | Support Django < 1.5 with a simplified version of `get_url()`
| Python | mit | nikolas/behave-django,nikolas/behave-django,behave/behave-django,bittner/behave-django,bittner/behave-django,behave/behave-django | <REPLACE_OLD> call_command
from <REPLACE_NEW> call_command
try:
from <REPLACE_END> <REPLACE_OLD> resolve_url
from <REPLACE_NEW> resolve_url
except ImportError:
import warnings
warnings.warn("URL path supported only in get_url() with Django < 1.5")
resolve_url = lambda to, *args, **kwargs: to
from <REPLACE_END> <|endoftext|> from django.core.management import call_command
try:
from django.shortcuts import resolve_url
except ImportError:
import warnings
warnings.warn("URL path supported only in get_url() with Django < 1.5")
resolve_url = lambda to, *args, **kwargs: to
from behave_django.testcase import BehaveDjangoTestCase
def before_scenario(context, scenario):
# This is probably a hacky method of setting up the test case
# outside of a test runner. Suggestions are welcome. :)
context.test = BehaveDjangoTestCase()
context.test.setUpClass()
context.test()
# Load fixtures
if getattr(context, 'fixtures', None):
call_command('loaddata', *context.fixtures, verbosity=0)
context.base_url = context.test.live_server_url
def get_url(to=None, *args, **kwargs):
"""
URL helper attached to context with built-in reverse resolution as a
handy shortcut. Takes an absolute path, a view name, or a model
instance as an argument (as django.shortcuts.resolve_url). Examples::
context.get_url()
context.get_url('/absolute/url/here')
context.get_url('view-name')
context.get_url('view-name', 'with args', and='kwargs')
context.get_url(model_instance)
"""
return context.base_url + (
resolve_url(to, *args, **kwargs) if to else '')
context.get_url = get_url
def after_scenario(context, scenario):
context.test.tearDownClass()
del context.test
| Support Django < 1.5 with a simplified version of `get_url()`
from django.core.management import call_command
from django.shortcuts import resolve_url
from behave_django.testcase import BehaveDjangoTestCase
def before_scenario(context, scenario):
# This is probably a hacky method of setting up the test case
# outside of a test runner. Suggestions are welcome. :)
context.test = BehaveDjangoTestCase()
context.test.setUpClass()
context.test()
# Load fixtures
if getattr(context, 'fixtures', None):
call_command('loaddata', *context.fixtures, verbosity=0)
context.base_url = context.test.live_server_url
def get_url(to=None, *args, **kwargs):
"""
URL helper attached to context with built-in reverse resolution as a
handy shortcut. Takes an absolute path, a view name, or a model
instance as an argument (as django.shortcuts.resolve_url). Examples::
context.get_url()
context.get_url('/absolute/url/here')
context.get_url('view-name')
context.get_url('view-name', 'with args', and='kwargs')
context.get_url(model_instance)
"""
return context.base_url + (
resolve_url(to, *args, **kwargs) if to else '')
context.get_url = get_url
def after_scenario(context, scenario):
context.test.tearDownClass()
del context.test
|
041a3bbd512d1800067bc12f522238d681c35ac4 | sheared/web/__init__.py | sheared/web/__init__.py | # vim:nowrap:textwidth=0
#
# Sheared -- non-blocking network programming library for Python
# Copyright (C) 2003 Sune Kirkeby <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
__all__ = ['server', 'subserver', 'querystring', 'virtualhost',
'collection', 'error', 'entwiner', 'xmlrpc', 'resource',
'application']
| # vim:nowrap:textwidth=0
#
# Sheared -- non-blocking network programming library for Python
# Copyright (C) 2003 Sune Kirkeby <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
__all__ = ['server', 'subserver', 'querystring', 'virtualhost',
'collection', 'error', 'entwiner', 'xmlrpc', 'resource',
'application', 'proxy']
| Add proxy module to __all__. | Add proxy module to __all__.
git-svn-id: 8b0eea19d26e20ec80f5c0ea247ec202fbcc1090@248 5646265b-94b7-0310-9681-9501d24b2df7
| Python | mit | kirkeby/sheared | <REPLACE_OLD> 'application']
<REPLACE_NEW> 'application', 'proxy']
<REPLACE_END> <|endoftext|> # vim:nowrap:textwidth=0
#
# Sheared -- non-blocking network programming library for Python
# Copyright (C) 2003 Sune Kirkeby <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
__all__ = ['server', 'subserver', 'querystring', 'virtualhost',
'collection', 'error', 'entwiner', 'xmlrpc', 'resource',
'application', 'proxy']
| Add proxy module to __all__.
git-svn-id: 8b0eea19d26e20ec80f5c0ea247ec202fbcc1090@248 5646265b-94b7-0310-9681-9501d24b2df7
# vim:nowrap:textwidth=0
#
# Sheared -- non-blocking network programming library for Python
# Copyright (C) 2003 Sune Kirkeby <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
__all__ = ['server', 'subserver', 'querystring', 'virtualhost',
'collection', 'error', 'entwiner', 'xmlrpc', 'resource',
'application']
|
c339cf70342df088b920eb42aca4e3094fd96938 | test/test_action.py | test/test_action.py | #!/usr/bin/env python2.6
#
# This file is used to test reading and processing of config files
#
import os
#It's ugly I know....
from shinken_test import *
from shinken.action import Action
class TestConfig(ShinkenTest):
#setUp is in shinken_test
#Change ME :)
def test_action(self):
a = Action()
a.timeout = 10
if os.name == 'nt':
a.command = "./dummy_command.cmd"
else:
a.command = "./dummy_command.sh"
self.assert_(a.got_shell_caracters() == False)
a.execute()
self.assert_(a.status == 'launched')
#Give also the max output we want for the command
for i in xrange(1, 100):
if a.status == 'launched':
a.check_finished(8012)
self.assert_(a.exit_status == 0)
self.assert_(a.status == 'done')
self.assert_(a.output == "Hi, I'm for testing only. Please do not use me directly, really ")
self.assert_(a.perf_data == " Hip=99% Bob=34mm")
if __name__ == '__main__':
unittest.main()
| Add a test for actions. | Add a test for actions.
| Python | agpl-3.0 | staute/shinken_package,xorpaul/shinken,kaji-project/shinken,h4wkmoon/shinken,baloo/shinken,lets-software/shinken,KerkhoffTechnologies/shinken,peeyush-tm/shinken,tal-nino/shinken,naparuba/shinken,staute/shinken_deb,savoirfairelinux/shinken,baloo/shinken,dfranco/shinken,ddurieux/alignak,kaji-project/shinken,h4wkmoon/shinken,geektophe/shinken,staute/shinken_deb,Simage/shinken,naparuba/shinken,fpeyre/shinken,xorpaul/shinken,ddurieux/alignak,KerkhoffTechnologies/shinken,Simage/shinken,claneys/shinken,rednach/krill,mohierf/shinken,KerkhoffTechnologies/shinken,staute/shinken_package,geektophe/shinken,Simage/shinken,geektophe/shinken,dfranco/shinken,baloo/shinken,fpeyre/shinken,fpeyre/shinken,peeyush-tm/shinken,claneys/shinken,h4wkmoon/shinken,peeyush-tm/shinken,Aimage/shinken,rednach/krill,savoirfairelinux/shinken,claneys/shinken,naparuba/shinken,kaji-project/shinken,savoirfairelinux/shinken,KerkhoffTechnologies/shinken,lets-software/shinken,KerkhoffTechnologies/shinken,staute/shinken_package,rledisez/shinken,rledisez/shinken,staute/shinken_deb,kaji-project/shinken,staute/shinken_package,xorpaul/shinken,baloo/shinken,kaji-project/shinken,KerkhoffTechnologies/shinken,rledisez/shinken,naparuba/shinken,mohierf/shinken,peeyush-tm/shinken,lets-software/shinken,ddurieux/alignak,savoirfairelinux/shinken,savoirfairelinux/shinken,Simage/shinken,baloo/shinken,h4wkmoon/shinken,dfranco/shinken,mohierf/shinken,Simage/shinken,h4wkmoon/shinken,titilambert/alignak,xorpaul/shinken,ddurieux/alignak,mohierf/shinken,claneys/shinken,claneys/shinken,Aimage/shinken,naparuba/shinken,titilambert/alignak,staute/shinken_package,fpeyre/shinken,dfranco/shinken,Simage/shinken,rledisez/shinken,rledisez/shinken,claneys/shinken,staute/shinken_deb,baloo/shinken,geektophe/shinken,staute/shinken_deb,staute/shinken_package,gst/alignak,rednach/krill,peeyush-tm/shinken,h4wkmoon/shinken,titilambert/alignak,gst/alignak,rednach/krill,mohierf/shinken,rledisez/shinken,gst/alignak,Aimage/shinken,dfranco/shinken,savoirfairelinux/shinken,lets-software/shinken,kaji-project/shinken,fpeyre/shinken,xorpaul/shinken,staute/shinken_deb,geektophe/shinken,Aimage/shinken,xorpaul/shinken,geektophe/shinken,gst/alignak,ddurieux/alignak,peeyush-tm/shinken,tal-nino/shinken,naparuba/shinken,ddurieux/alignak,mohierf/shinken,xorpaul/shinken,dfranco/shinken,Alignak-monitoring/alignak,titilambert/alignak,Alignak-monitoring/alignak,rednach/krill,h4wkmoon/shinken,tal-nino/shinken,tal-nino/shinken,rednach/krill,tal-nino/shinken,Aimage/shinken,lets-software/shinken,Aimage/shinken,xorpaul/shinken,h4wkmoon/shinken,fpeyre/shinken,lets-software/shinken,kaji-project/shinken,tal-nino/shinken | <REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/env python2.6
#
# This file is used to test reading and processing of config files
#
import os
#It's ugly I know....
from shinken_test import *
from shinken.action import Action
class TestConfig(ShinkenTest):
#setUp is in shinken_test
#Change ME :)
def test_action(self):
a = Action()
a.timeout = 10
if os.name == 'nt':
a.command = "./dummy_command.cmd"
else:
a.command = "./dummy_command.sh"
self.assert_(a.got_shell_caracters() == False)
a.execute()
self.assert_(a.status == 'launched')
#Give also the max output we want for the command
for i in xrange(1, 100):
if a.status == 'launched':
a.check_finished(8012)
self.assert_(a.exit_status == 0)
self.assert_(a.status == 'done')
self.assert_(a.output == "Hi, I'm for testing only. Please do not use me directly, really ")
self.assert_(a.perf_data == " Hip=99% Bob=34mm")
if __name__ == '__main__':
unittest.main()
<REPLACE_END> <|endoftext|> #!/usr/bin/env python2.6
#
# This file is used to test reading and processing of config files
#
import os
#It's ugly I know....
from shinken_test import *
from shinken.action import Action
class TestConfig(ShinkenTest):
#setUp is in shinken_test
#Change ME :)
def test_action(self):
a = Action()
a.timeout = 10
if os.name == 'nt':
a.command = "./dummy_command.cmd"
else:
a.command = "./dummy_command.sh"
self.assert_(a.got_shell_caracters() == False)
a.execute()
self.assert_(a.status == 'launched')
#Give also the max output we want for the command
for i in xrange(1, 100):
if a.status == 'launched':
a.check_finished(8012)
self.assert_(a.exit_status == 0)
self.assert_(a.status == 'done')
self.assert_(a.output == "Hi, I'm for testing only. Please do not use me directly, really ")
self.assert_(a.perf_data == " Hip=99% Bob=34mm")
if __name__ == '__main__':
unittest.main()
| Add a test for actions.
|
|
4bf03eaf81f8d4c28e3b3b89c7442a787361eb5e | scripts/structure_mlsp2013_dataset.py | scripts/structure_mlsp2013_dataset.py | import csv
def test():
with open("CVfolds_2.txt", newline='') as id2set, open("rec_id2filename.txt", newline='') as id2file, open("rec_labels_test_hidden.txt", newline='') as id2label:
with open("file2label.csv", 'w', newline='') as file2label:
readId2Label = csv.reader(id2label)
readId2Set = csv.reader(id2set)
readId2File = csv.reader(id2file)
file2labelwriter = csv.writer(file2label)
id2file = {}
for r in readId2File:
if r[0] == 'rec_id':
print("Reading id to file...")
else:
id2file[r[0]] = r[1]
print("Done reading id to file.")
nb_samples = 0
nb_bird_present = 0
print("Creating file to labels csv...")
for (id2label, id2set) in zip(readId2Label, readId2Set):
if(id2set[0] != id2label[0]):
raise ValueError
iden = id2set[0]
if(id2set[1] == '0'):
nb_samples += 1
if(len(id2label) > 1):
labels = id2label[1:]
nb_bird_present += 1
f = id2file[iden]
file2labelwriter.writerow([f] + labels)
else:
file2labelwriter.writerow([f])
print("Number of training samples: ", nb_samples)
print("Number of training samples with birds present: ", nb_bird_present)
| Add a script which structures the mlsp2013 data | Add a script which structures the mlsp2013 data
- creates a csv file which maps a file name to a label set
| Python | mit | johnmartinsson/bird-species-classification,johnmartinsson/bird-species-classification | <REPLACE_OLD> <REPLACE_NEW> import csv
def test():
with open("CVfolds_2.txt", newline='') as id2set, open("rec_id2filename.txt", newline='') as id2file, open("rec_labels_test_hidden.txt", newline='') as id2label:
with open("file2label.csv", 'w', newline='') as file2label:
readId2Label = csv.reader(id2label)
readId2Set = csv.reader(id2set)
readId2File = csv.reader(id2file)
file2labelwriter = csv.writer(file2label)
id2file = {}
for r in readId2File:
if r[0] == 'rec_id':
print("Reading id to file...")
else:
id2file[r[0]] = r[1]
print("Done reading id to file.")
nb_samples = 0
nb_bird_present = 0
print("Creating file to labels csv...")
for (id2label, id2set) in zip(readId2Label, readId2Set):
if(id2set[0] != id2label[0]):
raise ValueError
iden = id2set[0]
if(id2set[1] == '0'):
nb_samples += 1
if(len(id2label) > 1):
labels = id2label[1:]
nb_bird_present += 1
f = id2file[iden]
file2labelwriter.writerow([f] + labels)
else:
file2labelwriter.writerow([f])
print("Number of training samples: ", nb_samples)
print("Number of training samples with birds present: ", nb_bird_present)
<REPLACE_END> <|endoftext|> import csv
def test():
with open("CVfolds_2.txt", newline='') as id2set, open("rec_id2filename.txt", newline='') as id2file, open("rec_labels_test_hidden.txt", newline='') as id2label:
with open("file2label.csv", 'w', newline='') as file2label:
readId2Label = csv.reader(id2label)
readId2Set = csv.reader(id2set)
readId2File = csv.reader(id2file)
file2labelwriter = csv.writer(file2label)
id2file = {}
for r in readId2File:
if r[0] == 'rec_id':
print("Reading id to file...")
else:
id2file[r[0]] = r[1]
print("Done reading id to file.")
nb_samples = 0
nb_bird_present = 0
print("Creating file to labels csv...")
for (id2label, id2set) in zip(readId2Label, readId2Set):
if(id2set[0] != id2label[0]):
raise ValueError
iden = id2set[0]
if(id2set[1] == '0'):
nb_samples += 1
if(len(id2label) > 1):
labels = id2label[1:]
nb_bird_present += 1
f = id2file[iden]
file2labelwriter.writerow([f] + labels)
else:
file2labelwriter.writerow([f])
print("Number of training samples: ", nb_samples)
print("Number of training samples with birds present: ", nb_bird_present)
| Add a script which structures the mlsp2013 data
- creates a csv file which maps a file name to a label set
|
|
8545faa94a95ddeabffc444bcaf65e764c0c8712 | fresque/lib/__init__.py | fresque/lib/__init__.py | # -*- coding: utf-8 -*-
'''
Internal library for the fresque application.
This module and all its files contains all the operations independant of the
framework and should be completely covered in unit-tests.
'''
import sqlalchemy as sa
import fresque.lib.database as db
| # -*- coding: utf-8 -*-
'''
Internal library for the fresque application.
This module and all its files contains all the operations independant of the
framework and should be completely covered in unit-tests.
'''
import sqlalchemy as sa
import fresque.lib.database as db
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import SQLAlchemyError
def create_session(db_url, debug=False, pool_recycle=3600):
""" Create the Session object to use to query the database.
:arg db_url: URL used to connect to the database. The URL contains
information with regards to the database engine, the host to connect
to, the user and password and the database name.
ie: <engine>://<user>:<password>@<host>/<dbname>
:kwarg debug: a boolean specifying wether we should have the verbose
output of sqlalchemy or not.
:return a Session that can be used to query the database.
"""
engine = sa.create_engine(
db_url,
echo=debug,
pool_recycle=pool_recycle)
scopedsession = scoped_session(sessionmaker(bind=engine))
return scopedsession
| Add method to create a database session in the internal library | Add method to create a database session in the internal library
| Python | agpl-3.0 | fedora-infra/fresque,whitel/fresque,rahulrrixe/fresque,whitel/fresque,fedora-infra/fresque,vivekanand1101/fresque,vivekanand1101/fresque,whitel/fresque,rahulrrixe/fresque,rahulrrixe/fresque,vivekanand1101/fresque,fedora-infra/fresque,fedora-infra/fresque,rahulrrixe/fresque,whitel/fresque,vivekanand1101/fresque | <REPLACE_OLD> db
<REPLACE_NEW> db
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import SQLAlchemyError
def create_session(db_url, debug=False, pool_recycle=3600):
""" Create the Session object to use to query the database.
:arg db_url: URL used to connect to the database. The URL contains
information with regards to the database engine, the host to connect
to, the user and password and the database name.
ie: <engine>://<user>:<password>@<host>/<dbname>
:kwarg debug: a boolean specifying wether we should have the verbose
output of sqlalchemy or not.
:return a Session that can be used to query the database.
"""
engine = sa.create_engine(
db_url,
echo=debug,
pool_recycle=pool_recycle)
scopedsession = scoped_session(sessionmaker(bind=engine))
return scopedsession
<REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
'''
Internal library for the fresque application.
This module and all its files contains all the operations independant of the
framework and should be completely covered in unit-tests.
'''
import sqlalchemy as sa
import fresque.lib.database as db
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import SQLAlchemyError
def create_session(db_url, debug=False, pool_recycle=3600):
""" Create the Session object to use to query the database.
:arg db_url: URL used to connect to the database. The URL contains
information with regards to the database engine, the host to connect
to, the user and password and the database name.
ie: <engine>://<user>:<password>@<host>/<dbname>
:kwarg debug: a boolean specifying wether we should have the verbose
output of sqlalchemy or not.
:return a Session that can be used to query the database.
"""
engine = sa.create_engine(
db_url,
echo=debug,
pool_recycle=pool_recycle)
scopedsession = scoped_session(sessionmaker(bind=engine))
return scopedsession
| Add method to create a database session in the internal library
# -*- coding: utf-8 -*-
'''
Internal library for the fresque application.
This module and all its files contains all the operations independant of the
framework and should be completely covered in unit-tests.
'''
import sqlalchemy as sa
import fresque.lib.database as db
|
850c5c6f133fdfd131605eb1bf1e971b33dd7416 | website/addons/twofactor/tests/test_views.py | website/addons/twofactor/tests/test_views.py | from nose.tools import *
from webtest_plus import TestApp
from tests.base import OsfTestCase
from tests.factories import AuthUserFactory
from website.app import init_app
from website.addons.twofactor.tests import _valid_code
app = init_app(
routes=True,
set_backends=False,
settings_module='website.settings',
)
class TestViews(OsfTestCase):
def setUp(self):
super(TestViews, self).setUp()
self.user = AuthUserFactory()
self.user.add_addon('twofactor')
self.user_settings = self.user.get_addon('twofactor')
self.app = TestApp(app)
def test_confirm_code(self):
# Send a valid code to the API endpoint for the user settings.
res = self.app.post_json(
'/api/v1/settings/twofactor/',
{'code': _valid_code(self.user_settings.totp_secret)},
auth=self.user.auth
)
# reload the user settings object from the DB
self.user_settings.reload()
assert_true(self.user_settings.is_confirmed)
assert_equal(res.status_code, 200)
| from nose.tools import *
from webtest.app import AppError
from webtest_plus import TestApp
from tests.base import OsfTestCase
from tests.factories import AuthUserFactory
from website.app import init_app
from website.addons.twofactor.tests import _valid_code
app = init_app(
routes=True,
set_backends=False,
settings_module='website.settings',
)
class TestViews(OsfTestCase):
def setUp(self):
super(TestViews, self).setUp()
self.user = AuthUserFactory()
self.user.add_addon('twofactor')
self.user_settings = self.user.get_addon('twofactor')
self.app = TestApp(app)
def test_confirm_code(self):
# Send a valid code to the API endpoint for the user settings.
res = self.app.post_json(
'/api/v1/settings/twofactor/',
{'code': _valid_code(self.user_settings.totp_secret)},
auth=self.user.auth
)
# reload the user settings object from the DB
self.user_settings.reload()
assert_true(self.user_settings.is_confirmed)
assert_equal(res.status_code, 200)
def test_confirm_code_failure(self):
with assert_raises(AppError) as error:
res = self.app.post_json(
'/api/v1/settings/twofactor/',
{'code': '000000'},
auth=self.user.auth
)
assert_in('403 FORBIDDEN', error.message)
# reload the user settings object from the DB
self.user_settings.reload()
assert_false(self.user_settings.is_confirmed) | Add test for failure to confirm 2FA code | Add test for failure to confirm 2FA code
| Python | apache-2.0 | doublebits/osf.io,brianjgeiger/osf.io,billyhunt/osf.io,cwisecarver/osf.io,CenterForOpenScience/osf.io,barbour-em/osf.io,wearpants/osf.io,MerlinZhang/osf.io,alexschiller/osf.io,brandonPurvis/osf.io,haoyuchen1992/osf.io,SSJohns/osf.io,HalcyonChimera/osf.io,dplorimer/osf,amyshi188/osf.io,SSJohns/osf.io,chrisseto/osf.io,ticklemepierce/osf.io,mattclark/osf.io,SSJohns/osf.io,amyshi188/osf.io,caneruguz/osf.io,ckc6cz/osf.io,baylee-d/osf.io,hmoco/osf.io,Nesiehr/osf.io,revanthkolli/osf.io,Ghalko/osf.io,caseyrollins/osf.io,Johnetordoff/osf.io,mluo613/osf.io,sloria/osf.io,caseyrygt/osf.io,bdyetton/prettychart,erinspace/osf.io,binoculars/osf.io,himanshuo/osf.io,ZobairAlijan/osf.io,jmcarp/osf.io,reinaH/osf.io,petermalcolm/osf.io,ZobairAlijan/osf.io,binoculars/osf.io,mluke93/osf.io,himanshuo/osf.io,zachjanicki/osf.io,haoyuchen1992/osf.io,cosenal/osf.io,abought/osf.io,hmoco/osf.io,AndrewSallans/osf.io,caseyrollins/osf.io,zamattiac/osf.io,kwierman/osf.io,jolene-esposito/osf.io,cwisecarver/osf.io,MerlinZhang/osf.io,chrisseto/osf.io,revanthkolli/osf.io,rdhyee/osf.io,barbour-em/osf.io,abought/osf.io,acshi/osf.io,lyndsysimon/osf.io,monikagrabowska/osf.io,mluo613/osf.io,arpitar/osf.io,leb2dg/osf.io,SSJohns/osf.io,ZobairAlijan/osf.io,asanfilippo7/osf.io,wearpants/osf.io,monikagrabowska/osf.io,chrisseto/osf.io,erinspace/osf.io,sbt9uc/osf.io,asanfilippo7/osf.io,abought/osf.io,caneruguz/osf.io,icereval/osf.io,felliott/osf.io,KAsante95/osf.io,kch8qx/osf.io,leb2dg/osf.io,samanehsan/osf.io,cldershem/osf.io,asanfilippo7/osf.io,TomHeatwole/osf.io,fabianvf/osf.io,chrisseto/osf.io,brandonPurvis/osf.io,ckc6cz/osf.io,GaryKriebel/osf.io,aaxelb/osf.io,emetsger/osf.io,barbour-em/osf.io,jolene-esposito/osf.io,dplorimer/osf,mfraezz/osf.io,HalcyonChimera/osf.io,rdhyee/osf.io,billyhunt/osf.io,samchrisinger/osf.io,acshi/osf.io,fabianvf/osf.io,samanehsan/osf.io,felliott/osf.io,revanthkolli/osf.io,Nesiehr/osf.io,brandonPurvis/osf.io,monikagrabowska/osf.io,KAsante95/osf.io,MerlinZhang/osf.io,mluo613/osf.io,mfraezz/osf.io,zamattiac/osf.io,emetsger/osf.io,AndrewSallans/osf.io,alexschiller/osf.io,TomBaxter/osf.io,doublebits/osf.io,cosenal/osf.io,crcresearch/osf.io,monikagrabowska/osf.io,aaxelb/osf.io,zkraime/osf.io,erinspace/osf.io,felliott/osf.io,wearpants/osf.io,petermalcolm/osf.io,mluke93/osf.io,himanshuo/osf.io,cosenal/osf.io,ZobairAlijan/osf.io,zkraime/osf.io,jinluyuan/osf.io,rdhyee/osf.io,sloria/osf.io,lamdnhan/osf.io,KAsante95/osf.io,TomHeatwole/osf.io,fabianvf/osf.io,DanielSBrown/osf.io,cslzchen/osf.io,mluo613/osf.io,TomHeatwole/osf.io,HarryRybacki/osf.io,danielneis/osf.io,haoyuchen1992/osf.io,icereval/osf.io,barbour-em/osf.io,aaxelb/osf.io,jolene-esposito/osf.io,alexschiller/osf.io,mattclark/osf.io,kch8qx/osf.io,chennan47/osf.io,Johnetordoff/osf.io,amyshi188/osf.io,samchrisinger/osf.io,pattisdr/osf.io,haoyuchen1992/osf.io,chennan47/osf.io,jinluyuan/osf.io,acshi/osf.io,cwisecarver/osf.io,Ghalko/osf.io,GaryKriebel/osf.io,Johnetordoff/osf.io,adlius/osf.io,acshi/osf.io,DanielSBrown/osf.io,mattclark/osf.io,ticklemepierce/osf.io,GaryKriebel/osf.io,arpitar/osf.io,kwierman/osf.io,wearpants/osf.io,reinaH/osf.io,cwisecarver/osf.io,sbt9uc/osf.io,aaxelb/osf.io,caneruguz/osf.io,adlius/osf.io,amyshi188/osf.io,leb2dg/osf.io,dplorimer/osf,petermalcolm/osf.io,cldershem/osf.io,HarryRybacki/osf.io,cldershem/osf.io,cslzchen/osf.io,sbt9uc/osf.io,binoculars/osf.io,Nesiehr/osf.io,danielneis/osf.io,zkraime/osf.io,baylee-d/osf.io,jeffreyliu3230/osf.io,adlius/osf.io,Johnetordoff/osf.io,MerlinZhang/osf.io,kushG/osf.io,HalcyonChimera/osf.io,jmcarp/osf.io,njantrania/osf.io,GageGaskins/osf.io,laurenrevere/osf.io,mluo613/osf.io,kushG/osf.io,sloria/osf.io,Ghalko/osf.io,ticklemepierce/osf.io,CenterForOpenScience/osf.io,zachjanicki/osf.io,GageGaskins/osf.io,leb2dg/osf.io,lyndsysimon/osf.io,caseyrygt/osf.io,mfraezz/osf.io,GageGaskins/osf.io,njantrania/osf.io,brandonPurvis/osf.io,kwierman/osf.io,GaryKriebel/osf.io,billyhunt/osf.io,GageGaskins/osf.io,HarryRybacki/osf.io,billyhunt/osf.io,fabianvf/osf.io,mluke93/osf.io,hmoco/osf.io,laurenrevere/osf.io,baylee-d/osf.io,cslzchen/osf.io,DanielSBrown/osf.io,jmcarp/osf.io,lyndsysimon/osf.io,lyndsysimon/osf.io,saradbowman/osf.io,zamattiac/osf.io,HalcyonChimera/osf.io,alexschiller/osf.io,TomHeatwole/osf.io,cldershem/osf.io,billyhunt/osf.io,emetsger/osf.io,lamdnhan/osf.io,zamattiac/osf.io,jnayak1/osf.io,danielneis/osf.io,samchrisinger/osf.io,arpitar/osf.io,mluke93/osf.io,RomanZWang/osf.io,acshi/osf.io,doublebits/osf.io,jolene-esposito/osf.io,reinaH/osf.io,zkraime/osf.io,samchrisinger/osf.io,zachjanicki/osf.io,dplorimer/osf,petermalcolm/osf.io,cslzchen/osf.io,bdyetton/prettychart,rdhyee/osf.io,RomanZWang/osf.io,felliott/osf.io,brianjgeiger/osf.io,caseyrollins/osf.io,CenterForOpenScience/osf.io,bdyetton/prettychart,lamdnhan/osf.io,mfraezz/osf.io,jinluyuan/osf.io,reinaH/osf.io,samanehsan/osf.io,chennan47/osf.io,zachjanicki/osf.io,laurenrevere/osf.io,HarryRybacki/osf.io,kushG/osf.io,crcresearch/osf.io,adlius/osf.io,brianjgeiger/osf.io,lamdnhan/osf.io,jnayak1/osf.io,arpitar/osf.io,pattisdr/osf.io,GageGaskins/osf.io,alexschiller/osf.io,ticklemepierce/osf.io,TomBaxter/osf.io,revanthkolli/osf.io,cosenal/osf.io,DanielSBrown/osf.io,hmoco/osf.io,jeffreyliu3230/osf.io,asanfilippo7/osf.io,TomBaxter/osf.io,jeffreyliu3230/osf.io,bdyetton/prettychart,jnayak1/osf.io,crcresearch/osf.io,ckc6cz/osf.io,kch8qx/osf.io,pattisdr/osf.io,himanshuo/osf.io,RomanZWang/osf.io,jinluyuan/osf.io,njantrania/osf.io,brianjgeiger/osf.io,ckc6cz/osf.io,kushG/osf.io,njantrania/osf.io,danielneis/osf.io,Nesiehr/osf.io,RomanZWang/osf.io,monikagrabowska/osf.io,caseyrygt/osf.io,doublebits/osf.io,jnayak1/osf.io,brandonPurvis/osf.io,doublebits/osf.io,Ghalko/osf.io,samanehsan/osf.io,kwierman/osf.io,caneruguz/osf.io,RomanZWang/osf.io,saradbowman/osf.io,emetsger/osf.io,sbt9uc/osf.io,CenterForOpenScience/osf.io,caseyrygt/osf.io,jmcarp/osf.io,kch8qx/osf.io,abought/osf.io,KAsante95/osf.io,kch8qx/osf.io,icereval/osf.io,KAsante95/osf.io,jeffreyliu3230/osf.io | <INSERT> webtest.app import AppError
from <INSERT_END> <REPLACE_OLD> 200)
<REPLACE_NEW> 200)
def test_confirm_code_failure(self):
with assert_raises(AppError) as error:
res = self.app.post_json(
'/api/v1/settings/twofactor/',
{'code': '000000'},
auth=self.user.auth
)
assert_in('403 FORBIDDEN', error.message)
# reload the user settings object from the DB
self.user_settings.reload()
assert_false(self.user_settings.is_confirmed) <REPLACE_END> <|endoftext|> from nose.tools import *
from webtest.app import AppError
from webtest_plus import TestApp
from tests.base import OsfTestCase
from tests.factories import AuthUserFactory
from website.app import init_app
from website.addons.twofactor.tests import _valid_code
app = init_app(
routes=True,
set_backends=False,
settings_module='website.settings',
)
class TestViews(OsfTestCase):
def setUp(self):
super(TestViews, self).setUp()
self.user = AuthUserFactory()
self.user.add_addon('twofactor')
self.user_settings = self.user.get_addon('twofactor')
self.app = TestApp(app)
def test_confirm_code(self):
# Send a valid code to the API endpoint for the user settings.
res = self.app.post_json(
'/api/v1/settings/twofactor/',
{'code': _valid_code(self.user_settings.totp_secret)},
auth=self.user.auth
)
# reload the user settings object from the DB
self.user_settings.reload()
assert_true(self.user_settings.is_confirmed)
assert_equal(res.status_code, 200)
def test_confirm_code_failure(self):
with assert_raises(AppError) as error:
res = self.app.post_json(
'/api/v1/settings/twofactor/',
{'code': '000000'},
auth=self.user.auth
)
assert_in('403 FORBIDDEN', error.message)
# reload the user settings object from the DB
self.user_settings.reload()
assert_false(self.user_settings.is_confirmed) | Add test for failure to confirm 2FA code
from nose.tools import *
from webtest_plus import TestApp
from tests.base import OsfTestCase
from tests.factories import AuthUserFactory
from website.app import init_app
from website.addons.twofactor.tests import _valid_code
app = init_app(
routes=True,
set_backends=False,
settings_module='website.settings',
)
class TestViews(OsfTestCase):
def setUp(self):
super(TestViews, self).setUp()
self.user = AuthUserFactory()
self.user.add_addon('twofactor')
self.user_settings = self.user.get_addon('twofactor')
self.app = TestApp(app)
def test_confirm_code(self):
# Send a valid code to the API endpoint for the user settings.
res = self.app.post_json(
'/api/v1/settings/twofactor/',
{'code': _valid_code(self.user_settings.totp_secret)},
auth=self.user.auth
)
# reload the user settings object from the DB
self.user_settings.reload()
assert_true(self.user_settings.is_confirmed)
assert_equal(res.status_code, 200)
|
9a58d241e61301b9390b17e391e4b65a3ea85071 | squadron/libraries/apt/__init__.py | squadron/libraries/apt/__init__.py | import os
import subprocess
from string import find
def run_command(command):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return out,err
def schema():
"""
This returns
"""
return { 'title': 'apt schema',
'type': 'string'
}
def verify(inputhashes):
"""
"""
failed = []
for package in inputhashes:
out = run_command(['dpkg-query', '-W', package])[0]
#We expect the output to contain the version
#Any error doesn't get captured, so out will be empty (yes this is weird)
if(find(out, package) == -1):
failed.append(package)
return failed
def apply(inputhashes, dry_run=True):
failed = []
for package in inputhashes:
out = run_command(['apt-get', 'install', '-y', package])
if(find(out[1], 'Permission denied') != -1):
failed.append(package) #Install failed because we're not root
if(find(out[0], ('Setting up ' + package)) != -1 and find(out[0], (package + ' already the newest version')) != -1):
#Something else happened, we weren't installed and we didn't get installed
failed.append(package)
print out
return failed
| import os
import subprocess
from string import find
def run_command(command):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return out,err
def schema():
"""
This returns
"""
return { 'title': 'apt schema',
'type': 'string'
}
def verify(inputhashes):
"""
"""
failed = []
for package in inputhashes:
out = run_command(['dpkg-query', '-W', package])[0]
#We expect the output to contain the version
#Any error doesn't get captured, so out will be empty (yes this is weird)
if(find(out, package) == -1):
failed.append(package)
return failed
def apply(inputhashes, dry_run=True):
failed = []
for package in inputhashes:
out = run_command(['apt-get', 'install', '-y', package])
if(find(out[1], 'Permission denied') != -1):
failed.append(package) # Install failed because we're not root
if(find(out[0], ('Setting up ' + package)) != -1 and find(out[0], (package + ' already the newest version')) != -1):
# Something else happened, we weren't installed and we didn't get installed
failed.append(package)
return failed
| Remove extra print in apt | Remove extra print in apt
| Python | mit | gosquadron/squadron,gosquadron/squadron | <REPLACE_OLD> #Install <REPLACE_NEW> # Install <REPLACE_END> <REPLACE_OLD> #Something <REPLACE_NEW> # Something <REPLACE_END> <DELETE> print out
<DELETE_END> <|endoftext|> import os
import subprocess
from string import find
def run_command(command):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return out,err
def schema():
"""
This returns
"""
return { 'title': 'apt schema',
'type': 'string'
}
def verify(inputhashes):
"""
"""
failed = []
for package in inputhashes:
out = run_command(['dpkg-query', '-W', package])[0]
#We expect the output to contain the version
#Any error doesn't get captured, so out will be empty (yes this is weird)
if(find(out, package) == -1):
failed.append(package)
return failed
def apply(inputhashes, dry_run=True):
failed = []
for package in inputhashes:
out = run_command(['apt-get', 'install', '-y', package])
if(find(out[1], 'Permission denied') != -1):
failed.append(package) # Install failed because we're not root
if(find(out[0], ('Setting up ' + package)) != -1 and find(out[0], (package + ' already the newest version')) != -1):
# Something else happened, we weren't installed and we didn't get installed
failed.append(package)
return failed
| Remove extra print in apt
import os
import subprocess
from string import find
def run_command(command):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return out,err
def schema():
"""
This returns
"""
return { 'title': 'apt schema',
'type': 'string'
}
def verify(inputhashes):
"""
"""
failed = []
for package in inputhashes:
out = run_command(['dpkg-query', '-W', package])[0]
#We expect the output to contain the version
#Any error doesn't get captured, so out will be empty (yes this is weird)
if(find(out, package) == -1):
failed.append(package)
return failed
def apply(inputhashes, dry_run=True):
failed = []
for package in inputhashes:
out = run_command(['apt-get', 'install', '-y', package])
if(find(out[1], 'Permission denied') != -1):
failed.append(package) #Install failed because we're not root
if(find(out[0], ('Setting up ' + package)) != -1 and find(out[0], (package + ' already the newest version')) != -1):
#Something else happened, we weren't installed and we didn't get installed
failed.append(package)
print out
return failed
|
ba41dc9bff21558d1712fe06751f867806d8abd6 | setup.py | setup.py | from distutils.core import setup
setup(
name='python_lemonway',
version='0.1.0',
author='Pierre Pigeau',
author_email='[email protected]',
packages=['lemonway'],
url='',
license='LICENSE.txt',
description='',
long_description=open('README.rst').read(),
package_data={'lemonway': ['lemonway.wsdl']},
install_requires=[
"suds-jurko==0.6",
"lxml==3.3.5"
],
)
| from distutils.core import setup
setup(
name='python_lemonway',
version='0.1.1',
author='Pierre Pigeau',
author_email='[email protected]',
packages=['lemonway'],
url='',
license='LICENSE.txt',
description='',
long_description=open('README.rst').read(),
package_data={'lemonway': ['lemonway.wsdl']},
install_requires=[
"suds-jurko==0.6",
"lxml==3.3.5"
],
)
| ADD - newversion of python_lemonway with improvements of MoneyIn | ADD - newversion of python_lemonway with improvements of MoneyIn
| Python | mit | brightforme/python-lemonway | <REPLACE_OLD> version='0.1.0',
<REPLACE_NEW> version='0.1.1',
<REPLACE_END> <|endoftext|> from distutils.core import setup
setup(
name='python_lemonway',
version='0.1.1',
author='Pierre Pigeau',
author_email='[email protected]',
packages=['lemonway'],
url='',
license='LICENSE.txt',
description='',
long_description=open('README.rst').read(),
package_data={'lemonway': ['lemonway.wsdl']},
install_requires=[
"suds-jurko==0.6",
"lxml==3.3.5"
],
)
| ADD - newversion of python_lemonway with improvements of MoneyIn
from distutils.core import setup
setup(
name='python_lemonway',
version='0.1.0',
author='Pierre Pigeau',
author_email='[email protected]',
packages=['lemonway'],
url='',
license='LICENSE.txt',
description='',
long_description=open('README.rst').read(),
package_data={'lemonway': ['lemonway.wsdl']},
install_requires=[
"suds-jurko==0.6",
"lxml==3.3.5"
],
)
|
ad4b972667e9111c403c1d3726b2cde87fcbc88e | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='natural',
version='0.1.4',
description='Convert data to their natural (human-readable) format',
long_description='''
Example Usage
=============
Basic usage::
>>> from natural.file import accessed
>>> print accessed(__file__)
just now
We speak your language (with `your support`_)::
>>> import locale
>>> locale.setlocale(locale.LC_MESSAGES, 'nl_NL')
>>> print accessed(__file__)
zojuist
Bugs/Features
=============
You can issue a ticket in GitHub: https://github.com/tehmaze/natural/issues
Documentation
=============
The project documentation can be found at http://natural.rtfd.org/
.. _your support: http://natural.readthedocs.org/en/latest/locales.html
''',
author='Wijnand Modderman-Lenstra',
author_email='[email protected]',
license='MIT',
keywords='natural data date file number size',
url='https://github.com/tehmaze/natural',
packages=['natural'],
package_data={'natural': ['locale/*/LC_MESSAGES/*.mo']},
)
| #!/usr/bin/env python
from distutils.core import setup
setup(name='natural',
version='0.1.4',
description='Convert data to their natural (human-readable) format',
long_description='''
Example Usage
=============
Basic usage::
>>> from natural.file import accessed
>>> print accessed(__file__)
just now
We speak your language (with `your support`_)::
>>> import locale
>>> locale.setlocale(locale.LC_MESSAGES, 'nl_NL')
>>> print accessed(__file__)
zojuist
Bugs/Features
=============
You can issue a ticket in GitHub: https://github.com/tehmaze/natural/issues
Documentation
=============
The project documentation can be found at http://natural.rtfd.org/
.. _your support: http://natural.readthedocs.org/en/latest/locales.html
''',
author='Wijnand Modderman-Lenstra',
author_email='[email protected]',
license='MIT',
keywords='natural data date file number size',
url='https://github.com/tehmaze/natural',
packages=['natural'],
package_data={'natural': ['locale/*/LC_MESSAGES/*.mo']},
use_2to3=True,
)
| Use 2to3 for Python 3 | Use 2to3 for Python 3
| Python | mit | tehmaze/natural | <REPLACE_OLD> ['locale/*/LC_MESSAGES/*.mo']},
)
<REPLACE_NEW> ['locale/*/LC_MESSAGES/*.mo']},
use_2to3=True,
)
<REPLACE_END> <|endoftext|> #!/usr/bin/env python
from distutils.core import setup
setup(name='natural',
version='0.1.4',
description='Convert data to their natural (human-readable) format',
long_description='''
Example Usage
=============
Basic usage::
>>> from natural.file import accessed
>>> print accessed(__file__)
just now
We speak your language (with `your support`_)::
>>> import locale
>>> locale.setlocale(locale.LC_MESSAGES, 'nl_NL')
>>> print accessed(__file__)
zojuist
Bugs/Features
=============
You can issue a ticket in GitHub: https://github.com/tehmaze/natural/issues
Documentation
=============
The project documentation can be found at http://natural.rtfd.org/
.. _your support: http://natural.readthedocs.org/en/latest/locales.html
''',
author='Wijnand Modderman-Lenstra',
author_email='[email protected]',
license='MIT',
keywords='natural data date file number size',
url='https://github.com/tehmaze/natural',
packages=['natural'],
package_data={'natural': ['locale/*/LC_MESSAGES/*.mo']},
use_2to3=True,
)
| Use 2to3 for Python 3
#!/usr/bin/env python
from distutils.core import setup
setup(name='natural',
version='0.1.4',
description='Convert data to their natural (human-readable) format',
long_description='''
Example Usage
=============
Basic usage::
>>> from natural.file import accessed
>>> print accessed(__file__)
just now
We speak your language (with `your support`_)::
>>> import locale
>>> locale.setlocale(locale.LC_MESSAGES, 'nl_NL')
>>> print accessed(__file__)
zojuist
Bugs/Features
=============
You can issue a ticket in GitHub: https://github.com/tehmaze/natural/issues
Documentation
=============
The project documentation can be found at http://natural.rtfd.org/
.. _your support: http://natural.readthedocs.org/en/latest/locales.html
''',
author='Wijnand Modderman-Lenstra',
author_email='[email protected]',
license='MIT',
keywords='natural data date file number size',
url='https://github.com/tehmaze/natural',
packages=['natural'],
package_data={'natural': ['locale/*/LC_MESSAGES/*.mo']},
)
|
925ff38344b5058ce196877e1fdcf79a1d1f6719 | ue4/tests/test_messaging.py | ue4/tests/test_messaging.py | import pytest
from m2u.ue4 import connection
def test_send_message_size():
"""Send a big message, larger than buffer size, so the server has to
read multiple chunks.
"""
message = "TestMessageSize " + ("abcdefg" * 5000)
connection.connect()
result = connection.send_message(message)
assert result == str(len(message))
connection.disconnect()
| Add basic test for checking messages are received correctly | Add basic test for checking messages are received correctly
| Python | mit | m2u/m2u | <INSERT> import pytest
from m2u.ue4 import connection
def test_send_message_size():
<INSERT_END> <INSERT> """Send a big message, larger than buffer size, so the server has to
read multiple chunks.
"""
message = "TestMessageSize " + ("abcdefg" * 5000)
connection.connect()
result = connection.send_message(message)
assert result == str(len(message))
connection.disconnect()
<INSERT_END> <|endoftext|> import pytest
from m2u.ue4 import connection
def test_send_message_size():
"""Send a big message, larger than buffer size, so the server has to
read multiple chunks.
"""
message = "TestMessageSize " + ("abcdefg" * 5000)
connection.connect()
result = connection.send_message(message)
assert result == str(len(message))
connection.disconnect()
| Add basic test for checking messages are received correctly
|
|
bcee6173027c48bfb25a65d3e97660f2e2a0852b | gentest.py | gentest.py | from itertools import product
import json
import numpy
cube = numpy.array(range(1, 9)).reshape(2, 2, 2)
pcube = [
cube[0 ,0 ,0 ],
cube[0 ,0 ,0:2],
cube[0 ,0:2,0:1],
cube[0 ,0:2,0:2],
cube[0:2,0:1,0:1],
cube[0:2,0:1,0:2],
cube[0:2,0:2,0:1],
cube[0:2,0:2,0:2],
]
for (i, (a, b)) in enumerate(product(pcube, repeat=2), start=1):
print 'public function testBsxfun{0:0>2d}()'.format(i)
print '{'
print '$a = {0};'.format(json.dumps(a.tolist()))
print '$b = {0};'.format(json.dumps(b.tolist()))
print '$expected = {0};'.format(json.dumps((a * b).tolist()))
print '$actual = Bsxfun::bsxfun($this->times, $a, $b);'
print '$this->assertEquals($expected, $actual);'
print '}'
print
| Add a python script to generate test methods | Add a python script to generate test methods
| Python | mit | y-uti/php-bsxfun,y-uti/php-bsxfun | <INSERT> from itertools import product
import json
import numpy
cube = numpy.array(range(1, 9)).reshape(2, 2, 2)
pcube = [
<INSERT_END> <INSERT> cube[0 ,0 ,0 ],
cube[0 ,0 ,0:2],
cube[0 ,0:2,0:1],
cube[0 ,0:2,0:2],
cube[0:2,0:1,0:1],
cube[0:2,0:1,0:2],
cube[0:2,0:2,0:1],
cube[0:2,0:2,0:2],
]
for (i, (a, b)) in enumerate(product(pcube, repeat=2), start=1):
print 'public function testBsxfun{0:0>2d}()'.format(i)
print '{'
print '$a = {0};'.format(json.dumps(a.tolist()))
print '$b = {0};'.format(json.dumps(b.tolist()))
print '$expected = {0};'.format(json.dumps((a * b).tolist()))
print '$actual = Bsxfun::bsxfun($this->times, $a, $b);'
print '$this->assertEquals($expected, $actual);'
print '}'
print
<INSERT_END> <|endoftext|> from itertools import product
import json
import numpy
cube = numpy.array(range(1, 9)).reshape(2, 2, 2)
pcube = [
cube[0 ,0 ,0 ],
cube[0 ,0 ,0:2],
cube[0 ,0:2,0:1],
cube[0 ,0:2,0:2],
cube[0:2,0:1,0:1],
cube[0:2,0:1,0:2],
cube[0:2,0:2,0:1],
cube[0:2,0:2,0:2],
]
for (i, (a, b)) in enumerate(product(pcube, repeat=2), start=1):
print 'public function testBsxfun{0:0>2d}()'.format(i)
print '{'
print '$a = {0};'.format(json.dumps(a.tolist()))
print '$b = {0};'.format(json.dumps(b.tolist()))
print '$expected = {0};'.format(json.dumps((a * b).tolist()))
print '$actual = Bsxfun::bsxfun($this->times, $a, $b);'
print '$this->assertEquals($expected, $actual);'
print '}'
print
| Add a python script to generate test methods
|
|
164c70386191f0761923c1344447b8fac0e0795c | pelican/settings.py | pelican/settings.py | import os
_DEFAULT_THEME = os.sep.join([os.path.dirname(os.path.abspath(__file__)),
"themes/notmyidea"])
_DEFAULT_CONFIG = {'PATH': None,
'THEME': _DEFAULT_THEME,
'OUTPUT_PATH': 'output/',
'MARKUP': ('rst', 'md'),
'STATIC_PATHS': ['images',],
'THEME_STATIC_PATHS': ['static',],
'FEED': 'feeds/all.atom.xml',
'CATEGORY_FEED': 'feeds/%s.atom.xml',
'TRANSLATION_FEED': 'feeds/all-%s.atom.xml',
'SITENAME': 'A Pelican Blog',
'DISPLAY_PAGES_ON_MENU': True,
'PDF_GENERATOR': False,
'DEFAULT_CATEGORY': 'misc',
'FALLBACK_ON_FS_DATE': True,
'CSS_FILE': 'main.css',
'REVERSE_ARCHIVE_ORDER': False,
'KEEP_OUTPUT_DIRECTORY': False,
'CLEAN_URLS': False, # use /blah/ instead /blah.html in urls
'RELATIVE_URLS': True,
'DEFAULT_LANG': 'en',
}
def read_settings(filename):
"""Load a Python file into a dictionary.
"""
context = _DEFAULT_CONFIG.copy()
if filename:
tempdict = {}
execfile(filename, tempdict)
for key in tempdict:
if key.isupper():
context[key] = tempdict[key]
return context
| import os
_DEFAULT_THEME = os.sep.join([os.path.dirname(os.path.abspath(__file__)),
"themes/notmyidea"])
_DEFAULT_CONFIG = {'PATH': None,
'THEME': _DEFAULT_THEME,
'OUTPUT_PATH': 'output/',
'MARKUP': ('rst', 'md'),
'STATIC_PATHS': ['images',],
'THEME_STATIC_PATHS': ['static',],
'FEED': 'feeds/all.atom.xml',
'CATEGORY_FEED': 'feeds/%s.atom.xml',
'TRANSLATION_FEED': 'feeds/all-%s.atom.xml',
'SITENAME': 'A Pelican Blog',
'DISPLAY_PAGES_ON_MENU': True,
'PDF_GENERATOR': False,
'DEFAULT_CATEGORY': 'misc',
'FALLBACK_ON_FS_DATE': True,
'CSS_FILE': 'main.css',
'REVERSE_ARCHIVE_ORDER': False,
'KEEP_OUTPUT_DIRECTORY': False,
'CLEAN_URLS': False, # use /blah/ instead /blah.html in urls
'RELATIVE_URLS': True,
'DEFAULT_LANG': 'en',
'JINJA_EXTENSIONS': [],
}
def read_settings(filename):
"""Load a Python file into a dictionary.
"""
context = _DEFAULT_CONFIG.copy()
if filename:
tempdict = {}
execfile(filename, tempdict)
for key in tempdict:
if key.isupper():
context[key] = tempdict[key]
return context
| Add a default for JINJA_EXTENSIONS (default is no extensions) | Add a default for JINJA_EXTENSIONS (default is no extensions)
| Python | agpl-3.0 | treyhunner/pelican,joetboole/pelican,janaurka/git-debug-presentiation,goerz/pelican,JeremyMorgan/pelican,Polyconseil/pelican,deved69/pelican-1,JeremyMorgan/pelican,douglaskastle/pelican,farseerfc/pelican,51itclub/pelican,florianjacob/pelican,liyonghelpme/myBlog,levanhien8/pelican,lucasplus/pelican,btnpushnmunky/pelican,gymglish/pelican,catdog2/pelican,liyonghelpme/myBlog,ehashman/pelican,lazycoder-ru/pelican,koobs/pelican,douglaskastle/pelican,jimperio/pelican,Scheirle/pelican,sunzhongwei/pelican,koobs/pelican,GiovanniMoretti/pelican,liyonghelpme/myBlog,janaurka/git-debug-presentiation,lazycoder-ru/pelican,karlcow/pelican,51itclub/pelican,lucasplus/pelican,jimperio/pelican,garbas/pelican,simonjj/pelican,jvehent/pelican,kernc/pelican,GiovanniMoretti/pelican,karlcow/pelican,abrahamvarricatt/pelican,eevee/pelican,iKevinY/pelican,Natim/pelican,ehashman/pelican,jimperio/pelican,iurisilvio/pelican,number5/pelican,jo-tham/pelican,sunzhongwei/pelican,avaris/pelican,joetboole/pelican,iurisilvio/pelican,rbarraud/pelican,catdog2/pelican,11craft/pelican,eevee/pelican,goerz/pelican,catdog2/pelican,kennethlyn/pelican,btnpushnmunky/pelican,alexras/pelican,levanhien8/pelican,HyperGroups/pelican,fbs/pelican,treyhunner/pelican,iurisilvio/pelican,kernc/pelican,alexras/pelican,liyonghelpme/myBlog,ingwinlu/pelican,ls2uper/pelican,goerz/pelican,GiovanniMoretti/pelican,11craft/pelican,alexras/pelican,kennethlyn/pelican,gymglish/pelican,Summonee/pelican,ehashman/pelican,Summonee/pelican,TC01/pelican,Scheirle/pelican,deved69/pelican-1,jo-tham/pelican,arty-name/pelican,treyhunner/pelican,garbas/pelican,koobs/pelican,simonjj/pelican,UdeskDeveloper/pelican,UdeskDeveloper/pelican,ls2uper/pelican,TC01/pelican,number5/pelican,0xMF/pelican,kennethlyn/pelican,51itclub/pelican,crmackay/pelican,zackw/pelican,Rogdham/pelican,rbarraud/pelican,janaurka/git-debug-presentiation,ionelmc/pelican,JeremyMorgan/pelican,getpelican/pelican,zackw/pelican,lucasplus/pelican,florianjacob/pelican,btnpushnmunky/pelican,abrahamvarricatt/pelican,talha131/pelican,ls2uper/pelican,jvehent/pelican,florianjacob/pelican,eevee/pelican,gymglish/pelican,liyonghelpme/myBlog,simonjj/pelican,Polyconseil/pelican,joetboole/pelican,crmackay/pelican,farseerfc/pelican,Summonee/pelican,ingwinlu/pelican,sunzhongwei/pelican,sunzhongwei/pelican,Scheirle/pelican,karlcow/pelican,11craft/pelican,crmackay/pelican,getpelican/pelican,HyperGroups/pelican,lazycoder-ru/pelican,Rogdham/pelican,talha131/pelican,zackw/pelican,TC01/pelican,levanhien8/pelican,Rogdham/pelican,deved69/pelican-1,jvehent/pelican,number5/pelican,HyperGroups/pelican,justinmayer/pelican,deanishe/pelican,garbas/pelican,iKevinY/pelican,avaris/pelican,deanishe/pelican,rbarraud/pelican,UdeskDeveloper/pelican,douglaskastle/pelican,abrahamvarricatt/pelican,deanishe/pelican,kernc/pelican | <INSERT> 'JINJA_EXTENSIONS': [],
<INSERT_END> <|endoftext|> import os
_DEFAULT_THEME = os.sep.join([os.path.dirname(os.path.abspath(__file__)),
"themes/notmyidea"])
_DEFAULT_CONFIG = {'PATH': None,
'THEME': _DEFAULT_THEME,
'OUTPUT_PATH': 'output/',
'MARKUP': ('rst', 'md'),
'STATIC_PATHS': ['images',],
'THEME_STATIC_PATHS': ['static',],
'FEED': 'feeds/all.atom.xml',
'CATEGORY_FEED': 'feeds/%s.atom.xml',
'TRANSLATION_FEED': 'feeds/all-%s.atom.xml',
'SITENAME': 'A Pelican Blog',
'DISPLAY_PAGES_ON_MENU': True,
'PDF_GENERATOR': False,
'DEFAULT_CATEGORY': 'misc',
'FALLBACK_ON_FS_DATE': True,
'CSS_FILE': 'main.css',
'REVERSE_ARCHIVE_ORDER': False,
'KEEP_OUTPUT_DIRECTORY': False,
'CLEAN_URLS': False, # use /blah/ instead /blah.html in urls
'RELATIVE_URLS': True,
'DEFAULT_LANG': 'en',
'JINJA_EXTENSIONS': [],
}
def read_settings(filename):
"""Load a Python file into a dictionary.
"""
context = _DEFAULT_CONFIG.copy()
if filename:
tempdict = {}
execfile(filename, tempdict)
for key in tempdict:
if key.isupper():
context[key] = tempdict[key]
return context
| Add a default for JINJA_EXTENSIONS (default is no extensions)
import os
_DEFAULT_THEME = os.sep.join([os.path.dirname(os.path.abspath(__file__)),
"themes/notmyidea"])
_DEFAULT_CONFIG = {'PATH': None,
'THEME': _DEFAULT_THEME,
'OUTPUT_PATH': 'output/',
'MARKUP': ('rst', 'md'),
'STATIC_PATHS': ['images',],
'THEME_STATIC_PATHS': ['static',],
'FEED': 'feeds/all.atom.xml',
'CATEGORY_FEED': 'feeds/%s.atom.xml',
'TRANSLATION_FEED': 'feeds/all-%s.atom.xml',
'SITENAME': 'A Pelican Blog',
'DISPLAY_PAGES_ON_MENU': True,
'PDF_GENERATOR': False,
'DEFAULT_CATEGORY': 'misc',
'FALLBACK_ON_FS_DATE': True,
'CSS_FILE': 'main.css',
'REVERSE_ARCHIVE_ORDER': False,
'KEEP_OUTPUT_DIRECTORY': False,
'CLEAN_URLS': False, # use /blah/ instead /blah.html in urls
'RELATIVE_URLS': True,
'DEFAULT_LANG': 'en',
}
def read_settings(filename):
"""Load a Python file into a dictionary.
"""
context = _DEFAULT_CONFIG.copy()
if filename:
tempdict = {}
execfile(filename, tempdict)
for key in tempdict:
if key.isupper():
context[key] = tempdict[key]
return context
|
6a40aab945e28c509e24ede6a48b7ac1f3b89ce2 | product_isp/__manifest__.py | product_isp/__manifest__.py | # Copyright (C) 2019 - TODAY, Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': 'Product ISP',
'version': '12.0.1.0.0',
'license': 'AGPL-3',
'summary': 'Assign ISPs to Products',
'author': 'Open Source Integrators, Odoo Community Association (OCA)',
"website": 'https://github.com/OCA/vertical-isp',
'depends': [
'stock',
'base_phone_rate'
],
'data': [
'views/product_product.xml',
],
'installable': True,
'development_status': 'Beta',
'maintainers': [
'wolfhall',
'max3903',
'osi-scampbell',
],
}
| # Copyright (C) 2019 - TODAY, Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': 'Product ISP',
'version': '12.0.1.0.0',
'license': 'AGPL-3',
'summary': 'Assign ISPs to Products',
'author': 'Open Source Integrators, Odoo Community Association (OCA)',
"website": 'https://github.com/OCA/vertical-isp',
'depends': [
'product',
'base_phone_rate'
],
'data': [
'views/product_product.xml',
],
'installable': True,
'development_status': 'Beta',
'maintainers': [
'wolfhall',
'max3903',
'osi-scampbell',
],
}
| Remove unneeded dependency on Inventory | [IMP] Remove unneeded dependency on Inventory
| Python | agpl-3.0 | OCA/vertical-isp,OCA/vertical-isp | <REPLACE_OLD> 'stock',
<REPLACE_NEW> 'product',
<REPLACE_END> <|endoftext|> # Copyright (C) 2019 - TODAY, Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': 'Product ISP',
'version': '12.0.1.0.0',
'license': 'AGPL-3',
'summary': 'Assign ISPs to Products',
'author': 'Open Source Integrators, Odoo Community Association (OCA)',
"website": 'https://github.com/OCA/vertical-isp',
'depends': [
'product',
'base_phone_rate'
],
'data': [
'views/product_product.xml',
],
'installable': True,
'development_status': 'Beta',
'maintainers': [
'wolfhall',
'max3903',
'osi-scampbell',
],
}
| [IMP] Remove unneeded dependency on Inventory
# Copyright (C) 2019 - TODAY, Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': 'Product ISP',
'version': '12.0.1.0.0',
'license': 'AGPL-3',
'summary': 'Assign ISPs to Products',
'author': 'Open Source Integrators, Odoo Community Association (OCA)',
"website": 'https://github.com/OCA/vertical-isp',
'depends': [
'stock',
'base_phone_rate'
],
'data': [
'views/product_product.xml',
],
'installable': True,
'development_status': 'Beta',
'maintainers': [
'wolfhall',
'max3903',
'osi-scampbell',
],
}
|
1db5fefc1752b71bf11fbf63853f7c93bcc526f5 | tests/macaroon_property_tests.py | tests/macaroon_property_tests.py | from __future__ import unicode_literals
from mock import *
from nose.tools import *
from hypothesis import *
from hypothesis.specifiers import *
from six import text_type, binary_type
from pymacaroons import Macaroon, Verifier
ascii_text_stategy = strategy(text_type).map(
lambda s: s.encode('ascii', 'ignore')
)
ascii_bin_strategy = strategy(binary_type).map(
lambda s: s.decode('ascii', 'ignore')
)
class TestMacaroon(object):
def setup(self):
pass
@given(
key_id=one_of((ascii_text_stategy, ascii_bin_strategy)),
loc=one_of((ascii_text_stategy, ascii_bin_strategy)),
key=one_of((ascii_text_stategy, ascii_bin_strategy))
)
def test_serializing_deserializing_macaroon(self, key_id, loc, key):
assume(key_id and loc and key)
macaroon = Macaroon(
location=loc,
identifier=key_id,
key=key
)
deserialized = Macaroon.deserialize(macaroon.serialize())
assert_equal(macaroon.identifier, deserialized.identifier)
assert_equal(macaroon.location, deserialized.location)
assert_equal(macaroon.signature, deserialized.signature)
| from __future__ import unicode_literals
from mock import *
from nose.tools import *
from hypothesis import *
from hypothesis.specifiers import *
from six import text_type, binary_type
from pymacaroons import Macaroon, Verifier
from pymacaroons.utils import convert_to_bytes
ascii_text_strategy = strategy(
[sampled_from(map(chr, range(0, 128)))]
).map(lambda c: ''.join(c))
ascii_bin_strategy = strategy(ascii_text_strategy).map(
lambda s: convert_to_bytes(s)
)
class TestMacaroon(object):
def setup(self):
pass
@given(
key_id=one_of((ascii_text_strategy, ascii_bin_strategy)),
loc=one_of((ascii_text_strategy, ascii_bin_strategy)),
key=one_of((ascii_text_strategy, ascii_bin_strategy))
)
def test_serializing_deserializing_macaroon(self, key_id, loc, key):
assume(key_id and loc and key)
macaroon = Macaroon(
location=loc,
identifier=key_id,
key=key
)
deserialized = Macaroon.deserialize(macaroon.serialize())
assert_equal(macaroon.identifier, deserialized.identifier)
assert_equal(macaroon.location, deserialized.location)
assert_equal(macaroon.signature, deserialized.signature)
| Improve strategies in property tests | Improve strategies in property tests
| Python | mit | matrix-org/pymacaroons,matrix-org/pymacaroons,ecordell/pymacaroons,illicitonion/pymacaroons | <REPLACE_OLD> Verifier
ascii_text_stategy = strategy(text_type).map(
<REPLACE_NEW> Verifier
from pymacaroons.utils import convert_to_bytes
ascii_text_strategy = strategy(
[sampled_from(map(chr, range(0, 128)))]
).map(lambda c: ''.join(c))
ascii_bin_strategy = strategy(ascii_text_strategy).map(
<REPLACE_END> <REPLACE_OLD> s.encode('ascii', 'ignore')
)
ascii_bin_strategy = strategy(binary_type).map(
lambda s: s.decode('ascii', 'ignore')
)
class <REPLACE_NEW> convert_to_bytes(s)
)
class <REPLACE_END> <REPLACE_OLD> key_id=one_of((ascii_text_stategy, <REPLACE_NEW> key_id=one_of((ascii_text_strategy, <REPLACE_END> <REPLACE_OLD> loc=one_of((ascii_text_stategy, <REPLACE_NEW> loc=one_of((ascii_text_strategy, <REPLACE_END> <REPLACE_OLD> key=one_of((ascii_text_stategy, <REPLACE_NEW> key=one_of((ascii_text_strategy, <REPLACE_END> <|endoftext|> from __future__ import unicode_literals
from mock import *
from nose.tools import *
from hypothesis import *
from hypothesis.specifiers import *
from six import text_type, binary_type
from pymacaroons import Macaroon, Verifier
from pymacaroons.utils import convert_to_bytes
ascii_text_strategy = strategy(
[sampled_from(map(chr, range(0, 128)))]
).map(lambda c: ''.join(c))
ascii_bin_strategy = strategy(ascii_text_strategy).map(
lambda s: convert_to_bytes(s)
)
class TestMacaroon(object):
def setup(self):
pass
@given(
key_id=one_of((ascii_text_strategy, ascii_bin_strategy)),
loc=one_of((ascii_text_strategy, ascii_bin_strategy)),
key=one_of((ascii_text_strategy, ascii_bin_strategy))
)
def test_serializing_deserializing_macaroon(self, key_id, loc, key):
assume(key_id and loc and key)
macaroon = Macaroon(
location=loc,
identifier=key_id,
key=key
)
deserialized = Macaroon.deserialize(macaroon.serialize())
assert_equal(macaroon.identifier, deserialized.identifier)
assert_equal(macaroon.location, deserialized.location)
assert_equal(macaroon.signature, deserialized.signature)
| Improve strategies in property tests
from __future__ import unicode_literals
from mock import *
from nose.tools import *
from hypothesis import *
from hypothesis.specifiers import *
from six import text_type, binary_type
from pymacaroons import Macaroon, Verifier
ascii_text_stategy = strategy(text_type).map(
lambda s: s.encode('ascii', 'ignore')
)
ascii_bin_strategy = strategy(binary_type).map(
lambda s: s.decode('ascii', 'ignore')
)
class TestMacaroon(object):
def setup(self):
pass
@given(
key_id=one_of((ascii_text_stategy, ascii_bin_strategy)),
loc=one_of((ascii_text_stategy, ascii_bin_strategy)),
key=one_of((ascii_text_stategy, ascii_bin_strategy))
)
def test_serializing_deserializing_macaroon(self, key_id, loc, key):
assume(key_id and loc and key)
macaroon = Macaroon(
location=loc,
identifier=key_id,
key=key
)
deserialized = Macaroon.deserialize(macaroon.serialize())
assert_equal(macaroon.identifier, deserialized.identifier)
assert_equal(macaroon.location, deserialized.location)
assert_equal(macaroon.signature, deserialized.signature)
|
134338b7aab3c3b79c2aa62fd878926ff9d9adc5 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
def main ():
dlls = ["bin/%s" % dll for dll in ["libcairo-2.dll"]]
licenses = ["doc/%s" % license for license in ["LICENSE-LGPL.TXT",
"LICENSE-CAIRO.TXT"]]
others = ["README.rst", "LICENSE.rst"]
long_description = """ This package contains dynamic link dependencies required to run the
python-cairo library on Microsoft Windows.
Please see README.rst for more details."""
classifiers = ["Development Status :: 6 - Mature",
"Environment :: Win32 (MS Windows)",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"License :: MIT License", "License :: zlib/libpng License",
"Operating System :: Microsoft",
"Operating System :: Microsoft :: Windows",
"Topic :: Software Development :: Libraries"]
return setup(name="cairp-dependencies", version="0.1",
maintainer="Jonathan McManus", maintainer_email="[email protected]", author="various",
url="http://www.github.com/jmcb/python-cairo-dependencies",
download_url="http://www.wxwhatever.com/jmcb/cairo", platforms="Microsoft Windows",
description="Dynamic link library dependencies for pycairo.",
license="GNU LGPLv2, MIT, MPL.",
data_files=[("lib/site-packages/cairo", dlls), ("doc/python-cairo", licenses + others)],
long_description=long_description, classifiers=classifiers)
if __name__=="__main__":
main ()
| #!/usr/bin/env python
from distutils.core import setup
def main ():
dlls = ["bin/%s" % dll for dll in ["libcairo-2.dll"]]
licenses = ["doc/%s" % license for license in ["LICENSE-LGPL.TXT",
"LICENSE-CAIRO.TXT"]]
others = ["README.rst", "LICENSE.rst"]
long_description = """ This package contains dynamic link dependencies required to run the
python-cairo library on Microsoft Windows.
Please see README.rst for more details."""
classifiers = ["Development Status :: 6 - Mature",
"Environment :: Win32 (MS Windows)",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"License :: MIT License", "License :: zlib/libpng License",
"Operating System :: Microsoft",
"Operating System :: Microsoft :: Windows",
"Topic :: Software Development :: Libraries"]
return setup(name="cairo-dependencies", version="0.1",
maintainer="Jonathan McManus", maintainer_email="[email protected]", author="various",
url="http://www.github.com/jmcb/python-cairo-dependencies",
download_url="http://www.wxwhatever.com/jmcb/cairo", platforms="Microsoft Windows",
description="Dynamic link library dependencies for pycairo.",
license="GNU LGPLv2, MIT, MPL.",
data_files=[("lib/site-packages/cairo", dlls), ("doc/python-cairo", licenses + others)],
long_description=long_description, classifiers=classifiers)
if __name__=="__main__":
main ()
| Fix typo in package name. | Fix typo in package name.
Cairp: what you get when you mix cairo with carp. Or perhaps a cairn
made of carp?
| Python | mit | jmcb/python-cairo-dependencies | <REPLACE_OLD> setup(name="cairp-dependencies", <REPLACE_NEW> setup(name="cairo-dependencies", <REPLACE_END> <|endoftext|> #!/usr/bin/env python
from distutils.core import setup
def main ():
dlls = ["bin/%s" % dll for dll in ["libcairo-2.dll"]]
licenses = ["doc/%s" % license for license in ["LICENSE-LGPL.TXT",
"LICENSE-CAIRO.TXT"]]
others = ["README.rst", "LICENSE.rst"]
long_description = """ This package contains dynamic link dependencies required to run the
python-cairo library on Microsoft Windows.
Please see README.rst for more details."""
classifiers = ["Development Status :: 6 - Mature",
"Environment :: Win32 (MS Windows)",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"License :: MIT License", "License :: zlib/libpng License",
"Operating System :: Microsoft",
"Operating System :: Microsoft :: Windows",
"Topic :: Software Development :: Libraries"]
return setup(name="cairo-dependencies", version="0.1",
maintainer="Jonathan McManus", maintainer_email="[email protected]", author="various",
url="http://www.github.com/jmcb/python-cairo-dependencies",
download_url="http://www.wxwhatever.com/jmcb/cairo", platforms="Microsoft Windows",
description="Dynamic link library dependencies for pycairo.",
license="GNU LGPLv2, MIT, MPL.",
data_files=[("lib/site-packages/cairo", dlls), ("doc/python-cairo", licenses + others)],
long_description=long_description, classifiers=classifiers)
if __name__=="__main__":
main ()
| Fix typo in package name.
Cairp: what you get when you mix cairo with carp. Or perhaps a cairn
made of carp?
#!/usr/bin/env python
from distutils.core import setup
def main ():
dlls = ["bin/%s" % dll for dll in ["libcairo-2.dll"]]
licenses = ["doc/%s" % license for license in ["LICENSE-LGPL.TXT",
"LICENSE-CAIRO.TXT"]]
others = ["README.rst", "LICENSE.rst"]
long_description = """ This package contains dynamic link dependencies required to run the
python-cairo library on Microsoft Windows.
Please see README.rst for more details."""
classifiers = ["Development Status :: 6 - Mature",
"Environment :: Win32 (MS Windows)",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"License :: MIT License", "License :: zlib/libpng License",
"Operating System :: Microsoft",
"Operating System :: Microsoft :: Windows",
"Topic :: Software Development :: Libraries"]
return setup(name="cairp-dependencies", version="0.1",
maintainer="Jonathan McManus", maintainer_email="[email protected]", author="various",
url="http://www.github.com/jmcb/python-cairo-dependencies",
download_url="http://www.wxwhatever.com/jmcb/cairo", platforms="Microsoft Windows",
description="Dynamic link library dependencies for pycairo.",
license="GNU LGPLv2, MIT, MPL.",
data_files=[("lib/site-packages/cairo", dlls), ("doc/python-cairo", licenses + others)],
long_description=long_description, classifiers=classifiers)
if __name__=="__main__":
main ()
|
843f689fd76344aa6921b94576a92d4ff7bba609 | test/load_unload/TestLoadUnload.py | test/load_unload/TestLoadUnload.py | """
Test that breakpoint by symbol name works correctly dlopen'ing a dynamic lib.
"""
import os, time
import unittest
import lldb
import lldbtest
class TestClassTypes(lldbtest.TestBase):
mydir = "load_unload"
def test_dead_strip(self):
"""Test breakpoint by name works correctly with dlopen'ing."""
res = self.res
exe = os.path.join(os.getcwd(), "a.out")
self.ci.HandleCommand("file " + exe, res)
self.assertTrue(res.Succeeded())
# Break by function name a_function (not yet loaded).
self.ci.HandleCommand("breakpoint set -n a_function", res)
self.assertTrue(res.Succeeded())
self.assertTrue(res.GetOutput().startswith(
"Breakpoint created: 1: name = 'a_function', locations = 0 "
"(pending)"
))
self.ci.HandleCommand("run", res)
time.sleep(0.1)
self.assertTrue(res.Succeeded())
# The stop reason of the thread should be breakpoint and at a_function.
self.ci.HandleCommand("thread list", res)
output = res.GetOutput()
self.assertTrue(res.Succeeded())
self.assertTrue(output.find('state is Stopped') > 0 and
output.find('a_function') > 0 and
output.find('a.c:14') > 0 and
output.find('stop reason = breakpoint') > 0)
# The breakpoint should have a hit count of 1.
self.ci.HandleCommand("breakpoint list", res)
self.assertTrue(res.Succeeded())
self.assertTrue(res.GetOutput().find(' resolved, hit count = 1') > 0)
self.ci.HandleCommand("continue", res)
self.assertTrue(res.Succeeded())
# # We should stop agaian at a_function.
# # The stop reason of the thread should be breakpoint and at a_function.
# self.ci.HandleCommand("thread list", res)
# output = res.GetOutput()
# self.assertTrue(res.Succeeded())
# self.assertTrue(output.find('state is Stopped') > 0 and
# output.find('a_function') > 0 and
# output.find('a.c:14') > 0 and
# output.find('stop reason = breakpoint') > 0)
# # The breakpoint should have a hit count of 2.
# self.ci.HandleCommand("breakpoint list", res)
# self.assertTrue(res.Succeeded())
# self.assertTrue(res.GetOutput().find(' resolved, hit count = 2') > 0)
# self.ci.HandleCommand("continue", res)
# self.assertTrue(res.Succeeded())
if __name__ == '__main__':
lldb.SBDebugger.Initialize()
unittest.main()
lldb.SBDebugger.Terminate()
| Test that breakpoint by symbol name works correctly dlopen'ing a dynamic lib. | Test that breakpoint by symbol name works correctly dlopen'ing a dynamic lib.
git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@107812 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb | <REPLACE_OLD> <REPLACE_NEW> """
Test that breakpoint by symbol name works correctly dlopen'ing a dynamic lib.
"""
import os, time
import unittest
import lldb
import lldbtest
class TestClassTypes(lldbtest.TestBase):
mydir = "load_unload"
def test_dead_strip(self):
"""Test breakpoint by name works correctly with dlopen'ing."""
res = self.res
exe = os.path.join(os.getcwd(), "a.out")
self.ci.HandleCommand("file " + exe, res)
self.assertTrue(res.Succeeded())
# Break by function name a_function (not yet loaded).
self.ci.HandleCommand("breakpoint set -n a_function", res)
self.assertTrue(res.Succeeded())
self.assertTrue(res.GetOutput().startswith(
"Breakpoint created: 1: name = 'a_function', locations = 0 "
"(pending)"
))
self.ci.HandleCommand("run", res)
time.sleep(0.1)
self.assertTrue(res.Succeeded())
# The stop reason of the thread should be breakpoint and at a_function.
self.ci.HandleCommand("thread list", res)
output = res.GetOutput()
self.assertTrue(res.Succeeded())
self.assertTrue(output.find('state is Stopped') > 0 and
output.find('a_function') > 0 and
output.find('a.c:14') > 0 and
output.find('stop reason = breakpoint') > 0)
# The breakpoint should have a hit count of 1.
self.ci.HandleCommand("breakpoint list", res)
self.assertTrue(res.Succeeded())
self.assertTrue(res.GetOutput().find(' resolved, hit count = 1') > 0)
self.ci.HandleCommand("continue", res)
self.assertTrue(res.Succeeded())
# # We should stop agaian at a_function.
# # The stop reason of the thread should be breakpoint and at a_function.
# self.ci.HandleCommand("thread list", res)
# output = res.GetOutput()
# self.assertTrue(res.Succeeded())
# self.assertTrue(output.find('state is Stopped') > 0 and
# output.find('a_function') > 0 and
# output.find('a.c:14') > 0 and
# output.find('stop reason = breakpoint') > 0)
# # The breakpoint should have a hit count of 2.
# self.ci.HandleCommand("breakpoint list", res)
# self.assertTrue(res.Succeeded())
# self.assertTrue(res.GetOutput().find(' resolved, hit count = 2') > 0)
# self.ci.HandleCommand("continue", res)
# self.assertTrue(res.Succeeded())
if __name__ == '__main__':
lldb.SBDebugger.Initialize()
unittest.main()
lldb.SBDebugger.Terminate()
<REPLACE_END> <|endoftext|> """
Test that breakpoint by symbol name works correctly dlopen'ing a dynamic lib.
"""
import os, time
import unittest
import lldb
import lldbtest
class TestClassTypes(lldbtest.TestBase):
mydir = "load_unload"
def test_dead_strip(self):
"""Test breakpoint by name works correctly with dlopen'ing."""
res = self.res
exe = os.path.join(os.getcwd(), "a.out")
self.ci.HandleCommand("file " + exe, res)
self.assertTrue(res.Succeeded())
# Break by function name a_function (not yet loaded).
self.ci.HandleCommand("breakpoint set -n a_function", res)
self.assertTrue(res.Succeeded())
self.assertTrue(res.GetOutput().startswith(
"Breakpoint created: 1: name = 'a_function', locations = 0 "
"(pending)"
))
self.ci.HandleCommand("run", res)
time.sleep(0.1)
self.assertTrue(res.Succeeded())
# The stop reason of the thread should be breakpoint and at a_function.
self.ci.HandleCommand("thread list", res)
output = res.GetOutput()
self.assertTrue(res.Succeeded())
self.assertTrue(output.find('state is Stopped') > 0 and
output.find('a_function') > 0 and
output.find('a.c:14') > 0 and
output.find('stop reason = breakpoint') > 0)
# The breakpoint should have a hit count of 1.
self.ci.HandleCommand("breakpoint list", res)
self.assertTrue(res.Succeeded())
self.assertTrue(res.GetOutput().find(' resolved, hit count = 1') > 0)
self.ci.HandleCommand("continue", res)
self.assertTrue(res.Succeeded())
# # We should stop agaian at a_function.
# # The stop reason of the thread should be breakpoint and at a_function.
# self.ci.HandleCommand("thread list", res)
# output = res.GetOutput()
# self.assertTrue(res.Succeeded())
# self.assertTrue(output.find('state is Stopped') > 0 and
# output.find('a_function') > 0 and
# output.find('a.c:14') > 0 and
# output.find('stop reason = breakpoint') > 0)
# # The breakpoint should have a hit count of 2.
# self.ci.HandleCommand("breakpoint list", res)
# self.assertTrue(res.Succeeded())
# self.assertTrue(res.GetOutput().find(' resolved, hit count = 2') > 0)
# self.ci.HandleCommand("continue", res)
# self.assertTrue(res.Succeeded())
if __name__ == '__main__':
lldb.SBDebugger.Initialize()
unittest.main()
lldb.SBDebugger.Terminate()
| Test that breakpoint by symbol name works correctly dlopen'ing a dynamic lib.
git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@107812 91177308-0d34-0410-b5e6-96231b3b80d8
|
|
8a309491f6370814f88d8be7e5b7c697c4b59dcd | great_expectations/__init__.py | great_expectations/__init__.py | import pandas as pd
from util import *
import dataset
from pkg_resources import get_distribution
try:
__version__ = get_distribution('great_expectations').version
except:
pass
def list_sources():
raise NotImplementedError
def connect_to_datasource():
raise NotImplementedError
def connect_to_dataset():
raise NotImplementedError
def read_csv(filename, dataset_config=None, *args, **kwargs):
df = pd.read_csv(filename, *args, **kwargs)
df.__class__ = dataset.pandas_dataset.PandasDataSet
df.initialize_expectations(dataset_config)
return df
def expect(data_source_str, expectation):
raise NotImplementedError
| import pandas as pd
from .util import *
import dataset
from pkg_resources import get_distribution
try:
__version__ = get_distribution('great_expectations').version
except:
pass
def list_sources():
raise NotImplementedError
def connect_to_datasource():
raise NotImplementedError
def connect_to_dataset():
raise NotImplementedError
def read_csv(filename, dataset_config=None, *args, **kwargs):
df = pd.read_csv(filename, *args, **kwargs)
df.__class__ = dataset.pandas_dataset.PandasDataSet
df.initialize_expectations(dataset_config)
return df
def df(df, dataset_config=None, *args, **kwargs):
df.__class__ = dataset.pandas_dataset.PandasDataSet
df.initialize_expectations(dataset_config)
return df
def expect(data_source_str, expectation):
raise NotImplementedError
| Change import util to .util to support python 3 | Change import util to .util to support python 3
| Python | apache-2.0 | great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations | <REPLACE_OLD> util <REPLACE_NEW> .util <REPLACE_END> <REPLACE_OLD> df
<REPLACE_NEW> df
def df(df, dataset_config=None, *args, **kwargs):
<REPLACE_END> <REPLACE_OLD>
def <REPLACE_NEW> df.__class__ = dataset.pandas_dataset.PandasDataSet
df.initialize_expectations(dataset_config)
return df
def <REPLACE_END> <|endoftext|> import pandas as pd
from .util import *
import dataset
from pkg_resources import get_distribution
try:
__version__ = get_distribution('great_expectations').version
except:
pass
def list_sources():
raise NotImplementedError
def connect_to_datasource():
raise NotImplementedError
def connect_to_dataset():
raise NotImplementedError
def read_csv(filename, dataset_config=None, *args, **kwargs):
df = pd.read_csv(filename, *args, **kwargs)
df.__class__ = dataset.pandas_dataset.PandasDataSet
df.initialize_expectations(dataset_config)
return df
def df(df, dataset_config=None, *args, **kwargs):
df.__class__ = dataset.pandas_dataset.PandasDataSet
df.initialize_expectations(dataset_config)
return df
def expect(data_source_str, expectation):
raise NotImplementedError
| Change import util to .util to support python 3
import pandas as pd
from util import *
import dataset
from pkg_resources import get_distribution
try:
__version__ = get_distribution('great_expectations').version
except:
pass
def list_sources():
raise NotImplementedError
def connect_to_datasource():
raise NotImplementedError
def connect_to_dataset():
raise NotImplementedError
def read_csv(filename, dataset_config=None, *args, **kwargs):
df = pd.read_csv(filename, *args, **kwargs)
df.__class__ = dataset.pandas_dataset.PandasDataSet
df.initialize_expectations(dataset_config)
return df
def expect(data_source_str, expectation):
raise NotImplementedError
|
2932698f81a17204b824763e648cd56dbab5f5b2 | hawkpost/settings/development.py | hawkpost/settings/development.py | from .common import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': "hawkpost_dev",
}
}
# Development Applications
INSTALLED_APPS += (
'debug_toolbar',
'django_extensions'
)
EMAIL_HOST = "127.0.0.1"
EMAIL_PORT = 1025
| from .common import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': "hawkpost_dev",
}
}
# If the DB_HOST was specified it is overriding the default connection
if 'DB_HOST' in os.environ:
DATABASES['default']['HOST'] = os.environ.get("DB_HOST")
DATABASES['default']['PORT'] = os.environ.get("DB_PORT", 5432)
DATABASES['default']['USER'] = os.environ.get("DB_USER")
DATABASES['default']['NAME'] = os.environ.get("DB_NAME", "hawkpost_dev")
if 'DB_PASSWORD' in os.environ:
DATABASES['default']['PASSWORD'] = os.environ.get("DB_PASSWORD")
# Development Applications
INSTALLED_APPS += (
'debug_toolbar',
'django_extensions'
)
EMAIL_HOST = os.environ.get("EMAIL_HOST", "127.0.0.1")
EMAIL_PORT = os.environ.get("EMAIL_PORT", 1025)
| Allow overriding database and mail_debug settings | Allow overriding database and mail_debug settings
Using environment variables to override default database connection
and mail_debug settings in development mode. This allows setting
the values needed by the Docker environment.
| Python | mit | whitesmith/hawkpost,whitesmith/hawkpost,whitesmith/hawkpost | <REPLACE_OLD> }
}
# <REPLACE_NEW> }
}
# If the DB_HOST was specified it is overriding the default connection
if 'DB_HOST' in os.environ:
DATABASES['default']['HOST'] = os.environ.get("DB_HOST")
DATABASES['default']['PORT'] = os.environ.get("DB_PORT", 5432)
DATABASES['default']['USER'] = os.environ.get("DB_USER")
DATABASES['default']['NAME'] = os.environ.get("DB_NAME", "hawkpost_dev")
if 'DB_PASSWORD' in os.environ:
DATABASES['default']['PASSWORD'] = os.environ.get("DB_PASSWORD")
# <REPLACE_END> <REPLACE_OLD> "127.0.0.1"
EMAIL_PORT <REPLACE_NEW> os.environ.get("EMAIL_HOST", "127.0.0.1")
EMAIL_PORT <REPLACE_END> <REPLACE_OLD> 1025
<REPLACE_NEW> os.environ.get("EMAIL_PORT", 1025)
<REPLACE_END> <|endoftext|> from .common import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': "hawkpost_dev",
}
}
# If the DB_HOST was specified it is overriding the default connection
if 'DB_HOST' in os.environ:
DATABASES['default']['HOST'] = os.environ.get("DB_HOST")
DATABASES['default']['PORT'] = os.environ.get("DB_PORT", 5432)
DATABASES['default']['USER'] = os.environ.get("DB_USER")
DATABASES['default']['NAME'] = os.environ.get("DB_NAME", "hawkpost_dev")
if 'DB_PASSWORD' in os.environ:
DATABASES['default']['PASSWORD'] = os.environ.get("DB_PASSWORD")
# Development Applications
INSTALLED_APPS += (
'debug_toolbar',
'django_extensions'
)
EMAIL_HOST = os.environ.get("EMAIL_HOST", "127.0.0.1")
EMAIL_PORT = os.environ.get("EMAIL_PORT", 1025)
| Allow overriding database and mail_debug settings
Using environment variables to override default database connection
and mail_debug settings in development mode. This allows setting
the values needed by the Docker environment.
from .common import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': "hawkpost_dev",
}
}
# Development Applications
INSTALLED_APPS += (
'debug_toolbar',
'django_extensions'
)
EMAIL_HOST = "127.0.0.1"
EMAIL_PORT = 1025
|
09498335615b7e770f5976b9749d68050966501d | models/timeandplace.py | models/timeandplace.py | #!/usr/bin/env python3
from .base import Serializable
from .locations import Platform
from datetime import datetime
class TimeAndPlace(Serializable):
def __init__(self, platform=None, arrival=None, departure=None):
super().__init__()
self.platform = platform
self.arrival = arrival
self.departure = departure
self.passthrough = False
@classmethod
def _validate(cls):
return {
'platform': (None, Platform),
'arrival': (None, datetime),
'departure': (None, datetime),
'passthrough': bool
}
@property
def stop(self):
return self.platform.stop
def __eq__(self, other):
assert isinstance(other, TimeAndPlace)
return (self.platform == other.platform and
self.arrival == other.arrival and
self.departure == other.departure)
def __repr__(self):
return ('<TimeAndPlace %s %s %s>' % (self.arrival, self.departure, self.platform))
| #!/usr/bin/env python3
from .base import Serializable
from .locations import Platform
from .realtime import RealtimeTime
class TimeAndPlace(Serializable):
def __init__(self, platform=None, arrival=None, departure=None):
super().__init__()
self.platform = platform
self.arrival = arrival
self.departure = departure
self.passthrough = False
@classmethod
def _validate(cls):
return {
'platform': (None, Platform),
'arrival': (None, RealtimeTime),
'departure': (None, RealtimeTime),
'passthrough': bool
}
@property
def stop(self):
return self.platform.stop
def __eq__(self, other):
assert isinstance(other, TimeAndPlace)
return (self.platform == other.platform and
self.arrival == other.arrival and
self.departure == other.departure)
def __repr__(self):
return ('<TimeAndPlace %s %s %s>' % (self.arrival, self.departure, self.platform))
| Revert "TimeAndPlace no longer refers to realtime data" | Revert "TimeAndPlace no longer refers to realtime data"
This reverts commit cf92e191e3748c67102f142b411937517c5051f4.
| Python | apache-2.0 | NoMoKeTo/choo,NoMoKeTo/transit | <REPLACE_OLD> datetime <REPLACE_NEW> .realtime <REPLACE_END> <REPLACE_OLD> datetime
class <REPLACE_NEW> RealtimeTime
class <REPLACE_END> <REPLACE_OLD> datetime),
<REPLACE_NEW> RealtimeTime),
<REPLACE_END> <REPLACE_OLD> datetime),
<REPLACE_NEW> RealtimeTime),
<REPLACE_END> <|endoftext|> #!/usr/bin/env python3
from .base import Serializable
from .locations import Platform
from .realtime import RealtimeTime
class TimeAndPlace(Serializable):
def __init__(self, platform=None, arrival=None, departure=None):
super().__init__()
self.platform = platform
self.arrival = arrival
self.departure = departure
self.passthrough = False
@classmethod
def _validate(cls):
return {
'platform': (None, Platform),
'arrival': (None, RealtimeTime),
'departure': (None, RealtimeTime),
'passthrough': bool
}
@property
def stop(self):
return self.platform.stop
def __eq__(self, other):
assert isinstance(other, TimeAndPlace)
return (self.platform == other.platform and
self.arrival == other.arrival and
self.departure == other.departure)
def __repr__(self):
return ('<TimeAndPlace %s %s %s>' % (self.arrival, self.departure, self.platform))
| Revert "TimeAndPlace no longer refers to realtime data"
This reverts commit cf92e191e3748c67102f142b411937517c5051f4.
#!/usr/bin/env python3
from .base import Serializable
from .locations import Platform
from datetime import datetime
class TimeAndPlace(Serializable):
def __init__(self, platform=None, arrival=None, departure=None):
super().__init__()
self.platform = platform
self.arrival = arrival
self.departure = departure
self.passthrough = False
@classmethod
def _validate(cls):
return {
'platform': (None, Platform),
'arrival': (None, datetime),
'departure': (None, datetime),
'passthrough': bool
}
@property
def stop(self):
return self.platform.stop
def __eq__(self, other):
assert isinstance(other, TimeAndPlace)
return (self.platform == other.platform and
self.arrival == other.arrival and
self.departure == other.departure)
def __repr__(self):
return ('<TimeAndPlace %s %s %s>' % (self.arrival, self.departure, self.platform))
|
ee22ba999deb9213445112f4486a6080834ba036 | django/__init__.py | django/__init__.py | VERSION = (1, 0, 'post-release-SVN')
def get_version():
"Returns the version as a human-format string."
v = '.'.join([str(i) for i in VERSION[:-1]])
if VERSION[-1]:
from django.utils.version import get_svn_revision
v = '%s-%s-%s' % (v, VERSION[-1], get_svn_revision())
return v
| VERSION = (1, 1, 0, 'alpha', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
from django.utils.version import get_svn_revision
svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
version = "%s %s" % (version, svn_rev)
return version
| Update django.VERSION in trunk per previous discussion | Update django.VERSION in trunk per previous discussion
--HG--
extra : convert_revision : svn%3Abcc190cf-cafb-0310-a4f2-bffc1f526a37/django/trunk%409103
| Python | bsd-3-clause | adieu/django-nonrel,adieu/django-nonrel,adieu/django-nonrel | <INSERT> 1, <INSERT_END> <REPLACE_OLD> 'post-release-SVN')
def <REPLACE_NEW> 'alpha', 0)
def <REPLACE_END> <DELETE> "Returns the <DELETE_END> <DELETE> as a human-format string."
v <DELETE_END> <REPLACE_OLD> '.'.join([str(i) for i in VERSION[:-1]])
<REPLACE_NEW> '%s.%s' % (VERSION[0], VERSION[1])
<REPLACE_END> <REPLACE_OLD> VERSION[-1]:
<REPLACE_NEW> VERSION[2]:
<REPLACE_END> <INSERT> version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
<INSERT_END> <INSERT> svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
<INSERT_END> <REPLACE_OLD> v <REPLACE_NEW> version <REPLACE_END> <REPLACE_OLD> '%s-%s-%s' <REPLACE_NEW> "%s %s" <REPLACE_END> <REPLACE_OLD> (v, VERSION[-1], get_svn_revision())
<REPLACE_NEW> (version, svn_rev)
<REPLACE_END> <REPLACE_OLD> v
<REPLACE_NEW> version
<REPLACE_END> <|endoftext|> VERSION = (1, 1, 0, 'alpha', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if VERSION[3] != 'final':
version = '%s %s' % (version, VERSION[4])
from django.utils.version import get_svn_revision
svn_rev = get_svn_revision()
if svn_rev != u'SVN-unknown':
version = "%s %s" % (version, svn_rev)
return version
| Update django.VERSION in trunk per previous discussion
--HG--
extra : convert_revision : svn%3Abcc190cf-cafb-0310-a4f2-bffc1f526a37/django/trunk%409103
VERSION = (1, 0, 'post-release-SVN')
def get_version():
"Returns the version as a human-format string."
v = '.'.join([str(i) for i in VERSION[:-1]])
if VERSION[-1]:
from django.utils.version import get_svn_revision
v = '%s-%s-%s' % (v, VERSION[-1], get_svn_revision())
return v
|
5770dfc5b5df312dc15f0bc44437c0e62936d688 | events/migrations/0073_soft_delete_replaced_objects.py | events/migrations/0073_soft_delete_replaced_objects.py | # Generated by Django 2.2.9 on 2020-01-31 08:25
from django.db import migrations
def soft_delete_replaced_objects(Model, deleted_attr='deleted', replaced_by_attr='replaced_by'):
for obj in Model.objects.filter(**{f'{replaced_by_attr}__isnull': False, deleted_attr: False}):
print(f'Found an object that is replaced but not soft deleted: "{obj}". Soft deleting now.')
setattr(obj, deleted_attr, True)
obj.save()
def forwards(apps, schema_editor):
# Begin printing on a new line
print('')
Keyword = apps.get_model('events', 'Keyword')
Place = apps.get_model('events', 'Place')
Event = apps.get_model('events', 'Event')
soft_delete_replaced_objects(Keyword, deleted_attr='deprecated')
soft_delete_replaced_objects(Place)
soft_delete_replaced_objects(Event)
class Migration(migrations.Migration):
dependencies = [
('events', '0072_allow_replaced_by_blank'),
]
operations = [
migrations.RunPython(forwards, migrations.RunPython.noop)
]
| Add data migration that deletes replaced objects | Add data migration that deletes replaced objects
| Python | mit | City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents | <INSERT> # Generated by Django 2.2.9 on 2020-01-31 08:25
from django.db import migrations
def soft_delete_replaced_objects(Model, deleted_attr='deleted', replaced_by_attr='replaced_by'):
<INSERT_END> <INSERT> for obj in Model.objects.filter(**{f'{replaced_by_attr}__isnull': False, deleted_attr: False}):
print(f'Found an object that is replaced but not soft deleted: "{obj}". Soft deleting now.')
setattr(obj, deleted_attr, True)
obj.save()
def forwards(apps, schema_editor):
# Begin printing on a new line
print('')
Keyword = apps.get_model('events', 'Keyword')
Place = apps.get_model('events', 'Place')
Event = apps.get_model('events', 'Event')
soft_delete_replaced_objects(Keyword, deleted_attr='deprecated')
soft_delete_replaced_objects(Place)
soft_delete_replaced_objects(Event)
class Migration(migrations.Migration):
dependencies = [
('events', '0072_allow_replaced_by_blank'),
]
operations = [
migrations.RunPython(forwards, migrations.RunPython.noop)
]
<INSERT_END> <|endoftext|> # Generated by Django 2.2.9 on 2020-01-31 08:25
from django.db import migrations
def soft_delete_replaced_objects(Model, deleted_attr='deleted', replaced_by_attr='replaced_by'):
for obj in Model.objects.filter(**{f'{replaced_by_attr}__isnull': False, deleted_attr: False}):
print(f'Found an object that is replaced but not soft deleted: "{obj}". Soft deleting now.')
setattr(obj, deleted_attr, True)
obj.save()
def forwards(apps, schema_editor):
# Begin printing on a new line
print('')
Keyword = apps.get_model('events', 'Keyword')
Place = apps.get_model('events', 'Place')
Event = apps.get_model('events', 'Event')
soft_delete_replaced_objects(Keyword, deleted_attr='deprecated')
soft_delete_replaced_objects(Place)
soft_delete_replaced_objects(Event)
class Migration(migrations.Migration):
dependencies = [
('events', '0072_allow_replaced_by_blank'),
]
operations = [
migrations.RunPython(forwards, migrations.RunPython.noop)
]
| Add data migration that deletes replaced objects
|
|
74506160831ec44f29b82ca02ff131b00ce91847 | masters/master.chromiumos.tryserver/master_site_config.py | masters/master.chromiumos.tryserver/master_site_config.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumOSTryServer(Master.ChromiumOSBase):
project_name = 'ChromiumOS Try Server'
master_port = 8049
slave_port = 8149
master_port_alt = 8249
try_job_port = 8349
buildbot_url = 'http://chromegw/p/tryserver.chromiumos/'
repo_url_ext = 'https://chromium.googlesource.com/chromiumos/tryjobs.git'
repo_url_int = 'https://chrome-internal.googlesource.com/chromeos/tryjobs.git'
from_address = '[email protected]'
# The reply-to address to set for emails sent from the server.
reply_to = '[email protected]'
# Select tree status urls and codereview location.
base_app_url = 'https://chromiumos-status.appspot.com'
tree_status_url = base_app_url + '/status'
| # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumOSTryServer(Master.ChromiumOSBase):
project_name = 'ChromiumOS Try Server'
master_port = 8049
slave_port = 8149
master_port_alt = 8249
try_job_port = 8349
buildbot_url = 'https://uberchromegw.corp.google.com/p/tryserver.chromiumos/'
repo_url_ext = 'https://chromium.googlesource.com/chromiumos/tryjobs.git'
repo_url_int = 'https://chrome-internal.googlesource.com/chromeos/tryjobs.git'
from_address = '[email protected]'
# The reply-to address to set for emails sent from the server.
reply_to = '[email protected]'
# Select tree status urls and codereview location.
base_app_url = 'https://chromiumos-status.appspot.com'
tree_status_url = base_app_url + '/status'
| Use UberProxy URL for 'tryserver.chromiumos' | Use UberProxy URL for 'tryserver.chromiumos'
BUG=352897
TEST=None
Review URL: https://codereview.chromium.org/554383002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@291886 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | <REPLACE_OLD> 'http://chromegw/p/tryserver.chromiumos/'
<REPLACE_NEW> 'https://uberchromegw.corp.google.com/p/tryserver.chromiumos/'
<REPLACE_END> <|endoftext|> # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumOSTryServer(Master.ChromiumOSBase):
project_name = 'ChromiumOS Try Server'
master_port = 8049
slave_port = 8149
master_port_alt = 8249
try_job_port = 8349
buildbot_url = 'https://uberchromegw.corp.google.com/p/tryserver.chromiumos/'
repo_url_ext = 'https://chromium.googlesource.com/chromiumos/tryjobs.git'
repo_url_int = 'https://chrome-internal.googlesource.com/chromeos/tryjobs.git'
from_address = '[email protected]'
# The reply-to address to set for emails sent from the server.
reply_to = '[email protected]'
# Select tree status urls and codereview location.
base_app_url = 'https://chromiumos-status.appspot.com'
tree_status_url = base_app_url + '/status'
| Use UberProxy URL for 'tryserver.chromiumos'
BUG=352897
TEST=None
Review URL: https://codereview.chromium.org/554383002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@291886 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumOSTryServer(Master.ChromiumOSBase):
project_name = 'ChromiumOS Try Server'
master_port = 8049
slave_port = 8149
master_port_alt = 8249
try_job_port = 8349
buildbot_url = 'http://chromegw/p/tryserver.chromiumos/'
repo_url_ext = 'https://chromium.googlesource.com/chromiumos/tryjobs.git'
repo_url_int = 'https://chrome-internal.googlesource.com/chromeos/tryjobs.git'
from_address = '[email protected]'
# The reply-to address to set for emails sent from the server.
reply_to = '[email protected]'
# Select tree status urls and codereview location.
base_app_url = 'https://chromiumos-status.appspot.com'
tree_status_url = base_app_url + '/status'
|
83d45c0fa64da347eec6b96f46c5eb1fbfe516d4 | plugins/call_bad_permissions.py | plugins/call_bad_permissions.py | # -*- coding:utf-8 -*-
#
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Β Β Licensed under the Apache License, Version 2.0 (the "License"); you may
# Β Β not use this file except in compliance with the License. You may obtain
# Β Β a copy of the License at
#
# Β Β Β Β http://www.apache.org/licenses/LICENSE-2.0
#
# Β Β Unless required by applicable law or agreed to in writing, software
# Β Β distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# Β Β WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# Β Β License for the specific language governing permissions and limitations
# Β Β under the License.
import bandit
import stat
from bandit.test_selector import *
@checks_functions
def call_bad_permissions(context):
if 'chmod' in context.call_function_name:
if context.call_args_count == 2:
mode = context.get_call_arg_at_position(1)
if mode is not None and (mode & stat.S_IWOTH or mode & stat.S_IXGRP):
filename = context.get_call_arg_at_position(0)
if filename is None:
filename = 'NOT PARSED'
return(bandit.ERROR, 'Chmod setting a permissive mask %s on '
'file (%s).' % (oct(mode), filename))
| # -*- coding:utf-8 -*-
#
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Β Β Licensed under the Apache License, Version 2.0 (the "License"); you may
# Β Β not use this file except in compliance with the License. You may obtain
# Β Β a copy of the License at
#
# Β Β Β Β http://www.apache.org/licenses/LICENSE-2.0
#
# Β Β Unless required by applicable law or agreed to in writing, software
# Β Β distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# Β Β WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# Β Β License for the specific language governing permissions and limitations
# Β Β under the License.
import bandit
import stat
from bandit.test_selector import *
@checks_functions
def call_bad_permissions(context):
if 'chmod' in context.call_function_name:
if context.call_args_count == 2:
mode = context.get_call_arg_at_position(1)
if(mode is not None and type(mode) == int and
(mode & stat.S_IWOTH or mode & stat.S_IXGRP)):
filename = context.get_call_arg_at_position(0)
if filename is None:
filename = 'NOT PARSED'
return(bandit.ERROR, 'Chmod setting a permissive mask %s on '
'file (%s).' % (oct(mode), filename))
| Fix bug with permissions matching | Fix bug with permissions matching
| Python | apache-2.0 | chair6/bandit,stackforge/bandit,austin987/bandit,pombredanne/bandit,stackforge/bandit,pombredanne/bandit | <REPLACE_OLD> if mode <REPLACE_NEW> if(mode <REPLACE_END> <INSERT> type(mode) == int and
<INSERT_END> <REPLACE_OLD> stat.S_IXGRP):
<REPLACE_NEW> stat.S_IXGRP)):
<REPLACE_END> <|endoftext|> # -*- coding:utf-8 -*-
#
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Β Β Licensed under the Apache License, Version 2.0 (the "License"); you may
# Β Β not use this file except in compliance with the License. You may obtain
# Β Β a copy of the License at
#
# Β Β Β Β http://www.apache.org/licenses/LICENSE-2.0
#
# Β Β Unless required by applicable law or agreed to in writing, software
# Β Β distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# Β Β WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# Β Β License for the specific language governing permissions and limitations
# Β Β under the License.
import bandit
import stat
from bandit.test_selector import *
@checks_functions
def call_bad_permissions(context):
if 'chmod' in context.call_function_name:
if context.call_args_count == 2:
mode = context.get_call_arg_at_position(1)
if(mode is not None and type(mode) == int and
(mode & stat.S_IWOTH or mode & stat.S_IXGRP)):
filename = context.get_call_arg_at_position(0)
if filename is None:
filename = 'NOT PARSED'
return(bandit.ERROR, 'Chmod setting a permissive mask %s on '
'file (%s).' % (oct(mode), filename))
| Fix bug with permissions matching
# -*- coding:utf-8 -*-
#
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Β Β Licensed under the Apache License, Version 2.0 (the "License"); you may
# Β Β not use this file except in compliance with the License. You may obtain
# Β Β a copy of the License at
#
# Β Β Β Β http://www.apache.org/licenses/LICENSE-2.0
#
# Β Β Unless required by applicable law or agreed to in writing, software
# Β Β distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# Β Β WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# Β Β License for the specific language governing permissions and limitations
# Β Β under the License.
import bandit
import stat
from bandit.test_selector import *
@checks_functions
def call_bad_permissions(context):
if 'chmod' in context.call_function_name:
if context.call_args_count == 2:
mode = context.get_call_arg_at_position(1)
if mode is not None and (mode & stat.S_IWOTH or mode & stat.S_IXGRP):
filename = context.get_call_arg_at_position(0)
if filename is None:
filename = 'NOT PARSED'
return(bandit.ERROR, 'Chmod setting a permissive mask %s on '
'file (%s).' % (oct(mode), filename))
|
916b86865acf0297293e4a13f1da6838f9b2711f | scripts/lib/errors.py | scripts/lib/errors.py | """ ΠΠΏΠΎΠ²Π΅ΡΠ΅Π½ΠΈΠ΅ Π°Π΄ΠΌΠΈΠ½ΠΈΡΡΡΠ°ΡΠΎΡΠ° ΠΎ Π²ΠΎΠ·Π½ΠΈΠΊΡΠΈΡ
ΠΎΡΠΈΠ±ΠΊΠ°Ρ
"""
from traceback import format_exception, format_exc
from lib.config import emergency_id
from lib.commands import vk, api
class ErrorManager:
""" Π£ΠΏΡΠΎΡΠ΅Π½Π½ΠΎΠ΅ ΠΎΠΏΠΎΠ²Π΅ΡΠ΅Π½ΠΈΠ΅ ΠΎΠ± ΠΎΡΠΈΠ±ΠΊΠ°Ρ
str name: Π½Π°Π·Π²Π°Π½ΠΈΠ΅ ΡΠΊΡΠΈΠΏΡΠ° (ΠΎΠ±ΡΡΠ½ΠΎ ΡΠΊΠΎΡΠΎΡΠ΅Π½Π½ΠΎΠ΅)
ΠΡΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°Π½ΠΈΠ΅: with ErrorManager(name): main()
"""
def __init__(self, name):
self.name = name
def __enter__(self):
pass
def __exit__(self, *args):
if args[0] is not None:
sendErrorMessage(self.name)
def sendErrorMessage(name, exception=None):
""" ΠΡΠΏΠΎΠ»ΡΠ·ΡΠ΅Ρ Π»ΠΈΠ±ΠΎ ΠΏΠΎΠ»ΡΡΠ΅Π½Π½ΡΡ ΠΎΡΠΈΠ±ΠΊΡ, Π»ΠΈΠ±ΠΎ ΡΡ, ΡΡΠΎ Π²ΠΎΠ·Π½ΠΈΠΊΠ»Π° ΠΏΠΎΡΠ»Π΅Π΄Π½Π΅ΠΉ """
exception = format_error(exception)
message = "{}:\n{}".format(name, exception)
vk(api.messages.send, user_id=emergency_id, message=message)
def format_error(error):
if error is not None:
error_info = format_exception(type(error), error, error.__traceback__)
return "".join(error_info)
else:
return format_exc()
| """ ΠΠΏΠΎΠ²Π΅ΡΠ΅Π½ΠΈΠ΅ Π°Π΄ΠΌΠΈΠ½ΠΈΡΡΡΠ°ΡΠΎΡΠ° ΠΎ Π²ΠΎΠ·Π½ΠΈΠΊΡΠΈΡ
ΠΎΡΠΈΠ±ΠΊΠ°Ρ
"""
from traceback import format_exception, format_exc
from contextlib import contextmanager
from lib.config import emergency_id
from lib.commands import vk, api
@contextmanager
def ErrorManager(name):
""" Π£ΠΏΡΠΎΡΠ΅Π½Π½ΠΎΠ΅ ΠΎΠΏΠΎΠ²Π΅ΡΠ΅Π½ΠΈΠ΅ ΠΎΠ± ΠΎΡΠΈΠ±ΠΊΠ°Ρ
str name: Π½Π°Π·Π²Π°Π½ΠΈΠ΅ ΡΠΊΡΠΈΠΏΡΠ° (ΠΎΠ±ΡΡΠ½ΠΎ ΡΠΊΠΎΡΠΎΡΠ΅Π½Π½ΠΎΠ΅)
ΠΡΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°Π½ΠΈΠ΅: with ErrorManager(name): main()
"""
try:
yield
except Exception as e:
sendErrorMessage(name)
raise e
def sendErrorMessage(name, exception=None):
""" ΠΡΠΏΠΎΠ»ΡΠ·ΡΠ΅Ρ Π»ΠΈΠ±ΠΎ ΠΏΠΎΠ»ΡΡΠ΅Π½Π½ΡΡ ΠΎΡΠΈΠ±ΠΊΡ, Π»ΠΈΠ±ΠΎ ΡΡ, ΡΡΠΎ Π²ΠΎΠ·Π½ΠΈΠΊΠ»Π° ΠΏΠΎΡΠ»Π΅Π΄Π½Π΅ΠΉ """
exception = format_error(exception)
message = "{}:\n{}".format(name, exception)
vk(api.messages.send, user_id=emergency_id, message=message)
def format_error(error):
if error is not None:
error_info = format_exception(type(error), error, error.__traceback__)
return "".join(error_info)
else:
return format_exc()
| Change error class to function | Change error class to function
| Python | mit | Varabe/Guild-Manager | <INSERT> contextlib import contextmanager
from <INSERT_END> <REPLACE_OLD> api
class ErrorManager:
""" <REPLACE_NEW> api
@contextmanager
def ErrorManager(name):
""" <REPLACE_END> <REPLACE_OLD> ΠΎΡΠΈΠ±ΠΊΠ°Ρ
str <REPLACE_NEW> ΠΎΡΠΈΠ±ΠΊΠ°Ρ
str <REPLACE_END> <REPLACE_OLD> ΡΠΊΠΎΡΠΎΡΠ΅Π½Π½ΠΎΠ΅)
ΠΡΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°Π½ΠΈΠ΅: <REPLACE_NEW> ΡΠΊΠΎΡΠΎΡΠ΅Π½Π½ΠΎΠ΅)
ΠΡΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°Π½ΠΈΠ΅: <REPLACE_END> <REPLACE_OLD> main()
"""
def __init__(self, name):
self.name = name
def __enter__(self):
pass
def __exit__(self, *args):
if args[0] is not None:
sendErrorMessage(self.name)
def <REPLACE_NEW> main()
"""
try:
yield
except Exception as e:
sendErrorMessage(name)
raise e
def <REPLACE_END> <|endoftext|> """ ΠΠΏΠΎΠ²Π΅ΡΠ΅Π½ΠΈΠ΅ Π°Π΄ΠΌΠΈΠ½ΠΈΡΡΡΠ°ΡΠΎΡΠ° ΠΎ Π²ΠΎΠ·Π½ΠΈΠΊΡΠΈΡ
ΠΎΡΠΈΠ±ΠΊΠ°Ρ
"""
from traceback import format_exception, format_exc
from contextlib import contextmanager
from lib.config import emergency_id
from lib.commands import vk, api
@contextmanager
def ErrorManager(name):
""" Π£ΠΏΡΠΎΡΠ΅Π½Π½ΠΎΠ΅ ΠΎΠΏΠΎΠ²Π΅ΡΠ΅Π½ΠΈΠ΅ ΠΎΠ± ΠΎΡΠΈΠ±ΠΊΠ°Ρ
str name: Π½Π°Π·Π²Π°Π½ΠΈΠ΅ ΡΠΊΡΠΈΠΏΡΠ° (ΠΎΠ±ΡΡΠ½ΠΎ ΡΠΊΠΎΡΠΎΡΠ΅Π½Π½ΠΎΠ΅)
ΠΡΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°Π½ΠΈΠ΅: with ErrorManager(name): main()
"""
try:
yield
except Exception as e:
sendErrorMessage(name)
raise e
def sendErrorMessage(name, exception=None):
""" ΠΡΠΏΠΎΠ»ΡΠ·ΡΠ΅Ρ Π»ΠΈΠ±ΠΎ ΠΏΠΎΠ»ΡΡΠ΅Π½Π½ΡΡ ΠΎΡΠΈΠ±ΠΊΡ, Π»ΠΈΠ±ΠΎ ΡΡ, ΡΡΠΎ Π²ΠΎΠ·Π½ΠΈΠΊΠ»Π° ΠΏΠΎΡΠ»Π΅Π΄Π½Π΅ΠΉ """
exception = format_error(exception)
message = "{}:\n{}".format(name, exception)
vk(api.messages.send, user_id=emergency_id, message=message)
def format_error(error):
if error is not None:
error_info = format_exception(type(error), error, error.__traceback__)
return "".join(error_info)
else:
return format_exc()
| Change error class to function
""" ΠΠΏΠΎΠ²Π΅ΡΠ΅Π½ΠΈΠ΅ Π°Π΄ΠΌΠΈΠ½ΠΈΡΡΡΠ°ΡΠΎΡΠ° ΠΎ Π²ΠΎΠ·Π½ΠΈΠΊΡΠΈΡ
ΠΎΡΠΈΠ±ΠΊΠ°Ρ
"""
from traceback import format_exception, format_exc
from lib.config import emergency_id
from lib.commands import vk, api
class ErrorManager:
""" Π£ΠΏΡΠΎΡΠ΅Π½Π½ΠΎΠ΅ ΠΎΠΏΠΎΠ²Π΅ΡΠ΅Π½ΠΈΠ΅ ΠΎΠ± ΠΎΡΠΈΠ±ΠΊΠ°Ρ
str name: Π½Π°Π·Π²Π°Π½ΠΈΠ΅ ΡΠΊΡΠΈΠΏΡΠ° (ΠΎΠ±ΡΡΠ½ΠΎ ΡΠΊΠΎΡΠΎΡΠ΅Π½Π½ΠΎΠ΅)
ΠΡΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°Π½ΠΈΠ΅: with ErrorManager(name): main()
"""
def __init__(self, name):
self.name = name
def __enter__(self):
pass
def __exit__(self, *args):
if args[0] is not None:
sendErrorMessage(self.name)
def sendErrorMessage(name, exception=None):
""" ΠΡΠΏΠΎΠ»ΡΠ·ΡΠ΅Ρ Π»ΠΈΠ±ΠΎ ΠΏΠΎΠ»ΡΡΠ΅Π½Π½ΡΡ ΠΎΡΠΈΠ±ΠΊΡ, Π»ΠΈΠ±ΠΎ ΡΡ, ΡΡΠΎ Π²ΠΎΠ·Π½ΠΈΠΊΠ»Π° ΠΏΠΎΡΠ»Π΅Π΄Π½Π΅ΠΉ """
exception = format_error(exception)
message = "{}:\n{}".format(name, exception)
vk(api.messages.send, user_id=emergency_id, message=message)
def format_error(error):
if error is not None:
error_info = format_exception(type(error), error, error.__traceback__)
return "".join(error_info)
else:
return format_exc()
|
bea43337d9caa4e9a5271b66d951ae6547a23c80 | DjangoLibrary/middleware.py | DjangoLibrary/middleware.py | from django.contrib import auth
from django.contrib.auth.middleware import AuthenticationMiddleware
import base64
class AutologinAuthenticationMiddleware(AuthenticationMiddleware):
def process_request(self, request):
if 'autologin' not in request.COOKIES:
return
if request.COOKIES['autologin'] == '':
auth.logout(request)
return
autologin_cookie_value = base64.b64decode(request.COOKIES['autologin'])
autologin_cookie_value = autologin_cookie_value.decode('utf8')
username = autologin_cookie_value.split(':')[0]
password = autologin_cookie_value.split(':')[1]
user = auth.authenticate(username=username, password=password)
if user is not None:
if user.is_active:
auth.login(request, user)
| from django.contrib import auth
from django.contrib.auth.middleware import AuthenticationMiddleware
import base64
class AutologinAuthenticationMiddleware(AuthenticationMiddleware):
def process_request(self, request):
if 'autologin' not in request.COOKIES:
return
if request.COOKIES['autologin'] == '':
auth.logout(request)
return
autologin_cookie_value = base64.b64decode(request.COOKIES['autologin'])
# Py3 uses a bytes string here, so we need to decode to utf-8
autologin_cookie_value = autologin_cookie_value.decode('utf-8')
username = autologin_cookie_value.split(':')[0]
password = autologin_cookie_value.split(':')[1]
user = auth.authenticate(username=username, password=password)
if user is not None:
if user.is_active:
auth.login(request, user)
| Add a comment to py3 byte string decode. | Add a comment to py3 byte string decode.
| Python | apache-2.0 | kitconcept/robotframework-djangolibrary | <INSERT> # Py3 uses a bytes string here, so we need to decode to utf-8
<INSERT_END> <REPLACE_OLD> autologin_cookie_value.decode('utf8')
<REPLACE_NEW> autologin_cookie_value.decode('utf-8')
<REPLACE_END> <|endoftext|> from django.contrib import auth
from django.contrib.auth.middleware import AuthenticationMiddleware
import base64
class AutologinAuthenticationMiddleware(AuthenticationMiddleware):
def process_request(self, request):
if 'autologin' not in request.COOKIES:
return
if request.COOKIES['autologin'] == '':
auth.logout(request)
return
autologin_cookie_value = base64.b64decode(request.COOKIES['autologin'])
# Py3 uses a bytes string here, so we need to decode to utf-8
autologin_cookie_value = autologin_cookie_value.decode('utf-8')
username = autologin_cookie_value.split(':')[0]
password = autologin_cookie_value.split(':')[1]
user = auth.authenticate(username=username, password=password)
if user is not None:
if user.is_active:
auth.login(request, user)
| Add a comment to py3 byte string decode.
from django.contrib import auth
from django.contrib.auth.middleware import AuthenticationMiddleware
import base64
class AutologinAuthenticationMiddleware(AuthenticationMiddleware):
def process_request(self, request):
if 'autologin' not in request.COOKIES:
return
if request.COOKIES['autologin'] == '':
auth.logout(request)
return
autologin_cookie_value = base64.b64decode(request.COOKIES['autologin'])
autologin_cookie_value = autologin_cookie_value.decode('utf8')
username = autologin_cookie_value.split(':')[0]
password = autologin_cookie_value.split(':')[1]
user = auth.authenticate(username=username, password=password)
if user is not None:
if user.is_active:
auth.login(request, user)
|
d237c121955b7249e0e2ab5580d2abc2d19b0f25 | noveltorpedo/models.py | noveltorpedo/models.py | from django.db import models
class Author(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Story(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
contents = models.TextField(default='')
def __str__(self):
return self.title
| from django.db import models
class Author(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Story(models.Model):
authors = models.ManyToManyField(Author)
title = models.CharField(max_length=255)
contents = models.TextField(default='')
def __str__(self):
return self.title
| Allow a story to have many authors | Allow a story to have many authors
| Python | mit | NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo | <REPLACE_OLD> author <REPLACE_NEW> authors <REPLACE_END> <REPLACE_OLD> models.ForeignKey(Author, on_delete=models.CASCADE)
<REPLACE_NEW> models.ManyToManyField(Author)
<REPLACE_END> <|endoftext|> from django.db import models
class Author(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Story(models.Model):
authors = models.ManyToManyField(Author)
title = models.CharField(max_length=255)
contents = models.TextField(default='')
def __str__(self):
return self.title
| Allow a story to have many authors
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Story(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
contents = models.TextField(default='')
def __str__(self):
return self.title
|
d144e30d557ea2f4b03a2f0b7fb68f1cee54a602 | cla_backend/apps/legalaid/migrations/0023_migrate_contact_for_research_via_field.py | cla_backend/apps/legalaid/migrations/0023_migrate_contact_for_research_via_field.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from django.db.models import Q
def migrate_contact_for_research_via_field_data(apps, schema_editor):
ContactResearchMethod = apps.get_model("legalaid", "ContactResearchMethod")
research_methods = {method.method: method.id for method in ContactResearchMethod.objects.all()}
PersonalDetails = apps.get_model("legalaid", "PersonalDetails")
models = PersonalDetails.objects.exclude(Q(contact_for_research_via="") | Q(contact_for_research_via=None))
for model in models:
if not list(model.contact_for_research_methods.all()):
model.contact_for_research_methods = [research_methods.get(model.contact_for_research_via)]
model.save()
def rollback_migrate_contact_for_research_via_field_data(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [("legalaid", "0022_default_contact_for_research_methods")]
operations = [
migrations.RunPython(
migrate_contact_for_research_via_field_data, rollback_migrate_contact_for_research_via_field_data
)
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def migrate_contact_for_research_via_field_data(apps, schema_editor):
ContactResearchMethod = apps.get_model("legalaid", "ContactResearchMethod")
PersonalDetails = apps.get_model("legalaid", "PersonalDetails")
for method in ContactResearchMethod.objects.all():
details_qs = PersonalDetails.objects.filter(
contact_for_research_via=method.method, contact_for_research_methods__isnull=True
)
for details in details_qs:
details.contact_for_research_methods.add(method)
def rollback_migrate_contact_for_research_via_field_data(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [("legalaid", "0022_default_contact_for_research_methods")]
operations = [
migrations.RunPython(
migrate_contact_for_research_via_field_data, rollback_migrate_contact_for_research_via_field_data
)
]
| Simplify data migration and make it safe to rerun | Simplify data migration and make it safe to rerun
| Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend | <REPLACE_OLD> migrations
from django.db.models import Q
def <REPLACE_NEW> migrations
def <REPLACE_END> <DELETE> research_methods = {method.method: method.id for method in ContactResearchMethod.objects.all()}
<DELETE_END> <REPLACE_OLD> "PersonalDetails")
models = PersonalDetails.objects.exclude(Q(contact_for_research_via="") | Q(contact_for_research_via=None))
<REPLACE_NEW> "PersonalDetails")
<REPLACE_END> <REPLACE_OLD> model <REPLACE_NEW> method <REPLACE_END> <REPLACE_OLD> models:
<REPLACE_NEW> ContactResearchMethod.objects.all():
<REPLACE_END> <REPLACE_OLD> if not list(model.contact_for_research_methods.all()):
<REPLACE_NEW> details_qs = PersonalDetails.objects.filter(
<REPLACE_END> <REPLACE_OLD> model.contact_for_research_methods = [research_methods.get(model.contact_for_research_via)]
<REPLACE_NEW> contact_for_research_via=method.method, contact_for_research_methods__isnull=True
)
for details in details_qs:
<REPLACE_END> <REPLACE_OLD> model.save()
def <REPLACE_NEW> details.contact_for_research_methods.add(method)
def <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def migrate_contact_for_research_via_field_data(apps, schema_editor):
ContactResearchMethod = apps.get_model("legalaid", "ContactResearchMethod")
PersonalDetails = apps.get_model("legalaid", "PersonalDetails")
for method in ContactResearchMethod.objects.all():
details_qs = PersonalDetails.objects.filter(
contact_for_research_via=method.method, contact_for_research_methods__isnull=True
)
for details in details_qs:
details.contact_for_research_methods.add(method)
def rollback_migrate_contact_for_research_via_field_data(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [("legalaid", "0022_default_contact_for_research_methods")]
operations = [
migrations.RunPython(
migrate_contact_for_research_via_field_data, rollback_migrate_contact_for_research_via_field_data
)
]
| Simplify data migration and make it safe to rerun
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from django.db.models import Q
def migrate_contact_for_research_via_field_data(apps, schema_editor):
ContactResearchMethod = apps.get_model("legalaid", "ContactResearchMethod")
research_methods = {method.method: method.id for method in ContactResearchMethod.objects.all()}
PersonalDetails = apps.get_model("legalaid", "PersonalDetails")
models = PersonalDetails.objects.exclude(Q(contact_for_research_via="") | Q(contact_for_research_via=None))
for model in models:
if not list(model.contact_for_research_methods.all()):
model.contact_for_research_methods = [research_methods.get(model.contact_for_research_via)]
model.save()
def rollback_migrate_contact_for_research_via_field_data(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [("legalaid", "0022_default_contact_for_research_methods")]
operations = [
migrations.RunPython(
migrate_contact_for_research_via_field_data, rollback_migrate_contact_for_research_via_field_data
)
]
|
abb23c47f503197e005637ce220a07975dc01094 | recipes/spyder-line-profiler/run_test.py | recipes/spyder-line-profiler/run_test.py | from xvfbwrapper import Xvfb
vdisplay = Xvfb()
vdisplay.start()
import spyder_line_profiler
vdisplay.stop()
| """
Test whether spyder_line_profiler is installed
The test is only whether the module can be found. It does not attempt
to import the module because this needs an X server.
"""
import imp
imp.find_module('spyder_line_profiler')
| Use imp.find_module in test for spyder-line-profiler | Use imp.find_module in test for spyder-line-profiler
| Python | bsd-3-clause | jjhelmus/staged-recipes,igortg/staged-recipes,petrushy/staged-recipes,Cashalow/staged-recipes,patricksnape/staged-recipes,conda-forge/staged-recipes,NOAA-ORR-ERD/staged-recipes,petrushy/staged-recipes,synapticarbors/staged-recipes,grlee77/staged-recipes,larray-project/staged-recipes,shadowwalkersb/staged-recipes,patricksnape/staged-recipes,planetarypy/staged-recipes,basnijholt/staged-recipes,SylvainCorlay/staged-recipes,chrisburr/staged-recipes,hadim/staged-recipes,goanpeca/staged-recipes,guillochon/staged-recipes,chohner/staged-recipes,NOAA-ORR-ERD/staged-recipes,benvandyke/staged-recipes,larray-project/staged-recipes,gqmelo/staged-recipes,Cashalow/staged-recipes,chrisburr/staged-recipes,rvalieris/staged-recipes,birdsarah/staged-recipes,kwilcox/staged-recipes,mcs07/staged-recipes,hadim/staged-recipes,johanneskoester/staged-recipes,ocefpaf/staged-recipes,glemaitre/staged-recipes,mcs07/staged-recipes,koverholt/staged-recipes,igortg/staged-recipes,grlee77/staged-recipes,rmcgibbo/staged-recipes,JohnGreeley/staged-recipes,basnijholt/staged-recipes,SylvainCorlay/staged-recipes,chohner/staged-recipes,gqmelo/staged-recipes,dschreij/staged-recipes,jjhelmus/staged-recipes,rvalieris/staged-recipes,pmlandwehr/staged-recipes,jochym/staged-recipes,JohnGreeley/staged-recipes,mariusvniekerk/staged-recipes,birdsarah/staged-recipes,isuruf/staged-recipes,scopatz/staged-recipes,jakirkham/staged-recipes,Juanlu001/staged-recipes,sodre/staged-recipes,barkls/staged-recipes,johanneskoester/staged-recipes,ReimarBauer/staged-recipes,benvandyke/staged-recipes,guillochon/staged-recipes,conda-forge/staged-recipes,asmeurer/staged-recipes,koverholt/staged-recipes,sannykr/staged-recipes,ceholden/staged-recipes,stuertz/staged-recipes,cpaulik/staged-recipes,blowekamp/staged-recipes,dschreij/staged-recipes,ReimarBauer/staged-recipes,pmlandwehr/staged-recipes,sannykr/staged-recipes,ocefpaf/staged-recipes,goanpeca/staged-recipes,jochym/staged-recipes,mariusvniekerk/staged-recipes,isuruf/staged-recipes,ceholden/staged-recipes,blowekamp/staged-recipes,kwilcox/staged-recipes,Juanlu001/staged-recipes,scopatz/staged-recipes,rmcgibbo/staged-recipes,barkls/staged-recipes,shadowwalkersb/staged-recipes,sodre/staged-recipes,jakirkham/staged-recipes,planetarypy/staged-recipes,sodre/staged-recipes,asmeurer/staged-recipes,synapticarbors/staged-recipes,stuertz/staged-recipes,cpaulik/staged-recipes,glemaitre/staged-recipes | <REPLACE_OLD> from xvfbwrapper <REPLACE_NEW> """
Test whether spyder_line_profiler is installed
The test is only whether the module can be found. It does not attempt
to <REPLACE_END> <REPLACE_OLD> Xvfb
vdisplay = Xvfb()
vdisplay.start()
import spyder_line_profiler
vdisplay.stop()
<REPLACE_NEW> the module because this needs an X server.
"""
import imp
imp.find_module('spyder_line_profiler')
<REPLACE_END> <|endoftext|> """
Test whether spyder_line_profiler is installed
The test is only whether the module can be found. It does not attempt
to import the module because this needs an X server.
"""
import imp
imp.find_module('spyder_line_profiler')
| Use imp.find_module in test for spyder-line-profiler
from xvfbwrapper import Xvfb
vdisplay = Xvfb()
vdisplay.start()
import spyder_line_profiler
vdisplay.stop()
|
377d0634a77c63ce9e3d937f31bdd82ebe695cbb | ev3dev/auto.py | ev3dev/auto.py | import platform
# -----------------------------------------------------------------------------
# Guess platform we are running on
def current_platform():
machine = platform.machine()
if machine == 'armv5tejl':
return 'ev3'
elif machine == 'armv6l':
return 'brickpi'
else:
return 'unsupported'
if current_platform() == 'brickpi':
from .brickpi import *
else:
# Import ev3 by default, so that it is covered by documentation.
from .ev3 import *
| import platform
import sys
# -----------------------------------------------------------------------------
if sys.version_info < (3,4):
raise SystemError('Must be using Python 3.4 or higher')
# -----------------------------------------------------------------------------
# Guess platform we are running on
def current_platform():
machine = platform.machine()
if machine == 'armv5tejl':
return 'ev3'
elif machine == 'armv6l':
return 'brickpi'
else:
return 'unsupported'
# -----------------------------------------------------------------------------
if current_platform() == 'brickpi':
from .brickpi import *
else:
# Import ev3 by default, so that it is covered by documentation.
from .ev3 import *
| Enforce the use of Python 3.4 or higher | Enforce the use of Python 3.4 or higher
| Python | mit | rhempel/ev3dev-lang-python,dwalton76/ev3dev-lang-python,dwalton76/ev3dev-lang-python | <REPLACE_OLD> platform
# <REPLACE_NEW> platform
import sys
# -----------------------------------------------------------------------------
if sys.version_info < (3,4):
raise SystemError('Must be using Python 3.4 or higher')
# <REPLACE_END> <REPLACE_OLD> on
def <REPLACE_NEW> on
def <REPLACE_END> <REPLACE_OLD> 'unsupported'
if <REPLACE_NEW> 'unsupported'
# -----------------------------------------------------------------------------
if <REPLACE_END> <|endoftext|> import platform
import sys
# -----------------------------------------------------------------------------
if sys.version_info < (3,4):
raise SystemError('Must be using Python 3.4 or higher')
# -----------------------------------------------------------------------------
# Guess platform we are running on
def current_platform():
machine = platform.machine()
if machine == 'armv5tejl':
return 'ev3'
elif machine == 'armv6l':
return 'brickpi'
else:
return 'unsupported'
# -----------------------------------------------------------------------------
if current_platform() == 'brickpi':
from .brickpi import *
else:
# Import ev3 by default, so that it is covered by documentation.
from .ev3 import *
| Enforce the use of Python 3.4 or higher
import platform
# -----------------------------------------------------------------------------
# Guess platform we are running on
def current_platform():
machine = platform.machine()
if machine == 'armv5tejl':
return 'ev3'
elif machine == 'armv6l':
return 'brickpi'
else:
return 'unsupported'
if current_platform() == 'brickpi':
from .brickpi import *
else:
# Import ev3 by default, so that it is covered by documentation.
from .ev3 import *
|
4a81ee90a39c4831dca186ae269184c703ddbf2e | src/autobot/src/udpRemote.py | src/autobot/src/udpRemote.py | #!/usr/bin/env python
import rospy
import socket
from autobot.msg import drive_param
"""
Warning: This code has not been tested at all
Protocol could be comma delimited
Vaa.aa;Abb.bb
TODO
- [ ] Unit test
- [ ] Define protocol
- [ ] Use select() for non-blocking operation
- [ ] Use a timeout for setting drive/angle to '0' (safety)
"""
def parseCommand(cmd, pub, driveParam):
"""
pass in Paa.aa where P is the ID of the command
"""
val = 0.0
# first test to see if able to parse the value from substring
try:
val = float(cmd.substring(1))
except ValueError:
return driveParam # unable to parse, bail
if cmd[0] == 'V':
driveParam.velocity = val
elif cmd[0] == 'A':
driveParam.angle = val
return driveParam # valid drive parameter parsed
def parseMessage(msg, pub):
"""
Attempts to parse a message for a proper command string
If the command string is valid, a drive parameter will be
published
"""
driveParam = drive_param()
if ";" in msg:
arr = msg.split(";")
for cmd in arr:
driveParam = parseCommand(cmd, driveParam)
pub.publish(driveParam)
else:
pass
def main():
UDP_IP = "127.0.0.1" # loopback
UDP_PORT = 11156
rospy.init_node("udpRemote", anonymous=True)
pub = rospy.Publisher("drive_parameters", drive_param, queue_size=10)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024)
parseMessage(str(data, "utf-8"), pub)
if __name__ == "__main__":
main()
| Add code for udp remote | Add code for udp remote
This code is untested and is still WIP.
| Python | mit | atkvo/masters-bot,atkvo/masters-bot,atkvo/masters-bot,atkvo/masters-bot,atkvo/masters-bot | <REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/env python
import rospy
import socket
from autobot.msg import drive_param
"""
Warning: This code has not been tested at all
Protocol could be comma delimited
Vaa.aa;Abb.bb
TODO
- [ ] Unit test
- [ ] Define protocol
- [ ] Use select() for non-blocking operation
- [ ] Use a timeout for setting drive/angle to '0' (safety)
"""
def parseCommand(cmd, pub, driveParam):
"""
pass in Paa.aa where P is the ID of the command
"""
val = 0.0
# first test to see if able to parse the value from substring
try:
val = float(cmd.substring(1))
except ValueError:
return driveParam # unable to parse, bail
if cmd[0] == 'V':
driveParam.velocity = val
elif cmd[0] == 'A':
driveParam.angle = val
return driveParam # valid drive parameter parsed
def parseMessage(msg, pub):
"""
Attempts to parse a message for a proper command string
If the command string is valid, a drive parameter will be
published
"""
driveParam = drive_param()
if ";" in msg:
arr = msg.split(";")
for cmd in arr:
driveParam = parseCommand(cmd, driveParam)
pub.publish(driveParam)
else:
pass
def main():
UDP_IP = "127.0.0.1" # loopback
UDP_PORT = 11156
rospy.init_node("udpRemote", anonymous=True)
pub = rospy.Publisher("drive_parameters", drive_param, queue_size=10)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024)
parseMessage(str(data, "utf-8"), pub)
if __name__ == "__main__":
main()
<REPLACE_END> <|endoftext|> #!/usr/bin/env python
import rospy
import socket
from autobot.msg import drive_param
"""
Warning: This code has not been tested at all
Protocol could be comma delimited
Vaa.aa;Abb.bb
TODO
- [ ] Unit test
- [ ] Define protocol
- [ ] Use select() for non-blocking operation
- [ ] Use a timeout for setting drive/angle to '0' (safety)
"""
def parseCommand(cmd, pub, driveParam):
"""
pass in Paa.aa where P is the ID of the command
"""
val = 0.0
# first test to see if able to parse the value from substring
try:
val = float(cmd.substring(1))
except ValueError:
return driveParam # unable to parse, bail
if cmd[0] == 'V':
driveParam.velocity = val
elif cmd[0] == 'A':
driveParam.angle = val
return driveParam # valid drive parameter parsed
def parseMessage(msg, pub):
"""
Attempts to parse a message for a proper command string
If the command string is valid, a drive parameter will be
published
"""
driveParam = drive_param()
if ";" in msg:
arr = msg.split(";")
for cmd in arr:
driveParam = parseCommand(cmd, driveParam)
pub.publish(driveParam)
else:
pass
def main():
UDP_IP = "127.0.0.1" # loopback
UDP_PORT = 11156
rospy.init_node("udpRemote", anonymous=True)
pub = rospy.Publisher("drive_parameters", drive_param, queue_size=10)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024)
parseMessage(str(data, "utf-8"), pub)
if __name__ == "__main__":
main()
| Add code for udp remote
This code is untested and is still WIP.
|
|
1ce040e0642c6dcc888b3787f7448c65ba0318f8 | logos_setup_data/__openerp__.py | logos_setup_data/__openerp__.py | # -*- coding: utf-8 -*-
{
'name': 'Logos Set Up Data',
'version': '1.0',
'category': 'Accounting',
'sequence': 14,
'summary': '',
'description': """
Logos Set Up Data
=====================
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'crm',
'purchase',
'sale',
'portal_sale_distributor',
'website_sale',
# 'base_location',
'price_security',
'product_price_currency',
'logos_product_attributes',
'product_catalog_aeroo_report',
],
'data': [
# Para arreglar error
'security/ir.model.access.csv',
'security/logos_security.xml',
'report_data.xml',
'product_view.xml',
'crm_view.xml'
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | # -*- coding: utf-8 -*-
{
'name': 'Logos Set Up Data',
'version': '1.0',
'category': 'Accounting',
'sequence': 14,
'summary': '',
'description': """
Logos Set Up Data
=====================
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'crm',
'purchase',
'sale',
'portal_sale_distributor',
'website_sale',
'base_location',
'price_security',
'product_price_currency',
'logos_product_attributes',
'product_catalog_aeroo_report',
],
'data': [
# Para arreglar error
'security/ir.model.access.csv',
'security/logos_security.xml',
'report_data.xml',
'product_view.xml',
'crm_view.xml'
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | ADD base location to logos as it is necesary for security rules | ADD base location to logos as it is necesary for security rules
| Python | agpl-3.0 | ingadhoc/odoo-personalizations,adhoc-dev/odoo-personalizations | <DELETE> # <DELETE_END> <|endoftext|> # -*- coding: utf-8 -*-
{
'name': 'Logos Set Up Data',
'version': '1.0',
'category': 'Accounting',
'sequence': 14,
'summary': '',
'description': """
Logos Set Up Data
=====================
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'crm',
'purchase',
'sale',
'portal_sale_distributor',
'website_sale',
'base_location',
'price_security',
'product_price_currency',
'logos_product_attributes',
'product_catalog_aeroo_report',
],
'data': [
# Para arreglar error
'security/ir.model.access.csv',
'security/logos_security.xml',
'report_data.xml',
'product_view.xml',
'crm_view.xml'
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | ADD base location to logos as it is necesary for security rules
# -*- coding: utf-8 -*-
{
'name': 'Logos Set Up Data',
'version': '1.0',
'category': 'Accounting',
'sequence': 14,
'summary': '',
'description': """
Logos Set Up Data
=====================
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'crm',
'purchase',
'sale',
'portal_sale_distributor',
'website_sale',
# 'base_location',
'price_security',
'product_price_currency',
'logos_product_attributes',
'product_catalog_aeroo_report',
],
'data': [
# Para arreglar error
'security/ir.model.access.csv',
'security/logos_security.xml',
'report_data.xml',
'product_view.xml',
'crm_view.xml'
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
c7785ff4367de929392b85f73a396e987cfe4606 | apps/chats/models.py | apps/chats/models.py | from django.db import models
from django.contrib.auth.models import User
from django.utils.text import truncate_words
from automatic_timestamps.models import TimestampModel
class Chat(TimestampModel):
"""
A chat is a single or multi-line text excerpt from a chat (usually
purposefully out of context) posted by a user. It is often
view-restricted to specific groups.
"""
# A chat without any associated Friend Groups is considered public and will
# be viewable to the entire world!
friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True)
posted_by = models.ForeignKey(User)
text = models.TextField()
def __unicode__(self):
"""Return the first six words from this chat's text field."""
return truncate_words(self.text, 6)
| from django.db import models
from django.contrib.auth.models import User
from django.utils.text import truncate_words
from automatic_timestamps.models import TimestampModel
class Chat(TimestampModel):
"""
A chat is a single or multi-line text excerpt from a chat (usually
purposefully out of context) posted by a user. It is often
view-restricted to specific groups.
"""
# A chat without any associated Friend Groups is considered public and will
# be viewable to the entire world!
friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True)
posted_by = models.ForeignKey(User)
text = models.TextField()
def as_html(self, tag='div'):
"""
Return an HTML representation of this chat, including tags marking
the author and text selection accordingly.
Use the tag argument to customize the tag that wraps each line in a chat.
"""
html = u''
for line in self.text.splitlines():
line_sections = line.split(': ', 1)
if len(line_sections) > 1:
html += u'<{tag} class="line"><span class="author">{author}</span>: <span class="text">{text}</span></{tag}>'.format(
author=line_sections[0],
tag=tag,
text=line_sections[1],
)
else:
html += u'<{tag} class="no-author line"><span class="text">{text}</span></{tag}>'.format(
tag=tag,
text=line_sections[0],
)
return html
def __unicode__(self):
"""Return the first six words from this chat's text field."""
return truncate_words(self.text, 6)
| Add HTML representation of chat | Add HTML representation of chat
| Python | mit | tofumatt/quotes,tofumatt/quotes | <INSERT> as_html(self, tag='div'):
"""
Return an HTML representation of this chat, including tags marking
the author and text selection accordingly.
Use the tag argument to customize the tag that wraps each line in a chat.
"""
html = u''
for line in self.text.splitlines():
line_sections = line.split(': ', 1)
if len(line_sections) > 1:
html += u'<{tag} class="line"><span class="author">{author}</span>: <span class="text">{text}</span></{tag}>'.format(
author=line_sections[0],
tag=tag,
text=line_sections[1],
)
else:
html += u'<{tag} class="no-author line"><span class="text">{text}</span></{tag}>'.format(
tag=tag,
text=line_sections[0],
)
return html
def <INSERT_END> <|endoftext|> from django.db import models
from django.contrib.auth.models import User
from django.utils.text import truncate_words
from automatic_timestamps.models import TimestampModel
class Chat(TimestampModel):
"""
A chat is a single or multi-line text excerpt from a chat (usually
purposefully out of context) posted by a user. It is often
view-restricted to specific groups.
"""
# A chat without any associated Friend Groups is considered public and will
# be viewable to the entire world!
friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True)
posted_by = models.ForeignKey(User)
text = models.TextField()
def as_html(self, tag='div'):
"""
Return an HTML representation of this chat, including tags marking
the author and text selection accordingly.
Use the tag argument to customize the tag that wraps each line in a chat.
"""
html = u''
for line in self.text.splitlines():
line_sections = line.split(': ', 1)
if len(line_sections) > 1:
html += u'<{tag} class="line"><span class="author">{author}</span>: <span class="text">{text}</span></{tag}>'.format(
author=line_sections[0],
tag=tag,
text=line_sections[1],
)
else:
html += u'<{tag} class="no-author line"><span class="text">{text}</span></{tag}>'.format(
tag=tag,
text=line_sections[0],
)
return html
def __unicode__(self):
"""Return the first six words from this chat's text field."""
return truncate_words(self.text, 6)
| Add HTML representation of chat
from django.db import models
from django.contrib.auth.models import User
from django.utils.text import truncate_words
from automatic_timestamps.models import TimestampModel
class Chat(TimestampModel):
"""
A chat is a single or multi-line text excerpt from a chat (usually
purposefully out of context) posted by a user. It is often
view-restricted to specific groups.
"""
# A chat without any associated Friend Groups is considered public and will
# be viewable to the entire world!
friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True)
posted_by = models.ForeignKey(User)
text = models.TextField()
def __unicode__(self):
"""Return the first six words from this chat's text field."""
return truncate_words(self.text, 6)
|
138aa351b3dbe95f3cdebf01dbd3c75f1ce3fac2 | src/ggrc/fulltext/sql.py | src/ggrc/fulltext/sql.py | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: [email protected]
# Maintained By: [email protected]
from ggrc import db
from . import Indexer
class SqlIndexer(Indexer):
def create_record(self, record, commit=True):
for k,v in record.properties.items():
db.session.add(self.record_type(
key=record.key,
type=record.type,
context_id=record.context_id,
tags=record.tags,
property=k,
content=v,
))
if commit:
db.session.commit()
def update_record(self, record, commit=True):
self.delete_record(record.key, commit=False)
self.create_record(record, commit=commit)
def delete_record(self, key, type, commit=True):
db.session.query(self.record_type).filter(\
self.record_type.key == key,
self.record_type.type == type).delete()
if commit:
db.session.commit()
def delete_all_records(self, commit=True):
db.session.query(self.record_type).delete()
if commit:
db.session.commit()
| # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: [email protected]
# Maintained By: [email protected]
from ggrc import db
from . import Indexer
class SqlIndexer(Indexer):
def create_record(self, record, commit=True):
for k,v in record.properties.items():
db.session.add(self.record_type(
key=record.key,
type=record.type,
context_id=record.context_id,
tags=record.tags,
property=k,
content=v,
))
if commit:
db.session.commit()
def update_record(self, record, commit=True):
self.delete_record(record.key, record.type, commit=False)
self.create_record(record, commit=commit)
def delete_record(self, key, type, commit=True):
db.session.query(self.record_type).filter(\
self.record_type.key == key,
self.record_type.type == type).delete()
if commit:
db.session.commit()
def delete_all_records(self, commit=True):
db.session.query(self.record_type).delete()
if commit:
db.session.commit()
| Fix test broken due to delete_record change | Fix test broken due to delete_record change
| Python | apache-2.0 | kr41/ggrc-core,uskudnik/ggrc-core,vladan-m/ggrc-core,AleksNeStu/ggrc-core,prasannav7/ggrc-core,josthkko/ggrc-core,vladan-m/ggrc-core,hyperNURb/ggrc-core,vladan-m/ggrc-core,uskudnik/ggrc-core,jmakov/ggrc-core,NejcZupec/ggrc-core,hyperNURb/ggrc-core,andrei-karalionak/ggrc-core,hasanalom/ggrc-core,selahssea/ggrc-core,AleksNeStu/ggrc-core,hyperNURb/ggrc-core,josthkko/ggrc-core,jmakov/ggrc-core,hasanalom/ggrc-core,prasannav7/ggrc-core,NejcZupec/ggrc-core,kr41/ggrc-core,selahssea/ggrc-core,edofic/ggrc-core,prasannav7/ggrc-core,kr41/ggrc-core,edofic/ggrc-core,j0gurt/ggrc-core,AleksNeStu/ggrc-core,kr41/ggrc-core,uskudnik/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core,jmakov/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,josthkko/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,selahssea/ggrc-core,hasanalom/ggrc-core,vladan-m/ggrc-core,hasanalom/ggrc-core,VinnieJohns/ggrc-core,uskudnik/ggrc-core,NejcZupec/ggrc-core,uskudnik/ggrc-core,selahssea/ggrc-core,josthkko/ggrc-core,andrei-karalionak/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,prasannav7/ggrc-core,jmakov/ggrc-core,plamut/ggrc-core,vladan-m/ggrc-core,hyperNURb/ggrc-core,edofic/ggrc-core,plamut/ggrc-core,hasanalom/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,jmakov/ggrc-core,j0gurt/ggrc-core,NejcZupec/ggrc-core,edofic/ggrc-core,hyperNURb/ggrc-core | <INSERT> record.type, <INSERT_END> <|endoftext|> # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: [email protected]
# Maintained By: [email protected]
from ggrc import db
from . import Indexer
class SqlIndexer(Indexer):
def create_record(self, record, commit=True):
for k,v in record.properties.items():
db.session.add(self.record_type(
key=record.key,
type=record.type,
context_id=record.context_id,
tags=record.tags,
property=k,
content=v,
))
if commit:
db.session.commit()
def update_record(self, record, commit=True):
self.delete_record(record.key, record.type, commit=False)
self.create_record(record, commit=commit)
def delete_record(self, key, type, commit=True):
db.session.query(self.record_type).filter(\
self.record_type.key == key,
self.record_type.type == type).delete()
if commit:
db.session.commit()
def delete_all_records(self, commit=True):
db.session.query(self.record_type).delete()
if commit:
db.session.commit()
| Fix test broken due to delete_record change
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: [email protected]
# Maintained By: [email protected]
from ggrc import db
from . import Indexer
class SqlIndexer(Indexer):
def create_record(self, record, commit=True):
for k,v in record.properties.items():
db.session.add(self.record_type(
key=record.key,
type=record.type,
context_id=record.context_id,
tags=record.tags,
property=k,
content=v,
))
if commit:
db.session.commit()
def update_record(self, record, commit=True):
self.delete_record(record.key, commit=False)
self.create_record(record, commit=commit)
def delete_record(self, key, type, commit=True):
db.session.query(self.record_type).filter(\
self.record_type.key == key,
self.record_type.type == type).delete()
if commit:
db.session.commit()
def delete_all_records(self, commit=True):
db.session.query(self.record_type).delete()
if commit:
db.session.commit()
|
79bf320f18db1b1dc89383a1c8e2f1080391c56c | tests/zeus/api/resources/test_revision_artifacts.py | tests/zeus/api/resources/test_revision_artifacts.py | from datetime import timedelta
from zeus import factories
from zeus.models import RepositoryAccess, RepositoryBackend, RepositoryProvider
from zeus.utils import timezone
def test_revision_artifacts(
client, db_session, default_login, default_user, git_repo_config
):
repo = factories.RepositoryFactory.create(
backend=RepositoryBackend.git,
provider=RepositoryProvider.github,
url=git_repo_config.url,
)
db_session.add(RepositoryAccess(user=default_user, repository=repo))
db_session.flush()
revision = factories.RevisionFactory.create(
sha=git_repo_config.commits[0], repository=repo
)
source = factories.SourceFactory.create(revision=revision)
factories.BuildFactory.create(
source=source, date_created=timezone.now() - timedelta(minutes=1)
)
build = factories.BuildFactory.create(source=source, date_created=timezone.now())
job = factories.JobFactory.create(build=build)
artifact = factories.ArtifactFactory.create(job=job)
resp = client.get(
"/api/repos/{}/revisions/{}/artifacts".format(
repo.get_full_name(), revision.sha
)
)
assert resp.status_code == 200
data = resp.json()
assert len(data) == 1
assert data[0]["id"] == str(artifact.id)
| Add coverage for revision artifacts endpoint | test: Add coverage for revision artifacts endpoint
| Python | apache-2.0 | getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus | <INSERT> from datetime import timedelta
from zeus import factories
from zeus.models import RepositoryAccess, RepositoryBackend, RepositoryProvider
from zeus.utils import timezone
def test_revision_artifacts(
<INSERT_END> <INSERT> client, db_session, default_login, default_user, git_repo_config
):
repo = factories.RepositoryFactory.create(
backend=RepositoryBackend.git,
provider=RepositoryProvider.github,
url=git_repo_config.url,
)
db_session.add(RepositoryAccess(user=default_user, repository=repo))
db_session.flush()
revision = factories.RevisionFactory.create(
sha=git_repo_config.commits[0], repository=repo
)
source = factories.SourceFactory.create(revision=revision)
factories.BuildFactory.create(
source=source, date_created=timezone.now() - timedelta(minutes=1)
)
build = factories.BuildFactory.create(source=source, date_created=timezone.now())
job = factories.JobFactory.create(build=build)
artifact = factories.ArtifactFactory.create(job=job)
resp = client.get(
"/api/repos/{}/revisions/{}/artifacts".format(
repo.get_full_name(), revision.sha
)
)
assert resp.status_code == 200
data = resp.json()
assert len(data) == 1
assert data[0]["id"] == str(artifact.id)
<INSERT_END> <|endoftext|> from datetime import timedelta
from zeus import factories
from zeus.models import RepositoryAccess, RepositoryBackend, RepositoryProvider
from zeus.utils import timezone
def test_revision_artifacts(
client, db_session, default_login, default_user, git_repo_config
):
repo = factories.RepositoryFactory.create(
backend=RepositoryBackend.git,
provider=RepositoryProvider.github,
url=git_repo_config.url,
)
db_session.add(RepositoryAccess(user=default_user, repository=repo))
db_session.flush()
revision = factories.RevisionFactory.create(
sha=git_repo_config.commits[0], repository=repo
)
source = factories.SourceFactory.create(revision=revision)
factories.BuildFactory.create(
source=source, date_created=timezone.now() - timedelta(minutes=1)
)
build = factories.BuildFactory.create(source=source, date_created=timezone.now())
job = factories.JobFactory.create(build=build)
artifact = factories.ArtifactFactory.create(job=job)
resp = client.get(
"/api/repos/{}/revisions/{}/artifacts".format(
repo.get_full_name(), revision.sha
)
)
assert resp.status_code == 200
data = resp.json()
assert len(data) == 1
assert data[0]["id"] == str(artifact.id)
| test: Add coverage for revision artifacts endpoint
|
|
fbdfb3de379af44880b928b6779a2edb578fb987 | changes/api/serializer/models/plan.py | changes/api/serializer/models/plan.py | import json
from changes.api.serializer import Serializer, register
from changes.models import Plan, Step
@register(Plan)
class PlanSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'steps': list(instance.steps),
'dateCreated': instance.date_created,
'dateModified': instance.date_modified,
}
@register(Step)
class StepSerializer(Serializer):
def serialize(self, instance, attrs):
implementation = instance.get_implementation()
return {
'id': instance.id.hex,
'implementation': instance.implementation,
'order': instance.order,
'name': implementation.get_label() if implementation else '',
'data': json.dumps(dict(instance.data)),
'dateCreated': instance.date_created,
}
| import json
from changes.api.serializer import Serializer, register
from changes.models import Plan, Step
@register(Plan)
class PlanSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'steps': list(instance.steps),
'dateCreated': instance.date_created,
'dateModified': instance.date_modified,
}
@register(Step)
class StepSerializer(Serializer):
def serialize(self, instance, attrs):
implementation = instance.get_implementation()
return {
'id': instance.id.hex,
'implementation': instance.implementation,
'order': instance.order,
'name': implementation.get_label() if implementation else '',
'data': json.dumps(dict(instance.data or {})),
'dateCreated': instance.date_created,
}
| Handle optional value in step.data | Handle optional value in step.data
| Python | apache-2.0 | dropbox/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,dropbox/changes | <REPLACE_OLD> json.dumps(dict(instance.data)),
<REPLACE_NEW> json.dumps(dict(instance.data or {})),
<REPLACE_END> <|endoftext|> import json
from changes.api.serializer import Serializer, register
from changes.models import Plan, Step
@register(Plan)
class PlanSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'steps': list(instance.steps),
'dateCreated': instance.date_created,
'dateModified': instance.date_modified,
}
@register(Step)
class StepSerializer(Serializer):
def serialize(self, instance, attrs):
implementation = instance.get_implementation()
return {
'id': instance.id.hex,
'implementation': instance.implementation,
'order': instance.order,
'name': implementation.get_label() if implementation else '',
'data': json.dumps(dict(instance.data or {})),
'dateCreated': instance.date_created,
}
| Handle optional value in step.data
import json
from changes.api.serializer import Serializer, register
from changes.models import Plan, Step
@register(Plan)
class PlanSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'steps': list(instance.steps),
'dateCreated': instance.date_created,
'dateModified': instance.date_modified,
}
@register(Step)
class StepSerializer(Serializer):
def serialize(self, instance, attrs):
implementation = instance.get_implementation()
return {
'id': instance.id.hex,
'implementation': instance.implementation,
'order': instance.order,
'name': implementation.get_label() if implementation else '',
'data': json.dumps(dict(instance.data)),
'dateCreated': instance.date_created,
}
|
8f5849a90c63c82b036e21d36b9d77b20e1aa60b | src/pretix/testutils/settings.py | src/pretix/testutils/settings.py | import atexit
import os
import tempfile
tmpdir = tempfile.TemporaryDirectory()
os.environ.setdefault('DATA_DIR', tmpdir.name)
from pretix.settings import * # NOQA
DATA_DIR = tmpdir.name
LOG_DIR = os.path.join(DATA_DIR, 'logs')
MEDIA_ROOT = os.path.join(DATA_DIR, 'media')
atexit.register(tmpdir.cleanup)
EMAIL_BACKEND = 'django.core.mail.outbox'
COMPRESS_ENABLED = COMPRESS_OFFLINE = False
DEBUG = True
PASSWORD_HASHERS = ['django.contrib.auth.hashers.MD5PasswordHasher']
# Disable celery
CELERY_ALWAYS_EAGER = True
HAS_CELERY = False
# Don't use redis
SESSION_ENGINE = "django.contrib.sessions.backends.db"
HAS_REDIS = False
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
| import atexit
import os
import tempfile
tmpdir = tempfile.TemporaryDirectory()
os.environ.setdefault('DATA_DIR', tmpdir.name)
from pretix.settings import * # NOQA
DATA_DIR = tmpdir.name
LOG_DIR = os.path.join(DATA_DIR, 'logs')
MEDIA_ROOT = os.path.join(DATA_DIR, 'media')
atexit.register(tmpdir.cleanup)
EMAIL_BACKEND = 'django.core.mail.outbox'
COMPRESS_ENABLED = COMPRESS_OFFLINE = False
DEBUG = True
PASSWORD_HASHERS = ['django.contrib.auth.hashers.MD5PasswordHasher']
# Disable celery
CELERY_ALWAYS_EAGER = True
HAS_CELERY = False
# Don't use redis
SESSION_ENGINE = "django.contrib.sessions.backends.db"
HAS_REDIS = False
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
}
| Test on SQLite if not configured otherwise | Test on SQLite if not configured otherwise
| Python | apache-2.0 | Flamacue/pretix,Flamacue/pretix,Flamacue/pretix,Flamacue/pretix | <INSERT> }
}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
<INSERT_END> <|endoftext|> import atexit
import os
import tempfile
tmpdir = tempfile.TemporaryDirectory()
os.environ.setdefault('DATA_DIR', tmpdir.name)
from pretix.settings import * # NOQA
DATA_DIR = tmpdir.name
LOG_DIR = os.path.join(DATA_DIR, 'logs')
MEDIA_ROOT = os.path.join(DATA_DIR, 'media')
atexit.register(tmpdir.cleanup)
EMAIL_BACKEND = 'django.core.mail.outbox'
COMPRESS_ENABLED = COMPRESS_OFFLINE = False
DEBUG = True
PASSWORD_HASHERS = ['django.contrib.auth.hashers.MD5PasswordHasher']
# Disable celery
CELERY_ALWAYS_EAGER = True
HAS_CELERY = False
# Don't use redis
SESSION_ENGINE = "django.contrib.sessions.backends.db"
HAS_REDIS = False
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
}
| Test on SQLite if not configured otherwise
import atexit
import os
import tempfile
tmpdir = tempfile.TemporaryDirectory()
os.environ.setdefault('DATA_DIR', tmpdir.name)
from pretix.settings import * # NOQA
DATA_DIR = tmpdir.name
LOG_DIR = os.path.join(DATA_DIR, 'logs')
MEDIA_ROOT = os.path.join(DATA_DIR, 'media')
atexit.register(tmpdir.cleanup)
EMAIL_BACKEND = 'django.core.mail.outbox'
COMPRESS_ENABLED = COMPRESS_OFFLINE = False
DEBUG = True
PASSWORD_HASHERS = ['django.contrib.auth.hashers.MD5PasswordHasher']
# Disable celery
CELERY_ALWAYS_EAGER = True
HAS_CELERY = False
# Don't use redis
SESSION_ENGINE = "django.contrib.sessions.backends.db"
HAS_REDIS = False
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
|
67a230dd5673601f2e1f1a8c3deb8597f29287db | src/tmlib/workflow/align/args.py | src/tmlib/workflow/align/args.py | from tmlib.workflow.args import BatchArguments
from tmlib.workflow.args import SubmissionArguments
from tmlib.workflow.args import Argument
from tmlib.workflow import register_batch_args
from tmlib.workflow import register_submission_args
@register_batch_args('align')
class AlignBatchArguments(BatchArguments):
ref_cycle = Argument(
type=int, required=True, flag='c',
help='''zero-based index of the cycle whose sites should be used
as reference
'''
)
ref_wavelength = Argument(
type=str, required=True, flag='w',
help='name of the wavelength whose images should be used as reference'
)
batch_size = Argument(
type=int, default=10, flag='b',
help='number of image files that should be processed per job'
)
@register_submission_args('align')
class AlignSubmissionArguments(SubmissionArguments):
pass
| from tmlib.workflow.args import BatchArguments
from tmlib.workflow.args import SubmissionArguments
from tmlib.workflow.args import Argument
from tmlib.workflow import register_batch_args
from tmlib.workflow import register_submission_args
@register_batch_args('align')
class AlignBatchArguments(BatchArguments):
ref_cycle = Argument(
type=int, required=True, flag='c',
help='''zero-based index of the cycle whose sites should be used
as reference
'''
)
ref_wavelength = Argument(
type=str, required=True, flag='w',
help='name of the wavelength whose images should be used as reference'
)
batch_size = Argument(
type=int, default=100, flag='b',
help='number of image files that should be processed per job'
)
@register_submission_args('align')
class AlignSubmissionArguments(SubmissionArguments):
pass
| Increase default batch size for align step | Increase default batch size for align step
| Python | agpl-3.0 | TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary | <REPLACE_OLD> default=10, <REPLACE_NEW> default=100, <REPLACE_END> <|endoftext|> from tmlib.workflow.args import BatchArguments
from tmlib.workflow.args import SubmissionArguments
from tmlib.workflow.args import Argument
from tmlib.workflow import register_batch_args
from tmlib.workflow import register_submission_args
@register_batch_args('align')
class AlignBatchArguments(BatchArguments):
ref_cycle = Argument(
type=int, required=True, flag='c',
help='''zero-based index of the cycle whose sites should be used
as reference
'''
)
ref_wavelength = Argument(
type=str, required=True, flag='w',
help='name of the wavelength whose images should be used as reference'
)
batch_size = Argument(
type=int, default=100, flag='b',
help='number of image files that should be processed per job'
)
@register_submission_args('align')
class AlignSubmissionArguments(SubmissionArguments):
pass
| Increase default batch size for align step
from tmlib.workflow.args import BatchArguments
from tmlib.workflow.args import SubmissionArguments
from tmlib.workflow.args import Argument
from tmlib.workflow import register_batch_args
from tmlib.workflow import register_submission_args
@register_batch_args('align')
class AlignBatchArguments(BatchArguments):
ref_cycle = Argument(
type=int, required=True, flag='c',
help='''zero-based index of the cycle whose sites should be used
as reference
'''
)
ref_wavelength = Argument(
type=str, required=True, flag='w',
help='name of the wavelength whose images should be used as reference'
)
batch_size = Argument(
type=int, default=10, flag='b',
help='number of image files that should be processed per job'
)
@register_submission_args('align')
class AlignSubmissionArguments(SubmissionArguments):
pass
|
30008019f47f4077469ad12cb2a3e203fba24527 | server.py | server.py | import tornado.ioloop
import tornado.web
import logging
import motor
from settings import routing
from tornado.options import options
import os
if not os.path.exists(options.log_dir):
os.makedirs(options.log_dir)
logging.basicConfig(
format='%(asctime)s [%(name)s] %(levelname)s: %(message)s',
filename='%s/%s' % (options.log_dir, options.log_file),
level=logging.DEBUG
)
ioLoop = tornado.ioloop.IOLoop.current()
mongodb = ioLoop.run_sync(motor.MotorClient(options.db_address).open)
app = tornado.web.Application(routing, db=mongodb, autoreload=options.autoreload)
app.listen(options.port)
if __name__ == "__main__":
try:
logging.info("Starting HTTP server on port %d" % options.port)
ioLoop.start()
except KeyboardInterrupt:
logging.info("Shutting down server HTTP proxy on port %d" % options.port)
ioLoop.stop()
| import tornado.ioloop
import tornado.web
import logging
import motor
from settings import routing
from tornado.options import options
import os
if not os.path.exists(options.log_dir):
os.makedirs(options.log_dir)
logging.basicConfig(
format='%(asctime)s [%(name)s] %(levelname)s: %(message)s',
filename='%s/%s' % (options.log_dir, options.log_file),
level=logging.DEBUG
)
logging.getLogger('INIT').info('Connecting to mongodb at: %s' % options.db_address)
ioLoop = tornado.ioloop.IOLoop.current()
mongodb = ioLoop.run_sync(motor.MotorClient(options.db_address).open)
app = tornado.web.Application(routing, db=mongodb, autoreload=options.autoreload)
app.listen(options.port)
if __name__ == "__main__":
try:
logging.info("Starting HTTP server on port %d" % options.port)
ioLoop.start()
except KeyboardInterrupt:
logging.info("Shutting down server HTTP proxy on port %d" % options.port)
ioLoop.stop()
| Add to log db connection url | Add to log db connection url
| Python | apache-2.0 | jiss-software/jiss-file-service,jiss-software/jiss-file-service,jiss-software/jiss-file-service | <REPLACE_OLD> level=logging.DEBUG
)
ioLoop <REPLACE_NEW> level=logging.DEBUG
)
logging.getLogger('INIT').info('Connecting to mongodb at: %s' % options.db_address)
ioLoop <REPLACE_END> <|endoftext|> import tornado.ioloop
import tornado.web
import logging
import motor
from settings import routing
from tornado.options import options
import os
if not os.path.exists(options.log_dir):
os.makedirs(options.log_dir)
logging.basicConfig(
format='%(asctime)s [%(name)s] %(levelname)s: %(message)s',
filename='%s/%s' % (options.log_dir, options.log_file),
level=logging.DEBUG
)
logging.getLogger('INIT').info('Connecting to mongodb at: %s' % options.db_address)
ioLoop = tornado.ioloop.IOLoop.current()
mongodb = ioLoop.run_sync(motor.MotorClient(options.db_address).open)
app = tornado.web.Application(routing, db=mongodb, autoreload=options.autoreload)
app.listen(options.port)
if __name__ == "__main__":
try:
logging.info("Starting HTTP server on port %d" % options.port)
ioLoop.start()
except KeyboardInterrupt:
logging.info("Shutting down server HTTP proxy on port %d" % options.port)
ioLoop.stop()
| Add to log db connection url
import tornado.ioloop
import tornado.web
import logging
import motor
from settings import routing
from tornado.options import options
import os
if not os.path.exists(options.log_dir):
os.makedirs(options.log_dir)
logging.basicConfig(
format='%(asctime)s [%(name)s] %(levelname)s: %(message)s',
filename='%s/%s' % (options.log_dir, options.log_file),
level=logging.DEBUG
)
ioLoop = tornado.ioloop.IOLoop.current()
mongodb = ioLoop.run_sync(motor.MotorClient(options.db_address).open)
app = tornado.web.Application(routing, db=mongodb, autoreload=options.autoreload)
app.listen(options.port)
if __name__ == "__main__":
try:
logging.info("Starting HTTP server on port %d" % options.port)
ioLoop.start()
except KeyboardInterrupt:
logging.info("Shutting down server HTTP proxy on port %d" % options.port)
ioLoop.stop()
|
28126555aea9a78467dfcadbb2b14f9c640cdc6d | dwitter/templatetags/to_gravatar_url.py | dwitter/templatetags/to_gravatar_url.py | import hashlib
from django import template
register = template.Library()
@register.filter
def to_gravatar_url(email):
return ('https://gravatar.com/avatar/%s?d=retro' %
hashlib.md5((email or '').strip().lower()).hexdigest())
| import hashlib
from django import template
register = template.Library()
@register.filter
def to_gravatar_url(email):
return ('https://gravatar.com/avatar/%s?d=retro' %
hashlib.md5((email or '').strip().lower().encode('utf-8')).hexdigest())
| Fix gravatar hashing error on py3 | Fix gravatar hashing error on py3
| Python | apache-2.0 | lionleaf/dwitter,lionleaf/dwitter,lionleaf/dwitter | <REPLACE_OLD> '').strip().lower()).hexdigest())
<REPLACE_NEW> '').strip().lower().encode('utf-8')).hexdigest())
<REPLACE_END> <|endoftext|> import hashlib
from django import template
register = template.Library()
@register.filter
def to_gravatar_url(email):
return ('https://gravatar.com/avatar/%s?d=retro' %
hashlib.md5((email or '').strip().lower().encode('utf-8')).hexdigest())
| Fix gravatar hashing error on py3
import hashlib
from django import template
register = template.Library()
@register.filter
def to_gravatar_url(email):
return ('https://gravatar.com/avatar/%s?d=retro' %
hashlib.md5((email or '').strip().lower()).hexdigest())
|
640ce1a3b4f9cca4ebcc10f3d62b1d4d995dd0c5 | src/foremast/pipeline/create_pipeline_manual.py | src/foremast/pipeline/create_pipeline_manual.py | # Foremast - Pipeline Tooling
#
# Copyright 2016 Gogo, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Create manual Pipeline for Spinnaker."""
from ..utils.lookups import FileLookup
from .create_pipeline import SpinnakerPipeline
class SpinnakerPipelineManual(SpinnakerPipeline):
"""Manual JSON configured Spinnaker Pipelines."""
def create_pipeline(self):
"""Use JSON files to create Pipelines."""
self.log.info('Uploading manual Pipelines: %s')
lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir)
for json_file in self.settings['pipeline']['pipeline_files']:
json_dict = lookup.json(filename=json_file)
json_dict['name'] = json_file
self.post_pipeline(json_dict)
return True
| # Foremast - Pipeline Tooling
#
# Copyright 2016 Gogo, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Create manual Pipeline for Spinnaker."""
from ..utils.lookups import FileLookup
from .clean_pipelines import delete_pipeline
from .create_pipeline import SpinnakerPipeline
class SpinnakerPipelineManual(SpinnakerPipeline):
"""Manual JSON configured Spinnaker Pipelines."""
def create_pipeline(self):
"""Use JSON files to create Pipelines."""
self.log.info('Uploading manual Pipelines: %s')
lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir)
for json_file in self.settings['pipeline']['pipeline_files']:
delete_pipeline(app=self.app_name, pipeline_name=json_file)
json_dict = lookup.json(filename=json_file)
json_dict['name'] = json_file
self.post_pipeline(json_dict)
return True
| Delete manual Pipeline before creating | fix: Delete manual Pipeline before creating
See also: #72
| Python | apache-2.0 | gogoair/foremast,gogoair/foremast | <INSERT> .clean_pipelines import delete_pipeline
from <INSERT_END> <INSERT> delete_pipeline(app=self.app_name, pipeline_name=json_file)
<INSERT_END> <|endoftext|> # Foremast - Pipeline Tooling
#
# Copyright 2016 Gogo, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Create manual Pipeline for Spinnaker."""
from ..utils.lookups import FileLookup
from .clean_pipelines import delete_pipeline
from .create_pipeline import SpinnakerPipeline
class SpinnakerPipelineManual(SpinnakerPipeline):
"""Manual JSON configured Spinnaker Pipelines."""
def create_pipeline(self):
"""Use JSON files to create Pipelines."""
self.log.info('Uploading manual Pipelines: %s')
lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir)
for json_file in self.settings['pipeline']['pipeline_files']:
delete_pipeline(app=self.app_name, pipeline_name=json_file)
json_dict = lookup.json(filename=json_file)
json_dict['name'] = json_file
self.post_pipeline(json_dict)
return True
| fix: Delete manual Pipeline before creating
See also: #72
# Foremast - Pipeline Tooling
#
# Copyright 2016 Gogo, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Create manual Pipeline for Spinnaker."""
from ..utils.lookups import FileLookup
from .create_pipeline import SpinnakerPipeline
class SpinnakerPipelineManual(SpinnakerPipeline):
"""Manual JSON configured Spinnaker Pipelines."""
def create_pipeline(self):
"""Use JSON files to create Pipelines."""
self.log.info('Uploading manual Pipelines: %s')
lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir)
for json_file in self.settings['pipeline']['pipeline_files']:
json_dict = lookup.json(filename=json_file)
json_dict['name'] = json_file
self.post_pipeline(json_dict)
return True
|
ec244cc9c56fec571502529ef24af2ca18d9f5f5 | spirit/templatetags/tags/utils/gravatar.py | spirit/templatetags/tags/utils/gravatar.py | #-*- coding: utf-8 -*-
import hashlib
from django.utils.http import urlencode, urlquote
from .. import register
@register.simple_tag()
def get_gravatar_url(user, size, rating='g', default='identicon'):
url = "http://www.gravatar.com/avatar/"
hash = hashlib.md5(user.email.strip().lower()).hexdigest()
data = urlencode({'d': urlquote(default), 's': str(size), 'r': rating})
return "".join((url, hash, '?', data))
| #-*- coding: utf-8 -*-
import hashlib
from django.utils.http import urlencode, urlquote
from django.utils.encoding import force_bytes
from .. import register
@register.simple_tag()
def get_gravatar_url(user, size, rating='g', default='identicon'):
url = "http://www.gravatar.com/avatar/"
hash = hashlib.md5(force_bytes(user.email.strip().lower().encode('utf_8'))).hexdigest()
data = urlencode({'d': urlquote(default), 's': str(size), 'r': rating})
return "".join((url, hash, '?', data))
| Use django utils force_bytes to arguments of hashlib | Use django utils force_bytes to arguments of hashlib
| Python | mit | alesdotio/Spirit,a-olszewski/Spirit,raybesiga/Spirit,a-olszewski/Spirit,dvreed/Spirit,ramaseshan/Spirit,adiyengar/Spirit,battlecat/Spirit,ramaseshan/Spirit,gogobook/Spirit,dvreed/Spirit,nitely/Spirit,mastak/Spirit,battlecat/Spirit,nitely/Spirit,a-olszewski/Spirit,alesdotio/Spirit,mastak/Spirit,alesdotio/Spirit,gogobook/Spirit,raybesiga/Spirit,adiyengar/Spirit,gogobook/Spirit,dvreed/Spirit,mastak/Spirit,battlecat/Spirit,nitely/Spirit,adiyengar/Spirit,ramaseshan/Spirit,raybesiga/Spirit | <REPLACE_OLD> urlquote
from <REPLACE_NEW> urlquote
from django.utils.encoding import force_bytes
from <REPLACE_END> <REPLACE_OLD> hashlib.md5(user.email.strip().lower()).hexdigest()
<REPLACE_NEW> hashlib.md5(force_bytes(user.email.strip().lower().encode('utf_8'))).hexdigest()
<REPLACE_END> <|endoftext|> #-*- coding: utf-8 -*-
import hashlib
from django.utils.http import urlencode, urlquote
from django.utils.encoding import force_bytes
from .. import register
@register.simple_tag()
def get_gravatar_url(user, size, rating='g', default='identicon'):
url = "http://www.gravatar.com/avatar/"
hash = hashlib.md5(force_bytes(user.email.strip().lower().encode('utf_8'))).hexdigest()
data = urlencode({'d': urlquote(default), 's': str(size), 'r': rating})
return "".join((url, hash, '?', data))
| Use django utils force_bytes to arguments of hashlib
#-*- coding: utf-8 -*-
import hashlib
from django.utils.http import urlencode, urlquote
from .. import register
@register.simple_tag()
def get_gravatar_url(user, size, rating='g', default='identicon'):
url = "http://www.gravatar.com/avatar/"
hash = hashlib.md5(user.email.strip().lower()).hexdigest()
data = urlencode({'d': urlquote(default), 's': str(size), 'r': rating})
return "".join((url, hash, '?', data))
|
47f4e738cc11ec40d3410332106163b0235f5da4 | tests/python/tests/test_result.py | tests/python/tests/test_result.py | import unittest
import librepo
from librepo import LibrepoException
class TestCaseResult(unittest.TestCase):
def test_result_getinfo(self):
r = librepo.Result()
self.assertTrue(r)
self.assertRaises(ValueError, r.getinfo, 99999999)
self.assertFalse(r.getinfo(librepo.LRR_YUM_REPO))
self.assertFalse(r.getinfo(librepo.LRR_YUM_REPOMD))
self.assertRaises(LibrepoException, r.getinfo, librepo.LRR_YUM_TIMESTAMP)
def test_result_attrs(self):
r = librepo.Result()
self.assertTrue(r)
self.assertRaises(AttributeError, getattr, r, 'foobar_attr')
# Attrs should not be filled (that's why None or
# LibrepoException is expected), but they definitelly
# should exists (not AttributeError should be raised)
self.assertFalse(r.yum_repo)
self.assertFalse(r.yum_repomd)
self.assertRaises(LibrepoException, getattr, r, 'yum_timestamp')
| Add tests for Result object | Tests: Add tests for Result object
| Python | lgpl-2.1 | Conan-Kudo/librepo,bgamari/librepo,Tojaj/librepo,rholy/librepo,rholy/librepo,cgwalters/librepo,rpm-software-management/librepo,Tojaj/librepo,Conan-Kudo/librepo,rholy/librepo,cgwalters/librepo,cgwalters/librepo,rholy/librepo,Conan-Kudo/librepo,cgwalters/librepo,rpm-software-management/librepo,Tojaj/librepo,rpm-software-management/librepo,bgamari/librepo,bgamari/librepo | <INSERT> import unittest
import librepo
from librepo import LibrepoException
class TestCaseResult(unittest.TestCase):
<INSERT_END> <INSERT> def test_result_getinfo(self):
r = librepo.Result()
self.assertTrue(r)
self.assertRaises(ValueError, r.getinfo, 99999999)
self.assertFalse(r.getinfo(librepo.LRR_YUM_REPO))
self.assertFalse(r.getinfo(librepo.LRR_YUM_REPOMD))
self.assertRaises(LibrepoException, r.getinfo, librepo.LRR_YUM_TIMESTAMP)
def test_result_attrs(self):
r = librepo.Result()
self.assertTrue(r)
self.assertRaises(AttributeError, getattr, r, 'foobar_attr')
# Attrs should not be filled (that's why None or
# LibrepoException is expected), but they definitelly
# should exists (not AttributeError should be raised)
self.assertFalse(r.yum_repo)
self.assertFalse(r.yum_repomd)
self.assertRaises(LibrepoException, getattr, r, 'yum_timestamp')
<INSERT_END> <|endoftext|> import unittest
import librepo
from librepo import LibrepoException
class TestCaseResult(unittest.TestCase):
def test_result_getinfo(self):
r = librepo.Result()
self.assertTrue(r)
self.assertRaises(ValueError, r.getinfo, 99999999)
self.assertFalse(r.getinfo(librepo.LRR_YUM_REPO))
self.assertFalse(r.getinfo(librepo.LRR_YUM_REPOMD))
self.assertRaises(LibrepoException, r.getinfo, librepo.LRR_YUM_TIMESTAMP)
def test_result_attrs(self):
r = librepo.Result()
self.assertTrue(r)
self.assertRaises(AttributeError, getattr, r, 'foobar_attr')
# Attrs should not be filled (that's why None or
# LibrepoException is expected), but they definitelly
# should exists (not AttributeError should be raised)
self.assertFalse(r.yum_repo)
self.assertFalse(r.yum_repomd)
self.assertRaises(LibrepoException, getattr, r, 'yum_timestamp')
| Tests: Add tests for Result object
|
|
21c7232081483c05752e6db3d60692a04d482d24 | dakota/tests/test_dakota_base.py | dakota/tests/test_dakota_base.py | #!/usr/bin/env python
#
# Tests for dakota.dakota_base module.
#
# Call with:
# $ nosetests -sv
#
# Mark Piper ([email protected])
import os
import filecmp
from nose.tools import *
from dakota.dakota_base import DakotaBase
# Fixtures -------------------------------------------------------------
def setup_module():
"""Called before any tests are performed."""
print('\n*** DakotaBase tests')
def teardown_module():
"""Called after all tests have completed."""
pass
# Tests ----------------------------------------------------------------
@raises(TypeError)
def test_instantiate():
"""Test whether DakotaBase fails to instantiate."""
d = DakotaBase()
| #!/usr/bin/env python
#
# Tests for dakota.dakota_base module.
#
# Call with:
# $ nosetests -sv
#
# Mark Piper ([email protected])
from nose.tools import *
from dakota.dakota_base import DakotaBase
# Helpers --------------------------------------------------------------
class Concrete(DakotaBase):
"""A subclass of DakotaBase used for testing."""
def __init__(self):
DakotaBase.__init__(self)
# Fixtures -------------------------------------------------------------
def setup_module():
"""Called before any tests are performed."""
print('\n*** DakotaBase tests')
global c
c = Concrete()
def teardown_module():
"""Called after all tests have completed."""
pass
# Tests ----------------------------------------------------------------
@raises(TypeError)
def test_instantiate():
"""Test whether DakotaBase fails to instantiate."""
d = DakotaBase()
def test_environment_block():
"""Test type of environment_block method results."""
s = c.environment_block()
assert_true(type(s) is str)
def test_method_block():
"""Test type of method_block method results."""
s = c.method_block()
assert_true(type(s) is str)
def test_variables_block():
"""Test type of variables_block method results."""
s = c.variables_block()
assert_true(type(s) is str)
def test_interface_block():
"""Test type of interface_block method results."""
s = c.interface_block()
assert_true(type(s) is str)
def test_responses_block():
"""Test type of responses_block method results."""
s = c.responses_block()
assert_true(type(s) is str)
def test_autogenerate_descriptors():
"""Test autogenerate_descriptors method."""
c.n_variables, c.n_responses = 1, 1
c.autogenerate_descriptors()
assert_true(len(c.variable_descriptors) == 1)
assert_true(len(c.response_descriptors) == 1)
| Add tests for dakota.dakota_base module | Add tests for dakota.dakota_base module
Make a subclass of DakotaBase to use for testing. Add tests for the
"block" sections used to define an input file.
| Python | mit | csdms/dakota,csdms/dakota | <REPLACE_OLD> ([email protected])
import os
import filecmp
from <REPLACE_NEW> ([email protected])
from <REPLACE_END> <REPLACE_OLD> DakotaBase
# <REPLACE_NEW> DakotaBase
# Helpers --------------------------------------------------------------
class Concrete(DakotaBase):
"""A subclass of DakotaBase used for testing."""
def __init__(self):
DakotaBase.__init__(self)
# <REPLACE_END> <REPLACE_OLD> tests')
def <REPLACE_NEW> tests')
global c
c = Concrete()
def <REPLACE_END> <REPLACE_OLD> DakotaBase()
<REPLACE_NEW> DakotaBase()
def test_environment_block():
"""Test type of environment_block method results."""
s = c.environment_block()
assert_true(type(s) is str)
def test_method_block():
"""Test type of method_block method results."""
s = c.method_block()
assert_true(type(s) is str)
def test_variables_block():
"""Test type of variables_block method results."""
s = c.variables_block()
assert_true(type(s) is str)
def test_interface_block():
"""Test type of interface_block method results."""
s = c.interface_block()
assert_true(type(s) is str)
def test_responses_block():
"""Test type of responses_block method results."""
s = c.responses_block()
assert_true(type(s) is str)
def test_autogenerate_descriptors():
"""Test autogenerate_descriptors method."""
c.n_variables, c.n_responses = 1, 1
c.autogenerate_descriptors()
assert_true(len(c.variable_descriptors) == 1)
assert_true(len(c.response_descriptors) == 1)
<REPLACE_END> <|endoftext|> #!/usr/bin/env python
#
# Tests for dakota.dakota_base module.
#
# Call with:
# $ nosetests -sv
#
# Mark Piper ([email protected])
from nose.tools import *
from dakota.dakota_base import DakotaBase
# Helpers --------------------------------------------------------------
class Concrete(DakotaBase):
"""A subclass of DakotaBase used for testing."""
def __init__(self):
DakotaBase.__init__(self)
# Fixtures -------------------------------------------------------------
def setup_module():
"""Called before any tests are performed."""
print('\n*** DakotaBase tests')
global c
c = Concrete()
def teardown_module():
"""Called after all tests have completed."""
pass
# Tests ----------------------------------------------------------------
@raises(TypeError)
def test_instantiate():
"""Test whether DakotaBase fails to instantiate."""
d = DakotaBase()
def test_environment_block():
"""Test type of environment_block method results."""
s = c.environment_block()
assert_true(type(s) is str)
def test_method_block():
"""Test type of method_block method results."""
s = c.method_block()
assert_true(type(s) is str)
def test_variables_block():
"""Test type of variables_block method results."""
s = c.variables_block()
assert_true(type(s) is str)
def test_interface_block():
"""Test type of interface_block method results."""
s = c.interface_block()
assert_true(type(s) is str)
def test_responses_block():
"""Test type of responses_block method results."""
s = c.responses_block()
assert_true(type(s) is str)
def test_autogenerate_descriptors():
"""Test autogenerate_descriptors method."""
c.n_variables, c.n_responses = 1, 1
c.autogenerate_descriptors()
assert_true(len(c.variable_descriptors) == 1)
assert_true(len(c.response_descriptors) == 1)
| Add tests for dakota.dakota_base module
Make a subclass of DakotaBase to use for testing. Add tests for the
"block" sections used to define an input file.
#!/usr/bin/env python
#
# Tests for dakota.dakota_base module.
#
# Call with:
# $ nosetests -sv
#
# Mark Piper ([email protected])
import os
import filecmp
from nose.tools import *
from dakota.dakota_base import DakotaBase
# Fixtures -------------------------------------------------------------
def setup_module():
"""Called before any tests are performed."""
print('\n*** DakotaBase tests')
def teardown_module():
"""Called after all tests have completed."""
pass
# Tests ----------------------------------------------------------------
@raises(TypeError)
def test_instantiate():
"""Test whether DakotaBase fails to instantiate."""
d = DakotaBase()
|
b42d2239d24bb651f95830899d972e4302a10d77 | setup.py | setup.py | #!/usr/bin/env python
import setuptools
import samsungctl
setuptools.setup(
name=samsungctl.__title__,
version=samsungctl.__version__,
description=samsungctl.__doc__,
url=samsungctl.__url__,
author=samsungctl.__author__,
author_email=samsungctl.__author_email__,
license=samsungctl.__license__,
long_description=open("README.md").read(),
entry_points={
"console_scripts": ["samsungctl=samsungctl.__main__:main"]
},
packages=["samsungctl"],
install_requires=[],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Topic :: Home Automation"
]
)
| #!/usr/bin/env python
import setuptools
import samsungctl
setuptools.setup(
name=samsungctl.__title__,
version=samsungctl.__version__,
description=samsungctl.__doc__,
url=samsungctl.__url__,
author=samsungctl.__author__,
author_email=samsungctl.__author_email__,
license=samsungctl.__license__,
long_description=open("README.md").read(),
entry_points={
"console_scripts": ["samsungctl=samsungctl.__main__:main"]
},
packages=["samsungctl"],
install_requires=[],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Topic :: Home Automation",
],
)
| Use comma on every line on multi-line lists | Use comma on every line on multi-line lists
| Python | mit | dominikkarall/samsungctl,Ape/samsungctl | <REPLACE_OLD> Automation"
<REPLACE_NEW> Automation",
<REPLACE_END> <REPLACE_OLD> ]
)
<REPLACE_NEW> ],
)
<REPLACE_END> <|endoftext|> #!/usr/bin/env python
import setuptools
import samsungctl
setuptools.setup(
name=samsungctl.__title__,
version=samsungctl.__version__,
description=samsungctl.__doc__,
url=samsungctl.__url__,
author=samsungctl.__author__,
author_email=samsungctl.__author_email__,
license=samsungctl.__license__,
long_description=open("README.md").read(),
entry_points={
"console_scripts": ["samsungctl=samsungctl.__main__:main"]
},
packages=["samsungctl"],
install_requires=[],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Topic :: Home Automation",
],
)
| Use comma on every line on multi-line lists
#!/usr/bin/env python
import setuptools
import samsungctl
setuptools.setup(
name=samsungctl.__title__,
version=samsungctl.__version__,
description=samsungctl.__doc__,
url=samsungctl.__url__,
author=samsungctl.__author__,
author_email=samsungctl.__author_email__,
license=samsungctl.__license__,
long_description=open("README.md").read(),
entry_points={
"console_scripts": ["samsungctl=samsungctl.__main__:main"]
},
packages=["samsungctl"],
install_requires=[],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Topic :: Home Automation"
]
)
|
0ad53b5dc887ab4b81e3cf83bfb897340880c3a2 | launch_control/models/test_case.py | launch_control/models/test_case.py | """
Module with the TestCase model.
"""
from launch_control.utils.json.pod import PlainOldData
class TestCase(PlainOldData):
"""
TestCase model.
Currently contains just two fields:
- test_case_id (test-case specific ID)
- name (human readable)
"""
__slots__ = ('test_case_id', 'desc')
def __init__(self, test_case_id, desc):
self.test_case_id = test_case_id
self.name = name
| """
Module with the TestCase model.
"""
from launch_control.utils.json.pod import PlainOldData
class TestCase(PlainOldData):
"""
TestCase model.
Currently contains just two fields:
- test_case_id (test-case specific ID)
- name (human readable)
"""
__slots__ = ('test_case_id', 'name')
def __init__(self, test_case_id, desc):
self.test_case_id = test_case_id
self.name = name
| Fix TestCase definition to have a slot 'name' instead of 'desc' | Fix TestCase definition to have a slot 'name' instead of 'desc'
| Python | agpl-3.0 | Linaro/lava-server,Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,OSSystems/lava-server,OSSystems/lava-server,Linaro/lava-server | <REPLACE_OLD> 'desc')
<REPLACE_NEW> 'name')
<REPLACE_END> <|endoftext|> """
Module with the TestCase model.
"""
from launch_control.utils.json.pod import PlainOldData
class TestCase(PlainOldData):
"""
TestCase model.
Currently contains just two fields:
- test_case_id (test-case specific ID)
- name (human readable)
"""
__slots__ = ('test_case_id', 'name')
def __init__(self, test_case_id, desc):
self.test_case_id = test_case_id
self.name = name
| Fix TestCase definition to have a slot 'name' instead of 'desc'
"""
Module with the TestCase model.
"""
from launch_control.utils.json.pod import PlainOldData
class TestCase(PlainOldData):
"""
TestCase model.
Currently contains just two fields:
- test_case_id (test-case specific ID)
- name (human readable)
"""
__slots__ = ('test_case_id', 'desc')
def __init__(self, test_case_id, desc):
self.test_case_id = test_case_id
self.name = name
|
8db3ee0d6b73b864a91cd3617342138f05175d9d | accounts/models.py | accounts/models.py | # coding: utf-8
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from registration.signals import user_activated
from django.dispatch import receiver
class UserAccount(models.Model):
"""
A user account. Used to store any information related to users.
"""
user = models.OneToOneField(settings.AUTH_USER_MODEL,
related_name='account')
class Meta:
verbose_name = _('user account')
verbose_name_plural = _('user accounts')
@receiver(user_activated)
def registration_completed(sender, user, request, **kwargs):
account, created = UserAccount.objects.get_or_create(user=user)
print account, created
| # coding: utf-8
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from registration.signals import user_activated
from django.dispatch import receiver
class UserAccount(models.Model):
"""
A user account. Used to store any information related to users.
"""
user = models.OneToOneField(settings.AUTH_USER_MODEL,
related_name='account')
class Meta:
verbose_name = _('user account')
verbose_name_plural = _('user accounts')
def __unicode__(self):
return u'{}'.format(self.user.username)
@receiver(user_activated)
def registration_completed(sender, user, request, **kwargs):
account, created = UserAccount.objects.get_or_create(user=user)
print account, created
| Add __unicode__ method to UserAccount model | Add __unicode__ method to UserAccount model
| Python | agpl-3.0 | coders4help/volunteer_planner,alper/volunteer_planner,klinger/volunteer_planner,pitpalme/volunteer_planner,volunteer-planner/volunteer_planner,pitpalme/volunteer_planner,christophmeissner/volunteer_planner,pitpalme/volunteer_planner,christophmeissner/volunteer_planner,alper/volunteer_planner,flindenberg/volunteer_planner,klinger/volunteer_planner,coders4help/volunteer_planner,klinger/volunteer_planner,christophmeissner/volunteer_planner,volunteer-planner/volunteer_planner,coders4help/volunteer_planner,flindenberg/volunteer_planner,volunteer-planner/volunteer_planner,christophmeissner/volunteer_planner,alper/volunteer_planner,volunteer-planner/volunteer_planner,klinger/volunteer_planner,flindenberg/volunteer_planner,pitpalme/volunteer_planner,coders4help/volunteer_planner | <REPLACE_OLD> accounts')
@receiver(user_activated)
def <REPLACE_NEW> accounts')
def __unicode__(self):
return u'{}'.format(self.user.username)
@receiver(user_activated)
def <REPLACE_END> <|endoftext|> # coding: utf-8
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from registration.signals import user_activated
from django.dispatch import receiver
class UserAccount(models.Model):
"""
A user account. Used to store any information related to users.
"""
user = models.OneToOneField(settings.AUTH_USER_MODEL,
related_name='account')
class Meta:
verbose_name = _('user account')
verbose_name_plural = _('user accounts')
def __unicode__(self):
return u'{}'.format(self.user.username)
@receiver(user_activated)
def registration_completed(sender, user, request, **kwargs):
account, created = UserAccount.objects.get_or_create(user=user)
print account, created
| Add __unicode__ method to UserAccount model
# coding: utf-8
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from registration.signals import user_activated
from django.dispatch import receiver
class UserAccount(models.Model):
"""
A user account. Used to store any information related to users.
"""
user = models.OneToOneField(settings.AUTH_USER_MODEL,
related_name='account')
class Meta:
verbose_name = _('user account')
verbose_name_plural = _('user accounts')
@receiver(user_activated)
def registration_completed(sender, user, request, **kwargs):
account, created = UserAccount.objects.get_or_create(user=user)
print account, created
|
0efeaa258b19d5b1ba204cc55fbdb6969e0f3e64 | flake8_respect_noqa.py | flake8_respect_noqa.py | # -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.2
import pep8
class RespectNoqaReport(pep8.StandardReport):
def error(self, line_number, offset, text, check):
if len(self.lines) > line_number - 1 and pep8.noqa(self.lines[line_number - 1]):
return
else:
return super(RespectNoqaReport, self).error(line_number, offset,
text, check)
class RespectNoqa(object):
name = 'flake8-respect-noqa'
version = __version__
def __init__(self, *args, **kwargs):
pass
@classmethod
def parse_options(cls, options):
# The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
# or put "jobs = 1" in your [flake8] config.
# Otherwise, flake8 replaces this reported with it's own.
# See https://gitlab.com/pycqa/flake8/issues/66
options.reporter = RespectNoqaReport
options.report = RespectNoqaReport(options)
| # -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.2
try:
from pep8 import StandardReport, noqa
except ImportError:
# Try the new (as of 2016-June) pycodestyle package.
from pycodestyle import StandardReport, noqa
class RespectNoqaReport(StandardReport):
def error(self, line_number, offset, text, check):
if len(self.lines) > line_number - 1 and noqa(self.lines[line_number - 1]):
return
else:
return super(RespectNoqaReport, self).error(line_number, offset,
text, check)
class RespectNoqa(object):
name = 'flake8-respect-noqa'
version = __version__
def __init__(self, *args, **kwargs):
pass
@classmethod
def parse_options(cls, options):
# The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
# or put "jobs = 1" in your [flake8] config.
# Otherwise, flake8 replaces this reported with it's own.
# See https://gitlab.com/pycqa/flake8/issues/66
options.reporter = RespectNoqaReport
options.report = RespectNoqaReport(options)
| Adjust for pep8 package rename. | Adjust for pep8 package rename.
Closes #1
| Python | mit | spookylukey/flake8-respect-noqa | <REPLACE_OLD> 0.2
import pep8
class RespectNoqaReport(pep8.StandardReport):
<REPLACE_NEW> 0.2
try:
from pep8 import StandardReport, noqa
except ImportError:
# Try the new (as of 2016-June) pycodestyle package.
from pycodestyle import StandardReport, noqa
class RespectNoqaReport(StandardReport):
<REPLACE_END> <REPLACE_OLD> pep8.noqa(self.lines[line_number <REPLACE_NEW> noqa(self.lines[line_number <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.2
try:
from pep8 import StandardReport, noqa
except ImportError:
# Try the new (as of 2016-June) pycodestyle package.
from pycodestyle import StandardReport, noqa
class RespectNoqaReport(StandardReport):
def error(self, line_number, offset, text, check):
if len(self.lines) > line_number - 1 and noqa(self.lines[line_number - 1]):
return
else:
return super(RespectNoqaReport, self).error(line_number, offset,
text, check)
class RespectNoqa(object):
name = 'flake8-respect-noqa'
version = __version__
def __init__(self, *args, **kwargs):
pass
@classmethod
def parse_options(cls, options):
# The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
# or put "jobs = 1" in your [flake8] config.
# Otherwise, flake8 replaces this reported with it's own.
# See https://gitlab.com/pycqa/flake8/issues/66
options.reporter = RespectNoqaReport
options.report = RespectNoqaReport(options)
| Adjust for pep8 package rename.
Closes #1
# -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.2
import pep8
class RespectNoqaReport(pep8.StandardReport):
def error(self, line_number, offset, text, check):
if len(self.lines) > line_number - 1 and pep8.noqa(self.lines[line_number - 1]):
return
else:
return super(RespectNoqaReport, self).error(line_number, offset,
text, check)
class RespectNoqa(object):
name = 'flake8-respect-noqa'
version = __version__
def __init__(self, *args, **kwargs):
pass
@classmethod
def parse_options(cls, options):
# The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
# or put "jobs = 1" in your [flake8] config.
# Otherwise, flake8 replaces this reported with it's own.
# See https://gitlab.com/pycqa/flake8/issues/66
options.reporter = RespectNoqaReport
options.report = RespectNoqaReport(options)
|
dc0dfd4a763dceef655d62e8364b92a8073b7751 | chrome/chromehost.py | chrome/chromehost.py | #!/usr/bin/env python
import socket
import struct
import sys
def send_to_chrome(message):
# Write message size.
sys.stdout.write(struct.pack('I', len(message)))
# Write the message itself.
sys.stdout.write(message)
sys.stdout.flush()
def read_from_chrome():
text_length_bytes = sys.stdin.read(4)
if len(text_length_bytes) == 0:
sys.exit(0)
# Unpack message length as 4 byte integer.
text_length = struct.unpack('i', text_length_bytes)[0]
# Read the text (JSON object) of the message.
text = sys.stdin.read(text_length).decode('utf-8')
return text
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
socket_name = '/tmp/cachebrowser.sock'
sock.connect(socket_name)
message = read_from_chrome()
sock.send(message)
sock.send('\n')
response = ''
while True:
read = sock.recv(1024)
if len(read) == 0:
break
response += read
# response = sock.recv(1024)
send_to_chrome(response)
| #!/usr/bin/env python
import socket
import struct
import sys
def send_to_chrome(message):
# Write message size.
sys.stdout.write(struct.pack('I', len(message)))
# Write the message itself.
sys.stdout.write(message)
sys.stdout.flush()
def read_from_chrome():
text_length_bytes = sys.stdin.read(4)
if len(text_length_bytes) == 0:
sys.exit(0)
# Unpack message length as 4 byte integer.
text_length = struct.unpack('i', text_length_bytes)[0]
# Read the text (JSON object) of the message.
text = sys.stdin.read(text_length).decode('utf-8')
return text
# sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# socket_name = '/tmp/cachebrowser.sock'
# sock.connect(socket_name)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 4242))
message = read_from_chrome()
sock.send(message)
sock.send('\n')
# response = ''
# while True:
# read = sock.recv(1024)
# if len(read) == 0:
# break
# response += read
response = sock.recv(1024)
send_to_chrome(response)
# send_to_chrome("{}")
| Change chromhost to use normal sockets | Change chromhost to use normal sockets
| Python | mit | CacheBrowser/cachebrowser,NewBie1993/cachebrowser | <REPLACE_OLD> text
sock <REPLACE_NEW> text
# sock <REPLACE_END> <REPLACE_OLD> socket.SOCK_STREAM)
socket_name <REPLACE_NEW> socket.SOCK_STREAM)
# socket_name <REPLACE_END> <REPLACE_OLD> '/tmp/cachebrowser.sock'
sock.connect(socket_name)
message <REPLACE_NEW> '/tmp/cachebrowser.sock'
# sock.connect(socket_name)
sock <REPLACE_END> <REPLACE_OLD> read_from_chrome()
sock.send(message)
sock.send('\n')
response <REPLACE_NEW> socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 4242))
message <REPLACE_END> <REPLACE_OLD> ''
while True:
<REPLACE_NEW> read_from_chrome()
sock.send(message)
sock.send('\n')
# response = ''
# while True:
# <REPLACE_END> <REPLACE_OLD> sock.recv(1024)
<REPLACE_NEW> sock.recv(1024)
# <REPLACE_END> <REPLACE_OLD> 0:
<REPLACE_NEW> 0:
# <REPLACE_END> <REPLACE_OLD> break
<REPLACE_NEW> break
# <REPLACE_END> <REPLACE_OLD> read
# response <REPLACE_NEW> read
response <REPLACE_END> <REPLACE_OLD> sock.recv(1024)
send_to_chrome(response)
<REPLACE_NEW> sock.recv(1024)
send_to_chrome(response)
# send_to_chrome("{}")
<REPLACE_END> <|endoftext|> #!/usr/bin/env python
import socket
import struct
import sys
def send_to_chrome(message):
# Write message size.
sys.stdout.write(struct.pack('I', len(message)))
# Write the message itself.
sys.stdout.write(message)
sys.stdout.flush()
def read_from_chrome():
text_length_bytes = sys.stdin.read(4)
if len(text_length_bytes) == 0:
sys.exit(0)
# Unpack message length as 4 byte integer.
text_length = struct.unpack('i', text_length_bytes)[0]
# Read the text (JSON object) of the message.
text = sys.stdin.read(text_length).decode('utf-8')
return text
# sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# socket_name = '/tmp/cachebrowser.sock'
# sock.connect(socket_name)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 4242))
message = read_from_chrome()
sock.send(message)
sock.send('\n')
# response = ''
# while True:
# read = sock.recv(1024)
# if len(read) == 0:
# break
# response += read
response = sock.recv(1024)
send_to_chrome(response)
# send_to_chrome("{}")
| Change chromhost to use normal sockets
#!/usr/bin/env python
import socket
import struct
import sys
def send_to_chrome(message):
# Write message size.
sys.stdout.write(struct.pack('I', len(message)))
# Write the message itself.
sys.stdout.write(message)
sys.stdout.flush()
def read_from_chrome():
text_length_bytes = sys.stdin.read(4)
if len(text_length_bytes) == 0:
sys.exit(0)
# Unpack message length as 4 byte integer.
text_length = struct.unpack('i', text_length_bytes)[0]
# Read the text (JSON object) of the message.
text = sys.stdin.read(text_length).decode('utf-8')
return text
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
socket_name = '/tmp/cachebrowser.sock'
sock.connect(socket_name)
message = read_from_chrome()
sock.send(message)
sock.send('\n')
response = ''
while True:
read = sock.recv(1024)
if len(read) == 0:
break
response += read
# response = sock.recv(1024)
send_to_chrome(response)
|
4b63093abbc388bc26151422991ce39553cf137f | neuroimaging/utils/tests/test_odict.py | neuroimaging/utils/tests/test_odict.py | """Test file for the ordered dictionary module, odict.py."""
from neuroimaging.externals.scipy.testing import *
from neuroimaging.utils.odict import odict
class TestOdict(TestCase):
def setUp(self):
print 'setUp'
self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))
def test_copy(self):
"""Test odict.copy method."""
print self.thedict
cpydict = self.thedict.copy()
assert cpydict == self.thedict
# test that it's a copy and not a reference
assert cpydict is not self.thedict
if __name__ == "__main__":
nose.run(argv=['', __file__])
| """Test file for the ordered dictionary module, odict.py."""
from neuroimaging.externals.scipy.testing import *
from neuroimaging.utils.odict import odict
class TestOdict(TestCase):
def setUp(self):
print 'setUp'
self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))
def test_copy(self):
"""Test odict.copy method."""
print self.thedict
cpydict = self.thedict.copy()
assert cpydict == self.thedict
# test that it's a copy and not a reference
assert cpydict is not self.thedict
if __name__ == "__main__":
nose.runmodule()
| Fix nose call so tests run in __main__. | BUG: Fix nose call so tests run in __main__. | Python | bsd-3-clause | alexis-roche/nipy,alexis-roche/nipy,arokem/nipy,nipy/nipy-labs,nipy/nireg,alexis-roche/nireg,alexis-roche/register,nipy/nipy-labs,arokem/nipy,alexis-roche/register,nipy/nireg,bthirion/nipy,bthirion/nipy,alexis-roche/nireg,arokem/nipy,bthirion/nipy,alexis-roche/register,arokem/nipy,alexis-roche/niseg,alexis-roche/nipy,alexis-roche/nipy,alexis-roche/niseg,bthirion/nipy | <REPLACE_OLD> nose.run(argv=['', __file__])
<REPLACE_NEW> nose.runmodule()
<REPLACE_END> <|endoftext|> """Test file for the ordered dictionary module, odict.py."""
from neuroimaging.externals.scipy.testing import *
from neuroimaging.utils.odict import odict
class TestOdict(TestCase):
def setUp(self):
print 'setUp'
self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))
def test_copy(self):
"""Test odict.copy method."""
print self.thedict
cpydict = self.thedict.copy()
assert cpydict == self.thedict
# test that it's a copy and not a reference
assert cpydict is not self.thedict
if __name__ == "__main__":
nose.runmodule()
| BUG: Fix nose call so tests run in __main__.
"""Test file for the ordered dictionary module, odict.py."""
from neuroimaging.externals.scipy.testing import *
from neuroimaging.utils.odict import odict
class TestOdict(TestCase):
def setUp(self):
print 'setUp'
self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))
def test_copy(self):
"""Test odict.copy method."""
print self.thedict
cpydict = self.thedict.copy()
assert cpydict == self.thedict
# test that it's a copy and not a reference
assert cpydict is not self.thedict
if __name__ == "__main__":
nose.run(argv=['', __file__])
|
0dddfcbdb46ac91ddc0bfed4482bce049a8593c2 | lazyblacksmith/views/blueprint.py | lazyblacksmith/views/blueprint.py | # -*- encoding: utf-8 -*-
from flask import Blueprint
from flask import render_template
from lazyblacksmith.models import Activity
from lazyblacksmith.models import Item
from lazyblacksmith.models import Region
blueprint = Blueprint('blueprint', __name__)
@blueprint.route('/manufacturing/<int:item_id>')
def manufacturing(item_id):
"""
Display the manufacturing page with all data
"""
item = Item.query.get(item_id)
activity = item.activities.filter_by(activity=Activity.ACTIVITY_MANUFACTURING).one()
materials = item.activity_materials.filter_by(activity=Activity.ACTIVITY_MANUFACTURING)
product = item.activity_products.filter_by(activity=Activity.ACTIVITY_MANUFACTURING).one()
regions = Region.query.filter_by(wh=False)
# is any of the materials manufactured ?
has_manufactured_components = False
for material in materials:
if material.material.is_manufactured():
has_manufactured_components = True
break
return render_template('blueprint/manufacturing.html', **{
'blueprint': item,
'materials': materials,
'activity': activity,
'product': product,
'regions': regions,
'has_manufactured_components': has_manufactured_components,
})
@blueprint.route('/')
def search():
return render_template('blueprint/search.html')
| # -*- encoding: utf-8 -*-
import config
from flask import Blueprint
from flask import render_template
from lazyblacksmith.models import Activity
from lazyblacksmith.models import Item
from lazyblacksmith.models import Region
blueprint = Blueprint('blueprint', __name__)
@blueprint.route('/manufacturing/<int:item_id>')
def manufacturing(item_id):
"""
Display the manufacturing page with all data
"""
item = Item.query.get(item_id)
activity = item.activities.filter_by(activity=Activity.ACTIVITY_MANUFACTURING).one()
materials = item.activity_materials.filter_by(activity=Activity.ACTIVITY_MANUFACTURING)
product = item.activity_products.filter_by(activity=Activity.ACTIVITY_MANUFACTURING).one()
regions = Region.query.filter(
Region.id.in_(config.CREST_REGION_PRICE)
).filter_by(
wh=False
)
# is any of the materials manufactured ?
has_manufactured_components = False
for material in materials:
if material.material.is_manufactured():
has_manufactured_components = True
break
return render_template('blueprint/manufacturing.html', **{
'blueprint': item,
'materials': materials,
'activity': activity,
'product': product,
'regions': regions,
'has_manufactured_components': has_manufactured_components,
})
@blueprint.route('/')
def search():
return render_template('blueprint/search.html')
| Change region list to match config | Change region list to match config
| Python | bsd-3-clause | Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith | <REPLACE_OLD> -*-
from <REPLACE_NEW> -*-
import config
from <REPLACE_END> <REPLACE_OLD> render_template
from <REPLACE_NEW> render_template
from <REPLACE_END> <REPLACE_OLD> Region.query.filter_by(wh=False)
<REPLACE_NEW> Region.query.filter(
Region.id.in_(config.CREST_REGION_PRICE)
).filter_by(
wh=False
)
<REPLACE_END> <|endoftext|> # -*- encoding: utf-8 -*-
import config
from flask import Blueprint
from flask import render_template
from lazyblacksmith.models import Activity
from lazyblacksmith.models import Item
from lazyblacksmith.models import Region
blueprint = Blueprint('blueprint', __name__)
@blueprint.route('/manufacturing/<int:item_id>')
def manufacturing(item_id):
"""
Display the manufacturing page with all data
"""
item = Item.query.get(item_id)
activity = item.activities.filter_by(activity=Activity.ACTIVITY_MANUFACTURING).one()
materials = item.activity_materials.filter_by(activity=Activity.ACTIVITY_MANUFACTURING)
product = item.activity_products.filter_by(activity=Activity.ACTIVITY_MANUFACTURING).one()
regions = Region.query.filter(
Region.id.in_(config.CREST_REGION_PRICE)
).filter_by(
wh=False
)
# is any of the materials manufactured ?
has_manufactured_components = False
for material in materials:
if material.material.is_manufactured():
has_manufactured_components = True
break
return render_template('blueprint/manufacturing.html', **{
'blueprint': item,
'materials': materials,
'activity': activity,
'product': product,
'regions': regions,
'has_manufactured_components': has_manufactured_components,
})
@blueprint.route('/')
def search():
return render_template('blueprint/search.html')
| Change region list to match config
# -*- encoding: utf-8 -*-
from flask import Blueprint
from flask import render_template
from lazyblacksmith.models import Activity
from lazyblacksmith.models import Item
from lazyblacksmith.models import Region
blueprint = Blueprint('blueprint', __name__)
@blueprint.route('/manufacturing/<int:item_id>')
def manufacturing(item_id):
"""
Display the manufacturing page with all data
"""
item = Item.query.get(item_id)
activity = item.activities.filter_by(activity=Activity.ACTIVITY_MANUFACTURING).one()
materials = item.activity_materials.filter_by(activity=Activity.ACTIVITY_MANUFACTURING)
product = item.activity_products.filter_by(activity=Activity.ACTIVITY_MANUFACTURING).one()
regions = Region.query.filter_by(wh=False)
# is any of the materials manufactured ?
has_manufactured_components = False
for material in materials:
if material.material.is_manufactured():
has_manufactured_components = True
break
return render_template('blueprint/manufacturing.html', **{
'blueprint': item,
'materials': materials,
'activity': activity,
'product': product,
'regions': regions,
'has_manufactured_components': has_manufactured_components,
})
@blueprint.route('/')
def search():
return render_template('blueprint/search.html')
|
b5ae6290382ef69f9d76c0494aee90f85bdf2c16 | plugins/Views/SimpleView/__init__.py | plugins/Views/SimpleView/__init__.py | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import SimpleView
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"plugin": {
"name": i18n_catalog.i18nc("@label", "Simple View"),
"author": "Ultimaker",
"version": "1.0",
"decription": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple solid mesh view."),
"api": 2
},
"view": {
"name": i18n_catalog.i18nc("@item:inmenu", "Simple"),
"visible": False
}
}
def register(app):
return { "view": SimpleView.SimpleView() }
| # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import SimpleView
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"type": "view",
"plugin": {
"name": i18n_catalog.i18nc("@label", "Simple View"),
"author": "Ultimaker",
"version": "1.0",
"description": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple solid mesh view."),
"api": 2
},
"view": {
"name": i18n_catalog.i18nc("@item:inmenu", "Simple"),
"visible": False
}
}
def register(app):
return { "view": SimpleView.SimpleView() }
| Fix plug-in type and description key | Fix plug-in type and description key
't Was a typo.
Contributes to issue CURA-1190.
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | <INSERT> "type": "view",
<INSERT_END> <REPLACE_OLD> "decription": <REPLACE_NEW> "description": <REPLACE_END> <|endoftext|> # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import SimpleView
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"type": "view",
"plugin": {
"name": i18n_catalog.i18nc("@label", "Simple View"),
"author": "Ultimaker",
"version": "1.0",
"description": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple solid mesh view."),
"api": 2
},
"view": {
"name": i18n_catalog.i18nc("@item:inmenu", "Simple"),
"visible": False
}
}
def register(app):
return { "view": SimpleView.SimpleView() }
| Fix plug-in type and description key
't Was a typo.
Contributes to issue CURA-1190.
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import SimpleView
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"plugin": {
"name": i18n_catalog.i18nc("@label", "Simple View"),
"author": "Ultimaker",
"version": "1.0",
"decription": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple solid mesh view."),
"api": 2
},
"view": {
"name": i18n_catalog.i18nc("@item:inmenu", "Simple"),
"visible": False
}
}
def register(app):
return { "view": SimpleView.SimpleView() }
|
0404f6ebc33d83fc6dfeceed5d9370e73ef40e64 | awx/main/conf.py | awx/main/conf.py | # Copyright (c) 2015 Ansible, Inc..
# All Rights Reserved.
import json
from django.conf import settings as django_settings
from awx.main.models.configuration import TowerSettings
class TowerConfiguration(object):
def __getattr__(self, key):
ts = TowerSettings.objects.filter(key=key)
if not ts.exists():
return getattr(django_settings, key)
return ts[0].value_converted
def create(key, value):
settings_manifest = django_settings.TOWER_SETTINGS_MANIFEST
if key not in settings_manifest:
raise AttributeError("Tower Setting with key '{0}' does not exist".format(key))
settings_entry = settings_manifest[key]
setting_actual = TowerSettings.objects.filter(key=key)
if not settings_actual.exists():
settings_actual = TowerSettings(key=key,
description=settings_entry['description'],
category=settings_entry['category'],
value=value,
value_type=settings_entry['type'])
else:
settings_actual['value'] = value
settings_actual.save()
tower_settings = TowerConfiguration()
| # Copyright (c) 2015 Ansible, Inc..
# All Rights Reserved.
import json
from django.conf import settings as django_settings
from awx.main.models.configuration import TowerSettings
class TowerConfiguration(object):
# TODO: Caching so we don't have to hit the database every time for settings
def __getattr__(self, key):
ts = TowerSettings.objects.filter(key=key)
if not ts.exists():
return getattr(django_settings, key)
return ts[0].value_converted
def create(key, value):
settings_manifest = django_settings.TOWER_SETTINGS_MANIFEST
if key not in settings_manifest:
raise AttributeError("Tower Setting with key '{0}' does not exist".format(key))
settings_entry = settings_manifest[key]
setting_actual = TowerSettings.objects.filter(key=key)
if not settings_actual.exists():
settings_actual = TowerSettings(key=key,
description=settings_entry['description'],
category=settings_entry['category'],
value=value,
value_type=settings_entry['type'])
else:
settings_actual['value'] = value
settings_actual.save()
tower_settings = TowerConfiguration()
| Add a note about caching | Add a note about caching
| Python | apache-2.0 | snahelou/awx,wwitzel3/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,snahelou/awx | <INSERT> # TODO: Caching so we don't have to hit the database every time for settings
<INSERT_END> <|endoftext|> # Copyright (c) 2015 Ansible, Inc..
# All Rights Reserved.
import json
from django.conf import settings as django_settings
from awx.main.models.configuration import TowerSettings
class TowerConfiguration(object):
# TODO: Caching so we don't have to hit the database every time for settings
def __getattr__(self, key):
ts = TowerSettings.objects.filter(key=key)
if not ts.exists():
return getattr(django_settings, key)
return ts[0].value_converted
def create(key, value):
settings_manifest = django_settings.TOWER_SETTINGS_MANIFEST
if key not in settings_manifest:
raise AttributeError("Tower Setting with key '{0}' does not exist".format(key))
settings_entry = settings_manifest[key]
setting_actual = TowerSettings.objects.filter(key=key)
if not settings_actual.exists():
settings_actual = TowerSettings(key=key,
description=settings_entry['description'],
category=settings_entry['category'],
value=value,
value_type=settings_entry['type'])
else:
settings_actual['value'] = value
settings_actual.save()
tower_settings = TowerConfiguration()
| Add a note about caching
# Copyright (c) 2015 Ansible, Inc..
# All Rights Reserved.
import json
from django.conf import settings as django_settings
from awx.main.models.configuration import TowerSettings
class TowerConfiguration(object):
def __getattr__(self, key):
ts = TowerSettings.objects.filter(key=key)
if not ts.exists():
return getattr(django_settings, key)
return ts[0].value_converted
def create(key, value):
settings_manifest = django_settings.TOWER_SETTINGS_MANIFEST
if key not in settings_manifest:
raise AttributeError("Tower Setting with key '{0}' does not exist".format(key))
settings_entry = settings_manifest[key]
setting_actual = TowerSettings.objects.filter(key=key)
if not settings_actual.exists():
settings_actual = TowerSettings(key=key,
description=settings_entry['description'],
category=settings_entry['category'],
value=value,
value_type=settings_entry['type'])
else:
settings_actual['value'] = value
settings_actual.save()
tower_settings = TowerConfiguration()
|
2a61cdcad1de2d4b080a91e7eaca714a3e2ec68b | test/lib/environment_test.py | test/lib/environment_test.py | # Run the following command to test:
#
# (in /usr/local/googkit)
# $ python -m {test_module_name}
#
# See also: http://docs.python.org/3.3/library/unittest.html#command-line-interface
#
# We cannot use unittest.mock on python 2.x!
# Please install the Mock module when you use Python 2.x.
#
# $ easy_install -U Mock
#
# See also: http://www.voidspace.org.uk/python/mock/#installing
import unittest
import os
try:
# Python 3.3 or later
import unittest.mock as mock
except ImportError:
# Python 2.x or 3.2-
import mock
from lib.environment import Environment
class TestEnvironmtnt(unittest.TestCase):
# run {{{
def test_init(self):
args = mock.MagicMock()
config = mock.MagicMock()
env = Environment(args, config)
self.assertEqual(env.args, args)
self.assertEqual(env.config, config)
# }}}
if __name__ == '__main__':
unittest.main()
# vim: fdm=marker
| Add a test for lib.environment | Add a test for lib.environment
| Python | mit | googkit/googkit,googkit/googkit,googkit/googkit | <INSERT> # Run the following command to test:
#
# <INSERT_END> <INSERT> (in /usr/local/googkit)
# $ python -m {test_module_name}
#
# See also: http://docs.python.org/3.3/library/unittest.html#command-line-interface
#
# We cannot use unittest.mock on python 2.x!
# Please install the Mock module when you use Python 2.x.
#
# $ easy_install -U Mock
#
# See also: http://www.voidspace.org.uk/python/mock/#installing
import unittest
import os
try:
# Python 3.3 or later
import unittest.mock as mock
except ImportError:
# Python 2.x or 3.2-
import mock
from lib.environment import Environment
class TestEnvironmtnt(unittest.TestCase):
# run {{{
def test_init(self):
args = mock.MagicMock()
config = mock.MagicMock()
env = Environment(args, config)
self.assertEqual(env.args, args)
self.assertEqual(env.config, config)
# }}}
if __name__ == '__main__':
unittest.main()
# vim: fdm=marker
<INSERT_END> <|endoftext|> # Run the following command to test:
#
# (in /usr/local/googkit)
# $ python -m {test_module_name}
#
# See also: http://docs.python.org/3.3/library/unittest.html#command-line-interface
#
# We cannot use unittest.mock on python 2.x!
# Please install the Mock module when you use Python 2.x.
#
# $ easy_install -U Mock
#
# See also: http://www.voidspace.org.uk/python/mock/#installing
import unittest
import os
try:
# Python 3.3 or later
import unittest.mock as mock
except ImportError:
# Python 2.x or 3.2-
import mock
from lib.environment import Environment
class TestEnvironmtnt(unittest.TestCase):
# run {{{
def test_init(self):
args = mock.MagicMock()
config = mock.MagicMock()
env = Environment(args, config)
self.assertEqual(env.args, args)
self.assertEqual(env.config, config)
# }}}
if __name__ == '__main__':
unittest.main()
# vim: fdm=marker
| Add a test for lib.environment
|
|
35974efcbae0c8a1b3009d7a2f38c73a52ff5790 | powerdns/admin.py | powerdns/admin.py | # -*- coding: utf-8 -*-
from django.contrib import admin
from powerdns.models import Domain, Record, Supermaster
class RecordAdmin(admin.ModelAdmin):
list_display = ('name', 'type', 'content', 'ttl', 'prio', 'change_date',)
list_filter = ['type', 'ttl',]
search_fields = ('name','content',)
class DomainAdmin(admin.ModelAdmin):
list_display = ('name', 'type', 'last_check', 'account',)
list_filter = ['type', 'last_check', 'account',]
search_fields = ('name',)
class SupermasterAdmin(admin.ModelAdmin):
list_display = ('ip', 'nameserver', 'account',)
list_filter = ['ip', 'account',]
search_fields = ('ip', 'nameserver',)
admin.site.register(Domain,DomainAdmin)
admin.site.register(Record,RecordAdmin)
admin.site.register(Supermaster,SupermasterAdmin)
| # -*- coding: utf-8 -*-
from django.contrib import admin
from powerdns.models import Domain, Record, Supermaster
class RecordAdmin(admin.ModelAdmin):
list_display = ('name', 'type', 'content', 'ttl', 'prio', 'change_date',)
list_filter = ['type', 'ttl',]
search_fields = ('name','content',)
readonly_fields = ('change_date',)
class DomainAdmin(admin.ModelAdmin):
list_display = ('name', 'type', 'last_check', 'account',)
list_filter = ['type', 'last_check', 'account',]
search_fields = ('name',)
readonly_fields = ('notified_serial',)
class SupermasterAdmin(admin.ModelAdmin):
list_display = ('ip', 'nameserver', 'account',)
list_filter = ['ip', 'account',]
search_fields = ('ip', 'nameserver',)
admin.site.register(Domain,DomainAdmin)
admin.site.register(Record,RecordAdmin)
admin.site.register(Supermaster,SupermasterAdmin)
| Mark some fields as readonly in the Admin panel as they are set by the server (Requires Django 1.2 or greater) | Mark some fields as readonly in the Admin panel as they are set by the server (Requires Django 1.2 or greater)
| Python | bsd-2-clause | dominikkowalski/django-powerdns-dnssec,zefciu/django-powerdns-dnssec,zefciu/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,allegro/django-powerdns-dnssec,allegro/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,allegro/django-powerdns-dnssec,allegro/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,zefciu/django-powerdns-dnssec | <REPLACE_OLD> ('name','content',)
class <REPLACE_NEW> ('name','content',)
readonly_fields = ('change_date',)
class <REPLACE_END> <REPLACE_OLD> ('name',)
class <REPLACE_NEW> ('name',)
readonly_fields = ('notified_serial',)
class <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from django.contrib import admin
from powerdns.models import Domain, Record, Supermaster
class RecordAdmin(admin.ModelAdmin):
list_display = ('name', 'type', 'content', 'ttl', 'prio', 'change_date',)
list_filter = ['type', 'ttl',]
search_fields = ('name','content',)
readonly_fields = ('change_date',)
class DomainAdmin(admin.ModelAdmin):
list_display = ('name', 'type', 'last_check', 'account',)
list_filter = ['type', 'last_check', 'account',]
search_fields = ('name',)
readonly_fields = ('notified_serial',)
class SupermasterAdmin(admin.ModelAdmin):
list_display = ('ip', 'nameserver', 'account',)
list_filter = ['ip', 'account',]
search_fields = ('ip', 'nameserver',)
admin.site.register(Domain,DomainAdmin)
admin.site.register(Record,RecordAdmin)
admin.site.register(Supermaster,SupermasterAdmin)
| Mark some fields as readonly in the Admin panel as they are set by the server (Requires Django 1.2 or greater)
# -*- coding: utf-8 -*-
from django.contrib import admin
from powerdns.models import Domain, Record, Supermaster
class RecordAdmin(admin.ModelAdmin):
list_display = ('name', 'type', 'content', 'ttl', 'prio', 'change_date',)
list_filter = ['type', 'ttl',]
search_fields = ('name','content',)
class DomainAdmin(admin.ModelAdmin):
list_display = ('name', 'type', 'last_check', 'account',)
list_filter = ['type', 'last_check', 'account',]
search_fields = ('name',)
class SupermasterAdmin(admin.ModelAdmin):
list_display = ('ip', 'nameserver', 'account',)
list_filter = ['ip', 'account',]
search_fields = ('ip', 'nameserver',)
admin.site.register(Domain,DomainAdmin)
admin.site.register(Record,RecordAdmin)
admin.site.register(Supermaster,SupermasterAdmin)
|
b8796c355bc8a763dbd2a5b6c5ed88a61f91eab7 | tests/test_conditionals.py | tests/test_conditionals.py | import pytest
from thinglang.runner import run
def test_simple_conditionals():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
if "dog" eq "cat"
Output.write("dog is cat")
""").output == """dog is dog""".strip()
def test_unconditional_else():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
otherwise
Output.write("dog is not dog")
if "dog" eq "cat"
Output.write("dog is cat")
otherwise
Output.write("dog is not cat")
""").output == """dog is dog\ndog is not cat""".strip()
def test_conditional_else():
assert run("""
thing Program
does start
if "dog" eq "cat"
Output.write("dog is cat")
otherwise if "dog" eq "dog"
Output.write("dog is dog")
otherwise
Output.write("dog is not dog and not cat")
""").output == """dog is dog\ndog is not cat""".strip()
| import pytest
from thinglang.runner import run
def test_simple_conditionals():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
if "dog" eq "cat"
Output.write("dog is cat")
""").output == """dog is dog""".strip()
def test_unconditional_else():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
otherwise
Output.write("dog is not dog")
if "dog" eq "cat"
Output.write("dog is cat")
otherwise
Output.write("dog is not cat")
""").output == """dog is dog\ndog is not cat""".strip()
def test_conditional_else():
assert run("""
thing Program
does start
if "dog" eq "cat"
Output.write("dog is cat")
otherwise if "dog" eq "dog"
Output.write("dog is dog")
otherwise if "dog" eq "dog"
Output.write("dog is still dog")
otherwise
Output.write("dog is not dog and not cat")
if "dog" eq "cat"
Output.write("dog is cat")
otherwise if "dog" eq "Dog"
Output.write("dog is Dog")
otherwise if "dog" eq "mouse"
Output.write("dog is mouse")
otherwise
Output.write("dog is not cat and not mouse and not Dog")
""").output == """dog is dog\ndog is not cat and not mouse and not Dog""".strip()
| Update conditional else branch tests | Update conditional else branch tests
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang | <INSERT> otherwise if "dog" eq "dog"
Output.write("dog is still dog")
<INSERT_END> <INSERT> cat")
if "dog" eq "cat"
Output.write("dog is <INSERT_END> <INSERT> otherwise if "dog" eq "Dog"
Output.write("dog is Dog")
otherwise if "dog" eq "mouse"
Output.write("dog is mouse")
otherwise
Output.write("dog is not cat and not mouse and not Dog")
<INSERT_END> <REPLACE_OLD> cat""".strip()
<REPLACE_NEW> cat and not mouse and not Dog""".strip()
<REPLACE_END> <|endoftext|> import pytest
from thinglang.runner import run
def test_simple_conditionals():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
if "dog" eq "cat"
Output.write("dog is cat")
""").output == """dog is dog""".strip()
def test_unconditional_else():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
otherwise
Output.write("dog is not dog")
if "dog" eq "cat"
Output.write("dog is cat")
otherwise
Output.write("dog is not cat")
""").output == """dog is dog\ndog is not cat""".strip()
def test_conditional_else():
assert run("""
thing Program
does start
if "dog" eq "cat"
Output.write("dog is cat")
otherwise if "dog" eq "dog"
Output.write("dog is dog")
otherwise if "dog" eq "dog"
Output.write("dog is still dog")
otherwise
Output.write("dog is not dog and not cat")
if "dog" eq "cat"
Output.write("dog is cat")
otherwise if "dog" eq "Dog"
Output.write("dog is Dog")
otherwise if "dog" eq "mouse"
Output.write("dog is mouse")
otherwise
Output.write("dog is not cat and not mouse and not Dog")
""").output == """dog is dog\ndog is not cat and not mouse and not Dog""".strip()
| Update conditional else branch tests
import pytest
from thinglang.runner import run
def test_simple_conditionals():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
if "dog" eq "cat"
Output.write("dog is cat")
""").output == """dog is dog""".strip()
def test_unconditional_else():
assert run("""
thing Program
does start
if "dog" eq "dog"
Output.write("dog is dog")
otherwise
Output.write("dog is not dog")
if "dog" eq "cat"
Output.write("dog is cat")
otherwise
Output.write("dog is not cat")
""").output == """dog is dog\ndog is not cat""".strip()
def test_conditional_else():
assert run("""
thing Program
does start
if "dog" eq "cat"
Output.write("dog is cat")
otherwise if "dog" eq "dog"
Output.write("dog is dog")
otherwise
Output.write("dog is not dog and not cat")
""").output == """dog is dog\ndog is not cat""".strip()
|
Subsets and Splits