commit
stringlengths 40
40
| old_file
stringlengths 4
264
| new_file
stringlengths 4
264
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
624
| message
stringlengths 15
4.7k
| lang
stringclasses 3
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
---|---|---|---|---|---|---|---|---|---|
64a653b6bd6c9aae2492f3ee838bda1fafe639d6
|
upnpy/utils.py
|
upnpy/utils.py
|
# -*- coding: utf-8 -*-
"""
utils.py
~~~~~~~~
Defines utility functions used by UPnPy.
"""
def camelcase_to_underscore(text):
"""
Convert a camelCasedString to one separated_by_underscores. Treats
neighbouring capitals as acronyms and doesn't separated them, e.g. URL does
not become u_r_l. That would be stupid.
:param text: The string to convert.
"""
outstr = []
for char in text:
if char.is_lower():
outstr.append(char)
elif outstr[-1].is_lower():
outstr.append('_')
outstr.append(char.lower())
else:
outstr.append(char.lower())
return ''.join(outstr)
|
# -*- coding: utf-8 -*-
"""
utils.py
~~~~~~~~
Defines utility functions used by UPnPy.
"""
def camelcase_to_underscore(text):
"""
Convert a camelCasedString to one separated_by_underscores. Treats
neighbouring capitals as acronyms and doesn't separated them, e.g. URL does
not become u_r_l. That would be stupid.
:param text: The string to convert.
"""
outstr = []
for char in text:
if char.islower():
outstr.append(char)
elif (len(outstr) > 0) and (outstr[-1].islower()):
outstr.append('_')
outstr.append(char.lower())
else:
outstr.append(char.lower())
return ''.join(outstr)
|
Correct an AttributeError and a potential IndexErr
|
Correct an AttributeError and a potential IndexErr
|
Python
|
mit
|
WenhaoYu/upnpy,Lukasa/upnpy
|
705aab2107793d1067d571b71bc140c320d69aae
|
bot/api/api.py
|
bot/api/api.py
|
from bot.api.telegram import TelegramBotApi
from bot.storage import State
class Api:
def __init__(self, telegram_api: TelegramBotApi, state: State):
self.telegram_api = telegram_api
self.state = state
def get_me(self):
return self.telegram_api.get_me()
def send_message(self, message):
return self.telegram_api.send_message(chat_id=message.chat.id, text=message.text,
reply_to_message_id=message.reply_to_message_id)
def get_pending_updates(self):
yield from self.get_updates(timeout=0)
def get_updates(self, timeout=45):
updates = self.telegram_api.get_updates(offset=self.__get_updates_offset(), timeout=timeout)
for update in updates:
self.__set_updates_offset(update.update_id)
yield update
def __get_updates_offset(self):
return self.state.next_update_id
def __set_updates_offset(self, last_update_id):
self.state.next_update_id = str(last_update_id + 1)
|
from bot.api.telegram import TelegramBotApi
from bot.storage import State
class Api:
def __init__(self, telegram_api: TelegramBotApi, state: State):
self.telegram_api = telegram_api
self.state = state
def get_me(self):
return self.telegram_api.get_me()
def send_message(self, message):
return self.telegram_api.send_message(chat_id=message.chat.id, text=message.text,
reply_to_message_id=message.reply_to_message_id)
def get_pending_updates(self):
return self.get_updates(timeout=0)
def get_updates(self, timeout=45):
updates = self.telegram_api.get_updates(offset=self.__get_updates_offset(), timeout=timeout)
for update in updates:
self.__set_updates_offset(update.update_id)
yield update
def __get_updates_offset(self):
return self.state.next_update_id
def __set_updates_offset(self, last_update_id):
self.state.next_update_id = str(last_update_id + 1)
|
Change yield from to return to be compatible with python 3.2
|
Change yield from to return to be compatible with python 3.2
|
Python
|
agpl-3.0
|
alvarogzp/telegram-bot,alvarogzp/telegram-bot
|
41c49a44c5f1bc9747b22b6d1f1088f1354a2cd5
|
nes/cpu/decoder.py
|
nes/cpu/decoder.py
|
from sqlite3 import Connection, Row
class Decoder:
def __init__(self):
self.conn = Connection('nes.sqlite')
self.conn.row_factory = Row
def __del__(self):
self.conn.close()
def decode(self, opcode):
c = self.conn.cursor()
c.execute('select * from instruction where opcode=?', [opcode])
row = c.fetchone()
return dict(zip(row.keys(), row))
|
from sqlite3 import Connection, Row
class Decoder:
def __init__(self):
self.conn = Connection('nes.sqlite')
self.conn.row_factory = Row
def __del__(self):
self.conn.close()
def decode(self, opcode):
c = self.conn.cursor()
c.execute('select * from instruction where opcode=?', [opcode])
row = c.fetchone()
if row:
return dict(zip(row.keys(), row))
else:
raise NotImplementedError('Undocumented Opcode: ' + str(opcode))
|
Raise an exception when it's an undocumented opcode.
|
Raise an exception when it's an undocumented opcode.
|
Python
|
mit
|
Hexadorsimal/pynes
|
6829e9b4cf87b8d8d8b6e5a1c3aaf881f66393cf
|
healthcheck/contrib/django/status_endpoint/views.py
|
healthcheck/contrib/django/status_endpoint/views.py
|
import json
from django.conf import settings
from django.views.decorators.http import require_http_methods
from django.http import HttpResponse
from healthcheck.healthcheck import (
DjangoDBsHealthCheck, FilesDontExistHealthCheck, HealthChecker)
class JsonResponse(HttpResponse):
def __init__(self, data, **kwargs):
kwargs.setdefault('content_type', 'application/json')
data = json.dumps(data)
super(JsonResponse, self).__init__(content=data, **kwargs)
class JsonResponseServerError(JsonResponse):
status_code = 500
@require_http_methods(['GET'])
def status(request):
checks = []
if getattr(settings, 'STATUS_CHECK_DBS', True):
checks.append(DjangoDBsHealthCheck())
files_to_check = getattr(settings, 'STATUS_CHECK_FILES', None)
if files_to_check:
checks.append(FilesDontExistHealthCheck(
files_to_check, check_id="quiesce file doesn't exist"))
ok, details = HealthChecker(checks)()
if ok and not details:
details = 'There were no checks.'
if not ok:
return JsonResponseServerError(json.dumps(details))
return JsonResponse(details)
|
import json
from django.conf import settings
from django.views.decorators.http import require_http_methods
from django.http import HttpResponse
from healthcheck.healthcheck import (
DjangoDBsHealthCheck, FilesDontExistHealthCheck, HealthChecker)
class JsonResponse(HttpResponse):
def __init__(self, data, **kwargs):
kwargs.setdefault('content_type', 'application/json')
data = json.dumps(data)
super(JsonResponse, self).__init__(content=data, **kwargs)
class JsonResponseServerError(JsonResponse):
status_code = 500
@require_http_methods(['GET'])
def status(request):
checks = []
if getattr(settings, 'STATUS_CHECK_DBS', True):
checks.append(DjangoDBsHealthCheck())
files_to_check = getattr(settings, 'STATUS_CHECK_FILES', None)
if files_to_check:
checks.append(FilesDontExistHealthCheck(
files_to_check, check_id="quiesce file doesn't exist"))
ok, details = HealthChecker(checks)()
if ok and not details:
details = 'There were no checks.'
if not ok:
return JsonResponseServerError(details)
return JsonResponse(details)
|
Remove duplicated JSON encoding for error messages
|
Remove duplicated JSON encoding for error messages
|
Python
|
mit
|
yola/healthcheck
|
df6f82dc8d6f429ec57dffb60e336253a062769b
|
angus/client/version.py
|
angus/client/version.py
|
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
__version__ = "0.0.15rc1"
|
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
__version__ = "0.0.15rc2"
|
Prepare a second release candidate for 0.0.15
|
Prepare a second release candidate for 0.0.15
|
Python
|
apache-2.0
|
angus-ai/angus-sdk-python
|
089e8c74106f3a19b229d085d73c932df6fe4e7d
|
application.py
|
application.py
|
from canis import siriusxm, spotify, oauth
def main():
try:
current = siriusxm.get_currently_playing('siriusxmu')
spotify_id = spotify.id_for_song(current)
print(current, spotify_id)
except Exception, e:
print "Error {}".format(e)
if __name__ == "__main__":
oauth.app.run(debug=True)
main()
|
from canis import siriusxm, spotify, oauth
def main():
try:
current = siriusxm.get_currently_playing('siriusxmu')
spotify_id = spotify.id_for_song(current)
print(current, spotify_id)
except Exception, e:
print "Error {}".format(e)
if __name__ == "__main__":
oauth.app.run()
main()
|
Remove debug mode on flask
|
Remove debug mode on flask
|
Python
|
mit
|
maxgoedjen/canis
|
697833caade1323ddb9a0b4e51031f1d494262cd
|
201705/migonzalvar/biggest_set.py
|
201705/migonzalvar/biggest_set.py
|
#!/usr/bin/env python3
from contextlib import contextmanager
import time
from main import has_subset_sum_zero
class Duration:
def __init__(self, elapsed=None):
self.elapsed = elapsed
@contextmanager
def less_than(secs):
duration = Duration()
tic = time.time()
yield duration
elapsed = time.time() - tic
print(f'Duration: {elapsed} seconds')
if elapsed >= secs:
print('Limit reached. Stopping.')
raise SystemExit(0)
def do():
for n in range(1, 100, 10):
source = range(1, n)
print(f'Length: {n} items')
with less_than(300):
result = has_subset_sum_zero(source)
print(f'Result: {result}')
print('Continue...')
print()
if __name__ == '__main__':
do()
|
#!/usr/bin/env python3
from contextlib import contextmanager
import time
from main import has_subset_sum_zero
class Duration:
def __init__(self, elapsed=None):
self.elapsed = elapsed
@contextmanager
def less_than(secs):
duration = Duration()
tic = time.time()
yield duration
elapsed = time.time() - tic
duration.elapsed = elapsed
def nosolution_case(N):
return range(1, N + 1)
def negative_worst_case(N):
case = list(range(-N + 1, 0))
case += [abs(sum(case))]
return case
def positive_worst_case(N):
case = list(range(1, N))
case.insert(0, - sum(case))
return case
def do():
strategies = [nosolution_case, negative_worst_case, positive_worst_case]
for strategy in strategies:
print(f'## Using {strategy.__name__}')
print()
for n in range(1, 100, 10):
source = range(1, n)
print(f'Length: {n} items')
with less_than(300) as duration:
result = has_subset_sum_zero(source)
print(f'Result: {result}')
print(f'Duration: {duration.elapsed} seconds')
if duration.elapsed >= secs:
print('Limit reached. Stopping.')
break
print('Continue searching...')
print()
if __name__ == '__main__':
do()
|
Use several strategies for performance
|
Use several strategies for performance
|
Python
|
bsd-3-clause
|
VigoTech/reto,VigoTech/reto,VigoTech/reto,VigoTech/reto,VigoTech/reto,VigoTech/reto,VigoTech/reto,vigojug/reto,vigojug/reto,vigojug/reto,vigojug/reto,VigoTech/reto,vigojug/reto,vigojug/reto,vigojug/reto,vigojug/reto,VigoTech/reto,VigoTech/reto,vigojug/reto,vigojug/reto
|
0c785e349c2000bbf3b22671071a66eaca4d82d0
|
astropy/io/votable/__init__.py
|
astropy/io/votable/__init__.py
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This package reads and writes data formats used by the Virtual
Observatory (VO) initiative, particularly the VOTable XML format.
"""
from .table import (
parse, parse_single_table, validate, from_table, is_votable)
from .exceptions import (
VOWarning, VOTableChangeWarning, VOTableSpecWarning, UnimplementedWarning,
IOWarning, VOTableSpecError)
__all__ = [
'parse', 'parse_single_table', 'validate', 'from_table',
'is_votable', 'VOWarning', 'VOTableChangeWarning', 'VOTableSpecWarning',
'UnimplementedWarning', 'IOWarning', 'VOTableSpecError']
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This package reads and writes data formats used by the Virtual
Observatory (VO) initiative, particularly the VOTable XML format.
"""
from .table import (
parse, parse_single_table, validate, from_table, is_votable, writeto)
from .exceptions import (
VOWarning, VOTableChangeWarning, VOTableSpecWarning, UnimplementedWarning,
IOWarning, VOTableSpecError)
__all__ = [
'parse', 'parse_single_table', 'validate', 'from_table',
'is_votable', 'writeto', 'VOWarning', 'VOTableChangeWarning',
'VOTableSpecWarning', 'UnimplementedWarning', 'IOWarning',
'VOTableSpecError']
|
Put astropy.io.votable.writeto in the top-level namespace
|
Put astropy.io.votable.writeto in the top-level namespace
|
Python
|
bsd-3-clause
|
DougBurke/astropy,AustereCuriosity/astropy,funbaker/astropy,joergdietrich/astropy,StuartLittlefair/astropy,larrybradley/astropy,tbabej/astropy,mhvk/astropy,pllim/astropy,stargaser/astropy,lpsinger/astropy,joergdietrich/astropy,lpsinger/astropy,AustereCuriosity/astropy,kelle/astropy,saimn/astropy,DougBurke/astropy,bsipocz/astropy,mhvk/astropy,pllim/astropy,StuartLittlefair/astropy,astropy/astropy,saimn/astropy,dhomeier/astropy,StuartLittlefair/astropy,tbabej/astropy,joergdietrich/astropy,larrybradley/astropy,aleksandr-bakanov/astropy,funbaker/astropy,lpsinger/astropy,tbabej/astropy,AustereCuriosity/astropy,larrybradley/astropy,larrybradley/astropy,kelle/astropy,lpsinger/astropy,dhomeier/astropy,bsipocz/astropy,bsipocz/astropy,pllim/astropy,astropy/astropy,lpsinger/astropy,StuartLittlefair/astropy,joergdietrich/astropy,kelle/astropy,pllim/astropy,astropy/astropy,aleksandr-bakanov/astropy,MSeifert04/astropy,joergdietrich/astropy,stargaser/astropy,saimn/astropy,tbabej/astropy,AustereCuriosity/astropy,aleksandr-bakanov/astropy,mhvk/astropy,saimn/astropy,mhvk/astropy,dhomeier/astropy,DougBurke/astropy,dhomeier/astropy,funbaker/astropy,DougBurke/astropy,funbaker/astropy,mhvk/astropy,MSeifert04/astropy,larrybradley/astropy,stargaser/astropy,stargaser/astropy,bsipocz/astropy,kelle/astropy,saimn/astropy,astropy/astropy,dhomeier/astropy,aleksandr-bakanov/astropy,kelle/astropy,MSeifert04/astropy,MSeifert04/astropy,astropy/astropy,tbabej/astropy,StuartLittlefair/astropy,pllim/astropy,AustereCuriosity/astropy
|
fb1f03c7d46d9274f144a767830cf9c81078e8c8
|
kovfig.py
|
kovfig.py
|
#! /usr/bin/env python
# coding:utf-8
from os import path
# the number of loop for train IBM Model 2
loop_count = 10
phrase_model_file = path.join(
path.abspath(path.dirname(__file__)),
"phrase.model"
)
bigram_model_file = path.join(
path.abspath(path.dirname(__file__)),
"bigram.model"
)
if __name__ == '__main__':
print("{} = {}".format(
"loop_count",
loop_count))
print("{} = {}".format(
"phrase_model_file",
phrase_model_file))
print("{} = {}".format(
"bigram_model_file",
bigram_model_file))
|
#! /usr/bin/env python
# coding:utf-8
from os import path
# the number of loop for train IBM Model 2
LOOP_COUNT = 10
PHRASE_MODEL_FILE = path.join(
path.abspath(path.dirname(__file__)),
"phrase.model"
)
BIGRAM_MODEL_FILE = path.join(
path.abspath(path.dirname(__file__)),
"bigram.model"
)
if __name__ == '__main__':
print("{} = {}".format(
"LOOP_COUNT",
LOOP_COUNT))
print("{} = {}".format(
"phrase_model_file",
PHRASE_MODEL_FILE))
print("{} = {}".format(
"bigram_model_file",
BIGRAM_MODEL_FILE))
|
Use upper case variable for global vars
|
Use upper case variable for global vars
|
Python
|
mit
|
kenkov/kovlive
|
b9b9382a62b00aa00255fbc9271ef5ec2db8c295
|
fabfile.py
|
fabfile.py
|
from fabric.api import (
cd,
env,
put,
run,
sudo,
task
)
PRODUCTION_IP = '54.154.235.243'
PROJECT_DIRECTORY = '/home/ubuntu/ztm/'
COMPOSE_FILE = 'compose-production.yml'
@task
def production():
env.run = sudo
env.hosts = [
'ubuntu@' + PRODUCTION_IP + ':22',
]
def create_project_directory():
run('mkdir -p ' + PROJECT_DIRECTORY)
def update_compose_file():
put('./' + COMPOSE_FILE, PROJECT_DIRECTORY)
@task
def deploy():
create_project_directory()
update_compose_file()
with cd(PROJECT_DIRECTORY):
env.run('docker-compose -f ' + COMPOSE_FILE + ' pull')
env.run('docker-compose -f ' + COMPOSE_FILE + ' up -d')
|
from datetime import datetime
from fabric.api import (
cd,
env,
put,
run,
sudo,
task
)
PRODUCTION_IP = '54.154.235.243'
PROJECT_DIRECTORY = '/home/ubuntu/ztm/'
BACKUP_DIRECTORY = '/home/ubuntu/backup/'
COMPOSE_FILE = 'compose-production.yml'
@task
def production():
env.run = sudo
env.hosts = [
'ubuntu@' + PRODUCTION_IP + ':22',
]
def create_project_directory():
run('mkdir -p ' + PROJECT_DIRECTORY)
def update_compose_file():
put('./' + COMPOSE_FILE, PROJECT_DIRECTORY)
@task
def do_backup():
backup_time = datetime.now().strftime('%Y-%m-%d_%H%M')
with cd(BACKUP_DIRECTORY):
command = 'tar -cjvf ztm-' + backup_time + \
'.tar.bz2 ' + PROJECT_DIRECTORY
env.run(command)
command = 's3cmd sync ' + BACKUP_DIRECTORY + ' ' \
's3://zendesk-tickets-machine'
run(command)
@task
def deploy():
create_project_directory()
update_compose_file()
with cd(PROJECT_DIRECTORY):
env.run('docker-compose -f ' + COMPOSE_FILE + ' pull')
env.run('docker-compose -f ' + COMPOSE_FILE + ' up -d')
|
Add S3 command for performing backup data
|
Add S3 command for performing backup data
|
Python
|
mit
|
prontotools/zendesk-tickets-machine,prontotools/zendesk-tickets-machine,prontotools/zendesk-tickets-machine,prontotools/zendesk-tickets-machine
|
873b82225d287dcca9b9bc0e0c3746233d15d947
|
utilities.py
|
utilities.py
|
"""
Various utilities
"""
import pprint
def load_state(path):
"""
Load an n-puzzle state from a file into an array and return it.
"""
result = []
with open(path) as f:
for line in f:
result.append(line.split())
return result
def print_state(state):
"""
Prittily returns a puzzle state (a 2D array)
"""
return pprint.pformat(state)
print print_state(load_state('/home/benjamin/npuzz/puzzle_states/1'))
|
"""
Various utilities
"""
import pprint
def load_state(path):
"""
Load an n-puzzle state from a file into an array and return it.
"""
result = []
with open(path) as f:
for line in f:
result.append([])
for square in line.split():
try:
result[-1].append(int(square))
except ValueError: #if its a * character
result[-1].append(square)
return result
def print_state(state):
"""
Prittily returns a puzzle state (a 2D array)
"""
return pprint.pformat(state)
def check_goal(state):
"""
Returns True if state is the goal state. Otherwise, returns False.
state is expected to be a 2D array.
"""
n = len(state[0])
for i in range(0, n):
for j in range(0, n):
if state[i][j] != (j + 1) + (i * n):
if not(i == j == (n - 1) and state[i][j] == '*'):
return False
return True
print check_goal(load_state('/home/benjamin/npuzz/puzzle_states/1'))
|
Add function to check for goal state.
|
Add function to check for goal state.
|
Python
|
mit
|
bandrebandrebandre/npuzz
|
422bb9ebfcff9826cf58d17a20df61cea21fdd77
|
app/supplier_constants.py
|
app/supplier_constants.py
|
# Here we define a set of hardcoded keys that we use when denormalizing data from Supplier/ContactInformation tables
# into the SupplierFramework.declaration field. These are used only by the API and by the
# `digitalmarketplace-scripts/scripts/generate-framework-agreement-*-pages`, which generates framework agreement
# signature pages for successful suppliers to sign. These agreements are populated with some of the details below.
KEY_DUNS_NUMBER = 'supplierDunsNumber'
KEY_ORGANISATION_SIZE = 'supplierOrganisationSize'
KEY_REGISTERED_NAME = 'supplierRegisteredName'
KEY_REGISTRATION_BUILDING = 'supplierRegisteredBuilding'
KEY_REGISTRATION_COUNTRY = 'supplierRegisteredCountry'
KEY_REGISTRATION_NUMBER = 'supplierCompanyRegistrationNumber'
KEY_REGISTRATION_POSTCODE = 'supplierRegisteredPostcode'
KEY_REGISTRATION_TOWN = 'supplierRegisteredTown'
KEY_TRADING_NAME = 'supplierTradingName'
KEY_TRADING_STATUS = 'supplierTradingStatus'
KEY_VAT_NUMBER = 'supplierVatNumber'
|
# Here we define a set of hardcoded keys that we use when denormalizing data from Supplier/ContactInformation tables
# into the SupplierFramework.declaration field. These are used only by the API and by the
# `digitalmarketplace-scripts/scripts/generate-framework-agreement-*-pages`, which generates framework agreement
# signature pages for successful suppliers to sign. These agreements are populated with some of the details below.
KEY_DUNS_NUMBER = 'supplierDunsNumber'
KEY_ORGANISATION_SIZE = 'supplierOrganisationSize'
KEY_REGISTERED_NAME = 'supplierRegisteredName'
KEY_REGISTRATION_BUILDING = 'supplierRegisteredBuilding'
KEY_REGISTRATION_COUNTRY = 'supplierRegisteredCountry'
KEY_REGISTRATION_NUMBER = 'supplierCompanyRegistrationNumber'
KEY_REGISTRATION_POSTCODE = 'supplierRegisteredPostcode'
KEY_REGISTRATION_TOWN = 'supplierRegisteredTown'
KEY_TRADING_NAME = 'supplierTradingName'
KEY_TRADING_STATUS = 'supplierTradingStatus'
|
Remove VAT number from supplier constants
|
Remove VAT number from supplier constants
|
Python
|
mit
|
alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api
|
99909048bc702e21e980bb1167caf9217aa31196
|
steel/fields/strings.py
|
steel/fields/strings.py
|
import codecs
from steel.fields import Field
from steel.fields.mixin import Fixed
__all__ = ['Bytes', 'String', 'FixedBytes', 'FixedString']
class Bytes(Field):
"A stream of bytes that should be left unconverted"
def encode(self, value):
# Nothing to do here
return value
def decode(self, value):
# Nothing to do here
return value
class String(Field):
"A string that gets converted using a specified encoding"
def __init__(self, *args, encoding, **kwargs):
# Bail out early if the encoding isn't valid
codecs.lookup(encoding)
self.encoding = encoding
super(String, self).__init__(*args, **kwargs)
def encode(self, value):
return value.encode(self.encoding)
def decode(self, value):
return value.decode(self.encoding)
class FixedBytes(Fixed, Bytes):
"A stream of bytes that will always be set to the same value"
# The mixin does the heavy lifting
pass
class FixedString(Fixed, String):
"A stream of bytes that will always be set to the same value"
# The mixin does the heavy lifting
pass
|
import codecs
from steel.fields import Field
from steel.fields.mixin import Fixed
__all__ = ['Bytes', 'String', 'FixedBytes', 'FixedString']
class Bytes(Field):
"A stream of bytes that should be left unconverted"
def encode(self, value):
# Nothing to do here
return value
def decode(self, value):
# Nothing to do here
return value
class String(Field):
"A string that gets converted using a specified encoding"
def __init__(self, *args, encoding, **kwargs):
# Bail out early if the encoding isn't valid
codecs.lookup(encoding)
self.encoding = encoding
super(String, self).__init__(*args, **kwargs)
def encode(self, value):
return value.encode(self.encoding)
def decode(self, value):
return value.decode(self.encoding)
class FixedBytes(Fixed, Bytes):
"A stream of bytes that will always be set to the same value"
# The mixin does the heavy lifting
pass
class FixedString(Fixed, String):
"A string that will always be set to the same value"
# The mixin does the heavy lifting
pass
|
Fix the docstring for FixedString
|
Fix the docstring for FixedString
|
Python
|
bsd-3-clause
|
gulopine/steel-experiment
|
258a9dc694fc5ad308c6fbadfe01b0a375a2a34e
|
talks/core/renderers.py
|
talks/core/renderers.py
|
from rest_framework import renderers
from icalendar import Calendar, Event
class ICalRenderer(renderers.BaseRenderer):
media_type = 'text/calendar'
format = 'ical'
def render(self, data, media_type=None, renderer_context=None):
cal = Calendar()
cal.add('prodid', 'talks.ox.ac.uk')
cal.add('version', '2.0')
for e in data:
cal.add_component(self._event_to_ics(e))
return cal.to_ical()
@staticmethod
def _event_to_ics(e):
event = Event()
if 'title' in e:
event.add('summary', e['title'])
if 'description' in e:
event.add('description', e['description'])
if 'start' in e:
event.add('dtstart', e['start'])
if 'url' in e:
event.add('url', e['url'])
event.add('uid', e['url'])
# TODO add location field
return event
|
from rest_framework import renderers
from icalendar import Calendar, Event
class ICalRenderer(renderers.BaseRenderer):
media_type = 'text/calendar'
format = 'ics'
def render(self, data, media_type=None, renderer_context=None):
cal = Calendar()
cal.add('prodid', 'talks.ox.ac.uk')
cal.add('version', '2.0')
for e in data:
cal.add_component(self._event_to_ics(e))
return cal.to_ical()
@staticmethod
def _event_to_ics(e):
event = Event()
if 'title' in e:
event.add('summary', e['title'])
if 'description' in e:
event.add('description', e['description'])
if 'start' in e:
event.add('dtstart', e['start'])
if 'url' in e:
event.add('url', e['url'])
event.add('uid', e['url'])
# TODO add location field
return event
|
Change default format to ics instead of ical
|
Change default format to ics instead of ical
|
Python
|
apache-2.0
|
ox-it/talks.ox,ox-it/talks.ox,ox-it/talks.ox
|
be00af0a0e87af5b4c82107d2f1356f378b65cb4
|
obj_sys/management/commands/tag_the_file.py
|
obj_sys/management/commands/tag_the_file.py
|
import os
from optparse import make_option
from django.core.management import BaseCommand
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
from obj_sys.models_ufs_obj import UfsObj
class FileTagger(DjangoCmdBase):
option_list = BaseCommand.option_list + (
make_option('--tags',
action='store',
dest='tags',
type='string',
help='Tags separated with ","'),
make_option('--file_path',
action='store',
dest='file_path',
type='string',
help='Path of the file to be tagged'),
make_option('--log-file',
action='store',
dest='log_file',
help='Log file destination'),
make_option('--log-std',
action='store_true',
dest='log_std',
help='Redirect stdout and stderr to the logging system'),
)
def msg_loop(self):
# enum_method = enum_git_repo
# pull_all_in_enumerable(enum_method)
if os.path.exists(self.options["file_path"]):
new_file_ufs_obj = UfsObj.objects.get_or_create(full_path=self.options["file_path"])
new_file_ufs_obj.tags = self.options["tags"]
Command = FileTagger
|
import os
from optparse import make_option
from django.core.management import BaseCommand
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
from obj_sys.models_ufs_obj import UfsObj
class FileTagger(DjangoCmdBase):
option_list = BaseCommand.option_list + (
make_option('--tags',
action='store',
dest='tags',
type='string',
help='Tags separated with ","'),
make_option('--file_path',
action='store',
dest='file_path',
type='string',
help='Path of the file to be tagged'),
make_option('--log-file',
action='store',
dest='log_file',
help='Log file destination'),
make_option('--log-std',
action='store_true',
dest='log_std',
help='Redirect stdout and stderr to the logging system'),
)
def msg_loop(self):
# enum_method = enum_git_repo
# pull_all_in_enumerable(enum_method)
if os.path.exists(self.options["file_path"]):
new_file_ufs_obj, is_created = UfsObj.objects.get_or_create(full_path=self.options["file_path"])
new_file_ufs_obj.tags = self.options["tags"]
Command = FileTagger
|
Fix the issue that get_or_create returns a tuple instead of one object.
|
Fix the issue that get_or_create returns a tuple instead of one object.
|
Python
|
bsd-3-clause
|
weijia/obj_sys,weijia/obj_sys
|
fffb98874066d5762b815987d7e6768a2e9cb03c
|
tests/daemon_uid_gid.py
|
tests/daemon_uid_gid.py
|
#!/usr/bin/env python
from os import getuid, geteuid, getgid, getegid
from sys import argv
from time import sleep
from daemonize import Daemonize
pid = argv[1]
log = argv[2]
def main():
uids = getuid(), geteuid()
gids = getgid(), getegid()
with open(log, "w") as f:
f.write(" ".join(map(str, uids + gids)))
daemon = Daemonize(app="test_app", pid=pid, action=main, user="nobody", group="nobody", keep_fds=[1, 2])
daemon.start()
|
#!/usr/bin/env python
from os import getuid, geteuid, getgid, getegid
from sys import argv
from time import sleep
from daemonize import Daemonize
pid = argv[1]
log = argv[2]
def main():
uids = getuid(), geteuid()
gids = getgid(), getegid()
with open(log, "w") as f:
f.write(" ".join(map(str, uids + gids)))
group = "nogroup" if os.path.exists("/etc/debian_version") else "nobody"
daemon = Daemonize(app="test_app", pid=pid, action=main, user="nobody", group=group)
daemon.start()
|
Support debian based distributives in tests
|
Support debian based distributives in tests
|
Python
|
mit
|
thesharp/daemonize
|
329f4cd5123440baf537db30340fd3d33d7bbbf1
|
games/management/commands/makelove.py
|
games/management/commands/makelove.py
|
from django.core.management.base import BaseCommand
from games import models, bundle
def package_love(stdout, game, release):
if release.get_asset('love') is not None:
stdout.write(u"SKIPPING {}".format(release))
return
upload = release.get_asset('uploaded')
if upload is None:
stdout.write(u"NO UPLOAD {}".format(release))
return
identity = bundle.detect_identity(upload.blob) or game.slug
config = bundle.game_config(game.uuid, identity, release.version)
prefix = "build/love8"
if release.love_version == "0.9.0":
prefix = "build/love9"
# Detect version, fail if not specified
love = bundle.inject_code(game, upload.blob, config)
slug = game.slug
name = game.name
# Create binaries
love_file = bundle.blobify(bundle.package_love, game, love, prefix,
name, slug, release.version)
release.add_asset(love_file, tag='love')
stdout.write(u"FINISHED {}".format(release))
class Command(BaseCommand):
help = 'Backfill LOVE files for all games'
def handle(self, *args, **options):
for game in models.Game.objects.all():
for release in game.release_set.all():
package_love(self.stdout, game, release)
|
import zipfile
from django.core.management.base import BaseCommand
from games import models, bundle
def package_love(stdout, game, release):
if release.get_asset('love') is not None:
stdout.write(u"SKIPPING {}".format(release))
return
upload = release.get_asset('uploaded')
if upload is None:
stdout.write(u"NO UPLOAD {}".format(release))
return
try:
identity = bundle.detect_identity(upload.blob) or game.slug
except zipfile.BadZipfile:
stdout.write(u"BAD ZIP {}".format(release))
return
config = bundle.game_config(game.uuid, identity, release.version)
prefix = "build/love8"
if release.love_version == "0.9.0":
prefix = "build/love9"
# Detect version, fail if not specified
love = bundle.inject_code(game, upload.blob, config)
slug = game.slug
name = game.name
# Create binaries
love_file = bundle.blobify(bundle.package_love, game, love, prefix,
name, slug, release.version)
release.add_asset(love_file, tag='love')
stdout.write(u"FINISHED {}".format(release))
class Command(BaseCommand):
help = 'Backfill LOVE files for all games'
def handle(self, *args, **options):
for game in models.Game.objects.all():
for release in game.release_set.all():
package_love(self.stdout, game, release)
|
Make sure that uploaded files are zipfiles
|
Make sure that uploaded files are zipfiles
|
Python
|
mit
|
stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb,stackmachine/bearweb
|
52430087413e24c94a532e67a2c77248ecc0598c
|
saleor/core/extensions/checks.py
|
saleor/core/extensions/checks.py
|
import importlib
from typing import List
from django.conf import settings
from django.core.checks import Error, register
@register()
def check_extensions(app_configs, **kwargs):
"""Confirm a correct import of plugins and manager."""
errors = []
check_manager(errors)
plugins = settings.PLUGINS or []
for plugin_path in plugins:
check_single_plugin(plugin_path, errors)
return errors
def check_manager(errors: List[Error]):
if not hasattr(settings, "EXTENSIONS_MANAGER") or not settings.EXTENSIONS_MANAGER:
errors.append(Error("Settings should contain EXTENSIONS_MANAGER env"))
return
manager_path, _, manager_name = settings.EXTENSIONS_MANAGER.rpartition(".")
try:
manager_module = importlib.import_module(manager_path)
except ModuleNotFoundError:
errors.append(Error("Extension Manager path: %s doesn't exist" % manager_path))
else:
manager_class = getattr(manager_module, manager_name, None)
if not manager_class:
errors.append(
Error(
"Extension Manager %s doesn't exists in specific path %s"
% (manager_name, str(manager_module))
)
)
def check_single_plugin(plugin_path: str, errors: List[Error]):
if not plugin_path:
errors.append(Error("Wrong plugin_path %s" % plugin_path))
return
plugin_path, _, plugin_name = plugin_path.rpartition(".")
try:
plugin_module = importlib.import_module(plugin_path)
except ModuleNotFoundError:
errors.append(Error("Plugin with path: %s doesn't exist" % plugin_path))
else:
plugin_class = getattr(plugin_module, plugin_name, None)
if not plugin_class:
errors.append(
Error(
"Plugin %s doesn't exists in specific path %s"
% (plugin_name, str(plugin_module))
)
)
|
from typing import List
from django.conf import settings
from django.core.checks import Error, register
from django.utils.module_loading import import_string
@register()
def check_extensions(app_configs, **kwargs):
"""Confirm a correct import of plugins and manager."""
errors = []
check_manager(errors)
plugins = settings.PLUGINS or []
for plugin_path in plugins:
check_single_plugin(plugin_path, errors)
return errors
def check_manager(errors: List[Error]):
if not hasattr(settings, "EXTENSIONS_MANAGER") or not settings.EXTENSIONS_MANAGER:
errors.append(Error("Settings should contain EXTENSIONS_MANAGER env"))
return
try:
import_string(settings.EXTENSIONS_MANAGER)
except ImportError:
errors.append(
Error(
"Extension Manager path: %s doesn't exist" % settings.EXTENSIONS_MANAGER
)
)
def check_single_plugin(plugin_path: str, errors: List[Error]):
if not plugin_path:
errors.append(Error("Wrong plugin_path %s" % plugin_path))
return
try:
import_string(plugin_path)
except ImportError:
errors.append(Error("Plugin with path: %s doesn't exist" % plugin_path))
|
Use django helper to validate manager and plugins paths
|
Use django helper to validate manager and plugins paths
|
Python
|
bsd-3-clause
|
mociepka/saleor,mociepka/saleor,mociepka/saleor,maferelo/saleor,maferelo/saleor,maferelo/saleor
|
886d4d526d1766d154604f7a71182e48b3438a17
|
linter.py
|
linter.py
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by roadhump
# Copyright (c) 2014 roadhump
#
# License: MIT
#
"""This module exports the ESLint plugin class."""
from SublimeLinter.lint import Linter
class ESLint(Linter):
"""Provides an interface to the eslint executable."""
syntax = ('javascript', 'html')
cmd = 'eslint --format=compact'
version_args = '--version'
version_re = r'v(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 0.3.0'
regex = (
r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
r'(?P<message>.+)'
)
line_col_base = (1, 0)
selectors = {
'html': 'source.js.embedded.html'
}
tempfile_suffix = 'js'
config_file = ('--config', '.eslintrc')
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by roadhump
# Copyright (c) 2014 roadhump
#
# License: MIT
#
"""This module exports the ESLint plugin class."""
from SublimeLinter.lint import Linter
class ESLint(Linter):
"""Provides an interface to the eslint executable."""
syntax = ('javascript', 'html')
cmd = 'eslint --format=compact'
version_args = '--version'
version_re = r'v(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 0.3.0'
regex = (
r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
r'(?P<message>.+)'
)
line_col_base = (1, 0)
selectors = {
'html': 'source.js.embedded.html'
}
tempfile_suffix = 'js'
config_file = ('--config', '.eslintrc', '~')
|
Make fall back to ~/.eslintrc
|
Make fall back to ~/.eslintrc
|
Python
|
mit
|
joeybaker/SublimeLinter-textlint,roadhump/SublimeLinter-eslint,AndBicScadMedia/SublimeLinter-eslint
|
6f8a19c46a1d8b6b31039f212e733cd660551de7
|
mws/apis/__init__.py
|
mws/apis/__init__.py
|
from .feeds import Feeds
from .finances import Finances
from .inbound_shipments import InboundShipments
from .inventory import Inventory
from .merchant_fulfillment import MerchantFulfillment
from .offamazonpayments import OffAmazonPayments
from .orders import Orders
from .products import Products
from .recommendations import Recommendations
from .reports import Reports
from .sellers import Sellers
from .outbound_shipments import OutboundShipments
__all__ = [
'Feeds',
'Finances',
'InboundShipments',
'Inventory',
'MerchantFulfillment',
'OffAmazonPayments',
'Orders',
'OutboundShipments',
'Products',
'Recommendations',
'Reports',
'Sellers',
]
|
from .feeds import Feeds
from .finances import Finances
from .inbound_shipments import InboundShipments
from .inventory import Inventory
from .merchant_fulfillment import MerchantFulfillment
from .offamazonpayments import OffAmazonPayments
from .orders import Orders
from .outbound_shipments import OutboundShipments
from .products import Products
from .recommendations import Recommendations
from .reports import Reports
from .sellers import Sellers
from .subscriptions import Subscriptions
__all__ = [
'Feeds',
'Finances',
'InboundShipments',
'Inventory',
'MerchantFulfillment',
'OffAmazonPayments',
'Orders',
'OutboundShipments',
'Products',
'Recommendations',
'Reports',
'Sellers',
'Subscriptions',
]
|
Include the new Subscriptions stub
|
Include the new Subscriptions stub
|
Python
|
unlicense
|
Bobspadger/python-amazon-mws,GriceTurrble/python-amazon-mws
|
22935ee89217ac1f8b8d3c921571381336069584
|
lctools/lc.py
|
lctools/lc.py
|
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
import libcloud.security
from config import get_config
def get_lc(profile, resource=None):
if resource is None:
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
else:
pkg_name = 'libcloud.%s' % resource
Provider = __import__(pkg_name + ".types",
globals(), locals(), ['Provider'], -1).Provider
get_driver = __import__(pkg_name + ".providers",
globals(), locals(), ['get_driver'], -1).get_driver
conf = get_config(profile)
libcloud.security.VERIFY_SSL_CERT = conf.get('verify_ssl_certs') == 'true'
extra_kwargs = {}
extra = conf.get("extra")
if extra != "":
extra_kwargs = eval(extra)
if not isinstance(extra_kwargs, dict):
raise Exception('Extra arguments should be a Python dict')
driver = get_driver(getattr(Provider, conf.get('driver').upper()))
conn = driver(conf.get('access_id'), conf.get('secret_key'), **extra_kwargs)
return conn
|
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
import libcloud.security
from config import get_config
def get_lc(profile, resource=None):
if resource is None:
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
else:
pkg_name = 'libcloud.%s' % resource
Provider = __import__(pkg_name + ".types",
globals(), locals(), ['Provider'], -1).Provider
get_driver = __import__(pkg_name + ".providers",
globals(), locals(), ['get_driver'], -1).get_driver
conf = get_config(profile)
libcloud.security.VERIFY_SSL_CERT = conf.get('verify_ssl_certs') == 'true'
extra_kwargs = {}
extra = conf.get("extra")
if extra != "":
extra_kwargs = eval(extra)
if not isinstance(extra_kwargs, dict):
raise Exception('Extra arguments should be a Python dict')
# a hack because libcloud driver names for Rackspace doesn't match
# for loadbalancers and compute
driver_name = conf.get('driver').upper()
if 'loadbalancer' == resource and 'RACKSPACE' == driver_name:
driver_name += "_US"
driver = get_driver(getattr(Provider, driver_name))
conn = driver(conf.get('access_id'), conf.get('secret_key'), **extra_kwargs)
return conn
|
Add a hack to overcome driver name inconsistency in libcloud.
|
Add a hack to overcome driver name inconsistency in libcloud.
|
Python
|
apache-2.0
|
novel/lc-tools,novel/lc-tools
|
c541e85f8b1dccaabd047027e89791d807550ee5
|
fade/config.py
|
fade/config.py
|
#!/usr/bin/env python
"""
See LICENSE.txt file for copyright and license details.
"""
import os
basedir = os.path.abspath(os.path.dirname(__file__))
WTF_CSRF_ENABLED = True
SECRET_KEY = '3124534675689780'
# TODO: switch this to postgresql
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')
|
#!/usr/bin/env python
"""
See LICENSE.txt file for copyright and license details.
"""
import os
basedir = os.path.abspath(os.path.dirname(__file__))
WTF_CSRF_ENABLED = True
SECRET_KEY = '3124534675689780'
dbuser = 'rockwolf'
dbpass = ''
dbhost = 'testdb'
dbname = 'finance'
SQLALCHEMY_DATABASE_URI = 'postgresql://'
+ dbuser
+ ':'
+ dbpass
+ '@'
+ dbhost
+ '/'
+ dbname
SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'database')
|
Switch database connection string to pg
|
Switch database connection string to pg
|
Python
|
bsd-3-clause
|
rockwolf/python,rockwolf/python,rockwolf/python,rockwolf/python,rockwolf/python,rockwolf/python
|
6c8feca973703cf87a82cfa954fa3c7a3f152c72
|
manage.py
|
manage.py
|
from project import app, db
from project import models
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
|
from project import app, db
from project import models
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
@manager.command
def create_db():
"""Creates the db tables."""
db.create_all()
@manager.command
def drop_db():
"""Drops the db tables."""
db.drop_all()
@manager.command
def create_admin():
"""Creates the admin user."""
db.session.add(User("[email protected]", "admin"))
db.session.commit()
if __name__ == '__main__':
manager.run()
|
Create create_db, drop_db and create_admin functions
|
Create create_db, drop_db and create_admin functions
|
Python
|
mit
|
dylanshine/streamschool,dylanshine/streamschool
|
e6f3bd9c61be29560e09f5d5d9c7e355ec14c2e3
|
manage.py
|
manage.py
|
#!/usr/bin/env python
import sys
if __name__ == "__main__":
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
#!/usr/bin/env python
import sys
import os
if __name__ == "__main__":
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
Set a default settings module
|
Set a default settings module
|
Python
|
bsd-3-clause
|
wagnerand/olympia,andymckay/addons-server,kumar303/addons-server,andymckay/olympia,aviarypl/mozilla-l10n-addons-server,aviarypl/mozilla-l10n-addons-server,wagnerand/addons-server,lavish205/olympia,Prashant-Surya/addons-server,harry-7/addons-server,harikishen/addons-server,mstriemer/olympia,mozilla/addons-server,andymckay/addons-server,mozilla/addons-server,mstriemer/addons-server,eviljeff/olympia,lavish205/olympia,diox/olympia,andymckay/olympia,mstriemer/olympia,aviarypl/mozilla-l10n-addons-server,harikishen/addons-server,mstriemer/olympia,harry-7/addons-server,wagnerand/olympia,wagnerand/olympia,psiinon/addons-server,kumar303/addons-server,mozilla/olympia,atiqueahmedziad/addons-server,atiqueahmedziad/addons-server,mozilla/addons-server,lavish205/olympia,psiinon/addons-server,mstriemer/addons-server,Revanth47/addons-server,diox/olympia,eviljeff/olympia,kumar303/addons-server,aviarypl/mozilla-l10n-addons-server,kumar303/addons-server,bqbn/addons-server,tsl143/addons-server,andymckay/olympia,harikishen/addons-server,mstriemer/addons-server,eviljeff/olympia,atiqueahmedziad/addons-server,tsl143/addons-server,Prashant-Surya/addons-server,mozilla/addons-server,harry-7/addons-server,psiinon/addons-server,kumar303/olympia,bqbn/addons-server,andymckay/olympia,wagnerand/addons-server,eviljeff/olympia,wagnerand/addons-server,mstriemer/addons-server,mstriemer/olympia,kumar303/olympia,mozilla/olympia,andymckay/addons-server,diox/olympia,mozilla/olympia,bqbn/addons-server,Revanth47/addons-server,Prashant-Surya/addons-server,Revanth47/addons-server,wagnerand/olympia,atiqueahmedziad/addons-server,andymckay/addons-server,tsl143/addons-server,harry-7/addons-server,bqbn/addons-server,Prashant-Surya/addons-server,harikishen/addons-server,wagnerand/addons-server,kumar303/olympia,diox/olympia,lavish205/olympia,mozilla/olympia,Revanth47/addons-server,kumar303/olympia,tsl143/addons-server,psiinon/addons-server
|
34f0e697ba4d6a787f0f4fc294163a09a52c185f
|
tests/test_arrayfire.py
|
tests/test_arrayfire.py
|
import arrayfire
# We're going to test several arrayfire behaviours that we rely on
from asserts import *
import afnumpy as af
import numpy as np
def test_cast():
a = afnumpy.random.rand(2,3)
# Check that device_ptr does not cause a copy
assert a.d_array.device_ptr() == a.d_array.device_ptr()
# Check that cast does not cause a copy
assert arrayfire.cast(a.d_array, a.d_array.dtype()).device_ptr() == a.d_array.device_ptr()
|
import arrayfire
# We're going to test several arrayfire behaviours that we rely on
from asserts import *
import afnumpy as af
import numpy as np
def test_af_cast():
a = afnumpy.arrayfire.randu(2,3)
# Check that device_ptr does not cause a copy
assert a.device_ptr() == a.device_ptr()
# Check that cast does not cause a copy
assert arrayfire.cast(a, a.dtype()).device_ptr() == a.device_ptr()
def test_cast():
a = afnumpy.random.rand(2,3)
# Check that device_ptr does not cause a copy
assert a.d_array.device_ptr() == a.d_array.device_ptr()
# Check that cast does not cause a copy
assert arrayfire.cast(a.d_array, a.d_array.dtype()).device_ptr() == a.d_array.device_ptr()
|
Add a pure arrayfire cast test to check for seg faults
|
Add a pure arrayfire cast test to check for seg faults
|
Python
|
bsd-2-clause
|
FilipeMaia/afnumpy,daurer/afnumpy
|
aac31b69da5ec3a3622ca7752e8273886b344683
|
sublist/sublist.py
|
sublist/sublist.py
|
SUPERLIST = "superlist"
SUBLIST = "sublist"
EQUAL = "equal"
UNEQUAL = "unequal"
def check_lists(a, b):
if a == b:
return EQUAL
elif is_sublist(a, b):
return SUBLIST
elif is_sublist(b, a):
return SUPERLIST
else:
return UNEQUAL
def is_sublist(a, b):
return a in [b[i:i + len(a)] for i in range(len(b) - len(a) + 1)]
|
SUPERLIST = "superlist"
SUBLIST = "sublist"
EQUAL = "equal"
UNEQUAL = "unequal"
VERY_UNLIKELY_STRING = "ꗲꅯḪꍙ"
def check_lists(a, b):
if a == b:
return EQUAL
_a = VERY_UNLIKELY_STRING.join(map(str, a))
_b = VERY_UNLIKELY_STRING.join(map(str, b))
if _a in _b:
return SUBLIST
elif _b in _a:
return SUPERLIST
else:
return UNEQUAL
|
Switch back to the substring method - it's faster
|
Switch back to the substring method - it's faster
|
Python
|
agpl-3.0
|
CubicComet/exercism-python-solutions
|
6eae274fc200df9319e82abf99d0f2314a17a2af
|
formlibrary/migrations/0005_auto_20171204_0203.py
|
formlibrary/migrations/0005_auto_20171204_0203.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-12-04 10:03
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('workflow', '0007_auto_20171204_0203'),
('formlibrary', '0004_customform_created_by'),
]
operations = [
migrations.AddField(
model_name='customform',
name='form_uuid',
field=models.CharField(default='', max_length=255, verbose_name='CustomForm UUID'),
),
migrations.AddField(
model_name='customform',
name='silo_id',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='customform',
name='workflowlevel1',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='workflow.WorkflowLevel1'),
),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-12-04 10:03
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('workflow', '0007_auto_20171204_0203'),
('formlibrary', '0004_customform_created_by'),
]
operations = [
migrations.AddField(
model_name='customform',
name='form_uuid',
field=models.CharField(default='', max_length=255, verbose_name='CustomForm UUID'),
),
migrations.AddField(
model_name='customform',
name='silo_id',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='customform',
name='workflowlevel1',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='workflow.WorkflowLevel1'),
),
]
|
Split migration script of customform
|
Split migration script of customform
|
Python
|
apache-2.0
|
toladata/TolaActivity,toladata/TolaActivity,toladata/TolaActivity,toladata/TolaActivity
|
265edc24561bdacfae2412680048c203f7f78c14
|
calendarapp.py
|
calendarapp.py
|
from kivy.app import App
class CalendarApp(App):
"""Basic App to hold the calendar widget."""
def build(self):
return self.root
|
import kivy
kivy.require('1.8.0')
from kivy.config import Config
Config.set('graphics', 'width', '360')
Config.set('graphics', 'height', '640')
from kivy.app import App
class CalendarApp(App):
"""Basic App to hold the calendar widget."""
def build(self):
return self.root
|
Set the window size to emulate a mobile device
|
Set the window size to emulate a mobile device
|
Python
|
mit
|
hackebrot/garden.calendar
|
dde622c7296ef1ebb7ee369c029ed1c8c861cf50
|
client/capability-token-incoming/capability-token.6.x.py
|
client/capability-token-incoming/capability-token.6.x.py
|
from flask import Flask, Response
from twilio.jwt.client import ClientCapabilityToken
app = Flask(__name__)
@app.route('/token', methods=['GET'])
def get_capability_token():
"""Respond to incoming requests."""
# Find these values at twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
capability = ClientCapabilityToken(account_sid, auth_token)
capability.allow_client_incoming("jenny")
token = capability.generate()
return Response(token, mimetype='application/jwt')
if __name__ == "__main__":
app.run(debug=True)
|
from flask import Flask, Response
from twilio.jwt.client import ClientCapabilityToken
app = Flask(__name__)
@app.route('/token', methods=['GET'])
def get_capability_token():
"""Respond to incoming requests."""
# Find these values at twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
capability = ClientCapabilityToken(account_sid, auth_token)
capability.allow_client_incoming("jenny")
token = capability.to_jwt()
return Response(token, mimetype='application/jwt')
if __name__ == "__main__":
app.run(debug=True)
|
Update capability token creation method
|
Update capability token creation method
Old method was `generate()`, it's not `to_jwt()`
|
Python
|
mit
|
TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets
|
86382d372fc8fd7ee42c264019989d3f119508a2
|
integration-test/1106-merge-ocean-earth.py
|
integration-test/1106-merge-ocean-earth.py
|
# There should be a single, merged feature in each of these tiles
# Natural Earth
assert_less_than_n_features(5, 11, 11, 'water', {'kind': 'ocean'}, 2)
assert_less_than_n_features(5, 8, 11, 'earth', {'kind': 'earth'}, 2)
# OpenStreetMap
assert_less_than_n_features(9, 167, 186, 'water', {'kind': 'ocean'}, 2)
assert_less_than_n_features(9, 170, 186, 'earth', {'kind': 'earth'}, 2)
|
# There should be a single, merged feature in each of these tiles
# Natural Earth
assert_less_than_n_features(5, 12, 11, 'water', {'kind': 'ocean'}, 2)
assert_less_than_n_features(5, 8, 11, 'earth', {'kind': 'earth'}, 2)
# OpenStreetMap
assert_less_than_n_features(9, 167, 186, 'water', {'kind': 'ocean'}, 2)
assert_less_than_n_features(9, 170, 186, 'earth', {'kind': 'earth'}, 2)
|
Fix test by looking further east into the ocean
|
Fix test by looking further east into the ocean
|
Python
|
mit
|
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
|
401aafee6979cc95692555548b1fc10dea44a44e
|
product/api/views.py
|
product/api/views.py
|
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from .serializers import ProductSerializer
from ..models import Product
from django.http import Http404
from rest_framework.views import APIView
class ProductDetail(APIView):
permission_classes = (IsAuthenticated,)
"""
Retrieve a product instance.
"""
def get_object(self, slug):
try:
return Product.objects.get(code=slug)
except Product.DoesNotExist:
raise Http404
def get(self, request, slug, format=None):
snippet = self.get_object(slug)
serializer = ProductSerializer(snippet)
return Response(serializer.data)
|
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from .serializers import ProductSerializer
from ..models import Product
from django.http import Http404
from rest_framework.views import APIView
class ProductDetail(APIView):
permission_classes = (IsAuthenticated,)
"""
Retrieve a product instance.
"""
def get_object(self, code):
try:
return Product.get_by_code(code=code)
except Product.DoesNotExist:
raise Http404
def get(self, request, slug, format=None):
snippet = self.get_object(slug)
serializer = ProductSerializer(snippet)
return Response(serializer.data)
|
Use remote fallback for API request
|
Use remote fallback for API request
|
Python
|
bsd-3-clause
|
KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend
|
15db7def176572a667299cc30102c076b589620d
|
pyQuantuccia/tests/test_get_holiday_date.py
|
pyQuantuccia/tests/test_get_holiday_date.py
|
from pyQuantuccia import quantuccia
def test_get_holiday_date():
""" At the moment the only thing this function
can do is return NULL.
"""
assert(quantuccia.get_holiday_date() is None)
|
from pyQuantuccia import quantuccia
def test_get_holiday_date():
""" At the moment the only thing this function
can do is return NULL.
"""
assert(quantuccia.get_holiday_date() is None)
|
Correct spacing in the test file.
|
Correct spacing in the test file.
|
Python
|
bsd-3-clause
|
jwg4/pyQuantuccia,jwg4/pyQuantuccia
|
17bd35d7a2b442faebdb39aad07294612d8e7038
|
nflh/games.py
|
nflh/games.py
|
from datetime import datetime
GAME_VIDEO_BASE_URL = "http://www.nfl.com/feeds-rs/videos/byGameCenter/{0}.json"
LIVE_UPDATE_BASE_URL = "http://www.nfl.com/liveupdate/game-center/{0}/{0}_gtd.json"
class Game(object):
def __init__(self, id_, h, v):
self.id_ = id_
self.date = self.id_[:-2]
self.home = h
self.vis = v
self.latest_play_id = ""
self.latest_clip_id = ""
def is_today(self):
return self.date == str((datetime.today()).strftime('%Y%m%d'))
def video_url(self):
return GAME_VIDEO_BASE_URL.format(self.id_)
def live_update_url(self):
return LIVE_UPDATE_BASE_URL.format(self.id_)
|
from datetime import datetime
GAME_VIDEO_BASE_URL = "http://www.nfl.com/feeds-rs/videos/byGameCenter/{0}.json"
LIVE_UPDATE_BASE_URL = "http://www.nfl.com/liveupdate/game-center/{0}/{0}_gtd.json"
class Game(object):
def __init__(self, id_, h, v):
self.id_ = id_
self.date = self.id_[:-2]
self.home = h
self.vis = v
self.latest_play_id = ""
self.latest_clip_id = ""
self.videos = {}
def is_today(self):
return self.date == str((datetime.today()).strftime('%Y%m%d'))
def video_url(self):
return GAME_VIDEO_BASE_URL.format(self.id_)
def live_update_url(self):
return LIVE_UPDATE_BASE_URL.format(self.id_)
|
Add videos dict to Games.
|
Add videos dict to Games.
|
Python
|
apache-2.0
|
twbarber/nfl-highlight-bot
|
c36b0639190de6517260d6b6e8e5991976336760
|
shared/btr3baseball/DatasourceRepository.py
|
shared/btr3baseball/DatasourceRepository.py
|
import json
resource_package = __name__
resource_path_format = 'datasource/{}.json'
class DatasourceRepository:
def __init__(self):
self.availableSources = json.loads(pkg_resources.resource_string(resource_package, resource_path_format.format('all')))['available']
self.data = {}
for source in availableSources:
self.data[source] = json.loads(pkg_resources.resource_string(resource_package, resource_path_format.format(source)))
def listDatasources(self):
return self.availableSources
def getDatasource(self, sourceId):
if sourceId in self.data:
return self.data[sourceId]
else:
return None
|
import pkg_resources
import json
resource_package = __name__
resource_path_format = 'datasource/{}.json'
class DatasourceRepository:
def __init__(self):
self.availableSources = json.loads(pkg_resources.resource_string(resource_package, resource_path_format.format('all')))['available']
self.data = {}
for source in availableSources:
self.data[source] = json.loads(pkg_resources.resource_string(resource_package, resource_path_format.format(source)))
def listDatasources(self):
return self.availableSources
def getDatasource(self, sourceId):
if sourceId in self.data:
return self.data[sourceId]
else:
return None
|
Add pkg_resources back, working forward
|
Add pkg_resources back, working forward
|
Python
|
apache-2.0
|
bryantrobbins/baseball,bryantrobbins/baseball,bryantrobbins/baseball,bryantrobbins/baseball,bryantrobbins/baseball
|
e9949cdf609aeb99cfe97c37638c6cb80c947198
|
longclaw/longclawshipping/wagtail_hooks.py
|
longclaw/longclawshipping/wagtail_hooks.py
|
from wagtail.contrib.modeladmin.options import (
ModelAdmin, modeladmin_register
)
from longclaw.longclawshipping.models import ShippingCountry
class ShippingCountryModelAdmin(ModelAdmin):
model = ShippingCountry
menu_order = 200
menu_icon = 'site'
add_to_settings_menu = False
exclude_from_explorer = True
list_display = ('country', 'country_code', 'shipping_rates')
def flag(self, obj):
return obj.country.flag
def country_code(self, obj):
return obj.country.alpha3
def shipping_rates(self, obj):
return ", ".join(str(rate) for rate in obj.shipping_rates.all())
modeladmin_register(ShippingCountryModelAdmin)
|
from wagtail.contrib.modeladmin.options import (
ModelAdmin, modeladmin_register
)
from longclaw.longclawshipping.models import ShippingCountry
class ShippingCountryModelAdmin(ModelAdmin):
model = ShippingCountry
menu_label = 'Shipping'
menu_order = 200
menu_icon = 'site'
add_to_settings_menu = False
exclude_from_explorer = True
list_display = ('country', 'country_code', 'shipping_rates')
def flag(self, obj):
return obj.country.flag
def country_code(self, obj):
return obj.country.alpha3
def shipping_rates(self, obj):
return ", ".join(str(rate) for rate in obj.shipping_rates.all())
modeladmin_register(ShippingCountryModelAdmin)
|
Rename shipping label in model admin
|
Rename shipping label in model admin
|
Python
|
mit
|
JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw
|
8eddab84f27d5c068f5da477e05736c222cac4e2
|
mass/utils.py
|
mass/utils.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Helper functions.
"""
# built-in modules
import json
# 3rd-party modules
from botocore.client import Config
# local modules
from mass.exception import UnsupportedScheduler
from mass.input_handler import InputHandler
def submit(job, protocol=None, priority=1, scheduler='swf'):
"""Submit mass job to SWF with specific priority.
"""
if scheduler != 'swf':
raise UnsupportedScheduler(scheduler)
from mass.scheduler.swf import config
import boto3
client = boto3.client(
'swf',
region_name=config.REGION,
config=Config(connect_timeout=config.CONNECT_TIMEOUT,
read_timeout=config.READ_TIMEOUT))
handler = InputHandler(protocol)
res = client.start_workflow_execution(
domain=config.DOMAIN,
workflowId=job.title,
workflowType=config.WORKFLOW_TYPE_FOR_JOB,
taskList={'name': config.DECISION_TASK_LIST},
taskPriority=str(priority),
input=json.dumps({
'protocol': protocol,
'body': handler.save(
data=job,
job_title=job.title,
task_title=job.title
)
}),
executionStartToCloseTimeout=str(config.WORKFLOW_EXECUTION_START_TO_CLOSE_TIMEOUT),
tagList=[job.title],
taskStartToCloseTimeout=str(config.DECISION_TASK_START_TO_CLOSE_TIMEOUT),
childPolicy=config.WORKFLOW_CHILD_POLICY)
return job.title, res['runId']
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Helper functions.
"""
# built-in modules
import json
# 3rd-party modules
from botocore.client import Config
# local modules
from mass.exception import UnsupportedScheduler
from mass.input_handler import InputHandler
def submit(job, protocol=None, priority=1, scheduler='swf'):
"""Submit mass job to SWF with specific priority.
"""
if scheduler != 'swf':
raise UnsupportedScheduler(scheduler)
from mass.scheduler.swf import config
import boto3
client = boto3.client(
'swf',
region_name=config.REGION,
config=Config(connect_timeout=config.CONNECT_TIMEOUT,
read_timeout=config.READ_TIMEOUT))
handler = InputHandler(protocol)
res = client.start_workflow_execution(
domain=config.DOMAIN,
workflowId=job.title,
workflowType=config.WORKFLOW_TYPE_FOR_JOB,
taskList={'name': config.DECISION_TASK_LIST},
taskPriority=str(priority),
input=json.dumps({
'protocol': protocol,
'body': handler.save(
data=job,
genealogy=[job.title]
)
}),
executionStartToCloseTimeout=str(config.WORKFLOW_EXECUTION_START_TO_CLOSE_TIMEOUT),
tagList=[job.title],
taskStartToCloseTimeout=str(config.DECISION_TASK_START_TO_CLOSE_TIMEOUT),
childPolicy=config.WORKFLOW_CHILD_POLICY)
return job.title, res['runId']
|
Use [job.title] as genealogy of input_handler.save while submit job.
|
Use [job.title] as genealogy of input_handler.save while submit job.
|
Python
|
apache-2.0
|
badboy99tw/mass,KKBOX/mass,KKBOX/mass,badboy99tw/mass,KKBOX/mass,badboy99tw/mass
|
fad484694174e17ef8de9af99db3dda5cd866fac
|
md2pdf/core.py
|
md2pdf/core.py
|
# -*- coding: utf-8 -*-
from markdown2 import markdown, markdown_path
from weasyprint import HTML, CSS
from .exceptions import ValidationError
__title__ = 'md2pdf'
__version__ = '0.2.1'
__author__ = 'Julien Maupetit'
__license__ = 'MIT'
__copyright__ = 'Copyright 2013 Julien Maupetit'
def md2pdf(pdf_file_path, md_content=None, md_file_path=None,
css_file_path=None):
"""
Convert markdown file to pdf with styles
"""
# Convert markdown to html
raw_html = ""
extras = ["cuddled-lists"]
if md_file_path:
raw_html = markdown_path(md_file_path, extras=extras)
elif md_content:
raw_html = markdown(md_file_path, extras=extras)
if not len(raw_html):
raise ValidationError('Input markdown seems empty')
# Weasyprint HTML object
html = HTML(string=raw_html)
# Get styles
css = []
if css_file_path:
css.append(CSS(filename=css_file_path))
# Generate PDF
html.write_pdf(pdf_file_path, stylesheets=css)
return
|
# -*- coding: utf-8 -*-
from markdown2 import markdown, markdown_path
from weasyprint import HTML, CSS
from .exceptions import ValidationError
__title__ = 'md2pdf'
__version__ = '0.2.1'
__author__ = 'Julien Maupetit'
__license__ = 'MIT'
__copyright__ = 'Copyright 2013 Julien Maupetit'
def md2pdf(pdf_file_path, md_content=None, md_file_path=None,
css_file_path=None):
"""
Convert markdown file to pdf with styles
"""
# Convert markdown to html
raw_html = ""
extras = ["cuddled-lists"]
if md_file_path:
raw_html = markdown_path(md_file_path, extras=extras)
elif md_content:
raw_html = markdown(md_content, extras=extras)
if not len(raw_html):
raise ValidationError('Input markdown seems empty')
# Weasyprint HTML object
html = HTML(string=raw_html)
# Get styles
css = []
if css_file_path:
css.append(CSS(filename=css_file_path))
# Generate PDF
html.write_pdf(pdf_file_path, stylesheets=css)
return
|
Fix raw md content rendering
|
Fix raw md content rendering
|
Python
|
mit
|
jmaupetit/md2pdf
|
facaa380b9b0fbb8f5d6d4d7c6c24257235cbb65
|
plugin.py
|
plugin.py
|
# -*- coding: utf-8 -*-
"""Load and Unload all GitGutter modules.
This module exports __all__ modules, which Sublime Text needs to know about.
The list of __all__ exported symbols is defined in modules/__init__.py.
"""
try:
from .modules import *
except ValueError:
from modules import *
def plugin_loaded():
"""Plugin loaded callback."""
try:
# Reload 'modules' once after upgrading to ensure GitGutter is ready
# for use instantly again. (Works with ST3 and python3 only!)
from package_control import events
if events.post_upgrade(__package__):
from .modules.reload import reload_package
reload_package(__package__)
except ImportError:
# Fail silently if package control isn't installed.
pass
|
# -*- coding: utf-8 -*-
"""Load and Unload all GitGutter modules.
This module exports __all__ modules, which Sublime Text needs to know about.
The list of __all__ exported symbols is defined in modules/__init__.py.
"""
try:
from .modules import *
except ValueError:
from modules import *
except ImportError:
# Failed to import at least one module. This can happen after upgrade due
# to internal structure changes.
import sublime
sublime.message_dialog(
"GitGutter failed to reload some of its modules.\n"
"Please restart Sublime Text!")
def plugin_loaded():
"""Plugin loaded callback."""
try:
# Reload 'modules' once after upgrading to ensure GitGutter is ready
# for use instantly again. (Works with ST3 and python3 only!)
from package_control import events
if events.post_upgrade(__package__):
from .modules.reload import reload_package
reload_package(__package__)
except ImportError:
# Fail silently if package control isn't installed.
pass
|
Handle module reload exceptions gracefully
|
Enhancement: Handle module reload exceptions gracefully
In some rare cases if the internal module structure has changed the 'reload' module can't recover all modules and will fail with ImportError. This is the situation we need to advice a restart of Sublime Text.
|
Python
|
mit
|
jisaacks/GitGutter
|
a07ac44d433981b7476ab3b57339797edddb368c
|
lenet_slim.py
|
lenet_slim.py
|
import tensorflow as tf
slim = tf.contrib.slim
def le_net(images, num_classes=10, scope='LeNet'):
with tf.variable_scope(scope, 'LeNet', [images, num_classes]):
net = slim.conv2d(images, 32, [5, 5], scope='conv1')
net = slim.max_pool2d(net, [2, 2], 2, scope='pool1')
net = slim.conv2d(net, 64, [5, 5], scope='conv2')
net = slim.max_pool2d(net, [2, 2], 2, scope='pool2')
gap = tf.reduce_mean(net, (1, 2))
with tf.variable_scope('GAP'):
gap_w = tf.get_variable('W', shape=[64, 10], initializer=tf.random_normal_initializer(0., 0.01))
logits = tf.matmul(gap, gap_w)
return logits, net
def le_net_arg_scope(weight_decay=0.0):
with slim.arg_scope(
[slim.conv2d, slim.fully_connected],
weights_regularizer=slim.l2_regularizer(weight_decay),
weights_initializer=tf.truncated_normal_initializer(stddev=0.1),
activation_fn=tf.nn.relu) as sc:
return sc
|
import tensorflow as tf
slim = tf.contrib.slim
def le_net(images, num_classes=10, scope='LeNet'):
with tf.variable_scope(scope, 'LeNet', [images, num_classes]):
net = slim.conv2d(images, 32, [5, 5], scope='conv1')
net = slim.max_pool2d(net, [2, 2], 2, scope='pool1')
net = slim.conv2d(net, 64, [5, 5], scope='conv2')
net = slim.max_pool2d(net, [2, 2], 2, scope='pool2')
gap = tf.reduce_mean(net, (1, 2))
with tf.variable_scope('GAP'):
gap_w = tf.get_variable('W', shape=[64, num_classes], initializer=tf.random_normal_initializer(0., 0.01))
logits = tf.matmul(gap, gap_w)
return logits, net
def le_net_arg_scope(weight_decay=0.0):
with slim.arg_scope(
[slim.conv2d, slim.fully_connected],
weights_regularizer=slim.l2_regularizer(weight_decay),
weights_initializer=tf.truncated_normal_initializer(stddev=0.1),
activation_fn=tf.nn.relu) as sc:
return sc
|
Fix the shape of gap_w
|
Fix the shape of gap_w
|
Python
|
mit
|
philipperemy/tensorflow-class-activation-mapping
|
7f48dde064acbf1c192ab0bf303ac8e80e56e947
|
wafer/kv/models.py
|
wafer/kv/models.py
|
from django.contrib.auth.models import Group
from django.db import models
from jsonfield import JSONField
class KeyValue(models.Model):
group = models.ForeignKey(Group, on_delete=models.CASCADE)
key = models.CharField(max_length=64, db_index=True)
value = JSONField()
def __unicode__(self):
return u'KV(%s, %s, %r)' % (self.group.name, self.key, self.value)
def __str__(self):
return 'KV(%s, %s, %r)' % (self.group.name, self.key, self.value)
|
from django.contrib.auth.models import Group
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from jsonfield import JSONField
@python_2_unicode_compatible
class KeyValue(models.Model):
group = models.ForeignKey(Group, on_delete=models.CASCADE)
key = models.CharField(max_length=64, db_index=True)
value = JSONField()
def __str__(self):
return 'KV(%s, %s, %r)' % (self.group.name, self.key, self.value)
|
Use @python_2_unicode_compatible rather than repeating methods
|
Use @python_2_unicode_compatible rather than repeating methods
|
Python
|
isc
|
CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer
|
9be09ccf5749fae1d7a72663d592de5a88a755eb
|
archive/archive_api/src/responses.py
|
archive/archive_api/src/responses.py
|
# -*- encoding: utf-8
import json
from flask import Response, jsonify
class ContextResponse(Response):
"""
This class adds the "@context" parameter to JSON responses before
they're sent to the user.
For an explanation of how this works/is used, read
https://blog.miguelgrinberg.com/post/customizing-the-flask-response-class
"""
context_url = "https://api.wellcomecollection.org/storage/v1/context.json"
def __init__(self, response, **kwargs):
# Here we unmarshal the response as provided by Flask-RESTPlus, add
# the @context parameter, then repack it.
rv = json.loads(response)
# The @context may already be provided if we've been through the
# force_type method below.
if "@context" in rv:
return super(ContextResponse, self).__init__(response, **kwargs)
else:
rv["@context"] = self.context_url
return super(ContextResponse, self).__init__(json.dumps(rv), **kwargs)
@classmethod
def force_type(cls, rv, environ=None):
# All of our endpoints should be returning a dictionary to be
# serialised as JSON.
assert isinstance(rv, dict)
assert "@context" not in rv, rv
rv["@context"] = cls.context_url
return super(ContextResponse, cls).force_type(jsonify(rv), environ)
|
# -*- encoding: utf-8
import json
from flask import Response, jsonify
from werkzeug.wsgi import ClosingIterator
class ContextResponse(Response):
"""
This class adds the "@context" parameter to JSON responses before
they're sent to the user.
For an explanation of how this works/is used, read
https://blog.miguelgrinberg.com/post/customizing-the-flask-response-class
"""
context_url = "https://api.wellcomecollection.org/storage/v1/context.json"
def __init__(self, response, *args, **kwargs):
"""
Unmarshal the response as provided by Flask-RESTPlus, add the
@context parameter, then repack it.
"""
if isinstance(response, ClosingIterator):
response = b''.join([char for char in response])
rv = json.loads(response)
# The @context may already be provided if we've been through the
# force_type method below.
if "@context" in rv:
return super(ContextResponse, self).__init__(response, **kwargs)
else:
rv["@context"] = self.context_url
json_string = json.dumps(rv)
return super(ContextResponse, self).__init__(json_string, **kwargs)
@classmethod
def force_type(cls, rv, environ=None):
# All of our endpoints should be returning a dictionary to be
# serialised as JSON.
assert isinstance(rv, dict)
assert "@context" not in rv, rv
rv["@context"] = cls.context_url
return super(ContextResponse, cls).force_type(jsonify(rv), environ)
|
Handle a Werkzeug ClosingIterator (as exposed by the tests)
|
Handle a Werkzeug ClosingIterator (as exposed by the tests)
|
Python
|
mit
|
wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api
|
939e5721300013b2977375f28897a6a573509112
|
xml4h/exceptions.py
|
xml4h/exceptions.py
|
"""
Custom *xml4h* exceptions.
"""
class BaseXml4hException(Exception):
"""
Base exception class for all non-standard exceptions raised by *xml4h*.
"""
pass
class FeatureUnavailableException(BaseXml4hException):
"""
User has attempted to use a feature that is available in some *xml4h*
implementations/adapters, but is not available in the current one.
"""
pass
class IncorrectArgumentTypeException(ValueError, BaseXml4hException):
"""
Richer flavour of a ValueError that describes exactly what argument
types are expected.
"""
def __init__(self, arg, expected_types):
msg = (u'Argument %s is not one of the expected types: %s'
% (arg, expected_types))
super(IncorrectArgumentTypeException, self).__init__(msg)
|
"""
Custom *xml4h* exceptions.
"""
class Xml4hException(Exception):
"""
Base exception class for all non-standard exceptions raised by *xml4h*.
"""
pass
class FeatureUnavailableException(Xml4hException):
"""
User has attempted to use a feature that is available in some *xml4h*
implementations/adapters, but is not available in the current one.
"""
pass
class IncorrectArgumentTypeException(ValueError, Xml4hException):
"""
Richer flavour of a ValueError that describes exactly what argument
types are expected.
"""
def __init__(self, arg, expected_types):
msg = (u'Argument %s is not one of the expected types: %s'
% (arg, expected_types))
super(IncorrectArgumentTypeException, self).__init__(msg)
|
Rename base exception class; less ugly
|
Rename base exception class; less ugly
|
Python
|
mit
|
jmurty/xml4h,pipermerriam/xml4h,czardoz/xml4h
|
a23e211ebdee849543cd7c729a8dafc145ea6b5c
|
TorGTK/var.py
|
TorGTK/var.py
|
from gi.repository import Gtk
import tempfile
import os.path
version = "0.2.2"
# Define default port numbers
default_socks_port = 19050
default_control_port = 19051
# Tor process descriptor placeholder
tor_process = None
# Tor logfile location placeholder
tor_logfile_dir = tempfile.mkdtemp()
tor_logfile_location = os.path.join(tor_logfile_dir, "tor_log")
# User preferences location placeholder
home_dir = os.path.expanduser("~")
prefs_dir = os.path.join(home_dir, ".local", "share", "torgtk")
prefs_file = os.path.join(prefs_dir, "config")
# Define object dictionary
objs = { }
objs["menuMain"] = Gtk.Menu()
# Define error message types
InfoBox = Gtk.MessageType.INFO
ErrorBox = Gtk.MessageType.ERROR
|
from gi.repository import Gtk
import tempfile
import os.path
import platform
version = "0.2.2"
# Define default port numbers
default_socks_port = 19050
default_control_port = 19051
# Tor process descriptor placeholder
tor_process = None
# Tor logfile location placeholder
tor_logfile_dir = tempfile.mkdtemp()
tor_logfile_location = os.path.join(tor_logfile_dir, "tor_log")
# User preferences location placeholder
if platform.system() == "Windows":
prefs_dir = os.path.join(os.getenv("APPDATA"), "torgtk")
prefs_file = os.path.join(prefs_dir, "config")
else:
home_dir = os.path.expanduser("~")
prefs_dir = os.path.join(home_dir, ".local", "share", "torgtk")
prefs_file = os.path.join(prefs_dir, "config")
# Define object dictionary
objs = { }
objs["menuMain"] = Gtk.Menu()
# Define error message types
InfoBox = Gtk.MessageType.INFO
ErrorBox = Gtk.MessageType.ERROR
|
Add OS detection (mainly Windows vs Unix) to preferences directory selection
|
Add OS detection (mainly Windows vs Unix) to preferences directory selection
|
Python
|
bsd-2-clause
|
neelchauhan/TorGTK,neelchauhan/TorNova
|
3e54119f07b0fdcbbe556e86de3c161a3eb20ddf
|
mwikiircbot.py
|
mwikiircbot.py
|
import ircbotframe
import sys
class Handler:
def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]):
self.channels = channels
self.bot = ircbotframe.ircBot(host, port, name, description)
self.bot.bind("376", self.endMOTD)
self.bot.start()
def endMOTD(self, sender, headers, message):
for chan in self.channels:
bot.joinchan(chan)
def main(cmd, args):
if len(args) < 1:
print("Usage: `" + cmd + " <host> <channel> [<channel> ...]` (for full arguments, see the readme)")
return
else:
Handler(host=args[0])
if __name__ == "__main__":
if __name__ == '__main__':
main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else [])
|
import ircbotframe
import sys
class Handler:
def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]):
self.channels = channels
self.bot = ircbotframe.ircBot(host, port, name, description)
self.bot.bind("376", self.endMOTD)
self.bot.start()
def endMOTD(self, sender, headers, message):
for chan in self.channels:
self.bot.joinchan(chan)
def main(cmd, args):
if len(args) < 2:
print("Usage: " + cmd + " <host> <channel> [<channel> ...]")
return
elif len(args) > 1:
Handler(host=args[0], channels=args[1:])
if __name__ == "__main__":
if __name__ == '__main__':
main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else [])
|
Fix bot not joining any channels
|
Fix bot not joining any channels
Also removed unnecessary usage comment.
|
Python
|
mit
|
fenhl/mwikiircbot
|
e91a923efd7cff36368059f47ffbd52248362305
|
me_api/middleware/me.py
|
me_api/middleware/me.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from flask import Blueprint, jsonify
from me_api.configs import Config
me = Blueprint('me', __name__)
@me.route('/')
def index():
routers = []
for module in Config.modules['modules'].values():
routers.append(module['path'])
return jsonify(me=Config.me, routers=routers)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from flask import Blueprint, jsonify
from me_api.configs import Config
me = Blueprint('me', __name__)
@me.route('/')
def index():
routers = [module_config['path'] for module_config in
Config.modules['modules'].values()]
return jsonify(me=Config.me, routers=routers)
|
Improve the way that get all the routers
|
Improve the way that get all the routers
|
Python
|
mit
|
lord63/me-api
|
850fba4b07e4c444aa8640c6f4c3816f8a3259ea
|
website_medical_patient_species/controllers/main.py
|
website_medical_patient_species/controllers/main.py
|
# -*- coding: utf-8 -*-
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import http
from openerp.http import request
from openerp.addons.website_medical.controllers.main import (
WebsiteMedical
)
class WebsiteMedical(WebsiteMedical):
def _inject_medical_detail_vals(self, patient_id=0, **kwargs):
vals = super(WebsiteMedical, self)._inject_medical_detail_vals(
patient_id,
**kwargs
)
species_ids = request.env['medical.patient.species'].search([])
vals.update({
'species': species_ids,
})
return vals
|
# -*- coding: utf-8 -*-
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp.http import request
from openerp.addons.website_medical.controllers.main import (
WebsiteMedical
)
class WebsiteMedical(WebsiteMedical):
def _inject_medical_detail_vals(self, patient_id=0, **kwargs):
vals = super(WebsiteMedical, self)._inject_medical_detail_vals(
patient_id,
**kwargs
)
species_ids = request.env['medical.patient.species'].search([])
vals.update({
'species': species_ids,
})
return vals
|
Fix lint * Remove stray import to fix lint
|
[FIX] website_medical_patient_species: Fix lint
* Remove stray import to fix lint
|
Python
|
agpl-3.0
|
laslabs/vertical-medical,laslabs/vertical-medical
|
b94697fe7b4299f66336f56fb98f1c902278caed
|
polling_stations/apps/data_collection/management/commands/import_havant.py
|
polling_stations/apps/data_collection/management/commands/import_havant.py
|
from data_collection.management.commands import BaseXpressWebLookupCsvImporter
class Command(BaseXpressWebLookupCsvImporter):
council_id = 'E07000090'
addresses_name = 'HavantPropertyPostCodePollingStationWebLookup-2017-03-20.TSV'
stations_name = 'HavantPropertyPostCodePollingStationWebLookup-2017-03-20.TSV'
elections = [
'local.hampshire.2017-05-04',
'parl.2017-06-08'
]
csv_delimiter = '\t'
|
from data_collection.management.commands import BaseXpressWebLookupCsvImporter
class Command(BaseXpressWebLookupCsvImporter):
council_id = 'E07000090'
addresses_name = 'HavantPropertyPostCodePollingStationWebLookup-2017-03-20.TSV'
stations_name = 'HavantPropertyPostCodePollingStationWebLookup-2017-03-20.TSV'
elections = [
'local.hampshire.2017-05-04',
#'parl.2017-06-08'
]
csv_delimiter = '\t'
|
Remove Havant election id (update expected)
|
Remove Havant election id (update expected)
|
Python
|
bsd-3-clause
|
DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations
|
bd1df334d68c82b0fc57b4c20da7844155382f83
|
numpy-array-of-tuple.py
|
numpy-array-of-tuple.py
|
# Numpy converts a list of tuples *not* into an array of tuples, but into a 2D
# array instead.
list_of_tuples = [(1, 2), (3, 4)]
import numpy as np
print('list of tuples:', list_of_tuples, 'type:', type(list_of_tuples))
A = np.array(list_of_tuples)
print('numpy array of tuples:', A, 'type:', type(A))
# It makes computing unique rows trickier than it should:
unique_A, indices_to_A = np.unique(list_of_tuples, return_inverse=True)
print('naive numpy unique:', unique_A, 'and indices:', indices_to_A) # WRONG!
# Workaround to do np.unique by row (http://stackoverflow.com/a/8024764/3438463)
A_by_row = np.empty(len(list_of_tuples), object)
A_by_row[:] = list_of_tuples
unique_A, indices_to_A = np.unique(A_by_row, return_inverse=True)
print('unique tuples:', unique_A, 'and indices:', indices_to_A)
|
# Numpy converts a list of tuples *not* into an array of tuples, but into a 2D
# array instead.
import numpy as np # 1.11.1
list_of_tuples = [(1, 2), (3, 4)]
print('list of tuples:', list_of_tuples, 'type:', type(list_of_tuples))
A = np.array(list_of_tuples)
print('numpy array of tuples:', A, 'type:', type(A))
# It makes computing unique rows trickier than it should:
unique_A, indices_to_A = np.unique(list_of_tuples, return_inverse=True)
print('naive numpy unique:', unique_A, 'and indices:', indices_to_A) # WRONG!
# Workaround to do np.unique by row (http://stackoverflow.com/a/8024764/3438463)
A_by_row = np.empty(len(list_of_tuples), object)
A_by_row[:] = list_of_tuples
unique_A, indices_to_A = np.unique(A_by_row, return_inverse=True)
print('unique tuples:', unique_A, 'and indices:', indices_to_A)
|
Update numpy array of tuples with np version
|
Update numpy array of tuples with np version
|
Python
|
mit
|
cmey/surprising-snippets,cmey/surprising-snippets
|
717339f2cb2aed818729a407009a30de53b62a2c
|
oocgcm/test/test_eos.py
|
oocgcm/test/test_eos.py
|
import os
import numpy as np
import xarray as xr
from . import TestCase, assert_equal,assert_allclose,requires_numba
from oocgcm.oceanfuncs.eos import misc
@requires_numba
def test_numpy_spice():
assert_allclose(misc._spice(15,33),0.54458641375)
|
import os
import numpy as np
import xarray as xr
from . import TestCase, assert_equal,assert_allclose,requires_numba,has_numba
if has_numba:
from oocgcm.oceanfuncs.eos import misc
@requires_numba
def test_numpy_spice():
assert_allclose(misc._spice(15,33),0.54458641375)
|
Fix has_numba for travis build
|
Fix has_numba for travis build
|
Python
|
apache-2.0
|
lesommer/oocgcm
|
d60ce9b23bcf2f8c60b2a8ce75eeba8779345b8b
|
Orange/tests/__init__.py
|
Orange/tests/__init__.py
|
import os
import unittest
from Orange.widgets.tests import test_setting_provider, \
test_settings_handler, test_context_handler, \
test_class_values_context_handler, test_domain_context_handler
from Orange.widgets.data.tests import test_owselectcolumns
try:
from Orange.widgets.tests import test_widget
run_widget_tests = True
except ImportError:
run_widget_tests = False
def suite():
test_dir = os.path.dirname(__file__)
all_tests = [
unittest.TestLoader().discover(test_dir),
]
load = unittest.TestLoader().loadTestsFromModule
all_tests.extend([
load(test_setting_provider),
load(test_settings_handler),
load(test_context_handler),
load(test_class_values_context_handler),
load(test_domain_context_handler),
load(test_owselectcolumns)
])
if run_widget_tests:
all_tests.extend([
load(test_widget),
])
return unittest.TestSuite(all_tests)
test_suite = suite()
if __name__ == '__main__':
unittest.main(defaultTest='suite')
|
import os
import unittest
from Orange.widgets.tests import test_setting_provider, \
test_settings_handler, test_context_handler, \
test_class_values_context_handler, test_domain_context_handler
from Orange.widgets.data.tests import test_owselectcolumns
try:
from Orange.widgets.tests import test_widget
run_widget_tests = True
except ImportError:
run_widget_tests = False
def suite():
test_dir = os.path.dirname(__file__)
all_tests = [
unittest.TestLoader().discover(test_dir),
]
load = unittest.TestLoader().loadTestsFromModule
all_tests.extend([
load(test_setting_provider),
load(test_settings_handler),
load(test_context_handler),
load(test_class_values_context_handler),
load(test_domain_context_handler),
load(test_owselectcolumns)
])
if run_widget_tests:
all_tests.extend([
#load(test_widget), # does not run on travis
])
return unittest.TestSuite(all_tests)
test_suite = suite()
if __name__ == '__main__':
unittest.main(defaultTest='suite')
|
Disable widget test. (does not run on travis)
|
Disable widget test. (does not run on travis)
|
Python
|
bsd-2-clause
|
marinkaz/orange3,cheral/orange3,qPCR4vir/orange3,kwikadi/orange3,kwikadi/orange3,kwikadi/orange3,cheral/orange3,qusp/orange3,marinkaz/orange3,cheral/orange3,qPCR4vir/orange3,qusp/orange3,qPCR4vir/orange3,marinkaz/orange3,marinkaz/orange3,kwikadi/orange3,cheral/orange3,kwikadi/orange3,qPCR4vir/orange3,qPCR4vir/orange3,qPCR4vir/orange3,cheral/orange3,marinkaz/orange3,cheral/orange3,kwikadi/orange3,qusp/orange3,marinkaz/orange3,qusp/orange3
|
083a4066ed82065aa1b00cb714a7829dc2571327
|
crypto_enigma/_version.py
|
crypto_enigma/_version.py
|
#!/usr/bin/env python
# encoding: utf8
"""
Description
.. note::
Any additional note.
"""
from __future__ import (absolute_import, print_function, division, unicode_literals)
# See - http://www.python.org/dev/peps/pep-0440/
# See - http://semver.org
__author__ = 'Roy Levien'
__copyright__ = '(c) 2014-2015 Roy Levien'
__release__ = '0.2.1' # N(.N)*
__pre_release__ = 'b1' # aN | bN | cN |
__suffix__ = '' #'.dev5' # .devN | | .postN
__version__ = __release__ + __pre_release__ + __suffix__
|
#!/usr/bin/env python
# encoding: utf8
"""
Description
.. note::
Any additional note.
"""
from __future__ import (absolute_import, print_function, division, unicode_literals)
# See - http://www.python.org/dev/peps/pep-0440/
# See - http://semver.org
__author__ = 'Roy Levien'
__copyright__ = '(c) 2014-2015 Roy Levien'
__release__ = '0.2.1' # N(.N)*
__pre_release__ = 'b2' # aN | bN | cN |
__suffix__ = '.dev1' # .devN | | .postN
__version__ = __release__ + __pre_release__ + __suffix__
|
Update test version following release
|
Update test version following release
|
Python
|
bsd-3-clause
|
orome/crypto-enigma-py
|
ed1a14ef8f2038950b7e56c7ae5c21daa1d6618a
|
ordered_model/models.py
|
ordered_model/models.py
|
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db import models
class OrderedModel(models.Model):
"""
An abstract model that allows objects to be ordered relative to each other.
Provides an ``order`` field.
"""
order = models.PositiveIntegerField(editable=False, db_index=True)
class Meta:
abstract = True
ordering = ('order',)
def save(self, *args, **kwargs):
if not self.id:
qs = self.__class__.objects.order_by('-order')
try:
self.order = qs[0].order + 1
except IndexError:
self.order = 0
super(OrderedModel, self).save(*args, **kwargs)
def _move(self, up, qs=None):
if qs is None:
qs = self.__class__._default_manager
if up:
qs = qs.order_by('-order').filter(order__lt=self.order)
else:
qs = qs.filter(order__gt=self.order)
try:
replacement = qs[0]
except IndexError:
# already first/last
return
self.order, replacement.order = replacement.order, self.order
self.save()
replacement.save()
def move(self, direction, qs=None):
self._move(direction == 'up', qs)
def move_down(self):
"""
Move this object down one position.
"""
return self._move(up=False)
def move_up(self):
"""
Move this object up one position.
"""
return self._move(up=True)
|
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models import Max
class OrderedModel(models.Model):
"""
An abstract model that allows objects to be ordered relative to each other.
Provides an ``order`` field.
"""
order = models.PositiveIntegerField(editable=False, db_index=True)
class Meta:
abstract = True
ordering = ('order',)
def save(self, *args, **kwargs):
if not self.id:
c = self.__class__.objects.all().aggregate(Max('order')).get('order__max')
self.order = c and c + 1 or 0
super(OrderedModel, self).save(*args, **kwargs)
def _move(self, up, qs=None):
if qs is None:
qs = self.__class__._default_manager
if up:
qs = qs.order_by('-order').filter(order__lt=self.order)
else:
qs = qs.filter(order__gt=self.order)
try:
replacement = qs[0]
except IndexError:
# already first/last
return
self.order, replacement.order = replacement.order, self.order
self.save()
replacement.save()
def move(self, direction, qs=None):
self._move(direction == 'up', qs)
def move_down(self):
"""
Move this object down one position.
"""
return self._move(up=False)
def move_up(self):
"""
Move this object up one position.
"""
return self._move(up=True)
|
Use aggregate Max to fetch new order value.
|
Use aggregate Max to fetch new order value.
|
Python
|
bsd-3-clause
|
foozmeat/django-ordered-model,foozmeat/django-ordered-model,pombredanne/django-ordered-model,pombredanne/django-ordered-model,pombredanne/django-ordered-model,foozmeat/django-ordered-model
|
6443a0fed1b915745c591f425027d07216d28e12
|
podium/urls.py
|
podium/urls.py
|
"""podium URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/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.conf.urls import url, include
from django.contrib import admin
from .talks import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^talks/', include('podium.talks.urls')),
url(r'^$', views.session_list_view),
]
|
"""podium URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/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.conf.urls import url, include
from django.contrib import admin
from .talks import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^talks/', include('podium.talks.urls')),
url(r'^', include('podium.talks.urls')),
]
|
Use include, not a view, for the root URL.
|
Use include, not a view, for the root URL.
|
Python
|
mit
|
pyatl/podium-django,pyatl/podium-django,pyatl/podium-django
|
04c32537f7925aaeb54d8d7aa6da34ce85479c2c
|
mistraldashboard/test/helpers.py
|
mistraldashboard/test/helpers.py
|
# Copyright 2015 Huawei Technologies Co., Ltd.
#
# 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.
from openstack_dashboard.test import helpers
from mistraldashboard.test.test_data import utils
def create_stubs(stubs_to_create={}):
return helpers.create_stubs(stubs_to_create)
class MistralTestsMixin(object):
def _setup_test_data(self):
super(MistralTestsMixin, self)._setup_test_data()
utils.load_test_data(self)
class TestCase(MistralTestsMixin, helpers.TestCase):
use_mox = False
pass
class APITestCase(MistralTestsMixin, helpers.APITestCase):
use_mox = False
pass
|
# Copyright 2015 Huawei Technologies Co., Ltd.
#
# 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.
from openstack_dashboard.test import helpers
from mistraldashboard.test.test_data import utils
class MistralTestsMixin(object):
def _setup_test_data(self):
super(MistralTestsMixin, self)._setup_test_data()
utils.load_test_data(self)
class TestCase(MistralTestsMixin, helpers.TestCase):
pass
class APITestCase(MistralTestsMixin, helpers.APITestCase):
pass
|
Drop mox, no longer needed
|
Drop mox, no longer needed
The porting of mistral-dashboard is complete.
This fullfills the community goal "Remove Use of mox/mox3 for Testing"
set for Rocky: https://governance.openstack.org/tc/goals/rocky/mox_removal.html
Remove use_mox and remove dead code.
Change-Id: I59839fecd85caaf8b81129b7f890c4ed50d39db8
Signed-off-by: Chuck Short <[email protected]>
|
Python
|
apache-2.0
|
openstack/mistral-dashboard,openstack/mistral-dashboard,openstack/mistral-dashboard
|
087a706fb8cadf98e3bd515427665997ca2001ba
|
tests/pytests/functional/states/test_npm.py
|
tests/pytests/functional/states/test_npm.py
|
import pytest
from salt.exceptions import CommandExecutionError
@pytest.fixture(scope="module", autouse=True)
def install_npm(sminion):
try:
sminion.functions.pkg.install("npm")
# Just name the thing we're looking for
sminion.functions.npm # pylint: disable=pointless-statement
except (CommandExecutionError, AttributeError):
pytest.skip("Unable to install npm")
@pytest.mark.slow_test
@pytest.mark.destructive_test
@pytest.mark.requires_network
def test_removed_installed_cycle(sminion):
project_version = "[email protected]"
success = sminion.functions.npm.uninstall("pm2")
assert success, "Unable to uninstall pm2 in prep for tests"
ret = next(
iter(
sminion.functions.state.single(
"npm.installed", name=project_version
).values()
)
)
success = ret["result"]
assert success, "Failed to states.npm.installed " + project_version + ret["comment"]
ret = next(
iter(
sminion.functions.state.single("npm.removed", name=project_version).values()
)
)
success = ret["result"]
assert success, "Failed to states.npm.removed " + project_version
|
import pytest
from salt.exceptions import CommandExecutionError
@pytest.fixture(scope="module", autouse=True)
def install_npm(sminion):
try:
sminion.functions.state.single("pkg.installed", name="npm")
# Just name the thing we're looking for
sminion.functions.npm # pylint: disable=pointless-statement
except (CommandExecutionError, AttributeError) as e:
pytest.skip("Unable to install npm - " + str(e))
@pytest.mark.slow_test
@pytest.mark.destructive_test
@pytest.mark.requires_network
def test_removed_installed_cycle(sminion):
project_version = "[email protected]"
success = sminion.functions.npm.uninstall("pm2")
assert success, "Unable to uninstall pm2 in prep for tests"
ret = next(
iter(
sminion.functions.state.single(
"npm.installed", name=project_version
).values()
)
)
success = ret["result"]
assert success, "Failed to states.npm.installed " + project_version + ret["comment"]
ret = next(
iter(
sminion.functions.state.single("npm.removed", name=project_version).values()
)
)
success = ret["result"]
assert success, "Failed to states.npm.removed " + project_version
|
Use state.single to not upgrade npm
|
Use state.single to not upgrade npm
|
Python
|
apache-2.0
|
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
|
3071684f73e736950023be9f47c93dd31c50be1c
|
send2trash/compat.py
|
send2trash/compat.py
|
# Copyright 2017 Virgil Dupras
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licenses/bsd_license
import sys
import os
PY3 = sys.version_info[0] >= 3
if PY3:
text_type = str
binary_type = bytes
environb = os.environb
else:
text_type = unicode
binary_type = str
environb = os.environ
|
# Copyright 2017 Virgil Dupras
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licenses/bsd_license
import sys
import os
PY3 = sys.version_info[0] >= 3
if PY3:
text_type = str
binary_type = bytes
if os.supports_bytes_environ:
# environb will be unset under Windows, but then again we're not supposed to use it.
environb = os.environb
else:
text_type = unicode
binary_type = str
environb = os.environ
|
Fix newly-introduced crash under Windows
|
Fix newly-introduced crash under Windows
ref #14
|
Python
|
bsd-3-clause
|
hsoft/send2trash
|
6fcc041c45dc426d570aa4c44e48c3fc9d8fd5c0
|
settings/settings.py
|
settings/settings.py
|
# This file contains the project wide settings. It is not
# part of version control and it should be adapted to
# suit each deployment.
from os import environ
# Use the absolute path to the directory that stores the data.
# This can differ per deployment
DATA_DIRECTORY = "/cheshire3/clic/dbs/dickens/data/"
#TODO: make the cache settings imported in api.py
CACHE_DIR = ""
CACHE_LOCK = ""
# Check whether there are local settings.
# If there are, then overwrite the above settings
# with the specific settings defined in the local settings
try:
environ['CLIC_SETTINGS'] == 'local'
from local_settings import *
print 'Using the local settings (local_settings.py)'
except KeyError:
print 'Using the standard settings file (settings.py)'
|
# This file contains the project wide settings. It is not
# part of version control and it should be adapted to
# suit each deployment.
from os import environ
# Use the absolute path to the directory that stores the data.
# This can differ per deployment
DATA_DIRECTORY = "/home/vagrant/code/clic-project/clic/dbs/dickens/data/"
#TODO: make the cache settings imported in api.py
CACHE_DIR = ""
CACHE_LOCK = ""
# Check whether there are local settings.
# If there are, then overwrite the above settings
# with the specific settings defined in the local settings
try:
environ['CLIC_SETTINGS'] == 'local'
from local_settings import *
print 'Using the local settings (local_settings.py)'
except KeyError:
print 'Using the standard settings file (settings.py)'
|
Update the setting DATA_DIRECTORY to match the vagrant setup
|
Update the setting DATA_DIRECTORY to match the vagrant setup
|
Python
|
mit
|
CentreForCorpusResearch/clic,CentreForCorpusResearch/clic,CentreForResearchInAppliedLinguistics/clic,CentreForResearchInAppliedLinguistics/clic,CentreForResearchInAppliedLinguistics/clic,CentreForCorpusResearch/clic
|
11b70d10b07c38c1d84b58f5e8563a43c44d8f91
|
pyop/tests.py
|
pyop/tests.py
|
'''
These are tests to assist with creating :class:`.LinearOperator`.
'''
import numpy as np
from numpy.testing import assert_allclose
def adjointTest(O, significant = 7):
''' Test for verifying forward and adjoint functions in LinearOperator.
adjointTest verifies correctness for the forward and adjoint functions
for an operator via asserting :math:`<A^H y, x> = <y, A x>`
Parameters
----------
O : LinearOperator
The LinearOperator to test.
significant : int, optional
Perform the test with a numerical accuracy of "significant" digits.
Examples
--------
>>> from pyop import LinearOperator
>>> A = LinearOperator((4,4), lambda _, x: x, lambda _, x: x)
>>> adjointTest(A)
>>> B = LinearOperator((4,4), lambda _, x: x, lambda _, x: 2*x)
>>> adjointTest(B)
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
AssertionError:
'''
x = np.random.rand(O.shape[1])
y = np.random.rand(O.shape[0])
assert_allclose(O.T(y).dot(x), y.dot(O(x)), rtol = 10**significant)
|
'''
These are tests to assist with creating :class:`.LinearOperator`.
'''
import numpy as np
from numpy.testing import assert_allclose
def adjointTest(O, significant = 7):
''' Test for verifying forward and adjoint functions in LinearOperator.
adjointTest verifies correctness for the forward and adjoint functions
for an operator via asserting :math:`<A^H y, x> = <y, A x>`
Parameters
----------
O : LinearOperator
The LinearOperator to test.
significant : int, optional
Perform the test with a numerical accuracy of "significant" digits.
Examples
--------
>>> from pyop import LinearOperator
>>> A = LinearOperator((4,4), lambda _, x: x, lambda _, x: x)
>>> adjointTest(A)
>>> B = LinearOperator((4,4), lambda _, x: x, lambda _, x: 2*x)
>>> adjointTest(B)
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
AssertionError:
'''
x = np.random.rand(O.shape[1])
y = np.random.rand(O.shape[0])
assert_allclose(O.T(y).dot(x), y.dot(O(x)), rtol = 10**(-significant))
|
Fix wrong rtol in adjointTest
|
Fix wrong rtol in adjointTest
|
Python
|
bsd-3-clause
|
ryanorendorff/pyop
|
1b6217eea2284814583447901661823f3a3d0240
|
service/scheduler/schedule.py
|
service/scheduler/schedule.py
|
import os
import sys
import time
from redis import StrictRedis
from rq import Queue
from apscheduler.schedulers.blocking import BlockingScheduler
sys.path.append('/usr/local/d1lod')
from d1lod import jobs
conn = StrictRedis(host='redis', port='6379')
q = Queue(connection=conn)
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=1)
def timed_job():
print('This job is run every 1 minute.')
@sched.scheduled_job('interval', minutes=1)
def debug_job():
q.enqueue(jobs.update_graph)
@sched.scheduled_job('interval', minutes=1)
def debug_job():
q.enqueue(jobs.calculate_stats)
time.sleep(10)
sched.start()
|
import os
import sys
import time
from redis import StrictRedis
from rq import Queue
from apscheduler.schedulers.blocking import BlockingScheduler
sys.path.append('/usr/local/d1lod')
from d1lod import jobs
conn = StrictRedis(host='redis', port='6379')
q = Queue(connection=conn)
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=1)
def timed_job():
print('This job is run every 1 minute.')
@sched.scheduled_job('interval', minutes=1)
def debug_job():
q.enqueue(jobs.update_graph)
@sched.scheduled_job('interval', minutes=1)
def debug_job():
q.enqueue(jobs.calculate_stats)
@sched.scheduled_job('interval', minutes=1)
def export_job():
q.enqueue(jobs.export_graph)
@sched.scheduled_job('interval', minutes=1)
def debug_job():
jobs.print_jobs()
time.sleep(10)
sched.start()
|
Add export job and print_job jobs
|
Add export job and print_job jobs
|
Python
|
apache-2.0
|
ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod
|
17ac79bd57c1d89767bffccfec755df159205e2c
|
test/conditional_break/conditional_break.py
|
test/conditional_break/conditional_break.py
|
import sys
import lldb
import lldbutil
def stop_if_called_from_a():
# lldb.debugger_unique_id stores the id of the debugger associated with us.
dbg = lldb.SBDebugger.FindDebuggerWithID(lldb.debugger_unique_id)
# Perform synchronous interaction with the debugger.
dbg.SetAsync(False)
# Get the command interpreter.
ci = dbg.GetCommandInterpreter()
# And the result object for ci interaction.
res = lldb.SBCommandReturnObject()
# Retrieve the target, process, and the only thread.
target = dbg.GetSelectedTarget()
process = target.GetProcess()
thread = process.GetThreadAtIndex(0)
# We check the call frames in order to stop only when the immediate caller
# of the leaf function c() is a(). If it's not the right caller, we ask the
# command interpreter to continue execution.
#print >> sys.stdout, "Checking call frames..."
#lldbutil.PrintStackTrace(thread)
if thread.GetNumFrames() >= 2:
funcs = lldbutil.GetFunctionNames(thread)
#print >> sys.stdout, funcs[0], "called from", funcs[1]
if (funcs[0] == 'c' and funcs[1] == 'a'):
#print >> sys.stdout, "Stopped at c() with immediate caller as a()."
pass
else:
#print >> sys.stdout, "Continuing..."
ci.HandleCommand("process continue", res)
return True
|
import sys
import lldb
import lldbutil
def stop_if_called_from_a():
# lldb.debugger_unique_id stores the id of the debugger associated with us.
dbg = lldb.SBDebugger.FindDebuggerWithID(lldb.debugger_unique_id)
# Perform synchronous interaction with the debugger.
dbg.SetAsync(False)
# Retrieve the target, process, and the only thread.
target = dbg.GetSelectedTarget()
process = target.GetProcess()
thread = process.GetThreadAtIndex(0)
# We check the call frames in order to stop only when the immediate caller
# of the leaf function c() is a(). If it's not the right caller, we ask the
# command interpreter to continue execution.
#print >> sys.stdout, "Checking call frames..."
#lldbutil.PrintStackTrace(thread)
if thread.GetNumFrames() >= 2:
funcs = lldbutil.GetFunctionNames(thread)
#print >> sys.stdout, funcs[0], "called from", funcs[1]
if (funcs[0] == 'c' and funcs[1] == 'a'):
#print >> sys.stdout, "Stopped at c() with immediate caller as a()."
pass
else:
#print >> sys.stdout, "Continuing..."
process.Continue()
return True
|
Simplify the breakpoint command function. Instead of fetching the command interpreter and run the "process continue" command, use the SBProcess.Continue() API.
|
Simplify the breakpoint command function. Instead of fetching the command interpreter
and run the "process continue" command, use the SBProcess.Continue() API.
git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@122434 91177308-0d34-0410-b5e6-96231b3b80d8
|
Python
|
apache-2.0
|
apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb
|
8a6002015cf873d3054bd20d8d287a3fe7be6b84
|
server.py
|
server.py
|
from tornado import ioloop, web, websocket
class EchoWebSocket(websocket.WebSocketHandler):
def open(self):
print("WebSocket opened")
def on_message(self, message):
self.write_message("You said: " + message)
def on_close(self):
print("WebSocket closed")
class MainHandler(web.RequestHandler):
def get(self):
print 'MainHandler get'
self.write('''<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var ws = new WebSocket("ws://localhost:8888/_channel/");
ws.onopen = function() {
ws.send("Hello, world");
};
ws.onmessage = function (evt) {
alert(evt.data);
};
</script>
</body>
</html>''')
if __name__ == '__main__':
application = web.Application([
('/_channel/', EchoWebSocket),
('/', MainHandler),
])
application.listen(8888)
ioloop.IOLoop.instance().start()
|
from tornado import ioloop, web, websocket
class EchoWebSocket(websocket.WebSocketHandler):
def open(self):
print("WebSocket opened")
def on_message(self, message):
self.write_message("You said: " + message)
def on_close(self):
print("WebSocket closed")
SCRIPT = '''
<script type="text/javascript">
var ws = new WebSocket("ws://localhost:8888/_channel/");
ws.onopen = function() {
ws.send("Hello, world");
};
ws.onmessage = function (evt) {
alert(evt.data);
};
</script>
'''
class MainHandler(web.RequestHandler):
def get(self, path):
print self.request.path
with open('.' + self.request.path) as html_file:
for line in html_file:
if '</body>' not in line:
self.write(line)
else:
in_body, after_body = line.split('</body>')
self.write(in_body)
self.write(SCRIPT)
self.write('</body>')
self.write(after_body)
if __name__ == '__main__':
application = web.Application([
('/_channel/', EchoWebSocket),
('/(.+\.html)', MainHandler),
], template_path='.')
application.listen(8888)
ioloop.IOLoop.instance().start()
|
Load file or path now.
|
Load file or path now.
|
Python
|
bsd-3-clause
|
GrAndSE/livehtml,GrAndSE/livehtml
|
d00e84e1e41b43f5b680bb310b68444cd9bbcba5
|
fireplace/cards/tgt/shaman.py
|
fireplace/cards/tgt/shaman.py
|
from ..utils import *
##
# Hero Powers
# Lightning Jolt
class AT_050t:
play = Hit(TARGET, 2)
##
# Minions
# Tuskarr Totemic
class AT_046:
play = Summon(CONTROLLER, RandomTotem())
# Draenei Totemcarver
class AT_047:
play = Buff(SELF, "AT_047e") * Count(FRIENDLY_MINIONS + TOTEM)
# Thunder Bluff Valiant
class AT_049:
inspire = Buff(FRIENDLY_MINIONS + TOTEM, "AT_049e")
##
# Spells
# Healing Wave
class AT_048:
play = JOUST & Heal(TARGET, 7) | Heal(TARGET, 14)
# Elemental Destruction
class AT_051:
play = Hit(ALL_MINIONS, RandomNumber(4, 5))
# Ancestral Knowledge
class AT_053:
play = Draw(CONTROLLER) * 2
##
# Weapons
# Charged Hammer
class AT_050:
deathrattle = Summon(CONTROLLER, "AT_050t")
|
from ..utils import *
##
# Hero Powers
# Lightning Jolt
class AT_050t:
play = Hit(TARGET, 2)
##
# Minions
# Tuskarr Totemic
class AT_046:
play = Summon(CONTROLLER, RandomTotem())
# Draenei Totemcarver
class AT_047:
play = Buff(SELF, "AT_047e") * Count(FRIENDLY_MINIONS + TOTEM)
# Thunder Bluff Valiant
class AT_049:
inspire = Buff(FRIENDLY_MINIONS + TOTEM, "AT_049e")
# The Mistcaller
class AT_054:
# The Enchantment ID is correct
play = Buff(FRIENDLY + (IN_DECK | IN_HAND), "AT_045e")
##
# Spells
# Healing Wave
class AT_048:
play = JOUST & Heal(TARGET, 7) | Heal(TARGET, 14)
# Elemental Destruction
class AT_051:
play = Hit(ALL_MINIONS, RandomNumber(4, 5))
# Ancestral Knowledge
class AT_053:
play = Draw(CONTROLLER) * 2
##
# Weapons
# Charged Hammer
class AT_050:
deathrattle = Summon(CONTROLLER, "AT_050t")
|
Implement more TGT Shaman cards
|
Implement more TGT Shaman cards
|
Python
|
agpl-3.0
|
oftc-ftw/fireplace,amw2104/fireplace,amw2104/fireplace,smallnamespace/fireplace,jleclanche/fireplace,liujimj/fireplace,Ragowit/fireplace,Meerkov/fireplace,liujimj/fireplace,smallnamespace/fireplace,Meerkov/fireplace,beheh/fireplace,oftc-ftw/fireplace,Ragowit/fireplace,NightKev/fireplace
|
4021d27a7bd15a396b637beb57c10fc95936cb3f
|
snippet_parser/fr.py
|
snippet_parser/fr.py
|
#-*- encoding: utf-8 -*-
import base
class SnippetParser(base.SnippetParserBase):
def strip_template(self, template, normalize, collapse):
if template.name.matches('unité'):
return ' '.join(map(unicode, template.params[:2]))
elif self.is_citation_needed(template):
repl = [base.CITATION_NEEDED_MARKER]
if template.params:
repl = [template.params[0].value.strip_code()] + repl
return ''.join(repl)
return ''
|
#-*- encoding: utf-8 -*-
import base
def handle_date(template):
year = None
if len(template.params) >= 3:
try:
year = int(unicode(template.params[2]))
except ValueError:
pass
if isinstance(year, int):
# assume {{date|d|m|y|...}}
return ' '.join(map(unicode, template.params[:3]))
else:
# assume {{date|d m y|...}}
return unicode(template.params[0])
def handle_s(template):
ret = template.params[0]
if len(template.params) == 2:
ret += template.params[1]
if template.name.matches('-s'):
ret += ' av. J.-C'
return ret
class SnippetParser(base.SnippetParserBase):
def strip_template(self, template, normalize, collapse):
if template.name.matches('unité'):
return ' '.join(map(unicode, template.params[:2]))
elif template.name.matches('date'):
return handle_date(template)
elif template.name.matches('s') or template.name.matches('-s'):
return handle_s(template)
elif self.is_citation_needed(template):
repl = [base.CITATION_NEEDED_MARKER]
if template.params:
repl = [template.params[0].value.strip_code()] + repl
return ''.join(repl)
return ''
|
Implement a couple of other French templates.
|
Implement a couple of other French templates.
Still need to add tests for these.
|
Python
|
mit
|
Stryn/citationhunt,jhsoby/citationhunt,Stryn/citationhunt,Stryn/citationhunt,jhsoby/citationhunt,jhsoby/citationhunt,jhsoby/citationhunt,Stryn/citationhunt
|
77c114925fb45fa56c1da358ed47d8222775f99f
|
tailor/listeners/mainlistener.py
|
tailor/listeners/mainlistener.py
|
from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import isUpperCamelCase
class MainListener(SwiftListener):
def enterClassName(self, ctx):
className = ctx.getText()
if not isUpperCamelCase(className):
print('Line', str(ctx.start.line) + ':', 'Class names should be in UpperCamelCase')
|
from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import isUpperCamelCase
class MainListener(SwiftListener):
def enterClassName(self, ctx):
className = ctx.getText()
if not isUpperCamelCase(className):
print('Line', str(ctx.start.line) + ':', 'Class names should be in UpperCamelCase')
def enterEnumName(self, ctx):
pass
def enterEnumCaseName(self, ctx):
pass
def exitStructName(self, ctx):
pass
|
Add overrides for UpperCamelCase construct names
|
Add overrides for UpperCamelCase construct names
|
Python
|
mit
|
sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor
|
f5e6ba58fa29bd89722c1e4bf4ec743eb1125f75
|
python/helpers/pycharm/django_manage_shell.py
|
python/helpers/pycharm/django_manage_shell.py
|
#!/usr/bin/env python
from fix_getpass import fixGetpass
import os
from django.core import management
import sys
try:
from runpy import run_module
except ImportError:
from runpy_compat import run_module
def run(working_dir):
sys.path.insert(0, working_dir)
manage_file = os.getenv('PYCHARM_DJANGO_MANAGE_MODULE')
if not manage_file:
manage_file = 'manage'
def execute_manager(settings_mod, argv = None):
management.setup_environ(settings_mod)
management.execute_manager = execute_manager
def execute_from_command_line(argv=None):
pass
management.execute_from_command_line = execute_from_command_line
fixGetpass()
run_module(manage_file, None, '__main__', True)
|
#!/usr/bin/env python
from fix_getpass import fixGetpass
import os
from django.core import management
import sys
try:
from runpy import run_module
except ImportError:
from runpy_compat import run_module
def run(working_dir):
sys.path.insert(0, working_dir)
manage_file = os.getenv('PYCHARM_DJANGO_MANAGE_MODULE')
if not manage_file:
manage_file = 'manage'
def execute_manager(settings_mod, argv = None):
management.setup_environ(settings_mod)
management.execute_manager = execute_manager
def execute_from_command_line(argv=None):
pass
management.execute_from_command_line = execute_from_command_line
fixGetpass()
try:
#import settings to prevent circular dependencies later on import django.db
from django.conf import settings
apps=settings.INSTALLED_APPS
# From django.core.management.shell
# XXX: (Temporary) workaround for ticket #1796: force early loading of all
# models from installed apps.
from django.db.models.loading import get_models
get_models()
except:
pass
run_module(manage_file, None, '__main__', True)
|
Fix circular import problem in Django console (PY-9030).
|
Fix circular import problem in Django console (PY-9030).
|
Python
|
apache-2.0
|
retomerz/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,caot/intellij-community,signed/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,slisson/intellij-community,semonte/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,caot/intellij-community,adedayo/intellij-community,FHannes/intellij-community,vladmm/intellij-community,samthor/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,samthor/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,caot/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,hurricup/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,fnouama/intellij-community,slisson/intellij-community,FHannes/intellij-community,kool79/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,ibinti/intellij-community,fitermay/intellij-community,allotria/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,allotria/intellij-community,robovm/robovm-studio,kdwink/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,ibinti/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,robovm/robovm-studio,clumsy/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,ibinti/intellij-community,jagguli/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,fitermay/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,blademainer/intellij-community,slisson/intellij-community,diorcety/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,semonte/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,signed/intellij-community,da1z/intellij-community,izonder/intellij-community,clumsy/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,caot/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,slisson/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,caot/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,retomerz/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,kool79/intellij-community,ibinti/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,vladmm/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ryano144/intellij-community,hurricup/intellij-community,izonder/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,jagguli/intellij-community,kool79/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,robovm/robovm-studio,ryano144/intellij-community,allotria/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,caot/intellij-community,da1z/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,da1z/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,allotria/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,ibinti/intellij-community,fitermay/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,amith01994/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,supersven/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,izonder/intellij-community,petteyg/intellij-community,adedayo/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,amith01994/intellij-community,diorcety/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,jagguli/intellij-community,xfournet/intellij-community,asedunov/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,fitermay/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,clumsy/intellij-community,izonder/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,petteyg/intellij-community,izonder/intellij-community,ibinti/intellij-community,xfournet/intellij-community,allotria/intellij-community,signed/intellij-community,signed/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,diorcety/intellij-community,fitermay/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,slisson/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,signed/intellij-community,kool79/intellij-community,da1z/intellij-community,kool79/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,semonte/intellij-community,apixandru/intellij-community,kool79/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,signed/intellij-community,signed/intellij-community,youdonghai/intellij-community,semonte/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,clumsy/intellij-community,amith01994/intellij-community,supersven/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,adedayo/intellij-community,asedunov/intellij-community,blademainer/intellij-community,ibinti/intellij-community,supersven/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,holmes/intellij-community,allotria/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,semonte/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,kdwink/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,semonte/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,blademainer/intellij-community,retomerz/intellij-community,apixandru/intellij-community,signed/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,diorcety/intellij-community,allotria/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,slisson/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,robovm/robovm-studio,orekyuu/intellij-community,asedunov/intellij-community,allotria/intellij-community,supersven/intellij-community,jagguli/intellij-community,amith01994/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,FHannes/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,izonder/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,da1z/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,signed/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,holmes/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,semonte/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,retomerz/intellij-community,holmes/intellij-community,blademainer/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,dslomov/intellij-community,signed/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,da1z/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,apixandru/intellij-community,asedunov/intellij-community,samthor/intellij-community,kdwink/intellij-community,samthor/intellij-community,supersven/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,semonte/intellij-community,dslomov/intellij-community,xfournet/intellij-community,ryano144/intellij-community,fnouama/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,supersven/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,holmes/intellij-community,asedunov/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,retomerz/intellij-community,robovm/robovm-studio,fitermay/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,retomerz/intellij-community,clumsy/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,kdwink/intellij-community,kool79/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,FHannes/intellij-community,kool79/intellij-community,supersven/intellij-community,Lekanich/intellij-community,allotria/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,blademainer/intellij-community
|
1cba9aec784e54efc647db227a665fa9f88cab27
|
dthm4kaiako/config/__init__.py
|
dthm4kaiako/config/__init__.py
|
"""Configuration for Django system."""
__version__ = "0.9.0"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
|
"""Configuration for Django system."""
__version__ = "0.9.1"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
|
Increment version number to 0.9.1
|
Increment version number to 0.9.1
|
Python
|
mit
|
uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers
|
0c0b163d6454134595fb8ba794281afe56bc0100
|
gae-firebase-listener-python/main.py
|
gae-firebase-listener-python/main.py
|
import os
import webapp2
IS_DEV = os.environ["SERVER_SOFTWARE"][:3] == "Dev"
allowed_users = set()
if IS_DEV:
allowed_users.add("dev-instance")
class LoggingHandler(webapp2.RequestHandler):
def post(self):
user = self.request.headers.get('X-Appengine-Inbound-Appid', None)
if user and user in allowed_users:
firebaseSnapshot = self.request.params['fbSnapshot']
print firebaseSnapshot
else:
print "Got unauthenticated user: %s" % user
app = webapp2.WSGIApplication([
webapp2.Route('/log', LoggingHandler),
])
|
import os
import webapp2
IS_DEV = os.environ["SERVER_SOFTWARE"][:3] == "Dev"
allowed_users = set()
if IS_DEV:
allowed_users.add("dev-instance")
else:
# Add your Java App Engine proxy App Id here
allowed_users.add("your-java-appengine-proxy-app-id")
class LoggingHandler(webapp2.RequestHandler):
def post(self):
user = self.request.headers.get('X-Appengine-Inbound-Appid', None)
if user and user in allowed_users:
firebaseSnapshot = self.request.params['fbSnapshot']
print firebaseSnapshot
else:
print "Got unauthenticated user: %s" % user
app = webapp2.WSGIApplication([
webapp2.Route('/log', LoggingHandler),
])
|
Add proxy app id to listener
|
Add proxy app id to listener
|
Python
|
mit
|
misterwilliam/gae-firebase-event-proxy,misterwilliam/gae-firebase-event-proxy
|
0e6253bb0f06ebd4bf81c9e06037398899e37328
|
main/bfkdf.py
|
main/bfkdf.py
|
import brainfuck
import scrypt
import prng
def hash(password, salt):
k0 = scrypt.hash(password, salt, 512, 4, 8, 96)
code_key = k0[ 0:32]
data_key = k0[32:64]
code_iv = k0[64:80]
data_iv = k0[80:96]
code_rng = prng.AESCTR(code_key, code_iv)
data_rng = prng.AESCTR(data_key, data_iv)
code = brainfuck.BFG(code_rng).random_bf(1024)
print(code)
vm = brainfuck.BFJIT(code, 65536)
b = bytes(vm.eval(data_rng.bytes(), 1000000))
print(b)
k1 = scrypt.hash(b, salt, 512, 4, 8, 32)
return scrypt.hash(k1 + password, salt, 512, 4, 8, 32)
|
import brainfuck
import scrypt
import prng
def hash(password, salt):
"""The hash function you want to call."""
k0 = scrypt.hash(password, salt, 512, 4, 8, 48)
debug("k0", k0)
rng = prng.AESCTR(k0[:32], k0[32:])
b = run_brainfuck(rng)
k1 = scrypt.hash(b, salt, 512, 4, 8, 32)
debug("k1", k1)
key = scrypt.hash(k1 + password, salt, 512, 4, 8, 32)
debug("key", key)
return key
def run_brainfuck(rng):
"""Futile attempt to preseve randomness."""
output = b''
while len(output) < 48 or len(set(output)) < 44:
code = brainfuck.BFG(rng).random_bf(1024)
vm = brainfuck.BFJIT(code, 65536)
chunk = bytes(vm.eval(rng.bytes(), 1000000))
debug("chunk", chunk)
output += chunk
return output
def debug(label, data):
return
d = ''.join([ hex(b)[2:].rjust(2, '0') for b in data ])
d = d if len(d) < 100 else d[:50] + '...' + d[-50:]
print(label, '=', d, 'bytes =', len(data), 'unique bytes =', len(set(data)))
|
Make some attempt to preserve randomness. Use only 1 AES CTR step.
|
Make some attempt to preserve randomness. Use only 1 AES CTR step.
|
Python
|
unlicense
|
stribika/bfkdf
|
db4b8b2abbb1726a3d2db3496b82e0ad6c0572e9
|
gateway_mac.py
|
gateway_mac.py
|
import socket, struct
import scapy.all as scapy
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1,
verbose=False)[0]
clients_list = []
for element in answered_list:
client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
clients_list.append(client_dict)
return clients_list
if __name__ == '__main__':
default_gw = get_default_gateway_linux()
print(get_mac(default_gw))
|
import socket, struct
import scapy.all as scapy
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
routes = []
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
routes.append(socket.inet_ntoa(struct.pack("<L", int(fields[2], 16))))
print(routes)
return routes
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1,
verbose=False)[0]
clients_list = []
for element in answered_list:
client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
clients_list.append(client_dict)
return clients_list
if __name__ == '__main__':
default_gw = get_default_gateway_linux()
for g in default_gw:
print(get_mac(default_gw))
|
Update to support multiple default gateways
|
Update to support multiple default gateways
|
Python
|
mit
|
nulledbyte/scripts
|
b256f2733d32b55e6a3a7ebfa1300b1a13555bab
|
tools/pdtools/setup.py
|
tools/pdtools/setup.py
|
from setuptools import setup, find_packages
setup(
name="pdtools",
version='0.8.0',
author="ParaDrop Labs",
description="ParaDrop development tools",
install_requires=[
'click>=6.7',
'future>=0.16.0',
'PyYAML>=3.12',
'requests>=2.18.1',
'six>=1.10.0'
],
packages=find_packages(),
entry_points={
'console_scripts': [
'pdtools = pdtools.__main__:main',
],
},
)
|
from setuptools import setup, find_packages
setup(
name="pdtools",
version='0.8.0',
author="ParaDrop Labs",
description="ParaDrop development tools",
install_requires=[
'click>=6.7',
'future>=0.16.0',
'GitPython>=2.1.5',
'PyYAML>=3.12',
'requests>=2.18.1',
'six>=1.10.0'
],
packages=find_packages(),
entry_points={
'console_scripts': [
'pdtools = pdtools.__main__:main',
],
},
)
|
Add GitPython dependency for pdtools.
|
Add GitPython dependency for pdtools.
|
Python
|
apache-2.0
|
ParadropLabs/Paradrop,ParadropLabs/Paradrop,ParadropLabs/Paradrop
|
4db52d5c8a10460fb9ea4a701e953f790a720f83
|
admin/common_auth/forms.py
|
admin/common_auth/forms.py
|
from __future__ import absolute_import
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.contrib.auth.models import Group
from osf.models.user import OSFUser
from admin.common_auth.models import AdminProfile
class LoginForm(forms.Form):
email = forms.CharField(label=u'Email', required=True)
password = forms.CharField(
label=u'Password',
widget=forms.PasswordInput(render_value=False),
required=True
)
class UserRegistrationForm(UserCreationForm):
group_perms = forms.ModelMultipleChoiceField(
queryset=Group.objects.filter(name='prereg_group'),
widget=FilteredSelectMultiple('verbose name', is_stacked=False),
required=False
)
class Meta:
model = OSFUser
fields = ['given_name', 'username']
def __init__(self, *args, **kwargs):
super(UserRegistrationForm, self).__init__(*args, **kwargs)
self.fields['first_name'].required = True
self.fields['last_name'].required = True
self.fields['osf_id'].required = True
class DeskUserForm(forms.ModelForm):
class Meta:
model = AdminProfile
fields = ['desk_token', 'desk_token_secret']
|
from __future__ import absolute_import
from django import forms
from django.db.models import Q
from django.contrib.auth.models import Group
from admin.common_auth.models import AdminProfile
class LoginForm(forms.Form):
email = forms.CharField(label=u'Email', required=True)
password = forms.CharField(
label=u'Password',
widget=forms.PasswordInput(render_value=False),
required=True
)
class UserRegistrationForm(forms.Form):
""" A form that finds an existing OSF User, and grants permissions to that
user so that they can use the admin app"""
osf_id = forms.CharField(required=True, max_length=5, min_length=5)
group_perms = forms.ModelMultipleChoiceField(
queryset=Group.objects.filter(Q(name='prereg_group') | Q(name='osf_admin')),
required=True
)
class DeskUserForm(forms.ModelForm):
class Meta:
model = AdminProfile
fields = ['desk_token', 'desk_token_secret']
|
Update UserRegistrationForm to be connected to an existing OSF user.
|
Update UserRegistrationForm to be connected to an existing OSF user.
|
Python
|
apache-2.0
|
aaxelb/osf.io,Nesiehr/osf.io,erinspace/osf.io,brianjgeiger/osf.io,TomBaxter/osf.io,adlius/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,crcresearch/osf.io,brianjgeiger/osf.io,binoculars/osf.io,adlius/osf.io,laurenrevere/osf.io,mfraezz/osf.io,cslzchen/osf.io,caneruguz/osf.io,chrisseto/osf.io,felliott/osf.io,monikagrabowska/osf.io,brianjgeiger/osf.io,felliott/osf.io,sloria/osf.io,icereval/osf.io,mfraezz/osf.io,mattclark/osf.io,Nesiehr/osf.io,felliott/osf.io,mattclark/osf.io,hmoco/osf.io,caseyrollins/osf.io,aaxelb/osf.io,Johnetordoff/osf.io,crcresearch/osf.io,mfraezz/osf.io,binoculars/osf.io,acshi/osf.io,baylee-d/osf.io,Johnetordoff/osf.io,chennan47/osf.io,mfraezz/osf.io,caseyrollins/osf.io,pattisdr/osf.io,TomBaxter/osf.io,HalcyonChimera/osf.io,cwisecarver/osf.io,cwisecarver/osf.io,acshi/osf.io,laurenrevere/osf.io,caneruguz/osf.io,HalcyonChimera/osf.io,saradbowman/osf.io,Johnetordoff/osf.io,adlius/osf.io,icereval/osf.io,aaxelb/osf.io,laurenrevere/osf.io,icereval/osf.io,chrisseto/osf.io,brianjgeiger/osf.io,monikagrabowska/osf.io,chrisseto/osf.io,crcresearch/osf.io,hmoco/osf.io,HalcyonChimera/osf.io,hmoco/osf.io,Nesiehr/osf.io,sloria/osf.io,leb2dg/osf.io,chennan47/osf.io,TomBaxter/osf.io,leb2dg/osf.io,hmoco/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,felliott/osf.io,adlius/osf.io,Nesiehr/osf.io,monikagrabowska/osf.io,acshi/osf.io,saradbowman/osf.io,Johnetordoff/osf.io,acshi/osf.io,sloria/osf.io,CenterForOpenScience/osf.io,caneruguz/osf.io,monikagrabowska/osf.io,cwisecarver/osf.io,cslzchen/osf.io,cwisecarver/osf.io,cslzchen/osf.io,caneruguz/osf.io,erinspace/osf.io,erinspace/osf.io,pattisdr/osf.io,baylee-d/osf.io,acshi/osf.io,HalcyonChimera/osf.io,chennan47/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,caseyrollins/osf.io,cslzchen/osf.io,binoculars/osf.io,leb2dg/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,aaxelb/osf.io
|
32c971233fa4c83a163036da0090d35463d43c75
|
bananas/management/commands/syncpermissions.py
|
bananas/management/commands/syncpermissions.py
|
from django.contrib.auth.models import Permission
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = "Create admin permissions"
def handle(self, *args, **options):
if args: # pragma: no cover
raise CommandError("Command doesn't accept any arguments")
return self.handle_noargs(**options)
def handle_noargs(self, *args, **options):
from bananas import admin
from django.contrib import admin as django_admin
from django.contrib.contenttypes.models import ContentType
django_admin.autodiscover()
for model, _ in admin.site._registry.items():
if issubclass(getattr(model, "View", object), admin.AdminView):
meta = model._meta
ct, created = ContentType.objects.get_or_create(
app_label=meta.app_label, model=meta.object_name.lower()
)
if created:
print("Found new admin view: {} [{}]".format(ct.name, ct.app_label))
for codename, name in model._meta.permissions:
p, created = Permission.objects.get_or_create(
codename=codename, name=name, content_type=ct
)
if created:
print("Created permission: {}".format(name))
|
from django.contrib.auth.models import Permission
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = "Create admin permissions"
def handle(self, *args, **options):
if args: # pragma: no cover
raise CommandError("Command doesn't accept any arguments")
return self.handle_noargs(**options)
def handle_noargs(self, *args, **options):
from bananas import admin
from django.contrib import admin as django_admin
from django.contrib.contenttypes.models import ContentType
django_admin.autodiscover()
for model, _ in admin.site._registry.items():
if issubclass(getattr(model, "View", object), admin.AdminView):
meta = model._meta
ct, created = ContentType.objects.get_or_create(
app_label=meta.app_label, model=meta.object_name.lower()
)
if created:
print("Found new admin view: {} [{}]".format(ct.name, ct.app_label))
for codename, name in model._meta.permissions:
p, created = Permission.objects.update_or_create(
codename=codename, content_type=ct, defaults=dict(name=name)
)
if created:
print("Created permission: {}".format(name))
|
Update permission names when syncing
|
Update permission names when syncing
|
Python
|
mit
|
5monkeys/django-bananas,5monkeys/django-bananas,5monkeys/django-bananas
|
66cfb6f42cf681d848f944af5bbb7d472280d895
|
src/pyuniprot/cli.py
|
src/pyuniprot/cli.py
|
import click
from .manager import database
from .webserver.web import get_app
@click.group()
def main():
pass
@main.command()
def update():
"""Update PyUniProt data"""
database.update()
@main.command()
def web():
get_app().run()
|
import click
from .manager import database
from .webserver.web import get_app
@click.group()
def main():
pass
@main.command()
def update():
"""Update PyUniProt data"""
database.update()
@main.command()
@click.option('--host', default='0.0.0.0', help='Flask host. Defaults to localhost')
@click.option('--port', type=int, help='Flask port. Defaults to 5000')
def web(host, port):
get_app().run(host=host, port=port)
|
Add host and port options to web runner
|
Add host and port options to web runner
|
Python
|
apache-2.0
|
cebel/pyuniprot,cebel/pyuniprot
|
44f0207fe58b6798e612c16c06f3a0ee5b94cc9e
|
tests/scoring_engine/web/test_admin.py
|
tests/scoring_engine/web/test_admin.py
|
from web_test import WebTest
from scoring_engine.models.team import Team
from scoring_engine.models.user import User
class TestAdmin(WebTest):
def setup(self):
super(TestAdmin, self).setup()
team1 = Team(name="Team 1", color="White")
self.db.save(team1)
user1 = User(username='testuser', password='testpass', team=team1)
self.db.save(user1)
def auth_and_get_path(self, path):
self.client.login('testuser', 'testpass')
return self.client.get(path)
def test_auth_required_admin(self):
self.verify_auth_required('/admin')
def test_auth_required_admin_status(self):
self.verify_auth_required('/admin/status')
stats_resp = self.auth_and_get_path('/admin/status')
assert stats_resp.status_code == 200
def test_auth_required_admin_manage(self):
self.verify_auth_required('/admin/manage')
stats_resp = self.auth_and_get_path('/admin/manage')
assert stats_resp.status_code == 200
def test_auth_required_admin_stats(self):
self.verify_auth_required('/admin/stats')
stats_resp = self.auth_and_get_path('/admin/stats')
assert stats_resp.status_code == 200
|
from web_test import WebTest
from scoring_engine.models.team import Team
from scoring_engine.models.user import User
class TestAdmin(WebTest):
def setup(self):
super(TestAdmin, self).setup()
team1 = Team(name="Team 1", color="White")
self.db.save(team1)
user1 = User(username='testuser', password='testpass', team=team1)
self.db.save(user1)
def auth_and_get_path(self, path):
self.client.login('testuser', 'testpass')
return self.client.get(path)
def test_auth_required_admin(self):
self.verify_auth_required('/admin')
def test_auth_required_admin_status(self):
self.verify_auth_required('/admin/status')
stats_resp = self.auth_and_get_path('/admin/status')
assert stats_resp.status_code == 200
def test_auth_required_admin_manage(self):
self.verify_auth_required('/admin/manage')
stats_resp = self.auth_and_get_path('/admin/manage')
assert stats_resp.status_code == 200
def test_auth_required_admin_stats(self):
self.verify_auth_required('/admin/stats')
stats_resp = self.auth_and_get_path('/admin/stats')
assert stats_resp.status_code == 200
|
Add extra line for class in test admin
|
Add extra line for class in test admin
Signed-off-by: Brandon Myers <[email protected]>
|
Python
|
mit
|
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
|
6556604fb98c2153412384d6f0f705db2da1aa60
|
tinycss2/css-parsing-tests/make_color3_hsl.py
|
tinycss2/css-parsing-tests/make_color3_hsl.py
|
import colorsys # It turns out Python already does HSL -> RGB!
def trim(s):
return s if not s.endswith('.0') else s[:-2]
print('[')
print(',\n'.join(
'"hsl%s(%s, %s%%, %s%%%s)", [%s, %s, %s, %s]' % (
('a' if a is not None else '', h,
trim(str(s / 10.)), trim(str(l / 10.)),
', %s' % a if a is not None else '') +
tuple(trim(str(round(v, 10)))
for v in colorsys.hls_to_rgb(h / 360., l / 1000., s / 1000.)) +
(a if a is not None else 1,)
)
for a in [None, 1, .2, 0]
for l in range(0, 1001, 125)
for s in range(0, 1001, 125)
for h in range(0, 360, 30)
))
print(']')
|
import colorsys # It turns out Python already does HSL -> RGB!
def trim(s):
return s if not s.endswith('.0') else s[:-2]
print('[')
print(',\n'.join(
'"hsl%s(%s, %s%%, %s%%%s)", [%s, %s, %s, %s]' % (
('a' if alpha is not None else '', hue,
trim(str(saturation / 10.)), trim(str(light / 10.)),
', %s' % alpha if alpha is not None else '') +
tuple(trim(str(round(v, 10)))
for v in colorsys.hls_to_rgb(
hue / 360., light / 1000., saturation / 1000.)) +
(alpha if alpha is not None else 1,)
)
for alpha in [None, 1, .2, 0]
for light in range(0, 1001, 125)
for saturation in range(0, 1001, 125)
for hue in range(0, 360, 30)
))
print(']')
|
Fix failing tests with recent versions of pytest-flake8
|
Fix failing tests with recent versions of pytest-flake8
|
Python
|
bsd-3-clause
|
SimonSapin/tinycss2
|
13a39f4e025160f584beef8442e82ec3c3526a95
|
raco/myrial/cli_test.py
|
raco/myrial/cli_test.py
|
"""Basic test of the command-line interface to Myrial."""
import subprocess
import unittest
class CliTest(unittest.TestCase):
def test_cli(self):
out = subprocess.check_output(['python', 'scripts/myrial',
'examples/reachable.myl'])
self.assertIn('DO', out)
self.assertIn('WHILE', out)
def test_cli_reserved_column_name(self):
proc = subprocess.Popen(
['python', 'scripts/myrial', 'examples/bad_column_name.myl'],
stdout=subprocess.PIPE)
out = proc.communicate()[0]
self.assertIn('The token "SafeDiv" on line 2 is reserved', out)
|
"""Basic test of the command-line interface to Myrial."""
import subprocess
import unittest
class CliTest(unittest.TestCase):
def test_cli(self):
out = subprocess.check_output(['python', 'scripts/myrial',
'examples/reachable.myl'])
self.assertIn('DO', out)
self.assertIn('WHILE', out)
def test_cli_standalone(self):
out = subprocess.check_output(['python', 'scripts/myrial', '-f',
'examples/standalone.myl'])
self.assertIn('Dan Suciu,engineering', out)
def test_cli_reserved_column_name(self):
proc = subprocess.Popen(
['python', 'scripts/myrial', 'examples/bad_column_name.myl'],
stdout=subprocess.PIPE)
out = proc.communicate()[0]
self.assertIn('The token "SafeDiv" on line 2 is reserved', out)
|
Test of standalone myrial mode
|
Test of standalone myrial mode
|
Python
|
bsd-3-clause
|
uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco
|
0940612c13094f1950c70b4abc66ddcd76b20544
|
setup.py
|
setup.py
|
from setuptools import setup
setup(
name='Fulfil-Shop',
version='0.1dev',
packages=['shop'],
license='BSD',
include_package_data=True,
zip_safe=False,
long_description=open('README.rst').read(),
install_requires=[
'Flask',
'Flask-WTF',
'Flask-Assets',
'Flask-Login',
'Flask-Cache',
'Flask-DebugToolbar',
'Flask-Themes2',
'Flask-Babel',
'Flask-Redis',
'Flask-Fulfil',
'raven[flask]',
'premailer',
]
)
|
from setuptools import setup
setup(
name='Fulfil-Shop',
version='0.1dev',
packages=['shop'],
license='BSD',
include_package_data=True,
zip_safe=False,
long_description=open('README.rst').read(),
install_requires=[
'Flask',
'Flask-WTF',
'Flask-Assets',
'cssmin',
'jsmin',
'Flask-Login',
'Flask-Cache',
'Flask-DebugToolbar',
'Flask-Themes2',
'Flask-Babel',
'Flask-Redis',
'Flask-Fulfil',
'raven[flask]',
'premailer',
]
)
|
Add cssmin and jsmin to requires
|
Add cssmin and jsmin to requires
|
Python
|
bsd-3-clause
|
joeirimpan/shop,joeirimpan/shop,joeirimpan/shop
|
f495656a3a9a19a3bdb7cbb02b188e2c54740626
|
setup.py
|
setup.py
|
from setuptools import setup
setup(
name='django-kewl',
version=".".join(map(str, __import__('short_url').__version__)),
packages=['django_kewl'],
url='https://github.com/Alir3z4/django-kewl',
license='BSD',
author='Alireza Savand',
author_email='[email protected]',
description='Set of Django kewl utilities & helpers & highly used/needed stuff.',
long_description=open('README.rst').read(),
platforms='OS Independent',
platforms='OS Independent',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Framework :: Django',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development'
],
)
|
from setuptools import setup
setup(
name='django-kewl',
version=".".join(map(str, __import__('short_url').__version__)),
packages=['django_kewl'],
url='https://github.com/Alir3z4/django-kewl',
license='BSD',
author='Alireza Savand',
author_email='[email protected]',
description='Set of Django kewl utilities & helpers & highly used/needed stuff.',
long_description=open('README.rst').read(),
platforms='OS Independent',
platforms='OS Independent',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Framework :: Django',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development',
'License :: OSI Approved :: BSD License',
],
)
|
Add BSD license as well
|
Add BSD license as well
|
Python
|
bsd-3-clause
|
Alir3z4/django-kewl
|
922a0a321ee82ad2f23205f8c1ee55bf2c5a35ab
|
setup.py
|
setup.py
|
import setuptools
from flatdict import __version__
setuptools.setup(
name='flatdict',
version=__version__,
description=('Python module for interacting with nested dicts as a '
'single level dict with delimited keys.'),
long_description=open('README.rst').read(),
author='Gavin M. Roy',
author_email='[email protected]',
url='https://github.com/gmr/flatdict',
package_data={'': ['LICENSE', 'README.rst']},
py_modules=['flatdict'],
license='BSD',
classifiers=[
'Topic :: Software Development :: Libraries',
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
],
zip_safe=True)
|
import setuptools
from flatdict import __version__
setuptools.setup(
name='flatdict',
version=__version__,
description=('Python module for interacting with nested dicts as a '
'single level dict with delimited keys.'),
long_description=open('README.rst').read(),
author='Gavin M. Roy',
author_email='[email protected]',
url='https://github.com/gmr/flatdict',
package_data={'': ['LICENSE', 'README.rst']},
py_modules=['flatdict'],
license='BSD',
classifiers=[
'Topic :: Software Development :: Libraries',
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
],
zip_safe=True)
|
Add 3.7 to the trove classifiers
|
Add 3.7 to the trove classifiers
|
Python
|
bsd-3-clause
|
gmr/flatdict,gmr/flatdict
|
274d882fbfb97d6d4cbf013fcdf9d8644e22099e
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
setup(
name='tw2.wysihtml5',
version='0.2',
description='WYSIHTML5 widget for ToscaWidgets2',
author='Moritz Schlarb',
author_email='[email protected]',
url='https://github.com/toscawidgets/tw2.wysihtml5',
install_requires=[
"tw2.core",
"tw2.forms",
'tw2.bootstrap.forms',
"Mako",
## Add other requirements here
# "Genshi",
],
packages=find_packages(exclude=['ez_setup', 'tests']),
namespace_packages=['tw2', 'tw2.bootstrap'],
zip_safe=False,
include_package_data=True,
test_suite='nose.collector',
entry_points="""
[tw2.widgets]
# Register your widgets so they can be listed in the WidgetBrowser
widgets = tw2.wysihtml5
bootstrap = tw2.bootstrap.wysihtml5
""",
keywords=[
'toscawidgets.widgets',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Environment :: Web Environment :: ToscaWidgets',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Software Development :: Widget Sets',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
)
|
from setuptools import setup, find_packages
setup(
name='tw2.wysihtml5',
version='0.3',
description='WYSIHTML5 widget for ToscaWidgets2',
author='Moritz Schlarb',
author_email='[email protected]',
url='https://github.com/toscawidgets/tw2.wysihtml5',
install_requires=[
"tw2.core",
"tw2.forms",
'tw2.bootstrap.forms',
"Mako",
## Add other requirements here
# "Genshi",
],
packages=find_packages(exclude=['ez_setup', 'tests']),
namespace_packages=['tw2', 'tw2.bootstrap'],
zip_safe=False,
include_package_data=True,
test_suite='nose.collector',
entry_points="""
[tw2.widgets]
# Register your widgets so they can be listed in the WidgetBrowser
widgets = tw2.wysihtml5
bootstrap = tw2.bootstrap.wysihtml5
""",
keywords=[
'toscawidgets.widgets',
],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Environment :: Web Environment :: ToscaWidgets',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Software Development :: Widget Sets',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
)
|
Increase version so that my tests can run... :-]
|
Increase version so that my tests can run... :-]
|
Python
|
bsd-2-clause
|
toscawidgets/tw2.wysihtml5,toscawidgets/tw2.wysihtml5
|
a021b077834a932b5c8da6be49bb98e7862392d4
|
setup.py
|
setup.py
|
import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-mingus',
version='0.9.7',
description='A django blog engine.',
long_description=read('README.textile'),
author='Kevin Fricovsky',
author_email='[email protected]',
license='BSD',
url='http://github.com/montylounge/django-mingus/',
keywords = ['blog', 'django',],
packages=[
'mingus',
'mingus.core',
'mingus.core.templatetags',
],
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',
],
zip_safe=False,
)
|
import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-mingus',
version='0.9.7',
description='A django blog engine.',
long_description=read('README.textile'),
author='Kevin Fricovsky',
author_email='[email protected]',
license='BSD',
url='http://github.com/montylounge/django-mingus/',
keywords = ['blog', 'django',],
packages=[
'mingus',
'mingus.core',
'mingus.core.templatetags',
],
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',
],
zip_safe=False,
include_package_data=True,
)
|
Install templates when using pip to install package.
|
Install templates when using pip to install package.
|
Python
|
apache-2.0
|
emorozov/django-mingus,emorozov/django-mingus,emorozov/django-mingus,emorozov/django-mingus
|
32f7b04861c53cf6367ffcb40b4955334742dbad
|
setup.py
|
setup.py
|
from setuptools import setup
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'flask_swagger_ui/README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='flask-swagger-ui',
version='3.0.12a',
description='Swagger UI blueprint for Flask',
long_description=long_description,
url='https://github.com/sveint/flask-swagger-ui',
author='Svein Tore Koksrud Seljebotn',
author_email='[email protected]',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
keywords='flask swagger',
packages=['flask_swagger_ui'],
package_data={
'flask_swagger_ui': [
'README.md',
'templates/*.html',
'dist/VERSION',
'dist/LICENSE',
'dist/README.md',
'dist/*.html',
'dist/*.js',
'dist/*.css',
'dist/*.png'
],
}
)
|
from setuptools import setup
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'flask_swagger_ui/README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='flask-swagger-ui',
version='3.0.12a',
description='Swagger UI blueprint for Flask',
long_description=long_description,
zip_safe=False,
url='https://github.com/sveint/flask-swagger-ui',
author='Svein Tore Koksrud Seljebotn',
author_email='[email protected]',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
keywords='flask swagger',
packages=['flask_swagger_ui'],
package_data={
'flask_swagger_ui': [
'README.md',
'templates/*.html',
'dist/VERSION',
'dist/LICENSE',
'dist/README.md',
'dist/*.html',
'dist/*.js',
'dist/*.css',
'dist/*.png'
],
}
)
|
Mark the module as not zip safe.
|
Mark the module as not zip safe.
The template finder code in Flask doesn't handle zipped eggs well,
and thus won't find index.template.html. This makes the module
crash when attempting to load the UI.
|
Python
|
mit
|
sveint/flask-swagger-ui,sveint/flask-swagger-ui,sveint/flask-swagger-ui
|
e0388a4be8b15964ce87dafcf69805619f273805
|
setup.py
|
setup.py
|
from setuptools import setup
setup(name='pygraphc',
version='0.0.1',
description='Event log clustering in Python',
long_description='This package contains event log clustering method including non-graph and '
'graph-based approaches.',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Security',
],
keywords='log clustering graph anomaly',
url='http://github.com/studiawan/pygraphc/',
author='Hudan Studiawan',
author_email='[email protected]',
license='MIT',
packages=['pygraphc'],
scripts=['scripts/pygraphc'],
install_requires=[
'networkx',
'numpy',
'scipy',
'scikit-learn',
'nltk',
'Sphinx',
'numpydoc',
'TextBlob',
],
include_package_data=True,
zip_safe=False)
|
from setuptools import setup
setup(name='pygraphc',
version='0.0.1',
description='Event log clustering in Python',
long_description='This package contains event log clustering method including non-graph and '
'graph-based approaches.',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Security',
],
keywords='log clustering graph anomaly',
url='http://github.com/studiawan/pygraphc/',
author='Hudan Studiawan',
author_email='[email protected]',
license='MIT',
packages=['pygraphc'],
scripts=['scripts/pygraphc'],
entry_points={
'console_scripts': ['pygraphc=scripts.pygraphc:main']
},
install_requires=[
'networkx',
'scikit-learn',
'nltk',
'Sphinx',
'numpydoc',
'TextBlob',
],
include_package_data=True,
zip_safe=False)
|
Add entry_points to run executable pygraphc
|
Add entry_points to run executable pygraphc
|
Python
|
mit
|
studiawan/pygraphc
|
3dac61f518a0913faa5bb3350d0161f09b63f0e0
|
setup.py
|
setup.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup, find_packages
except ImportError:
import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
import os
setup(
name = "django-powerdns",
version = "0.1",
url = 'http://bitbucket.org/peternixon/django-powerdns/',
download_url = 'http://bitbucket.org/peternixon/django-powerdns/downloads/',
license = 'BSD',
description = "PowerDNS administration module for Django",
author = 'Peter Nixon',
author_email = '[email protected]',
packages = find_packages(),
include_package_data = True,
classifiers = [
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: Name Service (DNS)',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup, find_packages
except ImportError:
import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
import os
setup(
name = "django-powerdns",
version = "0.1",
url = 'http://bitbucket.org/peternixon/django-powerdns/',
download_url = 'http://bitbucket.org/peternixon/django-powerdns/downloads/',
license = 'BSD',
description = "PowerDNS administration module for Django",
author = 'Peter Nixon',
author_email = '[email protected]',
packages = find_packages(),
include_package_data = True,
classifiers = [
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: Name Service (DNS)',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
'Topic :: Software Development :: Libraries :: Python Modules',
]
install_requires=[
'Django>=1.2',
]
)
|
Add Django as a dependency
|
Add Django as a dependency
|
Python
|
bsd-2-clause
|
zefciu/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,allegro/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,zefciu/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,zefciu/django-powerdns-dnssec,allegro/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,allegro/django-powerdns-dnssec,allegro/django-powerdns-dnssec
|
8f2c6cb5da0c456cefe958db305292a0abda8607
|
setup.py
|
setup.py
|
# -*- coding: utf-8 -*-
"""setup.py -- setup file for antimarkdown
"""
import os
from setuptools import setup
README = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'README.rst')
setup(
name = "antimarkdown",
packages = ['antimarkdown'],
install_requires = [
'lxml',
],
package_data = {
'': ['*.txt', '*.html'],
},
zip_safe = False,
version = "1.0.0",
description = "HTML to Markdown converter.",
long_description = open(README).read(),
author = "David Eyk",
author_email = "[email protected]",
url = "http://github.com/Crossway/antimarkdown/",
license = 'BSD',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries',
'Topic :: Internet :: WWW/HTTP :: Site Management',
'Topic :: Software Development :: Documentation',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Filters',
'Topic :: Text Processing :: Markup :: HTML',
'Topic :: Communications :: Email :: Filters',
],
)
|
# -*- coding: utf-8 -*-
"""setup.py -- setup file for antimarkdown
"""
import os
from setuptools import setup
README = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'README.rst')
setup(
name = "antimarkdown",
packages = ['antimarkdown'],
install_requires = [
'lxml',
],
package_data = {
'': ['*.txt', '*.html'],
},
zip_safe = False,
version = "1.0.1",
description = "HTML to Markdown converter.",
long_description = open(README).read(),
author = "David Eyk",
author_email = "[email protected]",
url = "http://github.com/Crossway/antimarkdown/",
license = 'BSD',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries',
'Topic :: Internet :: WWW/HTTP :: Site Management',
'Topic :: Software Development :: Documentation',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Filters',
'Topic :: Text Processing :: Markup :: HTML',
'Topic :: Communications :: Email :: Filters',
],
)
|
Fix license trove classifier, bump to 1.0.1
|
Fix license trove classifier, bump to 1.0.1
|
Python
|
mit
|
Crossway/antimarkdown,Crossway/antimarkdown
|
e1200dfc7a882340037448ff64241786e828c8c3
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
setup(
name='mittn',
use_scm_version=True,
description='Mittn',
long_description=open('README.rst').read(),
classifiers=[
"Programming Language :: Python :: 2.7"
],
license='Apache License 2.0',
author='F-Secure Corporation',
author_email='[email protected]',
url='https://github.com/F-Secure/mittn',
packages=find_packages(exclude=['features']),
install_requires=open('requirements.txt').readlines(),
)
|
from setuptools import setup, find_packages
setup(
name='mittn',
use_scm_version=True,
description='Mittn',
long_description=open('README.rst').read() + '\n' + open('CHANGELOG.rst').read(),
classifiers=[
"Programming Language :: Python :: 2.7"
],
license='Apache License 2.0',
author='F-Secure Corporation',
author_email='[email protected]',
url='https://github.com/F-Secure/mittn',
packages=find_packages(exclude=['features']),
install_requires=open('requirements.txt').readlines(),
)
|
Include changelog on pypi page
|
Dev: Include changelog on pypi page
|
Python
|
apache-2.0
|
F-Secure/mittn,F-Secure/mittn
|
15437c33fd25a1f10c3203037be3bfef17716fbb
|
setup.py
|
setup.py
|
import os
from setuptools import setup, find_packages
LONG_DESCRIPTION = """Django-Prometheus
This library contains code to expose some monitoring metrics relevant
to Django internals so they can be monitored by Prometheus.io.
See https://github.com/korfuri/django-prometheus for usage
instructions.
"""
setup(
name="django-prometheus",
version="1.0.8",
author="Uriel Corfa",
author_email="[email protected]",
description=(
"Django middlewares to monitor your application with Prometheus.io."),
license="Apache",
keywords="django monitoring prometheus",
url="http://github.com/korfuri/django-prometheus",
packages=find_packages(),
test_suite="django_prometheus.tests",
long_description=LONG_DESCRIPTION,
install_requires=[
"prometheus_client>=0.0.13",
],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"Framework :: Django",
"Topic :: System :: Monitoring",
"License :: OSI Approved :: Apache Software License",
],
)
|
import os
from setuptools import setup, find_packages
LONG_DESCRIPTION = """Django-Prometheus
This library contains code to expose some monitoring metrics relevant
to Django internals so they can be monitored by Prometheus.io.
See https://github.com/korfuri/django-prometheus for usage
instructions.
"""
setup(
name="django-prometheus",
version="1.0.8",
author="Uriel Corfa",
author_email="[email protected]",
description=(
"Django middlewares to monitor your application with Prometheus.io."),
license="Apache",
keywords="django monitoring prometheus",
url="http://github.com/korfuri/django-prometheus",
packages=find_packages(),
test_suite="django_prometheus.tests",
long_description=LONG_DESCRIPTION,
install_requires=[
"prometheus_client>=0.0.13",
],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"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",
"Framework :: Django",
"Topic :: System :: Monitoring",
"License :: OSI Approved :: Apache Software License",
],
)
|
Add trove classifiers for Python versions
|
Add trove classifiers for Python versions
These are set to the versions tested by Travis.
This fixes #39.
|
Python
|
apache-2.0
|
korfuri/django-prometheus,obytes/django-prometheus,obytes/django-prometheus,korfuri/django-prometheus
|
0f97e1427cf86cab4d53f613eb440c1cf4426e6d
|
setup.py
|
setup.py
|
from distutils.core import setup
setup(
name = 'django-test-addons',
packages = ['test_addons'],
version = '0.3.5',
description = 'Library to provide support for testing multiple database system like Mongo, Redis, Neo4j along with django.',
author = 'Hakampreet Singh Pandher',
author_email = '[email protected]',
url = 'https://github.com/hspandher/django-test-utils',
download_url = 'https://github.com/hspandher/django-test-utils/tarball/0.1',
keywords = ['testing', 'django', 'mongo', 'redis', 'neo4j', 'TDD', 'python', 'memcache', 'django rest framework'],
license = 'MIT',
install_requires = [
'django>1.6'
],
extras_require = {
'mongo_testing': ['mongoengine>=0.8.7'],
'redis_testing': ['django-redis>=3.8.2'],
'neo4j_testing': ['py2neo>=2.0.6'],
'rest_framework_testing': ['djangorestframework>=3.0.5'],
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Testing',
'Topic :: Database',
],
)
|
from distutils.core import setup
setup(
name = 'django-test-addons',
packages = ['test_addons'],
version = '0.3.6',
description = 'Library to provide support for testing multiple database system like Mongo, Redis, Neo4j along with django.',
author = 'Hakampreet Singh Pandher',
author_email = '[email protected]',
url = 'https://github.com/hspandher/django-test-utils',
download_url = 'https://github.com/hspandher/django-test-utils/tarball/0.3.6',
keywords = ['testing', 'django', 'mongo', 'redis', 'neo4j', 'TDD', 'python', 'memcache', 'django rest framework'],
license = 'MIT',
install_requires = [
'django>1.6'
],
extras_require = {
'mongo_testing': ['mongoengine>=0.8.7'],
'redis_testing': ['django-redis>=3.8.2'],
'neo4j_testing': ['py2neo>=2.0.6'],
'rest_framework_testing': ['djangorestframework>=3.0.5'],
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Testing',
'Topic :: Database',
],
)
|
Change download url for release 0.3.6
|
Change download url for release 0.3.6
|
Python
|
mit
|
hspandher/django-test-addons
|
40afc357e0850c71153f8779583fc03f643b2271
|
setup.py
|
setup.py
|
from setuptools import find_packages, setup
setup(name='satnogsclient',
packages=find_packages(),
version='0.2.5',
author='SatNOGS team',
author_email='[email protected]',
url='https://github.com/satnogs/satnogs-client/',
description='SatNOGS Client',
include_package_data=True,
zip_safe=False,
install_requires=[
'APScheduler',
'SQLAlchemy',
'requests',
'validators',
'python-dateutil',
'ephem',
'pytz',
'flask',
'pyopenssl',
'pyserial',
'flask-socketio',
'redis'
],
extras_require={
'develop': 'flake8'
},
scripts=['satnogsclient/bin/satnogs-poller'])
|
from setuptools import find_packages, setup
setup(
name='satnogsclient',
version='0.2.5',
url='https://github.com/satnogs/satnogs-client/',
author='SatNOGS team',
author_email='[email protected]',
description='SatNOGS Client',
zip_safe=False,
install_requires=[
'APScheduler',
'SQLAlchemy',
'requests',
'validators',
'python-dateutil',
'ephem',
'pytz',
'flask',
'pyopenssl',
'pyserial',
'flask-socketio',
'redis'
],
extras_require={
'develop': 'flake8'
},
scripts=['satnogsclient/bin/satnogs-poller'],
include_package_data=True,
packages=find_packages()
)
|
Reorder and group metadata and options together
|
Reorder and group metadata and options together
|
Python
|
agpl-3.0
|
adamkalis/satnogs-client,adamkalis/satnogs-client
|
b65b0ed8d09d4a22164f16ed60f7c5b71d6f54db
|
setup.py
|
setup.py
|
import setuptools
from gitvendor.version import Version
from setuptools import find_packages
CLASSIFIERS = [
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Environment :: Console',
'Topic :: Software Development'
]
setuptools.setup(name='git-vendor',
version=Version('0.0.1').number,
description='Vendor tagged releases from git to $VCS',
long_description=open('README.md').read().strip(),
author='Charles Butler',
author_email='[email protected]',
url='http://github.com/chuckbutler/git-vendor',
py_modules=[],
packages=find_packages(),
entry_points={
'console_scripts': [
'git-vendor = gitvendor.cli:main'
],
},
install_requires=['gitpython', 'jinja2', 'pyyaml', 'path.py',
'dirsync', 'six'],
package_data={
'template': ['template/vendor-rc'],
},
include_package_data=True,
license='MIT License',
zip_safe=False,
keywords='git, vendor',
classifiers=CLASSIFIERS)
|
import setuptools
from gitvendor.version import Version
from setuptools import find_packages
CLASSIFIERS = [
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Environment :: Console',
'Topic :: Software Development'
]
setuptools.setup(name='git-vendor',
version=Version('0.0.3').number,
description='Vendor tagged releases from git to $VCS',
long_description=open('README.md').read().strip(),
author='Charles Butler',
author_email='[email protected]',
url='http://github.com/chuckbutler/git-vendor',
download_url='https://github.com/chuckbutler/git-vendor/releases/',
py_modules=[],
packages=find_packages(),
entry_points={
'console_scripts': [
'git-vendor = gitvendor.cli:main'
],
},
install_requires=['gitpython', 'jinja2', 'pyyaml', 'path.py',
'dirsync', 'six'],
package_data={
'template': ['template/vendor-rc'],
},
include_package_data=True,
license='MIT License',
zip_safe=False,
keywords='git, vendor',
classifiers=CLASSIFIERS)
|
Move download_url and bump version
|
Move download_url and bump version
|
Python
|
mit
|
chuckbutler/git-vendor
|
c1d111ab00cdc916412cc2985ef4bbc184166f20
|
setup.py
|
setup.py
|
"""
``onecodex``
------------
``onecodex`` provides a command line client for interaction with the
One Codex API.
Links
`````
* `One Codex: <https://www.onecodex.com/>`
* `API Docs: <http://docs.onecodex.com/>`
"""
from setuptools import setup
setup(
name='onecodex',
version='0.0.1',
url='https://www.onecodex.com/',
license='MIT',
author='Nick Boyd Greenfield',
author_email='[email protected]',
description='One Codex Command Line Client',
long_description=__doc__,
packages=['onecodex'],
zip_safe=True,
platforms='any',
install_requires=[
'requests>=2.4.3',
],
test_suite='nose.collector',
entry_points={
'console_scripts': ['onecodex = onecodex.cli:main']
},
)
|
"""
``onecodex``
------------
``onecodex`` provides a command line client for interaction with the
One Codex API.
Links
`````
* `One Codex: <https://www.onecodex.com/>`
* `API Docs: <http://docs.onecodex.com/>`
"""
from setuptools import setup
setup(
name='onecodex',
version='0.0.1',
url='https://www.onecodex.com/',
license='MIT',
author='Reference Genomics, Inc.',
author_email='[email protected]',
description='One Codex Command Line Client',
long_description=__doc__,
packages=['onecodex'],
zip_safe=True,
platforms='any',
install_requires=[
'requests>=2.4.3',
],
test_suite='nose.collector',
entry_points={
'console_scripts': ['onecodex = onecodex.cli:main']
},
)
|
Change contact field and author field for PyPI.
|
Change contact field and author field for PyPI.
|
Python
|
mit
|
onecodex/onecodex,refgenomics/onecodex,refgenomics/onecodex,onecodex/onecodex
|
a30ed634f641c3c62dc0d4501ed4cb852c9930d0
|
setup.py
|
setup.py
|
import os
from setuptools import setup
setup(
name = "augur",
version = "0.1.0",
author = "nextstrain developers",
author_email = "[email protected], [email protected]",
description = ("Pipelines for real-time phylogenetic analysis"),
license = "MIT",
keywords = "nextstrain, molecular epidemiology",
url = "https://github.com/nextstrain/augur",
packages=['augur'],
install_requires = [
"biopython >=1.69, ==1.*",
"boto >=2.38, ==2.*",
"cvxopt >=1.1.8, ==1.1.*",
"ipdb >=0.10.1, ==0.10.*",
"matplotlib >=2.0, ==2.*",
"pandas >=0.16.2, <0.18.0",
"pytest >=3.2.1, ==3.*",
"seaborn >=0.6.0, ==0.6.*",
"tox >=2.8.2, ==2.*",
"treetime ==0.4.0"
],
dependency_links = [
"https://api.github.com/repos/neherlab/treetime/tarball/py3#egg=treetime-0.4.0"
],
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Science",
"License :: OSI Approved :: MIT License",
],
scripts=['bin/augur']
)
|
import os
from setuptools import setup
setup(
name = "augur",
version = "0.1.0",
author = "nextstrain developers",
author_email = "[email protected], [email protected]",
description = ("Pipelines for real-time phylogenetic analysis"),
license = "MIT",
keywords = "nextstrain, molecular epidemiology",
url = "https://github.com/nextstrain/augur",
packages=['augur'],
install_requires = [
"biopython >=1.69, ==1.*",
"boto >=2.38, ==2.*",
"cvxopt >=1.1.8, ==1.1.*",
"ipdb >=0.10.1, ==0.10.*",
"matplotlib >=2.0, ==2.*",
"pandas >=0.16.2, <0.18.0",
"pytest >=3.2.1, ==3.*",
"seaborn >=0.6.0, ==0.6.*",
"tox >=2.8.2, ==2.*",
"treetime ==0.4.0"
],
dependency_links = [
"https://api.github.com/repos/neherlab/treetime/tarball/v0.4.0#egg=treetime-0.4.0"
],
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Science",
"License :: OSI Approved :: MIT License",
],
scripts=['bin/augur']
)
|
Update TreeTime dep link now that the py3 branch is merged
|
Update TreeTime dep link now that the py3 branch is merged
|
Python
|
agpl-3.0
|
nextstrain/augur,blab/nextstrain-augur,nextstrain/augur,nextstrain/augur
|
0f18b3ff63bf6183247e7bce25160547f8cfc21d
|
setup.py
|
setup.py
|
import os
import sys
from distutils.core import setup
if sys.version_info < (3,):
print('\nSorry, but Adventure can only be installed under Python 3.\n')
sys.exit(1)
README_PATH = os.path.join(os.path.dirname(__file__), 'adventure', 'README.txt')
with open(README_PATH, encoding="utf-8") as f:
README_TEXT = f.read()
setup(
name='adventure',
version='1.3',
description='Colossal Cave adventure game at the Python prompt',
long_description=README_TEXT,
author='Brandon Craig Rhodes',
author_email='[email protected]',
url='https://bitbucket.org/brandon/adventure/overview',
packages=['adventure', 'adventure/tests'],
package_data={'adventure': ['README.txt', '*.dat', 'tests/*.txt']},
classifiers=[
'Development Status :: 6 - Mature',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Topic :: Games/Entertainment',
],
)
|
import os
import sys
from distutils.core import setup
if sys.version_info < (3,):
print('\nSorry, but Adventure can only be installed under Python 3.\n')
sys.exit(1)
README_PATH = os.path.join(os.path.dirname(__file__), 'adventure', 'README.txt')
with open(README_PATH, encoding="utf-8") as f:
README_TEXT = f.read()
setup(
name='adventure',
version='1.3',
description='Colossal Cave adventure game at the Python prompt',
long_description=README_TEXT,
author='Brandon Craig Rhodes',
author_email='[email protected]',
url='https://bitbucket.org/brandon/adventure/overview',
packages=['adventure', 'adventure/tests'],
package_data={'adventure': ['README.txt', '*.dat', 'tests/*.txt']},
classifiers=[
'Development Status :: 6 - Mature',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Topic :: Games/Entertainment',
],
)
|
Change PyPI trove classifier for license terms.
|
Change PyPI trove classifier for license terms.
|
Python
|
apache-2.0
|
devinmcgloin/advent,devinmcgloin/advent
|
1641243682f080257b7f79b35503985d3d72aa44
|
setup.py
|
setup.py
|
from setuptools import setup
setup(name='osm_hall_monitor',
version='0.2',
description='Passive changeset monitoring for OpenStreetMap.',
url='http://github.com/ethan-nelson/osm_hall_monitor',
author='Ethan Nelson',
author_email='[email protected]',
install_requires = ['psycopg2','osmdt'],
packages=['osmhm'],
zip_safe=False)
|
from setuptools import setup
setup(name='osm_hall_monitor',
version='0.2',
description='Passive changeset monitoring for OpenStreetMap.',
url='http://github.com/ethan-nelson/osm_hall_monitor',
author='Ethan Nelson',
author_email='[email protected]',
install_requires = ['psycopg2','osm_diff_tool'],
packages=['osmhm'],
zip_safe=False)
|
Fix requirement for diff tool
|
Fix requirement for diff tool
|
Python
|
mit
|
ethan-nelson/osm_hall_monitor
|
024878fc913097364123d28a99ab7cb5501b0af5
|
setup.py
|
setup.py
|
#!/usr/bin/env python
import subprocess
from distutils.core import setup
requirements = [pkg.split('=')[0] for pkg in open('requirements.txt').readlines()]
description = 'Download videos from Udemy for personal offline use'
try:
subprocess.call(["pandoc", "README.md", "-f", "markdown", "-t", "rst", "-o", "README.rst"])
long_description = open("README.rst").read()
except OSError:
print("Pandoc not installed")
long_description = description
classifiers = ['Environment :: Console',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Multimedia :: Video',
]
version = open('CHANGES.txt').readlines()[0][1:].strip()
setup(name='udemy-dl',
version=version,
description=description,
author='Gaganpreet Singh Arora',
author_email='[email protected]',
url='https://github.com/gaganpreet/udemy-dl',
scripts=['src/udemy-dl',],
install_requires=requirements,
long_description=long_description,
packages=['udemy_dl'],
package_dir = {'udemy_dl': 'src/udemy_dl'},
classifiers=classifiers
)
|
#!/usr/bin/env python
import os
import subprocess
from distutils.core import setup
requirements = [pkg.split('=')[0] for pkg in open('requirements.txt').readlines()]
description = 'Download videos from Udemy for personal offline use'
try:
subprocess.call(["pandoc", "README.md", "-f", "markdown", "-t", "rst", "-o", "README.rst"])
long_description = open("README.rst").read()
except OSError:
print("Pandoc not installed")
long_description = description
classifiers = ['Environment :: Console',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Multimedia :: Video',
]
version = open('CHANGES.txt').readlines()[0][1:].strip()
# if installed as root or with sudo, set permission mask to allow read/exec for all users
if os.getuid() == 0:
os.umask(int('022', 8))
setup(name='udemy-dl',
version=version,
description=description,
author='Gaganpreet Singh Arora',
author_email='[email protected]',
url='https://github.com/gaganpreet/udemy-dl',
scripts=['src/udemy-dl',],
install_requires=requirements,
long_description=long_description,
packages=['udemy_dl'],
package_dir = {'udemy_dl': 'src/udemy_dl'},
classifiers=classifiers
)
|
Set permission mask to allow read/exec for all users
|
Set permission mask to allow read/exec for all users
|
Python
|
unlicense
|
rinodung/udemy-dl
|
f27e08b0dcace5b9f49c5b2a211347a2f50f8254
|
stats.py
|
stats.py
|
from bs4 import BeautifulSoup
import requests
def statsRoyale(tag):
link = 'http://statsroyale.com/profile/' + tag
response = (requests.get(link)).text
soup = BeautifulSoup(response, 'html.parser')
stats = {}
content = soup.find_all('div', {'class':'content'})
stats['clan'] = content[0].get_text()
if stats['clan'] == 'No Clan':
stats['clan'] = None
stats['highest_trophies'] = content[1].get_text()
stats['last_known_trophies'] = content[2].get_text()
stats['challenge_cards_won'] = content[3].get_text()
stats['tournament_cards_won'] = content[4].get_text()
stats['total_donations'] = content[5].get_text()
stats['best_session_rank'] = content[6].get_text()
stats['previous_session_rank'] = content[7].get_text()
stats['legendary_trophies'] = content[8].get_text()
stats['wins'] = content[9].get_text()
stats['losses'] = content[10].get_text()
stats['3_crown_wins'] = content[11].get_text()
return stats
stats = statsRoyale(tag='9890JJJV')
print stats
|
from bs4 import BeautifulSoup
import requests
def statsRoyale(tag):
if not tag.find('/') == -1:
tag = tag[::-1]
pos = tag.find('/')
tag = tag[:pos]
tag = tag[::-1]
link = 'http://statsroyale.com/profile/' + tag
response = (requests.get(link)).text
soup = BeautifulSoup(response, 'html.parser')
description = soup.find_all('div', {'class':'description'})
content = soup.find_all('div', {'class':'content'})
stats = {}
for i in range(len(description)):
description_text = ((description[i].get_text()).replace(' ', '_')).lower()
content_text = content[i].get_text()
stats[description_text] = content_text
if stats['clan'] == 'No Clan':
stats['clan'] = None
return stats
stats = statsRoyale(tag='9890JJJV')
print stats
|
Use tags or direct url
|
Use tags or direct url
|
Python
|
mit
|
atulya2109/Stats-Royale-Python
|
30d108b3a206d938ef67c112bc6c953a12c606af
|
tasks.py
|
tasks.py
|
"""Task functions for use with Invoke."""
from invoke import task
@task
def clean(context):
cmd = '$(npm bin)/gulp clean'
context.run(cmd)
@task
def requirements(context):
steps = [
'pip install -r requirements.txt',
'npm install',
'$(npm bin)/bower install',
]
cmd = ' && '.join(steps)
context.run(cmd)
@task
def run(context):
steps = [
'open http://127.0.0.1:5000/',
'FLASK_APP=typesetter/typesetter.py FLASK_DEBUG=1 flask run',
]
cmd = ' && '.join(steps)
context.run(cmd)
@task
def static(context):
cmd = '$(npm bin)/gulp'
context.run(cmd)
|
"""Task functions for use with Invoke."""
from invoke import task
@task
def clean(context):
cmd = '$(npm bin)/gulp clean'
context.run(cmd)
@task
def requirements(context):
steps = [
'pip install -r requirements.txt',
'npm install',
'$(npm bin)/bower install',
]
cmd = ' && '.join(steps)
context.run(cmd)
@task
def run(context, host='127.0.0.1', port='5000'):
steps = [
'open http://{host}:{port}/',
'FLASK_APP=typesetter/typesetter.py FLASK_DEBUG=1 flask run --host={host} --port={port}',
]
steps = [step.format(host=host, port=port) for step in steps]
cmd = ' && '.join(steps)
context.run(cmd)
@task
def static(context):
cmd = '$(npm bin)/gulp'
context.run(cmd)
|
Allow specifying custom host and port when starting app
|
Allow specifying custom host and port when starting app
|
Python
|
mit
|
rlucioni/typesetter,rlucioni/typesetter,rlucioni/typesetter
|
c05b06577785bdf34f1fcd051ecf6d4398d2f77e
|
tasks.py
|
tasks.py
|
from os.path import join
from invoke import Collection, ctask as task
from invocations import docs as _docs
d = 'sites'
# Usage doc/API site (published as docs.paramiko.org)
path = join(d, 'docs')
docs = Collection.from_module(_docs, name='docs', config={
'sphinx.source': path,
'sphinx.target': join(path, '_build'),
})
# Main/about/changelog site ((www.)?paramiko.org)
path = join(d, 'www')
www = Collection.from_module(_docs, name='www', config={
'sphinx.source': path,
'sphinx.target': join(path, '_build'),
})
# Until we move to spec-based testing
@task
def test(ctx):
ctx.run("python test.py --verbose")
@task
def coverage(ctx):
ctx.run("coverage run --source=paramiko test.py --verbose")
ns = Collection(test, coverage, docs=docs, www=www)
|
from os.path import join
from shutil import rmtree, move
from invoke import Collection, ctask as task
from invocations import docs as _docs
from invocations.packaging import publish
d = 'sites'
# Usage doc/API site (published as docs.paramiko.org)
docs_path = join(d, 'docs')
docs_build = join(docs_path, '_build')
docs = Collection.from_module(_docs, name='docs', config={
'sphinx.source': docs_path,
'sphinx.target': docs_build,
})
# Main/about/changelog site ((www.)?paramiko.org)
www_path = join(d, 'www')
www = Collection.from_module(_docs, name='www', config={
'sphinx.source': www_path,
'sphinx.target': join(www_path, '_build'),
})
# Until we move to spec-based testing
@task
def test(ctx):
ctx.run("python test.py --verbose")
@task
def coverage(ctx):
ctx.run("coverage run --source=paramiko test.py --verbose")
# Until we stop bundling docs w/ releases. Need to discover use cases first.
@task('docs') # Will invoke the API doc site build
def release(ctx):
# Move the built docs into where Epydocs used to live
rmtree('docs')
move(docs_build, 'docs')
# Publish
publish(ctx)
ns = Collection(test, coverage, release, docs=docs, www=www)
|
Add new release task w/ API doc prebuilding
|
Add new release task w/ API doc prebuilding
|
Python
|
lgpl-2.1
|
thusoy/paramiko,CptLemming/paramiko,rcorrieri/paramiko,redixin/paramiko,Automatic/paramiko,jaraco/paramiko,esc/paramiko,ameily/paramiko,zarr12steven/paramiko,dorianpula/paramiko,mirrorcoder/paramiko,jorik041/paramiko,thisch/paramiko,dlitz/paramiko,paramiko/paramiko,digitalquacks/paramiko,fvicente/paramiko,SebastianDeiss/paramiko,anadigi/paramiko,varunarya10/paramiko,zpzgone/paramiko,torkil/paramiko,mhdaimi/paramiko,reaperhulk/paramiko,selboo/paramiko,remram44/paramiko,toby82/paramiko,davidbistolas/paramiko
|
f4ba2cba93222b4dd494caf487cdd6be4309e41a
|
studygroups/forms.py
|
studygroups/forms.py
|
from django import forms
from studygroups.models import StudyGroupSignup, Application
from localflavor.us.forms import USPhoneNumberField
class ApplicationForm(forms.ModelForm):
mobile = USPhoneNumberField(required=False)
class Meta:
model = Application
labels = {
'name': 'Please tell us what to call you',
'mobile': 'What is your mobile number?',
'contact_method': 'Please tell us how would you perfer us to contact us',
'computer_access': 'Do you have normal everyday access to the computer?',
'goals': 'Please tell what your learning goals are',
'support': '',
}
widgets = {
'study_groups': forms.CheckboxSelectMultiple,
}
fields = '__all__'
class SignupForm(forms.ModelForm):
mobile = USPhoneNumberField(required=False)
class Meta:
model = StudyGroupSignup
exclude = []
widgets = {
'study_group': forms.HiddenInput
}
class EmailForm(forms.Form):
study_group_id = forms.IntegerField(widget=forms.HiddenInput)
subject = forms.CharField()
body = forms.CharField(widget=forms.Textarea)
sms_body = forms.CharField(max_length=160, widget=forms.Textarea)
|
from django import forms
from studygroups.models import StudyGroupSignup, Application
from localflavor.us.forms import USPhoneNumberField
class ApplicationForm(forms.ModelForm):
mobile = USPhoneNumberField(required=False)
class Meta:
model = Application
labels = {
'name': 'Please tell us what to call you',
'mobile': 'What is your mobile number?',
'contact_method': 'Preferred Method of Contact.',
'computer_access': 'Do you have access to a computer outside of the library?',
'goals': 'In one sentence, please explain your goals for taking this course.',
'support': 'A successful study group requires the support of all of its members. How will you help your peers achieve their goals?',
'study_groups': 'Which course are you applying for? (by applying for a specific course, you agree to attend sessions at the specified time and location).',
}
widgets = {
'study_groups': forms.CheckboxSelectMultiple,
}
fields = '__all__'
class SignupForm(forms.ModelForm):
mobile = USPhoneNumberField(required=False)
class Meta:
model = StudyGroupSignup
exclude = []
widgets = {
'study_group': forms.HiddenInput
}
class EmailForm(forms.Form):
study_group_id = forms.IntegerField(widget=forms.HiddenInput)
subject = forms.CharField()
body = forms.CharField(widget=forms.Textarea)
sms_body = forms.CharField(max_length=160, widget=forms.Textarea)
|
Update labels for application form
|
Update labels for application form
|
Python
|
mit
|
p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles
|
6755255332039ab3c0ea60346f61420b52e2f474
|
tests/functional/test_l10n.py
|
tests/functional/test_l10n.py
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(base_url, selenium):
page = HomePage(base_url, selenium).open()
initial = page.footer.language
# avoid selecting the same language or locales that have homepage redirects
excluded = [initial, 'ja', 'ja-JP-mac', 'zh-TW', 'zh-CN']
available = [l for l in page.footer.languages if l not in excluded]
new = random.choice(available)
page.footer.select_language(new)
assert new in selenium.current_url, 'Language is not in URL'
assert new == page.footer.language, 'Language has not been selected'
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(base_url, selenium):
page = HomePage(base_url, selenium).open()
initial = page.footer.language
# avoid selecting the same language or locales that have homepage redirects
excluded = [initial, 'ja', 'ja-JP-mac', 'zh-TW', 'zh-CN']
available = [l for l in page.footer.languages if l not in excluded]
new = random.choice(available)
page.footer.select_language(new)
assert '/{0}/'.format(new) in selenium.current_url, 'Language is not in URL'
assert new == page.footer.language, 'Language has not been selected'
|
Fix intermittent failure in l10n language selector test
|
Fix intermittent failure in l10n language selector test
|
Python
|
mpl-2.0
|
sgarrity/bedrock,TheoChevalier/bedrock,craigcook/bedrock,mkmelin/bedrock,TheoChevalier/bedrock,Sancus/bedrock,hoosteeno/bedrock,sylvestre/bedrock,schalkneethling/bedrock,Sancus/bedrock,analytics-pros/mozilla-bedrock,sylvestre/bedrock,glogiotatidis/bedrock,jgmize/bedrock,kyoshino/bedrock,mkmelin/bedrock,gerv/bedrock,davehunt/bedrock,alexgibson/bedrock,jpetto/bedrock,sylvestre/bedrock,sgarrity/bedrock,gerv/bedrock,craigcook/bedrock,ericawright/bedrock,analytics-pros/mozilla-bedrock,gauthierm/bedrock,davehunt/bedrock,pascalchevrel/bedrock,flodolo/bedrock,mozilla/bedrock,MichaelKohler/bedrock,alexgibson/bedrock,MichaelKohler/bedrock,gauthierm/bedrock,flodolo/bedrock,ericawright/bedrock,sgarrity/bedrock,analytics-pros/mozilla-bedrock,hoosteeno/bedrock,jpetto/bedrock,flodolo/bedrock,gauthierm/bedrock,gauthierm/bedrock,CSCI-462-01-2017/bedrock,jgmize/bedrock,mkmelin/bedrock,ericawright/bedrock,CSCI-462-01-2017/bedrock,CSCI-462-01-2017/bedrock,Sancus/bedrock,ericawright/bedrock,TheJJ100100/bedrock,glogiotatidis/bedrock,alexgibson/bedrock,sgarrity/bedrock,kyoshino/bedrock,MichaelKohler/bedrock,MichaelKohler/bedrock,TheJJ100100/bedrock,craigcook/bedrock,gerv/bedrock,pascalchevrel/bedrock,kyoshino/bedrock,mozilla/bedrock,jpetto/bedrock,TheoChevalier/bedrock,sylvestre/bedrock,glogiotatidis/bedrock,schalkneethling/bedrock,schalkneethling/bedrock,mozilla/bedrock,hoosteeno/bedrock,alexgibson/bedrock,CSCI-462-01-2017/bedrock,mozilla/bedrock,analytics-pros/mozilla-bedrock,mkmelin/bedrock,flodolo/bedrock,kyoshino/bedrock,davehunt/bedrock,TheJJ100100/bedrock,gerv/bedrock,TheoChevalier/bedrock,pascalchevrel/bedrock,craigcook/bedrock,Sancus/bedrock,jpetto/bedrock,hoosteeno/bedrock,pascalchevrel/bedrock,davehunt/bedrock,glogiotatidis/bedrock,jgmize/bedrock,schalkneethling/bedrock,TheJJ100100/bedrock,jgmize/bedrock
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.