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
19
3.3k
prompt
stringlengths
21
3.65k
7ad5e00abc9158951697e86242781567b82dd52c
oauth2_provider/generators.py
oauth2_provider/generators.py
from oauthlib.common import CLIENT_ID_CHARACTER_SET, generate_client_id as oauthlib_generate_client_id from .settings import oauth2_settings class BaseHashGenerator(object): """ All generators should extend this class overriding `.hash()` method. """ def hash(self): raise NotImplementedError() class ClientIdGenerator(BaseHashGenerator): def hash(self): """ Generate a client_id without colon char as in http://tools.ietf.org/html/rfc2617#section-2 for Basic Authentication scheme """ client_id_charset = CLIENT_ID_CHARACTER_SET.replace(":", "") return oauthlib_generate_client_id(length=40, chars=client_id_charset) class ClientSecretGenerator(BaseHashGenerator): def hash(self): return oauthlib_generate_client_id(length=128) def generate_client_id(): """ Generate a suitable client id """ client_id_generator = oauth2_settings.CLIENT_ID_GENERATOR_CLASS() return client_id_generator.hash() def generate_client_secret(): """ Generate a suitable client secret """ client_secret_generator = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS() return client_secret_generator.hash()
from oauthlib.common import generate_client_id as oauthlib_generate_client_id from .settings import oauth2_settings CLIENT_ID_CHARACTER_SET = r'_-.:;=?!@0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' class BaseHashGenerator(object): """ All generators should extend this class overriding `.hash()` method. """ def hash(self): raise NotImplementedError() class ClientIdGenerator(BaseHashGenerator): def hash(self): """ Generate a client_id without colon char as in http://tools.ietf.org/html/rfc2617#section-2 for Basic Authentication scheme """ client_id_charset = CLIENT_ID_CHARACTER_SET.replace(":", "") return oauthlib_generate_client_id(length=40, chars=client_id_charset) class ClientSecretGenerator(BaseHashGenerator): def hash(self): return oauthlib_generate_client_id(length=128, chars=CLIENT_ID_CHARACTER_SET) def generate_client_id(): """ Generate a suitable client id """ client_id_generator = oauth2_settings.CLIENT_ID_GENERATOR_CLASS() return client_id_generator.hash() def generate_client_secret(): """ Generate a suitable client secret """ client_secret_generator = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS() return client_secret_generator.hash()
Change default generator for client_id and client_secret: now use a safe set of characters that don't need escaping. That way we should avoid problems with many dummy client implementations
Change default generator for client_id and client_secret: now use a safe set of characters that don't need escaping. That way we should avoid problems with many dummy client implementations
Python
bsd-2-clause
cheif/django-oauth-toolkit,svetlyak40wt/django-oauth-toolkit,jensadne/django-oauth-toolkit,bleib1dj/django-oauth-toolkit,vmalavolta/django-oauth-toolkit,Knotis/django-oauth-toolkit,jensadne/django-oauth-toolkit,mjrulesamrat/django-oauth-toolkit,andrefsp/django-oauth-toolkit,DeskConnect/django-oauth-toolkit,CloudNcodeInc/django-oauth-toolkit,trbs/django-oauth-toolkit,JensTimmerman/django-oauth-toolkit,Gr1N/django-oauth-toolkit,trbs/django-oauth-toolkit,bleib1dj/django-oauth-toolkit,mjrulesamrat/django-oauth-toolkit,natgeo/django-oauth-toolkit,lzen/django-oauth-toolkit,Natgeoed/django-oauth-toolkit,Knotis/django-oauth-toolkit,lzen/django-oauth-toolkit,DeskConnect/django-oauth-toolkit,vmalavolta/django-oauth-toolkit,StepicOrg/django-oauth-toolkit,Gr1N/django-oauth-toolkit,drgarcia1986/django-oauth-toolkit,cheif/django-oauth-toolkit,StepicOrg/django-oauth-toolkit,JensTimmerman/django-oauth-toolkit,CloudNcodeInc/django-oauth-toolkit,drgarcia1986/django-oauth-toolkit,andrefsp/django-oauth-toolkit
from oauthlib.common import generate_client_id as oauthlib_generate_client_id from .settings import oauth2_settings CLIENT_ID_CHARACTER_SET = r'_-.:;=?!@0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' class BaseHashGenerator(object): """ All generators should extend this class overriding `.hash()` method. """ def hash(self): raise NotImplementedError() class ClientIdGenerator(BaseHashGenerator): def hash(self): """ Generate a client_id without colon char as in http://tools.ietf.org/html/rfc2617#section-2 for Basic Authentication scheme """ client_id_charset = CLIENT_ID_CHARACTER_SET.replace(":", "") return oauthlib_generate_client_id(length=40, chars=client_id_charset) class ClientSecretGenerator(BaseHashGenerator): def hash(self): return oauthlib_generate_client_id(length=128, chars=CLIENT_ID_CHARACTER_SET) def generate_client_id(): """ Generate a suitable client id """ client_id_generator = oauth2_settings.CLIENT_ID_GENERATOR_CLASS() return client_id_generator.hash() def generate_client_secret(): """ Generate a suitable client secret """ client_secret_generator = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS() return client_secret_generator.hash()
Change default generator for client_id and client_secret: now use a safe set of characters that don't need escaping. That way we should avoid problems with many dummy client implementations from oauthlib.common import CLIENT_ID_CHARACTER_SET, generate_client_id as oauthlib_generate_client_id from .settings import oauth2_settings class BaseHashGenerator(object): """ All generators should extend this class overriding `.hash()` method. """ def hash(self): raise NotImplementedError() class ClientIdGenerator(BaseHashGenerator): def hash(self): """ Generate a client_id without colon char as in http://tools.ietf.org/html/rfc2617#section-2 for Basic Authentication scheme """ client_id_charset = CLIENT_ID_CHARACTER_SET.replace(":", "") return oauthlib_generate_client_id(length=40, chars=client_id_charset) class ClientSecretGenerator(BaseHashGenerator): def hash(self): return oauthlib_generate_client_id(length=128) def generate_client_id(): """ Generate a suitable client id """ client_id_generator = oauth2_settings.CLIENT_ID_GENERATOR_CLASS() return client_id_generator.hash() def generate_client_secret(): """ Generate a suitable client secret """ client_secret_generator = oauth2_settings.CLIENT_SECRET_GENERATOR_CLASS() return client_secret_generator.hash()
3abe25d2272e2a0111511b68407da0ef3c53f59e
nazs/samba/module.py
nazs/samba/module.py
from nazs import module from nazs.commands import run from nazs.sudo import root import os import logging logger = logging.getLogger(__name__) class Samba(module.Module): """ Samba 4 module, it deploys samba AD and file server """ ETC_FILE = '/etc/samba/smb.conf' install_wizard = 'samba:install' def install(self): """ Installation procedure, it writes basic smb.conf and uses samba-tool to provision the domain """ with root(): if os.path.exists(self.ETC_FILE): os.remove(self.ETC_FILE) run("samba-tool domain provision " " --domain='zentyal' " " --workgroup='zentyal' " "--realm='zentyal.lan' " "--use-xattrs=yes " "--use-rfc2307 " "--server-role='domain controller' " "--use-ntvfs " "--adminpass='foobar1!'")
from nazs import module from nazs.commands import run from nazs.sudo import root import os import logging from .models import DomainSettings logger = logging.getLogger(__name__) class Samba(module.Module): """ Samba 4 module, it deploys samba AD and file server """ ETC_FILE = '/etc/samba/smb.conf' install_wizard = 'samba:install' def install(self): """ Installation procedure, it writes basic smb.conf and uses samba-tool to provision the domain """ domain_settings = DomainSettings.get() with root(): if os.path.exists(self.ETC_FILE): os.remove(self.ETC_FILE) if domain_settings.mode == 'ad': run("samba-tool domain provision " " --domain='zentyal' " " --workgroup='zentyal' " "--realm='zentyal.lan' " "--use-xattrs=yes " "--use-rfc2307 " "--server-role='domain controller' " "--use-ntvfs " "--adminpass='foobar1!'") elif domain_settings.mode == 'member': # TODO pass
Use wizard settings during samba provision
Use wizard settings during samba provision
Python
agpl-3.0
exekias/droplet,exekias/droplet,exekias/droplet
from nazs import module from nazs.commands import run from nazs.sudo import root import os import logging from .models import DomainSettings logger = logging.getLogger(__name__) class Samba(module.Module): """ Samba 4 module, it deploys samba AD and file server """ ETC_FILE = '/etc/samba/smb.conf' install_wizard = 'samba:install' def install(self): """ Installation procedure, it writes basic smb.conf and uses samba-tool to provision the domain """ domain_settings = DomainSettings.get() with root(): if os.path.exists(self.ETC_FILE): os.remove(self.ETC_FILE) if domain_settings.mode == 'ad': run("samba-tool domain provision " " --domain='zentyal' " " --workgroup='zentyal' " "--realm='zentyal.lan' " "--use-xattrs=yes " "--use-rfc2307 " "--server-role='domain controller' " "--use-ntvfs " "--adminpass='foobar1!'") elif domain_settings.mode == 'member': # TODO pass
Use wizard settings during samba provision from nazs import module from nazs.commands import run from nazs.sudo import root import os import logging logger = logging.getLogger(__name__) class Samba(module.Module): """ Samba 4 module, it deploys samba AD and file server """ ETC_FILE = '/etc/samba/smb.conf' install_wizard = 'samba:install' def install(self): """ Installation procedure, it writes basic smb.conf and uses samba-tool to provision the domain """ with root(): if os.path.exists(self.ETC_FILE): os.remove(self.ETC_FILE) run("samba-tool domain provision " " --domain='zentyal' " " --workgroup='zentyal' " "--realm='zentyal.lan' " "--use-xattrs=yes " "--use-rfc2307 " "--server-role='domain controller' " "--use-ntvfs " "--adminpass='foobar1!'")
453b6a8697b066174802257156ac364aed2c650a
emission/storage/timeseries/aggregate_timeseries.py
emission/storage/timeseries/aggregate_timeseries.py
import logging import pandas as pd import pymongo import emission.core.get_database as edb import emission.storage.timeseries.builtin_timeseries as bits class AggregateTimeSeries(bits.BuiltinTimeSeries): def __init__(self): super(AggregateTimeSeries, self).__init__(None) self.user_query = {}
import logging import pandas as pd import pymongo import emission.core.get_database as edb import emission.storage.timeseries.builtin_timeseries as bits class AggregateTimeSeries(bits.BuiltinTimeSeries): def __init__(self): super(AggregateTimeSeries, self).__init__(None) self.user_query = {} def _get_sort_key(self, time_query = None): return None
Implement a sort key method for the aggregate timeseries
Implement a sort key method for the aggregate timeseries This should return null because we want to mix up the identifying information from the timeseries and sorting will re-impose some order. Also sorting takes too much time!
Python
bsd-3-clause
shankari/e-mission-server,yw374cornell/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,yw374cornell/e-mission-server,sunil07t/e-mission-server,yw374cornell/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,yw374cornell/e-mission-server
import logging import pandas as pd import pymongo import emission.core.get_database as edb import emission.storage.timeseries.builtin_timeseries as bits class AggregateTimeSeries(bits.BuiltinTimeSeries): def __init__(self): super(AggregateTimeSeries, self).__init__(None) self.user_query = {} def _get_sort_key(self, time_query = None): return None
Implement a sort key method for the aggregate timeseries This should return null because we want to mix up the identifying information from the timeseries and sorting will re-impose some order. Also sorting takes too much time! import logging import pandas as pd import pymongo import emission.core.get_database as edb import emission.storage.timeseries.builtin_timeseries as bits class AggregateTimeSeries(bits.BuiltinTimeSeries): def __init__(self): super(AggregateTimeSeries, self).__init__(None) self.user_query = {}
01e62119750d0737e396358dbf45727dcbb5732f
tests/__init__.py
tests/__init__.py
import sys import unittest def main(): if sys.version_info[0] >= 3: from unittest.main import main main(module=None) else: unittest.main() if __name__ == '__main__': main()
from unittest.main import main if __name__ == '__main__': main(module=None, verbosity=2)
Drop Python 2 support in tests
Drop Python 2 support in tests
Python
bsd-3-clause
retext-project/pymarkups,mitya57/pymarkups
from unittest.main import main if __name__ == '__main__': main(module=None, verbosity=2)
Drop Python 2 support in tests import sys import unittest def main(): if sys.version_info[0] >= 3: from unittest.main import main main(module=None) else: unittest.main() if __name__ == '__main__': main()
a7908b4f6369f5a29e72fa828aff12285e3f3d25
app/applications.py
app/applications.py
from . import data_structures # 1. Stack application def balanced_parentheses_checker(symbol_string): """Verify that a set of parentheses is balanced.""" opening_symbols = '{[(' closing_symbols = '}])' opening_symbols_stack = data_structures.Stack() symbol_count = len(symbol_string) counter = 0 while counter < symbol_count: current_symbol = symbol_string[counter] if current_symbol in '{[(': opening_symbols_stack.push(current_symbol) else: if not opening_symbols_stack.is_empty() and \ opening_symbols.index(opening_symbols_stack.peek()) == \ closing_symbols.index(current_symbol): opening_symbols_stack.pop() else: counter = symbol_count counter += 1 return opening_symbols_stack.is_empty() and counter == symbol_count if __name__ == '__main__': print(balanced_parentheses_checker('[]{[]{([][])}()}'))
Apply stack in providing an efficient balanced parentheses-checker
Apply stack in providing an efficient balanced parentheses-checker
Python
mit
andela-kerinoso/data_structures_algo
from . import data_structures # 1. Stack application def balanced_parentheses_checker(symbol_string): """Verify that a set of parentheses is balanced.""" opening_symbols = '{[(' closing_symbols = '}])' opening_symbols_stack = data_structures.Stack() symbol_count = len(symbol_string) counter = 0 while counter < symbol_count: current_symbol = symbol_string[counter] if current_symbol in '{[(': opening_symbols_stack.push(current_symbol) else: if not opening_symbols_stack.is_empty() and \ opening_symbols.index(opening_symbols_stack.peek()) == \ closing_symbols.index(current_symbol): opening_symbols_stack.pop() else: counter = symbol_count counter += 1 return opening_symbols_stack.is_empty() and counter == symbol_count if __name__ == '__main__': print(balanced_parentheses_checker('[]{[]{([][])}()}'))
Apply stack in providing an efficient balanced parentheses-checker
f54db5d4e132fe1c227fe5bf1f7079772433429d
yunity/models/utils.py
yunity/models/utils.py
from django.db.models import Model, CharField, Field class MaxLengthCharField(CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 255 super().__init__(*args, **kwargs) class BaseModel(Model): class Meta: abstract = True def _get_explicit_field_names(self): return [field.name for field in self._meta.get_fields() if isinstance(field, Field) and field.name != 'id'] def to_dict(self): fields = self._get_explicit_field_names() return {field: getattr(self, field) for field in fields} def __repr__(self): return 'Model({})'.format(repr(self.to_dict()))
from django.db.models import Model, CharField, Field class MaxLengthCharField(CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 255 super().__init__(*args, **kwargs) class BaseModel(Model): class Meta: abstract = True def _get_explicit_field_names(self): return [field.name for field in self._meta.get_fields() if isinstance(field, Field) and field.name != 'id'] def to_dict(self): fields = self._get_explicit_field_names() return {field: getattr(self, field) for field in fields} def __repr__(self): model = str(self.__class__.__name__) columns = ', '.join('{}="{}"'.format(field, value) for field, value in self.to_dict().items()) return '{}({})'.format(model, columns)
Add columns and values to repr
Add columns and values to repr
Python
agpl-3.0
yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend
from django.db.models import Model, CharField, Field class MaxLengthCharField(CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 255 super().__init__(*args, **kwargs) class BaseModel(Model): class Meta: abstract = True def _get_explicit_field_names(self): return [field.name for field in self._meta.get_fields() if isinstance(field, Field) and field.name != 'id'] def to_dict(self): fields = self._get_explicit_field_names() return {field: getattr(self, field) for field in fields} def __repr__(self): model = str(self.__class__.__name__) columns = ', '.join('{}="{}"'.format(field, value) for field, value in self.to_dict().items()) return '{}({})'.format(model, columns)
Add columns and values to repr from django.db.models import Model, CharField, Field class MaxLengthCharField(CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 255 super().__init__(*args, **kwargs) class BaseModel(Model): class Meta: abstract = True def _get_explicit_field_names(self): return [field.name for field in self._meta.get_fields() if isinstance(field, Field) and field.name != 'id'] def to_dict(self): fields = self._get_explicit_field_names() return {field: getattr(self, field) for field in fields} def __repr__(self): return 'Model({})'.format(repr(self.to_dict()))
fbe7b34c575e30114c54587952c9aa919bc28d81
south/introspection_plugins/__init__.py
south/introspection_plugins/__init__.py
# This module contains built-in introspector plugins for various common # Django apps. # These imports trigger the lower-down files import south.introspection_plugins.geodjango import south.introspection_plugins.django_tagging import south.introspection_plugins.django_taggit import south.introspection_plugins.django_objectpermissions
# This module contains built-in introspector plugins for various common # Django apps. # These imports trigger the lower-down files import south.introspection_plugins.geodjango import south.introspection_plugins.django_tagging import south.introspection_plugins.django_taggit import south.introspection_plugins.django_objectpermissions import south.introspection_plugins.annoying_autoonetoone
Add import of django-annoying patch
Add import of django-annoying patch
Python
apache-2.0
theatlantic/django-south,theatlantic/django-south
# This module contains built-in introspector plugins for various common # Django apps. # These imports trigger the lower-down files import south.introspection_plugins.geodjango import south.introspection_plugins.django_tagging import south.introspection_plugins.django_taggit import south.introspection_plugins.django_objectpermissions import south.introspection_plugins.annoying_autoonetoone
Add import of django-annoying patch # This module contains built-in introspector plugins for various common # Django apps. # These imports trigger the lower-down files import south.introspection_plugins.geodjango import south.introspection_plugins.django_tagging import south.introspection_plugins.django_taggit import south.introspection_plugins.django_objectpermissions
b0d9a11292b6d6b17fe8b72d7735d26c47599187
linkatos/printer.py
linkatos/printer.py
def bot_says(channel, text, slack_client): return slack_client.api_call("chat.postMessage", channel=channel, text=text, as_user=True) def compose_explanation(url): return "If you would like {} to be stored please react to it with a :+1:, \ if you would like it to be ignored use :-1:".format(url) def ask_confirmation(message, slack_client): bot_says(message['channel'], compose_explanation(message['url']), slack_client) def compose_url_list(url_cache_list): if len(url_cache_list) == 0: return "The list is empty" list_message = "The list of urls to be confirmed is: \n" for index in range(0, len(url_cache_list)): extra = "{} - {} \n".format(index, url_cache_list[index]['url']) list_message = list_message + extra return list_message def list_cached_urls(url_cache_list, channel, slack_client): bot_says(channel, compose_url_list(url_cache_list), slack_client)
def bot_says(channel, text, slack_client): return slack_client.api_call("chat.postMessage", channel=channel, text=text, as_user=True) def compose_explanation(url): return "If you would like {} to be stored please react to it with a :+1:, \ if you would like it to be ignored use :-1:".format(url) def ask_confirmation(message, slack_client): bot_says(message['channel'], compose_explanation(message['url']), slack_client) def compose_url_list(url_cache_list): if len(url_cache_list) == 0: return "The list is empty" intro = "The list of urls to be confirmed is: \n" options = ["{} - {}".format(i, v['url']) for i, v in enumerate(url_cache_list)] return intro + "\n".join(options) def list_cached_urls(url_cache_list, channel, slack_client): bot_says(channel, compose_url_list(url_cache_list), slack_client)
Change iteration over a collection based on ags suggestion
refactor: Change iteration over a collection based on ags suggestion
Python
mit
iwi/linkatos,iwi/linkatos
def bot_says(channel, text, slack_client): return slack_client.api_call("chat.postMessage", channel=channel, text=text, as_user=True) def compose_explanation(url): return "If you would like {} to be stored please react to it with a :+1:, \ if you would like it to be ignored use :-1:".format(url) def ask_confirmation(message, slack_client): bot_says(message['channel'], compose_explanation(message['url']), slack_client) def compose_url_list(url_cache_list): if len(url_cache_list) == 0: return "The list is empty" intro = "The list of urls to be confirmed is: \n" options = ["{} - {}".format(i, v['url']) for i, v in enumerate(url_cache_list)] return intro + "\n".join(options) def list_cached_urls(url_cache_list, channel, slack_client): bot_says(channel, compose_url_list(url_cache_list), slack_client)
refactor: Change iteration over a collection based on ags suggestion def bot_says(channel, text, slack_client): return slack_client.api_call("chat.postMessage", channel=channel, text=text, as_user=True) def compose_explanation(url): return "If you would like {} to be stored please react to it with a :+1:, \ if you would like it to be ignored use :-1:".format(url) def ask_confirmation(message, slack_client): bot_says(message['channel'], compose_explanation(message['url']), slack_client) def compose_url_list(url_cache_list): if len(url_cache_list) == 0: return "The list is empty" list_message = "The list of urls to be confirmed is: \n" for index in range(0, len(url_cache_list)): extra = "{} - {} \n".format(index, url_cache_list[index]['url']) list_message = list_message + extra return list_message def list_cached_urls(url_cache_list, channel, slack_client): bot_says(channel, compose_url_list(url_cache_list), slack_client)
ee2e1727ece6b591b39752a1d3cd6a87d972226d
github3/search/code.py
github3/search/code.py
# -*- coding: utf-8 -*- from github3.models import GitHubCore from github3.repos import Repository class CodeSearchResult(GitHubCore): def __init__(self, data, session=None): super(CodeSearchResult, self).__init__(data, session) self._api = data.get('url') #: Filename the match occurs in self.name = data.get('name') #: Path in the repository to the file self.path = data.get('path') #: SHA in which the code can be found self.sha = data.get('sha') #: URL to the Git blob endpoint self.git_url = data.get('git_url') #: URL to the HTML view of the blob self.html_url = data.get('html_url') #: Repository the code snippet belongs to self.repository = Repository(data.get('repository', {}), self) #: Score of the result self.score = data.get('score') #: Text matches self.text_matches = data.get('text_matches', [])
# -*- coding: utf-8 -*- from github3.models import GitHubCore from github3.repos import Repository class CodeSearchResult(GitHubCore): def __init__(self, data, session=None): super(CodeSearchResult, self).__init__(data, session) self._api = data.get('url') #: Filename the match occurs in self.name = data.get('name') #: Path in the repository to the file self.path = data.get('path') #: SHA in which the code can be found self.sha = data.get('sha') #: URL to the Git blob endpoint self.git_url = data.get('git_url') #: URL to the HTML view of the blob self.html_url = data.get('html_url') #: Repository the code snippet belongs to self.repository = Repository(data.get('repository', {}), self) #: Score of the result self.score = data.get('score') #: Text matches self.text_matches = data.get('text_matches', []) def __repr__(self): return '<CodeSearchResult [{0}]>'.format(self.path)
Add a __repr__ for CodeSearchResult
Add a __repr__ for CodeSearchResult
Python
bsd-3-clause
h4ck3rm1k3/github3.py,ueg1990/github3.py,degustaf/github3.py,krxsky/github3.py,sigmavirus24/github3.py,itsmemattchung/github3.py,agamdua/github3.py,wbrefvem/github3.py,jim-minter/github3.py,icio/github3.py,christophelec/github3.py,balloob/github3.py
# -*- coding: utf-8 -*- from github3.models import GitHubCore from github3.repos import Repository class CodeSearchResult(GitHubCore): def __init__(self, data, session=None): super(CodeSearchResult, self).__init__(data, session) self._api = data.get('url') #: Filename the match occurs in self.name = data.get('name') #: Path in the repository to the file self.path = data.get('path') #: SHA in which the code can be found self.sha = data.get('sha') #: URL to the Git blob endpoint self.git_url = data.get('git_url') #: URL to the HTML view of the blob self.html_url = data.get('html_url') #: Repository the code snippet belongs to self.repository = Repository(data.get('repository', {}), self) #: Score of the result self.score = data.get('score') #: Text matches self.text_matches = data.get('text_matches', []) def __repr__(self): return '<CodeSearchResult [{0}]>'.format(self.path)
Add a __repr__ for CodeSearchResult # -*- coding: utf-8 -*- from github3.models import GitHubCore from github3.repos import Repository class CodeSearchResult(GitHubCore): def __init__(self, data, session=None): super(CodeSearchResult, self).__init__(data, session) self._api = data.get('url') #: Filename the match occurs in self.name = data.get('name') #: Path in the repository to the file self.path = data.get('path') #: SHA in which the code can be found self.sha = data.get('sha') #: URL to the Git blob endpoint self.git_url = data.get('git_url') #: URL to the HTML view of the blob self.html_url = data.get('html_url') #: Repository the code snippet belongs to self.repository = Repository(data.get('repository', {}), self) #: Score of the result self.score = data.get('score') #: Text matches self.text_matches = data.get('text_matches', [])
82162a334595ad47090dc1a8991d53ab5ece3736
components/expression_evaluator.py
components/expression_evaluator.py
"""A set of utility functions to evaluate expressions. Sample Usage: print(SgExpressionEvaluator.EvaluateExpressionInRow(["a", "bb", "ccc"], [1, 2, 3], "bb + 2.0 + ccc / a")) print(SgExpressionEvaluator.EvaluateExpressionsInRow(["a", "bb", "ccc"], [1, 2, 3], ["bb + 2.0 + ccc / a", "a + bb + ccc"])) t = tb.SgTable() t.SetFields(["a", "bb", "ccc"]) t.Append([1, 2, 3]) t.Append([2, 4, 6]) print(SgExpressionEvaluator.EvaluateExpressionsInTable(t, ["bb + 2.0 + ccc / a", "a + bb + ccc"])) """ import table as tb class SgExpressionEvaluator: """A set of utility functions to evaluate expressions.""" @staticmethod def EvaluateExpressionInRow(fields, row, expr): """ Evaluates the results of an expression (presumably a non-terminal field) given a list of fields and the values of a row. """ # TODO(lnishan): This works for now, but in the future we might want to implement # a proper evaluator (correct tokenization, 2-stack evaluation) pairs = zip(fields, row) pairs.sort(key=lambda p: len(p[0]), reverse=True) for pair in pairs: expr = expr.replace(pair[0], str(pair[1])) return eval(expr) @staticmethod def EvaluateExpressionsInRow(fields, row, exprs): return [SgExpressionEvaluator.EvaluateExpressionInRow(fields, row, expr) for expr in exprs] @staticmethod def EvaluateExpressionsInTable(table, exprs): ret = tb.SgTable() ret.SetFields(exprs) for row in table: ret.Append(SgExpressionEvaluator.EvaluateExpressionsInRow(table.GetFields(), row, exprs)) return ret
Add SgExpressionEvaluator - Evaluates expressions given fields and values
Add SgExpressionEvaluator - Evaluates expressions given fields and values
Python
mit
lnishan/SQLGitHub
"""A set of utility functions to evaluate expressions. Sample Usage: print(SgExpressionEvaluator.EvaluateExpressionInRow(["a", "bb", "ccc"], [1, 2, 3], "bb + 2.0 + ccc / a")) print(SgExpressionEvaluator.EvaluateExpressionsInRow(["a", "bb", "ccc"], [1, 2, 3], ["bb + 2.0 + ccc / a", "a + bb + ccc"])) t = tb.SgTable() t.SetFields(["a", "bb", "ccc"]) t.Append([1, 2, 3]) t.Append([2, 4, 6]) print(SgExpressionEvaluator.EvaluateExpressionsInTable(t, ["bb + 2.0 + ccc / a", "a + bb + ccc"])) """ import table as tb class SgExpressionEvaluator: """A set of utility functions to evaluate expressions.""" @staticmethod def EvaluateExpressionInRow(fields, row, expr): """ Evaluates the results of an expression (presumably a non-terminal field) given a list of fields and the values of a row. """ # TODO(lnishan): This works for now, but in the future we might want to implement # a proper evaluator (correct tokenization, 2-stack evaluation) pairs = zip(fields, row) pairs.sort(key=lambda p: len(p[0]), reverse=True) for pair in pairs: expr = expr.replace(pair[0], str(pair[1])) return eval(expr) @staticmethod def EvaluateExpressionsInRow(fields, row, exprs): return [SgExpressionEvaluator.EvaluateExpressionInRow(fields, row, expr) for expr in exprs] @staticmethod def EvaluateExpressionsInTable(table, exprs): ret = tb.SgTable() ret.SetFields(exprs) for row in table: ret.Append(SgExpressionEvaluator.EvaluateExpressionsInRow(table.GetFields(), row, exprs)) return ret
Add SgExpressionEvaluator - Evaluates expressions given fields and values
2bcf80e71ffc75796ef7d3667f61e57a884e5c5b
angr/__init__.py
angr/__init__.py
""" Angr module """ # pylint: disable=wildcard-import import logging logging.getLogger("angr").addHandler(logging.NullHandler()) from .project import * from .functionmanager import * from .variableseekr import * from .regmap import * from .path import * from .errors import * from .surveyor import * from .service import * from .analyses import * from .analysis import * from .tablespecs import * from . import surveyors from .blade import Blade from .simos import SimOS from .path_group import PathGroup from .surveyors.caller import Callable from .log import Loggers loggers = Loggers()
""" Angr module """ # pylint: disable=wildcard-import import logging logging.getLogger("angr").addHandler(logging.NullHandler()) from .project import * from .functionmanager import * from .variableseekr import * from .regmap import * from .path import * from .errors import * from .surveyor import * from .service import * from .analyses import * from .analysis import * from .tablespecs import * from . import surveyors from .blade import Blade from .simos import SimOS from .path_group import PathGroup from .surveyors.caller import Callable from .log import Loggers loggers = Loggers(logging.ERROR)
Make default logging level ERROR
Make default logging level ERROR
Python
bsd-2-clause
tyb0807/angr,axt/angr,chubbymaggie/angr,haylesr/angr,schieb/angr,chubbymaggie/angr,angr/angr,f-prettyland/angr,haylesr/angr,tyb0807/angr,axt/angr,angr/angr,angr/angr,schieb/angr,iamahuman/angr,chubbymaggie/angr,iamahuman/angr,schieb/angr,tyb0807/angr,iamahuman/angr,axt/angr,f-prettyland/angr,f-prettyland/angr
""" Angr module """ # pylint: disable=wildcard-import import logging logging.getLogger("angr").addHandler(logging.NullHandler()) from .project import * from .functionmanager import * from .variableseekr import * from .regmap import * from .path import * from .errors import * from .surveyor import * from .service import * from .analyses import * from .analysis import * from .tablespecs import * from . import surveyors from .blade import Blade from .simos import SimOS from .path_group import PathGroup from .surveyors.caller import Callable from .log import Loggers loggers = Loggers(logging.ERROR)
Make default logging level ERROR """ Angr module """ # pylint: disable=wildcard-import import logging logging.getLogger("angr").addHandler(logging.NullHandler()) from .project import * from .functionmanager import * from .variableseekr import * from .regmap import * from .path import * from .errors import * from .surveyor import * from .service import * from .analyses import * from .analysis import * from .tablespecs import * from . import surveyors from .blade import Blade from .simos import SimOS from .path_group import PathGroup from .surveyors.caller import Callable from .log import Loggers loggers = Loggers()
762908c10fc3d9a6c9e30d9328e96c2a8bf3ce46
setup.py
setup.py
""" The setup package to install MasterQA requirements """ from setuptools import setup, find_packages # noqa from os import path this_directory = path.abspath(path.dirname(__file__)) long_description = None try: with open(path.join(this_directory, 'README.md'), 'rb') as f: long_description = f.read().decode('utf-8') except IOError: long_description = ( 'Automation-Assisted Manual Testing - http://masterqa.com') setup( name='masterqa', version='1.1.5', description='Automation-Assisted Manual Testing - http://masterqa.com', long_description=long_description, platforms='Mac * Windows * Linux', url='http://masterqa.com', author='Michael Mintz', author_email='mdmintz@gmail.com', maintainer='Michael Mintz', license='The MIT License', install_requires=[ 'seleniumbase', ], packages=['masterqa'], entry_points={ 'nose.plugins': [] } )
""" The setup package to install MasterQA requirements """ from setuptools import setup, find_packages # noqa from os import path this_directory = path.abspath(path.dirname(__file__)) long_description = None try: with open(path.join(this_directory, 'README.md'), 'rb') as f: long_description = f.read().decode('utf-8') except IOError: long_description = ( 'Automation-Assisted Manual Testing - http://masterqa.com') setup( name='masterqa', version='1.1.5', description='Automation-Assisted Manual Testing - http://masterqa.com', long_description=long_description, long_description_content_type='text/markdown', platforms='Mac * Windows * Linux', url='http://masterqa.com', author='Michael Mintz', author_email='mdmintz@gmail.com', maintainer='Michael Mintz', license='The MIT License', install_requires=[ 'seleniumbase', ], packages=['masterqa'], entry_points={ 'nose.plugins': [] } )
Fix description content type for PyPi
Fix description content type for PyPi
Python
mit
masterqa/MasterQA,mdmintz/MasterQA
""" The setup package to install MasterQA requirements """ from setuptools import setup, find_packages # noqa from os import path this_directory = path.abspath(path.dirname(__file__)) long_description = None try: with open(path.join(this_directory, 'README.md'), 'rb') as f: long_description = f.read().decode('utf-8') except IOError: long_description = ( 'Automation-Assisted Manual Testing - http://masterqa.com') setup( name='masterqa', version='1.1.5', description='Automation-Assisted Manual Testing - http://masterqa.com', long_description=long_description, long_description_content_type='text/markdown', platforms='Mac * Windows * Linux', url='http://masterqa.com', author='Michael Mintz', author_email='mdmintz@gmail.com', maintainer='Michael Mintz', license='The MIT License', install_requires=[ 'seleniumbase', ], packages=['masterqa'], entry_points={ 'nose.plugins': [] } )
Fix description content type for PyPi """ The setup package to install MasterQA requirements """ from setuptools import setup, find_packages # noqa from os import path this_directory = path.abspath(path.dirname(__file__)) long_description = None try: with open(path.join(this_directory, 'README.md'), 'rb') as f: long_description = f.read().decode('utf-8') except IOError: long_description = ( 'Automation-Assisted Manual Testing - http://masterqa.com') setup( name='masterqa', version='1.1.5', description='Automation-Assisted Manual Testing - http://masterqa.com', long_description=long_description, platforms='Mac * Windows * Linux', url='http://masterqa.com', author='Michael Mintz', author_email='mdmintz@gmail.com', maintainer='Michael Mintz', license='The MIT License', install_requires=[ 'seleniumbase', ], packages=['masterqa'], entry_points={ 'nose.plugins': [] } )
508c9ef5f7dfd974fdad650cf1a211dad9d41db5
skipper/config.py
skipper/config.py
from string import Template from collections import defaultdict import os import yaml def load_defaults(): skipper_conf = 'skipper.yaml' defaults = {} if os.path.exists(skipper_conf): with open(skipper_conf) as confile: config = yaml.load(confile) containers = config.pop('containers', None) _normalize_config(config, defaults) if containers is not None: defaults['containers'] = containers return defaults def _normalize_config(config, normalized_config): for key, value in config.iteritems(): if isinstance(value, dict): normalized_config[key] = {} _normalize_config(value, normalized_config[key]) elif isinstance(value, list): normalized_config[key] = value else: normalized_key = key.replace('-', '_') normalized_config[normalized_key] = _interpolate_env_vars(value) def _interpolate_env_vars(key): return Template(key).substitute(defaultdict(lambda: "", os.environ))
from string import Template from collections import defaultdict import os import yaml def load_defaults(): skipper_conf = 'skipper.yaml' defaults = {} if os.path.exists(skipper_conf): with open(skipper_conf) as confile: config = yaml.load(confile) containers = config.pop('containers', None) _normalize_config(config, defaults) if containers is not None: defaults['containers'] = containers return defaults def _normalize_config(config, normalized_config): for key, value in config.iteritems(): if isinstance(value, dict): normalized_config[key] = {} _normalize_config(value, normalized_config[key]) elif isinstance(value, list): normalized_config[key] = [_interpolate_env_vars(x) for x in value] else: normalized_key = key.replace('-', '_') normalized_config[normalized_key] = _interpolate_env_vars(value) def _interpolate_env_vars(key): return Template(key).substitute(defaultdict(lambda: "", os.environ))
Handle env vars in volumes
Handle env vars in volumes
Python
apache-2.0
Stratoscale/skipper,Stratoscale/skipper
from string import Template from collections import defaultdict import os import yaml def load_defaults(): skipper_conf = 'skipper.yaml' defaults = {} if os.path.exists(skipper_conf): with open(skipper_conf) as confile: config = yaml.load(confile) containers = config.pop('containers', None) _normalize_config(config, defaults) if containers is not None: defaults['containers'] = containers return defaults def _normalize_config(config, normalized_config): for key, value in config.iteritems(): if isinstance(value, dict): normalized_config[key] = {} _normalize_config(value, normalized_config[key]) elif isinstance(value, list): normalized_config[key] = [_interpolate_env_vars(x) for x in value] else: normalized_key = key.replace('-', '_') normalized_config[normalized_key] = _interpolate_env_vars(value) def _interpolate_env_vars(key): return Template(key).substitute(defaultdict(lambda: "", os.environ))
Handle env vars in volumes from string import Template from collections import defaultdict import os import yaml def load_defaults(): skipper_conf = 'skipper.yaml' defaults = {} if os.path.exists(skipper_conf): with open(skipper_conf) as confile: config = yaml.load(confile) containers = config.pop('containers', None) _normalize_config(config, defaults) if containers is not None: defaults['containers'] = containers return defaults def _normalize_config(config, normalized_config): for key, value in config.iteritems(): if isinstance(value, dict): normalized_config[key] = {} _normalize_config(value, normalized_config[key]) elif isinstance(value, list): normalized_config[key] = value else: normalized_key = key.replace('-', '_') normalized_config[normalized_key] = _interpolate_env_vars(value) def _interpolate_env_vars(key): return Template(key).substitute(defaultdict(lambda: "", os.environ))
9c94c7c48f932e2134c2d520403fbfb09e464d95
pygameMidi_extended.py
pygameMidi_extended.py
#import pygame.midi.Output from pygame.midi import Output class Output(Output):#pygame.midi.Output): def set_pan(self, pan, channel): assert (0 <= channel <= 15) assert pan <= 127 self.write_short(0xB0 + channel, 0x0A, pan)
#import pygame.midi.Output from pygame.midi import Output class Output(Output):#pygame.midi.Output): def set_pan(self, pan, channel): assert (0 <= channel <= 15) assert pan <= 127 self.write_short(0xB0 + channel, 0x0A, pan) def set_volume(self, volume, channel): assert (0 <= channel <= 15) assert volume <= 127 self.write_short(0xB0 + channel, 0x07, volume) def set_pitch(self, pitch, channel): assert (0 <= channel <= 15) assert pitch <= (2**14-1) # the 7 least significant bits come into the first data byte, # the 7 most significant bits come into the second data byte pitch_lsb = (pitch >> 7) & 127 pitch_msb = pitch & 127 self.write_short(0xE0 + channel, pitch_lsb, pitch_msb)
Add Volume and Pitch methods
Add Volume and Pitch methods
Python
bsd-3-clause
RenolY2/py-playBMS
#import pygame.midi.Output from pygame.midi import Output class Output(Output):#pygame.midi.Output): def set_pan(self, pan, channel): assert (0 <= channel <= 15) assert pan <= 127 self.write_short(0xB0 + channel, 0x0A, pan) def set_volume(self, volume, channel): assert (0 <= channel <= 15) assert volume <= 127 self.write_short(0xB0 + channel, 0x07, volume) def set_pitch(self, pitch, channel): assert (0 <= channel <= 15) assert pitch <= (2**14-1) # the 7 least significant bits come into the first data byte, # the 7 most significant bits come into the second data byte pitch_lsb = (pitch >> 7) & 127 pitch_msb = pitch & 127 self.write_short(0xE0 + channel, pitch_lsb, pitch_msb)
Add Volume and Pitch methods #import pygame.midi.Output from pygame.midi import Output class Output(Output):#pygame.midi.Output): def set_pan(self, pan, channel): assert (0 <= channel <= 15) assert pan <= 127 self.write_short(0xB0 + channel, 0x0A, pan)
19a58255f247199d0e60408cab8220a8c2a1ff3b
qxlc/minifier.py
qxlc/minifier.py
import htmlmin from markupsafe import Markup from qxlc import app @app.template_filter("minify") def minify_filter(text): return Markup(htmlmin.minify(text.unescape(), remove_comments=True, remove_empty_space=True))
import htmlmin from markupsafe import Markup from qxlc import app @app.template_filter("minify") def minify_filter(s): return Markup(htmlmin.minify(str(s), remove_comments=True, remove_empty_space=True))
Use str(s) instead of s.unescape() to add support for escaping things inside. (took me a while to find that str() worked)
Use str(s) instead of s.unescape() to add support for escaping things inside. (took me a while to find that str() worked)
Python
apache-2.0
daboross/qxlc,daboross/qxlc
import htmlmin from markupsafe import Markup from qxlc import app @app.template_filter("minify") def minify_filter(s): return Markup(htmlmin.minify(str(s), remove_comments=True, remove_empty_space=True))
Use str(s) instead of s.unescape() to add support for escaping things inside. (took me a while to find that str() worked) import htmlmin from markupsafe import Markup from qxlc import app @app.template_filter("minify") def minify_filter(text): return Markup(htmlmin.minify(text.unescape(), remove_comments=True, remove_empty_space=True))
fa776fc0d3c568bda7d84ccd9b345e34c3fcf312
ideascube/mediacenter/tests/factories.py
ideascube/mediacenter/tests/factories.py
from django.conf import settings import factory from ..models import Document class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document
from django.conf import settings import factory from ..models import Document class EmptyFileField(factory.django.FileField): DEFAULT_FILENAME = None class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() preview = EmptyFileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document
Allow DocumentFactory to handle preview field.
Allow DocumentFactory to handle preview field. The factory.django.FileField.DEFAULT_FILENAME == 'example.dat'. It means that by default a FileField created by factoryboy is considered as a True value. Before this commit, we were not defining a Document.preview field in the factory so factoryboy created a empty FileField. To not break the API for other tests, we need to create a "False" FileField by default. To do so, we need to change the DEFAULT_FILENAME to None.
Python
agpl-3.0
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
from django.conf import settings import factory from ..models import Document class EmptyFileField(factory.django.FileField): DEFAULT_FILENAME = None class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() preview = EmptyFileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document
Allow DocumentFactory to handle preview field. The factory.django.FileField.DEFAULT_FILENAME == 'example.dat'. It means that by default a FileField created by factoryboy is considered as a True value. Before this commit, we were not defining a Document.preview field in the factory so factoryboy created a empty FileField. To not break the API for other tests, we need to create a "False" FileField by default. To do so, we need to change the DEFAULT_FILENAME to None. from django.conf import settings import factory from ..models import Document class DocumentFactory(factory.django.DjangoModelFactory): title = factory.Sequence(lambda n: "Test document {0}".format(n)) summary = "This is a test summary" lang = settings.LANGUAGE_CODE original = factory.django.FileField() credits = "Document credits" package_id = "" @factory.post_generation def tags(self, create, extracted, **kwargs): if extracted: self.tags.add(*extracted) class Meta: model = Document
f890663daa329e3f22d0f619ed6acf9365308c7c
apps/ignite/views.py
apps/ignite/views.py
from django.shortcuts import get_object_or_404 import jingo from challenges.models import Submission, Category from projects.models import Project def splash(request, project, slug, template_name='challenges/show.html'): """Show an individual project challenge.""" project = get_object_or_404(Project, slug=project) challenge = get_object_or_404(project.challenge_set, slug=slug) entries = Submission.objects.filter( phase__challenge=challenge ).exclude( is_draft=True ).extra( order_by="?" ) return jingo.render(request, 'ignite/splash.html', { 'challenge': challenge, 'project': project, 'phases': list(enumerate(challenge.phases.all(), start=1)), 'entries': entries[:10], 'categories': Category.objects.get_active_categories(), })
from django.shortcuts import get_object_or_404 import jingo from challenges.models import Submission, Category from projects.models import Project def splash(request, project, slug, template_name='challenges/show.html'): """Show an individual project challenge.""" project = get_object_or_404(Project, slug=project) challenge = get_object_or_404(project.challenge_set, slug=slug) entries = (Submission.objects.visible() .filter(phase__challenge=challenge) .order_by("?")) return jingo.render(request, 'ignite/splash.html', { 'challenge': challenge, 'project': project, 'phases': list(enumerate(challenge.phases.all(), start=1)), 'entries': entries[:10], 'categories': Category.objects.get_active_categories(), })
Update splash view to use visible() method.
Update splash view to use visible() method.
Python
bsd-3-clause
mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite
from django.shortcuts import get_object_or_404 import jingo from challenges.models import Submission, Category from projects.models import Project def splash(request, project, slug, template_name='challenges/show.html'): """Show an individual project challenge.""" project = get_object_or_404(Project, slug=project) challenge = get_object_or_404(project.challenge_set, slug=slug) entries = (Submission.objects.visible() .filter(phase__challenge=challenge) .order_by("?")) return jingo.render(request, 'ignite/splash.html', { 'challenge': challenge, 'project': project, 'phases': list(enumerate(challenge.phases.all(), start=1)), 'entries': entries[:10], 'categories': Category.objects.get_active_categories(), })
Update splash view to use visible() method. from django.shortcuts import get_object_or_404 import jingo from challenges.models import Submission, Category from projects.models import Project def splash(request, project, slug, template_name='challenges/show.html'): """Show an individual project challenge.""" project = get_object_or_404(Project, slug=project) challenge = get_object_or_404(project.challenge_set, slug=slug) entries = Submission.objects.filter( phase__challenge=challenge ).exclude( is_draft=True ).extra( order_by="?" ) return jingo.render(request, 'ignite/splash.html', { 'challenge': challenge, 'project': project, 'phases': list(enumerate(challenge.phases.all(), start=1)), 'entries': entries[:10], 'categories': Category.objects.get_active_categories(), })
cb7f4dfb9315c79448f2db52266df0f11aeb6210
setup.py
setup.py
from setuptools import setup, find_packages setup(name='coinop', version='0.0.3', description='Crypto-currency conveniences', url='http://github.com/BitVault/coinop-py', author='Matthew King', author_email='matthew@bitvault.io', license='MIT', packages=find_packages(exclude=[ u'*.tests', u'*.tests.*', u'tests.*', u'tests']), install_requires=[ # Not listed explicitly to ensure you install PyNaCl by hand-- # see README #'PyNaCl', 'cffi', 'pytest', 'pycrypto', 'python-bitcoinlib', 'pycoin', 'PyYAML', 'ecdsa' ], zip_safe=False)
from setuptools import setup, find_packages setup(name='coinop', version='0.1.0', description='Crypto-currency conveniences', url='http://github.com/BitVault/coinop-py', author='Matthew King', author_email='matthew@bitvault.io', license='MIT', packages=find_packages(exclude=[ u'*.tests', u'*.tests.*', u'tests.*', u'tests']), install_requires=[ # Not listed explicitly to ensure you install PyNaCl by hand-- # see README #'PyNaCl', 'cffi', 'pytest', 'pycrypto', 'python-bitcoinlib', 'pycoin', 'PyYAML', 'ecdsa' ], zip_safe=False)
Make version number match patchboard, bitvault
Make version number match patchboard, bitvault
Python
mit
GemHQ/coinop-py
from setuptools import setup, find_packages setup(name='coinop', version='0.1.0', description='Crypto-currency conveniences', url='http://github.com/BitVault/coinop-py', author='Matthew King', author_email='matthew@bitvault.io', license='MIT', packages=find_packages(exclude=[ u'*.tests', u'*.tests.*', u'tests.*', u'tests']), install_requires=[ # Not listed explicitly to ensure you install PyNaCl by hand-- # see README #'PyNaCl', 'cffi', 'pytest', 'pycrypto', 'python-bitcoinlib', 'pycoin', 'PyYAML', 'ecdsa' ], zip_safe=False)
Make version number match patchboard, bitvault from setuptools import setup, find_packages setup(name='coinop', version='0.0.3', description='Crypto-currency conveniences', url='http://github.com/BitVault/coinop-py', author='Matthew King', author_email='matthew@bitvault.io', license='MIT', packages=find_packages(exclude=[ u'*.tests', u'*.tests.*', u'tests.*', u'tests']), install_requires=[ # Not listed explicitly to ensure you install PyNaCl by hand-- # see README #'PyNaCl', 'cffi', 'pytest', 'pycrypto', 'python-bitcoinlib', 'pycoin', 'PyYAML', 'ecdsa' ], zip_safe=False)
f2eb45ea24429fd3e4d32a490dbe3f8a2f383d9f
scuole/stats/models/base.py
scuole/stats/models/base.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible from .staff_student import StaffStudentBase @python_2_unicode_compatible class SchoolYear(models.Model): name = models.CharField(max_length=9) def __str__(self): return self.name class StatsBase(StaffStudentBase): """ An abstract model representing stats commonly tracked across all entities in TEA data. Meant to be the base used by other apps for establishing their stats models. Example: class CampusStats(StatsBase): ... """ class Meta: abstract = True
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible from .staff_student import StaffStudentBase from .postsecondary_readiness import PostSecondaryReadinessBase @python_2_unicode_compatible class SchoolYear(models.Model): name = models.CharField(max_length=9) def __str__(self): return self.name class StatsBase(StaffStudentBase, PostSecondaryReadinessBase): """ An abstract model representing stats commonly tracked across all entities in TEA data. Meant to be the base used by other apps for establishing their stats models. Example: class CampusStats(StatsBase): ... """ class Meta: abstract = True
Add postsecondary stats to the StatsBase model
Add postsecondary stats to the StatsBase model
Python
mit
texastribune/scuole,texastribune/scuole,texastribune/scuole,texastribune/scuole
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible from .staff_student import StaffStudentBase from .postsecondary_readiness import PostSecondaryReadinessBase @python_2_unicode_compatible class SchoolYear(models.Model): name = models.CharField(max_length=9) def __str__(self): return self.name class StatsBase(StaffStudentBase, PostSecondaryReadinessBase): """ An abstract model representing stats commonly tracked across all entities in TEA data. Meant to be the base used by other apps for establishing their stats models. Example: class CampusStats(StatsBase): ... """ class Meta: abstract = True
Add postsecondary stats to the StatsBase model # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible from .staff_student import StaffStudentBase @python_2_unicode_compatible class SchoolYear(models.Model): name = models.CharField(max_length=9) def __str__(self): return self.name class StatsBase(StaffStudentBase): """ An abstract model representing stats commonly tracked across all entities in TEA data. Meant to be the base used by other apps for establishing their stats models. Example: class CampusStats(StatsBase): ... """ class Meta: abstract = True
e01697c5d5e5e45a0dd20870c71bb17399991ca1
setup.py
setup.py
import os from setuptools import setup, find_packages ROOT = os.path.abspath(os.path.dirname(__file__)) setup( name='django-nose', version='0.2', description='Django test runner that uses nose.', long_description=open(os.path.join(ROOT, 'README.rst')).read(), author='Jeff Balogh', author_email='me@jeffbalogh.org', url='http://github.com/jbalogh/django-nose', license='BSD', packages=find_packages(exclude=['testapp','testapp/*']), include_package_data=True, zip_safe=False, install_requires=['nose'], tests_require=['Django', 'south'], entry_points=""" [nose.plugins.0.10] fixture_bundler = django_nose.fixture_bundling:FixtureBundlingPlugin """, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
import os from setuptools import setup, find_packages ROOT = os.path.abspath(os.path.dirname(__file__)) setup( name='django-nose', version='0.2', description='Django test runner that uses nose.', long_description=open(os.path.join(ROOT, 'README.rst')).read(), author='Jeff Balogh', author_email='me@jeffbalogh.org', url='http://github.com/jbalogh/django-nose', license='BSD', packages=find_packages(exclude=['testapp','testapp/*']), include_package_data=True, zip_safe=False, install_requires=['nose'], tests_require=['Django', 'south'], # This blows up tox runs that install django-nose into a virtualenv, # because it causes Nose to import django_nose.runner before the Django # settings are initialized, leading to a mess of errors. There's no reason # we need FixtureBundlingPlugin declared as an entrypoint anyway, since you # need to be using django-nose to find the it useful, and django-nose knows # about it intrinsically. #entry_points=""" # [nose.plugins.0.10] # fixture_bundler = django_nose.fixture_bundling:FixtureBundlingPlugin # """, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
Comment out entrypoint because it blows up django-nose in connection with tox. Ouch.
Comment out entrypoint because it blows up django-nose in connection with tox. Ouch.
Python
bsd-3-clause
millerdev/django-nose,millerdev/django-nose,harukaeru/django-nose,dgladkov/django-nose,sociateru/django-nose,360youlun/django-nose,mzdaniel/django-nose,brilliant-org/django-nose,sociateru/django-nose,dgladkov/django-nose,krinart/django-nose,fabiosantoscode/django-nose-123-fix,mzdaniel/django-nose,franciscoruiz/django-nose,krinart/django-nose,alexhayes/django-nose,daineX/django-nose,alexhayes/django-nose,Deepomatic/django-nose,daineX/django-nose,fabiosantoscode/django-nose-123-fix,aristiden7o/django-nose,harukaeru/django-nose,franciscoruiz/django-nose,Deepomatic/django-nose,brilliant-org/django-nose,aristiden7o/django-nose,360youlun/django-nose
import os from setuptools import setup, find_packages ROOT = os.path.abspath(os.path.dirname(__file__)) setup( name='django-nose', version='0.2', description='Django test runner that uses nose.', long_description=open(os.path.join(ROOT, 'README.rst')).read(), author='Jeff Balogh', author_email='me@jeffbalogh.org', url='http://github.com/jbalogh/django-nose', license='BSD', packages=find_packages(exclude=['testapp','testapp/*']), include_package_data=True, zip_safe=False, install_requires=['nose'], tests_require=['Django', 'south'], # This blows up tox runs that install django-nose into a virtualenv, # because it causes Nose to import django_nose.runner before the Django # settings are initialized, leading to a mess of errors. There's no reason # we need FixtureBundlingPlugin declared as an entrypoint anyway, since you # need to be using django-nose to find the it useful, and django-nose knows # about it intrinsically. #entry_points=""" # [nose.plugins.0.10] # fixture_bundler = django_nose.fixture_bundling:FixtureBundlingPlugin # """, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
Comment out entrypoint because it blows up django-nose in connection with tox. Ouch. import os from setuptools import setup, find_packages ROOT = os.path.abspath(os.path.dirname(__file__)) setup( name='django-nose', version='0.2', description='Django test runner that uses nose.', long_description=open(os.path.join(ROOT, 'README.rst')).read(), author='Jeff Balogh', author_email='me@jeffbalogh.org', url='http://github.com/jbalogh/django-nose', license='BSD', packages=find_packages(exclude=['testapp','testapp/*']), include_package_data=True, zip_safe=False, install_requires=['nose'], tests_require=['Django', 'south'], entry_points=""" [nose.plugins.0.10] fixture_bundler = django_nose.fixture_bundling:FixtureBundlingPlugin """, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
677d2d4f422f9b05746fa80d63492de4ae9aced4
tests/test_examples.py
tests/test_examples.py
import pytest import examples.basic_usage import examples.basic_usage_manual import examples.dataset import examples.variant_ts_difficulties import examples.variants def test_dataset(unihan_options): examples.dataset.run() def test_variants(unihan_options): examples.variants.run(unihan_options=unihan_options) def test_ts_difficulties(unihan_options): examples.variant_ts_difficulties.run(unihan_options=unihan_options) def test_basic_usage(unihan_options, capsys: pytest.CaptureFixture[str]): examples.basic_usage.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out def test_basic_usage_manual(unihan_options, capsys: pytest.CaptureFixture[str]): examples.basic_usage_manual.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out
import importlib import importlib.util import sys import types import pytest def load_script(example: str) -> types.ModuleType: file_path = f"examples/{example}.py" module_name = "run" spec = importlib.util.spec_from_file_location(module_name, file_path) assert spec is not None module = importlib.util.module_from_spec(spec) sys.modules[module_name] = module assert spec.loader is not None spec.loader.exec_module(module) return module def test_dataset(unihan_options): example = load_script("dataset") example.run() def test_variants(unihan_options): example = load_script("variants") example.run() def test_ts_difficulties(unihan_options): example = load_script("variant_ts_difficulties") example.run(unihan_options=unihan_options) def test_basic_usage(unihan_options, capsys: pytest.CaptureFixture[str]): example = load_script("basic_usage") example.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out def test_basic_usage_manual(unihan_options, capsys: pytest.CaptureFixture[str]): example = load_script("basic_usage_manual") example.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out
Rework for handling of examples/
refactor(tests): Rework for handling of examples/
Python
mit
cihai/cihai,cihai/cihai
import importlib import importlib.util import sys import types import pytest def load_script(example: str) -> types.ModuleType: file_path = f"examples/{example}.py" module_name = "run" spec = importlib.util.spec_from_file_location(module_name, file_path) assert spec is not None module = importlib.util.module_from_spec(spec) sys.modules[module_name] = module assert spec.loader is not None spec.loader.exec_module(module) return module def test_dataset(unihan_options): example = load_script("dataset") example.run() def test_variants(unihan_options): example = load_script("variants") example.run() def test_ts_difficulties(unihan_options): example = load_script("variant_ts_difficulties") example.run(unihan_options=unihan_options) def test_basic_usage(unihan_options, capsys: pytest.CaptureFixture[str]): example = load_script("basic_usage") example.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out def test_basic_usage_manual(unihan_options, capsys: pytest.CaptureFixture[str]): example = load_script("basic_usage_manual") example.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out
refactor(tests): Rework for handling of examples/ import pytest import examples.basic_usage import examples.basic_usage_manual import examples.dataset import examples.variant_ts_difficulties import examples.variants def test_dataset(unihan_options): examples.dataset.run() def test_variants(unihan_options): examples.variants.run(unihan_options=unihan_options) def test_ts_difficulties(unihan_options): examples.variant_ts_difficulties.run(unihan_options=unihan_options) def test_basic_usage(unihan_options, capsys: pytest.CaptureFixture[str]): examples.basic_usage.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out def test_basic_usage_manual(unihan_options, capsys: pytest.CaptureFixture[str]): examples.basic_usage_manual.run(unihan_options=unihan_options) captured = capsys.readouterr() assert "lookup for 好: good" in captured.out assert 'matches for "good": 好' in captured.out
893e4292f6b1799bf5f1888fcbad41ec8b5a5951
examples/tic_ql_tabular_selfplay_all.py
examples/tic_ql_tabular_selfplay_all.py
''' In this example we use Q-learning via self-play to learn the value function of all Tic-Tac-Toe positions. ''' from capstone.environment import Environment from capstone.game import TicTacToe from capstone.mdp import GameMDP from capstone.rl import QLearningSelfPlay from capstone.rl.tabularf import TabularF from capstone.util import tic2pdf game = TicTacToe() env = Environment(GameMDP(game)) qlearning = QLearningSelfPlay(env, n_episodes=1000) qlearning.learn() for move in game.legal_moves(): print('-' * 80) value = qlearning.qf[(game, move)] new_game = game.copy().make_move(move) print(value) print(new_game)
Use Q-learning to learn all state-action values via self-play
Use Q-learning to learn all state-action values via self-play
Python
mit
davidrobles/mlnd-capstone-code
''' In this example we use Q-learning via self-play to learn the value function of all Tic-Tac-Toe positions. ''' from capstone.environment import Environment from capstone.game import TicTacToe from capstone.mdp import GameMDP from capstone.rl import QLearningSelfPlay from capstone.rl.tabularf import TabularF from capstone.util import tic2pdf game = TicTacToe() env = Environment(GameMDP(game)) qlearning = QLearningSelfPlay(env, n_episodes=1000) qlearning.learn() for move in game.legal_moves(): print('-' * 80) value = qlearning.qf[(game, move)] new_game = game.copy().make_move(move) print(value) print(new_game)
Use Q-learning to learn all state-action values via self-play
514614c68ced19e364e484e4dbec044e3fb03e24
setup.py
setup.py
from setuptools import setup, find_packages from taggit import VERSION f = open('README.txt') readme = f.read() f.close() setup( name='django-taggit', version=".".join(VERSION), description='django-taggit is a reusable Django application for simple tagging.', long_description=readme, author='Alex Gaynor', author_email='alex.gaynor@gmail.com', url='http://github.com/alex/django-taggit/tree/master', packages=find_packages(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], )
import os from setuptools import setup, find_packages from taggit import VERSION f = open(os.path.join(os.path.dirname(__file__), 'README.txt')) readme = f.read() f.close() setup( name='django-taggit', version=".".join(VERSION), description='django-taggit is a reusable Django application for simple tagging.', long_description=readme, author='Alex Gaynor', author_email='alex.gaynor@gmail.com', url='http://github.com/alex/django-taggit/tree/master', packages=find_packages(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], )
Update on suggestion of jezdez.
Update on suggestion of jezdez.
Python
bsd-3-clause
twig/django-taggit,kminkov/django-taggit,orbitvu/django-taggit,cimani/django-taggit,tamarmot/django-taggit,laanlabs/django-taggit,kaedroho/django-taggit,theatlantic/django-taggit,vhf/django-taggit,izquierdo/django-taggit,theatlantic/django-taggit2,doselect/django-taggit,adrian-sgn/django-taggit,nealtodd/django-taggit,decibyte/django-taggit,decibyte/django-taggit,7kfpun/django-taggit,eugena/django-taggit,guoqiao/django-taggit,IRI-Research/django-taggit,theatlantic/django-taggit2,Maplecroft/django-taggit,Eksmo/django-taggit,gem/django-taggit,benjaminrigaud/django-taggit,theatlantic/django-taggit
import os from setuptools import setup, find_packages from taggit import VERSION f = open(os.path.join(os.path.dirname(__file__), 'README.txt')) readme = f.read() f.close() setup( name='django-taggit', version=".".join(VERSION), description='django-taggit is a reusable Django application for simple tagging.', long_description=readme, author='Alex Gaynor', author_email='alex.gaynor@gmail.com', url='http://github.com/alex/django-taggit/tree/master', packages=find_packages(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], )
Update on suggestion of jezdez. from setuptools import setup, find_packages from taggit import VERSION f = open('README.txt') readme = f.read() f.close() setup( name='django-taggit', version=".".join(VERSION), description='django-taggit is a reusable Django application for simple tagging.', long_description=readme, author='Alex Gaynor', author_email='alex.gaynor@gmail.com', url='http://github.com/alex/django-taggit/tree/master', packages=find_packages(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], )
d436bcc20be8eb81960a53d442f699e42e2f9ea7
src/tkjoincsv.py
src/tkjoincsv.py
import tkFileDialog import joincsv import os.path import sys if __name__ == '__main__': filetypes=[("Spreadsheets", "*.csv"), ("Spreadsheets", "*.xls"), ("Spreadsheets", "*.xlsx")] if len(sys.argv) == 2: input_filename = sys.argv[1] else: input_filename = tkFileDialog.askopenfilename(filetypes=filetypes) if not os.path.isfile(input_filename): exit(0) output_filename = tkFileDialog.asksaveasfilename(filetypes=filetypes, defaultextension=".csv") if not os.path.isfile(output_filename): exit(0) joiner = joincsv.RecordJoiner(input_filename) joiner.save(output_filename)
import tkFileDialog import joincsv import os.path import sys if __name__ == '__main__': filetypes=[("Spreadsheets", "*.csv"), ("Spreadsheets", "*.xls"), ("Spreadsheets", "*.xlsx")] if len(sys.argv) == 2: input_filename = sys.argv[1] else: input_filename = tkFileDialog.askopenfilename(filetypes=filetypes) if not os.path.isfile(input_filename): exit(0) output_filename = tkFileDialog.asksaveasfilename(filetypes=filetypes, defaultextension=".csv") if output_filename: joiner = joincsv.RecordJoiner(input_filename) joiner.save(output_filename)
Allow saving to a file that does not already exist again.
Allow saving to a file that does not already exist again.
Python
apache-2.0
peterSW/corow
import tkFileDialog import joincsv import os.path import sys if __name__ == '__main__': filetypes=[("Spreadsheets", "*.csv"), ("Spreadsheets", "*.xls"), ("Spreadsheets", "*.xlsx")] if len(sys.argv) == 2: input_filename = sys.argv[1] else: input_filename = tkFileDialog.askopenfilename(filetypes=filetypes) if not os.path.isfile(input_filename): exit(0) output_filename = tkFileDialog.asksaveasfilename(filetypes=filetypes, defaultextension=".csv") if output_filename: joiner = joincsv.RecordJoiner(input_filename) joiner.save(output_filename)
Allow saving to a file that does not already exist again. import tkFileDialog import joincsv import os.path import sys if __name__ == '__main__': filetypes=[("Spreadsheets", "*.csv"), ("Spreadsheets", "*.xls"), ("Spreadsheets", "*.xlsx")] if len(sys.argv) == 2: input_filename = sys.argv[1] else: input_filename = tkFileDialog.askopenfilename(filetypes=filetypes) if not os.path.isfile(input_filename): exit(0) output_filename = tkFileDialog.asksaveasfilename(filetypes=filetypes, defaultextension=".csv") if not os.path.isfile(output_filename): exit(0) joiner = joincsv.RecordJoiner(input_filename) joiner.save(output_filename)
42bfa6b69697c0c093a961df5708f477288a6efa
icekit/plugins/twitter_embed/forms.py
icekit/plugins/twitter_embed/forms.py
import re from django import forms from fluent_contents.forms import ContentItemForm class TwitterEmbedAdminForm(ContentItemForm): def clean_twitter_url(self): """ Make sure the URL provided matches the twitter URL format. """ url = self.cleaned_data['twitter_url'] if url: pattern = re.compile(r'https?://(www\.)?twitter.com/\S+/status(es)?/\S+') if not pattern.match(url): raise forms.ValidationError('Please provide a valid twitter link.') return url
import re from django import forms from fluent_contents.forms import ContentItemForm from icekit.plugins.twitter_embed.models import TwitterEmbedItem class TwitterEmbedAdminForm(ContentItemForm): class Meta: model = TwitterEmbedItem fields = '__all__' def clean_twitter_url(self): """ Make sure the URL provided matches the twitter URL format. """ url = self.cleaned_data['twitter_url'] if url: pattern = re.compile(r'https?://(www\.)?twitter.com/\S+/status(es)?/\S+') if not pattern.match(url): raise forms.ValidationError('Please provide a valid twitter link.') return url
Add model and firld information to form.
Add model and firld information to form.
Python
mit
ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit
import re from django import forms from fluent_contents.forms import ContentItemForm from icekit.plugins.twitter_embed.models import TwitterEmbedItem class TwitterEmbedAdminForm(ContentItemForm): class Meta: model = TwitterEmbedItem fields = '__all__' def clean_twitter_url(self): """ Make sure the URL provided matches the twitter URL format. """ url = self.cleaned_data['twitter_url'] if url: pattern = re.compile(r'https?://(www\.)?twitter.com/\S+/status(es)?/\S+') if not pattern.match(url): raise forms.ValidationError('Please provide a valid twitter link.') return url
Add model and firld information to form. import re from django import forms from fluent_contents.forms import ContentItemForm class TwitterEmbedAdminForm(ContentItemForm): def clean_twitter_url(self): """ Make sure the URL provided matches the twitter URL format. """ url = self.cleaned_data['twitter_url'] if url: pattern = re.compile(r'https?://(www\.)?twitter.com/\S+/status(es)?/\S+') if not pattern.match(url): raise forms.ValidationError('Please provide a valid twitter link.') return url
591a40b6e1f4ac8b1d21050ccfa10779dc9dbf7c
analytic_code.py
analytic_code.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2013 XCG Consulting (www.xcg-consulting.fr) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv class analytic_code(osv.Model): _name = "analytic.code" _columns = dict( name=fields.char("Name", size=128, translate=True, required=True), nd_id=fields.many2one( "analytic.dimension", ondelete="restrict"), active=fields.boolean('Active'), nd_name=fields.related('nd_id', 'name', type="char", string="Dimension Name", store=False), description=fields.char('Description', size=512), ) _defaults = { 'active': 1, }
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2013 XCG Consulting (www.xcg-consulting.fr) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv class analytic_code(osv.Model): _name = "analytic.code" _columns = dict( name=fields.char("Name", size=128, translate=True, required=True), nd_id=fields.many2one( "analytic.dimension", "Dimensions", ondelete="restrict"), active=fields.boolean('Active'), nd_name=fields.related('nd_id', 'name', type="char", string="Dimension Name", store=False), description=fields.char('Description', size=512), ) _defaults = { 'active': 1, }
Add string to display the name of the field Dimension during the import
Add string to display the name of the field Dimension during the import
Python
agpl-3.0
xcgd/analytic_structure
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2013 XCG Consulting (www.xcg-consulting.fr) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv class analytic_code(osv.Model): _name = "analytic.code" _columns = dict( name=fields.char("Name", size=128, translate=True, required=True), nd_id=fields.many2one( "analytic.dimension", "Dimensions", ondelete="restrict"), active=fields.boolean('Active'), nd_name=fields.related('nd_id', 'name', type="char", string="Dimension Name", store=False), description=fields.char('Description', size=512), ) _defaults = { 'active': 1, }
Add string to display the name of the field Dimension during the import # -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2013 XCG Consulting (www.xcg-consulting.fr) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv class analytic_code(osv.Model): _name = "analytic.code" _columns = dict( name=fields.char("Name", size=128, translate=True, required=True), nd_id=fields.many2one( "analytic.dimension", ondelete="restrict"), active=fields.boolean('Active'), nd_name=fields.related('nd_id', 'name', type="char", string="Dimension Name", store=False), description=fields.char('Description', size=512), ) _defaults = { 'active': 1, }
031bce223eac9eda1f856a204a07149c8e9549fd
hoomd/update/__init__.py
hoomd/update/__init__.py
from hoomd.update.box_resize import BoxResize # TODO remove when no longer necessary class _updater: pass __all__ = [BoxResize]
from hoomd.update.box_resize import BoxResize # TODO remove when no longer necessary class _updater: pass __all__ = ['BoxResize']
Fix typo in hoomd.update.__all__ quote class name
Fix typo in hoomd.update.__all__ quote class name
Python
bsd-3-clause
joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue
from hoomd.update.box_resize import BoxResize # TODO remove when no longer necessary class _updater: pass __all__ = ['BoxResize']
Fix typo in hoomd.update.__all__ quote class name from hoomd.update.box_resize import BoxResize # TODO remove when no longer necessary class _updater: pass __all__ = [BoxResize]
3fe4cb6fbafe69b9e7520466b7e7e2d405cf0ed0
bookmarks/forms.py
bookmarks/forms.py
from django import forms from django.utils.translation import ugettext_lazy as _ from tagging.forms import TagField from bookmarks.models import Bookmark, BookmarkInstance class BookmarkInstanceForm(forms.ModelForm): url = forms.URLField(label = "URL", verify_exists=True, widget=forms.TextInput(attrs={"size": 40})) description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40})) redirect = forms.BooleanField(label="Redirect", required=False) tags = TagField(label="Tags", required=False) def __init__(self, user=None, *args, **kwargs): self.user = user super(BookmarkInstanceForm, self).__init__(*args, **kwargs) # hack to order fields self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect'] def clean(self): if 'url' not in self.cleaned_data: return if BookmarkInstance.on_site.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0: raise forms.ValidationError(_("You have already bookmarked this link.")) return self.cleaned_data def should_redirect(self): if self.cleaned_data["redirect"]: return True else: return False def save(self, commit=True): self.instance.url = self.cleaned_data['url'] return super(BookmarkInstanceForm, self).save(commit) class Meta: model = BookmarkInstance #fields = ('url', 'description', 'note', 'redirect')
from django import forms from django.utils.translation import ugettext_lazy as _ from tagging.forms import TagField from bookmarks.models import Bookmark, BookmarkInstance class BookmarkInstanceForm(forms.ModelForm): url = forms.URLField(label = "URL", widget=forms.TextInput(attrs={"size": 40})) description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40})) redirect = forms.BooleanField(label="Redirect", required=False) tags = TagField(label="Tags", required=False) def __init__(self, user=None, *args, **kwargs): self.user = user super(BookmarkInstanceForm, self).__init__(*args, **kwargs) # hack to order fields self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect'] def clean(self): if 'url' not in self.cleaned_data: return if BookmarkInstance.on_site.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0: raise forms.ValidationError(_("You have already bookmarked this link.")) return self.cleaned_data def should_redirect(self): if self.cleaned_data["redirect"]: return True else: return False def save(self, commit=True): self.instance.url = self.cleaned_data['url'] return super(BookmarkInstanceForm, self).save(commit) class Meta: model = BookmarkInstance #fields = ('url', 'description', 'note', 'redirect')
Make URLField compatible with Django 1.4 and remove verify_exists attribute
Make URLField compatible with Django 1.4 and remove verify_exists attribute
Python
mit
incuna/incuna-bookmarks,incuna/incuna-bookmarks
from django import forms from django.utils.translation import ugettext_lazy as _ from tagging.forms import TagField from bookmarks.models import Bookmark, BookmarkInstance class BookmarkInstanceForm(forms.ModelForm): url = forms.URLField(label = "URL", widget=forms.TextInput(attrs={"size": 40})) description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40})) redirect = forms.BooleanField(label="Redirect", required=False) tags = TagField(label="Tags", required=False) def __init__(self, user=None, *args, **kwargs): self.user = user super(BookmarkInstanceForm, self).__init__(*args, **kwargs) # hack to order fields self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect'] def clean(self): if 'url' not in self.cleaned_data: return if BookmarkInstance.on_site.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0: raise forms.ValidationError(_("You have already bookmarked this link.")) return self.cleaned_data def should_redirect(self): if self.cleaned_data["redirect"]: return True else: return False def save(self, commit=True): self.instance.url = self.cleaned_data['url'] return super(BookmarkInstanceForm, self).save(commit) class Meta: model = BookmarkInstance #fields = ('url', 'description', 'note', 'redirect')
Make URLField compatible with Django 1.4 and remove verify_exists attribute from django import forms from django.utils.translation import ugettext_lazy as _ from tagging.forms import TagField from bookmarks.models import Bookmark, BookmarkInstance class BookmarkInstanceForm(forms.ModelForm): url = forms.URLField(label = "URL", verify_exists=True, widget=forms.TextInput(attrs={"size": 40})) description = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"size": 40})) redirect = forms.BooleanField(label="Redirect", required=False) tags = TagField(label="Tags", required=False) def __init__(self, user=None, *args, **kwargs): self.user = user super(BookmarkInstanceForm, self).__init__(*args, **kwargs) # hack to order fields self.fields.keyOrder = ['url', 'description', 'note', 'tags', 'redirect'] def clean(self): if 'url' not in self.cleaned_data: return if BookmarkInstance.on_site.filter(bookmark__url=self.cleaned_data['url'], user=self.user).count() > 0: raise forms.ValidationError(_("You have already bookmarked this link.")) return self.cleaned_data def should_redirect(self): if self.cleaned_data["redirect"]: return True else: return False def save(self, commit=True): self.instance.url = self.cleaned_data['url'] return super(BookmarkInstanceForm, self).save(commit) class Meta: model = BookmarkInstance #fields = ('url', 'description', 'note', 'redirect')
0f047cded957bc67441a9acd65b46fab4bac6302
SUASImageParser/ADLC/characteristic_identifier.py
SUASImageParser/ADLC/characteristic_identifier.py
from SUASImageParser.utils.image import Image from SUASImageParser.utils.color import bcolors import cv2 import numpy as np class CharacteristicIdentifier: """ Identify target characteristics """ def __init__(self, **kwargs): pass def identify_characteristics(self, target): """ Identifies the characteristics of the target "target" and returns them as a dictionary object """ # My thoughts so far to accomplish this is to break the problem down # into the following tasks: # 1) Segmentation # 2) OCR # 3) Pixhawk log parse to gather data about # 3a) GPS # 3b) Heading # I'm not really sure how to implement this process, which is why I am # leaving it in this comment as a "stub" which needs to be resolved. # Returning the characteristics for each target return {} def segment(self, target): """ Separate different important aspects of the image out. This is to extract the letter within the image """ # @TODO: Implement segmentation here return target def OCR(self, target): """ Use OCR to identify the character within the image "target" """ # @TODO: Implement OCR here return ""
from SUASImageParser.utils.image import Image from SUASImageParser.utils.color import bcolors import cv2 import numpy as np class CharacteristicIdentifier: """ Identify target characteristics """ def __init__(self, **kwargs): pass def identify_characteristics(self, target): """ Identifies the characteristics of the target "target" and returns them as a dictionary object """ # My thoughts so far to accomplish this is to break the problem down # into the following tasks: # 1) Segmentation # 2) OCR # I'm not really sure how to implement this process, which is why I am # leaving it in this comment as a "stub" which needs to be resolved. # Returning the characteristics for each target return {} def segment(self, target): """ Separate different important aspects of the image out. This is to extract the letter within the image """ # @TODO: Implement segmentation here return target def OCR(self, target): """ Use OCR to identify the character within the image "target" """ # @TODO: Implement OCR here return ""
Remove mention of Log parser
Remove mention of Log parser
Python
mit
FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition
from SUASImageParser.utils.image import Image from SUASImageParser.utils.color import bcolors import cv2 import numpy as np class CharacteristicIdentifier: """ Identify target characteristics """ def __init__(self, **kwargs): pass def identify_characteristics(self, target): """ Identifies the characteristics of the target "target" and returns them as a dictionary object """ # My thoughts so far to accomplish this is to break the problem down # into the following tasks: # 1) Segmentation # 2) OCR # I'm not really sure how to implement this process, which is why I am # leaving it in this comment as a "stub" which needs to be resolved. # Returning the characteristics for each target return {} def segment(self, target): """ Separate different important aspects of the image out. This is to extract the letter within the image """ # @TODO: Implement segmentation here return target def OCR(self, target): """ Use OCR to identify the character within the image "target" """ # @TODO: Implement OCR here return ""
Remove mention of Log parser from SUASImageParser.utils.image import Image from SUASImageParser.utils.color import bcolors import cv2 import numpy as np class CharacteristicIdentifier: """ Identify target characteristics """ def __init__(self, **kwargs): pass def identify_characteristics(self, target): """ Identifies the characteristics of the target "target" and returns them as a dictionary object """ # My thoughts so far to accomplish this is to break the problem down # into the following tasks: # 1) Segmentation # 2) OCR # 3) Pixhawk log parse to gather data about # 3a) GPS # 3b) Heading # I'm not really sure how to implement this process, which is why I am # leaving it in this comment as a "stub" which needs to be resolved. # Returning the characteristics for each target return {} def segment(self, target): """ Separate different important aspects of the image out. This is to extract the letter within the image """ # @TODO: Implement segmentation here return target def OCR(self, target): """ Use OCR to identify the character within the image "target" """ # @TODO: Implement OCR here return ""
f8a6b4d8053a60cfec372d8b91bf294d606055ec
app/admin/routes.py
app/admin/routes.py
from flask import render_template, redirect, url_for, flash, request from flask.ext.login import login_required, current_user from . import admin from .forms import ProfileForm from .. import db from ..models import User @admin.route('/') @login_required def index(): return render_template('admin/user.html', user=current_user) @admin.route('/edit_user', methods=['GET', 'POST']) @login_required def edit_user(): form = ProfileForm() if form.validate_on_submit(): current_user.name = form.name.data current_user.location = form.location.data current_user.bio = form.bio.data db.session.add(current_user._get_current_object()) db.session.commit() flash("Síðan hefur verið uppfærð") return redirect(url_for('admin.index')) form.name.data = current_user.name form.location.data = current_user.location form.bio.data = current_user.bio return render_template('admin/edit_user.html', form=form) @admin.route('/news') @login_required def news(): return render_template('admin/news.html')
from datetime import datetime from flask import render_template, redirect, url_for, flash, request from flask.ext.login import login_required, current_user from . import admin from .forms import ProfileForm, PostForm from .. import db from ..models import User @admin.route('/') @login_required def index(): return render_template('admin/user.html', user=current_user) @admin.route('/edit_user', methods=['GET', 'POST']) @login_required def edit_user(): form = ProfileForm() if form.validate_on_submit(): current_user.name = form.name.data current_user.location = form.location.data current_user.bio = form.bio.data db.session.add(current_user._get_current_object()) db.session.commit() flash("Síðan hefur verið uppfærð") return redirect(url_for('admin.index')) form.name.data = current_user.name form.location.data = current_user.location form.bio.data = current_user.bio return render_template('admin/edit_user.html', form=form) @admin.route('/news') @login_required def news(): return render_template('admin/news.html') @admin.route('/news/post', methods=['GET', 'POST']) @login_required def post(): form = PostForm() form.category.choices = [(0, 'Almenn frétt')] if form.validate_on_submit(): flash("Fréttin hefur verið vistuð!") return redirect(url_for('admin.news')) return render_template('admin/post.html', form=form)
Add a route to admin/news/post to post a news story. Uses the PostForm for forms
Add a route to admin/news/post to post a news story. Uses the PostForm for forms
Python
mit
finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is
from datetime import datetime from flask import render_template, redirect, url_for, flash, request from flask.ext.login import login_required, current_user from . import admin from .forms import ProfileForm, PostForm from .. import db from ..models import User @admin.route('/') @login_required def index(): return render_template('admin/user.html', user=current_user) @admin.route('/edit_user', methods=['GET', 'POST']) @login_required def edit_user(): form = ProfileForm() if form.validate_on_submit(): current_user.name = form.name.data current_user.location = form.location.data current_user.bio = form.bio.data db.session.add(current_user._get_current_object()) db.session.commit() flash("Síðan hefur verið uppfærð") return redirect(url_for('admin.index')) form.name.data = current_user.name form.location.data = current_user.location form.bio.data = current_user.bio return render_template('admin/edit_user.html', form=form) @admin.route('/news') @login_required def news(): return render_template('admin/news.html') @admin.route('/news/post', methods=['GET', 'POST']) @login_required def post(): form = PostForm() form.category.choices = [(0, 'Almenn frétt')] if form.validate_on_submit(): flash("Fréttin hefur verið vistuð!") return redirect(url_for('admin.news')) return render_template('admin/post.html', form=form)
Add a route to admin/news/post to post a news story. Uses the PostForm for forms from flask import render_template, redirect, url_for, flash, request from flask.ext.login import login_required, current_user from . import admin from .forms import ProfileForm from .. import db from ..models import User @admin.route('/') @login_required def index(): return render_template('admin/user.html', user=current_user) @admin.route('/edit_user', methods=['GET', 'POST']) @login_required def edit_user(): form = ProfileForm() if form.validate_on_submit(): current_user.name = form.name.data current_user.location = form.location.data current_user.bio = form.bio.data db.session.add(current_user._get_current_object()) db.session.commit() flash("Síðan hefur verið uppfærð") return redirect(url_for('admin.index')) form.name.data = current_user.name form.location.data = current_user.location form.bio.data = current_user.bio return render_template('admin/edit_user.html', form=form) @admin.route('/news') @login_required def news(): return render_template('admin/news.html')
479275674916e45c0a2b70a372962f3d0c271e4f
SatNOGS/base/management/commands/update_all_tle.py
SatNOGS/base/management/commands/update_all_tle.py
from orbit import satellite from django.core.management.base import BaseCommand from base.utils import update_all_satellites from base.models import Satellite class Command(BaseCommand): help = 'Create initial fixtures' def handle(self, *args, **options): satellites = Satellite.objets.all() for obj in satellites: try: sat = satellite(obj.norad_cat_id) except: self.stdout.write(('Satellite {} with Identifier {} does ' 'not exist').format(obj.name, obj.norad_cat_id)) continue obj.name = sat.name() tle = sat.tle() obj.tle0 = tle[0] obj.tle1 = tle[1] obj.tle2 = tle[2] obj.save() self.stdout.write(('Satellite {} with Identifier {} ' 'found [updated]').format(obj.norad_cat_id, obj.name))
Add management command to update all existing satellite tle data
Add management command to update all existing satellite tle data
Python
agpl-3.0
cshields/satnogs-network,cshields/satnogs-network,cshields/satnogs-network,cshields/satnogs-network
from orbit import satellite from django.core.management.base import BaseCommand from base.utils import update_all_satellites from base.models import Satellite class Command(BaseCommand): help = 'Create initial fixtures' def handle(self, *args, **options): satellites = Satellite.objets.all() for obj in satellites: try: sat = satellite(obj.norad_cat_id) except: self.stdout.write(('Satellite {} with Identifier {} does ' 'not exist').format(obj.name, obj.norad_cat_id)) continue obj.name = sat.name() tle = sat.tle() obj.tle0 = tle[0] obj.tle1 = tle[1] obj.tle2 = tle[2] obj.save() self.stdout.write(('Satellite {} with Identifier {} ' 'found [updated]').format(obj.norad_cat_id, obj.name))
Add management command to update all existing satellite tle data
959e30bed3dcaee03df929f8ec2848d07c745dc9
tests/webcam_read_qr.py
tests/webcam_read_qr.py
#!/usr/bin/env python """ This module sets up a video stream from internal or connected webcam using Gstreamer. You can then take snapshots. import qrtools qr = qrtools.QR() qr.decode("cam.jpg") print qr.data """ import gi gi.require_version('Gtk', '3.0') gi.require_version('Gst', '1.0') from gi.repository import Gtk as gtk from gi.repository import Gdk from gi.repository import Gst as gst from gi.repository import GdkPixbuf from avocado import Test from os.path import exists, relpath import qrtools import time #import pyqrcode class WebcamReadQR(Test): def setUp(self): # if not exists('/dev/video0'): # self.skip("No webcam detected: /dev/video0 cannot be found"); self.device = '/dev/video0' Gdk.threads_init() gtk.main() self.take_snapshot() def test(self): self.create_video_pipeline() def create_video_pipeline(self): gst.init([]) #v4l2src self.video_player = gst.parse_launch("videotestsrc ! jpegenc ! filesink location=cam.jpg") self.video_player.set_state(gst.State.PLAYING) bus = self.video_player.get_bus() bus.add_signal_watch() bus.connect("message", self.on_message) bus.enable_sync_message_emission() bus.connect("sync-message::element", self.on_sync_message) def on_message(self, bus, message): t = message.type if t == gst.MessageType.EOS: self.exit() elif t == gst.MessageType.ERROR: self.exit() self.fail("Error {0}".format(message.parse_error())) def on_sync_message(self, bus, message): if message.structure is None: return message_name = message.structure.get_name() def exit(self): self.video_player.set_state(gst.State.NULL) gtk.main_quit() def take_snapshot(self): #TODO:fill this in
Put gst code into Avocado test format. Needs to be edited to take a snapshot and read the qr code.
Put gst code into Avocado test format. Needs to be edited to take a snapshot and read the qr code.
Python
mit
daveol/Fedora-Test-Laptop,daveol/Fedora-Test-Laptop
#!/usr/bin/env python """ This module sets up a video stream from internal or connected webcam using Gstreamer. You can then take snapshots. import qrtools qr = qrtools.QR() qr.decode("cam.jpg") print qr.data """ import gi gi.require_version('Gtk', '3.0') gi.require_version('Gst', '1.0') from gi.repository import Gtk as gtk from gi.repository import Gdk from gi.repository import Gst as gst from gi.repository import GdkPixbuf from avocado import Test from os.path import exists, relpath import qrtools import time #import pyqrcode class WebcamReadQR(Test): def setUp(self): # if not exists('/dev/video0'): # self.skip("No webcam detected: /dev/video0 cannot be found"); self.device = '/dev/video0' Gdk.threads_init() gtk.main() self.take_snapshot() def test(self): self.create_video_pipeline() def create_video_pipeline(self): gst.init([]) #v4l2src self.video_player = gst.parse_launch("videotestsrc ! jpegenc ! filesink location=cam.jpg") self.video_player.set_state(gst.State.PLAYING) bus = self.video_player.get_bus() bus.add_signal_watch() bus.connect("message", self.on_message) bus.enable_sync_message_emission() bus.connect("sync-message::element", self.on_sync_message) def on_message(self, bus, message): t = message.type if t == gst.MessageType.EOS: self.exit() elif t == gst.MessageType.ERROR: self.exit() self.fail("Error {0}".format(message.parse_error())) def on_sync_message(self, bus, message): if message.structure is None: return message_name = message.structure.get_name() def exit(self): self.video_player.set_state(gst.State.NULL) gtk.main_quit() def take_snapshot(self): #TODO:fill this in
Put gst code into Avocado test format. Needs to be edited to take a snapshot and read the qr code.
290ead5bbc57e526f0fe12d161fa5fb684ab4edf
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import materializecssform setup( name='django-materializecss-form', version=materializecssform.__version__, packages=find_packages(), author="Kal Walkden", author_email="kal@walkden.us", description="A simple Django form template tag to work with Materializecss", long_description=open('README.md').read(), long_description_content_type="text/markdown", include_package_data=True, url='https://github.com/kalwalkden/django-materializecss-form', classifiers=[ "Programming Language :: Python", "Development Status :: 4 - Beta", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 3.6", "Topic :: Documentation :: Sphinx", ], license="MIT", zip_safe=False )
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import materializecssform with open("README.md", "r") as fh: long_description = fh.read() setup( name='django-materializecss-form', version=materializecssform.__version__, packages=find_packages(), author="Kal Walkden", author_email="kal@walkden.us", description="A simple Django form template tag to work with Materializecss", long_description=long_description, long_description_content_type="text/markdown", include_package_data=True, url='https://github.com/kalwalkden/django-materializecss-form', classifiers=[ "Programming Language :: Python", "Development Status :: 4 - Beta", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 3.6", ], license="MIT", zip_safe=False )
Update meta version so that documentation looks good in pypi
Update meta version so that documentation looks good in pypi
Python
mit
florent1933/django-materializecss-form,florent1933/django-materializecss-form
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import materializecssform with open("README.md", "r") as fh: long_description = fh.read() setup( name='django-materializecss-form', version=materializecssform.__version__, packages=find_packages(), author="Kal Walkden", author_email="kal@walkden.us", description="A simple Django form template tag to work with Materializecss", long_description=long_description, long_description_content_type="text/markdown", include_package_data=True, url='https://github.com/kalwalkden/django-materializecss-form', classifiers=[ "Programming Language :: Python", "Development Status :: 4 - Beta", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 3.6", ], license="MIT", zip_safe=False )
Update meta version so that documentation looks good in pypi #!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import materializecssform setup( name='django-materializecss-form', version=materializecssform.__version__, packages=find_packages(), author="Kal Walkden", author_email="kal@walkden.us", description="A simple Django form template tag to work with Materializecss", long_description=open('README.md').read(), long_description_content_type="text/markdown", include_package_data=True, url='https://github.com/kalwalkden/django-materializecss-form', classifiers=[ "Programming Language :: Python", "Development Status :: 4 - Beta", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 3.6", "Topic :: Documentation :: Sphinx", ], license="MIT", zip_safe=False )
cb45cea953880bf87a774bec4120bb0e7331d480
tcconfig/parser/_model.py
tcconfig/parser/_model.py
from simplesqlite.model import Integer, Model, Text from .._const import Tc class Filter(Model): device = Text(attr_name=Tc.Param.DEVICE, not_null=True) filter_id = Text(attr_name=Tc.Param.FILTER_ID) flowid = Text(attr_name=Tc.Param.FLOW_ID) protocol = Text(attr_name=Tc.Param.PROTOCOL) priority = Integer(attr_name=Tc.Param.PRIORITY) src_network = Text(attr_name=Tc.Param.SRC_NETWORK) dst_network = Text(attr_name=Tc.Param.DST_NETWORK) src_port = Integer(attr_name=Tc.Param.SRC_PORT) dst_port = Integer(attr_name=Tc.Param.DST_PORT) classid = Text(attr_name=Tc.Param.CLASS_ID) handle = Integer(attr_name=Tc.Param.HANDLE) class Qdisc(Model): device = Text(attr_name=Tc.Param.DEVICE, not_null=True) direct_qlen = Integer() parent = Text(attr_name=Tc.Param.PARENT, not_null=True) handle = Text(attr_name=Tc.Param.HANDLE, not_null=True) delay = Text() delay_distro = Text(attr_name="delay-distro") loss = Text() duplicate = Text() corrupt = Text() reorder = Text() rate = Text()
Add ORM models for filter/qdisc
Add ORM models for filter/qdisc
Python
mit
thombashi/tcconfig,thombashi/tcconfig
from simplesqlite.model import Integer, Model, Text from .._const import Tc class Filter(Model): device = Text(attr_name=Tc.Param.DEVICE, not_null=True) filter_id = Text(attr_name=Tc.Param.FILTER_ID) flowid = Text(attr_name=Tc.Param.FLOW_ID) protocol = Text(attr_name=Tc.Param.PROTOCOL) priority = Integer(attr_name=Tc.Param.PRIORITY) src_network = Text(attr_name=Tc.Param.SRC_NETWORK) dst_network = Text(attr_name=Tc.Param.DST_NETWORK) src_port = Integer(attr_name=Tc.Param.SRC_PORT) dst_port = Integer(attr_name=Tc.Param.DST_PORT) classid = Text(attr_name=Tc.Param.CLASS_ID) handle = Integer(attr_name=Tc.Param.HANDLE) class Qdisc(Model): device = Text(attr_name=Tc.Param.DEVICE, not_null=True) direct_qlen = Integer() parent = Text(attr_name=Tc.Param.PARENT, not_null=True) handle = Text(attr_name=Tc.Param.HANDLE, not_null=True) delay = Text() delay_distro = Text(attr_name="delay-distro") loss = Text() duplicate = Text() corrupt = Text() reorder = Text() rate = Text()
Add ORM models for filter/qdisc
d757ec338478ac67f984c1b7aa898f1c374b2a09
openprescribing/frontend/tests/commands/test_import_ccg_boundaries.py
openprescribing/frontend/tests/commands/test_import_ccg_boundaries.py
from django.core.management import call_command from django.test import TestCase from frontend.models import PCT def setUpModule(): call_command('loaddata', 'frontend/tests/fixtures/ccgs.json', verbosity=0) def tearDownModule(): call_command('flush', verbosity=0, interactive=False) class CommandsTestCase(TestCase): def test_import_ccg_boundaries(self): args = [] opts = { 'filename': ('frontend/tests/fixtures/commands/' 'CCG_BSC_Apr2015.TAB') } call_command('import_ccg_boundaries', *args, **opts) pct = PCT.objects.get(code='03Q') self.assertEqual(pct.boundary.centroid.x, -1.0307530606980588)
from django.core.management import call_command from django.test import TestCase from frontend.models import PCT def setUpModule(): call_command('loaddata', 'frontend/tests/fixtures/ccgs.json', verbosity=0) def tearDownModule(): call_command('flush', verbosity=0, interactive=False) class CommandsTestCase(TestCase): def test_import_ccg_boundaries(self): args = [] opts = { 'filename': ('frontend/tests/fixtures/commands/' 'CCG_BSC_Apr2015.TAB') } call_command('import_ccg_boundaries', *args, **opts) pct = PCT.objects.get(code='03Q') self.assertAlmostEqual(pct.boundary.centroid.x, -1.0307530606980588)
Use almostEqual for comparing geo coordinates
Use almostEqual for comparing geo coordinates An upgrade in one of the underlying libraries has shifted the numbers very slightly.
Python
mit
annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc
from django.core.management import call_command from django.test import TestCase from frontend.models import PCT def setUpModule(): call_command('loaddata', 'frontend/tests/fixtures/ccgs.json', verbosity=0) def tearDownModule(): call_command('flush', verbosity=0, interactive=False) class CommandsTestCase(TestCase): def test_import_ccg_boundaries(self): args = [] opts = { 'filename': ('frontend/tests/fixtures/commands/' 'CCG_BSC_Apr2015.TAB') } call_command('import_ccg_boundaries', *args, **opts) pct = PCT.objects.get(code='03Q') self.assertAlmostEqual(pct.boundary.centroid.x, -1.0307530606980588)
Use almostEqual for comparing geo coordinates An upgrade in one of the underlying libraries has shifted the numbers very slightly. from django.core.management import call_command from django.test import TestCase from frontend.models import PCT def setUpModule(): call_command('loaddata', 'frontend/tests/fixtures/ccgs.json', verbosity=0) def tearDownModule(): call_command('flush', verbosity=0, interactive=False) class CommandsTestCase(TestCase): def test_import_ccg_boundaries(self): args = [] opts = { 'filename': ('frontend/tests/fixtures/commands/' 'CCG_BSC_Apr2015.TAB') } call_command('import_ccg_boundaries', *args, **opts) pct = PCT.objects.get(code='03Q') self.assertEqual(pct.boundary.centroid.x, -1.0307530606980588)
c02cad5047ff397229e1139109df80208e7dd5b6
fireant/__init__.py
fireant/__init__.py
# coding: utf-8 __version__ = '{major}.{minor}.{patch}'.format(major=0, minor=12, patch=0)
# coding: utf-8 __version__ = '{major}.{minor}.{patch}'.format(major=0, minor=13, patch=0)
Bump fireant version to 0.13.0
Bump fireant version to 0.13.0
Python
apache-2.0
kayak/fireant,mikeengland/fireant
# coding: utf-8 __version__ = '{major}.{minor}.{patch}'.format(major=0, minor=13, patch=0)
Bump fireant version to 0.13.0 # coding: utf-8 __version__ = '{major}.{minor}.{patch}'.format(major=0, minor=12, patch=0)
0ad8d8665f064542346c3788cecaffdcb68f168a
plasmapy/utils/tests/test_exceptions.py
plasmapy/utils/tests/test_exceptions.py
import pytest import warnings from .. import (PlasmaPyError, PhysicsError, RelativityError, AtomicError) from .. import (PlasmaPyWarning, PhysicsWarning, RelativityWarning, AtomicWarning) plasmapy_exceptions = [ PlasmaPyError, PhysicsError, RelativityError, AtomicError, ] plasmapy_warnings = [ PlasmaPyWarning, PhysicsWarning, RelativityWarning, AtomicWarning, ] @pytest.mark.parametrize("exception", plasmapy_exceptions) def test_exceptions(exception): r"""Test that custom PlasmaPy exceptions can be raised with an error message.""" with pytest.raises(exception): raise exception("What an exceptionally exceptional exception!") @pytest.mark.parametrize("warning", plasmapy_warnings) def test_warnings(warning): r"""Test that custom PlasmaPy warnings can be issued with a warning message.""" with pytest.warns(warning): warnings.warn("Coverage decreased (-0.00002%)", warning) @pytest.mark.parametrize("exception", plasmapy_exceptions) def test_PlasmaPyError_subclassing(exception): r"""Test that each custom PlasmaPy exception can be caught as a PlasmaPyError.""" with pytest.raises(PlasmaPyError): raise exception("I'm sorry, Dave. I'm afraid I can't do that.") @pytest.mark.parametrize("warning", plasmapy_warnings) def test_PlasmaPyWarning_subclassing(warning): r"""Test that custom PlasmaPy warnings can all be caught as a PlasmaPyWarning.""" with pytest.warns(PlasmaPyWarning): warnings.warn("Electrons are WEIRD.", warning)
Create tests for custom exceptions and warnings
Create tests for custom exceptions and warnings
Python
bsd-3-clause
StanczakDominik/PlasmaPy
import pytest import warnings from .. import (PlasmaPyError, PhysicsError, RelativityError, AtomicError) from .. import (PlasmaPyWarning, PhysicsWarning, RelativityWarning, AtomicWarning) plasmapy_exceptions = [ PlasmaPyError, PhysicsError, RelativityError, AtomicError, ] plasmapy_warnings = [ PlasmaPyWarning, PhysicsWarning, RelativityWarning, AtomicWarning, ] @pytest.mark.parametrize("exception", plasmapy_exceptions) def test_exceptions(exception): r"""Test that custom PlasmaPy exceptions can be raised with an error message.""" with pytest.raises(exception): raise exception("What an exceptionally exceptional exception!") @pytest.mark.parametrize("warning", plasmapy_warnings) def test_warnings(warning): r"""Test that custom PlasmaPy warnings can be issued with a warning message.""" with pytest.warns(warning): warnings.warn("Coverage decreased (-0.00002%)", warning) @pytest.mark.parametrize("exception", plasmapy_exceptions) def test_PlasmaPyError_subclassing(exception): r"""Test that each custom PlasmaPy exception can be caught as a PlasmaPyError.""" with pytest.raises(PlasmaPyError): raise exception("I'm sorry, Dave. I'm afraid I can't do that.") @pytest.mark.parametrize("warning", plasmapy_warnings) def test_PlasmaPyWarning_subclassing(warning): r"""Test that custom PlasmaPy warnings can all be caught as a PlasmaPyWarning.""" with pytest.warns(PlasmaPyWarning): warnings.warn("Electrons are WEIRD.", warning)
Create tests for custom exceptions and warnings
85d2c012bfaeeb04fa8dd31cd05a04a8dc43c14e
tests/grammar_term-nonterm_test/NonterminalsInvalidTest.py
tests/grammar_term-nonterm_test/NonterminalsInvalidTest.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from unittest import TestCase, main from grammpy.RawGrammar import RawGrammar class NonterminalsInvalidTest(TestCase): pass if __name__ == '__main__': main()
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from unittest import TestCase, main from grammpy.RawGrammar import RawGrammar as Grammar from grammpy import Nonterminal from grammpy.exceptions import NotNonterminalException class TempClass(Nonterminal): pass class NonterminalsInvalidTest(TestCase): def test_invalidAddNumber(self): gr = Grammar() with self.assertRaises(NotNonterminalException): gr.add_nonterm(0) def test_invalidAddString(self): gr = Grammar() with self.assertRaises(NotNonterminalException): gr.add_nonterm("string") def test_invalidAddAfterCorrectAdd(self): gr = Grammar() gr.add_nonterm(TempClass) with self.assertRaises(NotNonterminalException): gr.add_nonterm("asdf") def test_invalidAddInArray(self): gr = Grammar() with self.assertRaises(NotNonterminalException): gr.add_nonterm([TempClass, "asdf"]) def test_invalidHaveNumber(self): gr = Grammar() with self.assertRaises(NotNonterminalException): gr.have_nonterm(0) def test_invalidHaveString(self): gr = Grammar() with self.assertRaises(NotNonterminalException): gr.have_nonterm("string") def test_invalidHaveAfterCorrectAdd(self): gr = Grammar() gr.add_nonterm(TempClass) with self.assertRaises(NotNonterminalException): gr.have_nonterm("asdf") def test_invalidHaveInArray(self): gr = Grammar() with self.assertRaises(NotNonterminalException): gr.have_nonterm([TempClass, "asdf"]) if __name__ == '__main__': main()
Add tests that have and get of nonterms raise exceptions
Add tests that have and get of nonterms raise exceptions
Python
mit
PatrikValkovic/grammpy
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from unittest import TestCase, main from grammpy.RawGrammar import RawGrammar as Grammar from grammpy import Nonterminal from grammpy.exceptions import NotNonterminalException class TempClass(Nonterminal): pass class NonterminalsInvalidTest(TestCase): def test_invalidAddNumber(self): gr = Grammar() with self.assertRaises(NotNonterminalException): gr.add_nonterm(0) def test_invalidAddString(self): gr = Grammar() with self.assertRaises(NotNonterminalException): gr.add_nonterm("string") def test_invalidAddAfterCorrectAdd(self): gr = Grammar() gr.add_nonterm(TempClass) with self.assertRaises(NotNonterminalException): gr.add_nonterm("asdf") def test_invalidAddInArray(self): gr = Grammar() with self.assertRaises(NotNonterminalException): gr.add_nonterm([TempClass, "asdf"]) def test_invalidHaveNumber(self): gr = Grammar() with self.assertRaises(NotNonterminalException): gr.have_nonterm(0) def test_invalidHaveString(self): gr = Grammar() with self.assertRaises(NotNonterminalException): gr.have_nonterm("string") def test_invalidHaveAfterCorrectAdd(self): gr = Grammar() gr.add_nonterm(TempClass) with self.assertRaises(NotNonterminalException): gr.have_nonterm("asdf") def test_invalidHaveInArray(self): gr = Grammar() with self.assertRaises(NotNonterminalException): gr.have_nonterm([TempClass, "asdf"]) if __name__ == '__main__': main()
Add tests that have and get of nonterms raise exceptions #!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from unittest import TestCase, main from grammpy.RawGrammar import RawGrammar class NonterminalsInvalidTest(TestCase): pass if __name__ == '__main__': main()
8214d516b3feba92ab3ad3b1f2fa1cf253e83012
pyexcel/internal/__init__.py
pyexcel/internal/__init__.py
""" pyexcel.internal ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pyexcel internals that subjected to change :copyright: (c) 2015-2017 by Onni Software Ltd. :license: New BSD License """ from lml.loader import scan_plugins from pyexcel.internal.plugins import PARSER, RENDERER # noqa from pyexcel.internal.source_plugin import SOURCE # noqa from pyexcel.internal.generators import SheetStream, BookStream # noqa BLACK_LIST = [ "pyexcel_io", "pyexcel_webio", "pyexcel_xlsx", "pyexcel_xls", "pyexcel_ods3", "pyexcel_ods", "pyexcel_odsr", "pyexcel_xlsxw", ] WHITE_LIST = [ "pyexcel.plugins.parsers", "pyexcel.plugins.renderers", "pyexcel.plugins.sources", ] scan_plugins("pyexcel_", "pyexcel", BLACK_LIST, WHITE_LIST)
""" pyexcel.internal ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pyexcel internals that subjected to change :copyright: (c) 2015-2017 by Onni Software Ltd. :license: New BSD License """ from lml.loader import scan_plugins from pyexcel.internal.plugins import PARSER, RENDERER # noqa from pyexcel.internal.source_plugin import SOURCE # noqa from pyexcel.internal.generators import SheetStream, BookStream # noqa BLACK_LIST = [ "pyexcel_io", "pyexcel_webio", "pyexcel_xlsx", "pyexcel_xls", "pyexcel_ods3", "pyexcel_ods", "pyexcel_odsr", "pyexcel_xlsxw", ] WHITE_LIST = [ "pyexcel.plugins.parsers", "pyexcel.plugins.renderers", "pyexcel.plugins.sources", ] scan_plugins_regex("^pyexcel_.+$", "pyexcel", BLACK_LIST, WHITE_LIST)
Remove use of deprecated `scan_plugins` method
Remove use of deprecated `scan_plugins` method `scan_plugins` has been deprecated in favour of `scan_plugins_regex`. This is causing warnings to be logged. The new method takes a regular expression as its first argument, rather than a simple prefix string. This commit adds a regular expression which does the same thing as the prefix argument used to do. For source code see: https://lml.readthedocs.io/en/latest/_modules/lml/loader.html
Python
bsd-3-clause
chfw/pyexcel,chfw/pyexcel
""" pyexcel.internal ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pyexcel internals that subjected to change :copyright: (c) 2015-2017 by Onni Software Ltd. :license: New BSD License """ from lml.loader import scan_plugins from pyexcel.internal.plugins import PARSER, RENDERER # noqa from pyexcel.internal.source_plugin import SOURCE # noqa from pyexcel.internal.generators import SheetStream, BookStream # noqa BLACK_LIST = [ "pyexcel_io", "pyexcel_webio", "pyexcel_xlsx", "pyexcel_xls", "pyexcel_ods3", "pyexcel_ods", "pyexcel_odsr", "pyexcel_xlsxw", ] WHITE_LIST = [ "pyexcel.plugins.parsers", "pyexcel.plugins.renderers", "pyexcel.plugins.sources", ] scan_plugins_regex("^pyexcel_.+$", "pyexcel", BLACK_LIST, WHITE_LIST)
Remove use of deprecated `scan_plugins` method `scan_plugins` has been deprecated in favour of `scan_plugins_regex`. This is causing warnings to be logged. The new method takes a regular expression as its first argument, rather than a simple prefix string. This commit adds a regular expression which does the same thing as the prefix argument used to do. For source code see: https://lml.readthedocs.io/en/latest/_modules/lml/loader.html """ pyexcel.internal ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pyexcel internals that subjected to change :copyright: (c) 2015-2017 by Onni Software Ltd. :license: New BSD License """ from lml.loader import scan_plugins from pyexcel.internal.plugins import PARSER, RENDERER # noqa from pyexcel.internal.source_plugin import SOURCE # noqa from pyexcel.internal.generators import SheetStream, BookStream # noqa BLACK_LIST = [ "pyexcel_io", "pyexcel_webio", "pyexcel_xlsx", "pyexcel_xls", "pyexcel_ods3", "pyexcel_ods", "pyexcel_odsr", "pyexcel_xlsxw", ] WHITE_LIST = [ "pyexcel.plugins.parsers", "pyexcel.plugins.renderers", "pyexcel.plugins.sources", ] scan_plugins("pyexcel_", "pyexcel", BLACK_LIST, WHITE_LIST)
9140b3249820d0dd86f7f85270327d9264841b50
tests/search_backend_mysql.py
tests/search_backend_mysql.py
from wolis.test_case import WolisTestCase from wolis import utils class SearchBackendMysqlTest(WolisTestCase): @utils.restrict_database('mysql*') @utils.restrict_phpbb_version('>=3.1.0') def test_set_search_backend(self): self.login('morpheus', 'morpheus') self.acp_login('morpheus', 'morpheus') self.change_acp_knob( link_text='Search settings', check_page_text='Here you can define what search backend will be used', name='config[search_type]', value='phpbb_search_fulltext_mysql', confirm=True, ) if __name__ == '__main__': import unittest unittest.main()
Test for selecting mysql search backend
Test for selecting mysql search backend
Python
bsd-2-clause
p/wolis-phpbb,p/wolis-phpbb
from wolis.test_case import WolisTestCase from wolis import utils class SearchBackendMysqlTest(WolisTestCase): @utils.restrict_database('mysql*') @utils.restrict_phpbb_version('>=3.1.0') def test_set_search_backend(self): self.login('morpheus', 'morpheus') self.acp_login('morpheus', 'morpheus') self.change_acp_knob( link_text='Search settings', check_page_text='Here you can define what search backend will be used', name='config[search_type]', value='phpbb_search_fulltext_mysql', confirm=True, ) if __name__ == '__main__': import unittest unittest.main()
Test for selecting mysql search backend
200efbba25130b84da80720329794e4c47806573
NDIR_RasPi_Python/example.py
NDIR_RasPi_Python/example.py
import NDIR import time sensor = NDIR.Sensor(0x4D) sensor.begin() while True: sensor.measure() print("CO2 Concentration: " + str(sensor.ppm) + "ppm") time.sleep(1)
import NDIR import time sensor = NDIR.Sensor(0x4D) if sensor.begin() == False: print("Adaptor initialization FAILED!") exit() while True: if sensor.measure(): print("CO2 Concentration: " + str(sensor.ppm) + "ppm") else: print("Sensor communication ERROR.") time.sleep(1)
Make use of the return value of begin() and measure()
Make use of the return value of begin() and measure()
Python
mit
SandboxElectronics/NDIR,SandboxElectronics/NDIR,SandboxElectronics/NDIR
import NDIR import time sensor = NDIR.Sensor(0x4D) if sensor.begin() == False: print("Adaptor initialization FAILED!") exit() while True: if sensor.measure(): print("CO2 Concentration: " + str(sensor.ppm) + "ppm") else: print("Sensor communication ERROR.") time.sleep(1)
Make use of the return value of begin() and measure() import NDIR import time sensor = NDIR.Sensor(0x4D) sensor.begin() while True: sensor.measure() print("CO2 Concentration: " + str(sensor.ppm) + "ppm") time.sleep(1)
fa991297168f216c208d53b880124a4f23250034
setup.py
setup.py
import importlib from cx_Freeze import setup, Executable backend_path = importlib.import_module("bcrypt").__path__[0] backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend") # Dependencies are automatically detected, but it might need # fine tuning. build_exe_options = { "include_files": [ ("client/dist", "client"), "LICENSE", "templates", "readme.md", (backend_path, "lib/.libs_cffi_backend") ], "includes": [ "cffi", "numpy", "numpy.core._methods", "numpy.lib", "numpy.lib.format", "raven.processors" ], "packages": [ "_cffi_backend", "appdirs", "asyncio", "bcrypt", "cffi", "idna", "motor", "packaging", "ssl", "uvloop" ] } options = { "build_exe": build_exe_options } executables = [ Executable('run.py', base="Console") ] classifiers=[ "Programming Language :: Python :: 3.7" ] importlib.import_module("virtool") setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")
import importlib from cx_Freeze import setup, Executable backend_path = importlib.import_module("bcrypt").__path__[0] backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend") # Dependencies are automatically detected, but it might need # fine tuning. build_exe_options = { "include_files": [ ("client/dist", "client"), "LICENSE", "templates", "readme.md", (backend_path, "lib/.libs_cffi_backend") ], "includes": [ "cffi", "numpy", "numpy.core._methods", "numpy.lib", "numpy.lib.format", "raven.processors" ], "packages": [ "_cffi_backend", "appdirs", "asyncio", "bcrypt", "cffi", "gzip", "idna", "motor", "packaging", "ssl", "uvloop" ] } options = { "build_exe": build_exe_options } executables = [ Executable('run.py', base="Console") ] classifiers=[ "Programming Language :: Python :: 3.7" ] importlib.import_module("virtool") setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")
Add gzip to cx-freeze packages
Add gzip to cx-freeze packages
Python
mit
virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool
import importlib from cx_Freeze import setup, Executable backend_path = importlib.import_module("bcrypt").__path__[0] backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend") # Dependencies are automatically detected, but it might need # fine tuning. build_exe_options = { "include_files": [ ("client/dist", "client"), "LICENSE", "templates", "readme.md", (backend_path, "lib/.libs_cffi_backend") ], "includes": [ "cffi", "numpy", "numpy.core._methods", "numpy.lib", "numpy.lib.format", "raven.processors" ], "packages": [ "_cffi_backend", "appdirs", "asyncio", "bcrypt", "cffi", "gzip", "idna", "motor", "packaging", "ssl", "uvloop" ] } options = { "build_exe": build_exe_options } executables = [ Executable('run.py', base="Console") ] classifiers=[ "Programming Language :: Python :: 3.7" ] importlib.import_module("virtool") setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")
Add gzip to cx-freeze packages import importlib from cx_Freeze import setup, Executable backend_path = importlib.import_module("bcrypt").__path__[0] backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend") # Dependencies are automatically detected, but it might need # fine tuning. build_exe_options = { "include_files": [ ("client/dist", "client"), "LICENSE", "templates", "readme.md", (backend_path, "lib/.libs_cffi_backend") ], "includes": [ "cffi", "numpy", "numpy.core._methods", "numpy.lib", "numpy.lib.format", "raven.processors" ], "packages": [ "_cffi_backend", "appdirs", "asyncio", "bcrypt", "cffi", "idna", "motor", "packaging", "ssl", "uvloop" ] } options = { "build_exe": build_exe_options } executables = [ Executable('run.py', base="Console") ] classifiers=[ "Programming Language :: Python :: 3.7" ] importlib.import_module("virtool") setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")
7a0b8550fa2f52519df81c7fa795d454e5e3b0bc
scripts/master/factory/dart/channels.py
scripts/master/factory/dart/channels.py
# Copyright 2013 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. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 3), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/0.6', 2, '-stable', 1), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
# Copyright 2013 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. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 3), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/0.7', 2, '-stable', 1), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
Update the build branch for stable to 0.7
Update the build branch for stable to 0.7 TBR=ricow Review URL: https://codereview.chromium.org/26993005 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@228644 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
# Copyright 2013 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. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 3), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/0.7', 2, '-stable', 1), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
Update the build branch for stable to 0.7 TBR=ricow Review URL: https://codereview.chromium.org/26993005 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@228644 0039d316-1c4b-4281-b951-d872f2087c98 # Copyright 2013 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. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 3), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/0.6', 2, '-stable', 1), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
02f35718c6f6c3b18851b94e232031738629684e
promgen/sender/__init__.py
promgen/sender/__init__.py
import logging from promgen.models import Project, Service logger = logging.getLogger(__name__) class SenderBase(object): def send(self, data): for alert in data['alerts']: if 'project' in alert['labels']: sent = 0 for project in Project.objects.filter(name=alert['labels']['project']): for sender in project.sender.all(): if self._send(sender.value, alert, data): sent += 1 if 'service' in alert['labels']: for service in Service.objects.filter(name=alert['labels']['service']): for sender in service.sender.all(): if self._send(sender.value, alert, data): sent += 1 if sent == 0: logger.debug('No senders configured for project or service %s', alert['labels']['project']) return sent def test(self, target, alert): logger.debug('Sending test message to %s', target) self._send(target, alert, {'externalURL': ''})
import logging from promgen.models import Project, Service logger = logging.getLogger(__name__) class SenderBase(object): def send(self, data): sent = 0 for alert in data['alerts']: if 'project' in alert['labels']: logger.debug('Checking for projects') for project in Project.objects.filter(name=alert['labels']['project']): logger.debug('Checking %s', project) for sender in project.sender.all(): logger.debug('Sending to %s', sender) if self._send(sender.value, alert, data): sent += 1 if 'service' in alert['labels']: logger.debug('Checking for service') for service in Service.objects.filter(name=alert['labels']['service']): logger.debug('Checking %s', service) for sender in service.sender.all(): logger.debug('Sending to %s', sender) if self._send(sender.value, alert, data): sent += 1 if sent == 0: logger.debug('No senders configured for project or service %s', alert['labels']['project']) return sent def test(self, target, alert): logger.debug('Sending test message to %s', target) self._send(target, alert, {'externalURL': ''})
Fix send count and add debug logging
Fix send count and add debug logging
Python
mit
kfdm/promgen,kfdm/promgen,kfdm/promgen,kfdm/promgen
import logging from promgen.models import Project, Service logger = logging.getLogger(__name__) class SenderBase(object): def send(self, data): sent = 0 for alert in data['alerts']: if 'project' in alert['labels']: logger.debug('Checking for projects') for project in Project.objects.filter(name=alert['labels']['project']): logger.debug('Checking %s', project) for sender in project.sender.all(): logger.debug('Sending to %s', sender) if self._send(sender.value, alert, data): sent += 1 if 'service' in alert['labels']: logger.debug('Checking for service') for service in Service.objects.filter(name=alert['labels']['service']): logger.debug('Checking %s', service) for sender in service.sender.all(): logger.debug('Sending to %s', sender) if self._send(sender.value, alert, data): sent += 1 if sent == 0: logger.debug('No senders configured for project or service %s', alert['labels']['project']) return sent def test(self, target, alert): logger.debug('Sending test message to %s', target) self._send(target, alert, {'externalURL': ''})
Fix send count and add debug logging import logging from promgen.models import Project, Service logger = logging.getLogger(__name__) class SenderBase(object): def send(self, data): for alert in data['alerts']: if 'project' in alert['labels']: sent = 0 for project in Project.objects.filter(name=alert['labels']['project']): for sender in project.sender.all(): if self._send(sender.value, alert, data): sent += 1 if 'service' in alert['labels']: for service in Service.objects.filter(name=alert['labels']['service']): for sender in service.sender.all(): if self._send(sender.value, alert, data): sent += 1 if sent == 0: logger.debug('No senders configured for project or service %s', alert['labels']['project']) return sent def test(self, target, alert): logger.debug('Sending test message to %s', target) self._send(target, alert, {'externalURL': ''})
50b773cdde5b367ee6cb44426817664ee379ee9f
setup.py
setup.py
from setuptools import setup setup( name='jobcli', version='0.1.a2', py_modules=['jobcli'], install_requires=['click', 'requests',], entry_points={'console_scripts':['jobcli=jobcli:cli',]}, url='https://www.jobcli.com', author='Stephan Goergen', author_email='stephan.goergen@gmail.com', description='Job Search from the Command Line', license='MIT', zip_safe=False, include_package_data=False, keywords='board job search command line career developer engineer', classifiers=[ 'License :: OSI Approved :: MIT License' ,'Development Status :: 3 - Alpha' ,'Environment :: Console' ,'Operating System :: OS Independent' ,'Natural Language :: English' ,'Intended Audience :: Developers' ,'Intended Audience :: Information Technology' ,'Intended Audience :: System Administrators' ,'Intended Audience :: Science/Research' ,'Topic :: Office/Business' ,'Programming Language :: Python :: 2' ,'Programming Language :: Python :: 2.7' ,'Programming Language :: Python :: 3' ,'Programming Language :: Python :: 3.3' ,'Programming Language :: Python :: 3.4' ,'Programming Language :: Python :: 3.5' ] )
from setuptools import setup setup( name='jobcli', version='0.1b1', py_modules=['jobcli'], install_requires=['click', 'requests',], entry_points={'console_scripts':['jobcli=jobcli:cli',]}, url='https://www.jobcli.com', author='Stephan Goergen', author_email='stephan.goergen@gmail.com', description='Job Search from the Command Line', license='MIT', zip_safe=False, include_package_data=False, keywords='board job search command line career developer engineer', classifiers=[ 'License :: OSI Approved :: MIT License' ,'Development Status :: 4 - Beta' ,'Environment :: Console' ,'Operating System :: OS Independent' ,'Natural Language :: English' ,'Intended Audience :: Developers' ,'Intended Audience :: Information Technology' ,'Intended Audience :: System Administrators' ,'Intended Audience :: Science/Research' ,'Topic :: Office/Business' ,'Programming Language :: Python :: 2' ,'Programming Language :: Python :: 2.7' ,'Programming Language :: Python :: 3' ,'Programming Language :: Python :: 3.3' ,'Programming Language :: Python :: 3.4' ,'Programming Language :: Python :: 3.5' ] )
Increase version to beta 1.
Increase version to beta 1.
Python
mit
jobcli/jobcli-app,jobcli/jobcli-app
from setuptools import setup setup( name='jobcli', version='0.1b1', py_modules=['jobcli'], install_requires=['click', 'requests',], entry_points={'console_scripts':['jobcli=jobcli:cli',]}, url='https://www.jobcli.com', author='Stephan Goergen', author_email='stephan.goergen@gmail.com', description='Job Search from the Command Line', license='MIT', zip_safe=False, include_package_data=False, keywords='board job search command line career developer engineer', classifiers=[ 'License :: OSI Approved :: MIT License' ,'Development Status :: 4 - Beta' ,'Environment :: Console' ,'Operating System :: OS Independent' ,'Natural Language :: English' ,'Intended Audience :: Developers' ,'Intended Audience :: Information Technology' ,'Intended Audience :: System Administrators' ,'Intended Audience :: Science/Research' ,'Topic :: Office/Business' ,'Programming Language :: Python :: 2' ,'Programming Language :: Python :: 2.7' ,'Programming Language :: Python :: 3' ,'Programming Language :: Python :: 3.3' ,'Programming Language :: Python :: 3.4' ,'Programming Language :: Python :: 3.5' ] )
Increase version to beta 1. from setuptools import setup setup( name='jobcli', version='0.1.a2', py_modules=['jobcli'], install_requires=['click', 'requests',], entry_points={'console_scripts':['jobcli=jobcli:cli',]}, url='https://www.jobcli.com', author='Stephan Goergen', author_email='stephan.goergen@gmail.com', description='Job Search from the Command Line', license='MIT', zip_safe=False, include_package_data=False, keywords='board job search command line career developer engineer', classifiers=[ 'License :: OSI Approved :: MIT License' ,'Development Status :: 3 - Alpha' ,'Environment :: Console' ,'Operating System :: OS Independent' ,'Natural Language :: English' ,'Intended Audience :: Developers' ,'Intended Audience :: Information Technology' ,'Intended Audience :: System Administrators' ,'Intended Audience :: Science/Research' ,'Topic :: Office/Business' ,'Programming Language :: Python :: 2' ,'Programming Language :: Python :: 2.7' ,'Programming Language :: Python :: 3' ,'Programming Language :: Python :: 3.3' ,'Programming Language :: Python :: 3.4' ,'Programming Language :: Python :: 3.5' ] )
a667b3503b0434f01459bae2d29df800d95ba1c4
gapipy/resources/tour/departure.py
gapipy/resources/tour/departure.py
from __future__ import unicode_literals from ...models import Address, AddOn, DepartureRoom, PP2aPrice from ..base import Product from .tour_dossier import TourDossier from .departure_component import DepartureComponent class Departure(Product): _resource_name = 'departures' _is_listable = True _is_parent_resource = True _as_is_fields = [ 'id', 'href', 'availability', 'flags', 'nearest_start_airport', 'nearest_finish_airport', 'product_line', 'sku', 'requirements', ] _date_fields = ['start_date', 'finish_date'] _date_time_fields_utc = ['date_created', 'date_last_modified'] _date_time_fields_local = ['latest_arrival_time', 'earliest_departure_time'] _resource_fields = [('tour', 'Tour'), ('tour_dossier', TourDossier)] _resource_collection_fields = [ ('components', DepartureComponent), ] _model_fields = [('start_address', Address), ('finish_address', Address)] _model_collection_fields = [ ('addons', AddOn), ('rooms', DepartureRoom), ('lowest_pp2a_prices', PP2aPrice), ] _deprecated_fields = ['add_ons']
from __future__ import unicode_literals from ...models import Address, AddOn, DepartureRoom, PP2aPrice from ..base import Product from .tour_dossier import TourDossier from .departure_component import DepartureComponent class Departure(Product): _resource_name = 'departures' _is_listable = True _is_parent_resource = True _as_is_fields = [ 'id', 'href', 'name', 'availability', 'flags', 'nearest_start_airport', 'nearest_finish_airport', 'product_line', 'sku', 'requirements', ] _date_fields = ['start_date', 'finish_date'] _date_time_fields_utc = ['date_created', 'date_last_modified'] _date_time_fields_local = ['latest_arrival_time', 'earliest_departure_time'] _resource_fields = [('tour', 'Tour'), ('tour_dossier', TourDossier)] _resource_collection_fields = [ ('components', DepartureComponent), ] _model_fields = [('start_address', Address), ('finish_address', Address)] _model_collection_fields = [ ('addons', AddOn), ('rooms', DepartureRoom), ('lowest_pp2a_prices', PP2aPrice), ] _deprecated_fields = ['add_ons']
Add name to Departure resource
Add name to Departure resource
Python
mit
gadventures/gapipy
from __future__ import unicode_literals from ...models import Address, AddOn, DepartureRoom, PP2aPrice from ..base import Product from .tour_dossier import TourDossier from .departure_component import DepartureComponent class Departure(Product): _resource_name = 'departures' _is_listable = True _is_parent_resource = True _as_is_fields = [ 'id', 'href', 'name', 'availability', 'flags', 'nearest_start_airport', 'nearest_finish_airport', 'product_line', 'sku', 'requirements', ] _date_fields = ['start_date', 'finish_date'] _date_time_fields_utc = ['date_created', 'date_last_modified'] _date_time_fields_local = ['latest_arrival_time', 'earliest_departure_time'] _resource_fields = [('tour', 'Tour'), ('tour_dossier', TourDossier)] _resource_collection_fields = [ ('components', DepartureComponent), ] _model_fields = [('start_address', Address), ('finish_address', Address)] _model_collection_fields = [ ('addons', AddOn), ('rooms', DepartureRoom), ('lowest_pp2a_prices', PP2aPrice), ] _deprecated_fields = ['add_ons']
Add name to Departure resource from __future__ import unicode_literals from ...models import Address, AddOn, DepartureRoom, PP2aPrice from ..base import Product from .tour_dossier import TourDossier from .departure_component import DepartureComponent class Departure(Product): _resource_name = 'departures' _is_listable = True _is_parent_resource = True _as_is_fields = [ 'id', 'href', 'availability', 'flags', 'nearest_start_airport', 'nearest_finish_airport', 'product_line', 'sku', 'requirements', ] _date_fields = ['start_date', 'finish_date'] _date_time_fields_utc = ['date_created', 'date_last_modified'] _date_time_fields_local = ['latest_arrival_time', 'earliest_departure_time'] _resource_fields = [('tour', 'Tour'), ('tour_dossier', TourDossier)] _resource_collection_fields = [ ('components', DepartureComponent), ] _model_fields = [('start_address', Address), ('finish_address', Address)] _model_collection_fields = [ ('addons', AddOn), ('rooms', DepartureRoom), ('lowest_pp2a_prices', PP2aPrice), ] _deprecated_fields = ['add_ons']
b55676c4cfb2d662c9a82d17504db091449e3992
setup.py
setup.py
from setuptools import setup, find_packages setup(name='scattertext', version='0.0.2.22', description='An NLP package to visualize interesting terms in text.', url='https://github.com/JasonKessler/scattertext', author='Jason Kessler', author_email='jason.kessler@gmail.com', license='MIT', packages=find_packages(), install_requires=[ 'numpy', 'scipy', 'sklearn', 'pandas', #'spacy', #'jieba', #'tinysegmenter', #'empath', #'umap', #'gensim' # 'matplotlib', # 'seaborn', # 'jupyter', ], package_data={ 'scattertext': ['data/*', 'data/viz/*', 'data/viz/*/*'] }, test_suite="nose.collector", tests_require=['nose'], #setup_requires=['nose>=1.0'], entry_points={ 'console_scripts': [ 'scattertext = scattertext.CLI:main', ], }, zip_safe=False)
from setuptools import setup, find_packages setup(name='scattertext', version='0.0.2.22', description='An NLP package to visualize interesting terms in text.', url='https://github.com/JasonKessler/scattertext', author='Jason Kessler', author_email='jason.kessler@gmail.com', license='MIT', packages=find_packages(), install_requires=[ 'numpy', 'scipy', 'scikit-learn', 'pandas', #'spacy', #'jieba', #'tinysegmenter', #'empath', #'umap', #'gensim' # 'matplotlib', # 'seaborn', # 'jupyter', ], package_data={ 'scattertext': ['data/*', 'data/viz/*', 'data/viz/*/*'] }, test_suite="nose.collector", tests_require=['nose'], #setup_requires=['nose>=1.0'], entry_points={ 'console_scripts': [ 'scattertext = scattertext.CLI:main', ], }, zip_safe=False)
Replace `sklearn` dependency with `scikit-learn`
Replace `sklearn` dependency with `scikit-learn` `sklearn` isn't the package you're looking for; as https://pypi.python.org/pypi/sklearn politely notes, you should "use scikit-learn instead": https://pypi.python.org/pypi/scikit-learn/ It's unfortunate that the names of Python packages have nothing to do with their import names, besides convention :(
Python
apache-2.0
JasonKessler/scattertext,JasonKessler/scattertext,JasonKessler/scattertext,JasonKessler/scattertext
from setuptools import setup, find_packages setup(name='scattertext', version='0.0.2.22', description='An NLP package to visualize interesting terms in text.', url='https://github.com/JasonKessler/scattertext', author='Jason Kessler', author_email='jason.kessler@gmail.com', license='MIT', packages=find_packages(), install_requires=[ 'numpy', 'scipy', 'scikit-learn', 'pandas', #'spacy', #'jieba', #'tinysegmenter', #'empath', #'umap', #'gensim' # 'matplotlib', # 'seaborn', # 'jupyter', ], package_data={ 'scattertext': ['data/*', 'data/viz/*', 'data/viz/*/*'] }, test_suite="nose.collector", tests_require=['nose'], #setup_requires=['nose>=1.0'], entry_points={ 'console_scripts': [ 'scattertext = scattertext.CLI:main', ], }, zip_safe=False)
Replace `sklearn` dependency with `scikit-learn` `sklearn` isn't the package you're looking for; as https://pypi.python.org/pypi/sklearn politely notes, you should "use scikit-learn instead": https://pypi.python.org/pypi/scikit-learn/ It's unfortunate that the names of Python packages have nothing to do with their import names, besides convention :( from setuptools import setup, find_packages setup(name='scattertext', version='0.0.2.22', description='An NLP package to visualize interesting terms in text.', url='https://github.com/JasonKessler/scattertext', author='Jason Kessler', author_email='jason.kessler@gmail.com', license='MIT', packages=find_packages(), install_requires=[ 'numpy', 'scipy', 'sklearn', 'pandas', #'spacy', #'jieba', #'tinysegmenter', #'empath', #'umap', #'gensim' # 'matplotlib', # 'seaborn', # 'jupyter', ], package_data={ 'scattertext': ['data/*', 'data/viz/*', 'data/viz/*/*'] }, test_suite="nose.collector", tests_require=['nose'], #setup_requires=['nose>=1.0'], entry_points={ 'console_scripts': [ 'scattertext = scattertext.CLI:main', ], }, zip_safe=False)
d5c296197c7f5b422f44e58f8e58ead5fdc5c2ad
reports/models.py
reports/models.py
from datetime import datetime from django.db import models from django.utils.translation import ugettext_lazy as _ class Report(models.Model): addressed_to = models.TextField() reported_from = models.ForeignKey('members.User') content = models.TextField() created_at = models.DateField(_("Date"), default=datetime.now()) copies = models.ManyToManyField('protocols.Topic') signed_from = models.CharField(max_length=64) def __unicode__(self): return self.addressed_to def get_copies(self): return "\n".join([c.name for c in self.copies.all()])
from datetime import datetime from django.db import models class Report(models.Model): addressed_to = models.TextField() reported_from = models.ForeignKey('members.User') content = models.TextField() created_at = models.DateField(default=datetime.now) copies = models.ManyToManyField('protocols.Topic') signed_from = models.CharField(max_length=64) def __unicode__(self): return self.addressed_to def get_copies(self): return "\n".join([c.name for c in self.copies.all()])
Add new initial migration for reports
Add new initial migration for reports
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
from datetime import datetime from django.db import models class Report(models.Model): addressed_to = models.TextField() reported_from = models.ForeignKey('members.User') content = models.TextField() created_at = models.DateField(default=datetime.now) copies = models.ManyToManyField('protocols.Topic') signed_from = models.CharField(max_length=64) def __unicode__(self): return self.addressed_to def get_copies(self): return "\n".join([c.name for c in self.copies.all()])
Add new initial migration for reports from datetime import datetime from django.db import models from django.utils.translation import ugettext_lazy as _ class Report(models.Model): addressed_to = models.TextField() reported_from = models.ForeignKey('members.User') content = models.TextField() created_at = models.DateField(_("Date"), default=datetime.now()) copies = models.ManyToManyField('protocols.Topic') signed_from = models.CharField(max_length=64) def __unicode__(self): return self.addressed_to def get_copies(self): return "\n".join([c.name for c in self.copies.all()])
c8af52e91eb5ea40090a4b303e147c2d5d6cf28a
cloudbaseinit/shell.py
cloudbaseinit/shell.py
# Copyright 2012 Cloudbase Solutions Srl # # 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 sys from oslo_config import cfg from oslo_log import log as oslo_logging from cloudbaseinit import init from cloudbaseinit.utils import log as logging CONF = cfg.CONF LOG = oslo_logging.getLogger(__name__) def main(): CONF(sys.argv[1:]) logging.setup('cloudbaseinit') try: init.InitManager().configure_host() except Exception as exc: LOG.exception(exc) raise if __name__ == "__main__": main()
# Copyright 2012 Cloudbase Solutions Srl # # 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 sys import pythoncom sys.coinit_flags = pythoncom.COINIT_MULTITHREADED pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) from oslo_config import cfg from oslo_log import log as oslo_logging from cloudbaseinit import init from cloudbaseinit.utils import log as logging CONF = cfg.CONF LOG = oslo_logging.getLogger(__name__) def main(): CONF(sys.argv[1:]) logging.setup('cloudbaseinit') try: init.InitManager().configure_host() except Exception as exc: LOG.exception(exc) raise if __name__ == "__main__": main()
Fix py3 x64 crash thread related
Fix py3 x64 crash thread related Change-Id: Iac00ea2463df4346ad60a17d0ba9a2af089c87cd
Python
apache-2.0
chialiang-8/cloudbase-init,stackforge/cloudbase-init,openstack/cloudbase-init,stefan-caraiman/cloudbase-init,cmin764/cloudbase-init,alexpilotti/cloudbase-init,ader1990/cloudbase-init
# Copyright 2012 Cloudbase Solutions Srl # # 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 sys import pythoncom sys.coinit_flags = pythoncom.COINIT_MULTITHREADED pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) from oslo_config import cfg from oslo_log import log as oslo_logging from cloudbaseinit import init from cloudbaseinit.utils import log as logging CONF = cfg.CONF LOG = oslo_logging.getLogger(__name__) def main(): CONF(sys.argv[1:]) logging.setup('cloudbaseinit') try: init.InitManager().configure_host() except Exception as exc: LOG.exception(exc) raise if __name__ == "__main__": main()
Fix py3 x64 crash thread related Change-Id: Iac00ea2463df4346ad60a17d0ba9a2af089c87cd # Copyright 2012 Cloudbase Solutions Srl # # 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 sys from oslo_config import cfg from oslo_log import log as oslo_logging from cloudbaseinit import init from cloudbaseinit.utils import log as logging CONF = cfg.CONF LOG = oslo_logging.getLogger(__name__) def main(): CONF(sys.argv[1:]) logging.setup('cloudbaseinit') try: init.InitManager().configure_host() except Exception as exc: LOG.exception(exc) raise if __name__ == "__main__": main()
60bf4d1457059b3cd53e5b37eab6d428ff4df511
src/artgraph/plugins/infobox.py
src/artgraph/plugins/infobox.py
from artgraph.plugins.plugin import Plugin from artgraph.node import Node, NodeTypes from artgraph.relationship import AssociatedActRelationship class InfoboxPlugin(Plugin): def __init__(self, node): self._node = node def get_nodes(self): wikicode = self.get_wikicode(self._node.get_title()) templates = wikicode.filter_templates() relationships = [] for t in templates: if t.name.matches('Infobox musical artist'): associated_acts = t.get('associated_acts') for w in associated_acts.value.filter_wikilinks(): relationships.append(AssociatedActRelationship(self._node, Node(w.title, NodeTypes.ARTIST))) return relationships
from artgraph.plugins.plugin import Plugin class InfoboxPlugin(Plugin): def __init__(self, node): self._node = node def get_nodes(self): from artgraph.node import Node, NodeTypes from artgraph.relationship import AssociatedActRelationship wikicode = self.get_wikicode(self._node.get_title()) templates = wikicode.filter_templates() relationships = [] for t in templates: if t.name.matches('Infobox musical artist'): associated_acts = t.get('associated_acts') for w in associated_acts.value.filter_wikilinks(): relationships.append(AssociatedActRelationship(self._node, Node(w.title, NodeTypes.ARTIST))) return relationships
Fix imports to be able to import properly from the worker nodes
Fix imports to be able to import properly from the worker nodes
Python
mit
dMaggot/ArtistGraph
from artgraph.plugins.plugin import Plugin class InfoboxPlugin(Plugin): def __init__(self, node): self._node = node def get_nodes(self): from artgraph.node import Node, NodeTypes from artgraph.relationship import AssociatedActRelationship wikicode = self.get_wikicode(self._node.get_title()) templates = wikicode.filter_templates() relationships = [] for t in templates: if t.name.matches('Infobox musical artist'): associated_acts = t.get('associated_acts') for w in associated_acts.value.filter_wikilinks(): relationships.append(AssociatedActRelationship(self._node, Node(w.title, NodeTypes.ARTIST))) return relationships
Fix imports to be able to import properly from the worker nodes from artgraph.plugins.plugin import Plugin from artgraph.node import Node, NodeTypes from artgraph.relationship import AssociatedActRelationship class InfoboxPlugin(Plugin): def __init__(self, node): self._node = node def get_nodes(self): wikicode = self.get_wikicode(self._node.get_title()) templates = wikicode.filter_templates() relationships = [] for t in templates: if t.name.matches('Infobox musical artist'): associated_acts = t.get('associated_acts') for w in associated_acts.value.filter_wikilinks(): relationships.append(AssociatedActRelationship(self._node, Node(w.title, NodeTypes.ARTIST))) return relationships
1058ed0847d151246299f73b325004fc04946fa0
Basics/challenge_2.py
Basics/challenge_2.py
#!/usr/bin/env python if __name__ == '__main__': s1 = 0x1c0111001f010100061a024b53535009181c s2 = 0x686974207468652062756c6c277320657965 print(hex(s1 ^ s2))
Set 1 - Challenge 2
Set 1 - Challenge 2
Python
apache-2.0
Scythe14/Crypto
#!/usr/bin/env python if __name__ == '__main__': s1 = 0x1c0111001f010100061a024b53535009181c s2 = 0x686974207468652062756c6c277320657965 print(hex(s1 ^ s2))
Set 1 - Challenge 2
79ac1550b5acd407b2a107e694c66cccfbc0be89
alerts/lib/deadman_alerttask.py
alerts/lib/deadman_alerttask.py
from alerttask import AlertTask class DeadmanAlertTask(AlertTask): def __init__(self): self.deadman = True def executeSearchEventsSimple(self): # We override this method to specify the size as 1 # since we only care about if ANY events are found or not return self.main_query.execute(self.es, indices=self.event_indices, size=1)
from alerttask import AlertTask class DeadmanAlertTask(AlertTask): def executeSearchEventsSimple(self): # We override this method to specify the size as 1 # since we only care about if ANY events are found or not return self.main_query.execute(self.es, indices=self.event_indices, size=1)
Remove deadman alerttask init method
Remove deadman alerttask init method
Python
mpl-2.0
jeffbryner/MozDef,gdestuynder/MozDef,mozilla/MozDef,mpurzynski/MozDef,mozilla/MozDef,Phrozyn/MozDef,jeffbryner/MozDef,jeffbryner/MozDef,Phrozyn/MozDef,mpurzynski/MozDef,gdestuynder/MozDef,Phrozyn/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,gdestuynder/MozDef,Phrozyn/MozDef,mozilla/MozDef,jeffbryner/MozDef,mozilla/MozDef,gdestuynder/MozDef
from alerttask import AlertTask class DeadmanAlertTask(AlertTask): def executeSearchEventsSimple(self): # We override this method to specify the size as 1 # since we only care about if ANY events are found or not return self.main_query.execute(self.es, indices=self.event_indices, size=1)
Remove deadman alerttask init method from alerttask import AlertTask class DeadmanAlertTask(AlertTask): def __init__(self): self.deadman = True def executeSearchEventsSimple(self): # We override this method to specify the size as 1 # since we only care about if ANY events are found or not return self.main_query.execute(self.es, indices=self.event_indices, size=1)
adab4c914d759f84731bc736fc9afe9862f8222e
tests/backends/gstreamer.py
tests/backends/gstreamer.py
import unittest from mopidy.backends.gstreamer import GStreamerBackend from tests.backends import (BasePlaybackControllerTest, BaseCurrentPlaylistControllerTest) class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase): uri = ['file://data/song1.mp3', 'file://data/song2.mp3', 'file://data/song3.mp3', ] backend_class = GStreamerBackend class GStreamerPlaybackControllerTest(BasePlaybackControllerTest, unittest.TestCase): backend_class = GStreamerBackend if __name__ == '__main__': unittest.main()
import unittest from mopidy.backends.gstreamer import GStreamerBackend from tests.backends import (BasePlaybackControllerTest, BaseCurrentPlaylistControllerTest) class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase): uris = ['file://data/song1.mp3', 'file://data/song2.mp3', 'file://data/song3.mp3', ] backend_class = GStreamerBackend class GStreamerPlaybackControllerTest(BasePlaybackControllerTest, unittest.TestCase): backend_class = GStreamerBackend if __name__ == '__main__': unittest.main()
Fix typo in GStreamer test
Fix typo in GStreamer test
Python
apache-2.0
woutervanwijk/mopidy,hkariti/mopidy,quartz55/mopidy,woutervanwijk/mopidy,swak/mopidy,vrs01/mopidy,vrs01/mopidy,tkem/mopidy,jmarsik/mopidy,kingosticks/mopidy,swak/mopidy,mokieyue/mopidy,kingosticks/mopidy,bacontext/mopidy,glogiotatidis/mopidy,priestd09/mopidy,mokieyue/mopidy,ali/mopidy,hkariti/mopidy,mokieyue/mopidy,tkem/mopidy,mopidy/mopidy,jcass77/mopidy,pacificIT/mopidy,rawdlite/mopidy,priestd09/mopidy,jodal/mopidy,bencevans/mopidy,abarisain/mopidy,dbrgn/mopidy,jodal/mopidy,priestd09/mopidy,pacificIT/mopidy,bacontext/mopidy,ZenithDK/mopidy,ZenithDK/mopidy,adamcik/mopidy,pacificIT/mopidy,dbrgn/mopidy,jcass77/mopidy,vrs01/mopidy,SuperStarPL/mopidy,vrs01/mopidy,ZenithDK/mopidy,mopidy/mopidy,kingosticks/mopidy,tkem/mopidy,glogiotatidis/mopidy,bencevans/mopidy,quartz55/mopidy,diandiankan/mopidy,mokieyue/mopidy,adamcik/mopidy,rawdlite/mopidy,liamw9534/mopidy,liamw9534/mopidy,ZenithDK/mopidy,adamcik/mopidy,SuperStarPL/mopidy,SuperStarPL/mopidy,pacificIT/mopidy,quartz55/mopidy,hkariti/mopidy,jmarsik/mopidy,rawdlite/mopidy,swak/mopidy,ali/mopidy,quartz55/mopidy,abarisain/mopidy,mopidy/mopidy,bacontext/mopidy,glogiotatidis/mopidy,bacontext/mopidy,diandiankan/mopidy,rawdlite/mopidy,diandiankan/mopidy,dbrgn/mopidy,jodal/mopidy,dbrgn/mopidy,jmarsik/mopidy,bencevans/mopidy,glogiotatidis/mopidy,diandiankan/mopidy,swak/mopidy,SuperStarPL/mopidy,ali/mopidy,ali/mopidy,bencevans/mopidy,jmarsik/mopidy,jcass77/mopidy,hkariti/mopidy,tkem/mopidy
import unittest from mopidy.backends.gstreamer import GStreamerBackend from tests.backends import (BasePlaybackControllerTest, BaseCurrentPlaylistControllerTest) class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase): uris = ['file://data/song1.mp3', 'file://data/song2.mp3', 'file://data/song3.mp3', ] backend_class = GStreamerBackend class GStreamerPlaybackControllerTest(BasePlaybackControllerTest, unittest.TestCase): backend_class = GStreamerBackend if __name__ == '__main__': unittest.main()
Fix typo in GStreamer test import unittest from mopidy.backends.gstreamer import GStreamerBackend from tests.backends import (BasePlaybackControllerTest, BaseCurrentPlaylistControllerTest) class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase): uri = ['file://data/song1.mp3', 'file://data/song2.mp3', 'file://data/song3.mp3', ] backend_class = GStreamerBackend class GStreamerPlaybackControllerTest(BasePlaybackControllerTest, unittest.TestCase): backend_class = GStreamerBackend if __name__ == '__main__': unittest.main()
dfb53cd63c908f13dafcc159ce337af653523748
datasets/forms.py
datasets/forms.py
from django import forms from datasets.models import DatasetRelease, CategoryComment class DatasetReleaseForm(forms.ModelForm): max_number_of_sounds = forms.IntegerField(required=False) class Meta: model = DatasetRelease fields = ['release_tag', 'type'] class PresentNotPresentUnsureForm(forms.Form): vote = forms.ChoiceField( required=True, widget=forms.RadioSelect, choices=( ('1', 'Present and predominant',), ('0.5', 'Present but not predominant',), ('-1', 'Not Present',), ('0', 'Unsure',), ), ) annotation_id = forms.IntegerField( required=True, widget=forms.HiddenInput, ) visited_sound = forms.BooleanField( required=False, initial=False, widget=forms.HiddenInput, ) class CategoryCommentForm(forms.ModelForm): class Meta: model = CategoryComment fields = ['comment', 'category_id', 'dataset'] widgets = { 'comment': forms.Textarea(attrs={ 'cols': 80, 'rows': 3, 'placeholder': 'Add here any general comments you want to make about this category'}), 'category_id': forms.HiddenInput, 'dataset_id': forms.HiddenInput, }
from django import forms from datasets.models import DatasetRelease, CategoryComment class DatasetReleaseForm(forms.ModelForm): max_number_of_sounds = forms.IntegerField(required=False) class Meta: model = DatasetRelease fields = ['release_tag', 'type'] class PresentNotPresentUnsureForm(forms.Form): vote = forms.ChoiceField( required=True, widget=forms.RadioSelect, choices=( ('1', 'Present and predominant',), ('0.5', 'Present but not predominant',), ('-1', 'Not present',), ('0', 'Unsure',), ), ) annotation_id = forms.IntegerField( required=True, widget=forms.HiddenInput, ) visited_sound = forms.BooleanField( required=False, initial=False, widget=forms.HiddenInput, ) class CategoryCommentForm(forms.ModelForm): class Meta: model = CategoryComment fields = ['comment', 'category_id', 'dataset'] widgets = { 'comment': forms.Textarea(attrs={ 'cols': 80, 'rows': 3, 'placeholder': 'Add here any general comments you want to make about this category'}), 'category_id': forms.HiddenInput, 'dataset_id': forms.HiddenInput, }
Remove upper case Not Present
Remove upper case Not Present
Python
agpl-3.0
MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets
from django import forms from datasets.models import DatasetRelease, CategoryComment class DatasetReleaseForm(forms.ModelForm): max_number_of_sounds = forms.IntegerField(required=False) class Meta: model = DatasetRelease fields = ['release_tag', 'type'] class PresentNotPresentUnsureForm(forms.Form): vote = forms.ChoiceField( required=True, widget=forms.RadioSelect, choices=( ('1', 'Present and predominant',), ('0.5', 'Present but not predominant',), ('-1', 'Not present',), ('0', 'Unsure',), ), ) annotation_id = forms.IntegerField( required=True, widget=forms.HiddenInput, ) visited_sound = forms.BooleanField( required=False, initial=False, widget=forms.HiddenInput, ) class CategoryCommentForm(forms.ModelForm): class Meta: model = CategoryComment fields = ['comment', 'category_id', 'dataset'] widgets = { 'comment': forms.Textarea(attrs={ 'cols': 80, 'rows': 3, 'placeholder': 'Add here any general comments you want to make about this category'}), 'category_id': forms.HiddenInput, 'dataset_id': forms.HiddenInput, }
Remove upper case Not Present from django import forms from datasets.models import DatasetRelease, CategoryComment class DatasetReleaseForm(forms.ModelForm): max_number_of_sounds = forms.IntegerField(required=False) class Meta: model = DatasetRelease fields = ['release_tag', 'type'] class PresentNotPresentUnsureForm(forms.Form): vote = forms.ChoiceField( required=True, widget=forms.RadioSelect, choices=( ('1', 'Present and predominant',), ('0.5', 'Present but not predominant',), ('-1', 'Not Present',), ('0', 'Unsure',), ), ) annotation_id = forms.IntegerField( required=True, widget=forms.HiddenInput, ) visited_sound = forms.BooleanField( required=False, initial=False, widget=forms.HiddenInput, ) class CategoryCommentForm(forms.ModelForm): class Meta: model = CategoryComment fields = ['comment', 'category_id', 'dataset'] widgets = { 'comment': forms.Textarea(attrs={ 'cols': 80, 'rows': 3, 'placeholder': 'Add here any general comments you want to make about this category'}), 'category_id': forms.HiddenInput, 'dataset_id': forms.HiddenInput, }
d2106c0a6cb4bbf523914786ded873261cb174c2
nipype/pipeline/__init__.py
nipype/pipeline/__init__.py
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ Package contains modules for generating pipelines using interfaces """ __docformat__ = 'restructuredtext' from .engine import Node, MapNode, Workflow from .utils import write_prov
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ Package contains modules for generating pipelines using interfaces """ __docformat__ = 'restructuredtext' from engine import Node, MapNode, JoinNode, Workflow from .utils import write_prov
Add JoinNode to pipeline init
Add JoinNode to pipeline init
Python
bsd-3-clause
arokem/nipype,gerddie/nipype,Leoniela/nipype,fprados/nipype,pearsonlab/nipype,blakedewey/nipype,carolFrohlich/nipype,blakedewey/nipype,gerddie/nipype,dgellis90/nipype,glatard/nipype,arokem/nipype,carlohamalainen/nipype,carolFrohlich/nipype,Leoniela/nipype,glatard/nipype,dmordom/nipype,grlee77/nipype,carolFrohlich/nipype,iglpdc/nipype,grlee77/nipype,sgiavasis/nipype,carlohamalainen/nipype,fprados/nipype,blakedewey/nipype,wanderine/nipype,pearsonlab/nipype,sgiavasis/nipype,wanderine/nipype,FCP-INDI/nipype,blakedewey/nipype,sgiavasis/nipype,gerddie/nipype,Leoniela/nipype,FCP-INDI/nipype,iglpdc/nipype,carolFrohlich/nipype,mick-d/nipype,dgellis90/nipype,JohnGriffiths/nipype,mick-d/nipype,FCP-INDI/nipype,pearsonlab/nipype,wanderine/nipype,JohnGriffiths/nipype,pearsonlab/nipype,gerddie/nipype,mick-d/nipype_source,dmordom/nipype,grlee77/nipype,rameshvs/nipype,wanderine/nipype,carlohamalainen/nipype,mick-d/nipype,arokem/nipype,dgellis90/nipype,mick-d/nipype,grlee77/nipype,rameshvs/nipype,fprados/nipype,iglpdc/nipype,JohnGriffiths/nipype,sgiavasis/nipype,arokem/nipype,iglpdc/nipype,JohnGriffiths/nipype,dgellis90/nipype,glatard/nipype,FCP-INDI/nipype,rameshvs/nipype,dmordom/nipype,rameshvs/nipype,mick-d/nipype_source,mick-d/nipype_source,glatard/nipype
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ Package contains modules for generating pipelines using interfaces """ __docformat__ = 'restructuredtext' from engine import Node, MapNode, JoinNode, Workflow from .utils import write_prov
Add JoinNode to pipeline init # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ Package contains modules for generating pipelines using interfaces """ __docformat__ = 'restructuredtext' from .engine import Node, MapNode, Workflow from .utils import write_prov
896a9b3d116a6ac2d313c5ea8dbc16345a097138
linguine/ops/StanfordCoreNLP.py
linguine/ops/StanfordCoreNLP.py
#!/usr/bin/env python import os """ Performs some core NLP operations as a proof of concept for the library. """ from stanford_corenlp_pywrapper import CoreNLP class StanfordCoreNLP: def __init__(self): # I don't see anywhere to put properties like this path... # For now it's hardcoded and would need to be changed when deployed... coreNLPPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLP.jar') coreNLPModelsPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLPModels.jar') self.proc = CoreNLP('pos', corenlp_jars=[coreNLPPath, coreNLPModelsPath]) def run(self, data): results = [] for corpus in data: results.append(self.proc.parse_doc(corpus.contents)) return results
#!/usr/bin/env python import os """ Performs some core NLP operations as a proof of concept for the library. """ from stanford_corenlp_pywrapper import CoreNLP class StanfordCoreNLP: """ When the JSON segments return from the CoreNLP library, they separate the data acquired from each word into their own element. For readability's sake, it would be nice to pair all of the information for a given word with that word, making a list of words with their part of speech tags """ def jsonCleanup(self, data): for corpus in data: res = self.proc.parse_doc(corpus.contents) for sentence in res["sentences"]: words = [] for index, token in enumerate(sentence["tokens"]): word = {} word["token"] = sentence["tokens"][index] word["lemma"] = sentence["lemmas"][index] word["part-of-speech"] = sentence["pos"][index] words.append(word) return words def __init__(self): coreNLPPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLP.jar') coreNLPModelsPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLPModels.jar') self.proc = CoreNLP('pos', corenlp_jars=[coreNLPPath, coreNLPModelsPath]) def run(self, data): return self.jsonCleanup(data)
Format JSON to be collections of tokens
Format JSON to be collections of tokens When coreNLP returns the JSON payload, it is in an unmanageable format where multiple arrays are made for all parts of speech, tokens, and lemmas. It's much easier to manage when the response is formatted as a list of objects: { "token": "Pineapple", "lemma": "Pineapple", "part-of-speech": "DT" }
Python
mit
rigatoni/linguine-python,Pastafarians/linguine-python
#!/usr/bin/env python import os """ Performs some core NLP operations as a proof of concept for the library. """ from stanford_corenlp_pywrapper import CoreNLP class StanfordCoreNLP: """ When the JSON segments return from the CoreNLP library, they separate the data acquired from each word into their own element. For readability's sake, it would be nice to pair all of the information for a given word with that word, making a list of words with their part of speech tags """ def jsonCleanup(self, data): for corpus in data: res = self.proc.parse_doc(corpus.contents) for sentence in res["sentences"]: words = [] for index, token in enumerate(sentence["tokens"]): word = {} word["token"] = sentence["tokens"][index] word["lemma"] = sentence["lemmas"][index] word["part-of-speech"] = sentence["pos"][index] words.append(word) return words def __init__(self): coreNLPPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLP.jar') coreNLPModelsPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLPModels.jar') self.proc = CoreNLP('pos', corenlp_jars=[coreNLPPath, coreNLPModelsPath]) def run(self, data): return self.jsonCleanup(data)
Format JSON to be collections of tokens When coreNLP returns the JSON payload, it is in an unmanageable format where multiple arrays are made for all parts of speech, tokens, and lemmas. It's much easier to manage when the response is formatted as a list of objects: { "token": "Pineapple", "lemma": "Pineapple", "part-of-speech": "DT" } #!/usr/bin/env python import os """ Performs some core NLP operations as a proof of concept for the library. """ from stanford_corenlp_pywrapper import CoreNLP class StanfordCoreNLP: def __init__(self): # I don't see anywhere to put properties like this path... # For now it's hardcoded and would need to be changed when deployed... coreNLPPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLP.jar') coreNLPModelsPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLPModels.jar') self.proc = CoreNLP('pos', corenlp_jars=[coreNLPPath, coreNLPModelsPath]) def run(self, data): results = [] for corpus in data: results.append(self.proc.parse_doc(corpus.contents)) return results
27d37833663842405f159127f30c6351958fcb10
bench_examples/bench_dec_insert.py
bench_examples/bench_dec_insert.py
from csv import DictWriter from ktbs_bench.utils.decorators import bench @bench def batch_insert(graph, file): """Insert triples in batch.""" print(graph, file) if __name__ == '__main__': # Define some graph/store to use graph_list = ['g1', 'g2'] # Define some files to get the triples from n3file_list = ['f1', 'f2'] # Testing batch insert res = {'func_name': 'batch_insert'} for graph in graph_list: for n3file in n3file_list: time_res = batch_insert(graph, n3file) res[time_res[0]] = time_res[1] # Setup the result CSV with open('/tmp/res.csv', 'wb') as outfile: res_csv = DictWriter(outfile, fieldnames=res.keys()) res_csv.writeheader() # Write the results res_csv.writerow(res)
Add draft of example using the new @bench
Add draft of example using the new @bench
Python
mit
ktbs/ktbs-bench,ktbs/ktbs-bench
from csv import DictWriter from ktbs_bench.utils.decorators import bench @bench def batch_insert(graph, file): """Insert triples in batch.""" print(graph, file) if __name__ == '__main__': # Define some graph/store to use graph_list = ['g1', 'g2'] # Define some files to get the triples from n3file_list = ['f1', 'f2'] # Testing batch insert res = {'func_name': 'batch_insert'} for graph in graph_list: for n3file in n3file_list: time_res = batch_insert(graph, n3file) res[time_res[0]] = time_res[1] # Setup the result CSV with open('/tmp/res.csv', 'wb') as outfile: res_csv = DictWriter(outfile, fieldnames=res.keys()) res_csv.writeheader() # Write the results res_csv.writerow(res)
Add draft of example using the new @bench
6708fd75eb7272701e8e333e4940e47d5b6a05af
plugin_tests/web_client_test.py
plugin_tests/web_client_test.py
from tests import web_client_test setUpModule = web_client_test.setUpModule tearDownModule = web_client_test.tearDownModule class WebClientTestCase(web_client_test.WebClientTestCase): def setUp(self): super(WebClientTestCase, self).setUp() self.model('user').createUser( login='minerva-admin', password='minerva-password!', email='minerva@email.com', firstName='Min', lastName='Erva', admin=True )
Add a custom client side test runner
Add a custom client side test runner
Python
apache-2.0
Kitware/minerva,Kitware/minerva,Kitware/minerva
from tests import web_client_test setUpModule = web_client_test.setUpModule tearDownModule = web_client_test.tearDownModule class WebClientTestCase(web_client_test.WebClientTestCase): def setUp(self): super(WebClientTestCase, self).setUp() self.model('user').createUser( login='minerva-admin', password='minerva-password!', email='minerva@email.com', firstName='Min', lastName='Erva', admin=True )
Add a custom client side test runner
468e82418ceec8eb453054c1b3fbce433a27240f
keyring/__init__.py
keyring/__init__.py
from __future__ import absolute_import from .core import (set_keyring, get_keyring, set_password, get_password, delete_password) from .getpassbackend import get_password as get_pass_get_password try: import pkg_resources __version__ = pkg_resources.get_distribution('keyring').version except Exception: __version__ = 'unknown' __all__ = ( 'set_keyring', 'get_keyring', 'set_password', 'get_password', 'delete_password', 'get_pass_get_password', )
from __future__ import absolute_import from .core import (set_keyring, get_keyring, set_password, get_password, delete_password) from .getpassbackend import get_password as get_pass_get_password __all__ = ( 'set_keyring', 'get_keyring', 'set_password', 'get_password', 'delete_password', 'get_pass_get_password', )
Remove usage of pkg_resources, which has huge import overhead.
Remove usage of pkg_resources, which has huge import overhead.
Python
mit
jaraco/keyring
from __future__ import absolute_import from .core import (set_keyring, get_keyring, set_password, get_password, delete_password) from .getpassbackend import get_password as get_pass_get_password __all__ = ( 'set_keyring', 'get_keyring', 'set_password', 'get_password', 'delete_password', 'get_pass_get_password', )
Remove usage of pkg_resources, which has huge import overhead. from __future__ import absolute_import from .core import (set_keyring, get_keyring, set_password, get_password, delete_password) from .getpassbackend import get_password as get_pass_get_password try: import pkg_resources __version__ = pkg_resources.get_distribution('keyring').version except Exception: __version__ = 'unknown' __all__ = ( 'set_keyring', 'get_keyring', 'set_password', 'get_password', 'delete_password', 'get_pass_get_password', )
546a4681aa54ba183e956d220e98ef67ae6de691
user/decorators.py
user/decorators.py
from django.conf import settings from django.contrib.auth import get_user from django.shortcuts import redirect def custom_login_required(view): # view argument must be a function def new_view(request, *args, **kwargs): user = get_user(request) if user.is_authenticated(): return view(request, *args, **kwargs) else: url = '{}?next={}'.format( settings.LOGIN_URL, request.path) return redirect(url) return new_view
from functools import wraps from django.conf import settings from django.contrib.auth import get_user from django.shortcuts import redirect from django.utils.decorators import \ available_attrs def custom_login_required(view): # view argument must be a function @wraps(view, assigned=available_attrs(view)) def new_view(request, *args, **kwargs): user = get_user(request) if user.is_authenticated(): return view(request, *args, **kwargs) else: url = '{}?next={}'.format( settings.LOGIN_URL, request.path) return redirect(url) return new_view
Use functools.wraps to copy view signature.
Ch20: Use functools.wraps to copy view signature.
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
from functools import wraps from django.conf import settings from django.contrib.auth import get_user from django.shortcuts import redirect from django.utils.decorators import \ available_attrs def custom_login_required(view): # view argument must be a function @wraps(view, assigned=available_attrs(view)) def new_view(request, *args, **kwargs): user = get_user(request) if user.is_authenticated(): return view(request, *args, **kwargs) else: url = '{}?next={}'.format( settings.LOGIN_URL, request.path) return redirect(url) return new_view
Ch20: Use functools.wraps to copy view signature. from django.conf import settings from django.contrib.auth import get_user from django.shortcuts import redirect def custom_login_required(view): # view argument must be a function def new_view(request, *args, **kwargs): user = get_user(request) if user.is_authenticated(): return view(request, *args, **kwargs) else: url = '{}?next={}'.format( settings.LOGIN_URL, request.path) return redirect(url) return new_view
9b255d781e3b0aefa708e1366810d14700384d10
satyr/__init__.py
satyr/__init__.py
from __future__ import absolute_import, division, print_function import logging import pkg_resources as _pkg_resources from .scheduler import QueueScheduler from .executor import OneOffExecutor from .messages import PythonTask, PythonTaskStatus # important to register classes logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s') __version__ = _pkg_resources.get_distribution('satyr').version __all__ = ('QueueScheduler', 'OneOffExecutor', 'PythonTask', 'PythonTaskStatus')
from __future__ import absolute_import, division, print_function import logging import pkg_resources as _pkg_resources from .scheduler import QueueScheduler from .executor import OneOffExecutor from .messages import PythonTask, PythonTaskStatus # important to register classes logging.basicConfig(level=logging.INFO, format='%(relativeCreated)6d %(threadName)s %(message)s') __version__ = _pkg_resources.get_distribution('satyr').version __all__ = ('QueueScheduler', 'OneOffExecutor', 'PythonTask', 'PythonTaskStatus')
Set default logging level to INFO
Set default logging level to INFO
Python
apache-2.0
lensacom/satyr
from __future__ import absolute_import, division, print_function import logging import pkg_resources as _pkg_resources from .scheduler import QueueScheduler from .executor import OneOffExecutor from .messages import PythonTask, PythonTaskStatus # important to register classes logging.basicConfig(level=logging.INFO, format='%(relativeCreated)6d %(threadName)s %(message)s') __version__ = _pkg_resources.get_distribution('satyr').version __all__ = ('QueueScheduler', 'OneOffExecutor', 'PythonTask', 'PythonTaskStatus')
Set default logging level to INFO from __future__ import absolute_import, division, print_function import logging import pkg_resources as _pkg_resources from .scheduler import QueueScheduler from .executor import OneOffExecutor from .messages import PythonTask, PythonTaskStatus # important to register classes logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s') __version__ = _pkg_resources.get_distribution('satyr').version __all__ = ('QueueScheduler', 'OneOffExecutor', 'PythonTask', 'PythonTaskStatus')
98190f0e96b2e2880e81b4801ebd5b04c1e9f1d8
geomdl/__init__.py
geomdl/__init__.py
""" This package contains native Python implementations of several `The NURBS Book <http://www.springer.com/gp/book/9783642973857>`_ algorithms for generating B-spline / NURBS curves and surfaces. It also provides a data structure for storing elements required for evaluation these curves and surfaces. Please follow the `README.md <https://github.com/orbingol/NURBS-Python/blob/master/README.md>`_ file included in the `repository <https://github.com/orbingol/NURBS-Python>`_ for details on the algorithms. Some other advantages of this package are; * Python 2.x and 3.x compatibility * No external dependencies (such as NumPy) * Uses Python properties for the data storage access * A :code:`utilities` module containing several helper functions * :code:`Grid` and :code:`GridWeighted` classes for generating various types of control points grids The NURBS-Python package follows an object-oriented design as much as possible. However, in order to understand the algorithms, you might need to take a look at `The NURBS Book <http://www.springer.com/gp/book/9783642973857>`_ itself. .. moduleauthor:: Onur Rauf Bingol """ __version__ = "3.0.0"
""" This package contains native Python implementations of several `The NURBS Book <http://www.springer.com/gp/book/9783642973857>`_ algorithms for generating B-spline / NURBS curves and surfaces. It also provides a data structure for storing elements required for evaluation these curves and surfaces. Please follow the `README.md <https://github.com/orbingol/NURBS-Python/blob/master/README.md>`_ file included in the `repository <https://github.com/orbingol/NURBS-Python>`_ for details on the algorithms. Some other advantages of this package are; * Python 2.x and 3.x compatibility * No external dependencies (such as NumPy) * Uses Python properties for the data storage access * A :code:`utilities` module containing several helper functions * :code:`Grid` and :code:`GridWeighted` classes for generating various types of control points grids The NURBS-Python package follows an object-oriented design as much as possible. However, in order to understand the algorithms, you might need to take a look at `The NURBS Book <http://www.springer.com/gp/book/9783642973857>`_ itself. .. moduleauthor:: Onur Rauf Bingol """ __version__ = "3.0.0" # Fixes "from geomdl import *" but this is not considered as a good practice # @see: https://docs.python.org/3/tutorial/modules.html#importing-from-a-package __all__ = ["BSpline.Curve", "BSpline.Curve2D", "BSpline.Surface", "NURBS.Curve", "NURBS.Curve2D", "NURBS.Surface", "CPGen.Grid", "CPGen.GridWeighted", "utilities"]
Fix importing * (star) from package
Fix importing * (star) from package
Python
mit
orbingol/NURBS-Python,orbingol/NURBS-Python
""" This package contains native Python implementations of several `The NURBS Book <http://www.springer.com/gp/book/9783642973857>`_ algorithms for generating B-spline / NURBS curves and surfaces. It also provides a data structure for storing elements required for evaluation these curves and surfaces. Please follow the `README.md <https://github.com/orbingol/NURBS-Python/blob/master/README.md>`_ file included in the `repository <https://github.com/orbingol/NURBS-Python>`_ for details on the algorithms. Some other advantages of this package are; * Python 2.x and 3.x compatibility * No external dependencies (such as NumPy) * Uses Python properties for the data storage access * A :code:`utilities` module containing several helper functions * :code:`Grid` and :code:`GridWeighted` classes for generating various types of control points grids The NURBS-Python package follows an object-oriented design as much as possible. However, in order to understand the algorithms, you might need to take a look at `The NURBS Book <http://www.springer.com/gp/book/9783642973857>`_ itself. .. moduleauthor:: Onur Rauf Bingol """ __version__ = "3.0.0" # Fixes "from geomdl import *" but this is not considered as a good practice # @see: https://docs.python.org/3/tutorial/modules.html#importing-from-a-package __all__ = ["BSpline.Curve", "BSpline.Curve2D", "BSpline.Surface", "NURBS.Curve", "NURBS.Curve2D", "NURBS.Surface", "CPGen.Grid", "CPGen.GridWeighted", "utilities"]
Fix importing * (star) from package """ This package contains native Python implementations of several `The NURBS Book <http://www.springer.com/gp/book/9783642973857>`_ algorithms for generating B-spline / NURBS curves and surfaces. It also provides a data structure for storing elements required for evaluation these curves and surfaces. Please follow the `README.md <https://github.com/orbingol/NURBS-Python/blob/master/README.md>`_ file included in the `repository <https://github.com/orbingol/NURBS-Python>`_ for details on the algorithms. Some other advantages of this package are; * Python 2.x and 3.x compatibility * No external dependencies (such as NumPy) * Uses Python properties for the data storage access * A :code:`utilities` module containing several helper functions * :code:`Grid` and :code:`GridWeighted` classes for generating various types of control points grids The NURBS-Python package follows an object-oriented design as much as possible. However, in order to understand the algorithms, you might need to take a look at `The NURBS Book <http://www.springer.com/gp/book/9783642973857>`_ itself. .. moduleauthor:: Onur Rauf Bingol """ __version__ = "3.0.0"
b59d1dd5afd63422cd478d8ee519347bd1c43e3b
project/urls.py
project/urls.py
"""share URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.contrib import admin from django.conf.urls import url, include from django.conf import settings from django.views.generic.base import RedirectView from revproxy.views import ProxyView urlpatterns = [ url(r'^admin/', admin.site.urls), # url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api/', include('api.urls', namespace='api')), url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')), url(r'^accounts/', include('allauth.urls')), url(r'^(?P<path>app/.*)$', ProxyView.as_view(upstream=settings.EMBER_SHARE_URL)), url(r'^$', RedirectView.as_view(url='app/discover')), ]
"""share URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.contrib import admin from django.conf.urls import url, include from django.conf import settings from django.views.generic.base import RedirectView from revproxy.views import ProxyView urlpatterns = [ url(r'^admin/', admin.site.urls), # url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api/', include('api.urls', namespace='api')), url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')), url(r'^accounts/', include('allauth.urls')), url(r'^(?P<path>share/.*)$', ProxyView.as_view(upstream=settings.EMBER_SHARE_URL)), url(r'^$', RedirectView.as_view(url='share/')), ]
Change ember app prefix to 'share/'
Change ember app prefix to 'share/'
Python
apache-2.0
CenterForOpenScience/SHARE,aaxelb/SHARE,zamattiac/SHARE,aaxelb/SHARE,laurenbarker/SHARE,laurenbarker/SHARE,CenterForOpenScience/SHARE,zamattiac/SHARE,laurenbarker/SHARE,CenterForOpenScience/SHARE,aaxelb/SHARE,zamattiac/SHARE
"""share URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.contrib import admin from django.conf.urls import url, include from django.conf import settings from django.views.generic.base import RedirectView from revproxy.views import ProxyView urlpatterns = [ url(r'^admin/', admin.site.urls), # url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api/', include('api.urls', namespace='api')), url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')), url(r'^accounts/', include('allauth.urls')), url(r'^(?P<path>share/.*)$', ProxyView.as_view(upstream=settings.EMBER_SHARE_URL)), url(r'^$', RedirectView.as_view(url='share/')), ]
Change ember app prefix to 'share/' """share URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.contrib import admin from django.conf.urls import url, include from django.conf import settings from django.views.generic.base import RedirectView from revproxy.views import ProxyView urlpatterns = [ url(r'^admin/', admin.site.urls), # url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api/', include('api.urls', namespace='api')), url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')), url(r'^accounts/', include('allauth.urls')), url(r'^(?P<path>app/.*)$', ProxyView.as_view(upstream=settings.EMBER_SHARE_URL)), url(r'^$', RedirectView.as_view(url='app/discover')), ]
484636805602348c883d8dc775082169f97cce76
crawler/management/commands/similar_apps_category_counter.py
crawler/management/commands/similar_apps_category_counter.py
import logging.config from operator import or_ from django.core.management.base import BaseCommand from crawler.models import * logger = logging.getLogger('crawler.command') class Command(BaseCommand): help = 'Generate comparison between google similar app and ours' def handle(self, *args, **options): result_dict = dict() similar_apps = self.get_my_similar() for similar_app in similar_apps: app = App.objects.filter(package_name=similar_app) category = app.category_name() if category not in result_dict: count = 0 else: count = result_dict[category] result_dict[category] = count + 1 admin_file = open('similar_apps_category.csv', 'w') admin_file.write('category;count') for key in result_dict: admin_file.write('{};{}\n'.format(key, result_dict[key])) admin_file.close() self.stdout.write( self.style.SUCCESS('Finished category counter') ) @staticmethod def get_my_similar(): apps = SimilarApp.objects.order_by().values_list('source_package', flat=True).distinct() similar_apps = SimilarApp.objects.order_by().values_list('similar_package', flat=True).distinct() app_set = set(apps) similar_set = set(similar_apps) merged_set = reduce(or_, [app_set, similar_set]) return merged_set
Create similar category counter command
Create similar category counter command
Python
apache-2.0
bkosawa/admin-recommendation
import logging.config from operator import or_ from django.core.management.base import BaseCommand from crawler.models import * logger = logging.getLogger('crawler.command') class Command(BaseCommand): help = 'Generate comparison between google similar app and ours' def handle(self, *args, **options): result_dict = dict() similar_apps = self.get_my_similar() for similar_app in similar_apps: app = App.objects.filter(package_name=similar_app) category = app.category_name() if category not in result_dict: count = 0 else: count = result_dict[category] result_dict[category] = count + 1 admin_file = open('similar_apps_category.csv', 'w') admin_file.write('category;count') for key in result_dict: admin_file.write('{};{}\n'.format(key, result_dict[key])) admin_file.close() self.stdout.write( self.style.SUCCESS('Finished category counter') ) @staticmethod def get_my_similar(): apps = SimilarApp.objects.order_by().values_list('source_package', flat=True).distinct() similar_apps = SimilarApp.objects.order_by().values_list('similar_package', flat=True).distinct() app_set = set(apps) similar_set = set(similar_apps) merged_set = reduce(or_, [app_set, similar_set]) return merged_set
Create similar category counter command
deb5a6c45d6f52daef7ca5752f574d7c14abbc47
admin/base/urls.py
admin/base/urls.py
from django.conf.urls import include, url from django.contrib import admin from settings import ADMIN_BASE from . import views base_pattern = '^{}'.format(ADMIN_BASE) urlpatterns = [ ### ADMIN ### url( base_pattern, include([ url(r'^$', views.home, name='home'), url(r'^admin/', include(admin.site.urls)), url(r'^spam/', include('admin.spam.urls', namespace='spam')), url(r'^account/', include('admin.common_auth.urls', namespace='auth')), url(r'^password/', include('password_reset.urls')), url(r'^nodes/', include('admin.nodes.urls', namespace='nodes')), url(r'^users/', include('admin.users.urls', namespace='users')), url(r'^meetings/', include('admin.meetings.urls', namespace='meetings')), url(r'^project/', include('admin.pre_reg.urls', namespace='pre_reg')), url(r'^metrics/', include('admin.metrics.urls', namespace='metrics')), url(r'^desk/', include('admin.desk.urls', namespace='desk')), ]), ), ] admin.site.site_header = 'OSF-Admin administration'
from django.conf.urls import include, url from django.contrib import admin from settings import ADMIN_BASE from . import views base_pattern = '^{}'.format(ADMIN_BASE) urlpatterns = [ ### ADMIN ### url( base_pattern, include([ url(r'^$', views.home, name='home'), url(r'^admin/', include(admin.site.urls)), url(r'^spam/', include('admin.spam.urls', namespace='spam')), url(r'^account/', include('admin.common_auth.urls', namespace='auth')), url(r'^password/', include('password_reset.urls')), url(r'^nodes/', include('admin.nodes.urls', namespace='nodes')), url(r'^preprints/', include('admin.preprints.urls', namespace='preprints')), url(r'^users/', include('admin.users.urls', namespace='users')), url(r'^meetings/', include('admin.meetings.urls', namespace='meetings')), url(r'^project/', include('admin.pre_reg.urls', namespace='pre_reg')), url(r'^metrics/', include('admin.metrics.urls', namespace='metrics')), url(r'^desk/', include('admin.desk.urls', namespace='desk')), ]), ), ] admin.site.site_header = 'OSF-Admin administration'
Add preprints to the sidebar
Add preprints to the sidebar [#OSF-7198]
Python
apache-2.0
mattclark/osf.io,caseyrollins/osf.io,aaxelb/osf.io,icereval/osf.io,felliott/osf.io,cwisecarver/osf.io,adlius/osf.io,crcresearch/osf.io,caneruguz/osf.io,cslzchen/osf.io,pattisdr/osf.io,leb2dg/osf.io,mattclark/osf.io,mfraezz/osf.io,caseyrollins/osf.io,baylee-d/osf.io,chrisseto/osf.io,saradbowman/osf.io,brianjgeiger/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,Nesiehr/osf.io,aaxelb/osf.io,cslzchen/osf.io,adlius/osf.io,laurenrevere/osf.io,TomBaxter/osf.io,cwisecarver/osf.io,felliott/osf.io,mfraezz/osf.io,saradbowman/osf.io,hmoco/osf.io,cwisecarver/osf.io,Johnetordoff/osf.io,binoculars/osf.io,felliott/osf.io,chennan47/osf.io,TomBaxter/osf.io,hmoco/osf.io,leb2dg/osf.io,felliott/osf.io,baylee-d/osf.io,hmoco/osf.io,cslzchen/osf.io,cslzchen/osf.io,erinspace/osf.io,CenterForOpenScience/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,erinspace/osf.io,CenterForOpenScience/osf.io,caseyrollins/osf.io,chrisseto/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,caneruguz/osf.io,caneruguz/osf.io,leb2dg/osf.io,erinspace/osf.io,crcresearch/osf.io,Johnetordoff/osf.io,icereval/osf.io,chennan47/osf.io,HalcyonChimera/osf.io,crcresearch/osf.io,sloria/osf.io,icereval/osf.io,Nesiehr/osf.io,sloria/osf.io,adlius/osf.io,CenterForOpenScience/osf.io,TomBaxter/osf.io,binoculars/osf.io,binoculars/osf.io,baylee-d/osf.io,adlius/osf.io,laurenrevere/osf.io,Johnetordoff/osf.io,laurenrevere/osf.io,pattisdr/osf.io,chrisseto/osf.io,Nesiehr/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,chennan47/osf.io,brianjgeiger/osf.io,leb2dg/osf.io,mattclark/osf.io,HalcyonChimera/osf.io,aaxelb/osf.io,cwisecarver/osf.io,hmoco/osf.io,mfraezz/osf.io,pattisdr/osf.io,sloria/osf.io,Nesiehr/osf.io,mfraezz/osf.io,brianjgeiger/osf.io
from django.conf.urls import include, url from django.contrib import admin from settings import ADMIN_BASE from . import views base_pattern = '^{}'.format(ADMIN_BASE) urlpatterns = [ ### ADMIN ### url( base_pattern, include([ url(r'^$', views.home, name='home'), url(r'^admin/', include(admin.site.urls)), url(r'^spam/', include('admin.spam.urls', namespace='spam')), url(r'^account/', include('admin.common_auth.urls', namespace='auth')), url(r'^password/', include('password_reset.urls')), url(r'^nodes/', include('admin.nodes.urls', namespace='nodes')), url(r'^preprints/', include('admin.preprints.urls', namespace='preprints')), url(r'^users/', include('admin.users.urls', namespace='users')), url(r'^meetings/', include('admin.meetings.urls', namespace='meetings')), url(r'^project/', include('admin.pre_reg.urls', namespace='pre_reg')), url(r'^metrics/', include('admin.metrics.urls', namespace='metrics')), url(r'^desk/', include('admin.desk.urls', namespace='desk')), ]), ), ] admin.site.site_header = 'OSF-Admin administration'
Add preprints to the sidebar [#OSF-7198] from django.conf.urls import include, url from django.contrib import admin from settings import ADMIN_BASE from . import views base_pattern = '^{}'.format(ADMIN_BASE) urlpatterns = [ ### ADMIN ### url( base_pattern, include([ url(r'^$', views.home, name='home'), url(r'^admin/', include(admin.site.urls)), url(r'^spam/', include('admin.spam.urls', namespace='spam')), url(r'^account/', include('admin.common_auth.urls', namespace='auth')), url(r'^password/', include('password_reset.urls')), url(r'^nodes/', include('admin.nodes.urls', namespace='nodes')), url(r'^users/', include('admin.users.urls', namespace='users')), url(r'^meetings/', include('admin.meetings.urls', namespace='meetings')), url(r'^project/', include('admin.pre_reg.urls', namespace='pre_reg')), url(r'^metrics/', include('admin.metrics.urls', namespace='metrics')), url(r'^desk/', include('admin.desk.urls', namespace='desk')), ]), ), ] admin.site.site_header = 'OSF-Admin administration'
d3caf69dfe98aa2fd0f9046c01035cdd7e4e359e
opps/articles/tests/models.py
opps/articles/tests/models.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.test import TestCase from opps.articles.models import Article, Post class ArticleModelTest(TestCase): fixtures = ['tests/initial_data.json'] def setUp(self): self.article = Article.objects.get(id=1) def test_child_class(self): self.assertTrue(self.article.child_class) self.assertEqual(self.article.child_class, 'Post') def test_get_absolute_url(self): self.assertEqual(self.article.get_absolute_url(), u'/channel-01/test-post-application') self.assertEqual(self.article.get_absolute_url(), "/{0}/{1}".format(self.article.channel.long_slug, self.article.slug)) class PostModelTest(TestCase): fixtures = ['tests/initial_data.json'] def setUp(self): self.post = Post.objects.get(id=1) def test_basic_post_exist(self): post = Post.objects.all() self.assertTrue(post) self.assertTrue(post[0], self.post) self.assertEqual(len(post), 1) self.assertEqual(post[0].slug, u'test-post-application') self.assertEqual(post[0].title, u'test post application') self.assertTrue(post[0].short_url)
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.test import TestCase from opps.articles.models import Article, Post class ArticleModelTest(TestCase): fixtures = ['tests/initial_data.json'] def setUp(self): self.article = Article.objects.get(id=1) def test_child_class(self): self.assertTrue(self.article.child_class) self.assertEqual(self.article.child_class, 'Post') def test_get_absolute_url(self): self.assertEqual(self.article.get_absolute_url(), u'/channel-01/test-post-application') self.assertEqual(self.article.get_absolute_url(), "/{0}/{1}".format(self.article.channel.long_slug, self.article.slug)) def test_recommendation(self): self.assertEqual([], self.article.recommendation()) class PostModelTest(TestCase): fixtures = ['tests/initial_data.json'] def setUp(self): self.post = Post.objects.get(id=1) def test_basic_post_exist(self): post = Post.objects.all() self.assertTrue(post) self.assertTrue(post[0], self.post) self.assertEqual(len(post), 1) self.assertEqual(post[0].slug, u'test-post-application') self.assertEqual(post[0].title, u'test post application') self.assertTrue(post[0].short_url)
Test recommendation via article class
Test recommendation via article class
Python
mit
williamroot/opps,jeanmask/opps,opps/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,YACOWS/opps,opps/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,opps/opps
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.test import TestCase from opps.articles.models import Article, Post class ArticleModelTest(TestCase): fixtures = ['tests/initial_data.json'] def setUp(self): self.article = Article.objects.get(id=1) def test_child_class(self): self.assertTrue(self.article.child_class) self.assertEqual(self.article.child_class, 'Post') def test_get_absolute_url(self): self.assertEqual(self.article.get_absolute_url(), u'/channel-01/test-post-application') self.assertEqual(self.article.get_absolute_url(), "/{0}/{1}".format(self.article.channel.long_slug, self.article.slug)) def test_recommendation(self): self.assertEqual([], self.article.recommendation()) class PostModelTest(TestCase): fixtures = ['tests/initial_data.json'] def setUp(self): self.post = Post.objects.get(id=1) def test_basic_post_exist(self): post = Post.objects.all() self.assertTrue(post) self.assertTrue(post[0], self.post) self.assertEqual(len(post), 1) self.assertEqual(post[0].slug, u'test-post-application') self.assertEqual(post[0].title, u'test post application') self.assertTrue(post[0].short_url)
Test recommendation via article class #!/usr/bin/env python # -*- coding: utf-8 -*- from django.test import TestCase from opps.articles.models import Article, Post class ArticleModelTest(TestCase): fixtures = ['tests/initial_data.json'] def setUp(self): self.article = Article.objects.get(id=1) def test_child_class(self): self.assertTrue(self.article.child_class) self.assertEqual(self.article.child_class, 'Post') def test_get_absolute_url(self): self.assertEqual(self.article.get_absolute_url(), u'/channel-01/test-post-application') self.assertEqual(self.article.get_absolute_url(), "/{0}/{1}".format(self.article.channel.long_slug, self.article.slug)) class PostModelTest(TestCase): fixtures = ['tests/initial_data.json'] def setUp(self): self.post = Post.objects.get(id=1) def test_basic_post_exist(self): post = Post.objects.all() self.assertTrue(post) self.assertTrue(post[0], self.post) self.assertEqual(len(post), 1) self.assertEqual(post[0].slug, u'test-post-application') self.assertEqual(post[0].title, u'test post application') self.assertTrue(post[0].short_url)
c43a677e19ba1d2603dd4b7907fe053561c4fa06
neutron/objects/__init__.py
neutron/objects/__init__.py
# 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 sys def register_objects(): # local import to avoid circular import failure from neutron.common import utils utils.import_modules_recursively(sys.modules[__name__].__file__)
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os import sys def register_objects(): # local import to avoid circular import failure from neutron.common import utils dirn = os.path.dirname(sys.modules[__name__].__file__) utils.import_modules_recursively(dirn)
Use dirname in object recursive import
Use dirname in object recursive import __file__ just returns the init file which there was nothing under. TrivialFix Change-Id: I39da8a50c0b9197b7a5cb3d5ca4fd95f8d739eaa
Python
apache-2.0
openstack/neutron,huntxu/neutron,openstack/neutron,eayunstack/neutron,eayunstack/neutron,huntxu/neutron,mahak/neutron,openstack/neutron,mahak/neutron,mahak/neutron,noironetworks/neutron,noironetworks/neutron
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os import sys def register_objects(): # local import to avoid circular import failure from neutron.common import utils dirn = os.path.dirname(sys.modules[__name__].__file__) utils.import_modules_recursively(dirn)
Use dirname in object recursive import __file__ just returns the init file which there was nothing under. TrivialFix Change-Id: I39da8a50c0b9197b7a5cb3d5ca4fd95f8d739eaa # 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 sys def register_objects(): # local import to avoid circular import failure from neutron.common import utils utils.import_modules_recursively(sys.modules[__name__].__file__)
c954c153525265b2b4ff0d89f0cf7f89c08a136c
settings/test_settings.py
settings/test_settings.py
# -*- coding: utf-8 -*-# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import os from .common import * # noqa DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(ROOT_DIR, 'test.sqlite3'), } } TEMPLATE_CONTEXT_PROCESSORS += ( "django.core.context_processors.debug", ) EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' INSTALLED_APPS += ('django_extensions',) DEVICE_VERIFICATION_CODE = 11111 # DEBUG TOOLBAR INSTALLED_APPS += ('debug_toolbar',)
# -*- coding: utf-8 -*-# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import os from .common import * # noqa DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(ROOT_DIR, 'test.sqlite3'), } } TEMPLATE_CONTEXT_PROCESSORS += ( "django.core.context_processors.debug", ) EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' INSTALLED_APPS += ('django_extensions',) DEVICE_VERIFICATION_CODE = 11111
Remove debug toolbar in test settings
Remove debug toolbar in test settings
Python
mit
praba230890/junction,praba230890/junction,farhaanbukhsh/junction,farhaanbukhsh/junction,pythonindia/junction,ChillarAnand/junction,pythonindia/junction,praba230890/junction,ChillarAnand/junction,pythonindia/junction,nava45/junction,nava45/junction,ChillarAnand/junction,nava45/junction,ChillarAnand/junction,praba230890/junction,farhaanbukhsh/junction,pythonindia/junction,nava45/junction,farhaanbukhsh/junction
# -*- coding: utf-8 -*-# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import os from .common import * # noqa DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(ROOT_DIR, 'test.sqlite3'), } } TEMPLATE_CONTEXT_PROCESSORS += ( "django.core.context_processors.debug", ) EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' INSTALLED_APPS += ('django_extensions',) DEVICE_VERIFICATION_CODE = 11111
Remove debug toolbar in test settings # -*- coding: utf-8 -*-# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import os from .common import * # noqa DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(ROOT_DIR, 'test.sqlite3'), } } TEMPLATE_CONTEXT_PROCESSORS += ( "django.core.context_processors.debug", ) EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' INSTALLED_APPS += ('django_extensions',) DEVICE_VERIFICATION_CODE = 11111 # DEBUG TOOLBAR INSTALLED_APPS += ('debug_toolbar',)
a77ead1975050938c8557979f54683829747bf0f
addons/sale_stock/migrations/8.0.1.0/pre-migration.py
addons/sale_stock/migrations/8.0.1.0/pre-migration.py
# -*- coding: utf-8 -*- ############################################################################## # # Odoo, a suite of business apps # This module Copyright (C) 2014 Therp BV (<http://therp.nl>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.openupgrade import openupgrade column_renames = { 'sale.order.line': [('procurement_id', None)]} @openupgrade.migrate() def migrate(cr, version): openupgrade.rename_columns(cr, column_renames)
# -*- coding: utf-8 -*- ############################################################################## # # Odoo, a suite of business apps # This module Copyright (C) 2014 Therp BV (<http://therp.nl>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.openupgrade import openupgrade column_renames = { 'sale_order_line': [('procurement_id', None)]} @openupgrade.migrate() def migrate(cr, version): openupgrade.rename_columns(cr, column_renames)
Fix table name error in sale_stock column renames
Fix table name error in sale_stock column renames
Python
agpl-3.0
blaggacao/OpenUpgrade,sebalix/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,hifly/OpenUpgrade,kirca/OpenUpgrade,sebalix/OpenUpgrade,blaggacao/OpenUpgrade,kirca/OpenUpgrade,bwrsandman/OpenUpgrade,hifly/OpenUpgrade,Endika/OpenUpgrade,kirca/OpenUpgrade,OpenUpgrade/OpenUpgrade,pedrobaeza/OpenUpgrade,grap/OpenUpgrade,damdam-s/OpenUpgrade,bwrsandman/OpenUpgrade,pedrobaeza/OpenUpgrade,kirca/OpenUpgrade,Endika/OpenUpgrade,sebalix/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,bwrsandman/OpenUpgrade,pedrobaeza/OpenUpgrade,OpenUpgrade/OpenUpgrade,csrocha/OpenUpgrade,kirca/OpenUpgrade,damdam-s/OpenUpgrade,pedrobaeza/OpenUpgrade,sebalix/OpenUpgrade,blaggacao/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,sebalix/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,mvaled/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,csrocha/OpenUpgrade,kirca/OpenUpgrade,OpenUpgrade/OpenUpgrade,hifly/OpenUpgrade,grap/OpenUpgrade,mvaled/OpenUpgrade,OpenUpgrade/OpenUpgrade,csrocha/OpenUpgrade,hifly/OpenUpgrade,grap/OpenUpgrade,kirca/OpenUpgrade,sebalix/OpenUpgrade,sebalix/OpenUpgrade,mvaled/OpenUpgrade,bwrsandman/OpenUpgrade,0k/OpenUpgrade,Endika/OpenUpgrade,csrocha/OpenUpgrade,damdam-s/OpenUpgrade,Endika/OpenUpgrade,hifly/OpenUpgrade,0k/OpenUpgrade,hifly/OpenUpgrade,blaggacao/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,hifly/OpenUpgrade,0k/OpenUpgrade,grap/OpenUpgrade,grap/OpenUpgrade,bwrsandman/OpenUpgrade,OpenUpgrade/OpenUpgrade,0k/OpenUpgrade,damdam-s/OpenUpgrade,csrocha/OpenUpgrade,damdam-s/OpenUpgrade,blaggacao/OpenUpgrade,grap/OpenUpgrade,csrocha/OpenUpgrade,pedrobaeza/OpenUpgrade,Endika/OpenUpgrade,grap/OpenUpgrade,Endika/OpenUpgrade,blaggacao/OpenUpgrade,bwrsandman/OpenUpgrade,bwrsandman/OpenUpgrade,Endika/OpenUpgrade,mvaled/OpenUpgrade,0k/OpenUpgrade,pedrobaeza/OpenUpgrade,mvaled/OpenUpgrade,OpenUpgrade/OpenUpgrade,mvaled/OpenUpgrade,0k/OpenUpgrade,damdam-s/OpenUpgrade,blaggacao/OpenUpgrade,pedrobaeza/OpenUpgrade,damdam-s/OpenUpgrade,OpenUpgrade/OpenUpgrade,csrocha/OpenUpgrade,mvaled/OpenUpgrade
# -*- coding: utf-8 -*- ############################################################################## # # Odoo, a suite of business apps # This module Copyright (C) 2014 Therp BV (<http://therp.nl>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.openupgrade import openupgrade column_renames = { 'sale_order_line': [('procurement_id', None)]} @openupgrade.migrate() def migrate(cr, version): openupgrade.rename_columns(cr, column_renames)
Fix table name error in sale_stock column renames # -*- coding: utf-8 -*- ############################################################################## # # Odoo, a suite of business apps # This module Copyright (C) 2014 Therp BV (<http://therp.nl>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.openupgrade import openupgrade column_renames = { 'sale.order.line': [('procurement_id', None)]} @openupgrade.migrate() def migrate(cr, version): openupgrade.rename_columns(cr, column_renames)
7dbc1359ea4fb1b725fd53869a218856e4dec701
lswapi/httpie/__init__.py
lswapi/httpie/__init__.py
""" LswApi auth plugin for HTTPie. """ from json import loads, dumps from time import time from os import path from lswapi import __auth_token_url__, __token_store__, fetch_access_token from requests import post from httpie.plugins import AuthPlugin class LswApiAuth(object): def __init__(self, client_id, client_secret): self.client_id = client_id self.client_secret = client_secret def __call__(self, r): if path.exists(__token_store__): with open(__token_store__, 'r') as file: token = loads(file.read()) if 'expires_at' in token and token['expires_at'] > time(): r.headers['Authorization'] = '{token_type} {access_token}'.format(**token) return r token = fetch_access_token(self.client_id, self.client_secret, __auth_token_url__) with open(__token_store__, 'w') as file: file.write(dumps(token)) r.headers['Authorization'] = '{token_type} {access_token}'.format(**token) return r class ApiAuthPlugin(AuthPlugin): name = 'LswApi Oauth' auth_type = 'lswapi' description = 'LeaseWeb Api Oauth Authentication' def get_auth(self, username, password): return LswApiAuth(username, password)
""" LswApi auth plugin for HTTPie. """ from json import loads, dumps from time import time from os import path from lswapi import __auth_token_url__, __token_store__, fetch_access_token from requests import post from httpie.plugins import AuthPlugin class LswApiAuth(object): def __init__(self, client_id, client_secret): self.client_id = client_id self.client_secret = client_secret def __call__(self, r): if path.exists(__token_store__): with open(__token_store__, 'r') as file: token = loads(file.read()) if 'expires_at' in token and token['expires_at'] > time(): r.headers['Authorization'] = '{token_type} {access_token}'.format(**token) return r token = fetch_access_token(__auth_token_url__, self.client_id, self.client_secret) with open(__token_store__, 'w') as file: file.write(dumps(token)) r.headers['Authorization'] = '{token_type} {access_token}'.format(**token) return r class ApiAuthPlugin(AuthPlugin): name = 'LswApi Oauth' auth_type = 'lswapi' description = 'LeaseWeb Api Oauth Authentication' def get_auth(self, username, password): return LswApiAuth(username, password)
Fix for function signature change in 0.4.0 in fetch_access_token
Fix for function signature change in 0.4.0 in fetch_access_token
Python
apache-2.0
nrocco/lswapi
""" LswApi auth plugin for HTTPie. """ from json import loads, dumps from time import time from os import path from lswapi import __auth_token_url__, __token_store__, fetch_access_token from requests import post from httpie.plugins import AuthPlugin class LswApiAuth(object): def __init__(self, client_id, client_secret): self.client_id = client_id self.client_secret = client_secret def __call__(self, r): if path.exists(__token_store__): with open(__token_store__, 'r') as file: token = loads(file.read()) if 'expires_at' in token and token['expires_at'] > time(): r.headers['Authorization'] = '{token_type} {access_token}'.format(**token) return r token = fetch_access_token(__auth_token_url__, self.client_id, self.client_secret) with open(__token_store__, 'w') as file: file.write(dumps(token)) r.headers['Authorization'] = '{token_type} {access_token}'.format(**token) return r class ApiAuthPlugin(AuthPlugin): name = 'LswApi Oauth' auth_type = 'lswapi' description = 'LeaseWeb Api Oauth Authentication' def get_auth(self, username, password): return LswApiAuth(username, password)
Fix for function signature change in 0.4.0 in fetch_access_token """ LswApi auth plugin for HTTPie. """ from json import loads, dumps from time import time from os import path from lswapi import __auth_token_url__, __token_store__, fetch_access_token from requests import post from httpie.plugins import AuthPlugin class LswApiAuth(object): def __init__(self, client_id, client_secret): self.client_id = client_id self.client_secret = client_secret def __call__(self, r): if path.exists(__token_store__): with open(__token_store__, 'r') as file: token = loads(file.read()) if 'expires_at' in token and token['expires_at'] > time(): r.headers['Authorization'] = '{token_type} {access_token}'.format(**token) return r token = fetch_access_token(self.client_id, self.client_secret, __auth_token_url__) with open(__token_store__, 'w') as file: file.write(dumps(token)) r.headers['Authorization'] = '{token_type} {access_token}'.format(**token) return r class ApiAuthPlugin(AuthPlugin): name = 'LswApi Oauth' auth_type = 'lswapi' description = 'LeaseWeb Api Oauth Authentication' def get_auth(self, username, password): return LswApiAuth(username, password)
5beb443d4c9cf834be03ff33a2fb01605f8feb80
pyof/v0x01/symmetric/hello.py
pyof/v0x01/symmetric/hello.py
"""Defines Hello message.""" # System imports # Third-party imports from pyof.foundation.base import GenericMessage from pyof.v0x01.common.header import Header, Type __all__ = ('Hello',) # Classes class Hello(GenericMessage): """OpenFlow Hello Message. This message does not contain a body beyond the OpenFlow Header. """ header = Header(message_type=Type.OFPT_HELLO, length=8)
"""Defines Hello message.""" # System imports # Third-party imports from pyof.foundation.base import GenericMessage from pyof.foundation.basic_types import BinaryData from pyof.v0x01.common.header import Header, Type __all__ = ('Hello',) # Classes class Hello(GenericMessage): """OpenFlow Hello Message. This message does not contain a body beyond the OpenFlow Header. """ header = Header(message_type=Type.OFPT_HELLO, length=8) elements = BinaryData()
Add optional elements in v0x01 Hello
Add optional elements in v0x01 Hello For spec compliance. Ignore the elements as they're not used. Fix #379
Python
mit
kytos/python-openflow
"""Defines Hello message.""" # System imports # Third-party imports from pyof.foundation.base import GenericMessage from pyof.foundation.basic_types import BinaryData from pyof.v0x01.common.header import Header, Type __all__ = ('Hello',) # Classes class Hello(GenericMessage): """OpenFlow Hello Message. This message does not contain a body beyond the OpenFlow Header. """ header = Header(message_type=Type.OFPT_HELLO, length=8) elements = BinaryData()
Add optional elements in v0x01 Hello For spec compliance. Ignore the elements as they're not used. Fix #379 """Defines Hello message.""" # System imports # Third-party imports from pyof.foundation.base import GenericMessage from pyof.v0x01.common.header import Header, Type __all__ = ('Hello',) # Classes class Hello(GenericMessage): """OpenFlow Hello Message. This message does not contain a body beyond the OpenFlow Header. """ header = Header(message_type=Type.OFPT_HELLO, length=8)
901bd73c61fbc6d9d8971ec1ce12e64100e633cb
base/settings/testing.py
base/settings/testing.py
# -*- coding: utf-8 -*- import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, }
# -*- coding: utf-8 -*- import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } # django-celery. # ------------------------------------------------------------------ Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery',] BROKER_URL = 'django://' # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, }
Fix the Celery configuration under test settings.
Fix the Celery configuration under test settings.
Python
apache-2.0
hello-base/web,hello-base/web,hello-base/web,hello-base/web
# -*- coding: utf-8 -*- import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } # django-celery. # ------------------------------------------------------------------ Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery',] BROKER_URL = 'django://' # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, }
Fix the Celery configuration under test settings. # -*- coding: utf-8 -*- import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, }
c73d24259a6aa198d749fba097999ba2c18bd6da
website/addons/figshare/settings/defaults.py
website/addons/figshare/settings/defaults.py
API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000
CLIENT_ID = None CLIENT_SECRET = None API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000
Add figshare CLIENT_ID and CLIENT_SECRET back into default settings.
Add figshare CLIENT_ID and CLIENT_SECRET back into default settings. [skip ci]
Python
apache-2.0
mattclark/osf.io,brandonPurvis/osf.io,TomBaxter/osf.io,jnayak1/osf.io,SSJohns/osf.io,revanthkolli/osf.io,kch8qx/osf.io,amyshi188/osf.io,GaryKriebel/osf.io,fabianvf/osf.io,revanthkolli/osf.io,jinluyuan/osf.io,cldershem/osf.io,KAsante95/osf.io,lamdnhan/osf.io,caseyrygt/osf.io,leb2dg/osf.io,HarryRybacki/osf.io,caneruguz/osf.io,haoyuchen1992/osf.io,rdhyee/osf.io,zachjanicki/osf.io,emetsger/osf.io,ckc6cz/osf.io,kwierman/osf.io,GageGaskins/osf.io,KAsante95/osf.io,DanielSBrown/osf.io,adlius/osf.io,hmoco/osf.io,erinspace/osf.io,bdyetton/prettychart,ticklemepierce/osf.io,baylee-d/osf.io,mluke93/osf.io,ckc6cz/osf.io,cslzchen/osf.io,TomHeatwole/osf.io,CenterForOpenScience/osf.io,alexschiller/osf.io,GageGaskins/osf.io,HalcyonChimera/osf.io,RomanZWang/osf.io,crcresearch/osf.io,haoyuchen1992/osf.io,lamdnhan/osf.io,SSJohns/osf.io,reinaH/osf.io,himanshuo/osf.io,petermalcolm/osf.io,ZobairAlijan/osf.io,dplorimer/osf,Ghalko/osf.io,mluke93/osf.io,GaryKriebel/osf.io,asanfilippo7/osf.io,pattisdr/osf.io,leb2dg/osf.io,acshi/osf.io,chrisseto/osf.io,alexschiller/osf.io,mluo613/osf.io,mluo613/osf.io,arpitar/osf.io,amyshi188/osf.io,caseyrygt/osf.io,lamdnhan/osf.io,Ghalko/osf.io,barbour-em/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,Nesiehr/osf.io,rdhyee/osf.io,petermalcolm/osf.io,cosenal/osf.io,crcresearch/osf.io,felliott/osf.io,zkraime/osf.io,ticklemepierce/osf.io,barbour-em/osf.io,zkraime/osf.io,mluke93/osf.io,emetsger/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,Nesiehr/osf.io,reinaH/osf.io,aaxelb/osf.io,danielneis/osf.io,mluke93/osf.io,bdyetton/prettychart,emetsger/osf.io,fabianvf/osf.io,amyshi188/osf.io,dplorimer/osf,acshi/osf.io,KAsante95/osf.io,bdyetton/prettychart,brandonPurvis/osf.io,danielneis/osf.io,asanfilippo7/osf.io,jolene-esposito/osf.io,felliott/osf.io,baylee-d/osf.io,billyhunt/osf.io,Nesiehr/osf.io,mluo613/osf.io,sloria/osf.io,RomanZWang/osf.io,icereval/osf.io,doublebits/osf.io,SSJohns/osf.io,kwierman/osf.io,cslzchen/osf.io,TomHeatwole/osf.io,chrisseto/osf.io,chrisseto/osf.io,himanshuo/osf.io,arpitar/osf.io,jnayak1/osf.io,barbour-em/osf.io,monikagrabowska/osf.io,jinluyuan/osf.io,Johnetordoff/osf.io,jeffreyliu3230/osf.io,brianjgeiger/osf.io,zachjanicki/osf.io,MerlinZhang/osf.io,ZobairAlijan/osf.io,monikagrabowska/osf.io,alexschiller/osf.io,petermalcolm/osf.io,acshi/osf.io,dplorimer/osf,erinspace/osf.io,jolene-esposito/osf.io,billyhunt/osf.io,bdyetton/prettychart,zkraime/osf.io,saradbowman/osf.io,abought/osf.io,abought/osf.io,zamattiac/osf.io,GageGaskins/osf.io,kushG/osf.io,sbt9uc/osf.io,reinaH/osf.io,ckc6cz/osf.io,adlius/osf.io,icereval/osf.io,lyndsysimon/osf.io,caseyrygt/osf.io,cosenal/osf.io,billyhunt/osf.io,sloria/osf.io,brianjgeiger/osf.io,CenterForOpenScience/osf.io,jeffreyliu3230/osf.io,kch8qx/osf.io,pattisdr/osf.io,wearpants/osf.io,brandonPurvis/osf.io,CenterForOpenScience/osf.io,HalcyonChimera/osf.io,SSJohns/osf.io,caneruguz/osf.io,wearpants/osf.io,MerlinZhang/osf.io,himanshuo/osf.io,laurenrevere/osf.io,monikagrabowska/osf.io,doublebits/osf.io,doublebits/osf.io,samanehsan/osf.io,mluo613/osf.io,jmcarp/osf.io,zamattiac/osf.io,hmoco/osf.io,samchrisinger/osf.io,chennan47/osf.io,sbt9uc/osf.io,brianjgeiger/osf.io,monikagrabowska/osf.io,CenterForOpenScience/osf.io,erinspace/osf.io,lamdnhan/osf.io,jolene-esposito/osf.io,hmoco/osf.io,revanthkolli/osf.io,himanshuo/osf.io,ticklemepierce/osf.io,HalcyonChimera/osf.io,TomHeatwole/osf.io,zachjanicki/osf.io,brandonPurvis/osf.io,lyndsysimon/osf.io,arpitar/osf.io,samanehsan/osf.io,abought/osf.io,jinluyuan/osf.io,binoculars/osf.io,reinaH/osf.io,DanielSBrown/osf.io,jnayak1/osf.io,jmcarp/osf.io,cldershem/osf.io,ZobairAlijan/osf.io,kushG/osf.io,caneruguz/osf.io,laurenrevere/osf.io,cldershem/osf.io,mattclark/osf.io,HarryRybacki/osf.io,GageGaskins/osf.io,HalcyonChimera/osf.io,samanehsan/osf.io,rdhyee/osf.io,cldershem/osf.io,mfraezz/osf.io,aaxelb/osf.io,mfraezz/osf.io,saradbowman/osf.io,emetsger/osf.io,acshi/osf.io,caseyrygt/osf.io,kushG/osf.io,kch8qx/osf.io,asanfilippo7/osf.io,HarryRybacki/osf.io,Nesiehr/osf.io,leb2dg/osf.io,billyhunt/osf.io,baylee-d/osf.io,Ghalko/osf.io,RomanZWang/osf.io,sbt9uc/osf.io,leb2dg/osf.io,mattclark/osf.io,chennan47/osf.io,jmcarp/osf.io,cwisecarver/osf.io,petermalcolm/osf.io,jnayak1/osf.io,zamattiac/osf.io,amyshi188/osf.io,alexschiller/osf.io,Johnetordoff/osf.io,sloria/osf.io,lyndsysimon/osf.io,hmoco/osf.io,DanielSBrown/osf.io,aaxelb/osf.io,haoyuchen1992/osf.io,KAsante95/osf.io,sbt9uc/osf.io,dplorimer/osf,lyndsysimon/osf.io,arpitar/osf.io,mfraezz/osf.io,kch8qx/osf.io,samchrisinger/osf.io,brandonPurvis/osf.io,binoculars/osf.io,ckc6cz/osf.io,njantrania/osf.io,fabianvf/osf.io,pattisdr/osf.io,caseyrollins/osf.io,kushG/osf.io,zachjanicki/osf.io,TomBaxter/osf.io,cwisecarver/osf.io,cwisecarver/osf.io,cwisecarver/osf.io,chrisseto/osf.io,mfraezz/osf.io,jinluyuan/osf.io,jeffreyliu3230/osf.io,TomBaxter/osf.io,samchrisinger/osf.io,laurenrevere/osf.io,doublebits/osf.io,crcresearch/osf.io,rdhyee/osf.io,GaryKriebel/osf.io,binoculars/osf.io,felliott/osf.io,GaryKriebel/osf.io,HarryRybacki/osf.io,caseyrollins/osf.io,monikagrabowska/osf.io,samchrisinger/osf.io,jeffreyliu3230/osf.io,kwierman/osf.io,asanfilippo7/osf.io,abought/osf.io,MerlinZhang/osf.io,samanehsan/osf.io,wearpants/osf.io,acshi/osf.io,fabianvf/osf.io,alexschiller/osf.io,cslzchen/osf.io,MerlinZhang/osf.io,kwierman/osf.io,wearpants/osf.io,adlius/osf.io,revanthkolli/osf.io,RomanZWang/osf.io,RomanZWang/osf.io,mluo613/osf.io,caneruguz/osf.io,felliott/osf.io,caseyrollins/osf.io,zamattiac/osf.io,zkraime/osf.io,kch8qx/osf.io,doublebits/osf.io,jmcarp/osf.io,Ghalko/osf.io,barbour-em/osf.io,Johnetordoff/osf.io,DanielSBrown/osf.io,cosenal/osf.io,cosenal/osf.io,TomHeatwole/osf.io,njantrania/osf.io,adlius/osf.io,GageGaskins/osf.io,njantrania/osf.io,chennan47/osf.io,haoyuchen1992/osf.io,danielneis/osf.io,icereval/osf.io,billyhunt/osf.io,ticklemepierce/osf.io,danielneis/osf.io,KAsante95/osf.io,njantrania/osf.io,jolene-esposito/osf.io,ZobairAlijan/osf.io
CLIENT_ID = None CLIENT_SECRET = None API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000
Add figshare CLIENT_ID and CLIENT_SECRET back into default settings. [skip ci] API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000
539608a9ca9a21707184496e744fc40a8cb72cc1
announce/management/commands/migrate_mailchimp_users.py
announce/management/commands/migrate_mailchimp_users.py
from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from announce.mailchimp import archive_members, list_members, batch_subscribe from studygroups.models import Profile import requests import logging logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Synchronize mailchimp audience with users that opted in for communications' def handle(self, *args, **options): # get all mailchimp users mailchimp_members = list_members() filter_subscribed = lambda x: x.get('status') not in ['unsubscribed', 'cleaned'] mailchimp_members = filter(filter_subscribed, mailchimp_members) emails = [member.get('email_address').lower() for member in mailchimp_members] # add all members with communicagtion_opt_in == True to mailchimp subscribed = User.objects.filter(profile__communication_opt_in=True, is_active=True, profile__email_confirmed_at__isnull=False) to_sub = list(filter(lambda u: u.email.lower() not in emails, subscribed)) print('{} users will be added to the mailchimp list'.format(len(to_sub))) batch_subscribe(to_sub) # update profile.communication_opt_in = True for users subscribed to the mailchimp newsletter unsubscribed_users = User.objects.filter(profile__communication_opt_in=False, is_active=True, profile__email_confirmed_at__isnull=False) to_update = list(filter(lambda u: u.email.lower() in emails, unsubscribed_users)) for user in to_update: user.profile.communication_opt_in = True user.profile.save()
from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from announce.mailchimp import archive_members, list_members, batch_subscribe from studygroups.models import Profile import requests import logging logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Synchronize mailchimp audience with users that opted in for communications' def handle(self, *args, **options): # get all mailchimp users mailchimp_members = list_members() filter_subscribed = lambda x: x.get('status') not in ['unsubscribed', 'cleaned'] mailchimp_members = filter(filter_subscribed, mailchimp_members) emails = [member.get('email_address').lower() for member in mailchimp_members] # add all members with communicagtion_opt_in == True to mailchimp subscribed = User.objects.filter(profile__communication_opt_in=True, is_active=True, profile__email_confirmed_at__isnull=False) to_sub = list(filter(lambda u: u.email.lower() not in emails, subscribed)) print('{} users will be added to the mailchimp list'.format(len(to_sub))) batch_subscribe(to_sub)
Remove once of code for mailchimp list migration
Remove once of code for mailchimp list migration
Python
mit
p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles
from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from announce.mailchimp import archive_members, list_members, batch_subscribe from studygroups.models import Profile import requests import logging logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Synchronize mailchimp audience with users that opted in for communications' def handle(self, *args, **options): # get all mailchimp users mailchimp_members = list_members() filter_subscribed = lambda x: x.get('status') not in ['unsubscribed', 'cleaned'] mailchimp_members = filter(filter_subscribed, mailchimp_members) emails = [member.get('email_address').lower() for member in mailchimp_members] # add all members with communicagtion_opt_in == True to mailchimp subscribed = User.objects.filter(profile__communication_opt_in=True, is_active=True, profile__email_confirmed_at__isnull=False) to_sub = list(filter(lambda u: u.email.lower() not in emails, subscribed)) print('{} users will be added to the mailchimp list'.format(len(to_sub))) batch_subscribe(to_sub)
Remove once of code for mailchimp list migration from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from announce.mailchimp import archive_members, list_members, batch_subscribe from studygroups.models import Profile import requests import logging logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Synchronize mailchimp audience with users that opted in for communications' def handle(self, *args, **options): # get all mailchimp users mailchimp_members = list_members() filter_subscribed = lambda x: x.get('status') not in ['unsubscribed', 'cleaned'] mailchimp_members = filter(filter_subscribed, mailchimp_members) emails = [member.get('email_address').lower() for member in mailchimp_members] # add all members with communicagtion_opt_in == True to mailchimp subscribed = User.objects.filter(profile__communication_opt_in=True, is_active=True, profile__email_confirmed_at__isnull=False) to_sub = list(filter(lambda u: u.email.lower() not in emails, subscribed)) print('{} users will be added to the mailchimp list'.format(len(to_sub))) batch_subscribe(to_sub) # update profile.communication_opt_in = True for users subscribed to the mailchimp newsletter unsubscribed_users = User.objects.filter(profile__communication_opt_in=False, is_active=True, profile__email_confirmed_at__isnull=False) to_update = list(filter(lambda u: u.email.lower() in emails, unsubscribed_users)) for user in to_update: user.profile.communication_opt_in = True user.profile.save()
305c3e0ce2705dd23e00ec801f5588ec1dbcc3a8
py/two-sum-ii-input-array-is-sorted.py
py/two-sum-ii-input-array-is-sorted.py
class Solution(object): def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ head, tail = 0, len(numbers) - 1 while head < tail: s = numbers[head] + numbers[tail] if s == target: return [head + 1, tail + 1] elif s < target: head += 1 elif s > target: tail -= 1
Add py solution for 167. Two Sum II - Input array is sorted
Add py solution for 167. Two Sum II - Input array is sorted 167. Two Sum II - Input array is sorted: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
Python
apache-2.0
ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode
class Solution(object): def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ head, tail = 0, len(numbers) - 1 while head < tail: s = numbers[head] + numbers[tail] if s == target: return [head + 1, tail + 1] elif s < target: head += 1 elif s > target: tail -= 1
Add py solution for 167. Two Sum II - Input array is sorted 167. Two Sum II - Input array is sorted: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
619ca614890aa9d02acaf04fff51bee67233a8a8
setup.py
setup.py
#!/usr/bin/env python from setuptools import find_packages, Command setup_params = dict( name='bugimporters', version=0.1, author='Various contributers to the OpenHatch project, Berry Phillips', author_email='all@openhatch.org, berryphillips@gmail.com', packages=find_packages(), description='Bug importers for the OpenHatch project', install_requires=[ 'gdata', 'lxml', 'pyopenssl', 'unicodecsv', 'feedparser', 'twisted', 'python-dateutil', 'decorator', 'scrapy>0.9', 'argparse', 'mock', 'PyYAML', 'autoresponse>=0.2', ], ) ### Python 2.7 already has importlib. Because of that, ### we can't put it in install_requires. We test for ### that here; if needed, we add it. try: import importlib except ImportError: install_requires.append('importlib') if __name__ == '__main__': from setuptools import setup setup(**setup_params)
#!/usr/bin/env python from setuptools import find_packages, Command setup_params = dict( name='bugimporters', version=0.1, author='Various contributers to the OpenHatch project, Berry Phillips', author_email='all@openhatch.org, berryphillips@gmail.com', packages=find_packages(), description='Bug importers for the OpenHatch project', install_requires=[ 'gdata', 'lxml', 'pyopenssl', 'unicodecsv', 'feedparser', 'twisted', 'python-dateutil', 'decorator', 'scrapy>0.9', 'argparse', 'mock', 'PyYAML', 'autoresponse>=0.2', ], ) ### Python 2.7 already has importlib. Because of that, ### we can't put it in install_requires. We test for ### that here; if needed, we add it. try: import importlib except ImportError: setup_params['install_requires'].append('importlib') if __name__ == '__main__': from setuptools import setup setup(**setup_params)
Fix NameError on Python 2.6
Fix NameError on Python 2.6
Python
agpl-3.0
openhatch/oh-bugimporters,openhatch/oh-bugimporters,openhatch/oh-bugimporters
#!/usr/bin/env python from setuptools import find_packages, Command setup_params = dict( name='bugimporters', version=0.1, author='Various contributers to the OpenHatch project, Berry Phillips', author_email='all@openhatch.org, berryphillips@gmail.com', packages=find_packages(), description='Bug importers for the OpenHatch project', install_requires=[ 'gdata', 'lxml', 'pyopenssl', 'unicodecsv', 'feedparser', 'twisted', 'python-dateutil', 'decorator', 'scrapy>0.9', 'argparse', 'mock', 'PyYAML', 'autoresponse>=0.2', ], ) ### Python 2.7 already has importlib. Because of that, ### we can't put it in install_requires. We test for ### that here; if needed, we add it. try: import importlib except ImportError: setup_params['install_requires'].append('importlib') if __name__ == '__main__': from setuptools import setup setup(**setup_params)
Fix NameError on Python 2.6 #!/usr/bin/env python from setuptools import find_packages, Command setup_params = dict( name='bugimporters', version=0.1, author='Various contributers to the OpenHatch project, Berry Phillips', author_email='all@openhatch.org, berryphillips@gmail.com', packages=find_packages(), description='Bug importers for the OpenHatch project', install_requires=[ 'gdata', 'lxml', 'pyopenssl', 'unicodecsv', 'feedparser', 'twisted', 'python-dateutil', 'decorator', 'scrapy>0.9', 'argparse', 'mock', 'PyYAML', 'autoresponse>=0.2', ], ) ### Python 2.7 already has importlib. Because of that, ### we can't put it in install_requires. We test for ### that here; if needed, we add it. try: import importlib except ImportError: install_requires.append('importlib') if __name__ == '__main__': from setuptools import setup setup(**setup_params)
ecce72199a8c9f0f333715419d572444d5b9fc90
shade/tests/functional/test_devstack.py
shade/tests/functional/test_devstack.py
# Copyright (c) 2016 Red Hat, Inc. # # 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. """ test_devstack ------------- Throw errors if we do not actually detect the services we're supposed to. """ import os from testscenarios import load_tests_apply_scenarios as load_tests # noqa from shade.tests.functional import base class TestDevstack(base.BaseFunctionalTestCase): scenarios = [ ('designate', dict(env='DESIGNATE', service='dns')), ('heat', dict(env='HEAT', service='orchestration')), ('magnum', dict(env='MAGNUM', service='container')), ('neutron', dict(env='NEUTRON', service='network')), ('swift', dict(env='SWIFT', service='object-store')), ] def test_has_service(self): if os.environ.get('SHADE_HAS_{env}'.format(env=self.env), '0') == '1': self.assertTrue(self.demo_cloud.has_service(self.service))
Add test to trap for missing services
Add test to trap for missing services Recently when there was an issue with the magnum devstack plugin causing the shade gate to not have swift, we didn't notice except through the ansible tests. That's because we have a bunch of has_service checks in the tests themselves to deal with different configs. Unfortunately, that makes it easy to fail open. Put in a test, along with changes to devstack-gate jobs, to throw errors if services do not show up that should. Depends-On: I2433c7bced6c8ca785634056de45ddf624031509 Change-Id: I16f477c405583b315fff24929d6c7b2ca4f2eae3
Python
apache-2.0
openstack/python-openstacksdk,dtroyer/python-openstacksdk,openstack/python-openstacksdk,dtroyer/python-openstacksdk,stackforge/python-openstacksdk,stackforge/python-openstacksdk,openstack-infra/shade,openstack-infra/shade
# Copyright (c) 2016 Red Hat, Inc. # # 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. """ test_devstack ------------- Throw errors if we do not actually detect the services we're supposed to. """ import os from testscenarios import load_tests_apply_scenarios as load_tests # noqa from shade.tests.functional import base class TestDevstack(base.BaseFunctionalTestCase): scenarios = [ ('designate', dict(env='DESIGNATE', service='dns')), ('heat', dict(env='HEAT', service='orchestration')), ('magnum', dict(env='MAGNUM', service='container')), ('neutron', dict(env='NEUTRON', service='network')), ('swift', dict(env='SWIFT', service='object-store')), ] def test_has_service(self): if os.environ.get('SHADE_HAS_{env}'.format(env=self.env), '0') == '1': self.assertTrue(self.demo_cloud.has_service(self.service))
Add test to trap for missing services Recently when there was an issue with the magnum devstack plugin causing the shade gate to not have swift, we didn't notice except through the ansible tests. That's because we have a bunch of has_service checks in the tests themselves to deal with different configs. Unfortunately, that makes it easy to fail open. Put in a test, along with changes to devstack-gate jobs, to throw errors if services do not show up that should. Depends-On: I2433c7bced6c8ca785634056de45ddf624031509 Change-Id: I16f477c405583b315fff24929d6c7b2ca4f2eae3
c36a088ad0d56f2a4dbff85bc33922ab95fbc184
test_board_pytest.py
test_board_pytest.py
from board import Board def test_addPiece(): print("Testing adding a piece.") board = Board(5,5) board.addPiece(0, 1) assert board.boardMatrix.item(0,4) == 1
Add test for adding piece to board.
Add test for adding piece to board.
Python
mit
isaacarvestad/four-in-a-row
from board import Board def test_addPiece(): print("Testing adding a piece.") board = Board(5,5) board.addPiece(0, 1) assert board.boardMatrix.item(0,4) == 1
Add test for adding piece to board.
90655c89fcf56af06a69f8110a9f7154294ca11c
ritter/analytics/sentiment_analyzer.py
ritter/analytics/sentiment_analyzer.py
import re, math from collections import Counter import itertools from sentimental import sentimental class SentimentAnalyzer(): _sentimental = sentimental.Sentimental(max_ngrams=2) path = sentimental.Sentimental.get_datafolder() _sentimental.train([path + '/sv/ruhburg']) def calculate_friend_scores(marked_tree): reg = re.compile('\(([\w]+) \\\"GHOSTDOC-TOKEN\\\"\)') scores = {} for item in marked_tree: if 'text' in item: m = reg.findall(item['text']) c = sorted(list(Counter(m))) pairs = list(itertools.combinations(c, 2)) senti = SentimentAnalyzer.sentiment(item['text']) for pair in pairs: s = scores.get(pair, [0, 0]) if senti == 1: s[0] = s[0] + 1 elif senti == -1: s[1] = s[1] + 1 scores[pair] = s return {_id: (vals[0] - vals[1]) * math.exp(max(vals) / (vals[0] + vals[1] + 1)) for _id, vals in scores.items()} def sentiment(text): label = max(SentimentAnalyzer._sentimental.sentiment(text)) if label == 'positive': return 1 elif label == 'negative': return -1 else: return 0
import re, math from collections import Counter import itertools from sentimental import sentimental class SentimentAnalyzer(): _sentimental = sentimental.Sentimental(max_ngrams=2, undersample=True) path = sentimental.Sentimental.get_datafolder() _sentimental.train([path + '/sv/ruhburg']) def calculate_friend_scores(marked_tree): reg = re.compile('\(([\w]+) \\\"GHOSTDOC-TOKEN\\\"\)') scores = {} for item in marked_tree: if 'text' in item: m = reg.findall(item['text']) c = sorted(list(Counter(m))) pairs = list(itertools.combinations(c, 2)) senti = SentimentAnalyzer.sentiment(item['text']) for pair in pairs: s = scores.get(pair, [0, 0]) if senti == 1: s[0] = s[0] + 1 elif senti == -1: s[1] = s[1] + 1 scores[pair] = s return {_id: (vals[0] - vals[1]) * math.exp(max(vals) / (vals[0] + vals[1] + 1)) for _id, vals in scores.items()} def sentiment(text): label = max(SentimentAnalyzer._sentimental.sentiment(text)) if label == 'positive': return 1 elif label == 'negative': return -1 else: return 0
Update to Sentimental 2.2.x with undersampling
feat: Update to Sentimental 2.2.x with undersampling
Python
mit
ErikGartner/ghostdoc-ritter
import re, math from collections import Counter import itertools from sentimental import sentimental class SentimentAnalyzer(): _sentimental = sentimental.Sentimental(max_ngrams=2, undersample=True) path = sentimental.Sentimental.get_datafolder() _sentimental.train([path + '/sv/ruhburg']) def calculate_friend_scores(marked_tree): reg = re.compile('\(([\w]+) \\\"GHOSTDOC-TOKEN\\\"\)') scores = {} for item in marked_tree: if 'text' in item: m = reg.findall(item['text']) c = sorted(list(Counter(m))) pairs = list(itertools.combinations(c, 2)) senti = SentimentAnalyzer.sentiment(item['text']) for pair in pairs: s = scores.get(pair, [0, 0]) if senti == 1: s[0] = s[0] + 1 elif senti == -1: s[1] = s[1] + 1 scores[pair] = s return {_id: (vals[0] - vals[1]) * math.exp(max(vals) / (vals[0] + vals[1] + 1)) for _id, vals in scores.items()} def sentiment(text): label = max(SentimentAnalyzer._sentimental.sentiment(text)) if label == 'positive': return 1 elif label == 'negative': return -1 else: return 0
feat: Update to Sentimental 2.2.x with undersampling import re, math from collections import Counter import itertools from sentimental import sentimental class SentimentAnalyzer(): _sentimental = sentimental.Sentimental(max_ngrams=2) path = sentimental.Sentimental.get_datafolder() _sentimental.train([path + '/sv/ruhburg']) def calculate_friend_scores(marked_tree): reg = re.compile('\(([\w]+) \\\"GHOSTDOC-TOKEN\\\"\)') scores = {} for item in marked_tree: if 'text' in item: m = reg.findall(item['text']) c = sorted(list(Counter(m))) pairs = list(itertools.combinations(c, 2)) senti = SentimentAnalyzer.sentiment(item['text']) for pair in pairs: s = scores.get(pair, [0, 0]) if senti == 1: s[0] = s[0] + 1 elif senti == -1: s[1] = s[1] + 1 scores[pair] = s return {_id: (vals[0] - vals[1]) * math.exp(max(vals) / (vals[0] + vals[1] + 1)) for _id, vals in scores.items()} def sentiment(text): label = max(SentimentAnalyzer._sentimental.sentiment(text)) if label == 'positive': return 1 elif label == 'negative': return -1 else: return 0
e0385d0ba8fab48f129175123e103544574d1dac
commands.py
commands.py
#!/usr/bin/env python from twisted.protocols import amp from twisted.cred.error import UnauthorizedLogin # commands to server side class Login(amp.Command): arguments = [("username", amp.String()), ("password", amp.String())] response = [] errors = {UnauthorizedLogin: "UnauthorizedLogin"} # If we set requiresAnswer = False, then the client-side callRemote # returns None instead of a deferred, and we can't attach callbacks. # So be sure to return an empty dict instead. # TODO doc patch for twisted class SendToAll(amp.Command): arguments = [("message", amp.String())] response = [] class SendToUser(amp.Command): arguments = [("message", amp.String()), "username", amp.String()] response = [] # commands to client side class Send(amp.Command): arguments = [("message", amp.String()), ("sender", amp.String())] response = [] class AddUser(amp.Command): arguments = [("user", amp.String())] response = [] class DelUser(amp.Command): arguments = [("user", amp.String())] response = [] class LoggedIn(amp.Command): arguments = [("ok", amp.Boolean())] response = []
from twisted.protocols import amp from twisted.cred.error import UnauthorizedLogin # commands to server side class Login(amp.Command): arguments = [("username", amp.String()), ("password", amp.String())] response = [] errors = {UnauthorizedLogin: "UnauthorizedLogin"} # If we set requiresAnswer = False, then the client-side callRemote # returns None instead of a deferred, and we can't attach callbacks. # So be sure to return an empty dict instead. # TODO doc patch for twisted class SendToAll(amp.Command): arguments = [("message", amp.String())] response = [] class SendToUser(amp.Command): arguments = [("message", amp.String()), "username", amp.String()] response = [] # commands to client side class Send(amp.Command): arguments = [("message", amp.String()), ("sender", amp.String())] response = [] class AddUser(amp.Command): arguments = [("user", amp.String())] response = [] class DelUser(amp.Command): arguments = [("user", amp.String())] response = [] class LoggedIn(amp.Command): arguments = [("ok", amp.Boolean())] response = []
Remove shebang line from non-script.
Remove shebang line from non-script.
Python
mit
dripton/ampchat
from twisted.protocols import amp from twisted.cred.error import UnauthorizedLogin # commands to server side class Login(amp.Command): arguments = [("username", amp.String()), ("password", amp.String())] response = [] errors = {UnauthorizedLogin: "UnauthorizedLogin"} # If we set requiresAnswer = False, then the client-side callRemote # returns None instead of a deferred, and we can't attach callbacks. # So be sure to return an empty dict instead. # TODO doc patch for twisted class SendToAll(amp.Command): arguments = [("message", amp.String())] response = [] class SendToUser(amp.Command): arguments = [("message", amp.String()), "username", amp.String()] response = [] # commands to client side class Send(amp.Command): arguments = [("message", amp.String()), ("sender", amp.String())] response = [] class AddUser(amp.Command): arguments = [("user", amp.String())] response = [] class DelUser(amp.Command): arguments = [("user", amp.String())] response = [] class LoggedIn(amp.Command): arguments = [("ok", amp.Boolean())] response = []
Remove shebang line from non-script. #!/usr/bin/env python from twisted.protocols import amp from twisted.cred.error import UnauthorizedLogin # commands to server side class Login(amp.Command): arguments = [("username", amp.String()), ("password", amp.String())] response = [] errors = {UnauthorizedLogin: "UnauthorizedLogin"} # If we set requiresAnswer = False, then the client-side callRemote # returns None instead of a deferred, and we can't attach callbacks. # So be sure to return an empty dict instead. # TODO doc patch for twisted class SendToAll(amp.Command): arguments = [("message", amp.String())] response = [] class SendToUser(amp.Command): arguments = [("message", amp.String()), "username", amp.String()] response = [] # commands to client side class Send(amp.Command): arguments = [("message", amp.String()), ("sender", amp.String())] response = [] class AddUser(amp.Command): arguments = [("user", amp.String())] response = [] class DelUser(amp.Command): arguments = [("user", amp.String())] response = [] class LoggedIn(amp.Command): arguments = [("ok", amp.Boolean())] response = []
4393740af93ae0ac1927e68c422e24735b0216c1
infosystem/subsystem/policy/entity.py
infosystem/subsystem/policy/entity.py
from sqlalchemy import UniqueConstraint from infosystem.common.subsystem import entity from infosystem.database import db class Policy(entity.Entity, db.Model): attributes = ['id', 'capability_id', 'role_id', 'bypass'] domain_id = db.Column(db.CHAR(32), db.ForeignKey("domain.id"), nullable=False) capability_id = db.Column(db.CHAR(32), db.ForeignKey("capability.id"), nullable=False) role_id = db.Column(db.CHAR(32), db.ForeignKey("role.id"), nullable=True) bypass = db.Column(db.Boolean, nullable=False, default=False) __table_args__ = (UniqueConstraint('domain_id', 'capability_id', 'role_id', name='policy_uk'),) def __init__(self, id, domain_id, capability_id, role_id, bypass): super(Policy, self).__init__(id) self.domain_id = domain_id self.capability_id = capability_id self.role_id = role_id self.bypass = bypass
from sqlalchemy import UniqueConstraint from infosystem.common.subsystem import entity from infosystem.database import db class Policy(entity.Entity, db.Model): attributes = ['id', 'capability_id', 'role_id', 'bypass'] domain_id = db.Column(db.CHAR(32), db.ForeignKey("domain.id"), nullable=False) capability_id = db.Column(db.CHAR(32), db.ForeignKey("capability.id"), nullable=False) role_id = db.Column(db.CHAR(32), db.ForeignKey("role.id"), nullable=True) bypass = db.Column(db.Boolean, nullable=False, default=False) __table_args__ = (UniqueConstraint('domain_id', 'capability_id', 'role_id', name='policy_uk'),) def __init__(self, id, domain_id, capability_id, role_id=None, bypass=False): super(Policy, self).__init__(id) self.domain_id = domain_id self.capability_id = capability_id self.role_id = role_id self.bypass = bypass
Make role_id & bypass opt args in Policy __init__
Make role_id & bypass opt args in Policy __init__
Python
apache-2.0
samueldmq/infosystem
from sqlalchemy import UniqueConstraint from infosystem.common.subsystem import entity from infosystem.database import db class Policy(entity.Entity, db.Model): attributes = ['id', 'capability_id', 'role_id', 'bypass'] domain_id = db.Column(db.CHAR(32), db.ForeignKey("domain.id"), nullable=False) capability_id = db.Column(db.CHAR(32), db.ForeignKey("capability.id"), nullable=False) role_id = db.Column(db.CHAR(32), db.ForeignKey("role.id"), nullable=True) bypass = db.Column(db.Boolean, nullable=False, default=False) __table_args__ = (UniqueConstraint('domain_id', 'capability_id', 'role_id', name='policy_uk'),) def __init__(self, id, domain_id, capability_id, role_id=None, bypass=False): super(Policy, self).__init__(id) self.domain_id = domain_id self.capability_id = capability_id self.role_id = role_id self.bypass = bypass
Make role_id & bypass opt args in Policy __init__ from sqlalchemy import UniqueConstraint from infosystem.common.subsystem import entity from infosystem.database import db class Policy(entity.Entity, db.Model): attributes = ['id', 'capability_id', 'role_id', 'bypass'] domain_id = db.Column(db.CHAR(32), db.ForeignKey("domain.id"), nullable=False) capability_id = db.Column(db.CHAR(32), db.ForeignKey("capability.id"), nullable=False) role_id = db.Column(db.CHAR(32), db.ForeignKey("role.id"), nullable=True) bypass = db.Column(db.Boolean, nullable=False, default=False) __table_args__ = (UniqueConstraint('domain_id', 'capability_id', 'role_id', name='policy_uk'),) def __init__(self, id, domain_id, capability_id, role_id, bypass): super(Policy, self).__init__(id) self.domain_id = domain_id self.capability_id = capability_id self.role_id = role_id self.bypass = bypass
810a43c859264e3d5e1af8b43888bf89c06bee1d
ipybind/stream.py
ipybind/stream.py
# -*- coding: utf-8 -*- import contextlib import sys try: import fcntl except ImportError: fcntl = None from ipybind.common import is_kernel from ipybind.ext.wurlitzer import Wurlitzer _fwd = None class Forwarder(Wurlitzer): def __init__(self, handler=None): self._data_handler = handler if handler is not None else lambda x: x super().__init__(stdout=sys.stdout, stderr=sys.stderr) def _handle_data(self, data, stream): data = self._data_handler(self._decode(data)) if data and stream: stream.write(data) def _handle_stdout(self, data): self._handle_data(data, self._stdout) def _handle_stderr(self, data): self._handle_data(data, self._stderr) @contextlib.contextmanager def suppress(): if fcntl: with Forwarder(handler=lambda _: None): yield else: yield @contextlib.contextmanager def forward(handler=None): global _fwd if _fwd is None and is_kernel() and fcntl: with Forwarder(handler=handler): yield else: yield def start_forwarding(handler=None): global _fwd if fcntl: if _fwd is None: _fwd = Forwarder(handler=handler) _fwd.__enter__() def stop_forwarding(handler=None): global _fwd if fcntl: if _fwd is not None: _fwd.__exit__(None, None, None) _fwd = None
# -*- coding: utf-8 -*- import contextlib import sys try: import fcntl except ImportError: fcntl = None from ipybind.common import is_kernel from ipybind.ext.wurlitzer import Wurlitzer _fwd = None class Forwarder(Wurlitzer): def __init__(self, handler=None): self._data_handler = handler if handler is not None else lambda x: x super().__init__(stdout=sys.stdout, stderr=sys.stderr) def _handle_data(self, data, stream): data = self._data_handler(self._decode(data)) if data and stream: stream.write(data) def _handle_stdout(self, data): self._handle_data(data, self._stdout) def _handle_stderr(self, data): self._handle_data(data, self._stderr) @contextlib.contextmanager def forward(handler=None): global _fwd if _fwd is None and is_kernel() and fcntl: with Forwarder(handler=handler): yield else: yield def start_forwarding(handler=None): global _fwd if fcntl: if _fwd is None: _fwd = Forwarder(handler=handler) _fwd.__enter__() def stop_forwarding(handler=None): global _fwd if fcntl: if _fwd is not None: _fwd.__exit__(None, None, None) _fwd = None
Remove suppress() as it's no longer required
Remove suppress() as it's no longer required
Python
mit
aldanor/ipybind,aldanor/ipybind,aldanor/ipybind
# -*- coding: utf-8 -*- import contextlib import sys try: import fcntl except ImportError: fcntl = None from ipybind.common import is_kernel from ipybind.ext.wurlitzer import Wurlitzer _fwd = None class Forwarder(Wurlitzer): def __init__(self, handler=None): self._data_handler = handler if handler is not None else lambda x: x super().__init__(stdout=sys.stdout, stderr=sys.stderr) def _handle_data(self, data, stream): data = self._data_handler(self._decode(data)) if data and stream: stream.write(data) def _handle_stdout(self, data): self._handle_data(data, self._stdout) def _handle_stderr(self, data): self._handle_data(data, self._stderr) @contextlib.contextmanager def forward(handler=None): global _fwd if _fwd is None and is_kernel() and fcntl: with Forwarder(handler=handler): yield else: yield def start_forwarding(handler=None): global _fwd if fcntl: if _fwd is None: _fwd = Forwarder(handler=handler) _fwd.__enter__() def stop_forwarding(handler=None): global _fwd if fcntl: if _fwd is not None: _fwd.__exit__(None, None, None) _fwd = None
Remove suppress() as it's no longer required # -*- coding: utf-8 -*- import contextlib import sys try: import fcntl except ImportError: fcntl = None from ipybind.common import is_kernel from ipybind.ext.wurlitzer import Wurlitzer _fwd = None class Forwarder(Wurlitzer): def __init__(self, handler=None): self._data_handler = handler if handler is not None else lambda x: x super().__init__(stdout=sys.stdout, stderr=sys.stderr) def _handle_data(self, data, stream): data = self._data_handler(self._decode(data)) if data and stream: stream.write(data) def _handle_stdout(self, data): self._handle_data(data, self._stdout) def _handle_stderr(self, data): self._handle_data(data, self._stderr) @contextlib.contextmanager def suppress(): if fcntl: with Forwarder(handler=lambda _: None): yield else: yield @contextlib.contextmanager def forward(handler=None): global _fwd if _fwd is None and is_kernel() and fcntl: with Forwarder(handler=handler): yield else: yield def start_forwarding(handler=None): global _fwd if fcntl: if _fwd is None: _fwd = Forwarder(handler=handler) _fwd.__enter__() def stop_forwarding(handler=None): global _fwd if fcntl: if _fwd is not None: _fwd.__exit__(None, None, None) _fwd = None
c25b7820ccd52b943586af42d09ce53c3633ed96
cmsplugin_simple_markdown/models.py
cmsplugin_simple_markdown/models.py
import threading from django.db import models from django.utils.translation import ugettext_lazy as _ from cms.models.pluginmodel import CMSPlugin from cmsplugin_simple_markdown import utils localdata = threading.local() localdata.TEMPLATE_CHOICES = utils.autodiscover_templates() TEMPLATE_CHOICES = localdata.TEMPLATE_CHOICES class SimpleMarkdownPlugin(CMSPlugin): markdown_text = models.TextField(verbose_name=_('text')) template = models.CharField( verbose_name=_('template'), choices=TEMPLATE_CHOICES, max_length=255, default='cmsplugin_simple_markdown/simple_markdown.html', editable=len(TEMPLATE_CHOICES) > 1 ) def __unicode__(self): return self.markdown_text
import threading from django.db import models from django.utils.translation import ugettext_lazy as _ from cms.models.pluginmodel import CMSPlugin from cmsplugin_simple_markdown import utils localdata = threading.local() localdata.TEMPLATE_CHOICES = utils.autodiscover_templates() TEMPLATE_CHOICES = localdata.TEMPLATE_CHOICES class SimpleMarkdownPlugin(CMSPlugin): markdown_text = models.TextField(verbose_name=_('text')) template = models.CharField( verbose_name=_('template'), choices=TEMPLATE_CHOICES, max_length=255, default='cmsplugin_simple_markdown/simple_markdown.html', editable=len(TEMPLATE_CHOICES) > 1 ) def __unicode__(self): """ :rtype: str or unicode """ return self.markdown_text
Add some tiny docstring to the unicode method
Add some tiny docstring to the unicode method
Python
bsd-3-clause
Alir3z4/cmsplugin-simple-markdown,Alir3z4/cmsplugin-simple-markdown
import threading from django.db import models from django.utils.translation import ugettext_lazy as _ from cms.models.pluginmodel import CMSPlugin from cmsplugin_simple_markdown import utils localdata = threading.local() localdata.TEMPLATE_CHOICES = utils.autodiscover_templates() TEMPLATE_CHOICES = localdata.TEMPLATE_CHOICES class SimpleMarkdownPlugin(CMSPlugin): markdown_text = models.TextField(verbose_name=_('text')) template = models.CharField( verbose_name=_('template'), choices=TEMPLATE_CHOICES, max_length=255, default='cmsplugin_simple_markdown/simple_markdown.html', editable=len(TEMPLATE_CHOICES) > 1 ) def __unicode__(self): """ :rtype: str or unicode """ return self.markdown_text
Add some tiny docstring to the unicode method import threading from django.db import models from django.utils.translation import ugettext_lazy as _ from cms.models.pluginmodel import CMSPlugin from cmsplugin_simple_markdown import utils localdata = threading.local() localdata.TEMPLATE_CHOICES = utils.autodiscover_templates() TEMPLATE_CHOICES = localdata.TEMPLATE_CHOICES class SimpleMarkdownPlugin(CMSPlugin): markdown_text = models.TextField(verbose_name=_('text')) template = models.CharField( verbose_name=_('template'), choices=TEMPLATE_CHOICES, max_length=255, default='cmsplugin_simple_markdown/simple_markdown.html', editable=len(TEMPLATE_CHOICES) > 1 ) def __unicode__(self): return self.markdown_text
7e4aab6980519fd8124e36a6f8fd4415eaf8a4e7
tests/test_tracer.py
tests/test_tracer.py
import os import nose import tracer import logging l = logging.getLogger("tracer.tests.test_tracer") bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries')) pov_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), "povs")) test_data_location = str(os.path.dirname(os.path.realpath(__file__))) def test_cgc_0b32aa01_01_raw(): ''' Test CGC Scored Event 1's palindrome challenge with raw input ''' # test a valid palindrome t = tracer.Tracer(os.path.join(bin_location, "cgc_scored_event_1/cgc/0b32aa01_01"), "racecar\n") result_path, crash_state = t.run() # make sure there is no crash state nose.tools.assert_equal(crash_state, None) result_state = result_path.state # make sure angr modeled the correct output stdout_dump = result_state.posix.dumps(1) nose.tools.assert_true(stdout_dump.startswith("\t\tYes, that's a palindrome!\n\n")) # make sure there were no 'Nope's from non-palindromes nose.tools.assert_false("Nope" in stdout_dump) # now test crashing input t = tracer.Tracer(os.path.join(bin_location, "cgc_scored_event_1/cgc/0b32aa01_01"), "A" * 129) crash_path, crash_state = t.run() nose.tools.assert_not_equal(crash_path, None) nose.tools.assert_not_equal(crash_state, None) def run_all(): functions = globals() all_functions = dict(filter((lambda (k, v): k.startswith('test_')), functions.items())) for f in sorted(all_functions.keys()): if hasattr(all_functions[f], '__call__'): all_functions[f]() if __name__ == "__main__": logging.getLogger("angrop.rop").setLevel(logging.DEBUG) import sys if len(sys.argv) > 1: globals()['test_' + sys.argv[1]]() else: run_all()
Add a single testcase for the tracer
Add a single testcase for the tracer
Python
bsd-2-clause
schieb/angr,tyb0807/angr,tyb0807/angr,f-prettyland/angr,iamahuman/angr,angr/angr,angr/tracer,schieb/angr,iamahuman/angr,angr/angr,iamahuman/angr,schieb/angr,f-prettyland/angr,tyb0807/angr,f-prettyland/angr,angr/angr
import os import nose import tracer import logging l = logging.getLogger("tracer.tests.test_tracer") bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries')) pov_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), "povs")) test_data_location = str(os.path.dirname(os.path.realpath(__file__))) def test_cgc_0b32aa01_01_raw(): ''' Test CGC Scored Event 1's palindrome challenge with raw input ''' # test a valid palindrome t = tracer.Tracer(os.path.join(bin_location, "cgc_scored_event_1/cgc/0b32aa01_01"), "racecar\n") result_path, crash_state = t.run() # make sure there is no crash state nose.tools.assert_equal(crash_state, None) result_state = result_path.state # make sure angr modeled the correct output stdout_dump = result_state.posix.dumps(1) nose.tools.assert_true(stdout_dump.startswith("\t\tYes, that's a palindrome!\n\n")) # make sure there were no 'Nope's from non-palindromes nose.tools.assert_false("Nope" in stdout_dump) # now test crashing input t = tracer.Tracer(os.path.join(bin_location, "cgc_scored_event_1/cgc/0b32aa01_01"), "A" * 129) crash_path, crash_state = t.run() nose.tools.assert_not_equal(crash_path, None) nose.tools.assert_not_equal(crash_state, None) def run_all(): functions = globals() all_functions = dict(filter((lambda (k, v): k.startswith('test_')), functions.items())) for f in sorted(all_functions.keys()): if hasattr(all_functions[f], '__call__'): all_functions[f]() if __name__ == "__main__": logging.getLogger("angrop.rop").setLevel(logging.DEBUG) import sys if len(sys.argv) > 1: globals()['test_' + sys.argv[1]]() else: run_all()
Add a single testcase for the tracer
7560bce01be5560395dd2373e979dbee086f3c21
py2app/converters/nibfile.py
py2app/converters/nibfile.py
""" Automatic compilation of XIB files """ import subprocess, os from py2app.decorators import converts @converts(suffix=".xib") def convert_xib(source, destination, dry_run=0): destination = destination[:-4] + ".nib" if dry_run: return p = subprocess.Popen(['ibtool', '--compile', destination, source]) xit = p.wait() if xit != 0: raise RuntimeError("ibtool failed, code %d"%(xit,)) @converts(suffix=".nib") def convert_nib(source, destination, dry_run=0): destination = destination[:-4] + ".nib" if dry_run: return p = subprocess.Popen(['ibtool', '--compile', destination, source]) xit = p.wait() if xit != 0: raise RuntimeError("ibtool failed, code %d"%(xit,))
""" Automatic compilation of XIB files """ from __future__ import print_function import subprocess, os from py2app.decorators import converts gTool = None def _get_ibtool(): global gTool if gTool is None: if os.path.exists('/usr/bin/xcrun'): gTool = subprocess.check_output(['/usr/bin/xcrun', '-find', 'ibtool'])[:-1] else: gTool = 'ibtool' print (gTool) return gTool @converts(suffix=".xib") def convert_xib(source, destination, dry_run=0): destination = destination[:-4] + ".nib" print("compile %s -> %s"%(source, destination)) if dry_run: return subprocess.check_call([_get_ibtool(), '--compile', destination, source]) @converts(suffix=".nib") def convert_nib(source, destination, dry_run=0): destination = destination[:-4] + ".nib" print("compile %s -> %s"%(source, destination)) if dry_run: return subprocess.check_call([_get_ibtool, '--compile', destination, source])
Simplify nib compiler and support recent Xcode versions by using xcrun
Simplify nib compiler and support recent Xcode versions by using xcrun
Python
mit
metachris/py2app,metachris/py2app,metachris/py2app,metachris/py2app
""" Automatic compilation of XIB files """ from __future__ import print_function import subprocess, os from py2app.decorators import converts gTool = None def _get_ibtool(): global gTool if gTool is None: if os.path.exists('/usr/bin/xcrun'): gTool = subprocess.check_output(['/usr/bin/xcrun', '-find', 'ibtool'])[:-1] else: gTool = 'ibtool' print (gTool) return gTool @converts(suffix=".xib") def convert_xib(source, destination, dry_run=0): destination = destination[:-4] + ".nib" print("compile %s -> %s"%(source, destination)) if dry_run: return subprocess.check_call([_get_ibtool(), '--compile', destination, source]) @converts(suffix=".nib") def convert_nib(source, destination, dry_run=0): destination = destination[:-4] + ".nib" print("compile %s -> %s"%(source, destination)) if dry_run: return subprocess.check_call([_get_ibtool, '--compile', destination, source])
Simplify nib compiler and support recent Xcode versions by using xcrun """ Automatic compilation of XIB files """ import subprocess, os from py2app.decorators import converts @converts(suffix=".xib") def convert_xib(source, destination, dry_run=0): destination = destination[:-4] + ".nib" if dry_run: return p = subprocess.Popen(['ibtool', '--compile', destination, source]) xit = p.wait() if xit != 0: raise RuntimeError("ibtool failed, code %d"%(xit,)) @converts(suffix=".nib") def convert_nib(source, destination, dry_run=0): destination = destination[:-4] + ".nib" if dry_run: return p = subprocess.Popen(['ibtool', '--compile', destination, source]) xit = p.wait() if xit != 0: raise RuntimeError("ibtool failed, code %d"%(xit,))
fe78335e4f469e22f9a1de7a1e5ddd52021a7f0f
linesep.py
linesep.py
STARTER = -1 SEPARATOR = 0 TERMINATOR = 1 def readlines(fp, sep, mode=TERMINATOR, retain=True, size=512): if mode < 0: return _readlines_start(fp, sep, retain, size) elif mode == 0: return _readlines_sep(fp, sep, size) else: return _readlines_term(fp, sep, retain, size) def _readlines_start(fp, sep, retain=True, size=512): # Omits empty leading entry entries = _readlines_sep(fp, sep, size=size) e = next(entries) if e: yield e for e in entries: if retain: e = sep + e yield e def _readlines_sep(fp, sep, size=512): buff = '' for chunk in iter(lambda: fp.read(size), ''): buff += chunk lines = buff.split(sep) buff = lines.pop() for l in lines: yield l yield buff def _readlines_term(fp, sep, retain=True, size=512): # Omits empty trailing entry buff = '' for chunk in iter(lambda: fp.read(size), ''): buff += chunk lines = buff.split(sep) buff = lines.pop() for l in lines: if retain: l += sep yield l if buff: yield buff
def read_begun(fp, sep, retain=True, size=512): # Omits empty leading entry entries = read_separated(fp, sep, size=size) e = next(entries) if e: yield e for e in entries: if retain: e = sep + e yield e def read_separated(fp, sep, size=512): buff = '' for chunk in iter(lambda: fp.read(size), ''): buff += chunk lines = buff.split(sep) buff = lines.pop() for l in lines: yield l yield buff def read_terminated(fp, sep, retain=True, size=512): # Omits empty trailing entry buff = '' for chunk in iter(lambda: fp.read(size), ''): buff += chunk lines = buff.split(sep) buff = lines.pop() for l in lines: if retain: l += sep yield l if buff: yield buff
Use three public functions instead of one
Use three public functions instead of one
Python
mit
jwodder/linesep
def read_begun(fp, sep, retain=True, size=512): # Omits empty leading entry entries = read_separated(fp, sep, size=size) e = next(entries) if e: yield e for e in entries: if retain: e = sep + e yield e def read_separated(fp, sep, size=512): buff = '' for chunk in iter(lambda: fp.read(size), ''): buff += chunk lines = buff.split(sep) buff = lines.pop() for l in lines: yield l yield buff def read_terminated(fp, sep, retain=True, size=512): # Omits empty trailing entry buff = '' for chunk in iter(lambda: fp.read(size), ''): buff += chunk lines = buff.split(sep) buff = lines.pop() for l in lines: if retain: l += sep yield l if buff: yield buff
Use three public functions instead of one STARTER = -1 SEPARATOR = 0 TERMINATOR = 1 def readlines(fp, sep, mode=TERMINATOR, retain=True, size=512): if mode < 0: return _readlines_start(fp, sep, retain, size) elif mode == 0: return _readlines_sep(fp, sep, size) else: return _readlines_term(fp, sep, retain, size) def _readlines_start(fp, sep, retain=True, size=512): # Omits empty leading entry entries = _readlines_sep(fp, sep, size=size) e = next(entries) if e: yield e for e in entries: if retain: e = sep + e yield e def _readlines_sep(fp, sep, size=512): buff = '' for chunk in iter(lambda: fp.read(size), ''): buff += chunk lines = buff.split(sep) buff = lines.pop() for l in lines: yield l yield buff def _readlines_term(fp, sep, retain=True, size=512): # Omits empty trailing entry buff = '' for chunk in iter(lambda: fp.read(size), ''): buff += chunk lines = buff.split(sep) buff = lines.pop() for l in lines: if retain: l += sep yield l if buff: yield buff
f54c8f3b40bf44c4ba0f9fd1d1b6187991c327d5
tests/lints/check-external-size.py
tests/lints/check-external-size.py
#!/usr/bin/env python # -*- coding: utf8 -*- """ This script checks that all the external archive included in the repository are as small as they can be. """ from __future__ import print_function import os import sys import glob ROOT = os.path.join(os.path.dirname(__file__), "..", "..") ERRORS = 0 # when adding new files here, make sure that they are as small as possible! EXPECTED_SIZES = { "bzip2.tar.gz": 344, "fmt.tar.gz": 745, "gemmi.tar.gz": 476, "lzma.tar.gz": 256, "mmtf-cpp.tar.gz": 439, "molfiles.tar.gz": 477, "netcdf.tar.gz": 494, "pugixml.tar.gz": 549, "tng.tar.gz": 317, "xdrfile.tar.gz": 41, "zlib.tar.gz": 370, } def error(message): global ERRORS ERRORS += 1 print(message) if __name__ == "__main__": for path in glob.glob(os.path.join(ROOT, "external", "*.tar.gz")): size = os.path.getsize(path) size_kb = size // 1024 name = os.path.basename(path) if name not in EXPECTED_SIZES: error("{} is not a known external file, please edit this file".format(name)) expected = EXPECTED_SIZES[name] if size_kb > 1.1 * expected: error("{} size increased by more than 10%".format(name)) if size_kb < 0.7 * expected: error("{} size decreased by more than 30%, edit this file".format(name)) if ERRORS != 0: sys.exit(1)
Add a test checking the external archive size
Add a test checking the external archive size This should prevent size regressions
Python
bsd-3-clause
Luthaf/Chemharp,chemfiles/chemfiles,chemfiles/chemfiles,chemfiles/chemfiles,Luthaf/Chemharp,Luthaf/Chemharp,chemfiles/chemfiles
#!/usr/bin/env python # -*- coding: utf8 -*- """ This script checks that all the external archive included in the repository are as small as they can be. """ from __future__ import print_function import os import sys import glob ROOT = os.path.join(os.path.dirname(__file__), "..", "..") ERRORS = 0 # when adding new files here, make sure that they are as small as possible! EXPECTED_SIZES = { "bzip2.tar.gz": 344, "fmt.tar.gz": 745, "gemmi.tar.gz": 476, "lzma.tar.gz": 256, "mmtf-cpp.tar.gz": 439, "molfiles.tar.gz": 477, "netcdf.tar.gz": 494, "pugixml.tar.gz": 549, "tng.tar.gz": 317, "xdrfile.tar.gz": 41, "zlib.tar.gz": 370, } def error(message): global ERRORS ERRORS += 1 print(message) if __name__ == "__main__": for path in glob.glob(os.path.join(ROOT, "external", "*.tar.gz")): size = os.path.getsize(path) size_kb = size // 1024 name = os.path.basename(path) if name not in EXPECTED_SIZES: error("{} is not a known external file, please edit this file".format(name)) expected = EXPECTED_SIZES[name] if size_kb > 1.1 * expected: error("{} size increased by more than 10%".format(name)) if size_kb < 0.7 * expected: error("{} size decreased by more than 30%, edit this file".format(name)) if ERRORS != 0: sys.exit(1)
Add a test checking the external archive size This should prevent size regressions
beac0323253454f343b32d42d8c065cfc4fcc04f
src/epiweb/apps/reminder/models.py
src/epiweb/apps/reminder/models.py
import datetime from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class Reminder(models.Model): user = models.ForeignKey(User, unique=True) last_reminder = models.DateTimeField() next_reminder = models.DateField() wday = models.IntegerField() active = models.BooleanField() def add_reminder(sender, **kwargs): instance = kwargs.get('instance', None) try: reminder = Reminder.objects.get(user=instance) except Reminder.DoesNotExist: now = datetime.datetime.now() next = now + datetime.timedelta(days=7) reminder = Reminder() reminder.user = instance reminder.last_reminder = now reminder.next_reminder = next reminder.wday = now.timetuple().tm_wday reminder.active = True reminder.save() post_save.connect(add_reminder, sender=User)
import datetime from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save _ = lambda x: x # Reference: http://docs.python.org/library/time.html # - tm_wday => range [0,6], Monday is 0 MONDAY = 0 TUESDAY = 1 WEDNESDAY = 2 THURSDAY = 3 FRIDAY = 4 SATURDAY = 5 SUNDAY = 6 DAYS = ( (MONDAY, _('Monday')), (TUESDAY, _('Tuesday')), (WEDNESDAY, _('Wednesday')), (THURSDAY, _('Thursday')), (FRIDAY, _('Friday')), (SATURDAY, _('Saturday')), (SUNDAY, _('Sunday')) ) class Reminder(models.Model): user = models.ForeignKey(User, unique=True) last_reminder = models.DateTimeField() next_reminder = models.DateField() wday = models.IntegerField(choices=DAYS, verbose_name="Day", default=MONDAY) active = models.BooleanField() def add_reminder(sender, **kwargs): instance = kwargs.get('instance', None) try: reminder = Reminder.objects.get(user=instance) except Reminder.DoesNotExist: now = datetime.datetime.now() next = now + datetime.timedelta(days=7) reminder = Reminder() reminder.user = instance reminder.last_reminder = now reminder.next_reminder = next reminder.wday = now.timetuple().tm_wday reminder.active = True reminder.save() post_save.connect(add_reminder, sender=User)
Set available options for weekday field of reminder's model
Set available options for weekday field of reminder's model
Python
agpl-3.0
ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website
import datetime from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save _ = lambda x: x # Reference: http://docs.python.org/library/time.html # - tm_wday => range [0,6], Monday is 0 MONDAY = 0 TUESDAY = 1 WEDNESDAY = 2 THURSDAY = 3 FRIDAY = 4 SATURDAY = 5 SUNDAY = 6 DAYS = ( (MONDAY, _('Monday')), (TUESDAY, _('Tuesday')), (WEDNESDAY, _('Wednesday')), (THURSDAY, _('Thursday')), (FRIDAY, _('Friday')), (SATURDAY, _('Saturday')), (SUNDAY, _('Sunday')) ) class Reminder(models.Model): user = models.ForeignKey(User, unique=True) last_reminder = models.DateTimeField() next_reminder = models.DateField() wday = models.IntegerField(choices=DAYS, verbose_name="Day", default=MONDAY) active = models.BooleanField() def add_reminder(sender, **kwargs): instance = kwargs.get('instance', None) try: reminder = Reminder.objects.get(user=instance) except Reminder.DoesNotExist: now = datetime.datetime.now() next = now + datetime.timedelta(days=7) reminder = Reminder() reminder.user = instance reminder.last_reminder = now reminder.next_reminder = next reminder.wday = now.timetuple().tm_wday reminder.active = True reminder.save() post_save.connect(add_reminder, sender=User)
Set available options for weekday field of reminder's model import datetime from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class Reminder(models.Model): user = models.ForeignKey(User, unique=True) last_reminder = models.DateTimeField() next_reminder = models.DateField() wday = models.IntegerField() active = models.BooleanField() def add_reminder(sender, **kwargs): instance = kwargs.get('instance', None) try: reminder = Reminder.objects.get(user=instance) except Reminder.DoesNotExist: now = datetime.datetime.now() next = now + datetime.timedelta(days=7) reminder = Reminder() reminder.user = instance reminder.last_reminder = now reminder.next_reminder = next reminder.wday = now.timetuple().tm_wday reminder.active = True reminder.save() post_save.connect(add_reminder, sender=User)
9ceace60593f133b4f6dfdbd9b6f583362415294
src/configuration.py
src/configuration.py
import ConfigParser import os def class ConfigDlstats(object): """Cross platform configuration file handler. This class manages dlstats configuration files, providing easy access to the options.""" def __init__(self) """Open the configuration files handler, choosing the right path depending on the platform.""" appname = 'dlstats' if os.name == 'posix': if os.path.isfile(os.environ["HOME"]+'/.'+appname): self.filename = os.environ["HOME"]+'/.'+appname elif os.path.isfile('/etc/'+appname): self.filename = '/etc/'+appname else: raise FileNotFoundError('No configuration file found.' elif os.name == 'mac': self.filename = ("%s/Library/Application Support/%s" % (os.environ["HOME"], appname)) elif os.name == 'nt': self.filename = ("%s\Application Data\%s" % (os.environ["HOMEPATH"], appname)) else: raise UnsupportedOSError(os.name) self.config = ConfigParser.ConfigParser() self.config.read(self.filename)
import ConfigParser import os class ConfigDlstats(object): """Cross platform configuration file handler. This class manages dlstats configuration files, providing easy access to the options.""" def __init__(self): """Open the configuration files handler, choosing the right path depending on the platform.""" appname = 'dlstats' if os.name == 'posix': if os.path.isfile(os.environ["HOME"]+'/.'+appname): self.filename = os.environ["HOME"]+'/.'+appname elif os.path.isfile('/etc/'+appname): self.filename = '/etc/'+appname else: raise FileNotFoundError('No configuration file found.') elif os.name == 'mac': self.filename = ("%s/Library/Application Support/%s" % (os.environ["HOME"], appname)) elif os.name == 'nt': self.filename = ("%s\Application Data\%s" % (os.environ["HOMEPATH"], appname)) else: raise UnsupportedOSError(os.name) self.config = ConfigParser.ConfigParser() self.config.read(self.filename)
Fix a few syntax errors
Fix a few syntax errors
Python
agpl-3.0
MichelJuillard/dlstats,Widukind/dlstats,mmalter/dlstats,mmalter/dlstats,Widukind/dlstats,MichelJuillard/dlstats,mmalter/dlstats,MichelJuillard/dlstats
import ConfigParser import os class ConfigDlstats(object): """Cross platform configuration file handler. This class manages dlstats configuration files, providing easy access to the options.""" def __init__(self): """Open the configuration files handler, choosing the right path depending on the platform.""" appname = 'dlstats' if os.name == 'posix': if os.path.isfile(os.environ["HOME"]+'/.'+appname): self.filename = os.environ["HOME"]+'/.'+appname elif os.path.isfile('/etc/'+appname): self.filename = '/etc/'+appname else: raise FileNotFoundError('No configuration file found.') elif os.name == 'mac': self.filename = ("%s/Library/Application Support/%s" % (os.environ["HOME"], appname)) elif os.name == 'nt': self.filename = ("%s\Application Data\%s" % (os.environ["HOMEPATH"], appname)) else: raise UnsupportedOSError(os.name) self.config = ConfigParser.ConfigParser() self.config.read(self.filename)
Fix a few syntax errors import ConfigParser import os def class ConfigDlstats(object): """Cross platform configuration file handler. This class manages dlstats configuration files, providing easy access to the options.""" def __init__(self) """Open the configuration files handler, choosing the right path depending on the platform.""" appname = 'dlstats' if os.name == 'posix': if os.path.isfile(os.environ["HOME"]+'/.'+appname): self.filename = os.environ["HOME"]+'/.'+appname elif os.path.isfile('/etc/'+appname): self.filename = '/etc/'+appname else: raise FileNotFoundError('No configuration file found.' elif os.name == 'mac': self.filename = ("%s/Library/Application Support/%s" % (os.environ["HOME"], appname)) elif os.name == 'nt': self.filename = ("%s\Application Data\%s" % (os.environ["HOMEPATH"], appname)) else: raise UnsupportedOSError(os.name) self.config = ConfigParser.ConfigParser() self.config.read(self.filename)
3b684eeadb0c8b39593b14c15233a314bbab0895
troposphere/sns.py
troposphere/sns.py
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty, Tags from .compat import policytypes from .validators import boolean class Subscription(AWSProperty): props = { 'Endpoint': (basestring, True), 'Protocol': (basestring, True), } class SubscriptionResource(AWSObject): resource_type = "AWS::SNS::Subscription" props = { 'DeliveryPolicy': (dict, False), 'Endpoint': (basestring, False), 'FilterPolicy': (dict, False), 'Protocol': (basestring, True), 'RawMessageDelivery': (boolean, False), 'Region': (basestring, False), 'TopicArn': (basestring, True), } class TopicPolicy(AWSObject): resource_type = "AWS::SNS::TopicPolicy" props = { 'PolicyDocument': (policytypes, True), 'Topics': (list, True), } class Topic(AWSObject): resource_type = "AWS::SNS::Topic" props = { 'DisplayName': (basestring, False), 'KmsMasterKeyId': (basestring, False), 'Subscription': ([Subscription], False), 'Tags': (Tags, False), 'TopicName': (basestring, False), }
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty, Tags from .compat import policytypes from .validators import boolean class Subscription(AWSProperty): props = { 'Endpoint': (basestring, True), 'Protocol': (basestring, True), } class SubscriptionResource(AWSObject): resource_type = "AWS::SNS::Subscription" props = { 'DeliveryPolicy': (dict, False), 'Endpoint': (basestring, False), 'FilterPolicy': (dict, False), 'Protocol': (basestring, True), 'RawMessageDelivery': (boolean, False), 'RedrivePolicy': (dict, False), 'Region': (basestring, False), 'TopicArn': (basestring, True), } class TopicPolicy(AWSObject): resource_type = "AWS::SNS::TopicPolicy" props = { 'PolicyDocument': (policytypes, True), 'Topics': (list, True), } class Topic(AWSObject): resource_type = "AWS::SNS::Topic" props = { 'DisplayName': (basestring, False), 'KmsMasterKeyId': (basestring, False), 'Subscription': ([Subscription], False), 'Tags': (Tags, False), 'TopicName': (basestring, False), }
Update SNS per 2019-11-21 changes
Update SNS per 2019-11-21 changes
Python
bsd-2-clause
cloudtools/troposphere,ikben/troposphere,ikben/troposphere,cloudtools/troposphere
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty, Tags from .compat import policytypes from .validators import boolean class Subscription(AWSProperty): props = { 'Endpoint': (basestring, True), 'Protocol': (basestring, True), } class SubscriptionResource(AWSObject): resource_type = "AWS::SNS::Subscription" props = { 'DeliveryPolicy': (dict, False), 'Endpoint': (basestring, False), 'FilterPolicy': (dict, False), 'Protocol': (basestring, True), 'RawMessageDelivery': (boolean, False), 'RedrivePolicy': (dict, False), 'Region': (basestring, False), 'TopicArn': (basestring, True), } class TopicPolicy(AWSObject): resource_type = "AWS::SNS::TopicPolicy" props = { 'PolicyDocument': (policytypes, True), 'Topics': (list, True), } class Topic(AWSObject): resource_type = "AWS::SNS::Topic" props = { 'DisplayName': (basestring, False), 'KmsMasterKeyId': (basestring, False), 'Subscription': ([Subscription], False), 'Tags': (Tags, False), 'TopicName': (basestring, False), }
Update SNS per 2019-11-21 changes # Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty, Tags from .compat import policytypes from .validators import boolean class Subscription(AWSProperty): props = { 'Endpoint': (basestring, True), 'Protocol': (basestring, True), } class SubscriptionResource(AWSObject): resource_type = "AWS::SNS::Subscription" props = { 'DeliveryPolicy': (dict, False), 'Endpoint': (basestring, False), 'FilterPolicy': (dict, False), 'Protocol': (basestring, True), 'RawMessageDelivery': (boolean, False), 'Region': (basestring, False), 'TopicArn': (basestring, True), } class TopicPolicy(AWSObject): resource_type = "AWS::SNS::TopicPolicy" props = { 'PolicyDocument': (policytypes, True), 'Topics': (list, True), } class Topic(AWSObject): resource_type = "AWS::SNS::Topic" props = { 'DisplayName': (basestring, False), 'KmsMasterKeyId': (basestring, False), 'Subscription': ([Subscription], False), 'Tags': (Tags, False), 'TopicName': (basestring, False), }
d52c9731b0c6494e9f4181fc33f00cdf39adb3ca
tests/unit/test_util.py
tests/unit/test_util.py
import pytest from pmxbot import util @pytest.has_wordnik def test_lookup(): assert util.lookup('dachshund') is not None
import pytest from pmxbot import util @pytest.has_wordnik def test_lookup(): assert util.lookup('dachshund') is not None @pytest.has_internet def test_emergency_compliment(): assert util.load_emergency_compliments()
Add test for emergency compliments
Add test for emergency compliments
Python
mit
yougov/pmxbot,yougov/pmxbot,yougov/pmxbot
import pytest from pmxbot import util @pytest.has_wordnik def test_lookup(): assert util.lookup('dachshund') is not None @pytest.has_internet def test_emergency_compliment(): assert util.load_emergency_compliments()
Add test for emergency compliments import pytest from pmxbot import util @pytest.has_wordnik def test_lookup(): assert util.lookup('dachshund') is not None
4657acf6408b2fb416e2c9577ac09d18d81f8a68
nameless/config.py
nameless/config.py
import os _basedir = os.path.abspath(os.path.dirname(__file__)) # Plugin settings DATABASE_NAMES = ['atc', 'nhs', 'sms'] # Using sqlite for local development, will be SQL on production. SQLALCHEMY_BINDS = { 'atc': 'sqlite:///' + os.path.join(_basedir, 'db/atc.db'), 'nhs': 'sqlite:///' + os.path.join(_basedir, 'db/nhs.db'), 'sms': 'sqlite:///' + os.path.join(_basedir, 'db/sms.db') } # TxtLocal SMS settings SENDER = '447786202240' INBOX_ID = '498863' API_KEY = 'Sap3A0EaE2k-xL6d4nLJuQdZriNxBByUjRhOCHM5X0' API_URI = 'https://api.txtlocal.com/' API_SEND_URI = API_URI + 'send/?' API_RECEIVE_URI = API_URI + 'get_messages/?' TEST_MODE = 1 # 1 (True) to enable test mode & 0 to disable.
import os _basedir = os.path.abspath(os.path.dirname(__file__)) # Plugin settings DATABASE_NAMES = ['atc', 'sms'] # Using sqlite for local development, will be SQL on production. SQLALCHEMY_BINDS = { 'atc': 'sqlite:///' + os.path.join(_basedir, 'db/atc.db'), 'sms': 'sqlite:///' + os.path.join(_basedir, 'db/sms.db') } # TxtLocal SMS settings SENDER = '447786202240' INBOX_ID = '498863' API_KEY = 'Sap3A0EaE2k-xL6d4nLJuQdZriNxBByUjRhOCHM5X0' API_URI = 'https://api.txtlocal.com/' API_SEND_URI = API_URI + 'send/?' API_RECEIVE_URI = API_URI + 'get_messages/?' TEST_MODE = 1 # 1 (True) to enable test mode & 0 to disable.
Remove unused NHS database mockup
Remove unused NHS database mockup
Python
mit
jawrainey/sris
import os _basedir = os.path.abspath(os.path.dirname(__file__)) # Plugin settings DATABASE_NAMES = ['atc', 'sms'] # Using sqlite for local development, will be SQL on production. SQLALCHEMY_BINDS = { 'atc': 'sqlite:///' + os.path.join(_basedir, 'db/atc.db'), 'sms': 'sqlite:///' + os.path.join(_basedir, 'db/sms.db') } # TxtLocal SMS settings SENDER = '447786202240' INBOX_ID = '498863' API_KEY = 'Sap3A0EaE2k-xL6d4nLJuQdZriNxBByUjRhOCHM5X0' API_URI = 'https://api.txtlocal.com/' API_SEND_URI = API_URI + 'send/?' API_RECEIVE_URI = API_URI + 'get_messages/?' TEST_MODE = 1 # 1 (True) to enable test mode & 0 to disable.
Remove unused NHS database mockup import os _basedir = os.path.abspath(os.path.dirname(__file__)) # Plugin settings DATABASE_NAMES = ['atc', 'nhs', 'sms'] # Using sqlite for local development, will be SQL on production. SQLALCHEMY_BINDS = { 'atc': 'sqlite:///' + os.path.join(_basedir, 'db/atc.db'), 'nhs': 'sqlite:///' + os.path.join(_basedir, 'db/nhs.db'), 'sms': 'sqlite:///' + os.path.join(_basedir, 'db/sms.db') } # TxtLocal SMS settings SENDER = '447786202240' INBOX_ID = '498863' API_KEY = 'Sap3A0EaE2k-xL6d4nLJuQdZriNxBByUjRhOCHM5X0' API_URI = 'https://api.txtlocal.com/' API_SEND_URI = API_URI + 'send/?' API_RECEIVE_URI = API_URI + 'get_messages/?' TEST_MODE = 1 # 1 (True) to enable test mode & 0 to disable.
6c6934e8a36429e2a988835d8bd4d66fe95e306b
tensorflow_datasets/image/cifar_test.py
tensorflow_datasets/image/cifar_test.py
# coding=utf-8 # Copyright 2018 The TensorFlow Datasets Authors. # # 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. """Tests for cifar dataset module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_datasets.image import cifar from tensorflow_datasets.testing import dataset_builder_testing class Cifar10Test(dataset_builder_testing.TestCase): DATASET_CLASS = cifar.Cifar10 SPLITS = { "train": 10, # Number of examples. "test": 2, # See testing/generate_cifar10_like_example.py } if __name__ == "__main__": dataset_builder_testing.main()
# coding=utf-8 # Copyright 2018 The TensorFlow Datasets Authors. # # 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. """Tests for cifar dataset module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_datasets.image import cifar from tensorflow_datasets.testing import dataset_builder_testing class Cifar10Test(dataset_builder_testing.TestCase): DATASET_CLASS = cifar.Cifar10 SPLITS = { "train": 10, # Number of examples. "test": 2, # See testing/cifar10.py } if __name__ == "__main__": dataset_builder_testing.main()
Move references of deleted generate_cifar10_like_example.py to the new name cifar.py
Move references of deleted generate_cifar10_like_example.py to the new name cifar.py PiperOrigin-RevId: 225386826
Python
apache-2.0
tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets
# coding=utf-8 # Copyright 2018 The TensorFlow Datasets Authors. # # 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. """Tests for cifar dataset module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_datasets.image import cifar from tensorflow_datasets.testing import dataset_builder_testing class Cifar10Test(dataset_builder_testing.TestCase): DATASET_CLASS = cifar.Cifar10 SPLITS = { "train": 10, # Number of examples. "test": 2, # See testing/cifar10.py } if __name__ == "__main__": dataset_builder_testing.main()
Move references of deleted generate_cifar10_like_example.py to the new name cifar.py PiperOrigin-RevId: 225386826 # coding=utf-8 # Copyright 2018 The TensorFlow Datasets Authors. # # 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. """Tests for cifar dataset module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_datasets.image import cifar from tensorflow_datasets.testing import dataset_builder_testing class Cifar10Test(dataset_builder_testing.TestCase): DATASET_CLASS = cifar.Cifar10 SPLITS = { "train": 10, # Number of examples. "test": 2, # See testing/generate_cifar10_like_example.py } if __name__ == "__main__": dataset_builder_testing.main()
dcfb5116ba5f068afa354d063a4ab33bce853715
numba/sigutils.py
numba/sigutils.py
from __future__ import print_function, division, absolute_import from numba import types, typing def is_signature(sig): return isinstance(sig, (str, tuple)) def normalize_signature(sig): if isinstance(sig, str): return normalize_signature(parse_signature(sig)) elif isinstance(sig, tuple): return sig, None elif isinstance(sig, typing.Signature): return sig.args, sig.return_type else: raise TypeError(type(sig)) def parse_signature(signature_str): # Just eval signature_str using the types submodules as globals return eval(signature_str, {}, types.__dict__)
from __future__ import print_function, division, absolute_import from numba import types, typing def is_signature(sig): """ Return whether *sig* is a valid signature specification (for user-facing APIs). """ return isinstance(sig, (str, tuple, typing.Signature)) def normalize_signature(sig): """ From *sig* (a signature specification), return a ``(return_type, args)`` tuple, where ``args`` itself is a tuple of types, and ``return_type`` can be None if not specified. """ if isinstance(sig, str): return normalize_signature(parse_signature(sig)) elif isinstance(sig, tuple): return sig, None elif isinstance(sig, typing.Signature): return sig.args, sig.return_type else: raise TypeError(type(sig)) def parse_signature(signature_str): # Just eval signature_str using the types submodules as globals return eval(signature_str, {}, types.__dict__)
Add docstrings and fix failures
Add docstrings and fix failures
Python
bsd-2-clause
pitrou/numba,GaZ3ll3/numba,pitrou/numba,gdementen/numba,ssarangi/numba,gmarkall/numba,stonebig/numba,stonebig/numba,seibert/numba,GaZ3ll3/numba,gmarkall/numba,stonebig/numba,IntelLabs/numba,seibert/numba,pombredanne/numba,numba/numba,seibert/numba,jriehl/numba,pitrou/numba,numba/numba,stefanseefeld/numba,IntelLabs/numba,pombredanne/numba,ssarangi/numba,stonebig/numba,sklam/numba,stefanseefeld/numba,seibert/numba,cpcloud/numba,stuartarchibald/numba,gdementen/numba,stonebig/numba,numba/numba,stuartarchibald/numba,numba/numba,stuartarchibald/numba,ssarangi/numba,GaZ3ll3/numba,stuartarchibald/numba,cpcloud/numba,gdementen/numba,sklam/numba,GaZ3ll3/numba,jriehl/numba,pitrou/numba,IntelLabs/numba,sklam/numba,sklam/numba,jriehl/numba,pombredanne/numba,gdementen/numba,GaZ3ll3/numba,pombredanne/numba,sklam/numba,pombredanne/numba,gmarkall/numba,ssarangi/numba,IntelLabs/numba,jriehl/numba,cpcloud/numba,stefanseefeld/numba,gmarkall/numba,pitrou/numba,IntelLabs/numba,gdementen/numba,gmarkall/numba,jriehl/numba,stefanseefeld/numba,seibert/numba,ssarangi/numba,cpcloud/numba,numba/numba,stuartarchibald/numba,stefanseefeld/numba,cpcloud/numba
from __future__ import print_function, division, absolute_import from numba import types, typing def is_signature(sig): """ Return whether *sig* is a valid signature specification (for user-facing APIs). """ return isinstance(sig, (str, tuple, typing.Signature)) def normalize_signature(sig): """ From *sig* (a signature specification), return a ``(return_type, args)`` tuple, where ``args`` itself is a tuple of types, and ``return_type`` can be None if not specified. """ if isinstance(sig, str): return normalize_signature(parse_signature(sig)) elif isinstance(sig, tuple): return sig, None elif isinstance(sig, typing.Signature): return sig.args, sig.return_type else: raise TypeError(type(sig)) def parse_signature(signature_str): # Just eval signature_str using the types submodules as globals return eval(signature_str, {}, types.__dict__)
Add docstrings and fix failures from __future__ import print_function, division, absolute_import from numba import types, typing def is_signature(sig): return isinstance(sig, (str, tuple)) def normalize_signature(sig): if isinstance(sig, str): return normalize_signature(parse_signature(sig)) elif isinstance(sig, tuple): return sig, None elif isinstance(sig, typing.Signature): return sig.args, sig.return_type else: raise TypeError(type(sig)) def parse_signature(signature_str): # Just eval signature_str using the types submodules as globals return eval(signature_str, {}, types.__dict__)
cbdfc1b1cb4162256538576cabe2b6832aa83bca
django_mysqlpool/__init__.py
django_mysqlpool/__init__.py
from functools import wraps from django.db import connection def auto_close_db(f): "Ensures the database connection is closed when the function returns." @wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) finally: connection.close() return wrapper
from functools import wraps def auto_close_db(f): "Ensures the database connection is closed when the function returns." from django.db import connection @wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) finally: connection.close() return wrapper
Fix circular import when used with other add-ons that import django.db
Fix circular import when used with other add-ons that import django.db eg sorl_thumbnail: Traceback (most recent call last): File "/home/rpatterson/src/work/retrans/src/ReTransDjango/bin/manage", line 40, in <module> sys.exit(manage.main()) File "/home/rpatterson/src/work/retrans/src/ReTransDjango/retrans/manage.py", line 15, in main execute_manager(settings) File "/opt/src/eggs/Django-1.3-py2.7.egg/django/core/management/__init__.py", line 438, in execute_manager utility.execute() File "/opt/src/eggs/Django-1.3-py2.7.egg/django/core/management/__init__.py", line 379, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/src/eggs/Django-1.3-py2.7.egg/django/core/management/base.py", line 191, in run_from_argv self.execute(*args, **options.__dict__) File "/opt/src/eggs/Django-1.3-py2.7.egg/django/core/management/base.py", line 209, in execute translation.activate('en-us') File "/opt/src/eggs/Django-1.3-py2.7.egg/django/utils/translation/__init__.py", line 100, in activate return _trans.activate(language) File "/opt/src/eggs/Django-1.3-py2.7.egg/django/utils/translation/trans_real.py", line 202, in activate _active.value = translation(language) File "/opt/src/eggs/Django-1.3-py2.7.egg/django/utils/translation/trans_real.py", line 185, in translation default_translation = _fetch(settings.LANGUAGE_CODE) File "/opt/src/eggs/Django-1.3-py2.7.egg/django/utils/translation/trans_real.py", line 162, in _fetch app = import_module(appname) File "/opt/src/eggs/Django-1.3-py2.7.egg/django/utils/importlib.py", line 35, in import_module __import__(name) File "/opt/src/eggs/sorl_thumbnail-11.12-py2.7.egg/sorl/thumbnail/__init__.py", line 1, in <module> from sorl.thumbnail.fields import ImageField File "/opt/src/eggs/sorl_thumbnail-11.12-py2.7.egg/sorl/thumbnail/fields.py", line 2, in <module> from django.db import models File "/opt/src/eggs/Django-1.3-py2.7.egg/django/db/__init__.py", line 78, in <module> connection = connections[DEFAULT_DB_ALIAS] File "/opt/src/eggs/Django-1.3-py2.7.egg/django/db/utils.py", line 94, in __getitem__ backend = load_backend(db['ENGINE']) File "/opt/src/eggs/Django-1.3-py2.7.egg/django/db/utils.py", line 47, in load_backend if backend_name not in available_backends: django.core.exceptions.ImproperlyConfigured: 'django_mysqlpool.backends.mysqlpool' isn't an available database backend. Try using django.db.backends.XXX, where XXX is one of: 'dummy', 'mysql', 'oracle', 'postgresql', 'postgresql_psycopg2', 'sqlite3' Error was: cannot import name connection
Python
mit
smartfile/django-mysqlpool
from functools import wraps def auto_close_db(f): "Ensures the database connection is closed when the function returns." from django.db import connection @wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) finally: connection.close() return wrapper
Fix circular import when used with other add-ons that import django.db eg sorl_thumbnail: Traceback (most recent call last): File "/home/rpatterson/src/work/retrans/src/ReTransDjango/bin/manage", line 40, in <module> sys.exit(manage.main()) File "/home/rpatterson/src/work/retrans/src/ReTransDjango/retrans/manage.py", line 15, in main execute_manager(settings) File "/opt/src/eggs/Django-1.3-py2.7.egg/django/core/management/__init__.py", line 438, in execute_manager utility.execute() File "/opt/src/eggs/Django-1.3-py2.7.egg/django/core/management/__init__.py", line 379, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/src/eggs/Django-1.3-py2.7.egg/django/core/management/base.py", line 191, in run_from_argv self.execute(*args, **options.__dict__) File "/opt/src/eggs/Django-1.3-py2.7.egg/django/core/management/base.py", line 209, in execute translation.activate('en-us') File "/opt/src/eggs/Django-1.3-py2.7.egg/django/utils/translation/__init__.py", line 100, in activate return _trans.activate(language) File "/opt/src/eggs/Django-1.3-py2.7.egg/django/utils/translation/trans_real.py", line 202, in activate _active.value = translation(language) File "/opt/src/eggs/Django-1.3-py2.7.egg/django/utils/translation/trans_real.py", line 185, in translation default_translation = _fetch(settings.LANGUAGE_CODE) File "/opt/src/eggs/Django-1.3-py2.7.egg/django/utils/translation/trans_real.py", line 162, in _fetch app = import_module(appname) File "/opt/src/eggs/Django-1.3-py2.7.egg/django/utils/importlib.py", line 35, in import_module __import__(name) File "/opt/src/eggs/sorl_thumbnail-11.12-py2.7.egg/sorl/thumbnail/__init__.py", line 1, in <module> from sorl.thumbnail.fields import ImageField File "/opt/src/eggs/sorl_thumbnail-11.12-py2.7.egg/sorl/thumbnail/fields.py", line 2, in <module> from django.db import models File "/opt/src/eggs/Django-1.3-py2.7.egg/django/db/__init__.py", line 78, in <module> connection = connections[DEFAULT_DB_ALIAS] File "/opt/src/eggs/Django-1.3-py2.7.egg/django/db/utils.py", line 94, in __getitem__ backend = load_backend(db['ENGINE']) File "/opt/src/eggs/Django-1.3-py2.7.egg/django/db/utils.py", line 47, in load_backend if backend_name not in available_backends: django.core.exceptions.ImproperlyConfigured: 'django_mysqlpool.backends.mysqlpool' isn't an available database backend. Try using django.db.backends.XXX, where XXX is one of: 'dummy', 'mysql', 'oracle', 'postgresql', 'postgresql_psycopg2', 'sqlite3' Error was: cannot import name connection from functools import wraps from django.db import connection def auto_close_db(f): "Ensures the database connection is closed when the function returns." @wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) finally: connection.close() return wrapper
cbb90d03b83a495b1c46514a583538f2cfc0d29c
test/functional/test_manager.py
test/functional/test_manager.py
from osmviz.manager import PILImageManager, OSMManager import PIL.Image as Image def test_pil(): imgr = PILImageManager("RGB") osm = OSMManager(image_manager=imgr) image, bnds = osm.createOSMImage((30, 35, -117, -112), 9) wh_ratio = float(image.size[0]) / image.size[1] image2 = image.resize((int(800 * wh_ratio), 800), Image.ANTIALIAS) del image image2.show() if __name__ == "__main__": test_pil() # End of file
from osmviz.manager import PILImageManager, OSMManager import PIL.Image as Image def test_pil(): image_manager = PILImageManager("RGB") osm = OSMManager(image_manager=image_manager) image, bounds = osm.createOSMImage((30, 31, -117, -116), 9) wh_ratio = float(image.size[0]) / image.size[1] image2 = image.resize((int(800 * wh_ratio), 800), Image.ANTIALIAS) del image image2.show() if __name__ == "__main__": test_pil() # End of file
Reduce number of tiles downloaded
Reduce number of tiles downloaded
Python
mit
hugovk/osmviz,hugovk/osmviz
from osmviz.manager import PILImageManager, OSMManager import PIL.Image as Image def test_pil(): image_manager = PILImageManager("RGB") osm = OSMManager(image_manager=image_manager) image, bounds = osm.createOSMImage((30, 31, -117, -116), 9) wh_ratio = float(image.size[0]) / image.size[1] image2 = image.resize((int(800 * wh_ratio), 800), Image.ANTIALIAS) del image image2.show() if __name__ == "__main__": test_pil() # End of file
Reduce number of tiles downloaded from osmviz.manager import PILImageManager, OSMManager import PIL.Image as Image def test_pil(): imgr = PILImageManager("RGB") osm = OSMManager(image_manager=imgr) image, bnds = osm.createOSMImage((30, 35, -117, -112), 9) wh_ratio = float(image.size[0]) / image.size[1] image2 = image.resize((int(800 * wh_ratio), 800), Image.ANTIALIAS) del image image2.show() if __name__ == "__main__": test_pil() # End of file
42a92130fc9d6f3358bb03a7ab56cdc5f20eb4d1
tests/test_config.py
tests/test_config.py
import os import pytest from vrun import config from vrun.compat import ConfigParser @pytest.mark.parametrize('parts, result', [ ( ['simple'], ['simple'] ), ( ['multiple', 'simple'], ['multiple', 'simple'] ), ( ['with', '"quotes"'], ['with', '"quotes"'] ), ( ['"testing', 'quote', 'support"'], ['testing quote support'] ), ( ["'testing", 'quote', "support'"], ['testing quote support'] ), ( ['"testing', '\'quote', 'support"'], ['testing \'quote support'] ), ( ['"testing', '\'quote\'', 'support"'], ['testing \'quote\' support'] ), ( ['"testing', '\'quote', '\'support"'], ['testing \'quote \'support'] ), ( ['""'], ['""'] ), ( ['" ', ' "'], [' '] ), ]) def test_quoted_combine(parts, result): assert list(config.quoted_combine(parts)) == result @pytest.mark.parametrize('parts', [ ['"testing', '\'quote', '"support"'], ['" ', '""'], ['"test', '"ing'], ]) def test_quoted_combine_invalid(parts): with pytest.raises(ValueError): assert list(config.quoted_combine(parts)) @pytest.mark.parametrize('folder, result', [ ('configtest', 'vrun.cfg'), ('configtest/vrun_ini', 'vrun.ini'), ('configtest/setup_cfg', 'setup.cfg'), ('configtest/setup_cfg_no_section', None), ]) def test_find_config(folder, result): curpath = os.path.dirname(os.path.realpath(__file__)) cwd = os.path.join(curpath, folder) if result: assert config.find_config(cwd).endswith(result) else: assert config.find_config(cwd) == result @pytest.mark.parametrize('folder, result', [ ('configtest', 'vrun.cfg'), ('configtest/vrun_ini', 'vrun.ini'), ('configtest/setup_cfg', 'setup.cfg'), ]) def test_config_from_file(folder, result): curpath = os.path.dirname(os.path.realpath(__file__)) cwd = os.path.join(curpath, folder) config_file = config.find_config(cwd) assert isinstance(config.config_from_file(config_file), ConfigParser)
Add tests for ancillary functions
Add tests for ancillary functions
Python
isc
bertjwregeer/vrun
import os import pytest from vrun import config from vrun.compat import ConfigParser @pytest.mark.parametrize('parts, result', [ ( ['simple'], ['simple'] ), ( ['multiple', 'simple'], ['multiple', 'simple'] ), ( ['with', '"quotes"'], ['with', '"quotes"'] ), ( ['"testing', 'quote', 'support"'], ['testing quote support'] ), ( ["'testing", 'quote', "support'"], ['testing quote support'] ), ( ['"testing', '\'quote', 'support"'], ['testing \'quote support'] ), ( ['"testing', '\'quote\'', 'support"'], ['testing \'quote\' support'] ), ( ['"testing', '\'quote', '\'support"'], ['testing \'quote \'support'] ), ( ['""'], ['""'] ), ( ['" ', ' "'], [' '] ), ]) def test_quoted_combine(parts, result): assert list(config.quoted_combine(parts)) == result @pytest.mark.parametrize('parts', [ ['"testing', '\'quote', '"support"'], ['" ', '""'], ['"test', '"ing'], ]) def test_quoted_combine_invalid(parts): with pytest.raises(ValueError): assert list(config.quoted_combine(parts)) @pytest.mark.parametrize('folder, result', [ ('configtest', 'vrun.cfg'), ('configtest/vrun_ini', 'vrun.ini'), ('configtest/setup_cfg', 'setup.cfg'), ('configtest/setup_cfg_no_section', None), ]) def test_find_config(folder, result): curpath = os.path.dirname(os.path.realpath(__file__)) cwd = os.path.join(curpath, folder) if result: assert config.find_config(cwd).endswith(result) else: assert config.find_config(cwd) == result @pytest.mark.parametrize('folder, result', [ ('configtest', 'vrun.cfg'), ('configtest/vrun_ini', 'vrun.ini'), ('configtest/setup_cfg', 'setup.cfg'), ]) def test_config_from_file(folder, result): curpath = os.path.dirname(os.path.realpath(__file__)) cwd = os.path.join(curpath, folder) config_file = config.find_config(cwd) assert isinstance(config.config_from_file(config_file), ConfigParser)
Add tests for ancillary functions
20fa7e30e4658984a4057f5c99ef293216f57815
base_phone/controllers/main.py
base_phone/controllers/main.py
# -*- coding: utf-8 -*- ############################################################################## # # Base Phone module for Odoo # Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from odoo import http class BasePhoneController(http.Controller): @http.route('/base_phone/click2dial', type='json', auth='none') def click2dial(self, phone_number, click2dial_model, click2dial_id): res = http.request.env['phone.common'].click2dial( phone_number, { 'click2dial_model': click2dial_model, 'click2dial_id': click2dial_id, }) return res
# -*- coding: utf-8 -*- ############################################################################## # # Base Phone module for Odoo # Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from odoo import http class BasePhoneController(http.Controller): @http.route('/base_phone/click2dial', type='json', auth='user') def click2dial(self, phone_number, click2dial_model, click2dial_id): res = http.request.env['phone.common'].with_context( click2dial_model=click2dial_model, click2dial_id=click2dial_id).click2dial(phone_number) return res
Make click2dial work in real life
Make click2dial work in real life
Python
agpl-3.0
OCA/connector-telephony,OCA/connector-telephony,OCA/connector-telephony,OCA/connector-telephony
# -*- coding: utf-8 -*- ############################################################################## # # Base Phone module for Odoo # Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from odoo import http class BasePhoneController(http.Controller): @http.route('/base_phone/click2dial', type='json', auth='user') def click2dial(self, phone_number, click2dial_model, click2dial_id): res = http.request.env['phone.common'].with_context( click2dial_model=click2dial_model, click2dial_id=click2dial_id).click2dial(phone_number) return res
Make click2dial work in real life # -*- coding: utf-8 -*- ############################################################################## # # Base Phone module for Odoo # Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from odoo import http class BasePhoneController(http.Controller): @http.route('/base_phone/click2dial', type='json', auth='none') def click2dial(self, phone_number, click2dial_model, click2dial_id): res = http.request.env['phone.common'].click2dial( phone_number, { 'click2dial_model': click2dial_model, 'click2dial_id': click2dial_id, }) return res
f499f58c765cbd83e77e44be1dfbccc3aed772c6
mozillians/users/management/commands/reindex_mozillians.py
mozillians/users/management/commands/reindex_mozillians.py
from django.core.management.base import BaseCommand from mozillians.users.tasks import index_all_profiles class Command(BaseCommand): def handle(self, *args, **options): index_all_profiles()
Add management command to reindex mozillians ES.
Add management command to reindex mozillians ES.
Python
bsd-3-clause
akatsoulas/mozillians,mozilla/mozillians,johngian/mozillians,mozilla/mozillians,mozilla/mozillians,johngian/mozillians,akatsoulas/mozillians,johngian/mozillians,akatsoulas/mozillians,mozilla/mozillians,akatsoulas/mozillians,johngian/mozillians
from django.core.management.base import BaseCommand from mozillians.users.tasks import index_all_profiles class Command(BaseCommand): def handle(self, *args, **options): index_all_profiles()
Add management command to reindex mozillians ES.
469fdc0dfc756e68231eebd5ce40eb33e0fdd2f2
fireplace/cards/gvg/rogue.py
fireplace/cards/gvg/rogue.py
from ..utils import * ## # Minions # Goblin Auto-Barber class GVG_023: action = buffWeapon("GVG_023a") ## # Spells # Tinker's Sharpsword Oil class GVG_022: action = buffWeapon("GVG_022a") def action(self): if self.controller.weapon: self.buff(self.controller.weapon, "GVG_022a") if self.controller.field: self.buff(random.choice(self.controller.field), "GVG_022b") ## # Weapons # Cogmaster's Wrench class GVG_024: def atk(self, i): if self.controller.field.filter(race=Race.MECHANICAL): return i + 2 return i
from ..utils import * ## # Minions # Goblin Auto-Barber class GVG_023: action = buffWeapon("GVG_023a") # One-eyed Cheat class GVG_025: def OWN_MINION_SUMMON(self, player, minion): if minion.race == Race.PIRATE and minion != self: self.stealth = True # Iron Sensei class GVG_027: def OWN_TURN_END(self): mechs = self.controller.field.filter(race=Race.MECHANICAL).exclude(self) if mechs: self.buff(random.choice(mechs), "GVG_027e") # Trade Prince Gallywix class GVG_028: def CARD_PLAYED(self, player, card): if player is not self.controller and card.type == CardType.SPELL: if card.id != "GVG_028t": player.opponent.give(card.id) player.give("GVG_028t") class GVG_028t: def action(self): self.controller.tempMana += 1 ## # Spells # Tinker's Sharpsword Oil class GVG_022: action = buffWeapon("GVG_022a") def action(self): if self.controller.weapon: self.buff(self.controller.weapon, "GVG_022a") if self.controller.field: self.buff(random.choice(self.controller.field), "GVG_022b") ## # Weapons # Cogmaster's Wrench class GVG_024: def atk(self, i): if self.controller.field.filter(race=Race.MECHANICAL): return i + 2 return i
Implement One-eyed Cheat, Iron Sensei and Trade Prince Gallywix
Implement One-eyed Cheat, Iron Sensei and Trade Prince Gallywix
Python
agpl-3.0
beheh/fireplace,oftc-ftw/fireplace,Meerkov/fireplace,NightKev/fireplace,smallnamespace/fireplace,jleclanche/fireplace,butozerca/fireplace,liujimj/fireplace,Ragowit/fireplace,liujimj/fireplace,smallnamespace/fireplace,amw2104/fireplace,amw2104/fireplace,Meerkov/fireplace,oftc-ftw/fireplace,butozerca/fireplace,Ragowit/fireplace
from ..utils import * ## # Minions # Goblin Auto-Barber class GVG_023: action = buffWeapon("GVG_023a") # One-eyed Cheat class GVG_025: def OWN_MINION_SUMMON(self, player, minion): if minion.race == Race.PIRATE and minion != self: self.stealth = True # Iron Sensei class GVG_027: def OWN_TURN_END(self): mechs = self.controller.field.filter(race=Race.MECHANICAL).exclude(self) if mechs: self.buff(random.choice(mechs), "GVG_027e") # Trade Prince Gallywix class GVG_028: def CARD_PLAYED(self, player, card): if player is not self.controller and card.type == CardType.SPELL: if card.id != "GVG_028t": player.opponent.give(card.id) player.give("GVG_028t") class GVG_028t: def action(self): self.controller.tempMana += 1 ## # Spells # Tinker's Sharpsword Oil class GVG_022: action = buffWeapon("GVG_022a") def action(self): if self.controller.weapon: self.buff(self.controller.weapon, "GVG_022a") if self.controller.field: self.buff(random.choice(self.controller.field), "GVG_022b") ## # Weapons # Cogmaster's Wrench class GVG_024: def atk(self, i): if self.controller.field.filter(race=Race.MECHANICAL): return i + 2 return i
Implement One-eyed Cheat, Iron Sensei and Trade Prince Gallywix from ..utils import * ## # Minions # Goblin Auto-Barber class GVG_023: action = buffWeapon("GVG_023a") ## # Spells # Tinker's Sharpsword Oil class GVG_022: action = buffWeapon("GVG_022a") def action(self): if self.controller.weapon: self.buff(self.controller.weapon, "GVG_022a") if self.controller.field: self.buff(random.choice(self.controller.field), "GVG_022b") ## # Weapons # Cogmaster's Wrench class GVG_024: def atk(self, i): if self.controller.field.filter(race=Race.MECHANICAL): return i + 2 return i