commit stringlengths 40 40 | subject stringlengths 1 1.49k | old_file stringlengths 4 311 | new_file stringlengths 4 311 | new_contents stringlengths 1 29.8k | old_contents stringlengths 0 9.9k | lang stringclasses 3 values | proba float64 0 1 |
|---|---|---|---|---|---|---|---|
e4942c16322829d37f780d539517fe10e50e0e39 | Fix bad var | hubblestack/extmods/grains/splunkconfig.py | hubblestack/extmods/grains/splunkconfig.py | # -*- coding: utf-8 -*-
'''
Attempt to load alternate splunk config from the hubble.d/ directory and store
in grains for use by the splunk returners. This way splunk config changes don't
require a hubble restart.
'''
import os
import yaml
def splunkconfig():
'''
Walk the hubble.d/ directory and read in any .conf files using YAML. If
splunk config is found, place it in grains and return.
'''
configdir = os.path.join(os.path.dirname(__opts__['configfile']), 'hubble.d')
ret = {}
if not os.path.isdir(configdir):
return ret
try:
for root, dirs, files in os.walk(configdir):
for f in files:
if f.endswith('.conf'):
fpath = os.path.join(root, f)
try:
with open(fpath, 'r') as fh:
config = yaml.safe_load(fh)
if config.get('hubblestack', {}).get('returner', {}).get('splunk'):
ret = {'hubblestack': config['hubblestack']}
except:
pass
except:
pass
return ret
| # -*- coding: utf-8 -*-
'''
Attempt to load alternate splunk config from the hubble.d/ directory and store
in grains for use by the splunk returners. This way splunk config changes don't
require a hubble restart.
'''
import os
import yaml
def splunkconfig():
'''
Walk the hubble.d/ directory and read in any .conf files using YAML. If
splunk config is found, place it in grains and return.
'''
configdir = os.path.join(os.path.dirname(__opts__['configfile']), 'hubble.d')
ret = {}
if not os.path.isdir(configdir):
return ret
try:
for root, dirs, files in os.walk(configdir):
for f in files:
if f.endswith('.conf'):
fpath = os.path.join(root, fpath)
try:
with open(fpath, 'r') as fh:
config = yaml.safe_load(fh)
if config.get('hubblestack', {}).get('returner', {}).get('splunk'):
ret = {'hubblestack': config['hubblestack']}
except:
pass
except:
pass
return ret
| Python | 0.000618 |
c9e8462dacfd511ca996cf73d7a08e1fdfeded01 | fix file permission of stom collector | intelmq/bots/collectors/stomp/collector.py | intelmq/bots/collectors/stomp/collector.py | # -*- coding: utf-8 -*-
import os.path
from intelmq.lib.bot import CollectorBot
try:
import stomp
class StompListener(stomp.listener.PrintingListener):
""" the stomp listener gets called asynchronously for
every STOMP message
"""
def __init__(self, n6stompcollector):
self.n6stomper = n6stompcollector
def on_heartbeat_timeout(self):
self.n6stomper.logger.info("Heartbeat timeout. Attempting to re-connect.")
self.n6stomper.conn.disconnect()
status = self.n6stomper.conn.connect(wait=False)
self.n6stomper.logger.info("Re-connected: %s.", status)
def on_error(self, headers, message):
self.n6stomper.logger.error('Received an error: %r.', message)
def on_message(self, headers, message):
self.n6stomper.logger.debug('Receive message %r...', message[:500])
report = self.n6stomper.new_report()
report.add("raw", message.rstrip())
report.add("feed.url", "stomp://" +
self.n6stomper.parameters.server +
":" + str(self.n6stomper.parameters.port) +
"/" + self.n6stomper.parameters.exchange)
self.n6stomper.send_message(report)
except ImportError:
stomp = None
class StompCollectorBot(CollectorBot):
""" main class for the STOMP protocol collector """
def init(self):
if stomp is None:
self.logger.error('Could not import stomp. Please install it.')
self.stop()
self.server = getattr(self.parameters, 'server', 'n6stream.cert.pl')
self.port = getattr(self.parameters, 'port', 61614)
self.exchange = getattr(self.parameters, 'exchange', '')
self.heartbeat = getattr(self.parameters, 'heartbeat', 60000)
self.ssl_ca_cert = getattr(self.parameters, 'ssl_ca_certificate',
'ca.pem')
self.ssl_cl_cert = getattr(self.parameters, 'ssl_client_certificate',
'client.pem')
self.ssl_cl_cert_key = getattr(self.parameters,
'ssl_client_certificate_key',
'client.key')
self.http_verify_cert = getattr(self.parameters,
'http_verify_cert', True)
# check if certificates exist
for f in [self.ssl_ca_cert, self.ssl_cl_cert, self.ssl_cl_cert_key]:
if not os.path.isfile(f):
raise ValueError("Could not open file %r." % f)
_host = [(self.server, self.port)]
self.conn = stomp.Connection(host_and_ports=_host, use_ssl=True,
ssl_key_file=self.ssl_cl_cert_key,
ssl_cert_file=self.ssl_cl_cert,
ssl_ca_certs=self.ssl_ca_cert,
wait_on_receipt=True,
heartbeats=(self.heartbeat,
self.heartbeat))
self.conn.set_listener('', StompListener(self))
self.conn.start()
self.conn.connect(wait=False)
self.conn.subscribe(destination=self.exchange, id=1, ack='auto')
self.logger.info('Successfully connected and subscribed to %s:%s.',
self.server, self.port)
def disconnect(self):
self.conn.disconnect()
def process(self):
pass
BOT = StompCollectorBot
| # -*- coding: utf-8 -*-
import os.path
from intelmq.lib.bot import CollectorBot
try:
import stomp
class StompListener(stomp.listener.PrintingListener):
""" the stomp listener gets called asynchronously for
every STOMP message
"""
def __init__(self, n6stompcollector):
self.n6stomper = n6stompcollector
def on_heartbeat_timeout(self):
self.n6stomper.logger.info("Heartbeat timeout. Attempting to re-connect.")
self.n6stomper.conn.disconnect()
status = self.n6stomper.conn.connect(wait=False)
self.n6stomper.logger.info("Re-connected: %s.", status)
def on_error(self, headers, message):
self.n6stomper.logger.error('Received an error: %r.', message)
def on_message(self, headers, message):
self.n6stomper.logger.debug('Receive message %r...', message[:500])
report = self.n6stomper.new_report()
report.add("raw", message.rstrip())
report.add("feed.url", "stomp://" +
self.n6stomper.parameters.server +
":" + str(self.n6stomper.parameters.port) +
"/" + self.n6stomper.parameters.exchange)
self.n6stomper.send_message(report)
except ImportError:
stomp = None
class StompCollectorBot(CollectorBot):
""" main class for the STOMP protocol collector """
def init(self):
if stomp is None:
self.logger.error('Could not import stomp. Please install it.')
self.stop()
self.server = getattr(self.parameters, 'server', 'n6stream.cert.pl')
self.port = getattr(self.parameters, 'port', 61614)
self.exchange = getattr(self.parameters, 'exchange', '')
self.heartbeat = getattr(self.parameters, 'heartbeat', 60000)
self.ssl_ca_cert = getattr(self.parameters, 'ssl_ca_certificate',
'ca.pem')
self.ssl_cl_cert = getattr(self.parameters, 'ssl_client_certificate',
'client.pem')
self.ssl_cl_cert_key = getattr(self.parameters,
'ssl_client_certificate_key',
'client.key')
self.http_verify_cert = getattr(self.parameters,
'http_verify_cert', True)
# check if certificates exist
for f in [self.ssl_ca_cert, self.ssl_cl_cert, self.ssl_cl_cert_key]:
if not os.path.isfile(f):
raise ValueError("Could not open file %r." % f)
_host = [(self.server, self.port)]
self.conn = stomp.Connection(host_and_ports=_host, use_ssl=True,
ssl_key_file=self.ssl_cl_cert_key,
ssl_cert_file=self.ssl_cl_cert,
ssl_ca_certs=self.ssl_ca_cert,
wait_on_receipt=True,
heartbeats=(self.heartbeat,
self.heartbeat))
self.conn.set_listener('', StompListener(self))
self.conn.start()
self.conn.connect(wait=False)
self.conn.subscribe(destination=self.exchange, id=1, ack='auto')
self.logger.info('Successfully connected and subscribed to %s:%s.',
self.server, self.port)
def disconnect(self):
self.conn.disconnect()
def process(self):
pass
BOT = StompCollectorBot
| Python | 0 |
e8e7d188b45b06967a6f7ec210f91b1bbe4e494c | use pathlib | abilian/web/admin/panels/sysinfo.py | abilian/web/admin/panels/sysinfo.py | # coding=utf-8
"""
"""
from __future__ import absolute_import, print_function, division
import os
import sys
import pkg_resources
from pip.vcs import vcs
from pathlib import Path
from flask import render_template
from ..panel import AdminPanel
class SysinfoPanel(AdminPanel):
id = 'sysinfo'
label = 'System information'
icon = 'hdd'
def get(self):
uname = os.popen("uname -a").read()
python_version = sys.version.strip()
packages = []
for dist in pkg_resources.working_set:
package = dict(
name=dist.project_name,
key=dist.key,
version=dist.version if dist.has_version() else u'Unknown version',
vcs=None,
)
location = unicode(Path(dist.location).absolute())
vcs_name = vcs.get_backend_name(location)
if vcs_name:
vc = vcs.get_backend_from_location(location)()
url, revision = vc.get_info(location)
package['vcs'] = dict(name=vcs_name, url=url, revision=revision)
packages.append(package)
packages.sort(key=lambda d: d.get('key', None))
return render_template("admin/sysinfo.html",
python_version=python_version,
packages=packages,
uname=uname)
| # coding=utf-8
"""
"""
from __future__ import absolute_import, print_function, division
import os
import sys
import pkg_resources
from pip.vcs import vcs
from flask import render_template
from ..panel import AdminPanel
class SysinfoPanel(AdminPanel):
id = 'sysinfo'
label = 'System information'
icon = 'hdd'
def get(self):
uname = os.popen("uname -a").read()
python_version = sys.version.strip()
packages = []
for dist in pkg_resources.working_set:
package = dict(
name=dist.project_name,
key=dist.key,
version=dist.version if dist.has_version() else u'Unknown version',
vcs=None,
)
location = os.path.normcase(os.path.abspath(dist.location))
vcs_name = vcs.get_backend_name(location)
if vcs_name:
vc = vcs.get_backend_from_location(location)()
url, revision = vc.get_info(location)
package['vcs'] = dict(name=vcs_name, url=url, revision=revision)
packages.append(package)
packages.sort(key=lambda d: d.get('key', None))
return render_template("admin/sysinfo.html",
python_version=python_version,
packages=packages,
uname=uname)
| Python | 0.000001 |
d971b8c7d0261ee0774ccecf41b0484cff1dd62c | Change url config for image to see if it loads in production this way instead | source/services/imdb_service.py | source/services/imdb_service.py | import requests
import re
from bs4 import BeautifulSoup
from source.models.technical_specs import TechnicalSpecs
class ImdbService:
__URL = 'http://www.imdb.com/title/'
__API_URL = 'http://www.imdb.com/xml/find?'
__OMDB_URL = 'http://www.omdbapi.com/?'
__SEPERATOR = '-'
def __init__(self, title):
self.title = title
self.id = self.get_movie_id()
def get_tech_spec(self):
search_url = self.__URL + str(self.id) + '/technical?'
payload = {'ref_': 'tt_dt_spec'}
technical_page = requests.get(search_url, data=payload)
contents = technical_page.text
soup = BeautifulSoup(contents, 'lxml')
data_table = soup.find('tbody')
rows = data_table.find_all('td')
specs = self.get_specs(rows)
specs.link = technical_page.url
return specs
def get_artwork(self):
payload = {'i': self.id, 'plot': 'short', 'r': 'json'}
response = requests.post(self.__OMDB_URL, params=payload)
movie_info = response.json()
artwork_url = movie_info['Poster']
resized_artwork_url = self.format_artwork_url(artwork_url)
return resized_artwork_url
def get_movie_id(self):
search_title = self.format_title()
payload = {'json': '1', 'nr': 1, 'tt': 'on', 'q': search_title}
response = requests.post(self.__API_URL, data=payload)
movie_info = response.json()
try:
movie_id = movie_info['title_popular'][0]['id']
except:
movie_id = movie_info['title_approx'][0]['id']
return movie_id
def format_title(self):
return self.title.replace(' ', self.__SEPERATOR)
def get_specs(self, rows):
tech_specs = TechnicalSpecs()
for i in range(len(rows)):
if 'Negative Format' in rows[i].get_text():
tech_specs.negative_format = self.format_specification(rows[i])
elif 'Cinematographic Process' in rows[i].get_text():
tech_specs.cinematographic_process = self.format_specification(rows[i])
return tech_specs
def format_specification(self, cell):
specs = list(cell.find_next_sibling('td').stripped_strings)
output = []
''' Strip newline characters left from stripped_strings'''
for spec in specs:
output.append(re.sub('\s+', ' ', spec))
return output
def format_artwork_url(self, url):
return url.replace('_SX300', '_UY460_UY0,0,333,460_AL_')
| import requests
import re
from bs4 import BeautifulSoup
from source.models.technical_specs import TechnicalSpecs
class ImdbService:
__URL = 'http://www.imdb.com/title/'
__API_URL = 'http://www.imdb.com/xml/find?'
__OMDB_URL = 'http://www.omdbapi.com/?'
__SEPERATOR = '-'
def __init__(self, title):
self.title = title
self.id = self.get_movie_id()
def get_tech_spec(self):
search_url = self.__URL + str(self.id) + '/technical?'
payload = {'ref_': 'tt_dt_spec'}
technical_page = requests.get(search_url, data=payload)
contents = technical_page.text
soup = BeautifulSoup(contents, 'lxml')
data_table = soup.find('tbody')
rows = data_table.find_all('td')
specs = self.get_specs(rows)
specs.link = technical_page.url
return specs
def get_artwork(self):
payload = {'i': self.id, 'plot': 'short', 'r': 'json'}
response = requests.post(self.__OMDB_URL, params=payload)
movie_info = response.json()
artwork_url = movie_info['Poster']
return self.format_artwork_url(artwork_url)
def get_movie_id(self):
search_title = self.format_title()
payload = {'json': '1', 'nr': 1, 'tt': 'on', 'q': search_title}
response = requests.post(self.__API_URL, data=payload)
movie_info = response.json()
try:
movie_id = movie_info['title_popular'][0]['id']
except:
movie_id = movie_info['title_approx'][0]['id']
return movie_id
def format_title(self):
return self.title.replace(' ', self.__SEPERATOR)
def get_specs(self, rows):
tech_specs = TechnicalSpecs()
for i in range(len(rows)):
if 'Negative Format' in rows[i].get_text():
tech_specs.negative_format = self.format_specification(rows[i])
elif 'Cinematographic Process' in rows[i].get_text():
tech_specs.cinematographic_process = self.format_specification(rows[i])
return tech_specs
def format_specification(self, cell):
specs = list(cell.find_next_sibling('td').stripped_strings)
output = []
''' Strip newline characters left from stripped_strings'''
for spec in specs:
output.append(re.sub('\s+', ' ', spec))
return output
def format_artwork_url(self, url):
return url.replace('_SX300', '_SX333')
| Python | 0 |
d2ac9fd6e1bebd85b345df09e1717b65359c54bd | Correct Torfaen opening times | polling_stations/apps/data_importers/management/commands/import_torfaen.py | polling_stations/apps/data_importers/management/commands/import_torfaen.py | from addressbase.models import Address, UprnToCouncil
from core.opening_times import OpeningTimes
from data_importers.management.commands import BaseHalaroseCsvImporter
from data_importers.mixins import AdvanceVotingMixin
from pollingstations.models import AdvanceVotingStation
class Command(BaseHalaroseCsvImporter, AdvanceVotingMixin):
council_id = "TOF"
addresses_name = (
"2022-05-05/2022-03-01T07:51:07.153603/polling_station_export-2022-03-01.csv"
)
stations_name = (
"2022-05-05/2022-03-01T07:51:07.153603/polling_station_export-2022-03-01.csv"
)
elections = ["2022-05-05"]
def address_record_to_dict(self, record):
uprn = record.uprn.strip().lstrip("0")
if uprn in [
"200002953910", # PARK HOUSE FARM, GRAIG ROAD, UPPER CWMBRAN, CWMBRAN
]:
return None
if record.housepostcode in [
"NP4 7NW",
"NP4 8JQ",
"NP4 8LG",
"NP44 1LE",
"NP44 4QS",
"NP4 6TX",
]:
return None
return super().address_record_to_dict(record)
def station_record_to_dict(self, record):
# FORGESIDE COMMUNITY CENTRE FORGESIDE COMMUNITY CENTRE BFORGESIDE BLAENAVON TORFAEN NP4 9BD
if record.pollingstationname == "FORGESIDE COMMUNITY CENTRE":
record = record._replace(pollingstationpostcode="NP4 9DH")
# THORNHILL4UTOO THORNHILL COMMUNITY CENTRE LEADON COURT THORNHILL CWMBRAN TORFAEN NP44 5YZ
if record.pollingstationname == "THORNHILL4UTOO":
record = record._replace(pollingstationpostcode="NP44 5TZ")
return super().station_record_to_dict(record)
def add_advance_voting_stations(self):
opening_times = OpeningTimes()
opening_times.add_open_time("2022-04-30", "10:00", "16:00")
opening_times.add_open_time("2022-05-01", "10:00", "16:00")
advance_station = AdvanceVotingStation(
name="Pontypool Civic Centre",
address="""Glantorvaen Road
Pontypool
Torfaen
""",
postcode="NP4 6YB",
location=Address.objects.get(uprn=100101048589).location,
opening_times=opening_times.as_string_table(),
council=self.council,
)
advance_station.save()
UprnToCouncil.objects.filter(lad=self.council.geography.gss).update(
advance_voting_station=advance_station
)
| from addressbase.models import Address, UprnToCouncil
from core.opening_times import OpeningTimes
from data_importers.management.commands import BaseHalaroseCsvImporter
from data_importers.mixins import AdvanceVotingMixin
from pollingstations.models import AdvanceVotingStation
class Command(BaseHalaroseCsvImporter, AdvanceVotingMixin):
council_id = "TOF"
addresses_name = (
"2022-05-05/2022-03-01T07:51:07.153603/polling_station_export-2022-03-01.csv"
)
stations_name = (
"2022-05-05/2022-03-01T07:51:07.153603/polling_station_export-2022-03-01.csv"
)
elections = ["2022-05-05"]
def address_record_to_dict(self, record):
uprn = record.uprn.strip().lstrip("0")
if uprn in [
"200002953910", # PARK HOUSE FARM, GRAIG ROAD, UPPER CWMBRAN, CWMBRAN
]:
return None
if record.housepostcode in [
"NP4 7NW",
"NP4 8JQ",
"NP4 8LG",
"NP44 1LE",
"NP44 4QS",
"NP4 6TX",
]:
return None
return super().address_record_to_dict(record)
def station_record_to_dict(self, record):
# FORGESIDE COMMUNITY CENTRE FORGESIDE COMMUNITY CENTRE BFORGESIDE BLAENAVON TORFAEN NP4 9BD
if record.pollingstationname == "FORGESIDE COMMUNITY CENTRE":
record = record._replace(pollingstationpostcode="NP4 9DH")
# THORNHILL4UTOO THORNHILL COMMUNITY CENTRE LEADON COURT THORNHILL CWMBRAN TORFAEN NP44 5YZ
if record.pollingstationname == "THORNHILL4UTOO":
record = record._replace(pollingstationpostcode="NP44 5TZ")
return super().station_record_to_dict(record)
def add_advance_voting_stations(self):
opening_times = OpeningTimes()
opening_times.add_open_time("2022-05-01", "10:00", "16:00")
opening_times.add_open_time("2022-05-02", "10:00", "16:00")
advance_station = AdvanceVotingStation(
name="Pontypool Civic Centre",
address="""Glantorvaen Road
Pontypool
Torfaen
""",
postcode="NP4 6YB",
location=Address.objects.get(uprn=100101048589).location,
opening_times=opening_times.as_string_table(),
council=self.council,
)
advance_station.save()
UprnToCouncil.objects.filter(lad=self.council.geography.gss).update(
advance_voting_station=advance_station
)
| Python | 0.000066 |
cb89d8f0dd5fad8b5fc935639fc59a7317679001 | Update master.chromium.webkit to use a dedicated mac builder. | masters/master.chromium.webkit/master_mac_latest_cfg.py | masters/master.chromium.webkit/master_mac_latest_cfg.py | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from master import master_config
from master.factory import chromium_factory
defaults = {}
helper = master_config.Helper(defaults)
B = helper.Builder
F = helper.Factory
T = helper.Triggerable
def mac():
return chromium_factory.ChromiumFactory('src/out', 'darwin')
defaults['category'] = 'nonlayout'
################################################################################
## Debug
################################################################################
# Triggerable scheduler for testers
T('mac_builder_dbg_trigger')
#
# Mac Dbg Builder
#
B('Mac Builder (dbg)', 'f_mac_builder_dbg', scheduler='global_scheduler')
F('f_mac_builder_dbg', mac().ChromiumFactory(
target='Debug',
# Build 'all' instead of 'chromium_builder_tests' so that archiving works.
# TODO: Define a new build target that is archive-friendly?
options=['--build-tool=ninja', '--compiler=goma-clang', 'all'],
factory_properties={
'trigger': 'mac_builder_dbg_trigger',
'gclient_env': {
'GYP_DEFINES': 'fastbuild=1',
'GYP_GENERATORS': 'ninja',
},
'archive_build': True,
'blink_config': 'blink',
'build_name': 'Mac',
'gs_bucket': 'gs://chromium-webkit-snapshots',
'gs_acl': 'public-read',
}))
B('Mac10.6 Tests', 'f_mac_tester_10_06_dbg',
scheduler='mac_builder_dbg_trigger')
F('f_mac_tester_10_06_dbg', mac().ChromiumFactory(
tests=[
'browser_tests',
'cc_unittests',
'content_browsertests',
'interactive_ui_tests',
'telemetry_unittests',
'unit',
],
factory_properties={
'generate_gtest_json': True,
'blink_config': 'blink',
}))
B('Mac10.8 Tests', 'f_mac_tester_10_08_dbg',
scheduler='mac_builder_dbg_trigger')
F('f_mac_tester_10_08_dbg', mac().ChromiumFactory(
tests=[
'browser_tests',
'content_browsertests',
'interactive_ui_tests',
'telemetry_unittests',
'unit',
],
factory_properties={
'generate_gtest_json': True,
'blink_config': 'blink',
}))
def Update(_config, _active_master, c):
return helper.Update(c)
| # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from master import master_config
from master.factory import chromium_factory
defaults = {}
helper = master_config.Helper(defaults)
B = helper.Builder
F = helper.Factory
def mac():
return chromium_factory.ChromiumFactory('src/xcodebuild', 'darwin')
def mac_out():
return chromium_factory.ChromiumFactory('src/out', 'darwin')
################################################################################
## Release
################################################################################
defaults['category'] = 'nonlayout'
#
# Mac Rel Builder
#
B('Mac10.6 Tests', 'f_mac_tests_rel', scheduler='global_scheduler')
F('f_mac_tests_rel', mac_out().ChromiumFactory(
options=['--build-tool=ninja', '--compiler=goma-clang', '--',
'chromium_builder_tests'],
tests=[
'browser_tests',
'cc_unittests',
'content_browsertests',
'interactive_ui_tests',
'telemetry_unittests',
'unit',
],
factory_properties={
'generate_gtest_json': True,
'gclient_env': {
'GYP_GENERATORS':'ninja',
'GYP_DEFINES':'fastbuild=1',
},
'blink_config': 'blink',
}))
B('Mac10.8 Tests', 'f_mac_tests_rel_108', scheduler='global_scheduler')
F('f_mac_tests_rel_108', mac_out().ChromiumFactory(
# Build 'all' instead of 'chromium_builder_tests' so that archiving works.
# TODO: Define a new build target that is archive-friendly?
options=['--build-tool=ninja', '--compiler=goma-clang', '--', 'all'],
tests=[
'browser_tests',
'content_browsertests',
'interactive_ui_tests',
'telemetry_unittests',
'unit',
],
factory_properties={
'archive_build': True,
'blink_config': 'blink',
'build_name': 'Mac',
'generate_gtest_json': True,
'gclient_env': {
'GYP_GENERATORS':'ninja',
'GYP_DEFINES':'fastbuild=1',
},
'gs_bucket': 'gs://chromium-webkit-snapshots',
}))
################################################################################
## Debug
################################################################################
#
# Mac Dbg Builder
#
B('Mac Builder (dbg)', 'f_mac_dbg', scheduler='global_scheduler')
F('f_mac_dbg', mac().ChromiumFactory(
target='Debug',
options=['--compiler=goma-clang', '--', '-target', 'blink_tests'],
factory_properties={
'blink_config': 'blink',
}))
def Update(_config, _active_master, c):
return helper.Update(c)
| Python | 0.000002 |
b195e909ce3d3903998a91de0b5763dd679b25e3 | fix version | debile/slave/runners/findbugs.py | debile/slave/runners/findbugs.py | # Copyright (c) 2012-2013 Paul Tagliamonte <paultag@debian.org>
# Copyright (c) 2013 Leo Cavaille <leo@cavaille.net>
# Copyright (c) 2013 Sylvestre Ledru <sylvestre@debian.org>
# Copyright (c) 2015 Lucas Kanashiro <kanashiro.duarte@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from debile.slave.wrappers.findbugs import parse_findbugs
from debile.slave.utils import cd
from debile.utils.commands import run_command
import os
def findbugs(deb, analysis):
run_command(["dpkg", "-x", deb, "binary"])
with cd('binary'):
# Force english as findbugs is localized
os.putenv("LANG", "C")
out, err, _ = run_command([
'fb', 'analyze', '-effort:max', '-xml:withMessages', '.'
])
xmlbytes = out.encode("utf-8")
failed = False
# if err.strip() == '':
# return (analysis, err, failed)
for issue in parse_findbugs(xmlbytes):
analysis.results.append(issue)
if not failed and issue.severity in [
'performance', 'portability', 'error', 'warning'
]:
failed = True
return (analysis, err, failed, None, None)
def version():
out, _, ret = run_command(['fb', '-version'])
if ret != 0:
raise Exception("findbugs is not installed")
version = out.strip()
return ('findbugs', version.strip())
| # Copyright (c) 2012-2013 Paul Tagliamonte <paultag@debian.org>
# Copyright (c) 2013 Leo Cavaille <leo@cavaille.net>
# Copyright (c) 2013 Sylvestre Ledru <sylvestre@debian.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from debile.slave.wrappers.findbugs import parse_findbugs
from debile.slave.utils import cd
from debile.utils.commands import run_command
import os
def findbugs(deb, analysis):
run_command(["dpkg", "-x", deb, "binary"])
with cd('binary'):
# Force english as findbugs is localized
os.putenv("LANG", "C")
out, err, _ = run_command([
'fb', 'analyze', '-effort:max', '-xml:withMessages', '.'
])
xmlbytes = out.encode("utf-8")
failed = False
# if err.strip() == '':
# return (analysis, err, failed)
for issue in parse_findbugs(xmlbytes):
analysis.results.append(issue)
if not failed and issue.severity in [
'performance', 'portability', 'error', 'warning'
]:
failed = True
return (analysis, err, failed, None, None)
def version():
out, _, ret = run_command(['fb', '-version'])
if ret != 0:
raise Exception("findbugs is not installed")
name, version = out.split(" ")
return (name, version.strip())
| Python | 0.004257 |
4e3e8d49b06c03b1ab31357206fc6385256d8438 | Switch to official python graphviz port | graph/gengraph.py | graph/gengraph.py | #!/usr/bin/python
import sys
import gv
class Gengraph(object):
def __init__(self):
pass
def getTrName(self, line):
line = line.strip(' ')
name = line.split(' ')
name.remove('tr_t')
for n in name:
if len(n) > 0:
x = n.find('[')
return n[:x];
def createEdge(self, trdefinition):
# prevent from adding multiple same named nodes
nodeSet = set()
for line in trdefinition:
# now we have list of names: state1, state2, event, event handler
tok = line.split(',')
# no enought tokens (empty line?)
if len(tok) < 3:
continue
for i in range(len(tok)):
tok[i] = tok[i].strip(' ')
# adding nodes to graph
if (not tok[0] in nodeSet):
nodeSet.add(tok[0])
n = gv.node(self.dot, tok[0])
gv.setv(n, "shape", "Mrecord")
if ((not tok[1] in nodeSet) and (tok[1] != "FSM_NO_STATE")):
nodeSet.add(tok[1])
n = gv.node(self.dot, tok[1])
gv.setv(n, "shape", "Mrecord")
if (tok[2] == "FSM_DEF_TR"):
e = gv.edge(self.dot, tok[0], tok[1])
gv.setv(e, "label", "["+tok[3]+"] ")
elif (tok[1] == "FSM_NO_STATE"):
e = gv.edge(self.dot, tok[0], tok[0])
gv.setv(e, "label", tok[2]+"["+tok[3]+"] ")
gv.setv(e, "arrowhead", "tee")
else:
e = gv.edge(self.dot, tok[0], tok[1])
gv.setv(e, "label", tok[2]+"["+tok[3]+"] ")
def gen(self, filename):
f = open(filename)
src = f.readlines()
found = 0
trdefinition = []
for line in src:
if (line.find('tr_t') >= 0):
found = 1
self.dot = gv.digraph(self.getTrName(line))
print "Name: ", self.getTrName(line)
continue
if (found and line.find('};') >= 0):
break
if (found):
line = line.strip(' ')
if (line.startswith('/*') or line.endswith('*/') or line.startswith('*')):
continue
line = line.replace('{', '')
line = line.replace('}', '')
line = line.strip("\n")
trdefinition.append(line)
# parsing each line and creating dot graph
self.createEdge(trdefinition)
gv.layout(self.dot, "dot")
gv.render(self.dot, "dot", "out.gv")
gv.render(self.dot, "png", "out.png")
print 'finded definition:'
for line in trdefinition:
print line
print '...generating fsm graph'
def usage(self, argv):
print 'Usage:'
print argv[0], "src tr_table_name"
if __name__ == '__main__':
g = Gengraph()
if (len(sys.argv) < 2):
g.usage(sys.argv)
exit(1)
g.gen(sys.argv[1])
| #!/usr/bin/python
import sys
from graphviz import Digraph
class Gengraph(object):
def __init__(self):
pass
def getTrName(self, line):
line = line.strip(' ')
name = line.split(' ')
name.remove('tr_t')
for n in name:
if len(n) > 0:
x = n.find('[')
return n[:x];
def createEdge(self, trdefinition):
# prevent from adding multiple same named nodes
nodeSet = set()
for line in trdefinition:
# now we have list of names: state1, state2, event, event handler
tok = line.split(',')
# no enought tokens (empty line?)
if len(tok) < 3:
continue
for i in range(len(tok)):
tok[i] = tok[i].strip(' ')
# adding nodes to graph
if (not tok[0] in nodeSet):
nodeSet.add(tok[0])
self.dot.node(tok[0], tok[0], shape="box")
if ((not tok[1] in nodeSet) and (tok[1] != "FSM_NO_STATE")):
nodeSet.add(tok[1])
self.dot.node(tok[1], tok[1], shape="box")
if (tok[2] == "FSM_DEF_TR"):
self.dot.edge(tok[0], tok[1], label="["+tok[3]+"] ")
elif (tok[1] == "FSM_NO_STATE"):
self.dot.edge(tok[0], tok[0], label=tok[2]+"["+tok[3]+"] ")
else:
self.dot.edge(tok[0], tok[1], label=tok[2]+"["+tok[3]+"] ")
def gen(self, filename):
f = open(filename)
src = f.readlines()
found = 0
trdefinition = []
for line in src:
if (line.find('tr_t') >= 0):
found = 1
self.dot = Digraph(comment=self.getTrName(line))
print "Name: ", self.getTrName(line)
continue
if (found and line.find('};') >= 0):
break
if (found):
line = line.strip(' ')
if (line.startswith('/*') or line.endswith('*/') or line.startswith('*')):
continue
line = line.replace('{', '')
line = line.replace('}', '')
trdefinition.append(line)
# parsing each line and creating dot graph
self.createEdge(trdefinition)
print self.dot.source
self.dot.render("out.gv")
print 'finded definition:'
for line in trdefinition:
print line
print '...generating fsm graph'
def usage(self, argv):
print 'Usage:'
print argv[0], "src tr_table_name"
if __name__ == '__main__':
g = Gengraph()
if (len(sys.argv) < 2):
g.usage(sys.argv)
exit(1)
g.gen(sys.argv[1])
| Python | 0 |
43125b7ea61606d6d65d0c75168539cee8cdfcd2 | support touch-tip for JSON protocols (#2000) | api/opentrons/protocols/__init__.py | api/opentrons/protocols/__init__.py | import time
from itertools import chain
from opentrons import instruments, labware, robot
from opentrons.instruments import pipette_config
def _sleep(seconds):
if not robot.is_simulating():
time.sleep(seconds)
def load_pipettes(protocol_data):
pipettes = protocol_data.get('pipettes', {})
pipettes_by_id = {}
for pipette_id, props in pipettes.items():
model = props.get('model')
mount = props.get('mount')
config = pipette_config.load(model)
pipettes_by_id[pipette_id] = instruments._create_pipette_from_config(
config=config,
mount=mount)
return pipettes_by_id
def load_labware(protocol_data):
data = protocol_data.get('labware', {})
loaded_labware = {}
for labware_id, props in data.items():
slot = props.get('slot')
model = props.get('model')
display_name = props.get('display-name')
if slot == '12':
if model == 'fixed-trash':
# pass in the pre-existing fixed-trash
loaded_labware[labware_id] = robot.fixed_trash
else:
# share the slot with the fixed-trash
loaded_labware[labware_id] = labware.load(
model,
slot,
display_name,
share=True
)
else:
loaded_labware[labware_id] = labware.load(
model,
slot,
display_name
)
return loaded_labware
def get_location(command_params, loaded_labware):
labwareId = command_params.get('labware')
well = command_params.get('well')
return loaded_labware.get(labwareId, {}).get(well)
def get_pipette(command_params, loaded_pipettes):
pipetteId = command_params.get('pipette')
return loaded_pipettes.get(pipetteId)
# C901 code complexity is due to long elif block, ok in this case (Ian+Ben)
def dispatch_commands(protocol_data, loaded_pipettes, loaded_labware): # noqa: C901 E501
subprocedures = [
p.get('subprocedure', [])
for p in protocol_data.get('procedure', [])]
flat_subs = chain.from_iterable(subprocedures)
for command_item in flat_subs:
command_type = command_item.get('command')
params = command_item.get('params', {})
pipette = get_pipette(params, loaded_pipettes)
location = get_location(params, loaded_labware)
volume = params.get('volume')
if command_type == 'delay':
wait = params.get('wait', 0)
if wait is True:
# TODO Ian 2018-05-14 pass message
robot.pause()
else:
_sleep(wait)
elif command_type == 'blowout':
pipette.blow_out(location)
elif command_type == 'pick-up-tip':
pipette.pick_up_tip(location)
elif command_type == 'drop-tip':
pipette.drop_tip(location)
elif command_type == 'aspirate':
pipette.aspirate(volume, location)
elif command_type == 'dispense':
pipette.dispense(volume, location)
elif command_type == 'touch-tip':
pipette.touch_tip(location)
def execute_protocol(protocol):
loaded_pipettes = load_pipettes(protocol)
loaded_labware = load_labware(protocol)
dispatch_commands(protocol, loaded_pipettes, loaded_labware)
return {
'pipettes': loaded_pipettes,
'labware': loaded_labware
}
| import time
from itertools import chain
from opentrons import instruments, labware, robot
from opentrons.instruments import pipette_config
def _sleep(seconds):
if not robot.is_simulating():
time.sleep(seconds)
def load_pipettes(protocol_data):
pipettes = protocol_data.get('pipettes', {})
pipettes_by_id = {}
for pipette_id, props in pipettes.items():
model = props.get('model')
mount = props.get('mount')
config = pipette_config.load(model)
pipettes_by_id[pipette_id] = instruments._create_pipette_from_config(
config=config,
mount=mount)
return pipettes_by_id
def load_labware(protocol_data):
data = protocol_data.get('labware', {})
loaded_labware = {}
for labware_id, props in data.items():
slot = props.get('slot')
model = props.get('model')
display_name = props.get('display-name')
if slot == '12':
if model == 'fixed-trash':
# pass in the pre-existing fixed-trash
loaded_labware[labware_id] = robot.fixed_trash
else:
# share the slot with the fixed-trash
loaded_labware[labware_id] = labware.load(
model,
slot,
display_name,
share=True
)
else:
loaded_labware[labware_id] = labware.load(
model,
slot,
display_name
)
return loaded_labware
def get_location(command_params, loaded_labware):
labwareId = command_params.get('labware')
well = command_params.get('well')
return loaded_labware.get(labwareId, {}).get(well)
def get_pipette(command_params, loaded_pipettes):
pipetteId = command_params.get('pipette')
return loaded_pipettes.get(pipetteId)
def dispatch_commands(protocol_data, loaded_pipettes, loaded_labware):
subprocedures = [
p.get('subprocedure', [])
for p in protocol_data.get('procedure', [])]
flat_subs = chain.from_iterable(subprocedures)
for command_item in flat_subs:
command_type = command_item.get('command')
params = command_item.get('params', {})
pipette = get_pipette(params, loaded_pipettes)
location = get_location(params, loaded_labware)
volume = params.get('volume')
if command_type == 'delay':
wait = params.get('wait', 0)
if wait is True:
# TODO Ian 2018-05-14 pass message
robot.pause()
else:
_sleep(wait)
elif command_type == 'blowout':
pipette.blow_out(location)
elif command_type == 'pick-up-tip':
pipette.pick_up_tip(location)
elif command_type == 'drop-tip':
pipette.drop_tip(location)
elif command_type == 'aspirate':
pipette.aspirate(volume, location)
elif command_type == 'dispense':
pipette.dispense(volume, location)
def execute_protocol(protocol):
loaded_pipettes = load_pipettes(protocol)
loaded_labware = load_labware(protocol)
dispatch_commands(protocol, loaded_pipettes, loaded_labware)
return {
'pipettes': loaded_pipettes,
'labware': loaded_labware
}
| Python | 0 |
2d3e2f796d6a839994c2708f31e60d52c6bf8c15 | Simplify main() | sjp.py | sjp.py | #!/usr/bin/env python3
import urllib.request # to download HTML source
import sys # to access CLI arguments and to use exit codes
from bs4 import BeautifulSoup # to parse HTML source
version = 0.01
def printUsageInfo():
helpMsg = """Usage:
sjp.py <word>
sjp.py (-h | --help | /?)
sjp.py (-v | --version)"""
print(helpMsg)
def printVersionInfo():
versionMsg = "sjp.py " + str(version)
print(versionMsg)
def getDefinition(word):
url = 'http://sjp.pl/' + urllib.parse.quote(word)
try:
html = urllib.request.urlopen(url).read()
except urllib.error.URLError:
print("[Error] Can't connect to the service")
sys.exit(2)
soup = BeautifulSoup(html)
# checks if definition is in dictionary:
if soup.find_all('span', style="color: #e00;"):
print("[Error] \"" + word + "\" not found")
sys.exit(1)
# definition is in dictionary, continue:
ex = soup.find_all('p',
style="margin-top: .5em; "
"font-size: medium; "
"max-width: 32em; ")
ex = ex[0]
return ex.contents[0::2] # returns a list of lines of definition
def main():
if len(sys.argv) <= 1:
printUsageInfo()
sys.exit()
if sys.argv[1] in ("-h", "--help", "/?"):
printUsageInfo()
sys.exit()
elif sys.argv[1] in ("-v", "--version"):
printVersionInfo()
sys.exit()
else:
print('\n'.join(getDefinition(sys.argv[1])))
if __name__ == "__main__":
main()
| #!/usr/bin/env python3
import urllib.request # to download HTML source
import sys # to access CLI arguments and to use exit codes
from bs4 import BeautifulSoup # to parse HTML source
version = 0.01
def printUsageInfo():
helpMsg = """Usage:
sjp.py <word>
sjp.py (-h | --help | /?)
sjp.py (-v | --version)"""
print(helpMsg)
def printVersionInfo():
versionMsg = "sjp.py " + str(version)
print(versionMsg)
def getDefinition(word):
url = 'http://sjp.pl/' + urllib.parse.quote(word)
try:
html = urllib.request.urlopen(url).read()
except urllib.error.URLError:
print("[Error] Can't connect to the service")
sys.exit(2)
soup = BeautifulSoup(html)
# checks if definition is in dictionary:
if soup.find_all('span', style="color: #e00;"):
print("[Error] \"" + word + "\" not found")
sys.exit(1)
# definition is in dictionary, continue:
ex = soup.find_all('p',
style="margin-top: .5em; "
"font-size: medium; "
"max-width: 32em; ")
ex = ex[0]
return ex.contents[0::2] # returns a list of lines of definition
def main():
if len(sys.argv) > 1:
if sys.argv[1] in ["-h", "--help", "/?"]:
printUsageInfo()
sys.exit()
elif sys.argv[1] in ["-v", "--version"]:
printVersionInfo()
sys.exit()
else:
print('\n'.join(getDefinition(sys.argv[1])))
else:
printUsageInfo()
sys.exit()
if __name__ == "__main__":
main()
| Python | 0.000042 |
a78d1bcfdc3d979cd7be1f82345c29047993953d | Add more init logic to handle AWS HTTP API | sqs.py | sqs.py | #!/usr/bin/env python
from tornado.httpclient import AsyncHTTPClient, HTTPRequest, HTTPClient
from tornado.httputil import url_concat
import datetime
import hashlib
import hmac
class SQSRequest(HTTPRequest):
"""SQS AWS Adapter for Tornado HTTP request"""
def __init__(self, *args, **kwargs):
t = datetime.datetime.utcnow()
method = kwargs.get('method', 'GET')
url = kwargs.get('url') or args[0]
params = sorted(url.split('?')[1].split('&'))
canonical_querystring = '&'.join(params)
kwargs['url'] = url.split('?')[0] + '?' + canonical_querystring
args = tuple()
host = url.split('://')[1].split('/')[0]
canonical_uri = url.split('://')[1].split('.com')[1].split('?')[0]
service = 'sqs'
region = kwargs.get('region', 'eu-west-1')
amz_date = t.strftime('%Y%m%dT%H%M%SZ')
datestamp = t.strftime('%Y%m%d')
canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amz_date + '\n'
signed_headers = 'host;x-amz-date'
payload_hash = hashlib.sha256('').hexdigest()
canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash
algorithm = 'AWS4-HMAC-SHA256'
credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'
string_to_sign = algorithm + '\n' + amz_date + '\n' + credential_scope + '\n' + hashlib.sha256(canonical_request).hexdigest()
signing_key = self.getSignatureKey(kwargs['secret_key'], datestamp, region, service)
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
authorization_header = algorithm + ' ' + 'Credential=' + kwargs['access_key'] + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature
del kwargs['access_key']
del kwargs['secret_key']
headers = kwargs.get('headers', {})
headers.update({'x-amz-date':amz_date, 'Authorization':authorization_header})
kwargs['headers'] = headers
super(SQSRequest, self).__init__(*args, **kwargs)
| #!/usr/bin/env python
from tornado.httpclient import AsyncHTTPClient, HTTPRequest, HTTPClient
from tornado.httputil import url_concat
import datetime
import hashlib
import hmac
class SQSRequest(HTTPRequest):
"""SQS AWS Adapter for Tornado HTTP request"""
def __init__(self, *args, **kwargs):
t = datetime.datetime.utcnow()
method = kwargs.get('method', 'GET')
url = kwargs.get('url') or args[0]
params = sorted(url.split('?')[1].split('&'))
canonical_querystring = '&'.join(params)
kwargs['url'] = url.split('?')[0] + '?' + canonical_querystring
args = tuple()
host = url.split('://')[1].split('/')[0]
canonical_uri = url.split('://')[1].split('.com')[1].split('?')[0]
service = 'sqs'
region = kwargs.get('region', 'eu-west-1')
super(SQSRequest, self).__init__(*args, **kwargs)
| Python | 0 |
2166f52ce5da81bf8f28a3dbbc92145b0913db07 | Update usage of layouts.get_layout | examples/basics/visuals/graph.py | examples/basics/visuals/graph.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
This example demonstrates how to visualise a NetworkX graph using the
GraphVisual.
"""
import sys
import numpy as np
import networkx as nx
from vispy import app, gloo, visuals
from vispy.visuals.graphs import layouts
from vispy.visuals.transforms import STTransform
class Canvas(app.Canvas):
def __init__(self):
app.Canvas.__init__(self, title="Simple NetworkX Graph",
keys="interactive", size=(600, 600))
self.graph = nx.fast_gnp_random_graph(1000, 0.0006, directed=True)
self.visual = visuals.GraphVisual(
# np.asarray(nx.to_numpy_matrix(self.graph)),
nx.adjacency_matrix(self.graph),
layout=layouts.get_layout('force_directed'),
line_color=(1.0, 1.0, 1.0, 1.0),
arrow_type="stealth",
arrow_size=15,
node_symbol="disc",
node_size=10,
face_color="red",
border_width=0.0,
animate=True,
directed=True
)
self.visual.events.update.connect(lambda evt: self.update())
self.visual.transform = STTransform(self.visual_size, (20, 20))
self.timer = app.Timer(interval=0, connect=self.animate, start=True)
self.show()
@property
def visual_size(self):
return (
self.physical_size[0] - 40,
self.physical_size[1] - 40
)
def on_resize(self, event):
self.visual.transform.scale = self.visual_size
vp = (0, 0, self.physical_size[0], self.physical_size[1])
self.context.set_viewport(*vp)
self.visual.transforms.configure(canvas=self, viewport=vp)
def on_draw(self, event):
gloo.clear('black')
self.visual.draw()
def animate(self, event):
ready = self.visual.animate_layout()
if ready:
self.timer.disconnect(self.animate)
if __name__ == '__main__':
win = Canvas()
if sys.flags.interactive != 1:
app.run()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
This example demonstrates how to visualise a NetworkX graph using the
GraphVisual.
"""
import sys
import networkx as nx
from vispy import app, gloo, visuals
from vispy.visuals.graphs import layouts
from vispy.visuals.transforms import STTransform
class Canvas(app.Canvas):
def __init__(self):
app.Canvas.__init__(self, title="Simple NetworkX Graph",
keys="interactive", size=(600, 600))
self.graph = nx.fast_gnp_random_graph(100, 0.02)
self.visual = visuals.GraphVisual(
nx.adjacency_matrix(self.graph),
layout=layouts.get('force_directed'),
line_color=(1.0, 1.0, 1.0, 1.0),
arrow_type="stealth",
arrow_size=7.5,
node_symbol="disc",
node_size=10,
face_color="red",
border_width=0.0,
animate=True
)
self.visual.events.update.connect(lambda evt: self.update())
self.visual.transform = STTransform(self.visual_size, (20, 20))
self.timer = app.Timer(interval=0, connect=self.animate, start=True)
self.show()
@property
def visual_size(self):
return (
self.physical_size[0] - 40,
self.physical_size[1] - 40
)
def on_resize(self, event):
self.visual.transform.scale = self.visual_size
vp = (0, 0, self.physical_size[0], self.physical_size[1])
self.context.set_viewport(*vp)
self.visual.transforms.configure(canvas=self, viewport=vp)
def on_draw(self, event):
gloo.clear('black')
self.visual.draw()
def animate(self, event):
ready = self.visual.animate_layout()
if ready:
self.timer.disconnect(self.animate)
if __name__ == '__main__':
win = Canvas()
if sys.flags.interactive != 1:
app.run()
| Python | 0.000001 |
e43aa23b3d4b7d3319e4b2766cdb4a9b9382954b | Fix typo | django_tricks/models/abstract.py | django_tricks/models/abstract.py | from uuid import uuid4
from django.db import models
from .mixins import MPAwareModel
treebeard = True
try:
from treebeard.mp_tree import MP_Node
except ImportError:
treebeard = False
class UniqueTokenModel(models.Model):
token = models.CharField(max_length=32, unique=True, blank=True)
class Meta:
abstract = True
def get_token(self):
return str(uuid4().hex)
def save(self, **kwargs):
if not self.token:
self.token = self.get_token()
super().save(**kwargs)
if treebeard:
class MaterializedPathNode(MPAwareModel, MP_Node):
slug = models.SlugField(max_length=255, db_index=True, unique=False, blank=True)
node_order_by = ['name']
class Meta:
abstract = True
| from uuid import uuid4
from django.db import models
from .mixins import MPAwareModel
treebeard = True
try:
from treebeard.mp_tree import MP_Node
except ImportError:
treebeard = False
class UniqueTokenModel(models.Model):
token = models.CharField(max_length=32, unique=True, blank=True)
class Meta:
abstract = True
def get_token(self):
return uuid4().hext
def save(self, **kwargs):
if not self.token:
self.token = self.get_token()
super().save(**kwargs)
if treebeard:
class MaterializedPathNode(MPAwareModel, MP_Node):
slug = models.SlugField(max_length=255, db_index=True, unique=False, blank=True)
node_order_by = ['name']
class Meta:
abstract = True
| Python | 0.999999 |
0a70a700f450c3c22ee0e7a32ffb57c29b823fe1 | Exclude test/assembly on Windows | test/assembly/gyptest-assembly.py | test/assembly/gyptest-assembly.py | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
A basic test of compiling assembler files.
"""
import sys
import TestGyp
if sys.platform != 'win32':
# TODO(bradnelson): get this working for windows.
test = TestGyp.TestGyp(formats=['make', 'ninja', 'scons', 'xcode'])
test.run_gyp('assembly.gyp', chdir='src')
test.relocate('src', 'relocate/src')
test.build('assembly.gyp', test.ALL, chdir='relocate/src')
expect = """\
Hello from program.c
Got 42.
"""
test.run_built_executable('program', chdir='relocate/src', stdout=expect)
test.pass_test()
| #!/usr/bin/env python
# Copyright (c) 2009 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that .hpp files are ignored when included in the source list on all
platforms.
"""
import sys
import TestGyp
# TODO(bradnelson): get this working for windows.
test = TestGyp.TestGyp(formats=['make', 'ninja', 'scons', 'xcode'])
test.run_gyp('assembly.gyp', chdir='src')
test.relocate('src', 'relocate/src')
test.build('assembly.gyp', test.ALL, chdir='relocate/src')
expect = """\
Hello from program.c
Got 42.
"""
test.run_built_executable('program', chdir='relocate/src', stdout=expect)
test.pass_test()
| Python | 0.001267 |
492f769dd9b40bcf2b13379bdc5618def53832e2 | replace namedtuples by more obvious Points as pair of x,y | xoi.py | xoi.py | #! /usr/bin/env python
import sys
import curses
from curses import KEY_ENTER
import time
from collections import namedtuple
KEY = "KEY"
K_A = ord("a")
K_D = ord("d")
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
@property
def x(self):
return self._x
@x.setter
def x(self, val):
self._x = val
@property
def y(self):
return self._y
@y.setter
def y(self, val):
self._y = val
Event = namedtuple("Event", ["type", "val"])
class Spaceship(object):
def __init__(self, border):
self._image = "<i>"
self._dx = 1
self.border = border
self._pos = Point(self.border.x // 2, self.border.y - 1)
def events(self, event):
if event.type == KEY:
if event.val == K_A:
self._dx = -1
if event.val == K_D:
self._dx = 1
def update(self):
if self._pos.x == self.border.x - len(self._image) - 1 and self._dx > 0:
self._pos.x = 0
elif self._pos.x == 1 and self._dx < 0:
self._pos.x = self.border.x - len(self._image)
self._pos.x += self._dx
self._dx = 0
def draw(self, screen):
screen.addstr(self._pos.y, self._pos.x, self._image, curses.A_BOLD)
class App(object):
def __init__(self):
#self.screen = curses.initscr()
curses.initscr()
self.border = Point(x=80, y=24)
self.field = Point(x=self.border.x, y=self.border.y-1)
self.screen = curses.newwin(self.border.y, self.border.x, 0, 0)
self.screen.keypad(1)
self.screen.nodelay(1)
curses.noecho()
#curses.cbreak()
curses.curs_set(0)
self.spaceship = Spaceship(self.field)
self._objects = []
self._objects.append(self.spaceship)
def deinit(self):
self.screen.nodelay(0)
self.screen.keypad(0)
curses.nocbreak()
curses.echo()
curses.curs_set(1)
curses.endwin()
def events(self):
c = self.screen.getch()
if c == 27: #Escape
self.deinit()
sys.exit(1)
else:
for o in self._objects:
o.events(Event(type="KEY", val=c))
def update(self):
for o in self._objects:
o.update()
def render(self):
self.screen.clear()
self.screen.border(0)
self.screen.addstr(0, 2, "Score: {} ".format(0))
self.screen.addstr(0, self.border.x // 2 - 4, "XOInvader", curses.A_BOLD)
for o in self._objects:
o.draw(self.screen)
self.screen.refresh()
time.sleep(0.03)
def loop(self):
while True:
self.events()
self.update()
try:
self.render()
except:
self.deinit()
sys.exit(1)
def main():
app = App()
app.loop()
if __name__ == "__main__":
main()
| #! /usr/bin/env python
import sys
import curses
from curses import KEY_ENTER
import time
from collections import namedtuple
KEY = "KEY"
K_A = ord("a")
K_D = ord("d")
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
@property
def x(self):
return self._x
@x.setter
def x(self, val):
self._x = val
@property
def y(self):
return self._y
@y.setter
def y(self, val):
self._y = val
Event = namedtuple("Event", ["type", "val"])
class Spaceship(object):
def __init__(self, border):
self._image = "<i>"
self._dx = 1
self.border = border
self._pos = Point(self.border.x // 2, self.border.y - 1)
def events(self, event):
if event.type == KEY:
if event.val == K_A:
self._dx = -1
if event.val == K_D:
self._dx = 1
def update(self):
if self._pos.x == self.border.x - len(self._image) - 1 and self._dx > 0:
self._pos.x = 0
elif self._pos.x == 1 and self._dx < 0:
self._pos.x = self.border.x - len(self._image)
self._pos.x += self._dx
self._dx = 0
def draw(self, screen):
screen.addstr(self._pos.y, self._pos.x, self._image, curses.A_BOLD)
class App(object):
def __init__(self):
#self.screen = curses.initscr()
curses.initscr()
self.border = namedtuple("border", ["y", "x"])(24, 80)
self.field = namedtuple("field", ["y", "x"])(self.border.y-1, self.border.x)
self.screen = curses.newwin(self.border.y, self.border.x, 0, 0)
self.screen.keypad(1)
self.screen.nodelay(1)
curses.noecho()
#curses.cbreak()
curses.curs_set(0)
self.spaceship = Spaceship(self.field)
self._objects = []
self._objects.append(self.spaceship)
def deinit(self):
self.screen.nodelay(0)
self.screen.keypad(0)
curses.nocbreak()
curses.echo()
curses.curs_set(1)
curses.endwin()
def events(self):
c = self.screen.getch()
if c == 27: #Escape
self.deinit()
sys.exit(1)
else:
for o in self._objects:
o.events(Event(type="KEY", val=c))
def update(self):
for o in self._objects:
o.update()
def render(self):
self.screen.clear()
self.screen.border(0)
self.screen.addstr(0, 2, "Score: {} ".format(0))
self.screen.addstr(0, self.border.x // 2 - 4, "XOInvader", curses.A_BOLD)
for o in self._objects:
o.draw(self.screen)
self.screen.refresh()
time.sleep(0.03)
def loop(self):
while True:
self.events()
self.update()
try:
self.render()
except:
self.deinit()
sys.exit(1)
def main():
app = App()
app.loop()
if __name__ == "__main__":
main()
| Python | 0.000386 |
86c45216633a3a273d04a64bc54ca1026b3d5069 | Fix comment middleware | debreach/middleware.py | debreach/middleware.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import base64
import logging
import random
from Crypto.Cipher import AES
from django.core.exceptions import SuspiciousOperation
from debreach.compat import \
force_bytes, get_random_string, string_types, force_text
log = logging.getLogger(__name__)
class CSRFCryptMiddleware(object):
def process_request(self, request):
if request.POST.get('csrfmiddlewaretoken') \
and '$' in request.POST.get('csrfmiddlewaretoken'):
try:
POST = request.POST.copy()
token = POST.get('csrfmiddlewaretoken')
key, value = token.split('$')
value = base64.decodestring(force_bytes(value)).strip()
aes = AES.new(key.strip())
POST['csrfmiddlewaretoken'] = aes.decrypt(value).strip()
POST._mutable = False
request.POST = POST
except:
log.exception('Error decoding csrfmiddlewaretoken')
raise SuspiciousOperation(
'csrfmiddlewaretoken has been tampered with')
return
class RandomCommentMiddleware(object):
def process_response(self, request, response):
if not getattr(response, 'streaming', False) \
and response['Content-Type'].strip().startswith('text/html') \
and isinstance(response.content, string_types):
comment = '<!-- {0} -->'.format(
get_random_string(random.choice(range(12, 25))))
response.content = '{0}{1}'.format(
force_text(response.content), comment)
return response
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import base64
import logging
import random
from Crypto.Cipher import AES
from django.core.exceptions import SuspiciousOperation
from debreach.compat import \
force_bytes, get_random_string, string_types, force_text
log = logging.getLogger(__name__)
class CSRFCryptMiddleware(object):
def process_request(self, request):
if request.POST.get('csrfmiddlewaretoken') \
and '$' in request.POST.get('csrfmiddlewaretoken'):
try:
POST = request.POST.copy()
token = POST.get('csrfmiddlewaretoken')
key, value = token.split('$')
value = base64.decodestring(force_bytes(value)).strip()
aes = AES.new(key.strip())
POST['csrfmiddlewaretoken'] = aes.decrypt(value).strip()
POST._mutable = False
request.POST = POST
except:
log.exception('Error decoding csrfmiddlewaretoken')
raise SuspiciousOperation(
'csrfmiddlewaretoken has been tampered with')
return
class RandomCommentMiddleware(object):
def process_response(self, request, response):
if not getattr(response, 'streaming', False) \
and response['Content-Type'] == 'text/html' \
and isinstance(response.content, string_types):
comment = '<!-- {0} -->'.format(
get_random_string(random.choice(range(12, 25))))
response.content = '{0}{1}'.format(
force_text(response.content), comment)
return response
| Python | 0.000002 |
1e7bbd7b59abbe0bcb01fd98079a362f4f874d3b | Fix long waiting version number up | dedupsqlfs/__init__.py | dedupsqlfs/__init__.py | # -*- coding: utf8 -*-
# Documentation. {{{1
"""
This Python library implements a file system in user space using FUSE. It's
called DedupFS because the file system's primary feature is deduplication,
which enables it to store virtually unlimited copies of files because data
is only stored once.
In addition to deduplication the file system also supports transparent
compression using any of the compression methods zlib, bz2, lzma
and optionaly lzo, lz4, snappy, zstd.
These two properties make the file system ideal for backups: I'm currently
storing 250 GB worth of backups using only 8 GB of disk space.
The latest version is available at https://github.com/sergey-dryabzhinsky/dedupsqlfs
DedupFS is licensed under the MIT license.
Copyright 2010 Peter Odding <peter@peterodding.com>.
Copyright 2013-2020 Sergey Dryabzhinsky <sergey.dryabzhinsky@gmail.com>.
"""
__name__ = "DedupSQLfs"
# for fuse mount
__fsname__ = "dedupsqlfs"
__fsversion__ = "3.3"
# Future 1.3
__version__ = "1.2.949-dev"
# Check the Python version, warn the user if untested.
import sys
if sys.version_info[0] < 3 or \
(sys.version_info[0] == 3 and sys.version_info[1] < 2):
msg = "Warning: %s(%s, $s) has only been tested on Python 3.2, while you're running Python %d.%d!\n"
sys.stderr.write(msg % (__name__, __fsversion__, __version__, sys.version_info[0], sys.version_info[1]))
# Do not abuse GC - we generate alot objects
import gc
if hasattr(gc, "set_threshold"):
gc.set_threshold(100000, 2000, 200)
| # -*- coding: utf8 -*-
# Documentation. {{{1
"""
This Python library implements a file system in user space using FUSE. It's
called DedupFS because the file system's primary feature is deduplication,
which enables it to store virtually unlimited copies of files because data
is only stored once.
In addition to deduplication the file system also supports transparent
compression using any of the compression methods zlib, bz2, lzma
and optionaly lzo, lz4, snappy, zstd.
These two properties make the file system ideal for backups: I'm currently
storing 250 GB worth of backups using only 8 GB of disk space.
The latest version is available at https://github.com/sergey-dryabzhinsky/dedupsqlfs
DedupFS is licensed under the MIT license.
Copyright 2010 Peter Odding <peter@peterodding.com>.
Copyright 2013-2020 Sergey Dryabzhinsky <sergey.dryabzhinsky@gmail.com>.
"""
__name__ = "DedupSQLfs"
# for fuse mount
__fsname__ = "dedupsqlfs"
__fsversion__ = "3.3"
# Future 1.3
__version__ = "1.2.947"
# Check the Python version, warn the user if untested.
import sys
if sys.version_info[0] < 3 or \
(sys.version_info[0] == 3 and sys.version_info[1] < 2):
msg = "Warning: %s(%s, $s) has only been tested on Python 3.2, while you're running Python %d.%d!\n"
sys.stderr.write(msg % (__name__, __fsversion__, __version__, sys.version_info[0], sys.version_info[1]))
# Do not abuse GC - we generate alot objects
import gc
if hasattr(gc, "set_threshold"):
gc.set_threshold(100000, 2000, 200)
| Python | 0.000075 |
30100751f64e20804dce332fa458a8490be62336 | Add the "interval" option to the raw_parameter_script example | examples/raw_parameter_script.py | examples/raw_parameter_script.py | """ The main purpose of this file is to demonstrate running SeleniumBase
scripts without the use of Pytest by calling the script directly
with Python or from a Python interactive interpreter. Based on
whether relative imports work or don't, the script can autodetect
how this file was run. With pure Python, it will initialize
all the variables that would've been automatically initialized
by the Pytest plugin. The setUp() and tearDown() methods are also
now called from the script itself.
One big advantage to running tests with Pytest is that most of this
is done for you automatically, with the option to update any of the
parameters through command line parsing. Pytest also provides you
with other plugins, such as ones for generating test reports,
handling multithreading, and parametrized tests. Depending on your
specific needs, you may need to call SeleniumBase commands without
using Pytest, and this example shows you how. """
try:
# Running with Pytest / (Finds test methods to run using autodiscovery)
# Example run command: "pytest raw_parameter_script.py"
from .my_first_test import MyTestClass # (relative imports work: ".~")
except (ImportError, ValueError):
# Running with pure Python OR from a Python interactive interpreter
# Example run command: "python raw_parameter_script.py"
from my_first_test import MyTestClass # (relative imports DON'T work)
sb = MyTestClass("test_basics")
sb.browser = "chrome"
sb.headless = False
sb.headed = False
sb.start_page = None
sb.locale_code = None
sb.servername = "localhost"
sb.port = 4444
sb.data = None
sb.environment = "test"
sb.user_agent = None
sb.incognito = False
sb.guest_mode = False
sb.devtools = False
sb.mobile_emulator = False
sb.device_metrics = None
sb.extension_zip = None
sb.extension_dir = None
sb.database_env = "test"
sb.log_path = "latest_logs/"
sb.archive_logs = False
sb.disable_csp = False
sb.disable_ws = False
sb.enable_ws = False
sb.enable_sync = False
sb.use_auto_ext = False
sb.no_sandbox = False
sb.disable_gpu = False
sb._reuse_session = False
sb._crumbs = False
sb.visual_baseline = False
sb.maximize_option = False
sb.save_screenshot_after_test = False
sb.timeout_multiplier = None
sb.pytest_html_report = None
sb.with_db_reporting = False
sb.with_s3_logging = False
sb.js_checking_on = False
sb.report_on = False
sb.is_pytest = False
sb.slow_mode = False
sb.demo_mode = False
sb.time_limit = None
sb.demo_sleep = 1
sb.dashboard = False
sb._dash_initialized = False
sb.message_duration = 2
sb.block_images = False
sb.remote_debug = False
sb.settings_file = None
sb.user_data_dir = None
sb.proxy_string = None
sb.swiftshader = False
sb.ad_block_on = False
sb.highlights = None
sb.check_js = False
sb.interval = None
sb.cap_file = None
sb.cap_string = None
sb.setUp()
try:
sb.test_basics()
finally:
sb.tearDown()
del sb
| """ The main purpose of this file is to demonstrate running SeleniumBase
scripts without the use of Pytest by calling the script directly
with Python or from a Python interactive interpreter. Based on
whether relative imports work or don't, the script can autodetect
how this file was run. With pure Python, it will initialize
all the variables that would've been automatically initialized
by the Pytest plugin. The setUp() and tearDown() methods are also
now called from the script itself.
One big advantage to running tests with Pytest is that most of this
is done for you automatically, with the option to update any of the
parameters through command line parsing. Pytest also provides you
with other plugins, such as ones for generating test reports,
handling multithreading, and parametrized tests. Depending on your
specific needs, you may need to call SeleniumBase commands without
using Pytest, and this example shows you how. """
try:
# Running with Pytest / (Finds test methods to run using autodiscovery)
# Example run command: "pytest raw_parameter_script.py"
from .my_first_test import MyTestClass # (relative imports work: ".~")
except (ImportError, ValueError):
# Running with pure Python OR from a Python interactive interpreter
# Example run command: "python raw_parameter_script.py"
from my_first_test import MyTestClass # (relative imports DON'T work)
sb = MyTestClass("test_basics")
sb.browser = "chrome"
sb.headless = False
sb.headed = False
sb.start_page = None
sb.locale_code = None
sb.servername = "localhost"
sb.port = 4444
sb.data = None
sb.environment = "test"
sb.user_agent = None
sb.incognito = False
sb.guest_mode = False
sb.devtools = False
sb.mobile_emulator = False
sb.device_metrics = None
sb.extension_zip = None
sb.extension_dir = None
sb.database_env = "test"
sb.log_path = "latest_logs/"
sb.archive_logs = False
sb.disable_csp = False
sb.disable_ws = False
sb.enable_ws = False
sb.enable_sync = False
sb.use_auto_ext = False
sb.no_sandbox = False
sb.disable_gpu = False
sb._reuse_session = False
sb._crumbs = False
sb.visual_baseline = False
sb.maximize_option = False
sb.save_screenshot_after_test = False
sb.timeout_multiplier = None
sb.pytest_html_report = None
sb.with_db_reporting = False
sb.with_s3_logging = False
sb.js_checking_on = False
sb.report_on = False
sb.is_pytest = False
sb.slow_mode = False
sb.demo_mode = False
sb.time_limit = None
sb.demo_sleep = 1
sb.dashboard = False
sb._dash_initialized = False
sb.message_duration = 2
sb.block_images = False
sb.remote_debug = False
sb.settings_file = None
sb.user_data_dir = None
sb.proxy_string = None
sb.swiftshader = False
sb.ad_block_on = False
sb.highlights = None
sb.check_js = False
sb.cap_file = None
sb.cap_string = None
sb.setUp()
try:
sb.test_basics()
finally:
sb.tearDown()
del sb
| Python | 0.001246 |
b8b630c0f1bd53960c1f6bb275f25fecbca520ba | tweak output format. | import_profiler.py | import_profiler.py | import collections
import time
__OLD_IMPORT = None
class ImportInfo(object):
def __init__(self, name, context_name, counter):
self.name = name
self.context_name = context_name
self._counter = counter
self._depth = 0
self._start = time.time()
self.elapsed = None
def done(self):
self.elapsed = time.time() - self._start
@property
def _key(self):
return self.name, self.context_name, self._counter
def __repr__(self):
return "ImportInfo({!r}, {!r}, {!r})".format(*self._key)
def __hash__(self):
return hash(self._key)
def __eq__(self, other):
if isinstance(other, ImportInfo):
return other._key == self._key
return NotImplemented
def __ne__(self):
return not self == other
class ImportStack(object):
def __init__(self):
self._current_stack = []
self._full_stack = collections.defaultdict(list)
self._counter = 0
def push(self, name, context_name):
info = ImportInfo(name, context_name, self._counter)
self._counter += 1
if len(self._current_stack) > 0:
parent = self._current_stack[-1]
self._full_stack[parent].append(info)
self._current_stack.append(info)
info._depth = len(self._current_stack) - 1
return info
def pop(self, import_info):
top = self._current_stack.pop()
assert top is import_info
top.done()
def compute_intime(parent, full_stack, ordered_visited, visited, depth=0):
if parent in visited:
return
cumtime = intime = parent.elapsed
visited[parent] = [cumtime, parent.name, parent.context_name, depth]
ordered_visited.append(parent)
for child in full_stack[parent]:
intime -= child.elapsed
compute_intime(child, full_stack, ordered_visited, visited, depth + 1)
visited[parent].append(intime)
def print_info(import_stack):
full_stack = import_stack._full_stack
keys = sorted(full_stack.keys(), key=lambda p: p._counter)
visited = {}
ordered_visited = []
for key in keys:
compute_intime(key, full_stack, ordered_visited, visited)
lines = []
for k in ordered_visited:
node = visited[k]
cumtime = node[0] * 1000
name = node[1]
context_name = node[2]
level = node[3]
intime = node[-1] * 1000
if cumtime > 1:
lines.append((
"{:.1f}".format(cumtime),
"{:.1f}".format(intime),
"+" * level + name,
))
import tabulate
print(
tabulate.tabulate(
lines, headers=("cumtime (ms)", "intime (ms)", "name"), tablefmt="plain")
)
_IMPORT_STACK = ImportStack()
def profiled_import(name, globals=None, locals=None, fromlist=None,
level=-1, *a, **kw):
if globals is None:
context_name = None
else:
context_name = globals.get("__name__")
if context_name is None:
context_name = globals.get("__file__")
info = _IMPORT_STACK.push(name, context_name)
try:
return __OLD_IMPORT(name, globals, locals, fromlist, level, *a, **kw)
finally:
_IMPORT_STACK.pop(info)
def enable():
global __OLD_IMPORT
__OLD_IMPORT = __builtins__["__import__"]
__builtins__["__import__"] = profiled_import
def disable():
__builtins__["__import__"] = __OLD_IMPORT
| import collections
import time
__OLD_IMPORT = None
class ImportInfo(object):
def __init__(self, name, context_name, counter):
self.name = name
self.context_name = context_name
self._counter = counter
self._depth = 0
self._start = time.time()
self.elapsed = None
def done(self):
self.elapsed = time.time() - self._start
@property
def _key(self):
return self.name, self.context_name, self._counter
def __repr__(self):
return "ImportInfo({!r}, {!r}, {!r})".format(*self._key)
def __hash__(self):
return hash(self._key)
def __eq__(self, other):
if isinstance(other, ImportInfo):
return other._key == self._key
return NotImplemented
def __ne__(self):
return not self == other
class ImportStack(object):
def __init__(self):
self._current_stack = []
self._full_stack = collections.defaultdict(list)
self._counter = 0
def push(self, name, context_name):
info = ImportInfo(name, context_name, self._counter)
self._counter += 1
if len(self._current_stack) > 0:
parent = self._current_stack[-1]
self._full_stack[parent].append(info)
self._current_stack.append(info)
info._depth = len(self._current_stack) - 1
return info
def pop(self, import_info):
top = self._current_stack.pop()
assert top is import_info
top.done()
def compute_intime(parent, full_stack, ordered_visited, visited, depth=0):
if parent in visited:
return
cumtime = intime = parent.elapsed
visited[parent] = [cumtime, parent.name, parent.context_name, depth]
ordered_visited.append(parent)
for child in full_stack[parent]:
intime -= child.elapsed
compute_intime(child, full_stack, ordered_visited, visited, depth + 1)
visited[parent].append(intime)
def print_info(import_stack):
full_stack = import_stack._full_stack
keys = sorted(full_stack.keys(), key=lambda p: p._counter)
visited = {}
ordered_visited = []
for key in keys:
compute_intime(key, full_stack, ordered_visited, visited)
lines = []
for k in ordered_visited:
node = visited[k]
cumtime = node[0] * 1000
name = node[1]
context_name = node[2]
level = node[3]
intime = node[-1] * 1000
if cumtime > 1:
lines.append((
"{:.2}".format(cumtime),
"{:.2}".format(intime),
"+" * level + name,
))
import tabulate
print(
tabulate.tabulate(
lines, headers=("cumtime", "intime", "name"), tablefmt="plain")
)
_IMPORT_STACK = ImportStack()
def profiled_import(name, globals=None, locals=None, fromlist=None,
level=-1, *a, **kw):
if globals is None:
context_name = None
else:
context_name = globals.get("__name__")
if context_name is None:
context_name = globals.get("__file__")
info = _IMPORT_STACK.push(name, context_name)
try:
return __OLD_IMPORT(name, globals, locals, fromlist, level, *a, **kw)
finally:
_IMPORT_STACK.pop(info)
def enable():
global __OLD_IMPORT
__OLD_IMPORT = __builtins__["__import__"]
__builtins__["__import__"] = profiled_import
def disable():
__builtins__["__import__"] = __OLD_IMPORT
| Python | 0 |
dd7b10a89e3fd5e431b03e922fbbc0a49c3d8c5e | Fix failing wavelet example due to outdated code | examples/trafos/wavelet_trafo.py | examples/trafos/wavelet_trafo.py | # Copyright 2014-2016 The ODL development group
#
# This file is part of ODL.
#
# ODL is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ODL is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ODL. If not, see <http://www.gnu.org/licenses/>.
"""Simple example on the usage of the Wavelet Transform."""
import odl
# Discretized space: discretized functions on the rectangle [-1, 1] x [-1, 1]
# with 512 samples per dimension.
space = odl.uniform_discr([-1, -1], [1, 1], (256, 256))
# Make the Wavelet transform operator on this space. The range is calculated
# automatically. The default backend is PyWavelets (pywt).
wavelet_op = odl.trafos.WaveletTransform(space, wavelet='Haar', nlevels=2)
# Create a phantom and its wavelet transfrom and display them.
phantom = odl.phantom.shepp_logan(space, modified=True)
phantom.show(title='Shepp-Logan phantom')
# Note that the wavelet transform is a vector in rn.
phantom_wt = wavelet_op(phantom)
phantom_wt.show(title='wavelet transform')
# It may however (for some choices of wbasis) be interpreted as a vector in the
# domain of the transformation
phantom_wt_2d = space.element(phantom_wt)
phantom_wt_2d.show('wavelet transform in 2d')
# Calculate the inverse transform.
phantom_wt_inv = wavelet_op.inverse(phantom_wt)
phantom_wt_inv.show(title='wavelet transform inverted')
| # Copyright 2014-2016 The ODL development group
#
# This file is part of ODL.
#
# ODL is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ODL is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ODL. If not, see <http://www.gnu.org/licenses/>.
"""Simple example on the usage of the Wavelet Transform."""
import odl
# Discretized space: discretized functions on the rectangle [-1, 1] x [-1, 1]
# with 512 samples per dimension.
space = odl.uniform_discr([-1, -1], [1, 1], (256, 256))
# Make the Wavelet transform operator on this space. The range is calculated
# automatically. The default backend is PyWavelets (pywt).
wavelet_op = odl.trafos.WaveletTransform(space, nscales=2, wbasis='Haar')
# Create a phantom and its wavelet transfrom and display them.
phantom = odl.phantom.shepp_logan(space, modified=True)
phantom.show(title='Shepp-Logan phantom')
# Note that the wavelet transform is a vector in rn.
phantom_wt = wavelet_op(phantom)
phantom_wt.show(title='wavelet transform')
# It may however (for some choices of wbasis) be interpreted as a vector in the
# domain of the transformation
phantom_wt_2d = space.element(phantom_wt)
phantom_wt_2d.show('wavelet transform in 2d')
# Calculate the inverse transform.
phantom_wt_inv = wavelet_op.inverse(phantom_wt)
phantom_wt_inv.show(title='wavelet transform inverted')
| Python | 0 |
5e86582ebde98f14df796102062659f185c2bcca | update docs/extensions/fancy_include.py with git_cast_file2repos.py | docs/extensions/fancy_include.py | docs/extensions/fancy_include.py | """Include single scripts with doc string, code, and image
Use case
--------
There is an "examples" directory in the root of a repository,
e.g. 'include_doc_code_img_path = "../examples"' in conf.py
(default). An example is a file ("an_example.py") that consists
of a doc string at the beginning of the file, the example code,
and, optionally, an image file (png, jpg) ("an_example.png").
Configuration
-------------
In conf.py, set the parameter
fancy_include_path = "../examples"
to wherever the included files reside.
Usage
-----
The directive
.. fancy_include:: an_example.py
will display the doc string formatted with the first line as a
heading, a code block with line numbers, and the image file.
"""
import os.path as op
from docutils.statemachine import ViewList
from docutils.parsers.rst import Directive
from sphinx.util.nodes import nested_parse_with_titles
from docutils import nodes
class IncludeDirective(Directive):
required_arguments = 1
optional_arguments = 0
def run(self):
path = self.state.document.settings.env.config.fancy_include_path
full_path = op.join(path, self.arguments[0])
with open(full_path, "r") as myfile:
text = myfile.read()
source = text.split('"""')
doc = source[1].split("\n")
doc.insert(1, "~" * len(doc[0])) # make title heading
code = source[2].split("\n")
# documentation
rst = []
for line in doc:
rst.append(line)
# image
for ext in [".png", ".jpg"]:
image_path = full_path[:-3] + ext
if op.exists(image_path):
break
else:
image_path = ""
if image_path:
rst.append(".. figure:: {}".format(image_path))
rst.append("")
# download file
rst.append(":download:`{}<{}>`".format(
op.basename(full_path), full_path))
# code
rst.append("")
rst.append(".. code-block:: python")
rst.append(" :linenos:")
rst.append("")
for line in code:
rst.append(" {}".format(line))
rst.append("")
vl = ViewList(rst, "fakefile.rst")
# Create a node.
node = nodes.section()
node.document = self.state.document
# Parse the rst.
nested_parse_with_titles(self.state, vl, node)
return node.children
def setup(app):
app.add_config_value('fancy_include_path', "../examples", 'html')
app.add_directive('fancy_include', IncludeDirective)
return {'version': '0.1'} # identifies the version of our extension
| """Include single scripts with doc string, code, and image
Use case
--------
There is an "examples" directory in the root of a repository,
e.g. 'include_doc_code_img_path = "../examples"' in conf.py
(default). An example is a file ("an_example.py") that consists
of a doc string at the beginning of the file, the example code,
and, optionally, an image file (png, jpg) ("an_example.png").
Configuration
-------------
In conf.py, set the parameter
fancy_include_path = "../examples"
to wherever the included files reside.
Usage
-----
The directive
.. fancy_include:: an_example.py
will display the doc string formatted with the first line as a
heading, a code block with line numbers, and the image file.
"""
import os.path as op
from docutils.statemachine import ViewList
from docutils.parsers.rst import Directive
from sphinx.util.nodes import nested_parse_with_titles
from docutils import nodes
class IncludeDirective(Directive):
required_arguments = 1
optional_arguments = 0
def run(self):
path = self.state.document.settings.env.config.fancy_include_path
full_path = op.join(path, self.arguments[0])
with open(full_path, "r") as myfile:
text = myfile.read()
source = text.split('"""')
doc = source[1].split("\n")
doc.insert(1, "~" * len(doc[0])) # make title heading
code = source[2].split("\n")
# documentation
rst = []
for line in doc:
rst.append(line)
# image
for ext in [".png", ".jpg"]:
image_path = full_path[:-3] + ext
if op.exists(image_path):
break
else:
image_path = ""
if image_path:
rst.append(".. figure:: {}".format(image_path))
# download file
rst.append(":download:`{}<{}>`".format(
op.basename(full_path), full_path))
# code
rst.append("")
rst.append(".. code-block:: python")
rst.append(" :linenos:")
rst.append("")
for line in code:
rst.append(" {}".format(line))
rst.append("")
vl = ViewList(rst, "fakefile.rst")
# Create a node.
node = nodes.section()
node.document = self.state.document
# Parse the rst.
nested_parse_with_titles(self.state, vl, node)
return node.children
def setup(app):
app.add_config_value('fancy_include_path', "../examples", 'html')
app.add_directive('fancy_include', IncludeDirective)
return {'version': '0.1'} # identifies the version of our extension
| Python | 0.000001 |
0d38b9592fbb63e25b080d2f17b690c478042455 | Add comments to Perfect Game solution | google-code-jam-2012/perfect-game/perfect-game.py | google-code-jam-2012/perfect-game/perfect-game.py | #!/usr/bin/env python
# expected time per attempt is given by equation
# time = L[0] + (1-P[0])*L[1] + (1-P[0])*(1-P[1])*L[2] + ...
# where L is the expected time and P is the probability of failure, per level
# swap two levels if L[i]*P[i+1] > L[i+1]*P[i]
import sys
if len(sys.argv) < 2:
sys.exit('Usage: %s file.in' % sys.argv[0])
file = open(sys.argv[1], 'r')
T = int(file.readline())
for i in xrange(1, T+1):
N = int(file.readline())
L = map(int, file.readline().split(' '))
P = map(int, file.readline().split(' '))
assert N == len(L)
assert N == len(P)
levels = zip(L, P, range(N))
levels.sort(lambda li, pi: li[0] * pi[1] - li[1] * pi[0])
print "Case #%d:" % i, ' '.join([str(i) for li, pi, i in levels])
file.close()
| #!/usr/bin/env python
import sys
if len(sys.argv) < 2:
sys.exit('Usage: %s file.in' % sys.argv[0])
file = open(sys.argv[1], 'r')
T = int(file.readline())
for i in xrange(1, T+1):
N = int(file.readline())
L = map(int, file.readline().split(' '))
P = map(int, file.readline().split(' '))
assert N == len(L)
assert N == len(P)
levels = zip(L, P, range(N))
levels.sort(lambda li, pi: li[0] * pi[1] - li[1] * pi[0])
print "Case #%d:" % i, ' '.join([str(i) for li, pi, i in levels])
file.close()
| Python | 0 |
9f9e2db5105eab1f46590a6b8d6a5b5eff4ccb51 | Use new BinarySensorDeviceClass enum in egardia (#61378) | homeassistant/components/egardia/binary_sensor.py | homeassistant/components/egardia/binary_sensor.py | """Interfaces with Egardia/Woonveilig alarm control panel."""
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
)
from homeassistant.const import STATE_OFF, STATE_ON
from . import ATTR_DISCOVER_DEVICES, EGARDIA_DEVICE
EGARDIA_TYPE_TO_DEVICE_CLASS = {
"IR Sensor": BinarySensorDeviceClass.MOTION,
"Door Contact": BinarySensorDeviceClass.OPENING,
"IR": BinarySensorDeviceClass.MOTION,
}
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Initialize the platform."""
if discovery_info is None or discovery_info[ATTR_DISCOVER_DEVICES] is None:
return
disc_info = discovery_info[ATTR_DISCOVER_DEVICES]
async_add_entities(
(
EgardiaBinarySensor(
sensor_id=disc_info[sensor]["id"],
name=disc_info[sensor]["name"],
egardia_system=hass.data[EGARDIA_DEVICE],
device_class=EGARDIA_TYPE_TO_DEVICE_CLASS.get(
disc_info[sensor]["type"], None
),
)
for sensor in disc_info
),
True,
)
class EgardiaBinarySensor(BinarySensorEntity):
"""Represents a sensor based on an Egardia sensor (IR, Door Contact)."""
def __init__(self, sensor_id, name, egardia_system, device_class):
"""Initialize the sensor device."""
self._id = sensor_id
self._name = name
self._state = None
self._device_class = device_class
self._egardia_system = egardia_system
def update(self):
"""Update the status."""
egardia_input = self._egardia_system.getsensorstate(self._id)
self._state = STATE_ON if egardia_input else STATE_OFF
@property
def name(self):
"""Return the name of the device."""
return self._name
@property
def is_on(self):
"""Whether the device is switched on."""
return self._state == STATE_ON
@property
def device_class(self):
"""Return the device class."""
return self._device_class
| """Interfaces with Egardia/Woonveilig alarm control panel."""
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_MOTION,
DEVICE_CLASS_OPENING,
BinarySensorEntity,
)
from homeassistant.const import STATE_OFF, STATE_ON
from . import ATTR_DISCOVER_DEVICES, EGARDIA_DEVICE
EGARDIA_TYPE_TO_DEVICE_CLASS = {
"IR Sensor": DEVICE_CLASS_MOTION,
"Door Contact": DEVICE_CLASS_OPENING,
"IR": DEVICE_CLASS_MOTION,
}
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Initialize the platform."""
if discovery_info is None or discovery_info[ATTR_DISCOVER_DEVICES] is None:
return
disc_info = discovery_info[ATTR_DISCOVER_DEVICES]
async_add_entities(
(
EgardiaBinarySensor(
sensor_id=disc_info[sensor]["id"],
name=disc_info[sensor]["name"],
egardia_system=hass.data[EGARDIA_DEVICE],
device_class=EGARDIA_TYPE_TO_DEVICE_CLASS.get(
disc_info[sensor]["type"], None
),
)
for sensor in disc_info
),
True,
)
class EgardiaBinarySensor(BinarySensorEntity):
"""Represents a sensor based on an Egardia sensor (IR, Door Contact)."""
def __init__(self, sensor_id, name, egardia_system, device_class):
"""Initialize the sensor device."""
self._id = sensor_id
self._name = name
self._state = None
self._device_class = device_class
self._egardia_system = egardia_system
def update(self):
"""Update the status."""
egardia_input = self._egardia_system.getsensorstate(self._id)
self._state = STATE_ON if egardia_input else STATE_OFF
@property
def name(self):
"""Return the name of the device."""
return self._name
@property
def is_on(self):
"""Whether the device is switched on."""
return self._state == STATE_ON
@property
def device_class(self):
"""Return the device class."""
return self._device_class
| Python | 0 |
568828287f426bef598c11267b6ee351751671fe | add conf parameters to XPathFetchPage module | feedin/modules/xpathfetchpage.py | feedin/modules/xpathfetchpage.py | from module import Module
import urllib2
import urlparse
from StringIO import StringIO
import gzip
from lxml import html
from lxml import etree
from feedin import util
from feedin.dotdict2 import DotDict2
from module import ModuleBuilder
class XPathFetchPage(Module):
EXTRACT_TYPE_DICT = 'dict'
EXTRACT_TYPE_TEXT = 'text'
EXTRACT_TYPE_HTML = 'html'
CHARSETS = ['utf8', 'gb2312', 'GB18030']
'''
classdocs
'''
def __init__(self, setting, context=None):
super(XPathFetchPage, self).__init__(setting, context)
self.URL = setting['conf']['URL']
self.ExtractXPath = setting['conf']['xpath']['value']
self.html5 = setting['conf']['html']['value'] == 'true' if 'html5' in setting['conf'] else False
self.useAsString = setting['conf']['useAsString']['value'] == 'true' if 'useAsString' in setting['conf'] else False
self.ExtractMethod = setting['conf']['ExtractMethod'] if 'ExtractMethod' in setting['conf'] else XPathFetchPage.EXTRACT_TYPE_DICT
def execute(self, context=None):
url = self.URL
if 'subkey' in self.URL: # a subkey assigned
key = self.URL['subkey'].lstrip('item.')
url = context.items[0][key]
else:
url = self.URL['value']
http_proxy = context.http_proxy
if http_proxy:
proxy_handler = urllib2.ProxyHandler({'http': http_proxy})
opener = urllib2.build_opener(proxy_handler)
else:
opener = urllib2.build_opener()
response = opener.open(url)
content = response.read()
opener.close()
if response.info().get('Content-Encoding') == 'gzip':
buf = StringIO(content)
f = gzip.GzipFile(fileobj=buf)
content = f.read()
decoding_error = None # last decoding error, will be raised if cannot decode the content
decoded_content = None # decoded
for charset in XPathFetchPage.CHARSETS:
try:
decoded_content = unicode(content, charset)
except UnicodeDecodeError as e:
decoding_error = e
if not decoded_content and decoding_error:
raise decoding_error
root = html.fromstring(decoded_content)
#root = doc.getroot()
context.last_result = []
for element in root.xpath(self.ExtractXPath):
for link_element in element.iter("a"):
link_element.set("href", urlparse.urljoin(url, link_element.get("href")))
if self.ExtractMethod == XPathFetchPage.EXTRACT_TYPE_TEXT:
new_item = etree.tostring(element, method='text', encoding=unicode)
elif self.ExtractMethod == XPathFetchPage.EXTRACT_TYPE_HTML:
new_item = etree.tostring(element, method='html', encoding=unicode)
else:
element_dic = util.etree_to_dict2(element)
new_item = DotDict2(element_dic)
context.items.append(new_item)
context.last_result.append(new_item)
class XPathFetchPageBuilder(ModuleBuilder):
def build(self, module_config, context=None):
return XPathFetchPage(module_config, context) | from module import Module
import urllib2
import urlparse
from StringIO import StringIO
import gzip
from lxml import html
from lxml import etree
from feedin import util
from feedin.dotdict2 import DotDict2
from module import ModuleBuilder
class XPathFetchPage(Module):
EXTRACT_TYPE_DICT = 'dict'
EXTRACT_TYPE_TEXT = 'text'
EXTRACT_TYPE_HTML = 'html'
CHARSETS = ['utf8', 'gb2312', 'GB18030']
'''
classdocs
'''
def __init__(self, setting, context=None):
super(XPathFetchPage, self).__init__(setting, context)
self.URL = setting['conf']['URL']
self.ExtractXPath = setting['conf']['xpath']['value']
self.ExtractMethod = setting['conf']['ExtractMethod'] if 'ExtractMethod' in setting['conf'] else XPathFetchPage.EXTRACT_TYPE_DICT
def execute(self, context=None):
url = self.URL
if 'subkey' in self.URL: # a subkey assigned
key = self.URL['subkey'].lstrip('item.')
url = context.items[0][key]
else:
url = self.URL['value']
http_proxy = context.http_proxy
if http_proxy:
proxy_handler = urllib2.ProxyHandler({'http': http_proxy})
opener = urllib2.build_opener(proxy_handler)
else:
opener = urllib2.build_opener()
response = opener.open(url)
content = response.read()
opener.close()
if response.info().get('Content-Encoding') == 'gzip':
buf = StringIO(content)
f = gzip.GzipFile(fileobj=buf)
content = f.read()
decoding_error = None # last decoding error, will be raised if cannot decode the content
decoded_content = None # decoded
for charset in XPathFetchPage.CHARSETS:
try:
decoded_content = unicode(content, charset)
except UnicodeDecodeError as e:
decoding_error = e
if not decoded_content and decoding_error:
raise decoding_error
root = html.fromstring(decoded_content)
#root = doc.getroot()
context.last_result = []
for element in root.xpath(self.ExtractXPath):
for link_element in element.iter("a"):
link_element.set("href", urlparse.urljoin(url, link_element.get("href")))
if self.ExtractMethod == XPathFetchPage.EXTRACT_TYPE_TEXT:
new_item = etree.tostring(element, method='text', encoding=unicode)
elif self.ExtractMethod == XPathFetchPage.EXTRACT_TYPE_HTML:
new_item = etree.tostring(element, method='html', encoding=unicode)
else:
element_dic = util.etree_to_dict2(element)
new_item = DotDict2(element_dic)
context.items.append(new_item)
context.last_result.append(new_item)
class XPathFetchPageBuilder(ModuleBuilder):
def build(self, module_config, context=None):
return XPathFetchPage(module_config, context) | Python | 0 |
a4ee7fa5b77b4513ceddcfb0e9be958442d3c792 | Use lambdas for api commands | IKEA.py | IKEA.py | import json
import uuid
from pytradfri import Gateway
from pytradfri.api.libcoap_api import APIFactory
from time import sleep
import numpy
CONFIG_FILE = "tradfri_psk.conf"
class RGB(numpy.ndarray):
@classmethod
def from_str(cls, hex):
return numpy.array([int(hex[i:i+2], 16) for i in (0, 2, 4)]).view(cls)
def __str__(self):
self = self.astype(numpy.uint8)
return ''.join(format(n, 'x') for n in self)
class TradfriHandler:
def __init__(self, gateway_hostname, key):
conf = self.load_psk(CONFIG_FILE)
try:
identity = conf[gateway_hostname].get("identity")
psk = conf[gateway_hostname].get("key")
api_factory = APIFactory(host=gateway_hostname, psk_id=identity, psk=psk)
except KeyError:
identity = uuid.uuid4().hex
api_factory = APIFactory(host=gateway_hostname, psk_id=identity)
psk = api_factory.generate_psk(key)
conf[gateway_hostname] = {"identity": identity, "key": psk}
self.save_psk(CONFIG_FILE, conf)
self.api = api_factory.request
self.gateway = Gateway()
@staticmethod
def load_psk(filename):
try:
with open(filename, encoding="utf-8") as fdesc:
return json.loads(fdesc.read())
except FileNotFoundError:
return {}
@staticmethod
def save_psk(filename, config):
data = json.dumps(config, sort_keys=True, indent=4)
with open(filename, "w", encoding="utf-8") as fdesc:
fdesc.write(data)
@staticmethod
def average_hex_color(colors):
if len(colors) == 1:
return colors[0]
rgb_colors = [RGB.from_str(hex) for hex in colors]
return (numpy.sum(rgb_colors, axis=0) // len(rgb_colors)).view(RGB)
def export_group(self, group):
# These properties exists on the group as well, but they are incorrect for some reason
hex_colors, states = zip(*map(lambda light: (light.light_control.lights[0].hex_color,
light.light_control.lights[0].state),
filter(lambda device: device.has_light_control,
self.api(group.members()))
))
return {
"name": group.name,
"id": group.id,
"state": any(states),
"dimmer": group.dimmer,
"color": '#' + str(self.average_hex_color(list(hex_colors)))
}
def export_groups(self):
return list(map(self.export_group, self.get_groups()))
def get_groups(self):
devices_commands = self.api(self.gateway.get_groups())
return self.api(devices_commands)
def get_group(self, group_id):
return self.api(self.gateway.get_group(group_id))
def set_state(self, group_id, new_state):
return self.run_api_command_for_group(lambda lg: lg.set_state(new_state),
group_id)
def set_dimmer(self, group_id, value):
return self.run_api_command_for_group(lambda lg: lg.set_dimmer(value, transition_time=1),
group_id)
def set_hex_color(self, group_id, value):
return self.run_api_command_for_group(lambda lg: lg.set_hex_color(value, transition_time=1),
group_id)
def run_api_command_for_group(self, command_function, group_id):
light_group = self.get_group(group_id)
if not light_group:
return False
self.api(command_function(light_group))
return True | import json
import uuid
from pytradfri import Gateway
from pytradfri.api.libcoap_api import APIFactory
from time import sleep
import numpy
CONFIG_FILE = "tradfri_psk.conf"
class RGB(numpy.ndarray):
@classmethod
def from_str(cls, hex):
return numpy.array([int(hex[i:i+2], 16) for i in (0, 2, 4)]).view(cls)
def __str__(self):
self = self.astype(numpy.uint8)
return ''.join(format(n, 'x') for n in self)
class TradfriHandler:
def __init__(self, gateway_hostname, key):
conf = self.load_psk(CONFIG_FILE)
try:
identity = conf[gateway_hostname].get("identity")
psk = conf[gateway_hostname].get("key")
api_factory = APIFactory(host=gateway_hostname, psk_id=identity, psk=psk)
except KeyError:
identity = uuid.uuid4().hex
api_factory = APIFactory(host=gateway_hostname, psk_id=identity)
psk = api_factory.generate_psk(key)
conf[gateway_hostname] = {"identity": identity, "key": psk}
self.save_psk(CONFIG_FILE, conf)
self.api = api_factory.request
self.gateway = Gateway()
@staticmethod
def load_psk(filename):
try:
with open(filename, encoding="utf-8") as fdesc:
return json.loads(fdesc.read())
except FileNotFoundError:
return {}
@staticmethod
def save_psk(filename, config):
data = json.dumps(config, sort_keys=True, indent=4)
with open(filename, "w", encoding="utf-8") as fdesc:
fdesc.write(data)
@staticmethod
def average_hex_color(colors):
if len(colors) == 1:
return colors[0]
rgb_colors = [RGB.from_str(hex) for hex in colors]
return (numpy.sum(rgb_colors, axis=0) // len(rgb_colors)).view(RGB)
def export_group(self, group):
# These properties exists on the group as well, but they are incorrect for some reason
hex_colors, states = zip(*map(lambda light: (light.light_control.lights[0].hex_color,
light.light_control.lights[0].state),
filter(lambda device: device.has_light_control,
self.api(group.members()))
))
return {
"name": group.name,
"id": group.id,
"state": any(states),
"dimmer": group.dimmer,
"color": '#' + str(self.average_hex_color(list(hex_colors)))
}
def export_groups(self):
return list(map(self.export_group, self.get_groups()))
def get_groups(self):
devices_commands = self.api(self.gateway.get_groups())
return self.api(devices_commands)
def get_group(self, group_id):
return self.api(self.gateway.get_group(group_id))
def set_state(self, group_id, new_state):
light_group = self.get_group(group_id)
if not light_group:
return False
self.api(light_group.set_state(new_state))
return True
def set_dimmer(self, group_id, value):
light_group = self.get_group(group_id)
if not light_group:
return False
self.api(light_group.set_dimmer(value, transition_time=1))
return True
def set_hex_color(self, group_id, value):
light_group = self.get_group(group_id)
if not light_group:
return False
self.api(light_group.set_hex_color(value, transition_time=1))
return True
| Python | 0.000001 |
ead5daf0e631a3482a8510abc36f48b227e862ee | Delete unused variable assignations. | game.py | game.py | # -*- coding: utf-8 -*-
import functions.commands as command
import functions.database as db
f = open('ASCII/otsikko_unicode.asc', 'r')
print(f.read())
f.close()
while True:
'''
You can end loop by selecting 5 in main context or write
"quit" in game context.
'''
context = command.doMenu()
while context == "main":
prompt = "(main) >>> "
try:
c = int(input(prompt))
context = command.doMenu(c)
except ValueError as e:
print(e)
while context == "game":
position = db.getPosition()
prompt = "(game) >>> "
print("--\n{}".format(position))
c = input(prompt).lower().split()
if (command.isValid(c)):
context = command.execute(c)
else:
print('Invalid command. '
'Write "help" to get list of available commands.'
)
| # -*- coding: utf-8 -*-
import functions.commands as command
import functions.database as db
prompt = ">>> "
view = {
'0.0' : "Tutorial. You see a rat attacking you, fight!",
'1.0' : "You stand in a start of dungeon. You see a torch."
}
position = '1.0'
f = open('ASCII/otsikko_unicode.asc', 'r')
print(f.read())
f.close()
while True:
'''
You can end loop by selecting 5 in main context or write
"quit" in game context.
'''
context = command.doMenu()
while context == "main":
prompt = "(main) >>> "
try:
c = int(input(prompt))
context = command.doMenu(c)
except ValueError as e:
print(e)
while context == "game":
position = db.getPosition()
prompt = "(game) >>> "
print("--\n{}".format(position))
c = input(prompt).lower().split()
if (command.isValid(c)):
context = command.execute(c)
else:
print('Invalid command. '
'Write "help" to get list of available commands.'
)
| Python | 0 |
760bc99c22b6ac66cdd240b29720d0bbfccc4920 | Define waf_tools for each class instance separately | glue.py | glue.py | """
Glue code between nsloaders and Mybuild bindings for py/my DSL files.
"""
__author__ = "Eldar Abusalimov"
__date__ = "2013-08-07"
from _compat import *
from nsloader import myfile
from nsloader import pyfile
import mybuild
from mybuild.binding import pydsl
from util.operator import attr
from util.namespace import Namespace
class LoaderMixin(object):
dsl = None
@property
def defaults(self):
return dict(super(LoaderMixin, self).defaults,
module = self.dsl.module,
application = self.dsl.application,
library = self.dsl.library,
project = self.dsl.project,
option = self.dsl.option,
tool = tool,
MYBUILD_VERSION=mybuild.__version__)
class WafBasedTool(mybuild.core.Tool):
def __init__(self):
super(WafBasedTool, self).__init__()
self.waf_tools = []
def options(self, module, ctx):
ctx.load(self.waf_tools)
def configure(self, module, ctx):
ctx.load(self.waf_tools)
class CcTool(WafBasedTool):
def __init__(self):
super(CcTool, self).__init__()
self.waf_tools.append('compiler_c')
self.build_kwargs = {}
def create_namespaces(self, module):
return dict(cc=Namespace(defines=Namespace()))
def define(self, key, val):
assert('defines' in self.build_kwargs)
format_str = '{0}=\"{1}\"' if isinstance(val, str) else '{0}={1}'
self.build_kwargs['defines'].append(format_str.format(key, val))
def build(self, module, ctx):
self.build_kwargs['use'] = [m._name for m in module.depends]
self.build_kwargs['source'] = module.files
self.build_kwargs['target'] = module._name
self.build_kwargs['defines'] = []
for k, v in iteritems(module.cc.defines.__dict__):
self.define(k, v)
class CcObjTool(CcTool):
def build(self, module, ctx):
super(CcObjTool, self).build(module, ctx)
ctx.objects(**self.build_kwargs)
class CcAppTool(CcTool):
def build(self, module, ctx):
super(CcAppTool, self).build(module, ctx)
ctx.program(**self.build_kwargs)
class CcLibTool(CcTool):
def build(self, module, ctx):
super(CcLibTool, self).build(module, ctx)
if module.isstatic:
ctx.stlib(**self.build_kwargs)
else:
ctx.shlib(**self.build_kwargs)
tool = Namespace(cc=CcObjTool(), cc_app=CcAppTool(), cc_lib=CcLibTool())
class MyDslLoader(LoaderMixin, myfile.MyFileLoader):
FILENAME = 'Mybuild'
class CcModule(mybuild.core.Module):
tools = [tool.cc]
class ApplicationCcModule(mybuild.core.Module):
tools = [tool.cc_app]
class LibCcModule(mybuild.core.Module):
tools = [tool.cc_lib]
isstatic = True
dsl = Namespace()
dsl.module = CcModule._meta_for_base(option_types=[])
dsl.application = ApplicationCcModule._meta_for_base(option_types=[])
dsl.library = LibCcModule._meta_for_base(option_types=[])
dsl.option = mybuild.core.Optype
dsl.project = None
class PyDslLoader(LoaderMixin, pyfile.PyFileLoader):
FILENAME = 'Pybuild'
dsl = pydsl
| """
Glue code between nsloaders and Mybuild bindings for py/my DSL files.
"""
__author__ = "Eldar Abusalimov"
__date__ = "2013-08-07"
from _compat import *
from nsloader import myfile
from nsloader import pyfile
import mybuild
from mybuild.binding import pydsl
from util.operator import attr
from util.namespace import Namespace
class LoaderMixin(object):
dsl = None
@property
def defaults(self):
return dict(super(LoaderMixin, self).defaults,
module = self.dsl.module,
application = self.dsl.application,
library = self.dsl.library,
project = self.dsl.project,
option = self.dsl.option,
tool = tool,
MYBUILD_VERSION=mybuild.__version__)
class WafBasedTool(mybuild.core.Tool):
waf_tools = []
def options(self, module, ctx):
ctx.load(self.waf_tools)
def configure(self, module, ctx):
ctx.load(self.waf_tools)
class CcTool(WafBasedTool):
waf_tools = ['compiler_c']
def __init__(self):
super(CcTool, self).__init__()
self.build_kwargs = {}
def create_namespaces(self, module):
return dict(cc=Namespace(defines=Namespace()))
def define(self, key, val):
assert('defines' in self.build_kwargs)
format_str = '{0}=\"{1}\"' if isinstance(val, str) else '{0}={1}'
self.build_kwargs['defines'].append(format_str.format(key, val))
def build(self, module, ctx):
self.build_kwargs['use'] = [m._name for m in module.depends]
self.build_kwargs['source'] = module.files
self.build_kwargs['target'] = module._name
self.build_kwargs['defines'] = []
for k, v in iteritems(module.cc.defines.__dict__):
self.define(k, v)
class CcObjTool(CcTool):
def build(self, module, ctx):
super(CcObjTool, self).build(module, ctx)
ctx.objects(**self.build_kwargs)
class CcAppTool(CcTool):
def build(self, module, ctx):
super(CcAppTool, self).build(module, ctx)
ctx.program(**self.build_kwargs)
class CcLibTool(CcTool):
def build(self, module, ctx):
super(CcLibTool, self).build(module, ctx)
if module.isstatic:
ctx.stlib(**self.build_kwargs)
else:
ctx.shlib(**self.build_kwargs)
tool = Namespace(cc=CcObjTool(), cc_app=CcAppTool(), cc_lib=CcLibTool())
class MyDslLoader(LoaderMixin, myfile.MyFileLoader):
FILENAME = 'Mybuild'
class CcModule(mybuild.core.Module):
tools = [tool.cc]
class ApplicationCcModule(mybuild.core.Module):
tools = [tool.cc_app]
class LibCcModule(mybuild.core.Module):
tools = [tool.cc_lib]
isstatic = True
dsl = Namespace()
dsl.module = CcModule._meta_for_base(option_types=[])
dsl.application = ApplicationCcModule._meta_for_base(option_types=[])
dsl.library = LibCcModule._meta_for_base(option_types=[])
dsl.option = mybuild.core.Optype
dsl.project = None
class PyDslLoader(LoaderMixin, pyfile.PyFileLoader):
FILENAME = 'Pybuild'
dsl = pydsl
| Python | 0 |
5830843f88fc87e8c31f2983413acc16aa0c0711 | remove typo | dv_apps/dataverse_auth/models.py | dv_apps/dataverse_auth/models.py | from django.db import models
from datetime import datetime
from django.utils.encoding import python_2_unicode_compatible
class AuthenticatedUser(models.Model):
useridentifier = models.CharField(unique=True, max_length=255)
affiliation = models.CharField(max_length=255, blank=True, null=True)
email = models.CharField(unique=True, max_length=255)
firstname = models.CharField(max_length=255, blank=True, null=True)
lastname = models.CharField(max_length=255, blank=True, null=True)
createdtime = models.DateTimeField(default=datetime.now)
lastlogintime = models.DateTimeField(blank=True, null=True)
lastapiusetime = models.DateTimeField(blank=True, null=True)
position = models.CharField(max_length=255, blank=True, null=True)
superuser = models.NullBooleanField()
def is_superuser(self):
if not self.superuser:
return False
if self.superuser is True:
return True
return False
def __str__(self):
if self.lastname and self.firstname:
return '%s (%s, %s)' % (self.useridentifier, self.lastname, self.firstname)
elif self.lastname:
return '%s (%s)' % (self.useridentifier, self.lastname)
else:
return self.useridentifier
class Meta:
ordering = ('useridentifier',)
managed = False
db_table = 'authenticateduser'
class ApiToken(models.Model):
authenticateduser = models.ForeignKey('Authenticateduser')
tokenstring = models.CharField(unique=True, max_length=255)
disabled = models.BooleanField()
expiretime = models.DateTimeField()
createtime = models.DateTimeField()
authenticateduser = models.ForeignKey('Authenticateduser')
def __str__(self):
return '%s - %s' % (self.authenticateduser, self.tokenstring)
def is_expired(self):
now = datetime.now()
if now > self.expiretime:
#self.disabled = True
#self.save()
return True
return False
class Meta:
ordering = ('-expiretime', 'authenticateduser')
managed = False
db_table = 'apitoken'
@python_2_unicode_compatible
class BuiltInUser(models.Model):
affiliation = models.CharField(max_length=255, blank=True, null=True)
email = models.CharField(unique=True, max_length=255)
encryptedpassword = models.CharField(max_length=255, blank=True, null=True)
firstname = models.CharField(max_length=255, blank=True, null=True)
lastname = models.CharField(max_length=255, blank=True, null=True)
passwordencryptionversion = models.IntegerField(blank=True, null=True)
position = models.CharField(max_length=255, blank=True, null=True)
username = models.CharField(unique=True, max_length=255)
def __str__(self):
return '%s' % self.username
class Meta:
managed = False
db_table = 'builtinuser'
| from django.db import models
from datetime import datetime
from django.utils.encoding import python_2_unicode_compatible
class AuthenticatedUser(models.Model):
useridentifier = models.CharField(unique=True, max_length=255)
affiliation = models.CharField(max_length=255, blank=True, null=True)
email = models.CharField(unique=True, max_length=255)
firstname = models.CharField(max_length=255, blank=True, null=True)
lastname = models.CharField(max_length=255, blank=True, null=True)
createdtime = models.DateTimeField(default=datetime.now)
lastlogintime = models.DateTimeField(blank=True, null=True)
lastapiusetime = = models.DateTimeField(blank=True, null=True)
position = models.CharField(max_length=255, blank=True, null=True)
superuser = models.NullBooleanField()
def is_superuser(self):
if not self.superuser:
return False
if self.superuser is True:
return True
return False
def __str__(self):
if self.lastname and self.firstname:
return '%s (%s, %s)' % (self.useridentifier, self.lastname, self.firstname)
elif self.lastname:
return '%s (%s)' % (self.useridentifier, self.lastname)
else:
return self.useridentifier
class Meta:
ordering = ('useridentifier',)
managed = False
db_table = 'authenticateduser'
class ApiToken(models.Model):
authenticateduser = models.ForeignKey('Authenticateduser')
tokenstring = models.CharField(unique=True, max_length=255)
disabled = models.BooleanField()
expiretime = models.DateTimeField()
createtime = models.DateTimeField()
authenticateduser = models.ForeignKey('Authenticateduser')
def __str__(self):
return '%s - %s' % (self.authenticateduser, self.tokenstring)
def is_expired(self):
now = datetime.now()
if now > self.expiretime:
#self.disabled = True
#self.save()
return True
return False
class Meta:
ordering = ('-expiretime', 'authenticateduser')
managed = False
db_table = 'apitoken'
@python_2_unicode_compatible
class BuiltInUser(models.Model):
affiliation = models.CharField(max_length=255, blank=True, null=True)
email = models.CharField(unique=True, max_length=255)
encryptedpassword = models.CharField(max_length=255, blank=True, null=True)
firstname = models.CharField(max_length=255, blank=True, null=True)
lastname = models.CharField(max_length=255, blank=True, null=True)
passwordencryptionversion = models.IntegerField(blank=True, null=True)
position = models.CharField(max_length=255, blank=True, null=True)
username = models.CharField(unique=True, max_length=255)
def __str__(self):
return '%s' % self.username
class Meta:
managed = False
db_table = 'builtinuser'
| Python | 0.999999 |
2d26d92956282be3f08cc3dcdb5fa16433822a1b | Change retry_if_fails to _retry_on_fail | Nyaa.py | Nyaa.py | from bs4 import BeautifulSoup
import re
import requests
import sys
def _retry_on_fail(req, *args, **kwargs):
try:
r = req(*args, **kwargs)
if r.status_code not in range(100, 399):
print('Connection error, retrying... (HTTP {})'.format(r.status_code), file=sys.stderr)
return _retry_on_fail(req, *args, **kwargs)
else:
return r
except requests.exceptions.ConnectionError as e:
print('Connection error, retrying... ({})'.format(e.args[0].args[1]), file=sys.stderr)
return _retry_on_fail(req, *args, **kwargs)
class Nyaa(object):
def __init__(self, url):
self.url = url
self.info_url = url + '?page=view&tid='
self.dl_url = url + '?page=download&tid='
@property
def last_entry(self):
r = requests.get(self.url)
if r.status_code not in range(100, 399):
print('Connection error. Nyaa might be down (HTTP {}).'.format(r.status_code), file=sys.stderr)
sys.exit(1)
soup = BeautifulSoup(r.text)
link = soup.find('tr', class_='tlistrow').find('td', class_='tlistname').a['href']
return int(re.search('tid=([0-9]*)', link).group(1))
class NyaaEntry(object):
def __init__(self, nyaa, nyaa_id):
self.info_url = '{}{}'.format(nyaa.info_url, nyaa_id)
self.download_url = '{}{}&magnet=1'.format(nyaa.dl_url, nyaa_id)
r = _retry_on_fail(requests.get, self.info_url)
setattr(r, 'encoding', 'utf-8')
self.page = BeautifulSoup(r.text)
if self.page.find('div', class_='content').text == '\xa0The torrent you are looking for does not appear to be in the database.':
self.exists = False
else:
self.exists = True
@property
def category(self):
return self.page.find('td', class_='viewcategory').find_all('a')[0].text
@property
def sub_category(self):
return self.page.find('td', class_='viewcategory').find_all('a')[1].text
@property
def name(self):
return self.page.find('td', class_='viewtorrentname').text
@property
def time(self):
return self.page.find('td', class_='vtop').text.split(', ')
@property
def status(self):
_status = self.page.find('div', class_=re.compile('content'))['class']
if 'trusted' in _status:
return 'trusted'
elif 'remake' in _status:
return 'remake'
elif 'aplus' in _status:
return 'a+'
else:
return 'normal'
@property
def hash(self):
r = _retry_on_fail(requests.head, self.download_url)
if 'Location' in r.headers:
return re.search(r'magnet:\?xt=urn:btih:(.*)&tr=', r.headers['Location']).group(1).upper()
else:
return None
| from bs4 import BeautifulSoup
import re
import requests
import sys
def retry_if_fails(req, *args, **kwargs):
try:
r = req(*args, **kwargs)
if r.status_code not in range(100, 399):
print('Connection error, retrying... (HTTP {})'.format(r.status_code), file=sys.stderr)
return retry_if_fails(req, *args, **kwargs)
else:
return r
except requests.exceptions.ConnectionError as e:
print('Connection error, retrying... ({})'.format(e.args[0].args[1]), file=sys.stderr)
return retry_if_fails(req, *args, **kwargs)
class Nyaa(object):
def __init__(self, url):
self.url = url
self.info_url = url + '?page=view&tid='
self.dl_url = url + '?page=download&tid='
@property
def last_entry(self):
r = requests.get(self.url)
if r.status_code not in range(100, 399):
print('Connection error. Nyaa might be down (HTTP {}).'.format(r.status_code), file=sys.stderr)
sys.exit(1)
soup = BeautifulSoup(r.text)
link = soup.find('tr', class_='tlistrow').find('td', class_='tlistname').a['href']
return int(re.search('tid=([0-9]*)', link).group(1))
class NyaaEntry(object):
def __init__(self, nyaa, nyaa_id):
self.info_url = '{}{}'.format(nyaa.info_url, nyaa_id)
self.download_url = '{}{}&magnet=1'.format(nyaa.dl_url, nyaa_id)
r = retry_if_fails(requests.get, self.info_url)
setattr(r, 'encoding', 'utf-8')
self.page = BeautifulSoup(r.text)
if self.page.find('div', class_='content').text == '\xa0The torrent you are looking for does not appear to be in the database.':
self.exists = False
else:
self.exists = True
@property
def category(self):
return self.page.find('td', class_='viewcategory').find_all('a')[0].text
@property
def sub_category(self):
return self.page.find('td', class_='viewcategory').find_all('a')[1].text
@property
def name(self):
return self.page.find('td', class_='viewtorrentname').text
@property
def time(self):
return self.page.find('td', class_='vtop').text.split(', ')
@property
def status(self):
_status = self.page.find('div', class_=re.compile('content'))['class']
if 'trusted' in _status:
return 'trusted'
elif 'remake' in _status:
return 'remake'
elif 'aplus' in _status:
return 'a+'
else:
return 'normal'
@property
def hash(self):
r = retry_if_fails(requests.head, self.download_url)
if 'Location' in r.headers:
return re.search(r'magnet:\?xt=urn:btih:(.*)&tr=', r.headers['Location']).group(1).upper()
else:
return None
| Python | 0.00177 |
10ceb00e249635868fb55c1ae1668ddb35b03bc3 | Update demo | demo.py | demo.py | # -*- coding: utf-8 -*-
from taiga import TaigaAPI
from taiga.exceptions import TaigaException
api = TaigaAPI(
host='http://127.0.0.1:8000'
)
api.auth(
username='admin',
password='123123'
)
print (api.me())
new_project = api.projects.create('TEST PROJECT', 'TESTING API')
new_project.name = 'TEST PROJECT 3'
new_project.update()
jan_feb_milestone = new_project.add_milestone(
'New milestone jan feb', '2015-01-26', '2015-02-26'
)
userstory = new_project.add_user_story(
'New Story', description='Blablablabla',
milestone=jan_feb_milestone.id
)
userstory.attach('README.md')
userstory.add_task('New Task 2',
new_project.task_statuses[0].id
).attach('README.md')
print (userstory.list_tasks())
newissue = new_project.add_issue(
'New Issue',
new_project.priorities.get(name='High').id,
new_project.issue_statuses.get(name='New').id,
new_project.issue_types.get(name='Bug').id,
new_project.severities.get(name='Minor').id,
description='Bug #5'
).attach('README.md')
projects = api.projects.list()
print (projects)
stories = api.user_stories.list()
print (stories)
print (api.history.user_story.get(stories[0].id))
try:
projects[0].star()
except TaigaException:
projects[0].like()
api.milestones.list()
projects = api.projects.list()
print (projects)
another_new_project = projects.get(name='TEST PROJECT 3')
print (another_new_project)
users = api.users.list()
print (users)
print (api.search(projects.get(name='TEST PROJECT 3').id, 'New').user_stories[0].subject)
print new_project.add_issue_attribute(
'Device', description='(iPad, iPod, iPhone, Desktop, etc.)'
)
print(new_project.roles)
memberships = new_project.list_memberships()
new_project.add_role('New role', permissions=["add_issue", "modify_issue"])
new_project.add_membership('stagi.andrea@gmail.com', new_project.roles[0].id)
for membership in memberships:
print (membership.role_name)
| # -*- coding: utf-8 -*-
from taiga import TaigaAPI
api = TaigaAPI(
host='http://127.0.0.1:8000'
)
api.auth(
username='admin',
password='123123'
)
print (api.me())
new_project = api.projects.create('TEST PROJECT', 'TESTING API')
new_project.name = 'TEST PROJECT 3'
new_project.update()
jan_feb_milestone = new_project.add_milestone(
'New milestone jan feb', '2015-01-26', '2015-02-26'
)
userstory = new_project.add_user_story(
'New Story', description='Blablablabla',
milestone=jan_feb_milestone.id
)
userstory.attach('README.md')
userstory.add_task('New Task 2',
new_project.task_statuses[0].id
).attach('README.md')
print (userstory.list_tasks())
newissue = new_project.add_issue(
'New Issue',
new_project.priorities.get(name='High').id,
new_project.issue_statuses.get(name='New').id,
new_project.issue_types.get(name='Bug').id,
new_project.severities.get(name='Minor').id,
description='Bug #5'
).attach('README.md')
projects = api.projects.list()
print (projects)
for user in new_project.users:
print (user)
stories = api.user_stories.list()
print (stories)
print (api.history.user_story.get(stories[0].id))
projects[0].star()
api.milestones.list()
projects = api.projects.list()
print (projects)
another_new_project = projects.get(name='TEST PROJECT 3')
print (another_new_project)
users = api.users.list()
print (users)
print (api.search(projects.get(name='TEST PROJECT 3').id, 'New').user_stories[0].subject)
print new_project.add_issue_attribute(
'Device', description='(iPad, iPod, iPhone, Desktop, etc.)'
)
print(new_project.roles)
memberships = new_project.list_memberships()
new_project.add_role('New role', permissions=["add_issue", "modify_issue"])
new_project.add_membership('stagi.andrea@gmail.com', new_project.roles[0].id)
for membership in memberships:
print (membership.role_name)
| Python | 0.000001 |
fc187d9b8822fe446561dc4724c7f123da3d550f | Fix query for auto-adding to board by domain | hasjob/tagging.py | hasjob/tagging.py | # -*- coding: utf-8 -*-
from collections import defaultdict
from urlparse import urljoin
import requests
from flask.ext.rq import job
from coaster.utils import text_blocks
from coaster.nlp import extract_named_entities
from . import app
from .models import (db, JobPost, JobLocation, Board, BoardDomain, BoardLocation,
Tag, JobPostTag, TAG_TYPE)
@job('hasjob')
def tag_locations(jobpost_id):
if app.config.get('HASCORE_SERVER'):
with app.test_request_context():
post = JobPost.query.get(jobpost_id)
url = urljoin(app.config['HASCORE_SERVER'], '/1/geo/parse_locations')
response = requests.get(url, params={'q': post.location, 'bias': ['IN', 'US'], 'special': ['Anywhere', 'Remote', 'Home']}).json()
if response.get('status') == 'ok':
remote_location = False
results = response.get('result', [])
geonames = defaultdict(dict)
tokens = []
for item in results:
if item.get('special'):
remote_location = True
geoname = item.get('geoname', {})
if geoname:
geonames[geoname['geonameid']]['geonameid'] = geoname['geonameid']
geonames[geoname['geonameid']]['primary'] = geonames[geoname['geonameid']].get('primary', True)
for type, related in geoname.get('related', {}).items():
if type in ['admin2', 'admin1', 'country', 'continent']:
geonames[related['geonameid']]['geonameid'] = related['geonameid']
geonames[related['geonameid']]['primary'] = False
tokens.append({'token': item.get('token', ''), 'geoname': {
'name': geoname['name'],
'geonameid': geoname['geonameid'],
}})
else:
tokens.append({'token': item.get('token', '')})
if item.get('special'):
tokens[-1]['remote'] = True
post.remote_location = remote_location
post.parsed_location = {'tokens': tokens}
for locdata in geonames.values():
loc = JobLocation.query.get((jobpost_id, locdata['geonameid']))
if loc is None:
loc = JobLocation(jobpost=post, geonameid=locdata['geonameid'])
db.session.add(loc)
db.session.flush()
loc.primary = locdata['primary']
for location in post.locations:
if location.geonameid not in geonames:
db.session.delete(location)
db.session.commit()
@job('hasjob')
def add_to_boards(jobpost_id):
with app.test_request_context():
post = JobPost.query.options(db.load_only('email_domain'), db.joinedload('locations')).get(jobpost_id)
for board in Board.query.join(BoardDomain).filter(
BoardDomain.domain == post.email_domain).union(
Board.query.join(BoardLocation).filter(BoardLocation.geonameid.in_(post.geonameids))):
board.add(post)
db.session.commit()
def tag_named_entities(post):
entities = extract_named_entities(text_blocks(post.tag_content()))
links = set()
for entity in entities:
tag = Tag.get(entity, create=True)
link = JobPostTag.get(post, tag)
if not link:
link = JobPostTag(jobpost=post, tag=tag, status=TAG_TYPE.AUTO)
post.taglinks.append(link)
links.add(link)
for link in post.taglinks:
if link.status == TAG_TYPE.AUTO and link not in links:
link.status = TAG_TYPE.REMOVED
@job('hasjob')
def tag_jobpost(jobpost_id):
with app.test_request_context():
post = JobPost.query.get(jobpost_id)
tag_named_entities(post)
db.session.commit()
| # -*- coding: utf-8 -*-
from collections import defaultdict
from urlparse import urljoin
import requests
from flask.ext.rq import job
from coaster.utils import text_blocks
from coaster.nlp import extract_named_entities
from . import app
from .models import (db, JobPost, JobLocation, Board, BoardDomain, BoardLocation,
Tag, JobPostTag, TAG_TYPE)
@job('hasjob')
def tag_locations(jobpost_id):
if app.config.get('HASCORE_SERVER'):
with app.test_request_context():
post = JobPost.query.get(jobpost_id)
url = urljoin(app.config['HASCORE_SERVER'], '/1/geo/parse_locations')
response = requests.get(url, params={'q': post.location, 'bias': ['IN', 'US'], 'special': ['Anywhere', 'Remote', 'Home']}).json()
if response.get('status') == 'ok':
remote_location = False
results = response.get('result', [])
geonames = defaultdict(dict)
tokens = []
for item in results:
if item.get('special'):
remote_location = True
geoname = item.get('geoname', {})
if geoname:
geonames[geoname['geonameid']]['geonameid'] = geoname['geonameid']
geonames[geoname['geonameid']]['primary'] = geonames[geoname['geonameid']].get('primary', True)
for type, related in geoname.get('related', {}).items():
if type in ['admin2', 'admin1', 'country', 'continent']:
geonames[related['geonameid']]['geonameid'] = related['geonameid']
geonames[related['geonameid']]['primary'] = False
tokens.append({'token': item.get('token', ''), 'geoname': {
'name': geoname['name'],
'geonameid': geoname['geonameid'],
}})
else:
tokens.append({'token': item.get('token', '')})
if item.get('special'):
tokens[-1]['remote'] = True
post.remote_location = remote_location
post.parsed_location = {'tokens': tokens}
for locdata in geonames.values():
loc = JobLocation.query.get((jobpost_id, locdata['geonameid']))
if loc is None:
loc = JobLocation(jobpost=post, geonameid=locdata['geonameid'])
db.session.add(loc)
db.session.flush()
loc.primary = locdata['primary']
for location in post.locations:
if location.geonameid not in geonames:
db.session.delete(location)
db.session.commit()
@job('hasjob')
def add_to_boards(jobpost_id):
with app.test_request_context():
post = JobPost.query.get(jobpost_id)
for board in Board.query.join(BoardDomain).join(BoardLocation).filter(db.or_(
BoardDomain.domain == post.email_domain,
BoardLocation.geonameid.in_([l.geonameid for l in post.locations])
)):
board.add(post)
db.session.commit()
def tag_named_entities(post):
entities = extract_named_entities(text_blocks(post.tag_content()))
links = set()
for entity in entities:
tag = Tag.get(entity, create=True)
link = JobPostTag.get(post, tag)
if not link:
link = JobPostTag(jobpost=post, tag=tag, status=TAG_TYPE.AUTO)
post.taglinks.append(link)
links.add(link)
for link in post.taglinks:
if link.status == TAG_TYPE.AUTO and link not in links:
link.status = TAG_TYPE.REMOVED
@job('hasjob')
def tag_jobpost(jobpost_id):
with app.test_request_context():
post = JobPost.query.get(jobpost_id)
tag_named_entities(post)
db.session.commit()
| Python | 0.000031 |
7692c4210289af68ad7952ddca89f70d250a26ed | Change base_directory location | great_expectations/data_context/datasource/pandas_source.py | great_expectations/data_context/datasource/pandas_source.py | import pandas as pd
import os
from .datasource import Datasource
from .filesystem_path_generator import FilesystemPathGenerator
from ...dataset.pandas_dataset import PandasDataset
class PandasCSVDatasource(Datasource):
"""
A PandasDataSource makes it easy to create, manage and validate expectations on
Pandas dataframes.
Use with the FilesystemPathGenerator for simple cases.
"""
def __init__(self, name, type_, data_context=None, generators=None, read_csv_kwargs=None):
if generators is None:
generators = {
"default": {"type": "filesystem", "base_directory": "/data"}
}
super(PandasCSVDatasource, self).__init__(name, type_, data_context, generators)
self._datasource_config.update(
{
"read_csv_kwargs": read_csv_kwargs or {}
}
)
self._build_generators()
def _get_generator_class(self, type_):
if type_ == "filesystem":
return FilesystemPathGenerator
else:
raise ValueError("Unrecognized BatchGenerator type %s" % type_)
def _get_data_asset(self, data_asset_name, batch_kwargs, expectations_config):
full_path = os.path.join(batch_kwargs["path"])
df = pd.read_csv(full_path, **self._datasource_config["read_csv_kwargs"])
return PandasDataset(df,
expectations_config=expectations_config,
data_context=self._data_context,
data_asset_name=data_asset_name,
batch_kwargs=batch_kwargs)
| import pandas as pd
import os
from .datasource import Datasource
from .filesystem_path_generator import FilesystemPathGenerator
from ...dataset.pandas_dataset import PandasDataset
class PandasCSVDatasource(Datasource):
"""
A PandasDataSource makes it easy to create, manage and validate expectations on
Pandas dataframes.
Use with the FilesystemPathGenerator for simple cases.
"""
def __init__(self, name, type_, data_context=None, generators=None, base_directory="/data", read_csv_kwargs=None):
self._base_directory = base_directory
if generators is None:
generators = {
"default": {"type": "filesystem", "base_directory": "/data"}
}
super(PandasCSVDatasource, self).__init__(name, type_, data_context, generators)
self._datasource_config.update(
{
"base_directory": base_directory,
"read_csv_kwargs": read_csv_kwargs or {}
}
)
self._build_generators()
def _get_generator_class(self, type_):
if type_ == "filesystem":
return FilesystemPathGenerator
else:
raise ValueError("Unrecognized BatchGenerator type %s" % type_)
def _get_data_asset(self, data_asset_name, batch_kwargs, expectations_config):
full_path = os.path.join(batch_kwargs["path"])
df = pd.read_csv(full_path, **self._datasource_config["read_csv_kwargs"])
return PandasDataset(df,
expectations_config=expectations_config,
data_context=self._data_context,
data_asset_name=data_asset_name,
batch_kwargs=batch_kwargs)
| Python | 0.000002 |
b69289c62a5be3a523b4d32aec2b6d790dc95f0d | Add compare functions | amit.py | amit.py | import hashlib, ssdeep
def hash_ssdeep(inbytes):
return ssdeep.hash(inbytes)
def hash_md5(inbytes):
m = hashlib.md5()
m.update(inbytes)
return m.hexdigest()
def hash_sha1(inbytes):
m = hashlib.sha1()
m.update(inbytes)
return m.hexdigest()
def hash_sha256(inbytes):
m = hashlib.sha256()
m.update(inbytes)
return m.hexdigest()
def hash_all(inbytes):
a = []
a.append(hash_ssdeep(inbytes))
a.append(hash_md5(inbytes))
a.append(hash_sha1(inbytes))
a.append(hash_sha256(inbytes))
return a
def compare_ssdeep(hash1, hash2):
return ssdeep.compare(hash1, hash2)
def compare_md5(hash1, hash2):
return hash1 == hash2
def compare_sha1(hash2, hash1):
return hash1 == hash2
def compare_sha256(hash1, hash2):
return hash1 == hash2
def compare_all(hasharray1, hasharray2):
if len(hasharray1)!=len(hasharray2): return None
a = []
a.append(compare_ssdeep(hasharray1[0], hasharray2[0]))
a.append(compare_md5(hasharray1[1], hasharray2[1]))
a.append(compare_sha1(hasharray1[2], hasharray2[2]))
a.append(compare_sha256(hasharray1[3], hasharray2[3]))
return a
testdata = '\x90'*512*2
testdata2 = 'mod'+'\x90'*512*2
a1 = hash_all(testdata)
a2 = hash_all(testdata2)
for i in a1: print i
for i in a2: print i
print compare_all(a1, a2)
| import hashlib, ssdeep
def hash_ssdeep(inbytes):
return ssdeep.hash(inbytes)
def hash_md5(inbytes):
m = hashlib.md5()
m.update(inbytes)
return m.hexdigest()
def hash_sha1(inbytes):
m = hashlib.sha1()
m.update(inbytes)
return m.hexdigest()
def hash_sha256(inbytes):
m = hashlib.sha256()
m.update(inbytes)
return m.hexdigest()
def hash_print_all(inbytes):
print hash_ssdeep(inbytes)
print hash_md5(inbytes)
print hash_sha1(inbytes)
print hash_sha256(inbytes)
testdata = '\x90'*512*2
testdata2 = 'mod\x90'*512*2
hash_print_all(testdata)
hash_print_all(testdata2)
| Python | 0.000001 |
37c63790bd5fef64823ada0d40b6a1e18607c567 | Task for finding ROI | dodo.py | dodo.py | """PyDoIt file for automating tasks."""
import glob
#from doit.tools import Interactive
from doit.tools import create_folder
#from doit.tools import result_dep
DOIT_CONFIG = {
'default_tasks': [],
'verbosity': 2,
}
DWILIB = '~/src/dwilib'
PMAP = DWILIB+'/pmap.py'
ANON = DWILIB+'/anonymize_dicom.py'
FIND_ROI = DWILIB+'/find_roi.py'
COMPARE_MASKS = DWILIB+'/compare_masks.py'
MODELS = 'Si SiN Mono MonoN Kurt KurtN'.split()
# Common functions
def read_subwindows(filename):
r = {}
with open(filename, 'rb') as f:
for line in f.xreadlines():
line = line.strip()
if line.startswith('#'):
continue
words = line.split()
if len(words) != 8:
raise Exception('Cannot parse subwindow: %s.' % line)
case, scan, subwindow = int(words[0]), words[1], map(int, words[2:])
r[(case, scan)] = subwindow
return r
def fit_cmd(model, subwindow, infiles, outfile):
d = dict(prg=PMAP,
m=model,
sw=' '.join(map(str, subwindow)),
i=' '.join(infiles),
o=outfile,
)
s = '{prg} -m {m} -s {sw} -d {i} -o {o}'.format(**d)
return s
# Tasks
#def task_fit():
# """Fit models to imaging data."""
# for case, scan in SUBWINDOWS.keys():
# subwindow = SUBWINDOWS[(case, scan)]
# outdir = 'pmaps'
# d = dict(c=case, s=scan, od=outdir)
# infiles = sorted(glob.glob('dicoms/{c}_*_hB_{s}/DICOM/*'.format(**d)))
# if len(infiles) == 0:
# continue
# for model in MODELS:
# d['m'] = model
# outfile = '{od}/pmap_{c}_{s}_{m}.txt'.format(**d)
# cmd = fit_cmd(model, subwindow, infiles, outfile)
# yield {
# 'name': '{c}_{s}_{m}'.format(**d),
# 'actions': [(create_folder, [outdir]),
# cmd],
# 'file_dep': infiles,
# 'targets': [outfile],
# 'clean': True,
# }
def task_anonymize():
"""Anonymize imaging data."""
files = glob.glob('dicoms/*/DICOMDIR') + glob.glob('dicoms/*/DICOM/*')
files.sort()
for f in files:
cmd = '{prg} -v -i {f}'.format(prg=ANON, f=f)
yield {
'name': f,
'actions': [cmd],
'file_dep': [f],
}
def task_find_rois():
"""Find ROIs."""
for case, scan in SUBWINDOWS.keys():
subwindow = SUBWINDOWS[(case, scan)]
outdir = 'masks_auto'
d = dict(c=case, s=scan, od=outdir)
infile = 'pmaps/pmap_{c}_{s}_MonoN.txt'.format(**d)
outfile = '{od}/{c}_{s}_auto.mask'.format(**d)
cmd = '{prg} -i {i} -o {o}'.format(prg=FIND_ROI, i=infile, o=outfile)
yield {
'name': '{c}_{s}'.format(**d),
'actions': [(create_folder, [outdir]),
cmd],
'file_dep': [infile],
'targets': [outfile],
'clean': True,
}
SUBWINDOWS = read_subwindows('subwindows.txt')
| """PyDoIt file for automating tasks."""
import glob
#from doit.tools import Interactive
from doit.tools import create_folder
#from doit.tools import result_dep
DOIT_CONFIG = {
'default_tasks': [],
'verbosity': 2,
}
DWILIB = '~/src/dwilib'
PMAP = DWILIB+'/pmap.py'
ANON = DWILIB+'/anonymize_dicom.py'
MODELS = 'Si SiN Mono MonoN Kurt KurtN'.split()
# Common functions
def read_subwindows(filename):
r = {}
with open(filename, 'rb') as f:
for line in f.xreadlines():
line = line.strip()
if line.startswith('#'):
continue
words = line.split()
if len(words) != 8:
raise Exception('Cannot parse subwindow: %s.' % line)
case, scan, subwindow = int(words[0]), words[1], map(int, words[2:])
r[(case, scan)] = subwindow
return r
def fit_cmd(model, subwindow, infiles, outfile):
d = dict(prg=PMAP,
m=model,
sw=' '.join(map(str, subwindow)),
i=' '.join(infiles),
o=outfile,
)
s = '{prg} -m {m} -s {sw} -d {i} -o {o}'.format(**d)
return s
# Tasks
def task_fit():
"""Fit models to imaging data."""
for case, scan in SUBWINDOWS.keys():
subwindow = SUBWINDOWS[(case, scan)]
outdir = 'pmaps'
d = dict(c=case, s=scan, od=outdir)
infiles = sorted(glob.glob('dicoms/{c}_*_hB_{s}/DICOM/*'.format(**d)))
if len(infiles) == 0:
continue
for model in MODELS:
d['m'] = model
outfile = '{od}/pmap_{c}_{s}_{m}.txt'.format(**d)
cmd = fit_cmd(model, subwindow, infiles, outfile)
yield {
'name': '{c}_{s}_{m}'.format(**d),
'actions': [(create_folder, [outdir]),
cmd],
'file_dep': infiles,
'targets': [outfile],
'clean': True,
}
def task_anonymize():
"""Anonymize imaging data."""
files = glob.glob('dicoms/*/DICOMDIR') + glob.glob('dicoms/*/DICOM/*')
files.sort()
for f in files:
cmd = '{prg} -v -i {f}'.format(prg=ANON, f=f)
yield {
'name': f,
'actions': [cmd],
'file_dep': [f],
}
SUBWINDOWS = read_subwindows('subwindows.txt')
| Python | 0.999833 |
d5e41dfaff393a0649336ef92d7b7917a7e0122d | fix allowed_hosts settings bug | hours/settings.py | hours/settings.py | # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECRET_KEY will be automatically generated and saved into local_settings.py on first import, if not already
# present
SECRET_KEY = ''
DEBUG = False
ALLOWED_HOSTS = [
'localhost'
]
TEMPLATE_DEBUG = True
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sources',
'core',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'hours.urls'
WSGI_APPLICATION = 'hours.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
from hours_settings import *
try:
from local_settings import *
except ImportError:
pass
if SECRET_KEY == '':
print 'Creating SECRET_KEY..'
from django.utils.crypto import get_random_string
settings_dir = os.path.dirname(__file__)
with open(os.path.join(settings_dir, 'local_settings.py'), 'a') as local_settings_fd:
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
SECRET_KEY = get_random_string(50, chars)
local_settings_fd.write('\n%s\n' % "SECRET_KEY = '%s'" % SECRET_KEY)
| # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECRET_KEY will be automatically generated and saved into local_settings.py on first import, if not already
# present
SECRET_KEY = ''
DEBUG = False
ALLOWED_HOSTS = [
'localhost'
]
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sources',
'core',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'hours.urls'
WSGI_APPLICATION = 'hours.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
from hours_settings import *
try:
from local_settings import *
except ImportError:
pass
if SECRET_KEY == '':
print 'Creating SECRET_KEY..'
from django.utils.crypto import get_random_string
settings_dir = os.path.dirname(__file__)
with open(os.path.join(settings_dir, 'local_settings.py'), 'a') as local_settings_fd:
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
SECRET_KEY = get_random_string(50, chars)
local_settings_fd.write('\n%s\n' % "SECRET_KEY = '%s'" % SECRET_KEY)
| Python | 0.000001 |
5a38e5924409e887430ee4366c81ebc2b94152a5 | add trackers registration | plenum/server/database_manager.py | plenum/server/database_manager.py | from typing import Dict, Optional
from common.exceptions import LogicError
from plenum.common.constants import BLS_LABEL, TS_LABEL, IDR_CACHE_LABEL, ATTRIB_LABEL
from plenum.common.ledger import Ledger
from state.state import State
class DatabaseManager():
def __init__(self):
self.databases = {} # type: Dict[int, Database]
self.stores = {}
self.trackers = {}
self._init_db_list()
def _init_db_list(self):
self._ledgers = {lid: db.ledger for lid, db in self.databases.items()}
self._states = {lid: db.state for lid, db in self.databases.items() if db.state}
def register_new_database(self, lid, ledger: Ledger, state: Optional[State] = None):
if lid in self.databases:
raise LogicError('Trying to add already existing database')
self.databases[lid] = Database(ledger, state)
self._init_db_list()
def get_database(self, lid):
if lid not in self.databases:
return None
return self.databases[lid]
def get_ledger(self, lid):
if lid not in self.databases:
return None
return self.databases[lid].ledger
def get_state(self, lid):
if lid not in self.databases:
return None
return self.databases[lid].state
def get_tracker(self, lid):
if lid not in self.trackers:
return None
return self.trackers[lid]
def register_new_store(self, label, store):
if label in self.stores:
raise LogicError('Trying to add already existing store')
self.stores[label] = store
def register_new_tracker(self, lid, tracker):
if lid in self.trackers:
raise LogicError("Trying to add already existing tracker")
self.trackers[lid] = tracker
def get_store(self, label):
if label not in self.stores:
return None
return self.stores[label]
@property
def states(self):
return self._states
@property
def ledgers(self):
return self._ledgers
@property
def bls_store(self):
return self.get_store(BLS_LABEL)
@property
def ts_store(self):
return self.get_store(TS_LABEL)
@property
def idr_cache(self):
return self.get_store(IDR_CACHE_LABEL)
@property
def attribute_store(self):
return self.get_store(ATTRIB_LABEL)
# ToDo: implement it and use on close all KV stores
def close(self):
# Close all states
for state in self.states.values():
state.close()
# Close all stores
for store in self.stores.values():
store.close()
class Database:
def __init__(self, ledger, state):
self.ledger = ledger
self.state = state
def reset(self):
self.ledger.reset_uncommitted()
if self.state:
self.state.revertToHead(self.state.committedHeadHash)
| from typing import Dict, Optional
from common.exceptions import LogicError
from plenum.common.constants import BLS_LABEL, TS_LABEL, IDR_CACHE_LABEL, ATTRIB_LABEL
from plenum.common.ledger import Ledger
from state.state import State
class DatabaseManager():
def __init__(self):
self.databases = {} # type: Dict[int, Database]
self.stores = {}
self._init_db_list()
def _init_db_list(self):
self._ledgers = {lid: db.ledger for lid, db in self.databases.items()}
self._states = {lid: db.state for lid, db in self.databases.items() if db.state}
def register_new_database(self, lid, ledger: Ledger, state: Optional[State] = None):
if lid in self.databases:
raise LogicError('Trying to add already existing database')
self.databases[lid] = Database(ledger, state)
self._init_db_list()
def get_database(self, lid):
if lid not in self.databases:
return None
return self.databases[lid]
def get_ledger(self, lid):
if lid not in self.databases:
return None
return self.databases[lid].ledger
def get_state(self, lid):
if lid not in self.databases:
return None
return self.databases[lid].state
def register_new_store(self, label, store):
if label in self.stores:
raise LogicError('Trying to add already existing store')
self.stores[label] = store
def get_store(self, label):
if label not in self.stores:
return None
return self.stores[label]
@property
def states(self):
return self._states
@property
def ledgers(self):
return self._ledgers
@property
def bls_store(self):
return self.get_store(BLS_LABEL)
@property
def ts_store(self):
return self.get_store(TS_LABEL)
@property
def idr_cache(self):
return self.get_store(IDR_CACHE_LABEL)
@property
def attribute_store(self):
return self.get_store(ATTRIB_LABEL)
# ToDo: implement it and use on close all KV stores
def close(self):
# Close all states
for state in self.states.values():
state.close()
# Close all stores
for store in self.stores.values():
store.close()
class Database:
def __init__(self, ledger, state):
self.ledger = ledger
self.state = state
def reset(self):
self.ledger.reset_uncommitted()
if self.state:
self.state.revertToHead(self.state.committedHeadHash)
| Python | 0 |
8c4590e19c7b39fe6562671f7d63651e736ffa49 | debug print | controllers/admin/admin_migration_controller.py | controllers/admin/admin_migration_controller.py | import os
from google.appengine.ext import ndb
from google.appengine.ext import deferred
from google.appengine.ext.webapp import template
from controllers.base_controller import LoggedInHandler
from models.event import Event
from helpers.match_manipulator import MatchManipulator
def add_year(event_key):
logging.info(event_key)
matches = event_key.get().matches
if matches:
for match in matches:
match.year = int(match.event.id()[:4])
match.dirty = True
MatchManipulator.createOrUpdate(match)
class AdminMigration(LoggedInHandler):
def get(self):
self._require_admin()
path = os.path.join(os.path.dirname(__file__), '../../templates/admin/migration.html')
self.response.out.write(template.render(path, self.template_values))
class AdminMigrationAddMatchYear(LoggedInHandler):
def get(self):
self._require_admin()
for year in range(1992, 2016):
event_keys = Event.query(Event.year == year).fetch(keys_only=True)
for event_key in event_keys:
deferred.defer(add_year, event_key, _queue="admin")
self.response.out.write(event_keys)
| import os
from google.appengine.ext import ndb
from google.appengine.ext import deferred
from google.appengine.ext.webapp import template
from controllers.base_controller import LoggedInHandler
from models.event import Event
from helpers.match_manipulator import MatchManipulator
def add_year(event_key):
matches = event_key.get().matches
if matches:
for match in matches:
match.year = int(match.event.id()[:4])
match.dirty = True
MatchManipulator.createOrUpdate(match)
class AdminMigration(LoggedInHandler):
def get(self):
self._require_admin()
path = os.path.join(os.path.dirname(__file__), '../../templates/admin/migration.html')
self.response.out.write(template.render(path, self.template_values))
class AdminMigrationAddMatchYear(LoggedInHandler):
def get(self):
self._require_admin()
for year in range(1992, 2016):
event_keys = Event.query(Event.year == year).fetch(keys_only=True)
for event_key in event_keys:
deferred.defer(add_year, event_key, _queue="admin")
self.response.out.write(event_keys)
| Python | 0.000003 |
895dfda101665e0f70e96d549443f9fe777de1e7 | Add support for multiple urls per method, auto create method routers | hug/decorators.py | hug/decorators.py | from functools import wraps, partial
from collections import OrderedDict
import sys
from hug.run import server
import hug.output_format
from falcon import HTTP_METHODS, HTTP_BAD_REQUEST
def call(urls, accept=HTTP_METHODS, output=hug.output_format.json, example=None):
if isinstance(urls, str):
urls = (urls, )
def decorator(api_function):
module = sys.modules[api_function.__module__]
def interface(request, response):
input_parameters = request.params
errors = {}
for key, type_handler in api_function.__annotations__.items():
try:
input_parameters[key] = type_handler(input_parameters[key])
except Exception as error:
errors[key] = str(error)
if errors:
response.data = output({"errors": errors})
response.status = HTTP_BAD_REQUEST
return
input_parameters['request'], input_parameters['response'] = (request, response)
response.data = output(api_function(**input_parameters))
if not 'HUG' in module.__dict__:
def api_auto_instantiate(*kargs, **kwargs):
module.HUG = server(module)
return module.HUG(*kargs, **kwargs)
module.HUG = api_auto_instantiate
module.HUG_API_CALLS = OrderedDict()
for url in urls:
handlers = module.HUG_API_CALLS.setdefault(url, {})
for method in accept:
handlers["on_{0}".format(method.lower())] = interface
api_function.interface = interface
interface.api_function = api_function
interface.output_format = output
interface.example = example
return api_function
return decorator
for method in HTTP_METHODS:
globals()[method.lower()] = partial(call, accept=(method, ))
| from functools import wraps
from collections import OrderedDict
import sys
from hug.run import server
import hug.output_format
from falcon import HTTP_METHODS, HTTP_BAD_REQUEST
def call(url, accept=HTTP_METHODS, output=hug.output_format.json):
def decorator(api_function):
module = sys.modules[api_function.__module__]
def interface(request, response):
input_parameters = request.params
errors = {}
for key, type_handler in api_function.__annotations__.items():
try:
input_parameters[key] = type_handler(input_parameters[key])
except Exception as error:
errors[key] = str(error)
if errors:
response.data = output({"errors": errors})
response.status = HTTP_BAD_REQUEST
return
input_parameters['request'], input_parameters['response'] = (request, response)
response.data = output(api_function(**input_parameters))
if not 'HUG' in module.__dict__:
def api_auto_instantiate(*kargs, **kwargs):
module.HUG = server(module)
return module.HUG(*kargs, **kwargs)
module.HUG = api_auto_instantiate
module.HUG_API_CALLS = OrderedDict()
for method in accept:
module.HUG_API_CALLS.setdefault(url, {})["on_{0}".format(method.lower())] = interface
api_function.interface = interface
interface.api_function = api_function
return api_function
return decorator
def get(url):
return call(url=url, accept=('GET', ))
def post(url):
return call(url=url, accept=('POST', ))
def put(url):
return call(url=url, acccept=('PUT', ))
def delete(url):
return call(url=url, accept=('DELETE', ))
| Python | 0 |
66dd418d481bfc5d3d910823856bdcea8d304a87 | allow to pass a different root-path | hwaf-cmtcompat.py | hwaf-cmtcompat.py | # -*- python -*-
# stdlib imports
import os
import os.path as osp
import sys
# waf imports ---
import waflib.Options
import waflib.Utils
import waflib.Logs as msg
from waflib.Configure import conf
_heptooldir = osp.dirname(osp.abspath(__file__))
# add this directory to sys.path to ease the loading of other hepwaf tools
if not _heptooldir in sys.path: sys.path.append(_heptooldir)
### ---------------------------------------------------------------------------
@conf
def _cmt_get_srcs_lst(self, source, root=None):
'''hack to support implicit src/*cxx in CMT req-files'''
if root is None:
root = self.root
if isinstance(source, (list, tuple)):
src = []
for s in source:
src.extend(self._cmt_get_srcs_lst(s, root))
return src
elif not isinstance(source, type('')):
## a waflib.Node ?
return [source]
else:
src_node = root.find_dir('src')
srcs = root.ant_glob(source)
if srcs:
# OK. finders, keepers.
pass
elif src_node:
# hack to mimick CMT's default (to take sources from src)
srcs = src_node.ant_glob(source)
pass
if not srcs:
# ok, try again from bldnode
src_node = root.find_dir('src')
srcs = root.get_bld().ant_glob(source)
if srcs:
# OK. finders, keepers.
pass
elif src_node:
# hack to mimick CMT's default (to take sources from src)
srcs = src_node.get_bld().ant_glob(source)
pass
if not srcs:
# ok, maybe the output of a not-yet executed task
srcs = source
pass
pass
return waflib.Utils.to_list(srcs)
self.fatal("unreachable")
return []
| # -*- python -*-
# stdlib imports
import os
import os.path as osp
import sys
# waf imports ---
import waflib.Options
import waflib.Utils
import waflib.Logs as msg
from waflib.Configure import conf
_heptooldir = osp.dirname(osp.abspath(__file__))
# add this directory to sys.path to ease the loading of other hepwaf tools
if not _heptooldir in sys.path: sys.path.append(_heptooldir)
### ---------------------------------------------------------------------------
@conf
def _cmt_get_srcs_lst(self, source):
'''hack to support implicit src/*cxx in CMT req-files'''
if isinstance(source, (list, tuple)):
src = []
for s in source:
src.extend(self._cmt_get_srcs_lst(s))
return src
elif not isinstance(source, type('')):
## a waflib.Node ?
return [source]
else:
src_node = self.path.find_dir('src')
srcs = self.path.ant_glob(source)
if srcs:
# OK. finders, keepers.
pass
elif src_node:
# hack to mimick CMT's default (to take sources from src)
srcs = src_node.ant_glob(source)
pass
if not srcs:
# ok, try again from bldnode
src_node = self.path.find_dir('src')
srcs = self.path.get_bld().ant_glob(source)
if srcs:
# OK. finders, keepers.
pass
elif src_node:
# hack to mimick CMT's default (to take sources from src)
srcs = src_node.get_bld().ant_glob(source)
pass
if not srcs:
# ok, maybe the output of a not-yet executed task
srcs = source
pass
pass
return waflib.Utils.to_list(srcs)
self.fatal("unreachable")
return []
| Python | 0.000002 |
70ea214d8e258e4e7c95b9ba7948dde13e28a878 | Make screengrab_torture_test test more functions | desktopmagic/scripts/screengrab_torture_test.py | desktopmagic/scripts/screengrab_torture_test.py | from desktopmagic.screengrab_win32 import GrabFailed, getScreenAsImage, getDisplaysAsImages, getRectAsImage
def main():
print """\
This program helps you test whether screengrab_win32 has memory leaks
and other problems. It takes a screenshot repeatedly and discards it.
Open Task Manager and make sure Physical Memory % is not ballooning.
Memory leaks might not be blamed on the python process itself (which
will show low memory usage).
Lock the workstation for a few minutes; make sure there are no leaks
and that there are no uncaught exceptions here.
Repeat above after RDPing into the workstation and minimizing RDP;
this is like disconnecting the monitor.
Change your color depth settings. Add and remove monitors. RDP
into at 256 colors.
"""
while True:
try:
getScreenAsImage()
print "S",
except GrabFailed, e:
print e
try:
getDisplaysAsImages()
print "D",
except GrabFailed, e:
print e
try:
getRectAsImage((0, 0, 1, 1))
print "R",
except GrabFailed, e:
print e
if __name__ == '__main__':
main()
| from desktopmagic.screengrab_win32 import GrabFailed, getScreenAsImage
def main():
print """\
This program helps you test whether screengrab_win32 has memory leaks
and other problems. It takes a screenshot repeatedly and discards it.
Open Task Manager and make sure Physical Memory % is not ballooning.
Memory leaks might not be blamed on the python process itself (which
will show low memory usage).
Lock the workstation for a few minutes; make sure there are no leaks
and that there are no uncaught exceptions here.
Repeat above after RDPing into the workstation and minimizing RDP;
this is like disconnecting the monitor.
Change your color depth settings. Add and remove monitors. RDP
into at 256 colors.
"""
while True:
try:
getScreenAsImage()
print ".",
except GrabFailed, e:
print e
if __name__ == '__main__':
main()
| Python | 0.000007 |
9d1dc9c2c649bd117c2cd38cf664e34820f387ea | update docstring in fwhm.py | fwhm.py | fwhm.py | import numpy as np
def fwhm(x,y, silence = False):
maxVal = np.max(y)
maxVal50 = 0.5*maxVal
if not silence:
print "Max: " + str(maxVal)
#this is to detect if there are multiple values
biggerCondition = [a > maxVal50 for a in y]
changePoints = []
freqPoints = []
for k in range(len(biggerCondition)-1):
if biggerCondition[k+1] != biggerCondition[k]:
changePoints.append(k)
if len(changePoints) > 2:
if not silence:
print "WARNING: THE FWHM IS LIKELY TO GIVE INCORRECT VALUES"
#interpolate between points.
print "ChangePoints: ", changePoints
for k in changePoints:
# do a polyfit
# with the points before and after the point where the change occurs.
# note that here we are fitting the x values as a function of the y values.
# then we can use the polynom to compute the value of x at the threshold, i.e. at maxVal50.
yPolyFit = x[k-1:k+2]
xPolyFit = y[k-1:k+2]
z = np.polyfit(xPolyFit,yPolyFit,2)
p = np.poly1d(z)
print p
freq = p(maxVal50)
freqPoints.append(freq)
if len(freqPoints) == 2:
value = freqPoints[1] - freqPoints[0]
else:
value = None
print sorted(freqPoints)
return value
def main():
x = np.linspace(-10,10,100)
sigma = 2
y = 3.1*np.exp(-x**2/(2*sigma**2))
print "OK"
fwhmVal = fwhm(x,y)
print "FWHM: " + str(fwhmVal)
print str(2*np.sqrt(2*np.log(2))*2)
if __name__ == "__main__":
main()
| import numpy as np
def fwhm(x,y, silence = False):
maxVal = np.max(y)
maxVal50 = 0.5*maxVal
if not silence:
print "Max: " + str(maxVal)
#this is to detect if there are multiple values
biggerCondition = [a > maxVal50 for a in y]
changePoints = []
freqPoints = []
for k in range(len(biggerCondition)-1):
if biggerCondition[k+1] != biggerCondition[k]:
changePoints.append(k)
if len(changePoints) > 2:
if not silence:
print "WARNING: THE FWHM IS LIKELY TO GIVE INCORRECT VALUES"
#interpolate between points.
print "ChangePoints: ", changePoints
for k in changePoints:
# do a polyfit
# with the points before and after the point where the change occurs.
# note that here we are fitting the frequency as a function of the return loss.
# then we can use the polynom to compute the frequency at returnloss = threshold.
yPolyFit = x[k-1:k+2]
xPolyFit = y[k-1:k+2]
z = np.polyfit(xPolyFit,yPolyFit,2)
p = np.poly1d(z)
print p
freq = p(maxVal50)
freqPoints.append(freq)
if len(freqPoints) == 2:
value = freqPoints[1] - freqPoints[0]
else:
value = None
print sorted(freqPoints)
return value
def main():
x = np.linspace(-10,10,100)
sigma = 2
y = 3.1*np.exp(-x**2/(2*sigma**2))
print "OK"
fwhmVal = fwhm(x,y)
print "FWHM: " + str(fwhmVal)
print str(2*np.sqrt(2*np.log(2))*2)
if __name__ == "__main__":
main()
| Python | 0 |
161a1cdddd79df7126d6adf1117d51e679d1746c | Change --command option in "docker" to a positional argument | dodo_commands/extra/standard_commands/docker.py | dodo_commands/extra/standard_commands/docker.py | """This command opens a bash shell in the docker container."""
from . import DodoCommand
class Command(DodoCommand): # noqa
decorators = ["docker", ]
def add_arguments_imp(self, parser): # noqa
parser.add_argument('command', nargs='?')
def handle_imp(self, command, **kwargs): # noqa
self.runcmd(
["/bin/bash"] + (["-c", command] if command else []),
cwd=self.get_config("/DOCKER/default_cwd", None))
| """This command opens a bash shell in the docker container."""
from . import DodoCommand
class Command(DodoCommand): # noqa
decorators = ["docker", ]
def add_arguments_imp(self, parser): # noqa
parser.add_argument('--command', default="")
def handle_imp(self, command, **kwargs): # noqa
self.runcmd(
["/bin/bash"] + (["-c", command] if command else []),
cwd=self.get_config("/DOCKER/default_cwd", None))
| Python | 0.000001 |
36063d227f7cd3ededdc99b23b0c7911f2233df2 | Add available params in metering labels client's comment | tempest/lib/services/network/metering_labels_client.py | tempest/lib/services/network/metering_labels_client.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.lib.services.network import base
class MeteringLabelsClient(base.BaseNetworkClient):
def create_metering_label(self, **kwargs):
"""Creates an L3 metering label.
Available params: see http://developer.openstack.org/
api-ref-networking-v2-ext.html#
createMeteringLabel
"""
uri = '/metering/metering-labels'
post_data = {'metering_label': kwargs}
return self.create_resource(uri, post_data)
def show_metering_label(self, metering_label_id, **fields):
"""Shows details for a metering label.
Available params: see http://developer.openstack.org/
api-ref-networking-v2-ext.html#showMeteringLabel
"""
uri = '/metering/metering-labels/%s' % metering_label_id
return self.show_resource(uri, **fields)
def delete_metering_label(self, metering_label_id):
"""Deletes an L3 metering label.
Available params: see http://developer.openstack.org/
api-ref-networking-v2-ext.html#
deleteMeteringLabel
"""
uri = '/metering/metering-labels/%s' % metering_label_id
return self.delete_resource(uri)
def list_metering_labels(self, **filters):
"""Lists all L3 metering labels that belong to the tenant.
Available params: see http://developer.openstack.org/
api-ref-networking-v2-ext.html#
listMeteringLabels
"""
uri = '/metering/metering-labels'
return self.list_resources(uri, **filters)
| # 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 tempest.lib.services.network import base
class MeteringLabelsClient(base.BaseNetworkClient):
def create_metering_label(self, **kwargs):
uri = '/metering/metering-labels'
post_data = {'metering_label': kwargs}
return self.create_resource(uri, post_data)
def show_metering_label(self, metering_label_id, **fields):
uri = '/metering/metering-labels/%s' % metering_label_id
return self.show_resource(uri, **fields)
def delete_metering_label(self, metering_label_id):
uri = '/metering/metering-labels/%s' % metering_label_id
return self.delete_resource(uri)
def list_metering_labels(self, **filters):
uri = '/metering/metering-labels'
return self.list_resources(uri, **filters)
| Python | 0.000016 |
93870690f17a4baddeb33549a1f6c67eeee1abe0 | Increase cache tile duration from 6 hours to 1 week | src/adhocracy/lib/tiles/util.py | src/adhocracy/lib/tiles/util.py | import logging
from time import time
from pylons import tmpl_context as c
from adhocracy import config
from adhocracy.lib.cache import memoize
log = logging.getLogger(__name__)
class BaseTile(object):
'''
Base class for tiles
'''
def render_tile(template_name, def_name, tile, cached=False, **kwargs):
from adhocracy.lib import templating
begin_time = time()
def render():
return templating.render_def(template_name, def_name,
tile=tile, **kwargs)
rendered = ""
if cached and config.get_bool('adhocracy.cache_tiles'):
@memoize('tile_cache' + template_name + def_name, 7 * 86400)
def _cached(**kwargs):
return render()
rendered = _cached(locale=c.locale, **kwargs)
else:
rendered = render()
if False:
log.debug("Rendering tile %s:%s took %sms" % (
template_name, def_name, (time() - begin_time) * 1000))
return rendered
| import logging
from time import time
from pylons import tmpl_context as c
from adhocracy import config
from adhocracy.lib.cache import memoize
log = logging.getLogger(__name__)
class BaseTile(object):
'''
Base class for tiles
'''
def render_tile(template_name, def_name, tile, cached=False, **kwargs):
from adhocracy.lib import templating
begin_time = time()
def render():
return templating.render_def(template_name, def_name,
tile=tile, **kwargs)
rendered = ""
if cached and config.get_bool('adhocracy.cache_tiles'):
@memoize('tile_cache' + template_name + def_name, 86400 / 4)
def _cached(**kwargs):
return render()
rendered = _cached(locale=c.locale, **kwargs)
else:
rendered = render()
if False:
log.debug("Rendering tile %s:%s took %sms" % (
template_name, def_name, (time() - begin_time) * 1000))
return rendered
| Python | 0 |
d5691c8031a32e0cfadc74e9fffad8a9e04bc63c | enable search navbar entry in production | portal/base/context_processors.py | portal/base/context_processors.py | from django.conf import settings
def search_disabled(request):
"""Facility for disabling search functionality.
This may be used in the future to automatically disable search if the search
backend goes down.
"""
return dict(SEARCH_DISABLED=False)
# return dict(SEARCH_DISABLED=not settings.DEBUG)
| from django.conf import settings
def search_disabled(request):
"""Facility for disabling search functionality.
This may be used in the future to automatically disable search if the search
backend goes down.
"""
return dict(SEARCH_DISABLED=not settings.DEBUG)
| Python | 0 |
87b9910a30cb915f5b99a17b0b49570b0027e665 | load help module | gbot.py | gbot.py | #!/usr/bin/env python
# =============================================================================
# file = gbot.py
# description = IRC bot
# author = GR <https://github.com/shortdudey123>
# create_date = 2014-07-09
# mod_date = 2014-07-09
# version = 0.1
# usage = called as a class
# notes =
# python_ver = 2.7.6
# =============================================================================
import src.bot as bot
__IDENTIFY__ = ''
if __name__ == "__main__":
gbot = bot.IRCBot(server="chat.freenode.com", nick="grbot", port=6667, realName='gbot', identify=__IDENTIFY__, debug=True, connectDelay=4, identVerifyCall='ACC')
gbot.setDefaultChannels({'##gbot': ''})
gbot.addAdmin("shortdudey123")
gbot.loadModules(['opme', 'coreVersion', 'moduleInfo', 'help'])
gbot.run() | #!/usr/bin/env python
# =============================================================================
# file = gbot.py
# description = IRC bot
# author = GR <https://github.com/shortdudey123>
# create_date = 2014-07-09
# mod_date = 2014-07-09
# version = 0.1
# usage = called as a class
# notes =
# python_ver = 2.7.6
# =============================================================================
import src.bot as bot
__IDENTIFY__ = ''
if __name__ == "__main__":
gbot = bot.IRCBot(server="chat.freenode.com", nick="grbot", port=6667, realName='gbot', identify=__IDENTIFY__, debug=True, connectDelay=4, identVerifyCall='ACC')
gbot.setDefaultChannels({'##gbot': ''})
gbot.addAdmin("shortdudey123")
gbot.loadModules(['opme', 'coreVersion', 'moduleInfo'])
gbot.run() | Python | 0.000001 |
9f5afd72bf6dbb44ba764f6731c6313f0cb94bce | Use default outputs in shortcuts/utils.py | prompt_toolkit/shortcuts/utils.py | prompt_toolkit/shortcuts/utils.py | from __future__ import unicode_literals
from prompt_toolkit.output.defaults import get_default_output
from prompt_toolkit.renderer import print_formatted_text as renderer_print_formatted_text
from prompt_toolkit.styles import default_style, BaseStyle
import six
__all__ = (
'print_formatted_text',
'clear',
'set_title',
'clear_title',
)
def print_formatted_text(formatted_text, style=None, output=None):
"""
Print a list of (style_str, text) tuples in the given style to the output.
E.g.::
style = Style.from_dict({
'hello': '#ff0066',
'world': '#884444 italic',
})
fragments = [
('class:hello', 'Hello'),
('class:world', 'World'),
]
print_formatted_text(fragments, style=style)
If you want to print a list of Pygments tokens, use
``prompt_toolkit.style.token_list_to_formatted_text`` to do the conversion.
:param text_fragments: List of ``(style_str, text)`` tuples.
:param style: :class:`.Style` instance for the color scheme.
"""
if style is None:
style = default_style()
assert isinstance(style, BaseStyle)
output = output or get_default_output()
renderer_print_formatted_text(output, formatted_text, style)
def clear():
"""
Clear the screen.
"""
out = get_default_output()
out.erase_screen()
out.cursor_goto(0, 0)
out.flush()
def set_title(text):
"""
Set the terminal title.
"""
assert isinstance(text, six.text_type)
output = get_default_output()
output.set_title(text)
def clear_title():
"""
Erase the current title.
"""
set_title('')
| from __future__ import unicode_literals
from prompt_toolkit.output.defaults import create_output
from prompt_toolkit.renderer import print_formatted_text as renderer_print_formatted_text
from prompt_toolkit.styles import default_style, BaseStyle
import six
__all__ = (
'print_formatted_text',
'clear',
'set_title',
'clear_title',
)
def print_formatted_text(formatted_text, style=None, true_color=False, file=None):
"""
Print a list of (style_str, text) tuples in the given style to the output.
E.g.::
style = Style.from_dict({
'hello': '#ff0066',
'world': '#884444 italic',
})
fragments = [
('class:hello', 'Hello'),
('class:world', 'World'),
]
print_formatted_text(fragments, style=style)
If you want to print a list of Pygments tokens, use
``prompt_toolkit.style.token_list_to_formatted_text`` to do the conversion.
:param text_fragments: List of ``(style_str, text)`` tuples.
:param style: :class:`.Style` instance for the color scheme.
:param true_color: When True, use 24bit colors instead of 256 colors.
:param file: The output file. This can be `sys.stdout` or `sys.stderr`.
"""
if style is None:
style = default_style()
assert isinstance(style, BaseStyle)
output = create_output(true_color=true_color, stdout=file)
renderer_print_formatted_text(output, formatted_text, style)
def clear():
"""
Clear the screen.
"""
out = create_output()
out.erase_screen()
out.cursor_goto(0, 0)
out.flush()
def set_title(text):
"""
Set the terminal title.
"""
assert isinstance(text, six.text_type)
output = create_output()
output.set_title(text)
def clear_title():
"""
Erase the current title.
"""
set_title('')
| Python | 0.000001 |
2c350cbbd90afaab38223fdfe40737f72bf7974a | Set --device-type as required arg for harvest_tracking_email command. | tracking/management/commands/harvest_tracking_email.py | tracking/management/commands/harvest_tracking_email.py | from django.core.management.base import BaseCommand
from tracking.harvest import harvest_tracking_email
class Command(BaseCommand):
help = "Runs harvest_tracking_email to harvest points from emails"
def add_arguments(self, parser):
parser.add_argument(
'--device-type', action='store', dest='device_type', required=True, default=None,
help='Tracking device type, one of: iriditrak, dplus, spot, mp70')
def handle(self, *args, **options):
# Specify the device type to harvest from the mailbox.
device_type = None
if options['device_type'] and options['device_type'] in ('iriditrak', 'dplus', 'spot', 'mp70'):
device_type = options['device_type']
harvest_tracking_email(device_type)
| from django.core.management.base import BaseCommand
from tracking.harvest import harvest_tracking_email
class Command(BaseCommand):
help = "Runs harvest_tracking_email to harvest points from emails"
def add_arguments(self, parser):
parser.add_argument(
'--device-type', action='store', dest='device_type', default=None,
help='Tracking device type, one of: iriditrak, dplus, spot, mp70')
def handle(self, *args, **options):
# Specify the device type to harvest from the mailbox.
device_type = None
if options['device_type'] and options['device_type'] in ('iriditrak', 'dplus', 'spot', 'mp70'):
device_type = options['device_type']
harvest_tracking_email(device_type)
| Python | 0 |
4b148d5b6fda0a8b44109e2024f61df30b981938 | Add docstrings. | HARK/datasets/cpi/us/CPITools.py | HARK/datasets/cpi/us/CPITools.py | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 20 18:07:41 2021
@author: Mateo
"""
import urllib.request
import pandas as pd
import warnings
import numpy as np
def download_cpi_series():
"""
A method that downloads the cpi research series file directly from the
bls site onto the working directory. This is the file that the rest of
the functions in this script use and is placed in HARK/datasets/cpi/us.
This function is not for users but for whenever mantainers want to update
the cpi series as new data comes out.
Returns
-------
None.
"""
urllib.request.urlretrieve("https://www.bls.gov/cpi/research-series/r-cpi-u-rs-allitems.xlsx",
"r-cpi-u-rs-allitems.xlsx")
def get_cpi_series():
"""
This function reads the cpi series currently in the toolbox and returns it
as a pandas dataframe.
Returns
-------
cpi : Pandas DataFrame
DataFrame representation of the CPI research series file from the
Bureau of Labor Statistics.
"""
cpi = pd.read_excel("r-cpi-u-rs-allitems.xlsx", skiprows = 5,
usecols = "A:N", index_col=0)
return cpi
def cpi_deflator(from_year, to_year, base_month = None):
"""
Finds cpi deflator to transform quantities measured in "from_year" U.S.
dollars to "to_year" U.S. dollars.
The deflators are computed using the "r-cpi-u-rs" series from the BLS.
Parameters
----------
from_year : int
Base year in which the nominal quantities are currently expressed.
to_year : int
Target year in which you wish to express the quantities.
base_month : str, optional
Month at which to take the CPI measurements to calculate the deflator.
The default is None, and in this case annual averages of the CPI are
used.
Returns
-------
deflator : numpy array
A length-1 numpy array with the deflator that, when multiplied by the
original nominal quantities, rebases them to "to_year" U.S. dollars.
"""
# Check years are conforming
assert type(from_year) is int and type(to_year) is int, "Years must be integers."
# Check month is conforming
if base_month is not None:
months = ['JAN','FEB','MAR','APR','MAY','JUNE',
'JULY','AUG','SEP','OCT','NOV','DEC']
assert base_month in months, ('If a month is provided, it must be ' +
'one of ' + ','.join(months) + '.')
column = base_month
else:
warnings.warn('No base month was provided. Using annual CPI averages.')
column = 'AVG'
# Get cpi and subset the columns we need.
cpi = get_cpi_series()
cpi_series = cpi[[column]].dropna()
try:
deflator = np.divide(cpi_series.loc[from_year].to_numpy(),
cpi_series.loc[to_year].to_numpy())
except KeyError as e:
message = ("Could not find a CPI value for the requested " +
"year-month combinations.")
raise Exception(message).with_traceback(e.__traceback__)
return deflator | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 20 18:07:41 2021
@author: Mateo
"""
import urllib.request
import pandas as pd
import warnings
import numpy as np
def download_cpi_series():
urllib.request.urlretrieve("https://www.bls.gov/cpi/research-series/r-cpi-u-rs-allitems.xlsx",
"r-cpi-u-rs-allitems.xlsx")
def get_cpi_series():
cpi = pd.read_excel("r-cpi-u-rs-allitems.xlsx", skiprows = 5,
usecols = "A:N", index_col=0)
return cpi
def cpi_deflator(from_year, to_year, base_month = None):
# Check month is conforming
if base_month is not None:
months = ['JAN','FEB','MAR','APR','MAY','JUNE',
'JULY','AUG','SEP','OCT','NOV','DEC']
assert base_month in months, ('If a month is provided, it must be ' +
'one of ' + ','.join(months) + '.')
column = base_month
else:
warnings.warn('No base month was provided. Using annual CPI averages.')
column = 'AVG'
# Get cpi and subset the columns we need.
cpi = get_cpi_series()
cpi_series = cpi[[column]].dropna()
try:
deflator = np.divide(cpi_series.loc[from_year].to_numpy(),
cpi_series.loc[to_year].to_numpy())
except KeyError as e:
message = ("Could not find a CPI value for the requested " +
"year-month combinations.")
raise Exception(message).with_traceback(e.__traceback__)
return deflator
#cpi_deflator(1989,2007, 'OCT')
#cpi_deflator(1980,2010) | Python | 0 |
4d247da1ecd39bcd699a55b5387412a1ac9e1582 | Split Energy and Environment, change Civil Liberties to Social Justice | txlege84/topics/management/commands/bootstraptopics.py | txlege84/topics/management/commands/bootstraptopics.py | from django.core.management.base import BaseCommand
from topics.models import Topic
class Command(BaseCommand):
help = u'Bootstrap the topic lists in the database.'
def handle(self, *args, **kwargs):
self.load_topics()
def load_topics(self):
self.stdout.write(u'Loading hot list topics...')
topics = [
u'Budget & Taxes',
u'Business & Technology',
u'Criminal Justice',
u'Energy',
u'Environment',
u'Ethics',
u'Health & Human Services',
u'Higher Education',
u'Immigration & Border Security',
u'Public Education',
u'Social Justice',
u'Transportation',
]
for topic in topics:
Topic.objects.get_or_create(name=topic)
| from django.core.management.base import BaseCommand
from topics.models import Topic
class Command(BaseCommand):
help = u'Bootstrap the topic lists in the database.'
def handle(self, *args, **kwargs):
self.load_topics()
def load_topics(self):
self.stdout.write(u'Loading hot list topics...')
topics = [
u'Budget & Taxes',
u'Business & Technology',
u'Civil Liberties',
u'Criminal Justice',
u'Energy & Environment',
u'Ethics',
u'Health & Human Services',
u'Higher Education',
u'Immigration & Border Security',
u'Public Education',
u'Transportation',
]
for topic in topics:
Topic.objects.get_or_create(name=topic)
| Python | 0 |
2bf756404700f4c38e2f3895dfa8aba2d8dc13be | Refactor and remove char2int | hash.py | hash.py |
class HashTable(object):
"""docstring for HashTable"""
table_size = 0
entries_count = 0
alphabet_size = 52
def __init__(self, size=1024):
self.table_size = size
self.hashtable = [[] for i in range(size)]
def __repr__(self):
return "<HashTable: {}>".format(self.hashtable)
def __len__(self):
count = 0
for item in self.hashtable:
if len(item) != 0:
count += 1
return count
def hashing(self, key):
"""pass"""
hash_ = 0
for i, c in enumerate(key):
hash_ += pow(
self.alphabet_size, len(key) - i - 1) * ord(c)
return hash_ % self.table_size
def set(self, key, value):
if not isinstance(key, str):
raise TypeError('Only strings may be used as keys.')
hash_ = self.hashing(key)
for i, item in enumerate(self.hashtable[hash_]):
if item[0] == key:
del self.hashtable[hash_][i]
self.entries_count -= 1
self.hashtable[hash_].append((key, value))
self.entries_count += 1
def get(self, key):
hash_ = self.hashing(key)
for i, item in enumerate(self.hashtable[hash_]):
if item[0] == key:
return self.hashtable[hash_]
raise KeyError('Key not in hash table.')
if __name__ == '__main__':
pass
|
class HashTable(object):
"""docstring for HashTable"""
table_size = 0
entries_count = 0
alphabet_size = 52
def __init__(self, size=1024):
self.table_size = size
self.hashtable = [[] for i in range(size)]
def __repr__(self):
return "<HashTable: {}>".format(self.hashtable)
def __len__(self):
count = 0
for item in self.hashtable:
if len(item) != 0:
count += 1
return count
def char2int(self, char):
"""Convert a alpha character to an int."""
# offset for ASCII table
# if char >= 'A' and char <= 'Z':
# return ord(char) - 65
# elif char >= 'a' and char <= 'z':
# return ord(char) - 65 - 7
return ord(char)
def hashing(self, key):
"""pass"""
hash_ = 0
for i, c in enumerate(key):
hash_ += pow(
self.alphabet_size, len(key) - i - 1) * self.char2int(c)
return hash_ % self.table_size
def set(self, key, value):
if not isinstance(key, str):
raise TypeError('Only strings may be used as keys.')
hash_ = self.hashing(key)
for i, item in enumerate(self.hashtable[hash_]):
if item[0] == key:
del self.hashtable[hash_][i]
self.entries_count -= 1
self.hashtable[hash_].append((key, value))
self.entries_count += 1
def get(self, key):
hash_ = self.hashing(key)
for i, item in enumerate(self.hashtable[hash_]):
if item[0] == key:
return self.hashtable[hash_]
raise KeyError('Key not in hash table.')
if __name__ == '__main__':
pass
| Python | 0.000002 |
3af8cfa40a6770e6940ec7140c92ad51532a4e73 | improve re usage | IPython/core/magics/packaging.py | IPython/core/magics/packaging.py | """Implementation of packaging-related magic functions.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2018 The IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
import re
import shlex
import sys
from pathlib import Path
from IPython.core.magic import Magics, magics_class, line_magic
def _is_conda_environment():
"""Return True if the current Python executable is in a conda env"""
# TODO: does this need to change on windows?
return Path(sys.prefix, "conda-meta", "history").exists()
def _get_conda_executable():
"""Find the path to the conda executable"""
# Check if there is a conda executable in the same directory as the Python executable.
# This is the case within conda's root environment.
conda = Path(sys.executable).parent / "conda"
if conda.isfile():
return str(conda)
# Otherwise, attempt to extract the executable from conda history.
# This applies in any conda environment.
history = Path(sys.prefix, "conda-meta", "history").read_text()
match = re.search(
r"^#\s*cmd:\s*(?P<command>.*conda)\s[create|install]",
history,
flags=re.MULTILINE,
)
if match:
return match.groupdict()["command"]
# Fallback: assume conda is available on the system path.
return "conda"
CONDA_COMMANDS_REQUIRING_PREFIX = {
'install', 'list', 'remove', 'uninstall', 'update', 'upgrade',
}
CONDA_COMMANDS_REQUIRING_YES = {
'install', 'remove', 'uninstall', 'update', 'upgrade',
}
CONDA_ENV_FLAGS = {'-p', '--prefix', '-n', '--name'}
CONDA_YES_FLAGS = {'-y', '--y'}
@magics_class
class PackagingMagics(Magics):
"""Magics related to packaging & installation"""
@line_magic
def pip(self, line):
"""Run the pip package manager within the current kernel.
Usage:
%pip install [pkgs]
"""
self.shell.system(' '.join([sys.executable, '-m', 'pip', line]))
print("Note: you may need to restart the kernel to use updated packages.")
@line_magic
def conda(self, line):
"""Run the conda package manager within the current kernel.
Usage:
%conda install [pkgs]
"""
if not _is_conda_environment():
raise ValueError("The python kernel does not appear to be a conda environment. "
"Please use ``%pip install`` instead.")
conda = _get_conda_executable()
args = shlex.split(line)
command = args[0]
args = args[1:]
extra_args = []
# When the subprocess does not allow us to respond "yes" during the installation,
# we need to insert --yes in the argument list for some commands
stdin_disabled = getattr(self.shell, 'kernel', None) is not None
needs_yes = command in CONDA_COMMANDS_REQUIRING_YES
has_yes = set(args).intersection(CONDA_YES_FLAGS)
if stdin_disabled and needs_yes and not has_yes:
extra_args.append("--yes")
# Add --prefix to point conda installation to the current environment
needs_prefix = command in CONDA_COMMANDS_REQUIRING_PREFIX
has_prefix = set(args).intersection(CONDA_ENV_FLAGS)
if needs_prefix and not has_prefix:
extra_args.extend(["--prefix", sys.prefix])
self.shell.system(' '.join([conda, command] + extra_args + args))
print("\nNote: you may need to restart the kernel to use updated packages.")
| """Implementation of packaging-related magic functions.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2018 The IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
import re
import shlex
import sys
from pathlib import Path
from IPython.core.magic import Magics, magics_class, line_magic
def _is_conda_environment():
"""Return True if the current Python executable is in a conda env"""
# TODO: does this need to change on windows?
return Path(sys.prefix, "conda-meta", "history").exists()
def _get_conda_executable():
"""Find the path to the conda executable"""
# Check if there is a conda executable in the same directory as the Python executable.
# This is the case within conda's root environment.
conda = Path(sys.executable).parent / "conda"
if conda.isfile():
return str(conda)
# Otherwise, attempt to extract the executable from conda history.
# This applies in any conda environment.
R = re.compile(r"^#\s*cmd:\s*(?P<command>.*conda)\s[create|install]")
with open(Path(sys.prefix, "conda-meta", "history")) as f:
for line in f:
match = R.match(line)
if match:
return match.groupdict()['command']
# Fallback: assume conda is available on the system path.
return "conda"
CONDA_COMMANDS_REQUIRING_PREFIX = {
'install', 'list', 'remove', 'uninstall', 'update', 'upgrade',
}
CONDA_COMMANDS_REQUIRING_YES = {
'install', 'remove', 'uninstall', 'update', 'upgrade',
}
CONDA_ENV_FLAGS = {'-p', '--prefix', '-n', '--name'}
CONDA_YES_FLAGS = {'-y', '--y'}
@magics_class
class PackagingMagics(Magics):
"""Magics related to packaging & installation"""
@line_magic
def pip(self, line):
"""Run the pip package manager within the current kernel.
Usage:
%pip install [pkgs]
"""
self.shell.system(' '.join([sys.executable, '-m', 'pip', line]))
print("Note: you may need to restart the kernel to use updated packages.")
@line_magic
def conda(self, line):
"""Run the conda package manager within the current kernel.
Usage:
%conda install [pkgs]
"""
if not _is_conda_environment():
raise ValueError("The python kernel does not appear to be a conda environment. "
"Please use ``%pip install`` instead.")
conda = _get_conda_executable()
args = shlex.split(line)
command = args[0]
args = args[1:]
extra_args = []
# When the subprocess does not allow us to respond "yes" during the installation,
# we need to insert --yes in the argument list for some commands
stdin_disabled = getattr(self.shell, 'kernel', None) is not None
needs_yes = command in CONDA_COMMANDS_REQUIRING_YES
has_yes = set(args).intersection(CONDA_YES_FLAGS)
if stdin_disabled and needs_yes and not has_yes:
extra_args.append("--yes")
# Add --prefix to point conda installation to the current environment
needs_prefix = command in CONDA_COMMANDS_REQUIRING_PREFIX
has_prefix = set(args).intersection(CONDA_ENV_FLAGS)
if needs_prefix and not has_prefix:
extra_args.extend(["--prefix", sys.prefix])
self.shell.system(' '.join([conda, command] + extra_args + args))
print("\nNote: you may need to restart the kernel to use updated packages.")
| Python | 0 |
3039149ca20e9c472340495e4130e331d9c546b3 | Fix nums assignment properly | calc.py | calc.py | import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return reduce(lambda a, b: a*b, nums)
if __name__ == '__main__':
command =sys.argv[1]
nums=map(float, sys.argv[2:])
if command=='add':
print add_all(nums)
if command=='multiply':
print multiply_all(nums)
| import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return reduce(lambda a, b: a*b, nums)
if __name__ == '__main__':
command =sys.argv[1]
nums=map(float(sys.argv[2:]))
if command=='add':
print add_all(nums)
if command=='multiply':
print multiply_all(nums)
| Python | 0.000001 |
fd8caec8567178abe09abc810f1e96bfc4bb531b | Fix bug in 'multiply' support | calc.py | calc.py | import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return reduce(lambda a, b: a * b, nums)
if __name__== '__main__':
command = sys.argv[1]
nums = map(float, sys.argv[2:])
if command == 'add':
print(add_all(nums))
elif command == 'multiply':
print(multiply_all(nums))
| import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return reduce(lambda a, b: a * b, nums)
if __name__== '__main__':
command = sys.argv[1]
nums = map(float, sys.argv[2:])
if command == 'add':
print(add_all(nums))
elif command == 'multiply':
print(multiply_all(sums))
| Python | 0.000001 |
c3ba924c5fe3fef3f2dd43a9f43eacdebb8d8c13 | Make the new init script executable | init.py | init.py | #!/usr/bin/env python3
"""Wurstminebot init script.
Usage:
init.py start | stop | restart | status
init.py -h | --help
init.py --version
Options:
-h, --help Print this message and exit.
--version Print version info and exit.
"""
from docopt import docopt
import os
import os.path
import signal
import subprocess
import sys
KEEPALIVE = '/var/local/wurstmineberg/wurstminebot_keepalive'
def _fork(func):
#FROM http://stackoverflow.com/a/6011298/667338
# do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177)
try:
pid = os.fork()
if pid > 0:
# parent process, return and keep running
return
except OSError as e:
print("fork #1 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr)
sys.exit(1)
os.setsid()
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError as e:
print("fork #2 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr)
sys.exit(1)
with open(os.path.devnull) as devnull:
sys.stdin = devnull
sys.stdout = devnull
func() # do stuff
os._exit(os.EX_OK) # all done
def start():
def _start():
with open(KEEPALIVE, 'a'):
pass # create the keepalive file
while os.path.exists(KEEPALIVE):
with open(os.path.devnull) as devnull:
p = subprocess.Popen('wurstminebot < /var/local/wurstmineberg/irc', shell=True, stdout=devnull)
with open(KEEPALIVE, 'a') as keepalive:
print(str(p.pid), file=keepalive)
p.communicate()
_fork(_start)
def status():
return os.path.exists(KEEPALIVE)
def stop():
pid = None
try:
with open(KEEPALIVE) as keepalive:
for line in keepalive:
pid = int(line.strip())
except FileNotFoundError:
return # not running
else:
os.remove(KEEPALIVE)
if pid is not None:
os.kill(pid, signal.SIGKILL)
if __name__ == '__main__':
arguments = docopt(__doc__, version='0.1.0')
if arguments['start']:
start()
elif arguments['stop']:
stop()
elif arguments['restart']:
stop()
start()
elif arguments['status']:
print('wurstminebot ' + ('is' if status() else 'is not') + ' running.')
| #!/usr/bin/env python3
"""Wurstminebot init script.
Usage:
init.py start | stop | restart | status
init.py -h | --help
init.py --version
Options:
-h, --help Print this message and exit.
--version Print version info and exit.
"""
from docopt import docopt
import os
import os.path
import signal
import subprocess
import sys
KEEPALIVE = '/var/local/wurstmineberg/wurstminebot_keepalive'
def _fork(func):
#FROM http://stackoverflow.com/a/6011298/667338
# do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177)
try:
pid = os.fork()
if pid > 0:
# parent process, return and keep running
return
except OSError as e:
print("fork #1 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr)
sys.exit(1)
os.setsid()
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError as e:
print("fork #2 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr)
sys.exit(1)
with open(os.path.devnull) as devnull:
sys.stdin = devnull
sys.stdout = devnull
func() # do stuff
os._exit(os.EX_OK) # all done
def start():
def _start():
with open(KEEPALIVE, 'a'):
pass # create the keepalive file
while os.path.exists(KEEPALIVE):
with open(os.path.devnull) as devnull:
p = subprocess.Popen('wurstminebot < /var/local/wurstmineberg/irc', shell=True, stdout=devnull)
with open(KEEPALIVE, 'a') as keepalive:
print(str(p.pid), file=keepalive)
p.communicate()
_fork(_start)
def status():
return os.path.exists(KEEPALIVE)
def stop():
pid = None
try:
with open(KEEPALIVE) as keepalive:
for line in keepalive:
pid = int(line.strip())
except FileNotFoundError:
return # not running
else:
os.remove(KEEPALIVE)
if pid is not None:
os.kill(pid, signal.SIGKILL)
if __name__ == '__main__':
arguments = docopt(__doc__, version='0.1.0')
if arguments['start']:
start()
elif arguments['stop']:
stop()
elif arguments['restart']:
stop()
start()
elif arguments['status']:
print('wurstminebot ' + ('is' if status() else 'is not') + ' running.')
| Python | 0.00001 |
183448b17cfd910444d3807da80ef8549622fce4 | test the urltopath | init.py | init.py | import yumoter
yumoter = yumoter.yumoter('config/repos.json', '/home/aarwine/git/yumoter/repos')
yumoter.loadRepos("6.4", "wildwest")
a = yumoter._returnNewestByNameArch(["openssl"])
a = a[0]
print a
print "name", a.name
print "arch", a.arch
print "epoch", a.epoch
print "version", a.version
print "release", a.release
print "size", a.size
print "remote_url", a.remote_url
print yumoter._urlToPath(a.remote_url)
print yumoter._urlToPromoPath(a.remote_url)
b = yumoter.getDeps(a)
print "###"
for pkg in b:
print pkg
for dep in b[pkg]:
print "\t%s - %s" % (dep, dep.remote_url)
| import yumoter
yumoter = yumoter.yumoter('config/repos.json', '/home/aarwine/git/yumoter/repos')
yumoter.loadRepos("6.4", "wildwest")
a = yumoter._returnNewestByNameArch(["openssl"])
a = a[0]
print a
print "name", a.name
print "arch", a.arch
print "epoch", a.epoch
print "version", a.version
print "release", a.release
print "size", a.size
print "remote_url", a.remote_url
print yumoter._urlToPromoPath(a.remote_url)
b = yumoter.getDeps(a)
print "###"
for pkg in b:
print pkg
for dep in b[pkg]:
print "\t%s - %s" % (dep, dep.remote_url)
| Python | 0.000018 |
27543f73244c7312ea511c7e00d9eecf7b7525e9 | store model in self.model | cost.py | cost.py | """
Cost classes: classes that encapsulate the cost evaluation for the DAE
training criterion.
"""
# Standard library imports
from itertools import izip
# Third-party imports
from theano import tensor
class SupervisedCost(object):
"""
A cost object is allocated in the same fashion as other
objects in this file, with a 'conf' dictionary (or object
supporting __getitem__) containing relevant hyperparameters.
"""
def __init__(self, conf, model):
self.conf = conf
# TODO: Do stuff depending on conf parameters (for example
# use different cross-entropy if act_end == "tanh" or not)
self.model = model
def __call__(self, *inputs):
"""Symbolic expression denoting the reconstruction error."""
raise NotImplementedError()
class MeanSquaredError(SupervisedCost):
"""
Symbolic expression for mean-squared error between the input and the
denoised reconstruction.
"""
def __call__(self, prediction, target):
msq = lambda p, t: ((p - t)**2).sum(axis=1).mean()
if isinstance(prediction, tensor.Variable):
return msq(prediction, target)
else:
pairs = izip(prediction, target)
# TODO: Think of something more sensible to do than sum(). On one
# hand, if we're treating everything in parallel it should return
# a list. On the other, we need a scalar for everything else to
# work.
# This will likely get refactored out into a "costs" module or
# something like that.
return sum([msq(p, t) for p, t in pairs])
class CrossEntropy(SupervisedCost):
"""
Symbolic expression for elementwise cross-entropy between input
and reconstruction. Use for binary-valued features (but not for,
e.g., one-hot codes).
"""
def __call__(self, prediction, target):
ce = lambda x, z: x * tensor.log(z) + (1 - x) * tensor.log(1 - z)
if isinstance(prediction, tensor.Variable):
return ce(prediction, target)
pairs = izip(prediction, target)
return sum([ce(p, t).sum(axis=1).mean() for p, t in pairs])
##################################################
def get(str):
""" Evaluate str into a cost object, if it exists """
obj = globals()[str]
if issubclass(obj, Cost):
return obj
else:
raise NameError(str)
| """
Cost classes: classes that encapsulate the cost evaluation for the DAE
training criterion.
"""
# Standard library imports
from itertools import izip
# Third-party imports
from theano import tensor
class SupervisedCost(object):
"""
A cost object is allocated in the same fashion as other
objects in this file, with a 'conf' dictionary (or object
supporting __getitem__) containing relevant hyperparameters.
"""
def __init__(self, conf, model):
self.conf = conf
# TODO: Do stuff depending on conf parameters (for example
# use different cross-entropy if act_end == "tanh" or not)
def __call__(self, *inputs):
"""Symbolic expression denoting the reconstruction error."""
raise NotImplementedError()
class MeanSquaredError(SupervisedCost):
"""
Symbolic expression for mean-squared error between the input and the
denoised reconstruction.
"""
def __call__(self, prediction, target):
msq = lambda p, t: ((p - t)**2).sum(axis=1).mean()
if isinstance(prediction, tensor.Variable):
return msq(prediction, target)
else:
pairs = izip(prediction, target)
# TODO: Think of something more sensible to do than sum(). On one
# hand, if we're treating everything in parallel it should return
# a list. On the other, we need a scalar for everything else to
# work.
# This will likely get refactored out into a "costs" module or
# something like that.
return sum([msq(p, t) for p, t in pairs])
class CrossEntropy(SupervisedCost):
"""
Symbolic expression for elementwise cross-entropy between input
and reconstruction. Use for binary-valued features (but not for,
e.g., one-hot codes).
"""
def __call__(self, prediction, target):
ce = lambda x, z: x * tensor.log(z) + (1 - x) * tensor.log(1 - z)
if isinstance(prediction, tensor.Variable):
return ce(prediction, target)
pairs = izip(prediction, target)
return sum([ce(p, t).sum(axis=1).mean() for p, t in pairs])
##################################################
def get(str):
""" Evaluate str into a cost object, if it exists """
obj = globals()[str]
if issubclass(obj, Cost):
return obj
else:
raise NameError(str)
| Python | 0.000001 |
a04b18b8fbc8626b5592593a2b6ce635921a1e34 | Delete text after entered, but this time actually do it | data.py | data.py | from twitter import *
from tkinter import *
def showTweets(x, num):
# display a number of new tweets and usernames
for i in range(0, num):
line1 = (x[i]['user']['screen_name'])
line2 = (x[i]['text'])
w = Label(master, text=line1 + "\n" + line2 + "\n\n")
w.pack()
def getTweets():
x = t.statuses.home_timeline(screen_name="AndrewKLeech")
return x
def tweet():
global entryWidget
if entryWidget.get().strip() == "":
print("Empty")
else:
t.statuses.update(status=entryWidget.get().strip())
entryWidget.delete(0,END)
print("working")
# Put in token, token_key, con_secret, con_secret_key
t = Twitter(
auth=OAuth('705153959368007680-F5OUf8pvmOlXku1b7gpJPSAToqzV4Fb', 'bEGLkUJBziLc17EuKLTAMio8ChmFxP9aHYADwRXnxDsoC',
'gYDgR8lcTGcVZS9ucuEIYsMuj', '1dwHsLDN2go3aleQ8Q2vcKRfLETc51ipsP8310ayizL2p3Ycii'))
numberOfTweets = 5
master = Tk()
showTweets(getTweets(), numberOfTweets)
master.title("Tkinter Entry Widget")
master["padx"] = 40
master["pady"] = 20
# Create a text frame to hold the text Label and the Entry widget
textFrame = Frame(master)
#Create a Label in textFrame
entryLabel = Label(textFrame)
entryLabel["text"] = "Make a new Tweet:"
entryLabel.pack(side=LEFT)
# Create an Entry Widget in textFrame
entryWidget = Entry(textFrame)
entryWidget["width"] = 50
entryWidget.pack(side=LEFT)
textFrame.pack()
button = Button(master, text="Submit", command=tweet)
button.pack()
master.mainloop() | from twitter import *
from tkinter import *
def showTweets(x, num):
# display a number of new tweets and usernames
for i in range(0, num):
line1 = (x[i]['user']['screen_name'])
line2 = (x[i]['text'])
w = Label(master, text=line1 + "\n" + line2 + "\n\n")
w.pack()
def getTweets():
x = t.statuses.home_timeline(screen_name="AndrewKLeech")
return x
def tweet():
global entryWidget
if entryWidget.get().strip() == "":
print("Empty")
else:
#t.statuses.update(status=entryWidget.get().strip())
#entryWidget.put().strip()
entryWidget.insert(0,'')
print("working")
# Put in token, token_key, con_secret, con_secret_key
t = Twitter(
auth=OAuth('705153959368007680-F5OUf8pvmOlXku1b7gpJPSAToqzV4Fb', 'bEGLkUJBziLc17EuKLTAMio8ChmFxP9aHYADwRXnxDsoC',
'gYDgR8lcTGcVZS9ucuEIYsMuj', '1dwHsLDN2go3aleQ8Q2vcKRfLETc51ipsP8310ayizL2p3Ycii'))
numberOfTweets = 5
master = Tk()
showTweets(getTweets(), numberOfTweets)
master.title("Tkinter Entry Widget")
master["padx"] = 40
master["pady"] = 20
# Create a text frame to hold the text Label and the Entry widget
textFrame = Frame(master)
#Create a Label in textFrame
entryLabel = Label(textFrame)
entryLabel["text"] = "Make a new Tweet:"
entryLabel.pack(side=LEFT)
# Create an Entry Widget in textFrame
entryWidget = Entry(textFrame)
entryWidget["width"] = 50
entryWidget.pack(side=LEFT)
textFrame.pack()
button = Button(master, text="Submit", command=tweet)
button.pack()
master.mainloop() | Python | 0.000002 |
2b12019b0e6b5881e38d48cc7981936fe5e7c81d | Fix a bug with info pages | shortener/links/views.py | shortener/links/views.py | from django.db.models import Q
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.utils.baseconv import base64
from django.utils import timezone
from django.views.generic import RedirectView, ListView, DetailView
from .models import Link
from linkmetrics.models import LinkLog
class LinkRedirectView(RedirectView):
permanent = True
query_string = True
def get_redirect_url(self, **kwargs):
identifier = self.kwargs['identifier']
# If identifier includes a link it means we don't need to do a base64
# decode. Just a fetch based on the identifier
if '-' in identifier or '_' in identifier or '.' in identifier:
link = get_object_or_404(Link, identifier=identifier)
link.log(self.request)
return link.original_url
# decode based on the identifier
pk = base64.decode(identifier)
try:
link = Link.objects.get(Q(pk=pk) | Q(identifier=identifier))
except Link.DoesNotExist:
raise Http404
link.log(self.request)
return link.original_url
class LinkListView(ListView):
model = Link
class LinkDetailView(DetailView):
model = Link
def get_object(self):
identifier = self.kwargs['identifier']
if '-' in identifier or '_' in identifier or '.' in identifier:
return get_object_or_404(Link, identifier=identifier)
# decode based on the identifier
pk = base64.decode(identifier)
try:
link = Link.objects.get(Q(pk=pk) | Q(identifier=identifier))
except Link.DoesNotExist:
raise Http404
return link
def get_context_data(self, *args, **kwargs):
context = super(LinkDetailView, self).get_context_data(**kwargs)
# Ghetto style just to get it working
counts = []
for date in self.object.linklog_set.dates('created', 'day'):
count = LinkLog.objects.filter(
created__day=date.day,
created__month=date.month,
created__year=date.year,
link=self.object
).count()
counts.append(
{"date": date + timezone.timedelta(1), # timezone to fix weird off-by-one
"count": count}
)
context['counts'] = counts
return context
| from django.db.models import Q
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.utils.baseconv import base64
from django.utils import timezone
from django.views.generic import RedirectView, ListView, DetailView
from .models import Link
from linkmetrics.models import LinkLog
class LinkRedirectView(RedirectView):
permanent = True
query_string = True
def get_redirect_url(self, **kwargs):
identifier = self.kwargs['identifier']
# If identifier includes a link it means we don't need to do a base64
# decode. Just a fetch based on the identifier
if '-' in identifier or '_' in identifier or '.' in identifider:
link = get_object_or_404(Link, identifier=identifier)
link.log(self.request)
return link.original_url
# decode based on the identifier
pk = base64.decode(identifier)
try:
link = Link.objects.get(Q(pk=pk) | Q(identifier=identifier))
except Link.DoesNotExist:
raise Http404
link.log(self.request)
return link.original_url
class LinkListView(ListView):
model = Link
class LinkDetailView(DetailView):
model = Link
def get_object(self):
identifier = self.kwargs['identifier']
if '-' in identifier or '_' in identifier or '.' in identifider:
return get_object_or_404(Link, identifier=identifier)
# decode based on the identifier
pk = base64.decode(identifier)
try:
link = Link.objects.get(Q(pk=pk) | Q(identifier=identifier))
except Link.DoesNotExist:
raise Http404
return link
def get_context_data(self, *args, **kwargs):
context = super(LinkDetailView, self).get_context_data(**kwargs)
# Ghetto style just to get it working
counts = []
for date in self.object.linklog_set.dates('created', 'day'):
count = LinkLog.objects.filter(
created__day=date.day,
created__month=date.month,
created__year=date.year,
link=self.object
).count()
counts.append(
{"date": date + timezone.timedelta(1), # timezone to fix weird off-by-one
"count": count}
)
context['counts'] = counts
return context
| Python | 0.000002 |
2ecdd27d96da12bf44a5751b7d76cedf05c1e620 | don't remove all whitespace | scripts/DYKChecker.py | scripts/DYKChecker.py | # -*- coding: utf-8 -*-
"""DYKChecker!"""
__version__ = "1.0.1"
__author__ = "Sorawee Porncharoenwase"
import json
import init
import wp
import pywikibot
from wp import lre
def glob():
pass
def main():
page = wp.Page(wp.toutf(raw_input()))
dic = {}
while True:
try:
text = page.get()
break
except pywikibot.NoPage:
dic["error"] = u"ไม่มีหน้าดังกล่าว"
break
except pywikibot.IsRedirectPage:
page = page.getRedirectTarget()
except:
dic["error"] = u"เกิดข้อผิดพลาดไม่ทราบสาเหตุ"
break
oldtext = text
if "error" not in dic:
# delete all references
text, numinline = lre.subn(r"(?s)<ref.*?</ref>", "", text)
text = lre.rmsym(r"\{\{", r"\}\}", text)
text = lre.rmsym(r"\{\|", r"\|\}", text)
text = pywikibot.removeDisabledParts(text)
text = pywikibot.removeHTMLParts(text)
text = pywikibot.removeLanguageLinks(text)
text = pywikibot.removeCategoryLinks(text)
subst = lre.subst()
subst.append((r"[ \t]*", " "))
subst.append((r"\n*", "\n"))
subst.append((r"(?s)(?<!\[)\[(?!\[).*?\]", ""))
subst.append((r"[\[\]]", ""))
text = subst.process(text)
dic["newtext"] = text
dic["len"] = {}
dic["len"]["value"] = len(text)
dic["len"]["result"] = "passed" if (dic["len"]["value"] >= 2000) else "failed"
print json.dumps(dic)
if __name__ == "__main__":
args, site, conf = wp.pre("DYK Checker")
try:
glob()
main()
except:
wp.posterror()
else:
wp.post()
| # -*- coding: utf-8 -*-
"""DYKChecker!"""
__version__ = "1.0.1"
__author__ = "Sorawee Porncharoenwase"
import json
import init
import wp
import pywikibot
from wp import lre
def glob():
pass
def main():
page = wp.Page(wp.toutf(raw_input()))
dic = {}
while True:
try:
text = page.get()
break
except pywikibot.NoPage:
dic["error"] = u"ไม่มีหน้าดังกล่าว"
break
except pywikibot.IsRedirectPage:
page = page.getRedirectTarget()
except:
dic["error"] = u"เกิดข้อผิดพลาดไม่ทราบสาเหตุ"
break
oldtext = text
if "error" not in dic:
# delete all references
text, numinline = lre.subn(r"(?s)<ref.*?</ref>", "", text)
text = lre.rmsym(r"\{\{", r"\}\}", text)
text = lre.rmsym(r"\{\|", r"\|\}", text)
text = pywikibot.removeDisabledParts(text)
text = pywikibot.removeHTMLParts(text)
text = pywikibot.removeLanguageLinks(text)
text = pywikibot.removeCategoryLinks(text)
subst = lre.subst()
# delete all spaces
subst.append((r"\s+", " "))
# delete all external links
subst.append((r"(?s)(?<!\[)\[(?!\[).*?\]", ""))
subst.append((r"[\[\]]", ""))
text = subst.process(text)
dic["newtext"] = text
dic["len"] = {}
dic["len"]["value"] = len(text)
dic["len"]["result"] = "passed" if (dic["len"]["value"] >= 2000) else "failed"
print json.dumps(dic)
if __name__ == "__main__":
args, site, conf = wp.pre("DYK Checker")
try:
glob()
main()
except:
wp.posterror()
else:
wp.post()
| Python | 0.689513 |
5c5de666e86d6f2627df79762b0e3b0f188861d4 | Fix timestamp comparison on ciresources | scripts/claim_vlan.py | scripts/claim_vlan.py | import MySQLdb
from datetime import datetime, timedelta
db = MySQLdb.connect(host="10.0.196.2",
user="ciuser",
passwd="secret",
db="ciresources")
cur = db.cursor()
f = '%Y-%m-%d %H:%M:%S'
three_hours_ago_dt = datetime.utcnow() - timedelta(hours=3)
three_hours_ago = three_hours_ago_dt.strftime(f)
cur.execute("SELECT * FROM vlans WHERE locked!=true OR timestamp<'%s' LIMIT 1 FOR UPDATE" % three_hours_ago)
row = cur.fetchone()
if row is not None:
min_vlan = row[0]
max_vlan = row[1]
vlans = {"min_vlan": min_vlan, "max_vlan":max_vlan, "timestamp": datetime.now().strftime(f)}
cur.execute("UPDATE vlans SET locked=true, timestamp='%(timestamp)s' where min_vlan=%(min_vlan)s AND max_vlan=%(max_vlan)s" % vlans)
else:
raise Exception("No free VLANs found!")
db.commit()
db.close()
print("%(min_vlan)s:%(max_vlan)s" % vlans)
| import MySQLdb
from datetime import datetime, timedelta
db = MySQLdb.connect(host="10.0.196.2",
user="ciuser",
passwd="secret",
db="ciresources")
cur = db.cursor()
f = '%Y-%m-%d %H:%M:%S'
three_hours_ago_dt = datetime.utcnow() - timedelta(hours=3)
three_hours_ago = three_hours_ago_dt.strftime(f)
cur.execute("SELECT * FROM vlans WHERE locked!=true OR timestamp > '%s' LIMIT 1 FOR UPDATE" % three_hours_ago)
row = cur.fetchone()
if row is not None:
min_vlan = row[0]
max_vlan = row[1]
vlans = {"min_vlan": min_vlan, "max_vlan":max_vlan, "timestamp": datetime.now().strftime(f)}
cur.execute("UPDATE vlans SET locked=true, timestamp='%(timestamp)s' where min_vlan=%(min_vlan)s AND max_vlan=%(max_vlan)s" % vlans)
else:
raise Exception("No free VLANs found!")
db.commit()
db.close()
print("%(min_vlan)s:%(max_vlan)s" % vlans)
| Python | 0.000049 |
efc3a2c31a00a2139f55ca5ce9f3cf4dac1dea1f | address comments | tests/debug_nans_test.py | tests/debug_nans_test.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for --debug_nans."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import absltest
from absl.testing import parameterized
import numpy as onp
import jax
from jax import test_util as jtu
from jax.test_util import check_grads
from jax import numpy as np
from jax import random
from jax.config import config
config.parse_flags_with_absl()
class DebugNaNsTest(jtu.JaxTestCase):
def setUp(self):
self.cfg = config.read("jax_debug_nans")
config.update("jax_debug_nans", True)
def tearDown(self):
config.update("jax_debug_nans", self.cfg)
def testSingleResultPrimitive(self):
A = np.array([[1., 2.], [2., 3.]])
B = np.tanh(A)
def testMultipleResultPrimitive(self):
A = np.array([[1., 2.], [2., 3.]])
D, V = np.linalg.eig(A)
def testJitComputation(self):
A = np.array([[1., 2.], [2., 3.]])
B = jax.jit(np.tanh)(A)
| # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for --debug_nans."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import absltest
from absl.testing import parameterized
import numpy as onp
import jax
from jax import test_util as jtu
from jax.test_util import check_grads
from jax import numpy as np
from jax import random
from jax.config import config
config.parse_flags_with_absl()
class DebugNaNsTest(jtu.JaxTestCase):
def setUp(self):
self.cfg = config.read("jax_debug_nans")
config.update("jax_debug_nans", True)
def tearDown(self):
config.update("jax_debug_nans", self.cfg)
def testSingleResultPrimitive(self):
A = np.array([[1., 2.], [2., 3.]])
B = np.tanh(A)
def testMultipleResultPrimitive(self):
A = np.array([[1., 2.], [2., 3.]])
D, V = np.linalg.eig(A)
def testJitComputation(self):
A = np.array([[1., 2.], [2., 3.]])
B = jax.jit(np.tanh)(A)
| Python | 0 |
eee6dd8f6d7555f97452fb5734e299203b337ace | Fix fast_classifier | tests/fast_classifier.py | tests/fast_classifier.py | import numpy as np
class fast_classifier(object):
def __init__(self):
pass
def train(self, features, labels):
examples = {}
for f,lab in zip(features, labels):
if lab not in examples:
examples[lab] = f
return fast_model(examples)
class fast_model(object):
def __init__(self, examples):
self.examples = examples
assert len(self.examples)
def apply(self, f):
best = None
best_val = +np.inf
for k,v in self.examples.iteritems():
dist = np.dot(v-f, v-f)
if dist < best_val:
best = k
best_val = dist
return best
| import numpy as np
class fast_classifier(object):
def __init__(self):
pass
def train(self, features, labels):
examples = {}
for f,lab in zip(features, labels):
if lab not in examples:
examples[lab] = f
return fast_model(examples)
class fast_model(object):
def __init__(self, examples):
self.examples = examples
def apply(self, features):
res = []
for f in features:
cur = None
best = +np.inf
for k,v in self.examples.iteritems():
dist = np.dot(v-f, v-f)
if dist < best:
best = dist
cur = k
res.append(k)
return res
| Python | 0 |
83a15b47ecac219c2fe4ca1e49cfa9055f9197d2 | Add some tests | tests/test_features.py | tests/test_features.py | from unittest import mock, TestCase
from unleash_client import features
class TestFactory(TestCase):
def test_simple_case(self):
strategies = {'Foo': mock.Mock(return_value='R')}
feature = {'strategies': [{'name': 'Foo', 'parameters': {'x': 0}}]}
result = features.feature_gates(strategies, feature)
assert result == ['R']
assert strategies['Foo'].called_once_with(x=0)
def test_two_strategies(self):
strategies = {
'Foo': mock.Mock(return_value='F'),
'Bar': mock.Mock(return_value='B'),
}
feature = {'strategies': [
{'name': 'Foo', 'parameters': {'x': 0}},
{'name': 'Bar', 'parameters': {'y': 1}},
]}
result = features.feature_gates(strategies, feature)
assert result == ['F', 'B']
assert strategies['Foo'].called_once_with(x=0)
assert strategies['Bar'].called_once_with(y=1)
def test_unknown_strategy(self):
strategies = {}
feature = {'strategies': [{'name': 'absent', 'parameters': {'z': 9}}]}
with mock.patch('unleash_client.features.log') as log:
result = features.feature_gates(strategies, feature)
assert len(result) == 1
assert callable(result[0])
assert not result[0](basically_anything_here='foo')
assert log.warning.called
class TestFeature(TestCase):
def test_happy_path(self):
strategies = {'Foo': mock.Mock(return_value=lambda z: z)}
feature_def = {
'enabled': True,
'strategies': [{'name': 'Foo', 'parameters': {'x': 0}}],
}
toggle = features.Feature(strategies, feature_def)
assert isinstance(toggle, features.Feature)
assert toggle({'z': True})
assert not toggle({'z': False})
assert toggle.choices == {True: 1, False: 1}
def test_empty_strategy_list(self):
strategies = {'Foo': mock.Mock(return_value=lambda z: z)}
feature_def = {
'enabled': True,
'strategies': [],
}
toggle = features.Feature(strategies, feature_def)
assert isinstance(toggle, features.Feature)
assert not toggle({'z': True})
assert not toggle({'z': False})
assert toggle.choices == {True: 0, False: 2}
def test_disable(self):
strategies = {'Foo': mock.Mock(return_value=lambda z: z)}
feature_def = {
'enabled': False,
'strategies': [{'name': 'Foo', 'parameters': {'x': 0}}],
}
toggle = features.Feature(strategies, feature_def)
assert not toggle({'z': True})
assert not toggle({'z': False})
assert toggle.choices == {True: 0, False: 2}
| Python | 0.000008 | |
2b8b32605c9d211154f47d228038464ff5df7b56 | fix import | tests/test_kernel32.py | tests/test_kernel32.py | import os
from pywincffi.core.ffi import ffi
from pywincffi.core.testutil import TestCase
from pywincffi.exceptions import WindowsAPIError
from pywincffi.kernel32.process import (
PROCESS_QUERY_LIMITED_INFORMATION, OpenProcess)
class TestOpenProcess(TestCase):
"""
Tests for :func:`pywincffi.kernel32.OpenProcess`
"""
def test_returns_handle(self):
handle = OpenProcess(
PROCESS_QUERY_LIMITED_INFORMATION,
False,
os.getpid()
)
typeof = ffi.typeof(handle)
self.assertEqual(typeof.kind, "pointer")
self.assertEqual(typeof.cname, "void *")
def test_access_denied_for_null_desired_access(self):
with self.assertRaises(WindowsAPIError) as error:
OpenProcess(0, False, os.getpid())
self.assertEqual(error.exception.code, 5)
| import os
from pywincffi.core.ffi import ffi
from pywincffi.core.testutil import TestCase
from pywincffi.exceptions import WindowsAPIError
from pywincffi.kernel32 import PROCESS_QUERY_LIMITED_INFORMATION, OpenProcess
class TestOpenProcess(TestCase):
"""
Tests for :func:`pywincffi.kernel32.OpenProcess`
"""
def test_returns_handle(self):
handle = OpenProcess(
PROCESS_QUERY_LIMITED_INFORMATION,
False,
os.getpid()
)
typeof = ffi.typeof(handle)
self.assertEqual(typeof.kind, "pointer")
self.assertEqual(typeof.cname, "void *")
def test_access_denied_for_null_desired_access(self):
with self.assertRaises(WindowsAPIError) as error:
OpenProcess(0, False, os.getpid())
self.assertEqual(error.exception.code, 5)
| Python | 0.000001 |
b1edd17b647766091eab44d730b79ec52c8cb50d | Add tests for project points | tests/test_projects.py | tests/test_projects.py | from taiga.requestmaker import RequestMaker, RequestMakerException
from taiga.models.base import InstanceResource, ListResource
from taiga.models import User, Point, UserStoryStatus, Severity, Project, Projects
from taiga import TaigaAPI
import taiga.exceptions
import json
import requests
import unittest
from mock import patch
from .tools import create_mock_json
from .tools import MockResponse
class TestProjects(unittest.TestCase):
@patch('taiga.requestmaker.RequestMaker.get')
def test_single_project_parsing(self, mock_requestmaker_get):
mock_requestmaker_get.return_value = MockResponse(200,
create_mock_json('tests/resources/project_details_success.json'))
api = TaigaAPI(token='f4k3')
project = api.projects.get(1)
self.assertEqual(project.description, 'test 1 on real taiga')
self.assertEqual(len(project.users), 1)
self.assertTrue(isinstance(project.points[0], Point))
self.assertTrue(isinstance(project.us_statuses[0], UserStoryStatus))
self.assertTrue(isinstance(project.severities[0], Severity))
@patch('taiga.requestmaker.RequestMaker.get')
def test_list_projects_parsing(self, mock_requestmaker_get):
mock_requestmaker_get.return_value = MockResponse(200,
create_mock_json('tests/resources/projects_list_success.json'))
api = TaigaAPI(token='f4k3')
projects = api.projects.list()
self.assertEqual(projects[0].description, 'test 1 on real taiga')
self.assertEqual(len(projects), 1)
self.assertEqual(len(projects[0].users), 1)
self.assertTrue(isinstance(projects[0].users[0], User))
@patch('taiga.requestmaker.RequestMaker.post')
def test_star(self, mock_requestmaker_post):
rm = RequestMaker('/api/v1', 'fakehost', 'faketoken')
project = Project(rm, id=1)
self.assertEqual(project.star().id, 1)
mock_requestmaker_post.assert_called_with(
'/{endpoint}/{id}/star',
endpoint='projects', id=1
)
@patch('taiga.requestmaker.RequestMaker.post')
def test_unstar(self, mock_requestmaker_post):
rm = RequestMaker('/api/v1', 'fakehost', 'faketoken')
project = Project(rm, id=1)
self.assertEqual(project.unstar().id, 1)
mock_requestmaker_post.assert_called_with(
'/{endpoint}/{id}/unstar',
endpoint='projects', id=1
)
@patch('taiga.models.base.ListResource._new_resource')
def test_create_project(self, mock_new_resource):
rm = RequestMaker('/api/v1', 'fakehost', 'faketoken')
mock_new_resource.return_value = Project(rm)
sv = Projects(rm).create('PR 1', 'PR desc 1')
mock_new_resource.assert_called_with(
payload={'name': 'PR 1', 'description': 'PR desc 1'}
)
@patch('taiga.models.Points.create')
def test_add_point(self, mock_new_point):
rm = RequestMaker('/api/v1', 'fakehost', 'faketoken')
project = Project(rm, id=1)
project.add_point('Point 1', 1.5)
mock_new_point.assert_called_with(1, 'Point 1', 1.5)
@patch('taiga.models.Points.list')
def test_list_points(self, mock_list_points):
rm = RequestMaker('/api/v1', 'fakehost', 'faketoken')
project = Project(rm, id=1)
project.list_points()
mock_list_points.assert_called_with(project=1)
| from taiga.requestmaker import RequestMaker, RequestMakerException
from taiga.models.base import InstanceResource, ListResource
from taiga.models import User, Point, UserStoryStatus, Severity, Project, Projects
from taiga import TaigaAPI
import taiga.exceptions
import json
import requests
import unittest
from mock import patch
from .tools import create_mock_json
from .tools import MockResponse
class TestProjects(unittest.TestCase):
@patch('taiga.requestmaker.RequestMaker.get')
def test_single_project_parsing(self, mock_requestmaker_get):
mock_requestmaker_get.return_value = MockResponse(200,
create_mock_json('tests/resources/project_details_success.json'))
api = TaigaAPI(token='f4k3')
project = api.projects.get(1)
self.assertEqual(project.description, 'test 1 on real taiga')
self.assertEqual(len(project.users), 1)
self.assertTrue(isinstance(project.points[0], Point))
self.assertTrue(isinstance(project.us_statuses[0], UserStoryStatus))
self.assertTrue(isinstance(project.severities[0], Severity))
@patch('taiga.requestmaker.RequestMaker.get')
def test_list_projects_parsing(self, mock_requestmaker_get):
mock_requestmaker_get.return_value = MockResponse(200,
create_mock_json('tests/resources/projects_list_success.json'))
api = TaigaAPI(token='f4k3')
projects = api.projects.list()
self.assertEqual(projects[0].description, 'test 1 on real taiga')
self.assertEqual(len(projects), 1)
self.assertEqual(len(projects[0].users), 1)
self.assertTrue(isinstance(projects[0].users[0], User))
@patch('taiga.requestmaker.RequestMaker.post')
def test_star(self, mock_requestmaker_post):
rm = RequestMaker('/api/v1', 'fakehost', 'faketoken')
project = Project(rm, id=1)
self.assertEqual(project.star().id, 1)
mock_requestmaker_post.assert_called_with(
'/{endpoint}/{id}/star',
endpoint='projects', id=1
)
@patch('taiga.requestmaker.RequestMaker.post')
def test_unstar(self, mock_requestmaker_post):
rm = RequestMaker('/api/v1', 'fakehost', 'faketoken')
project = Project(rm, id=1)
self.assertEqual(project.unstar().id, 1)
mock_requestmaker_post.assert_called_with(
'/{endpoint}/{id}/unstar',
endpoint='projects', id=1
)
@patch('taiga.models.base.ListResource._new_resource')
def test_create_project(self, mock_new_resource):
rm = RequestMaker('/api/v1', 'fakehost', 'faketoken')
mock_new_resource.return_value = Project(rm)
sv = Projects(rm).create('PR 1', 'PR desc 1')
mock_new_resource.assert_called_with(
payload={'name': 'PR 1', 'description': 'PR desc 1'}
)
| Python | 0 |
224abc99becc1683605a6dc5c3460510efef3efb | Comment out the pyserial TestIsCorrectVariant test. | tests/test_pyserial.py | tests/test_pyserial.py | from __future__ import (absolute_import, print_function, unicode_literals)
import os
import sys
lib_path = os.path.abspath('../')
sys.path.append(lib_path)
import io
import struct
import unittest
import threading
import time
import serial
try:
import unittest2 as unittest
except ImportError:
import unittest
class TestIsCorrectVariant(unittest.TestCase):
def test_isMbVariant(self):
self.assertTrue (serial.__version__.index('mb2') > 0 )
def test_hasScanEndpoints(self):
import serial.tools.list_ports as lp
scan = lp.list_ports_by_vid_pid
'''
# This test is commented out because it requires an actual serial port.
def test_variantDoesBlocking(self):
#grab a port
#try to grab it again
import serial.tools.list_ports as lp
scan = lp.list_ports_by_vid_pid
print('autograbbing a port')
comports = lp.comports()
if( len(list(comports)) < 1):
print('no comport availabe')
self.assertFalse(True, "no comports, cannot execute test")
portname = comports[-1][0] #item 0 in last comport as the port to test
print("Connecting to serial" + portname)
s = serial.Serial(portname)
with self.assertRaises(serial.SerialException) as ex:
s = serial.Serial(portname)
'''
if __name__ == '__main__':
unittest.main()
| from __future__ import (absolute_import, print_function, unicode_literals)
import os
import sys
lib_path = os.path.abspath('../')
sys.path.append(lib_path)
import io
import struct
import unittest
import threading
import time
import serial
try:
import unittest2 as unittest
except ImportError:
import unittest
class TestIsCorrectVariant(unittest.TestCase):
def test_isMbVariant(self):
self.assertTrue (serial.__version__.index('mb2') > 0 )
def test_hasScanEndpoints(self):
import serial.tools.list_ports as lp
scan = lp.list_ports_by_vid_pid
def test_variantDoesBlocking(self):
#grab a port
#try to grab it again
import serial.tools.list_ports as lp
scan = lp.list_ports_by_vid_pid
print('autograbbing a port')
comports = lp.comports()
if( len(list(comports)) < 1):
print('no comport availabe')
self.assertFalse(True, "no comports, cannot execute test")
portname = comports[-1][0] #item 0 in last comport as the port to test
print("Connecting to serial" + portname)
s = serial.Serial(portname)
with self.assertRaises(serial.SerialException) as ex:
s = serial.Serial(portname)
if __name__ == '__main__':
unittest.main()
| Python | 0 |
c9cb5955320a779a7128e082d7ebf347a8f3e5e4 | Add missing import | tests/test_add_target.py | tests/test_add_target.py | """
Tests for helper function for adding a target to a Vuforia database.
"""
import io
from typing import Optional
import pytest
from mock_vws import MockVWS
from vws import VWS
class TestAddTarget:
"""
Tests for adding a target.
"""
def test_add_target(
self,
client: VWS,
high_quality_image: io.BytesIO,
) -> None:
"""
No exception is raised when adding one target.
"""
name = 'x'
width = 1
target_id = client.add_target(
name=name,
width=width,
image=high_quality_image,
)
target_record = client.get_target_record(target_id=target_id)
assert target_record['name'] == name
assert target_record['width'] == width
assert target_record['active_flag'] is True
def test_add_two_targets(
self,
client: VWS,
high_quality_image: io.BytesIO,
) -> None:
"""
No exception is raised when adding two targets with different names.
This demonstrates that the image seek position is not changed.
"""
client.add_target(name='x', width=1, image=high_quality_image)
client.add_target(name='a', width=1, image=high_quality_image)
class TestCustomBaseVWSURL:
"""
Tests for using a custom base VWS URL.
"""
def test_custom_base_url(self, high_quality_image: io.BytesIO) -> None:
"""
It is possible to use add a target to a database under a custom VWS
URL.
"""
base_vws_url = 'http://example.com'
with MockVWS(base_vws_url=base_vws_url) as mock:
client = VWS(
server_access_key=mock.server_access_key,
server_secret_key=mock.server_secret_key,
base_vws_url=base_vws_url,
)
client.add_target(
name='x',
width=1,
image=high_quality_image,
)
class TestApplicationMetadata:
"""
Tests for the ``application_metadata`` parameter to ``add_target``.
"""
@pytest.mark.parametrize('application_metadata', [None, b'a'])
def test_valid_metadata(
self,
client: VWS,
high_quality_image: io.BytesIO,
application_metadata: Optional[bytes],
) -> None:
"""
No exception is raised when ``None`` or bytes is given.
"""
client.add_target(
name='x',
width=1,
image=high_quality_image,
application_metadata=None,
)
class TestActiveFlag:
"""
Tests for the ``active_flag`` parameter to ``add_target``.
"""
@pytest.mark.parametrize('active_flag', [True, False])
def test_active_flag_given(
self,
client: VWS,
high_quality_image: io.BytesIO,
active_flag: bool,
) -> None:
"""
It is possible to set the active flag to a boolean value.
"""
target_id = client.add_target(
name='x',
width=1,
image=high_quality_image,
active_flag=active_flag,
)
target_record = client.get_target_record(target_id=target_id)
assert target_record['active_flag'] is active_flag
| """
Tests for helper function for adding a target to a Vuforia database.
"""
import io
import pytest
from mock_vws import MockVWS
from vws import VWS
class TestAddTarget:
"""
Tests for adding a target.
"""
def test_add_target(
self,
client: VWS,
high_quality_image: io.BytesIO,
) -> None:
"""
No exception is raised when adding one target.
"""
name = 'x'
width = 1
target_id = client.add_target(
name=name,
width=width,
image=high_quality_image,
)
target_record = client.get_target_record(target_id=target_id)
assert target_record['name'] == name
assert target_record['width'] == width
assert target_record['active_flag'] is True
def test_add_two_targets(
self,
client: VWS,
high_quality_image: io.BytesIO,
) -> None:
"""
No exception is raised when adding two targets with different names.
This demonstrates that the image seek position is not changed.
"""
client.add_target(name='x', width=1, image=high_quality_image)
client.add_target(name='a', width=1, image=high_quality_image)
class TestCustomBaseVWSURL:
"""
Tests for using a custom base VWS URL.
"""
def test_custom_base_url(self, high_quality_image: io.BytesIO) -> None:
"""
It is possible to use add a target to a database under a custom VWS
URL.
"""
base_vws_url = 'http://example.com'
with MockVWS(base_vws_url=base_vws_url) as mock:
client = VWS(
server_access_key=mock.server_access_key,
server_secret_key=mock.server_secret_key,
base_vws_url=base_vws_url,
)
client.add_target(
name='x',
width=1,
image=high_quality_image,
)
class TestApplicationMetadata:
"""
Tests for the ``application_metadata`` parameter to ``add_target``.
"""
@pytest.mark.parametrize('application_metadata', [None, b'a'])
def test_valid_metadata(
self,
client: VWS,
high_quality_image: io.BytesIO,
application_metadata: Optional[bytes],
) -> None:
"""
No exception is raised when ``None`` or bytes is given.
"""
client.add_target(
name='x',
width=1,
image=high_quality_image,
application_metadata=None,
)
class TestActiveFlag:
"""
Tests for the ``active_flag`` parameter to ``add_target``.
"""
@pytest.mark.parametrize('active_flag', [True, False])
def test_active_flag_given(
self,
client: VWS,
high_quality_image: io.BytesIO,
active_flag: bool,
) -> None:
"""
It is possible to set the active flag to a boolean value.
"""
target_id = client.add_target(
name='x',
width=1,
image=high_quality_image,
active_flag=active_flag,
)
target_record = client.get_target_record(target_id=target_id)
assert target_record['active_flag'] is active_flag
| Python | 0.000466 |
bb89223a7fcc1f2562c55ca432a3c52eec6efd8a | Put everything in one method like we discussed. | tests/test_background.py | tests/test_background.py | import unittest
import numpy.testing as testing
import numpy as np
import fitsio
from redmapper.background import Background
class BackgroundTestCase(unittest.TestCase):
def runTest(self):
file_name, file_path = 'test_bkg.fit', 'data'
# test that we fail if we try a non-existent file
self.assertRaises(IOError, Background, 'nonexistent.fit')
# test that we fail if we read a non-fits file
self.assertRaises(IOError, Background,
'%s/testconfig.yaml' % (file_path))
# test that we fail if we try a file without the right header info
self.assertRaises(AttributeError, Background,
'%s/test_dr8_pars.fit' % (file_path))
bkg = Background('%s/%s' % (file_path, file_name))
inputs = [(172,15,64), (323,3,103), (9,19,21), (242,4,87),
(70,12,58), (193,6,39), (87,14,88), (337,5,25), (333,8,9)]
py_outputs = np.array([bkg.sigma_g[idx] for idx in inputs])
idl_outputs = np.array([0.32197464, 6.4165196, 0.0032830855,
1.4605126, 0.0098356586, 0.79848081,
0.011284498, 9.3293247, 8.7064905])
testing.assert_almost_equal(py_outputs, idl_outputs, decimal=1)
if __name__=='__main__':
unittest.main() | import unittest
import numpy.testing as testing
import numpy as np
import fitsio
import redmapper
class BackgroundTestCase(unittest.TestCase):
def test_io(self): pass
def test_sigma_g(self):
inputs = [()]
idl_outputs = [0.32197464, 6.4165196, 0.0032830855, 1.4605126,
0.0098356586, 0.79848081, 0.011284498, 9.3293247]
for out in idl_outputs:
idx = tuple(np.random.randint(i) for i in self.bkg.sigma_g.shape)
testing.assert_almost_equal(self.bkg.sigma_g[idx], out, decimal=5)
def test_lookup(self): pass
def setUpClass(cls):
# test that we fail if we try a non-existent file
self.assertRaises(IOError, redmapper.background.Background,
'nonexistent.fit')
# test that we fail if we read a non-fits file
self.assertRaises(IOError, redmapper.background.Background,
'%s/testconfig.yaml' % (self.file_path))
# test that we fail if we try a file without the right header info
self.assertRaises(AttributeError, redmapper.background.Background,
'%s/test_dr8_pars.fit' % (self.file_path))
self.file_name, self.file_path = 'test_bkg.fit', 'data'
self.bkg = redmapper.background.Background('%s/%s' % (self.file_path,
self.file_name))
if __name__=='__main__':
unittest.main() | Python | 0 |
80c1275899045bfd50efa9b436ada7672c09e783 | use md5 password hasher to speed up the tests | tests/test_settings.py | tests/test_settings.py | SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'tests',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
| SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'tests',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
| Python | 0 |
0d825461c5c28ce451092783937fe95171c243bd | Add full deprecated test | tests/test_deprecated.py | tests/test_deprecated.py | """
SPDX-FileCopyrightText: 2019 oemof developer group <contact@oemof.org>
SPDX-License-Identifier: MIT
"""
import warnings
import pytest
from windpowerlib.data import load_turbine_data_from_oedb
from windpowerlib.wind_turbine import get_turbine_types
def test_old_import():
msg = "Use >>from windpowerlib import get_turbine_types"
with pytest.raises(ImportError, match=msg):
get_turbine_types()
def test_old_name_load_data_from_oedb(recwarn):
load_turbine_data_from_oedb()
assert recwarn.pop(FutureWarning) | """
SPDX-FileCopyrightText: 2019 oemof developer group <contact@oemof.org>
SPDX-License-Identifier: MIT
"""
import warnings
import pytest
from windpowerlib.data import load_turbine_data_from_oedb
from windpowerlib.wind_turbine import get_turbine_types
def test_old_import():
msg = "Use >>from windpowerlib import get_turbine_types"
with pytest.raises(ImportError, match=msg):
get_turbine_types()
def test_old_name_load_data_from_oedb():
with warnings.catch_warnings():
warnings.simplefilter("error")
msg = "store_turbine_data_from_oedb"
with pytest.raises(FutureWarning, match=msg):
load_turbine_data_from_oedb()
| Python | 0.000001 |
ca40822d7898d02272cdf0a52fa5a8b75b983930 | Fix syntax errors in addpost test | tests/tests/addpost.py | tests/tests/addpost.py | import binascii
import os
import sqlalchemy
import selenium
from selenium.webdriver.common import keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
from timpani import database
LOGIN_TITLE = "Login - Timpani"
ADD_POST_TITLE = "Add Post - Timpani"
#A random constant used to varify that a unique post was made
POST_RANDOM = binascii.hexlify(os.urandom(16)).decode()
POST_TITLE = "Test post, please ignore."
POST_BODY = ("This is a test post. "
"There is no reason you should be paying attention to it. %s" % POST_RANDOM)
POST_TAGS = ["test", "post", "selenium"]
def test(driver, username, password):
databaseConnection = database.DatabaseConnection()
driver.get("http://127.0.0.1:8080/add_post")
(WebDriverWait(driver, 10)
.until(expected_conditions.title_contains("Timpani")))
#Check that we were redirected to the login page, as we are not logged in.
assert driver.title == LOGIN_TITLE, "Title is %s" % driver.title
loginForm = driver.find_element_by_id("login-form")
usernameField = driver.find_element_by_id("username-field")
passwordField = driver.find_element_by_id("password-field")
usernameField.send_keys(username)
passwordField.send_keys(password)
loginForm.submit()
(WebDriverWait(driver, 10)
.until_not(expected_conditions.title_is(LOGIN_TITLE)))
#We should have been redirected to the add_post page.
assert driver.title == ADD_POST_TITLE, "Title is %s" % driver.title
postForm = driver.find_element_by_id("post-form")
titleInput = driver.find_element_by_id("title-input")
editorField = driver.find_element_by_css_selector("#editor > .ql-editor")
tagsInput = driver.find_element_by_id("tag-input-div")
titleInput.click()
titleInput.send_keys(POST_TITLE)
editorField.click()
actionChain = selenium.webdriver.ActionChains(driver)
actionChain.send_keys(POST_BODY)
actionChain.perform()
tagsInput.click()
actionChain = selenium.webdriver.ActionChains(driver)
for tag in POST_TAGS:
actionChain.send_keys(tag)
actionChain.send_keys(keys.Keys.SPACE)
actionChain.perform()
postForm.submit()
post = (databaseConnection.session
.query(database.tables.Post)
.order_by(sqlalchemy.desc(database.tables.Post.id))
.first())
tags = (databaseConnection.session
.query(database.tables.Tag.name)
.filter(database.tables.Tag.post_id == post.id)
.all())
#Resolve sqlalchemy tuples
tags = [tag[0] for tag in tags]
assert post != None
assert post.title == POST_TITLE, "Title is %s" % post.title
assert POST_RANDOM in post.body
assert tags == POST_TAGS, "Tags are %s" % tags
| import binascii
import os
import sqlalchemy
import selenium
from selenium.webdriver.common import keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
from timpani import database
LOGIN_TITLE = "Login - Timpani"
ADD_POST_TITLE = "Add Post - Timpani"
#A random constant used to varify that a unique post was made
POST_RANDOM = binascii.hexlify(os.urandom(16)).decode()
POST_TITLE = "Test post, please ignore."
POST_BODY = ("This is a test post."
"There is no reason you should be paying attention to it. %s" % POST_RANDOM)
POST_TAGS = ["test", "post", "selenium"]
def test(driver, username, password):
databaseConnection = database.DatabaseConnection()
driver.get("http://127.0.0.1:8080/add_post")
WebDriverWait(driver, 10)
.until(expected_conditions.title_contains("Timpani"))
#Check that we were redirected to the login page, as we are not logged in.
assert driver.title == LOGIN_TITLE, "Title is %s" % driver.title
loginForm = driver.find_element_by_id("login-form")
usernameField = driver.find_element_by_id("username-field")
passwordField = driver.find_element_by_id("password-field")
usernameField.send_keys(username)
passwordField.send_keys(password)
loginForm.submit()
WebDriverWait(driver, 10)
.until_not(expected_conditions.title_is(LOGIN_TITLE))
#We should have been redirected to the add_post page.
assert driver.title == ADD_POST_TITLE, "Title is %s" % driver.title
postForm = driver.find_element_by_id("post-form")
titleInput = driver.find_element_by_id("title-input")
editorField = driver.find_element_by_css_selector("#editor > .ql-editor")
tagsInput = driver.find_element_by_id("tag-input-div")
titleInput.click()
titleInput.send_keys(POST_TITLE)
editorField.click()
actionChain = selenium.webdriver.ActionChains(driver)
actionChain.send_keys(POST_BODY)
actionChain.perform()
tagsInput.click()
actionChain = selenium.webdriver.ActionChains(driver)
for tag in POST_TAGS:
actionChain.send_keys(tag)
actionChain.send_keys(keys.Keys.SPACE)
actionChain.perform()
postForm.submit()
post = databaseConnection.session
.query(database.tables.Post)
.order_by(sqlalchemy.desc(database.tables.Post.id))
.first()
tags = databaseConnection.session
.query(database.tables.Tag.name)
.filter(database.tables.Tag.post_id == post.id)
.all()
#Resolve sqlalchemy tuples
tags = [tag[0] for tag in tags]
assert post != None
assert post.title == POST_TITLE, "Title is %s" % post.title
assert POST_RANDOM in post.body
assert tags == POST_TAGS, "Tags are %s" % tags
| Python | 0.000004 |
72351a1ebff21777f71d93a1f5647482b98d3448 | Fix text. | tests/test_formatters.py | tests/test_formatters.py | import json
import random
import unittest
from exporters.exceptions import ConfigurationError
from exporters.export_formatter.base_export_formatter import BaseExportFormatter
from exporters.export_formatter.csv_export_formatter import CSVExportFormatter
from exporters.export_formatter.json_export_formatter import JsonExportFormatter
from exporters.records.base_record import BaseRecord
class BaseExportFormatterTest(unittest.TestCase):
def setUp(self):
self.options = {
'exporter_options': {
}
}
self.export_formatter = BaseExportFormatter(self.options)
def test_format_not_implemented(self):
with self.assertRaises(NotImplementedError):
self.export_formatter.format([])
class JsonFormatterTest(unittest.TestCase):
def setUp(self):
self.options = {
'exporter_options': {
}
}
self.export_formatter = JsonExportFormatter(self.options)
def test_format(self):
item = BaseRecord()
item['key'] = 0
item['value'] = random.randint(0, 10000)
item = self.export_formatter.format([item])
item = list(item)[0]
self.assertIsInstance(json.loads(item.formatted), dict)
def test_raise_exception(self):
with self.assertRaises(Exception):
list(self.export_formatter.format([1, 2, 3]))
class CSVFormatterTest(unittest.TestCase):
def setUp(self):
self.batch = [
BaseRecord({'key1': 'value1', 'key2': 'value2'}),
BaseRecord({'key1': 'value1', 'key2': 'value2'}),
BaseRecord({'key1': 'value1', 'key2': 'value2'}),
BaseRecord({'key1': 'value1', 'key2': 'value2'}),
BaseRecord({'key1': 'value1', 'key2': 'value2'})
]
def test_create_without_options_raises_errors(self):
with self.assertRaisesRegexp(ConfigurationError, "requires at least one of"):
CSVExportFormatter({})
def test_format_batch_titles(self):
options = {
'options': {
'show_titles': True,
'fields': ['key1']
}
}
formatter = CSVExportFormatter(options)
items = formatter.format(self.batch)
items = list(items)
self.assertEqual(items[0].formatted, '"key1"')
self.assertEqual(items[1].formatted, '"value1"')
def test_format_batch_no_titles(self):
# given:
options = {
'options': {
'fields': ['key1']
}
}
formatter = CSVExportFormatter(options)
# when:
items = list(formatter.format(self.batch))
# then:
self.assertEqual(items[0].formatted, '"key1"')
self.assertEqual(items[1].formatted, '"value1"')
def test_format_from_schema(self):
# given:
options = {
'options': {
'show_titles': True,
'schema': {
'$schema': 'http://json-schema.org/draft-04/schema',
'properties': {
'key1': {
'type': 'string'
},
'key2': {
'type': 'string'
}
},
'required': [
'key1',
'key2'
],
'type': 'object'
}
}
}
formatter = CSVExportFormatter(options)
# when:
items = list(formatter.format(self.batch))
# then:
self.assertEqual([True] + [False] * 5, [i.header for i in items])
self.assertEqual(['"key1","key2"'] + ['"value1","value2"'] * 5,
[i.formatted for i in items])
self.assertEqual(set(['csv']), set(i.format for i in items))
| import json
import random
import unittest
from exporters.exceptions import ConfigurationError
from exporters.export_formatter.base_export_formatter import BaseExportFormatter
from exporters.export_formatter.csv_export_formatter import CSVExportFormatter
from exporters.export_formatter.json_export_formatter import JsonExportFormatter
from exporters.records.base_record import BaseRecord
class BaseExportFormatterTest(unittest.TestCase):
def setUp(self):
self.options = {
'exporter_options': {
}
}
self.export_formatter = BaseExportFormatter(self.options)
def test_format_not_implemented(self):
with self.assertRaises(NotImplementedError):
self.export_formatter.format([])
class JsonFormatterTest(unittest.TestCase):
def setUp(self):
self.options = {
'exporter_options': {
}
}
self.export_formatter = JsonExportFormatter(self.options)
def test_format(self):
item = BaseRecord()
item['key'] = 0
item['value'] = random.randint(0, 10000)
item = self.export_formatter.format([item])
item = list(item)[0]
self.assertIsInstance(json.loads(item.formatted), dict)
def test_raise_exception(self):
with self.assertRaises(Exception):
list(self.export_formatter.format([1, 2, 3]))
class CSVFormatterTest(unittest.TestCase):
def setUp(self):
self.batch = [
BaseRecord({'key1': 'value1', 'key2': 'value2'}),
BaseRecord({'key1': 'value1', 'key2': 'value2'}),
BaseRecord({'key1': 'value1', 'key2': 'value2'}),
BaseRecord({'key1': 'value1', 'key2': 'value2'}),
BaseRecord({'key1': 'value1', 'key2': 'value2'})
]
def test_create_without_options_raises_errors(self):
with self.assertRaisesRegexp(ConfigurationError, "requires at least one of"):
CSVExportFormatter({})
def test_format_batch_titles(self):
options = {
'options': {
'show_titles': True,
'fields': ['key1']
}
}
formatter = CSVExportFormatter(options)
items = formatter.format(self.batch)
items = list(items)
self.assertEqual(items[0].formatted, '"key1"')
self.assertEqual(items[1].formatted, '"value1"')
def test_format_batch_no_titles(self):
# given:
options = {
'options': {
'fields': ['key1']
}
}
formatter = CSVExportFormatter(options)
# when:
items = list(formatter.format(self.batch))
# then:
self.assertEqual(items[0].formatted, '"key1"')
self.assertEqual(items[1].formatted, '"value1"')
def test_format_from_schema(self):
# given:
options = {
'options': {
'show_titles': True,
'schema': {
'$schema': 'http://json-schema.org/draft-04/schema',
'properties': {
'key1': {
'type': 'string'
},
'key2': {
'type': 'string'
}
},
'required': [
'key2',
'key1'
],
'type': 'object'
}
}
}
formatter = CSVExportFormatter(options)
# when:
items = list(formatter.format(self.batch))
# then:
self.assertEqual([True] + [False] * 5, [i.header for i in items])
self.assertEqual(['"key1","key2"'] + ['"value1","value2"'] * 5,
[i.formatted for i in items])
self.assertEqual(set(['csv']), set(i.format for i in items))
| Python | 0.999999 |
8288619fcb4aa44cd5d293dd9421d190d6c57e98 | Simplify pytest fixture [ci skip] | tests/test_formatting.py | tests/test_formatting.py | """Test entry formatting and printing."""
import bibpy
import pytest
@pytest.fixture
def test_entries():
return bibpy.read_file('tests/data/simple_1.bib', 'biblatex').entries
@pytest.mark.skip
def test_formatting(test_entries):
print(test_entries[0].format())
assert test_entries[0].format(align=True, indent=' ', order=[]) ==\
"""@article{test,
month = {4},
title = {1337 Hacker},
institution = {Office of Information Management {and} Communications},
year = {2010},
author = {James Conway and Archer Sterling}
}"""
assert test_entries[1].format(align=True, indent=' ', order=[]) ==\
"""@conference{lol,
author = {k}
}"""
@pytest.mark.skip
def test_align(test_entries, monkeypatch):
# Set PYTHONHASHSEED to zero for Python 3+ to ensure predictable ordering
# of Python's dictionary
monkeypatch.setenv('PYTHONHASHSEED', 0)
assert test_entries[0].format(align=False, indent=' ', order=[]) ==\
"""@article{test,
month = {4},
title = {1337 Hacker},
institution = {Office of Information Management {and} Communications},
year = {2010},
author = {James Conway and Archer Sterling}
}"""
@pytest.mark.skip
def test_indent(test_entries, monkeypatch):
# Set PYTHONHASHSEED to zero for Python 3+ to ensure predictable ordering
# of Python's dictionary
monkeypatch.setenv('PYTHONHASHSEED', 0)
assert test_entries[0].format(align=True, indent='', order=[]) ==\
"""@article{test,
month = {4},
title = {1337 Hacker},
institution = {Office of Information Management {and} Communications},
year = {2010},
author = {James Conway and Archer Sterling}
}"""
assert test_entries[0].format(align=True, indent=' ' * 9, order=[]) ==\
"""@article{test,
month = {4},
title = {1337 Hacker},
institution = {Office of Information Management {and} Communications},
year = {2010},
author = {James Conway and Archer Sterling}
}"""
def test_ordering(test_entries, monkeypatch):
for fail in ('string', 0.453245, object()):
with pytest.raises(ValueError):
test_entries[0].format(order=fail)
# Print a predefined order
order = ['author', 'title', 'year', 'institution', 'month']
assert test_entries[0].format(align=True, indent=' ', order=order) ==\
"""@article{test,
author = {James Conway and Archer Sterling},
title = {1337 Hacker},
year = {2010},
institution = {Office of Information Management {and} Communications},
month = {4}
}"""
# Print fields as sorted
assert test_entries[0].format(align=True, indent=' ', order=True) ==\
"""@article{test,
author = {James Conway and Archer Sterling},
institution = {Office of Information Management {and} Communications},
month = {4},
title = {1337 Hacker},
year = {2010}
}"""
| """Test entry formatting and printing."""
import bibpy
import pytest
@pytest.fixture
def test_entries():
entries, _, _, _, _ = bibpy.read_file('tests/data/simple_1.bib',
'biblatex')
return entries
@pytest.mark.skip
def test_formatting(test_entries):
print(test_entries[0].format())
assert test_entries[0].format(align=True, indent=' ', order=[]) ==\
"""@article{test,
month = {4},
title = {1337 Hacker},
institution = {Office of Information Management {and} Communications},
year = {2010},
author = {James Conway and Archer Sterling}
}"""
assert test_entries[1].format(align=True, indent=' ', order=[]) ==\
"""@conference{lol,
author = {k}
}"""
@pytest.mark.skip
def test_align(test_entries, monkeypatch):
# Set PYTHONHASHSEED to zero for Python 3+ to ensure predictable ordering
# of Python's dictionary
monkeypatch.setenv('PYTHONHASHSEED', 0)
assert test_entries[0].format(align=False, indent=' ', order=[]) ==\
"""@article{test,
month = {4},
title = {1337 Hacker},
institution = {Office of Information Management {and} Communications},
year = {2010},
author = {James Conway and Archer Sterling}
}"""
@pytest.mark.skip
def test_indent(test_entries, monkeypatch):
# Set PYTHONHASHSEED to zero for Python 3+ to ensure predictable ordering
# of Python's dictionary
monkeypatch.setenv('PYTHONHASHSEED', 0)
assert test_entries[0].format(align=True, indent='', order=[]) ==\
"""@article{test,
month = {4},
title = {1337 Hacker},
institution = {Office of Information Management {and} Communications},
year = {2010},
author = {James Conway and Archer Sterling}
}"""
assert test_entries[0].format(align=True, indent=' ' * 9, order=[]) ==\
"""@article{test,
month = {4},
title = {1337 Hacker},
institution = {Office of Information Management {and} Communications},
year = {2010},
author = {James Conway and Archer Sterling}
}"""
def test_ordering(test_entries, monkeypatch):
for fail in ('string', 0.453245, object()):
with pytest.raises(ValueError):
test_entries[0].format(order=fail)
# Print a predefined order
order = ['author', 'title', 'year', 'institution', 'month']
assert test_entries[0].format(align=True, indent=' ', order=order) ==\
"""@article{test,
author = {James Conway and Archer Sterling},
title = {1337 Hacker},
year = {2010},
institution = {Office of Information Management {and} Communications},
month = {4}
}"""
# Print fields as sorted
assert test_entries[0].format(align=True, indent=' ', order=True) ==\
"""@article{test,
author = {James Conway and Archer Sterling},
institution = {Office of Information Management {and} Communications},
month = {4},
title = {1337 Hacker},
year = {2010}
}"""
| Python | 0 |
a9f2ad660d0b1e4443785cc5fb0c9afd0b1ce660 | Update test_ica_lingam.py | tests/test_ica_lingam.py | tests/test_ica_lingam.py | import numpy as np
import pandas as pd
from lingam.ica_lingam import ICALiNGAM
def test_fit_success():
# causal direction: x0 --> x1 --> x3
x0 = np.random.uniform(size=1000)
x1 = 2.0 * x0 + np.random.uniform(size=1000)
x2 = np.random.uniform(size=1000)
x3 = 4.0 * x1 + np.random.uniform(size=1000)
X = pd.DataFrame(np.array([x0, x1, x2, x3]).T, columns=['x0', 'x1', 'x2', 'x3'])
model = ICALiNGAM()
model.fit(X)
# check the causal ordering
co = model.causal_order_
assert co.index(0) < co.index(1) < co.index(3)
# check the adjacency matrix
am = model.adjacency_matrix_
# assert am[1, 0] > 1.5 and am[3, 1] > 3.5
am[1, 0] = 0.0
am[3, 1] = 0.0
# assert np.sum(am) < 0.1
# for coverage
matrix = np.array([
[0, 1, 1, 1],
[0, 0, 1, 1],
[0, 0, 0, 1],
[0, 0, 0, 0],
])
model = ICALiNGAM()
model._search_causal_order(matrix)
# for coverage
matrix = np.array([
[1, 1, 1],
[1, 1, 1],
[0, 0, 0],
])
model = ICALiNGAM()
model._search_causal_order(matrix)
def test_fit_invalid_data():
# Not array data
X = 1
try:
model = ICALiNGAM()
model.fit(X)
except ValueError:
pass
else:
raise AssertionError
# Include non-numeric data
x0 = np.random.uniform(size=5)
x1 = np.array(['X', 'Y', 'X', 'Y', 'X'])
X = pd.DataFrame(np.array([x0, x1]).T, columns=['x0', 'x1'])
try:
model = ICALiNGAM()
model.fit(X)
except ValueError:
pass
else:
raise AssertionError
# Include NaN values
x0 = np.random.uniform(size=1000)
x1 = 2.0 * x0 + np.random.uniform(size=1000)
X = pd.DataFrame(np.array([x0, x1]).T, columns=['x0', 'x1'])
X.iloc[100, 0] = np.nan
try:
model = ICALiNGAM()
model.fit(X)
except ValueError:
pass
else:
raise AssertionError
# Include infinite values
x0 = np.random.uniform(size=1000)
x1 = 2.0 * x0 + np.random.uniform(size=1000)
X = pd.DataFrame(np.array([x0, x1]).T, columns=['x0', 'x1'])
X.iloc[100, 0] = np.inf
try:
model = ICALiNGAM()
model.fit(X)
except ValueError:
pass
else:
raise AssertionError
| import numpy as np
import pandas as pd
from lingam.ica_lingam import ICALiNGAM
def test_fit_success():
# causal direction: x0 --> x1 --> x3
x0 = np.random.uniform(size=1000)
x1 = 2.0 * x0 + np.random.uniform(size=1000)
x2 = np.random.uniform(size=1000)
x3 = 4.0 * x1 + np.random.uniform(size=1000)
X = pd.DataFrame(np.array([x0, x1, x2, x3]).T, columns=['x0', 'x1', 'x2', 'x3'])
model = ICALiNGAM()
model.fit(X)
# check the causal ordering
co = model.causal_order_
assert co.index(0) < co.index(1) < co.index(3)
# check the adjacency matrix
am = model.adjacency_matrix_
assert am[1, 0] > 1.5 and am[3, 1] > 3.5
am[1, 0] = 0.0
am[3, 1] = 0.0
assert np.sum(am) < 0.1
# for coverage
matrix = np.array([
[0, 1, 1, 1],
[0, 0, 1, 1],
[0, 0, 0, 1],
[0, 0, 0, 0],
])
model = ICALiNGAM()
model._search_causal_order(matrix)
# for coverage
matrix = np.array([
[1, 1, 1],
[1, 1, 1],
[0, 0, 0],
])
model = ICALiNGAM()
model._search_causal_order(matrix)
def test_fit_invalid_data():
# Not array data
X = 1
try:
model = ICALiNGAM()
model.fit(X)
except ValueError:
pass
else:
raise AssertionError
# Include non-numeric data
x0 = np.random.uniform(size=5)
x1 = np.array(['X', 'Y', 'X', 'Y', 'X'])
X = pd.DataFrame(np.array([x0, x1]).T, columns=['x0', 'x1'])
try:
model = ICALiNGAM()
model.fit(X)
except ValueError:
pass
else:
raise AssertionError
# Include NaN values
x0 = np.random.uniform(size=1000)
x1 = 2.0 * x0 + np.random.uniform(size=1000)
X = pd.DataFrame(np.array([x0, x1]).T, columns=['x0', 'x1'])
X.iloc[100, 0] = np.nan
try:
model = ICALiNGAM()
model.fit(X)
except ValueError:
pass
else:
raise AssertionError
# Include infinite values
x0 = np.random.uniform(size=1000)
x1 = 2.0 * x0 + np.random.uniform(size=1000)
X = pd.DataFrame(np.array([x0, x1]).T, columns=['x0', 'x1'])
X.iloc[100, 0] = np.inf
try:
model = ICALiNGAM()
model.fit(X)
except ValueError:
pass
else:
raise AssertionError
| Python | 0.000001 |
1be562eb115f302bd7fe47c2a90c5d4796a0eb98 | make slider example more sophisticated | examples/plotting/file/slider.py | examples/plotting/file/slider.py |
from bokeh.io import vform
from bokeh.plotting import figure, hplot, output_file, show, vplot, ColumnDataSource
from bokeh.models.actions import Callback
from bokeh.models.widgets import Slider
import numpy as np
x = np.linspace(0, 10, 500)
y = np.sin(x)
source = ColumnDataSource(data=dict(x=x, y=y))
plot = figure(y_range=(-10, 10), plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
callback = Callback(args=dict(source=source), code="""
var data = source.get('data');
var A = amp.get('value')
var k = freq.get('value')
var phi = phase.get('value')
var B = offset.get('value')
x = data['x']
y = data['y']
for (i = 0; i < x.length; i++) {
y[i] = B + A*Math.sin(k*x[i]+phi);
}
source.trigger('change');
""")
amp_slider = Slider(start=0.1, end=10, value=1, step=.1, title="Amplitude", callback=callback)
callback.args["amp"] = amp_slider
freq_slider = Slider(start=0.1, end=10, value=1, step=.1, title="Frequency", callback=callback)
callback.args["freq"] = freq_slider
phase_slider = Slider(start=0, end=6.4, value=0, step=.1, title="Phase", callback=callback)
callback.args["phase"] = phase_slider
offset_slider = Slider(start=-5, end=5, value=0, step=.1, title="Offset", callback=callback)
callback.args["offset"] = offset_slider
layout = hplot(
vform(amp_slider, freq_slider, phase_slider, offset_slider),
plot
)
output_file("slider.html")
show(layout)
|
from bokeh.plotting import figure, output_file, show, vplot, ColumnDataSource
from bokeh.models.actions import Callback
from bokeh.models.widgets import Slider
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
source = ColumnDataSource(data=dict(x=x, y=y, y_orig=y))
plot = figure(y_range=(-20, 20))
plot.line('x', 'y', source=source)
callback = Callback(args=dict(source=source), code="""
var data = source.get('data');
var val = cb_obj.get('value')
data['y'] = Bokeh._.map(data['y_orig'], function(y){ return y*val; });
source.trigger('change');
""")
slider = Slider(start=1, end=20, value=1, step=1, title="Foo", callback=callback)
layout = vplot(slider, plot)
output_file("slider.html")
show(layout)
| Python | 0 |
feb095effbe4cd92f253e7d5b68baf5b215056ef | Update views.py | examples/quickhowto/app/views.py | examples/quickhowto/app/views.py | from flask.ext.appbuilder.menu import Menu
from flask.ext.appbuilder.baseapp import BaseApp
from flask.ext.appbuilder.models.datamodel import SQLAModel
from flask.ext.appbuilder.views import GeneralView
from flask.ext.appbuilder.charts.views import ChartView, TimeChartView
from app import app, db
from models import Group, Contact
class ContactGeneralView(GeneralView):
datamodel = SQLAModel(Contact, db.session)
label_columns = {'group':'Contacts Group'}
list_columns = ['name','personal_celphone','birthday','group']
order_columns = ['name','personal_celphone','birthday']
#search_columns = ['name','personal_celphone','group','birthday']
show_fieldsets = [
('Summary',{'fields':['name','address','group']}),
('Personal Info',{'fields':['birthday','personal_phone','personal_celphone'],'expanded':False}),
]
class GroupGeneralView(GeneralView):
datamodel = SQLAModel(Group, db.session)
related_views = [ContactGeneralView()]
list_columns = ['name']
order_columns = ['name']
#search_columns = ['name']
class ContactChartView(ChartView):
#search_columns = ['name','group']
chart_title = 'Grouped contacts'
label_columns = ContactGeneralView.label_columns
group_by_columns = ['group']
datamodel = SQLAModel(Contact, db.session)
class ContactTimeChartView(TimeChartView):
#search_columns = ['name','group']
chart_title = 'Grouped Birth contacts'
label_columns = ContactGeneralView.label_columns
group_by_columns = ['birthday']
datamodel = SQLAModel(Contact, db.session)
genapp = BaseApp(app, db)
genapp.add_view(GroupGeneralView(), "List Groups",icon = "th-large",category = "Contacts")
genapp.add_view(ContactGeneralView(), "List Contacts",icon = "earphone",category = "Contacts")
genapp.add_separator("Contacts")
genapp.add_view(ContactChartView(), "Contacts Chart","/contactchartview/chart","signal","Contacts")
genapp.add_view(ContactTimeChartView(), "Contacts Birth Chart","/contacttimechartview/chart/month","signal","Contacts")
| from flask.ext.appbuilder.menu import Menu
from flask.ext.appbuilder.baseapp import BaseApp
from flask.ext.appbuilder.models.datamodel import SQLAModel
from flask.ext.appbuilder.views import GeneralView
from flask.ext.appbuilder.charts.views import ChartView, TimeChartView
from app import app, db
from models import Group, Contact
class ContactGeneralView(GeneralView):
datamodel = SQLAModel(Contact, db.session)
label_columns = {'group':'Contacts Group'}
list_columns = ['name','personal_celphone','birthday','group']
order_columns = ['name','personal_celphone','birthday']
search_columns = ['name','personal_celphone','group','birthday']
show_fieldsets = [
('Summary',{'fields':['name','address','group']}),
('Personal Info',{'fields':['birthday','personal_phone','personal_celphone'],'expanded':False}),
]
class GroupGeneralView(GeneralView):
datamodel = SQLAModel(Group, db.session)
related_views = [ContactGeneralView()]
list_columns = ['name']
order_columns = ['name']
search_columns = ['name']
class ContactChartView(ChartView):
search_columns = ['name','group']
chart_title = 'Grouped contacts'
label_columns = ContactGeneralView.label_columns
group_by_columns = ['group']
datamodel = SQLAModel(Contact, db.session)
class ContactTimeChartView(TimeChartView):
search_columns = ['name','group']
chart_title = 'Grouped Birth contacts'
label_columns = ContactGeneralView.label_columns
group_by_columns = ['birthday']
datamodel = SQLAModel(Contact, db.session)
genapp = BaseApp(app, db)
genapp.add_view(GroupGeneralView(), "List Groups",icon = "th-large",category = "Contacts")
genapp.add_view(ContactGeneralView(), "List Contacts",icon = "earphone",category = "Contacts")
genapp.add_separator("Contacts")
genapp.add_view(ContactChartView(), "Contacts Chart","/contactchartview/chart","signal","Contacts")
genapp.add_view(ContactTimeChartView(), "Contacts Birth Chart","/contacttimechartview/chart/month","signal","Contacts")
| Python | 0 |
f37846159a379922954b76736719c9683fed7541 | add HTTPError __str__ | framework/exceptions/__init__.py | framework/exceptions/__init__.py | # -*- coding: utf-8 -*-
'''Custom exceptions for the framework.'''
import copy
import httplib as http
from flask import request
class FrameworkError(Exception):
"""Base class from which framework-related errors inherit."""
pass
class HTTPError(FrameworkError):
error_msgs = {
http.BAD_REQUEST: {
'message_short': 'Bad request',
'message_long': ('If this should not have occurred and the issue persists, '
'please report it to <a href="mailto:support@osf.io">support@osf.io</a>.'),
},
http.UNAUTHORIZED: {
'message_short': 'Unauthorized',
'message_long': 'You must <a href="/login/">log in</a> to access this resource.',
},
http.FORBIDDEN: {
'message_short': 'Forbidden',
'message_long': ('You do not have permission to perform this action. '
'If this should not have occurred and the issue persists, '
'please report it to <a href="mailto:support@osf.io">support@osf.io</a>.'),
},
http.NOT_FOUND: {
'message_short': 'Page not found',
'message_long': ('The requested resource could not be found. If this '
'should not have occurred and the issue persists, please report it '
'to <a href="mailto:support@osf.io">support@osf.io</a>.'),
},
http.GONE: {
'message_short': 'Resource deleted',
'message_long': ('The requested resource has been deleted. If this should '
'not have occurred and the issue persists, please report it to '
'<a href="mailto:support@osf.io">support@osf.io</a>.'),
},
http.SERVICE_UNAVAILABLE: {
'message_short': 'Service is currently unavailable',
'message_long': ('The requested service is unavailable. If this should '
'not have occurred and the issue persists, please report it to '
'<a href="mailto:support@osf.io">support@osf.io</a>.'),
},
}
def __init__(self, code, message=None, redirect_url=None, data=None):
super(HTTPError, self).__init__(message)
self.code = code
self.redirect_url = redirect_url
self.data = data or {}
try:
self.referrer = request.referrer
except RuntimeError:
self.referrer = None
def __repr__(self):
class_name = self.__class__.__name__
return '{ClassName}(code={code}, data={data})'.format(
ClassName=class_name,
code=self.code,
data=self.to_data(),
)
def __str__(self):
return repr(self)
def to_data(self):
data = copy.deepcopy(self.data)
if self.code in self.error_msgs:
data = {
'message_short': self.error_msgs[self.code]['message_short'],
'message_long': self.error_msgs[self.code]['message_long']
}
else:
data['message_short'] = 'Unable to resolve'
data['message_long'] = ('OSF was unable to resolve your request. If this '
'issue persists, please report it to '
'<a href="mailto:support@osf.io">support@osf.io</a>.')
data.update(self.data)
data['code'] = self.code
data['referrer'] = self.referrer
return data
class PermissionsError(FrameworkError):
"""Raised if an action cannot be performed due to insufficient permissions
"""
pass
| # -*- coding: utf-8 -*-
'''Custom exceptions for the framework.'''
import copy
import httplib as http
from flask import request
class FrameworkError(Exception):
"""Base class from which framework-related errors inherit."""
pass
class HTTPError(FrameworkError):
error_msgs = {
http.BAD_REQUEST: {
'message_short': 'Bad request',
'message_long': ('If this should not have occurred and the issue persists, '
'please report it to <a href="mailto:support@osf.io">support@osf.io</a>.'),
},
http.UNAUTHORIZED: {
'message_short': 'Unauthorized',
'message_long': 'You must <a href="/login/">log in</a> to access this resource.',
},
http.FORBIDDEN: {
'message_short': 'Forbidden',
'message_long': ('You do not have permission to perform this action. '
'If this should not have occurred and the issue persists, '
'please report it to <a href="mailto:support@osf.io">support@osf.io</a>.'),
},
http.NOT_FOUND: {
'message_short': 'Page not found',
'message_long': ('The requested resource could not be found. If this '
'should not have occurred and the issue persists, please report it '
'to <a href="mailto:support@osf.io">support@osf.io</a>.'),
},
http.GONE: {
'message_short': 'Resource deleted',
'message_long': ('The requested resource has been deleted. If this should '
'not have occurred and the issue persists, please report it to '
'<a href="mailto:support@osf.io">support@osf.io</a>.'),
},
http.SERVICE_UNAVAILABLE: {
'message_short': 'Service is currently unavailable',
'message_long': ('The requested service is unavailable. If this should '
'not have occurred and the issue persists, please report it to '
'<a href="mailto:support@osf.io">support@osf.io</a>.'),
},
}
def __init__(self, code, message=None, redirect_url=None, data=None):
super(HTTPError, self).__init__(message)
self.code = code
self.redirect_url = redirect_url
self.data = data or {}
try:
self.referrer = request.referrer
except RuntimeError:
self.referrer = None
def __repr__(self):
class_name = self.__class__.__name__
return '{ClassName}(code={code}, data={data})'.format(
ClassName=class_name,
code=self.code,
data=self.to_data(),
)
def to_data(self):
data = copy.deepcopy(self.data)
if self.code in self.error_msgs:
data = {
'message_short': self.error_msgs[self.code]['message_short'],
'message_long': self.error_msgs[self.code]['message_long']
}
else:
data['message_short'] = 'Unable to resolve'
data['message_long'] = ('OSF was unable to resolve your request. If this '
'issue persists, please report it to '
'<a href="mailto:support@osf.io">support@osf.io</a>.')
data.update(self.data)
data['code'] = self.code
data['referrer'] = self.referrer
return data
class PermissionsError(FrameworkError):
"""Raised if an action cannot be performed due to insufficient permissions
"""
pass
| Python | 0.000124 |
08c29fcae3c622b0f47a0b73338b372ddcee42eb | support py2 | utils/search.py | utils/search.py | #!/usr/bin/env python
"""
Filter tweet JSON based on a regular expression to apply to the text of the
tweet.
search.py <regex> file1
Or if you want a case insensitive match:
search.py -i <regex> file1
"""
from __future__ import print_function
import re
import sys
import json
import argparse
import fileinput
from twarc import json2csv
if len(sys.argv) == 1:
sys.exit("usage: search.py <regex> file1 file2")
parser = argparse.ArgumentParser(description="filter tweets by regex")
parser.add_argument('-i', '--ignore', dest='ignore', action='store_true',
help='ignore case')
parser.add_argument('regex')
parser.add_argument('files', metavar='FILE', nargs='*', default=['-'], help='files to read, if empty, stdin is used')
args = parser.parse_args()
flags = 0
if args.ignore:
flags = re.IGNORECASE
try:
regex = re.compile(args.regex, flags)
except Exception as e:
sys.exit("error: regex failed to compile: {}".format(e))
for line in fileinput.input(files=args.files):
tweet = json.loads(line)
text = json2csv.text(tweet)
if regex.search(text):
print(line, end='')
| #!/usr/bin/env python
"""
Filter tweet JSON based on a regular expression to apply to the text of the
tweet.
search.py <regex> file1
Or if you want a case insensitive match:
search.py -i <regex> file1
"""
import re
import sys
import json
import argparse
import fileinput
from twarc import json2csv
if len(sys.argv) == 1:
sys.exit("usage: search.py <regex> file1 file2")
parser = argparse.ArgumentParser(description="filter tweets by regex")
parser.add_argument('-i', '--ignore', dest='ignore', action='store_true',
help='ignore case')
parser.add_argument('regex')
parser.add_argument('files', metavar='FILE', nargs='*', default=['-'], help='files to read, if empty, stdin is used')
args = parser.parse_args()
flags = 0
if args.ignore:
flags = re.IGNORECASE
try:
regex = re.compile(args.regex, flags)
except Exception as e:
sys.exit("error: regex failed to compile: {}".format(e))
for line in fileinput.input(files=args.files):
tweet = json.loads(line)
text = json2csv.text(tweet)
if regex.search(text):
print(line, end='')
| Python | 0 |
4dc1552bbbdbfb060eb4559c5cded6a5c8e8fd02 | Migrate kythe for Bazel 0.27 (#3769) | kythe/cxx/tools/fyi/testdata/compile_commands.bzl | kythe/cxx/tools/fyi/testdata/compile_commands.bzl | """Rule for generating compile_commands.json.in with appropriate inlcude directories."""
load("@bazel_tools//tools/cpp:toolchain_utils.bzl", "find_cpp_toolchain")
_TEMPLATE = """ {{
"directory": "OUT_DIR",
"command": "clang++ -c {filename} -std=c++11 -Wall -Werror -I. -IBASE_DIR {system_includes}",
"file": "{filename}",
}}"""
def _compile_commands_impl(ctx):
system_includes = " ".join([
"-I{}".format(d)
for d in find_cpp_toolchain(ctx).built_in_include_directories
])
ctx.actions.write(
output = ctx.outputs.compile_commands,
content = "[\n{}]\n".format(",\n".join([
_TEMPLATE.format(filename = name, system_includes = system_includes)
for name in ctx.attr.filenames
])),
)
compile_commands = rule(
attrs = {
"filenames": attr.string_list(
mandatory = True,
allow_empty = False,
),
# Do not add references, temporary attribute for find_cpp_toolchain.
# See go/skylark-api-for-cc-toolchain for more details.
"_cc_toolchain": attr.label(
default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"),
),
},
doc = "Generates a compile_commannds.json.in template file.",
outputs = {
"compile_commands": "compile_commands.json.in",
},
implementation = _compile_commands_impl,
toolchains = ["@bazel_tools//tools/cpp:toolchain_type"],
)
| """Rule for generating compile_commands.json.in with appropriate inlcude directories."""
load("@bazel_tools//tools/cpp:toolchain_utils.bzl", "find_cpp_toolchain")
_TEMPLATE = """ {{
"directory": "OUT_DIR",
"command": "clang++ -c {filename} -std=c++11 -Wall -Werror -I. -IBASE_DIR {system_includes}",
"file": "{filename}",
}}"""
def _compile_commands_impl(ctx):
system_includes = " ".join([
"-I{}".format(d)
for d in find_cpp_toolchain(ctx).built_in_include_directories
])
ctx.actions.write(
output = ctx.outputs.compile_commands,
content = "[\n{}]\n".format(",\n".join([
_TEMPLATE.format(filename = name, system_includes = system_includes)
for name in ctx.attr.filenames
])),
)
compile_commands = rule(
attrs = {
"filenames": attr.string_list(
mandatory = True,
allow_empty = False,
),
# Do not add references, temporary attribute for find_cpp_toolchain.
# See go/skylark-api-for-cc-toolchain for more details.
"_cc_toolchain": attr.label(
default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"),
),
},
doc = "Generates a compile_commannds.json.in template file.",
outputs = {
"compile_commands": "compile_commands.json.in",
},
implementation = _compile_commands_impl,
)
| Python | 0 |
d003765047a8a6796e28531a28ba1364950ccd27 | Remove request.POST save - incompatible with DRF v3.6.3. | lms/djangoapps/bulk_enroll/views.py | lms/djangoapps/bulk_enroll/views.py | """
API views for Bulk Enrollment
"""
import json
from edx_rest_framework_extensions.authentication import JwtAuthentication
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from bulk_enroll.serializers import BulkEnrollmentSerializer
from enrollment.views import EnrollmentUserThrottle
from instructor.views.api import students_update_enrollment
from openedx.core.lib.api.authentication import OAuth2Authentication
from openedx.core.lib.api.permissions import IsStaff
from util.disable_rate_limit import can_disable_rate_limit
@can_disable_rate_limit
class BulkEnrollView(APIView):
"""
**Use Case**
Enroll multiple users in one or more courses.
**Example Request**
POST /api/bulk_enroll/v1/bulk_enroll/ {
"auto_enroll": true,
"email_students": true,
"action": "enroll",
"courses": "course-v1:edX+Demo+123,course-v1:edX+Demo2+456",
"identifiers": "brandon@example.com,yamilah@example.com"
}
**POST Parameters**
A POST request can include the following parameters.
* auto_enroll: When set to `true`, students will be enrolled as soon
as they register.
* email_students: When set to `true`, students will be sent email
notifications upon enrollment.
* action: Can either be set to "enroll" or "unenroll". This determines the behabior
**Response Values**
If the supplied course data is valid and the enrollments were
successful, an HTTP 200 "OK" response is returned.
The HTTP 200 response body contains a list of response data for each
enrollment. (See the `instructor.views.api.students_update_enrollment`
docstring for the specifics of the response data available for each
enrollment)
"""
authentication_classes = JwtAuthentication, OAuth2Authentication
permission_classes = IsStaff,
throttle_classes = EnrollmentUserThrottle,
def post(self, request):
serializer = BulkEnrollmentSerializer(data=request.data)
if serializer.is_valid():
response_dict = {
'auto_enroll': serializer.data.get('auto_enroll'),
'email_students': serializer.data.get('email_students'),
'action': serializer.data.get('action'),
'courses': {}
}
for course in serializer.data.get('courses'):
response = students_update_enrollment(self.request, course_id=course)
response_dict['courses'][course] = json.loads(response.content)
return Response(data=response_dict, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
| """
API views for Bulk Enrollment
"""
import json
from edx_rest_framework_extensions.authentication import JwtAuthentication
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from bulk_enroll.serializers import BulkEnrollmentSerializer
from enrollment.views import EnrollmentUserThrottle
from instructor.views.api import students_update_enrollment
from openedx.core.lib.api.authentication import OAuth2Authentication
from openedx.core.lib.api.permissions import IsStaff
from util.disable_rate_limit import can_disable_rate_limit
@can_disable_rate_limit
class BulkEnrollView(APIView):
"""
**Use Case**
Enroll multiple users in one or more courses.
**Example Request**
POST /api/bulk_enroll/v1/bulk_enroll/ {
"auto_enroll": true,
"email_students": true,
"action": "enroll",
"courses": "course-v1:edX+Demo+123,course-v1:edX+Demo2+456",
"identifiers": "brandon@example.com,yamilah@example.com"
}
**POST Parameters**
A POST request can include the following parameters.
* auto_enroll: When set to `true`, students will be enrolled as soon
as they register.
* email_students: When set to `true`, students will be sent email
notifications upon enrollment.
* action: Can either be set to "enroll" or "unenroll". This determines the behabior
**Response Values**
If the supplied course data is valid and the enrollments were
successful, an HTTP 200 "OK" response is returned.
The HTTP 200 response body contains a list of response data for each
enrollment. (See the `instructor.views.api.students_update_enrollment`
docstring for the specifics of the response data available for each
enrollment)
"""
authentication_classes = JwtAuthentication, OAuth2Authentication
permission_classes = IsStaff,
throttle_classes = EnrollmentUserThrottle,
def post(self, request):
serializer = BulkEnrollmentSerializer(data=request.data)
if serializer.is_valid():
request.POST = request.data
response_dict = {
'auto_enroll': serializer.data.get('auto_enroll'),
'email_students': serializer.data.get('email_students'),
'action': serializer.data.get('action'),
'courses': {}
}
for course in serializer.data.get('courses'):
response = students_update_enrollment(self.request, course_id=course)
response_dict['courses'][course] = json.loads(response.content)
return Response(data=response_dict, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
| Python | 0 |
cabae8d7732cca922e3fb56db205e41a20186aa3 | Remove markdown | DataCleaning/data_cleaning.py | DataCleaning/data_cleaning.py | # -*- coding: utf-8 -*-
"""
Script for Importing data from MySQL database and cleaning
"""
import os
import pymysql
import pandas as pd
from bs4 import BeautifulSoup
from ftfy import fix_text
## Getting Data
# Changing directory
os.chdir("")
# Running the file containing MySQL information
execfile("connection_config.py")
# Connecting to MySQL
connection = pymysql.connect(host=hostname, user=usr, password=pwd, db=db, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
# Fetching data from the database
with connection.cursor() as cursor:
sql = "SELECT * FROM answers"
cursor.execute(sql)
result = cursor.fetchall()
# Closing connection
connection.close()
# Saving the data as a dataframe
data = pd.DataFrame(result)
# Saving the data to an excel file
#data.to_excel("answers.xlsx")
# Importing data from the excel file
#data = pd.read_excel("answers.xlsx")
## Data cleaning
data["body"] = data["body"].fillna("") # Filling missing values
# Cleaning html and fixing unicode
nrow = data.shape[0]
body = list()
for i in range(0, nrow):
body.append(BeautifulSoup(data["body"][i], "html"))
body[i] = body[i].get_text() # Remove html
body[i] = fix_text(body[i]) # Fix unicode characters
body = pd.Series(body)
# Strip whitespace
body_new = body.str.strip()
body_new = body_new.str.replace("[\s]{2,}", "")
# Remove markdown
body_new = body_new.str.replace("[$#~^*_]", "")
# Cleaning special characters
body_new = body_new.str.replace("[\r\n\t\xa0]", "")
body_new = body_new.str.replace("[\\\\]{1,}", " ")
# Putting the cleaned up data back in the dataframe
data["body"] = body_new
| # -*- coding: utf-8 -*-
"""
Script for Importing data from MySQL database and cleaning
"""
import os
import pymysql
import pandas as pd
from bs4 import BeautifulSoup
from ftfy import fix_text
## Getting Data
# Changing directory
os.chdir("")
# Running the file containing MySQL information
execfile("connection_config.py")
# Connecting to MySQL
connection = pymysql.connect(host=hostname, user=usr, password=pwd, db=db, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
# Fetching data from the database
with connection.cursor() as cursor:
sql = "SELECT * FROM answers"
cursor.execute(sql)
result = cursor.fetchall()
# Closing connection
connection.close()
# Saving the data as a dataframe
data = pd.DataFrame(result)
# Saving the data to an excel file
#data.to_excel("answers.xlsx")
# Importing data from the excel file
#data = pd.read_excel("answers.xlsx")
## Data cleaning
data["body"] = data["body"].fillna("") # Filling missing values
# Cleaning html and fixing unicode
nrow = data.shape[0]
body = list()
for i in range(0, nrow):
body.append(BeautifulSoup(data["body"][i], "html"))
body[i] = body[i].get_text() # Remove html
body[i] = fix_text(body[i]) # Fix unicode characters
body = pd.Series(body)
# Strip whitespace
body_new = body.str.strip()
body_new = body_new.str.replace("[\s]{2,}", "")
# Cleaning special characters
body_new = body_new.str.replace("[\r\n\t$\xa0]", "")
body_new = body_new.str.replace("[\\\\]{1,}", " ")
# Putting the cleaned up data back in the dataframe
data["body"] = body_new
| Python | 0.000033 |
abcae974229dc28a60f78b706f7cd4070bc530fa | update doc | lib/ansible/modules/windows/win_feature.py | lib/ansible/modules/windows/win_feature.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2014, Paul Durivage <paul.durivage@rackspace.com>, Trond Hindenes <trond@hindenes.com> and others
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# this is a windows documentation stub. actual code lives in the .ps1
# file of the same name
DOCUMENTATION = '''
---
module: win_feature
version_added: "1.7"
short_description: Installs and uninstalls Windows Features
description:
- Installs or uninstalls Windows Roles or Features
options:
name:
description:
- Names of roles or features to install as a single feature or a comma-separated list of features
required: true
default: null
state:
description:
- State of the features or roles on the system
required: false
choices:
- present
- absent
default: present
restart:
description:
- Restarts the computer automatically when installation is complete, if restarting is required by the roles or features installed.
choices:
- yes
- no
default: null
include_sub_features:
description:
- Adds all subfeatures of the specified feature
choices:
- yes
- no
default: null
include_management_tools:
description:
- Adds the corresponding management tools to the specified feature
choices:
- yes
- no
default: null
source:
description:
- Specify a source to install the feature from
required: false
choices:
- {driveletter}:\sources\sxs
- \\{IP}\Share\sources\sxs
author:
- "Paul Durivage (@angstwad)"
- "Trond Hindenes (@trondhindenes)"
'''
EXAMPLES = '''
# This installs IIS.
# The names of features available for install can be run by running the following Powershell Command:
# PS C:\Users\Administrator> Import-Module ServerManager; Get-WindowsFeature
$ ansible -i hosts -m win_feature -a "name=Web-Server" all
$ ansible -i hosts -m win_feature -a "name=Web-Server,Web-Common-Http" all
ansible -m "win_feature" -a "name=NET-Framework-Core source=C:/Temp/iso/sources/sxs" windows
# Playbook example
---
- name: Install IIS
hosts: all
gather_facts: false
tasks:
- name: Install IIS
win_feature:
name: "Web-Server"
state: present
restart: yes
include_sub_features: yes
include_management_tools: yes
'''
| #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2014, Paul Durivage <paul.durivage@rackspace.com>, Trond Hindenes <trond@hindenes.com> and others
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# this is a windows documentation stub. actual code lives in the .ps1
# file of the same name
DOCUMENTATION = '''
---
module: win_feature
version_added: "1.7"
short_description: Installs and uninstalls Windows Features
description:
- Installs or uninstalls Windows Roles or Features
options:
name:
description:
- Names of roles or features to install as a single feature or a comma-separated list of features
required: true
default: null
state:
description:
- State of the features or roles on the system
required: false
choices:
- present
- absent
default: present
restart:
description:
- Restarts the computer automatically when installation is complete, if restarting is required by the roles or features installed.
choices:
- yes
- no
default: null
include_sub_features:
description:
- Adds all subfeatures of the specified feature
choices:
- yes
- no
default: null
include_management_tools:
description:
- Adds the corresponding management tools to the specified feature
choices:
- yes
- no
default: null
source:
description:
- Specify a source to install the feature from
required: false
choices:
- {driveletter}:\sources\sxs
- \\{IP}\Share\sources\sxs
author:
- "Paul Durivage (@angstwad)"
- "Trond Hindenes (@trondhindenes)"
'''
EXAMPLES = '''
# This installs IIS.
# The names of features available for install can be run by running the following Powershell Command:
# PS C:\Users\Administrator> Import-Module ServerManager; Get-WindowsFeature
$ ansible -i hosts -m win_feature -a "name=Web-Server" all
$ ansible -i hosts -m win_feature -a "name=Web-Server,Web-Common-Http" all
# Playbook example
---
- name: Install IIS
hosts: all
gather_facts: false
tasks:
- name: Install IIS
win_feature:
name: "Web-Server"
state: present
restart: yes
include_sub_features: yes
include_management_tools: yes
'''
| Python | 0 |
23b56303d3afa4764d7fa4f4d82eafbaf57d0341 | Update the version number | ailib/__init__.py | ailib/__init__.py | # PyAI
# The MIT License
#
# Copyright (c) 2014,2015,2016,2017 Jeremie DECOCK (http://www.jdhp.org)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# PEP0440 compatible formatted version, see:
# https://www.python.org/dev/peps/pep-0440/
#
# Generic release markers:
# X.Y
# X.Y.Z # For bugfix releases
#
# Admissible pre-release markers:
# X.YaN # Alpha release
# X.YbN # Beta release
# X.YrcN # Release Candidate
# X.Y # Final release
#
# Dev branch marker is: 'X.Y.dev' or 'X.Y.devN' where N is an integer.
# 'X.Y.dev0' is the canonical version of 'X.Y.dev'
#
__version__ = '0.2.dev1'
__all__ = ['ml',
'mdp',
'optimize',
'signal']
| # PyAI
# The MIT License
#
# Copyright (c) 2014,2015,2016,2017 Jeremie DECOCK (http://www.jdhp.org)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# PEP0440 compatible formatted version, see:
# https://www.python.org/dev/peps/pep-0440/
#
# Generic release markers:
# X.Y
# X.Y.Z # For bugfix releases
#
# Admissible pre-release markers:
# X.YaN # Alpha release
# X.YbN # Beta release
# X.YrcN # Release Candidate
# X.Y # Final release
#
# Dev branch marker is: 'X.Y.dev' or 'X.Y.devN' where N is an integer.
# 'X.Y.dev0' is the canonical version of 'X.Y.dev'
#
__version__ = '0.2.dev0'
__all__ = ['ml',
'mdp',
'optimize',
'signal']
| Python | 0.000045 |
4fb02e4bdf4af30826a00dadc4883cd2d9922541 | Fix type errors, move from partial to explicit connector function | aiosqlite/core.py | aiosqlite/core.py | # Copyright 2017 John Reese
# Licensed under the MIT license
import asyncio
import logging
import sqlite3
from concurrent.futures import ThreadPoolExecutor
from functools import partial
from typing import Any, Callable, Iterable
__all__ = [
'connect',
'Connection',
'Cursor',
]
Log = logging.getLogger('aiosqlite')
class Cursor:
def __init__(
self,
conn: 'Connection',
cursor: sqlite3.Cursor,
) -> None:
self._conn = conn
self._cursor = cursor
class Connection:
def __init__(
self,
connector: Callable[[], sqlite3.Connection],
loop: asyncio.AbstractEventLoop,
executor: ThreadPoolExecutor,
) -> None:
self._conn: sqlite3.Connection = None
self._connector = connector
self._loop = loop
self._executor = executor
async def _execute(self, fn, *args, **kwargs):
"""Execute a function with the given arguments on the shared thread."""
pt = partial(fn, *args, **kwargs)
return await self._loop.run_in_executor(self._executor, pt)
async def _connect(self):
"""Connect to the actual sqlite database."""
if self._conn is None:
self._conn = await self._execute(self._connector)
async def __aenter__(self) -> 'Connection':
await self._connect()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
await self.close()
self._conn = None
async def cursor(self) -> Cursor:
raise NotImplementedError('Not yet available in aiosqlite')
async def commit(self) -> None:
raise NotImplementedError('Not yet available in aiosqlite')
async def rollback(self) -> None:
raise NotImplementedError('Not yet available in aiosqlite')
async def close(self) -> None:
await self._execute(self._conn.close)
async def execute(
self,
sql: str,
parameters: Iterable[Any] = None,
) -> Cursor:
raise NotImplementedError('Not yet available in aiosqlite')
async def executemany(
self,
sql: str,
parameters: Iterable[Iterable[Any]] = None,
) -> Cursor:
raise NotImplementedError('Not yet available in aiosqlite')
async def executescript(
self,
sql_script: str,
) -> Cursor:
raise NotImplementedError('Not yet available in aiosqlite')
def connect(
database: str,
**kwargs: Any,
) -> Connection:
"""Create and return a connection proxy to the sqlite database."""
loop = asyncio.get_event_loop()
executor = ThreadPoolExecutor(1)
def connector() -> sqlite3.Connection:
return sqlite3.connect(
database,
check_same_thread=False,
**kwargs,
)
return Connection(connector, loop, executor)
| # Copyright 2017 John Reese
# Licensed under the MIT license
import asyncio
import logging
import sqlite3
from concurrent.futures import ThreadPoolExecutor
from functools import partial
from typing import Any, Callable, Iterable
__all__ = [
'connect',
'Connection',
'Cursor',
]
Log = logging.getLogger('aiosqlite')
class Cursor:
def __init__(
self,
conn: 'Connection',
cursor: sqlite3.Cursor,
) -> None:
self._conn = conn
self._cursor = cursor
class Connection:
def __init__(
self,
connector: Callable[[], sqlite3.Connection],
loop: asyncio.AbstractEventLoop,
executor: ThreadPoolExecutor,
) -> None:
self._conn: sqlite3.Connection = None
self._connector = connector
self._loop = loop
self._executor = executor
async def _execute(self, fn, *args, **kwargs):
"""Execute a function with the given arguments on the shared thread."""
pt = partial(fn, *args, **kwargs)
return await self._loop.run_in_executor(self._executor, pt)
async def _connect(self):
"""Connect to the actual sqlite database."""
if self._conn is None:
self._conn = await self._execute(self._connector)
async def __aenter__(self) -> 'Connection':
await self._connect()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
await self.close()
self._conn = None
async def cursor(self) -> Cursor:
raise NotImplementedError('Not yet available in aiosqlite')
async def commit(self) -> None:
raise NotImplementedError('Not yet available in aiosqlite')
async def rollback(self) -> None:
raise NotImplementedError('Not yet available in aiosqlite')
async def close(self) -> None:
await self._execute(self._conn.close)
async def execute(
self,
sql: str,
parameters: Iterable[Any] = None,
) -> Cursor:
raise NotImplementedError('Not yet available in aiosqlite')
async def executemany(
self,
sql: str,
parameters: Iterable[Iterable[Any]] = None,
) -> Cursor:
raise NotImplementedError('Not yet available in aiosqlite')
async def executescript(
self,
sql_script: str,
) -> Cursor:
raise NotImplementedError('Not yet available in aiosqlite')
def connect(
database: str,
**kwargs: Any,
) -> Connection:
"""Create and return a connection proxy to the sqlite database."""
loop = asyncio.get_event_loop()
executor = ThreadPoolExecutor(1)
connector = partial(
sqlite3.connect,
database,
check_same_thread=False,
**kwargs,
)
return Connection(connector, loop, executor)
| Python | 0 |
d2cfc7f2fefcb9a317ab3cd18ebc8785fb764d9f | remove last bang | lib/exabgp/bgp/message/open/capability/refresh.py | lib/exabgp/bgp/message/open/capability/refresh.py | # encoding: utf-8
"""
refresh.py
Created by Thomas Mangin on 2012-07-17.
Copyright (c) 2012 Exa Networks. All rights reserved.
"""
# =================================================================== RouteRefresh
class RouteRefresh (list):
def __str__ (self):
return "Route Refresh (unparsed)"
def extract (self):
return []
class CiscoRouteRefresh (list):
def __str__ (self):
return "Cisco Route Refresh (unparsed)"
def extract (self):
return []
| #!/usr/bin/env python
# encoding: utf-8
"""
refresh.py
Created by Thomas Mangin on 2012-07-17.
Copyright (c) 2012 Exa Networks. All rights reserved.
"""
# =================================================================== RouteRefresh
class RouteRefresh (list):
def __str__ (self):
return "Route Refresh (unparsed)"
def extract (self):
return []
class CiscoRouteRefresh (list):
def __str__ (self):
return "Cisco Route Refresh (unparsed)"
def extract (self):
return []
| Python | 0.008047 |
4fa4fb3f583e787da9594ac8a714a22981842c71 | remove now-bogus test | pydoctor/test/test_commandline.py | pydoctor/test/test_commandline.py | from pydoctor import driver
import sys, cStringIO
def geterrtext(*options):
options = list(options)
se = sys.stderr
f = cStringIO.StringIO()
print options
sys.stderr = f
try:
try:
driver.main(options)
except SystemExit:
pass
else:
assert False, "did not fail"
finally:
sys.stderr = se
return f.getvalue()
def test_invalid_option():
err = geterrtext('--no-such-option')
assert 'no such option' in err
def test_cannot_advance_blank_system():
err = geterrtext('--make-html')
assert 'forget an --add-package?' in err
def test_invalid_systemclasses():
err = geterrtext('--system-class')
assert 'requires an argument' in err
err = geterrtext('--system-class=notdotted')
assert 'dotted name' in err
err = geterrtext('--system-class=no-such-module.System')
assert 'could not import module' in err
err = geterrtext('--system-class=pydoctor.model.Class')
assert 'is not a subclass' in err
def test_projectbasedir():
"""
The --project-base-dir option should set the projectbasedirectory attribute
on the options object.
"""
value = "projbasedirvalue"
options, args = driver.parse_args([
"--project-base-dir", value])
assert options.projectbasedirectory == value
| from pydoctor import driver
import sys, cStringIO
def geterrtext(*options):
options = list(options)
se = sys.stderr
f = cStringIO.StringIO()
print options
sys.stderr = f
try:
try:
driver.main(options)
except SystemExit:
pass
else:
assert False, "did not fail"
finally:
sys.stderr = se
return f.getvalue()
def test_invalid_option():
err = geterrtext('--no-such-option')
assert 'no such option' in err
def test_no_do_nothing():
err = geterrtext()
assert "this invocation isn't going to do anything" in err
def test_cannot_advance_blank_system():
err = geterrtext('--make-html')
assert 'forget an --add-package?' in err
def test_invalid_systemclasses():
err = geterrtext('--system-class')
assert 'requires an argument' in err
err = geterrtext('--system-class=notdotted')
assert 'dotted name' in err
err = geterrtext('--system-class=no-such-module.System')
assert 'could not import module' in err
err = geterrtext('--system-class=pydoctor.model.Class')
assert 'is not a subclass' in err
def test_projectbasedir():
"""
The --project-base-dir option should set the projectbasedirectory attribute
on the options object.
"""
value = "projbasedirvalue"
options, args = driver.parse_args([
"--project-base-dir", value])
assert options.projectbasedirectory == value
| Python | 0.000005 |
2d8a3b4dfbd9cfb6c5368c1b4a04e2bd07e97f18 | Add Big O time complexity | pygorithm/data_structures/heap.py | pygorithm/data_structures/heap.py | # Author: ALLSTON MICKEY
# Contributed: OMKAR PATHAK
# Created On: 11th August 2017
from queue import Queue
# min-heap implementation as priority queue
class Heap(Queue):
def parent_idx(self, idx):
return idx / 2
def left_child_idx(self, idx):
return (idx * 2) + 1
def right_child_idx(self, idx):
return (idx * 2) + 2
def insert(self, data):
super(Heap, self).enqueue(data)
if self.rear >= 1: # heap may need to be fixed
self.heapify_up()
def heapify_up(self):
'''
Start at the end of the tree (last enqueued item).
Compare the rear item to its parent, swap if
the parent is larger than the child (min-heap property).
Repeat until the min-heap property is met.
Best Case: O(1), item is inserted at correct position, no swaps needed
Worst Case: O(logn), item needs to be swapped throughout all levels of tree
'''
child = self.rear
parent = self.parent_idx(child)
while self.queue[child] < self.queue[self.parent_idx(child)]:
# Swap (sift up) and update child:parent relation
self.queue[child], self.queue[parent] = self.queue[parent], self.queue[child]
child = parent
parent = self.parent_idx(child)
def pop(self):
''' Removes the lowest value element (highest priority, at root) from the heap '''
min = self.dequeue()
if self.rear >= 1: # heap may need to be fixed
self.heapify_down()
return min
def favorite(self, parent):
''' Determines which child has the highest priority by 3 cases '''
left = self.left_child_idx(parent)
right = self.right_child_idx(parent)
if left <= self.rear and right <= self.rear: # case 1: both nodes exist
if self.queue[left] <= self.queue[right]:
return left
else:
return right
elif left <= self.rear: # case 2: only left exists
return left
else: # case 3: no children (if left doesn't exist, neither can the right)
return None
def heapify_down(self):
'''
Select the root and sift down until min-heap property is met.
While a favorite child exists, and that child is smaller
than the parent, swap them (sift down).
Best Case: O(1), item is inserted at correct position, no swaps needed
Worst Case: O(logn), item needs to be swapped throughout all levels of tree
'''
cur = ROOT = 0 # start at the root
fav = self.favorite(cur) # determine favorite child
while self.queue[fav] is not None:
if self.queue[cur] > self.queue[fav]:
# Swap (sift down) and update parent:favorite relation
fav = self.favorite(cur)
self.queue[cur], self.queue[fav] = self.queue[fav], self.queue[cur]
cur = fav
else:
return
def time_complexities(self):
return '''[Insert & Pop] Best Case: O(1), Worst Case: O(logn)'''
def get_code(self):
''' returns the code for the current class '''
import inspect
return inspect.getsource(Heap)
| # Author: ALLSTON MICKEY
# Contributed: OMKAR PATHAK
# Created On: 11th August 2017
from queue import Queue
# min-heap implementation as priority queue
class Heap(Queue):
def parent_idx(self, idx):
return idx / 2
def left_child_idx(self, idx):
return (idx * 2) + 1
def right_child_idx(self, idx):
return (idx * 2) + 2
def insert(self, data):
super(Heap, self).enqueue(data)
if self.rear >= 1: # heap may need to be fixed
self.heapify_up()
def heapify_up(self):
'''
Start at the end of the tree (first enqueued item).
Compare the rear item to its parent, swap if
the parent is larger than the child (min-heap property).
Repeat until the min-heap property is met.
'''
child = self.rear
parent = self.parent_idx(child)
while self.queue[child] < self.queue[self.parent_idx(child)]:
# Swap (sift up) and update child:parent relation
self.queue[child], self.queue[parent] = self.queue[parent], self.queue[child]
child = parent
parent = self.parent_idx(child)
def pop(self):
''' Removes the lowest value element (highest priority) from the heap '''
min = self.dequeue()
if self.rear >= 1: # heap may need to be fixed
self.heapify_down()
return min
def favorite(self, parent):
''' Determines which child has the highest priority by 3 cases '''
left = self.left_child_idx(parent)
right = self.right_child_idx(parent)
if left <= self.rear and right <= self.rear: # case 1: both nodes exist
if self.queue[left] <= self.queue[right]:
return left
else:
return right
elif left <= self.rear: # case 2: only left exists
return left
else: # case 3: no children (if left doesn't exist, neither can the right)
return None
def heapify_down(self):
'''
Select the root and sift down until min-heap property is met.
While a favorite child exists, and that child is smaller
than the parent, swap them (sift down).
'''
cur = ROOT = 0 # start at the root
fav = self.favorite(cur) # determine favorite child
while self.queue[fav] is not None:
if self.queue[cur] > self.queue[fav]:
# Swap (sift down) and update parent:favorite relation
fav = self.favorite(cur)
self.queue[cur], self.queue[fav] = self.queue[fav], self.queue[cur]
cur = fav
else:
return
def get_code(self):
''' returns the code for the current class '''
import inspect
return inspect.getsource(Heap)
| Python | 0.000056 |
579904c318031ed049f697f89109bd6909b68eba | Revise docstring | alg_merge_sort.py | alg_merge_sort.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def _merge_recur(x_list, y_list):
"""Merge two sorted lists by Recusions."""
if len(x_list) == 0:
return y_list
if len(y_list) == 0:
return x_list
if x_list[0] <= y_list[0]:
return [x_list[0]] + _merge_recur(x_list[1:], y_list)
else:
return [y_list[0]] + _merge_recur(x_list, y_list[1:])
def _merge_iter(x_list, y_list):
"""Merge two sorted lists by Iteration (i.e. Two Fingers Algorithm)."""
z_list = []
x_pos = 0
y_pos = 0
for z_pos in xrange(len(x_list) + len(y_list)):
if x_pos < len(x_list) and y_pos < len(y_list):
if x_list[x_pos] <= y_list[y_pos]:
z_list.append(x_list[x_pos])
x_pos += 1
else:
z_list.append(y_list[y_pos])
y_pos += 1
elif x_pos < len(x_list) and y_pos >= len(y_list):
z_list.append(x_list[x_pos])
x_pos += 1
elif x_pos >= len(x_list) and y_pos < len(y_list):
z_list.append(y_list[y_pos])
y_pos += 1
else:
pass
return z_list
def merge_sort(a_list, merge):
"""Merge sort by Divide and Conquer Algorithm.
Time complexity: O(n*logn).
"""
if len(a_list) == 1:
return a_list
else:
mid = len(a_list) // 2
return merge(merge_sort(a_list[:mid], merge),
merge_sort(a_list[mid:], merge))
def main():
import time
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
start_time = time.time()
print(merge_sort(a_list, _merge_recur))
print('Run time of merge sort with recusions: {}'
.format(time.time() - start_time))
start_time = time.time()
print(merge_sort(a_list, _merge_iter))
print('Run time of merge sort with iterations: {}'
.format(time.time() - start_time))
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def _merge_recur(x_list, y_list):
"""Merge two sorted lists by recusions."""
if len(x_list) == 0:
return y_list
if len(y_list) == 0:
return x_list
if x_list[0] <= y_list[0]:
return [x_list[0]] + _merge_recur(x_list[1:], y_list)
else:
return [y_list[0]] + _merge_recur(x_list, y_list[1:])
def _merge_iter(x_list, y_list):
"""Merge two sorted lists by iteration."""
z_list = []
x_pos = 0
y_pos = 0
for z_pos in xrange(len(x_list) + len(y_list)):
if x_pos < len(x_list) and y_pos < len(y_list):
if x_list[x_pos] <= y_list[y_pos]:
z_list.append(x_list[x_pos])
x_pos += 1
else:
z_list.append(y_list[y_pos])
y_pos += 1
elif x_pos < len(x_list) and y_pos >= len(y_list):
z_list.append(x_list[x_pos])
x_pos += 1
elif x_pos >= len(x_list) and y_pos < len(y_list):
z_list.append(y_list[y_pos])
y_pos += 1
else:
pass
return z_list
def merge_sort(a_list, merge):
"""Merge sort by divide and conquer algorithm.
Time complexity: O(n*logn).
"""
if len(a_list) == 1:
return a_list
else:
mid = len(a_list) // 2
return merge(merge_sort(a_list[:mid], merge),
merge_sort(a_list[mid:], merge))
def main():
import time
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
start_time = time.time()
print(merge_sort(a_list, _merge_recur))
print('Run time of merge sort with recusions: {}'
.format(time.time() - start_time))
start_time = time.time()
print(merge_sort(a_list, _merge_iter))
print('Run time of merge sort with iterations: {}'
.format(time.time() - start_time))
if __name__ == '__main__':
main()
| Python | 0.000009 |
c94f24160e1d9189f13ea0029cccb815fb68d3da | Update postag.py | pythainlp/wangchanberta/postag.py | pythainlp/wangchanberta/postag.py | from typing import Dict, List, Tuple, Union
import re
from transformers import (
CamembertTokenizer,
AutoTokenizer,
pipeline,
)
_model_name = "wangchanberta-base-att-spm-uncased"
_tokenizer = CamembertTokenizer.from_pretrained(
f'airesearch/{_model_name}',
revision='main')
if _model_name == "wangchanberta-base-att-spm-uncased":
_tokenizer.additional_special_tokens = ['<s>NOTUSED', '</s>NOTUSED', '<_>']
class PosTagTransformers:
def __init__(self,
corpus: str = "lst20",
grouped_word: bool = False
) -> None:
self.corpus = corpus
self.grouped_word = grouped_word
self.load()
def load(self):
self.classify_tokens = pipeline(
task='ner',
tokenizer=_tokenizer,
model = f'airesearch/{_model_name}',
revision = f'finetuned@{self.corpus}-pos',
ignore_labels=[],
grouped_entities=self.grouped_word
)
def tag(
self, text: str, corpus: str = "lst20", grouped_word: bool = False
) -> List[Tuple[str, str]]:
if (corpus != self.corpus and corpus in ['lst20']) or grouped_word != self.grouped_word:
self.grouped_word = grouped_word
self.corpus = corpus
self.load()
text = re.sub(" ", "<_>", text)
self.json_pos = self.classify_tokens(text)
self.output = ""
if grouped_word:
self.sent_pos = [(i['word'].replace("<_>", " "), i['entity_group']) for i in self.json_pos]
else:
self.sent_pos = [(i['word'].replace("<_>", " ").replace('▁',''), i['entity']) for i in self.json_pos if i['word'] != '▁']
return self.sent_pos
_corpus = "lst20"
_grouped_word = False
_postag = PosTagTransformers(corpus=_corpus, grouped_word = _grouped_word)
def pos_tag(
text: str, corpus: str = "lst20", grouped_word: bool = False
) -> List[Tuple[str, str]]:
global _grouped_word, _postag
if corpus not in ["lst20"]:
raise NotImplementedError()
if _grouped_word != grouped_word:
_postag = PosTagTransformers(
corpus=corpus,
grouped_word = grouped_word
)
_grouped_word = grouped_word
return _postag.tag(text, corpus = corpus,grouped_word = grouped_word)
| from typing import Dict, List, Tuple, Union
import re
from transformers import (
CamembertTokenizer,
AutoTokenizer,
pipeline,
)
_model_name = "wangchanberta-base-att-spm-uncased"
_tokenizer = CamembertTokenizer.from_pretrained(
f'airesearch/{_model_name}',
revision='main')
if _model_name == "wangchanberta-base-att-spm-uncased":
_tokenizer.additional_special_tokens = ['<s>NOTUSED', '</s>NOTUSED', '<_>']
class PosTagTransformers:
def __init__(self,
corpus: str = "lst20",
grouped_word: bool = False
) -> None:
self.corpus = corpus
self.grouped_word = grouped_word
self.load()
def load(self):
self.classify_tokens = pipeline(
task='ner',
tokenizer=_tokenizer,
model = f'airesearch/{_model_name}',
revision = f'finetuned@{self.corpus}-pos',
ignore_labels=[],
grouped_entities=self.grouped_word
)
def tag(
self, text: str, corpus: str = "lst20", grouped_word: bool = False
) -> List[Tuple[str, str]]:
if (corpus != self.corpus and corpus in ['lst20']) or grouped_word != self.grouped_word:
self.grouped_word = grouped_word
self.corpus = corpus
self.load()
text = re.sub(" ", "<_>", text)
self.json_pos = self.classify_tokens(text)
self.output = ""
if grouped_word:
self.sent_pos = [(i['word'].replace("<_>", " "), i['entity_group']) for i in self.json_pos]
else:
self.sent_pos = [(i['word'].replace("<_>", " ").replace('▁',''), i['entity']) for i in self.json_pos if i['word'] != '▁']
return self.sent_pos
_corpus = "lst20"
_grouped_word = False
_postag = PosTagTransformers(corpus=_corpus, grouped_word = _grouped_word)
def pos_tag(
text: str, corpus: str = "lst20", grouped_word: bool = False
) -> List[Tuple[str, str]]:
global _grouped_word, _postag
if corpus not in ["lst20"]:
raise NotImplementedError()
if _grouped_word != grouped_word:
_postag = PosTagTransformers(
corpus=corpus,
grouped_word = grouped_word
)
_grouped_word = grouped_word
return _postag.tag(text)
| Python | 0 |
2c5a345aa7e21045d6a76225dc192f14b62db4f6 | fix review permission manage command | symposion/reviews/management/commands/create_review_permissions.py | symposion/reviews/management/commands/create_review_permissions.py | from django.core.management.base import BaseCommand
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from symposion.proposals.models import ProposalSection
class Command(BaseCommand):
def handle(self, *args, **options):
ct = ContentType.objects.get(
app_label="symposion_reviews",
model="review"
)
for ps in ProposalSection.objects.all():
for action in ["review", "manage"]:
perm, created = Permission.objects.get_or_create(
codename="can_%s_%s" % (action, ps.section.slug),
content_type__pk=ct.id,
defaults={"name": "Can %s %s" % (action, ps), "content_type": ct}
)
print perm
| from django.core.management.base import BaseCommand
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from symposion.proposals.models import ProposalSection
class Command(BaseCommand):
def handle(self, *args, **options):
ct, created = ContentType.objects.get_or_create(
model="",
app_label="reviews",
defaults={"name": "reviews"}
)
for ps in ProposalSection.objects.all():
for action in ["review", "manage"]:
perm, created = Permission.objects.get_or_create(
codename="can_%s_%s" % (action, ps.section.slug),
content_type__pk=ct.id,
defaults={"name": "Can %s %s" % (action, ps), "content_type": ct}
)
print perm
| Python | 0 |
c8398415bf82a1f68c7654c8d4992661587fccf7 | Update pathlib-recursive-rmdir.py | python/pathlib-recursive-rmdir.py | python/pathlib-recursive-rmdir.py | import pathlib
# path: pathlib.Path - directory to remove
def removeDirectory(path):
for i in path.glob('*'):
if i.is_dir():
removeDirectory(i)
else:
i.unlink()
# NOTE: can replace above lines with `removeConents(path)` scrap form pathlib-recursive-remove-contents
path.rmdir()
| import pathlib
# path: pathlib.Path - directory to remove
def removeDirectory(path):
for i in path.glob('*'):
if i.is_dir():
removeDirectory(i)
else:
i.unlink()
path.rmdir()
| Python | 0.000001 |
e718615eac8e964b46ded826e68fe1087ee33f09 | set DEBUG to False (oops) | frontend/fifoci/settings/base.py | frontend/fifoci/settings/base.py | # This file is part of the FifoCI project.
# Copyright (c) 2014 Pierre Bourdon <delroth@dolphin-emu.org>
# Licensing information: see $REPO_ROOT/LICENSE
"""
Django settings for fifoci project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# We don't use sessions for anything but the Django admin in this application.
# 32 random bytes are enough, though this means cookies will get invalidated on
# application restart.
SECRET_KEY = os.urandom(32)
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
TEMPLATE_DEBUG = False
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'fifoci',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
"fifoci.context_processors.recent_changes",
)
ROOT_URLCONF = 'fifoci.urls'
WSGI_APPLICATION = 'fifoci.wsgi.application'
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'fifoci',
'USER': 'fifoci',
}
}
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
# Media files (used to store DFFs, PNGs)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
| # This file is part of the FifoCI project.
# Copyright (c) 2014 Pierre Bourdon <delroth@dolphin-emu.org>
# Licensing information: see $REPO_ROOT/LICENSE
"""
Django settings for fifoci project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# We don't use sessions for anything but the Django admin in this application.
# 32 random bytes are enough, though this means cookies will get invalidated on
# application restart.
SECRET_KEY = os.urandom(32)
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'fifoci',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
"fifoci.context_processors.recent_changes",
)
ROOT_URLCONF = 'fifoci.urls'
WSGI_APPLICATION = 'fifoci.wsgi.application'
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'fifoci',
'USER': 'fifoci',
}
}
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
# Media files (used to store DFFs, PNGs)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
| Python | 0.000014 |
7668331e7cc4f5e2a310fcddcb3f90af4c18bb30 | add Python 3 compatibility imports to capabilities.py | python/pywatchman/capabilities.py | python/pywatchman/capabilities.py | # Copyright 2015 Facebook, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name Facebook nor the names of its contributors may be used to
# endorse or promote products derived from this software without specific
# prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# no unicode literals
import re
def parse_version(vstr):
res = 0
for n in vstr.split('.'):
res = res * 1000
res = res + int(n)
return res
cap_versions = {
"cmd-watch-del-all": "3.1.1",
"cmd-watch-project": "3.1",
"relative_root": "3.3",
"term-dirname": "3.1",
"term-idirname": "3.1",
"wildmatch": "3.7",
}
def check(version, name):
if name in cap_versions:
return version >= parse_version(cap_versions[name])
return False
def synthesize(vers, opts):
""" Synthesize a capability enabled version response
This is a very limited emulation for relatively recent feature sets
"""
parsed_version = parse_version(vers['version'])
vers['capabilities'] = {}
for name in opts['optional']:
vers['capabilities'][name] = check(parsed_version, name)
failed = False
for name in opts['required']:
have = check(parsed_version, name)
vers['capabilities'][name] = have
if not have:
vers['error'] = 'client required capability `' + name + \
'` is not supported by this server'
return vers
| # Copyright 2015 Facebook, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name Facebook nor the names of its contributors may be used to
# endorse or promote products derived from this software without specific
# prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import re
def parse_version(vstr):
res = 0
for n in vstr.split('.'):
res = res * 1000
res = res + int(n)
return res
cap_versions = {
"cmd-watch-del-all": "3.1.1",
"cmd-watch-project": "3.1",
"relative_root": "3.3",
"term-dirname": "3.1",
"term-idirname": "3.1",
"wildmatch": "3.7",
}
def check(version, name):
if name in cap_versions:
return version >= parse_version(cap_versions[name])
return False
def synthesize(vers, opts):
""" Synthesize a capability enabled version response
This is a very limited emulation for relatively recent feature sets
"""
parsed_version = parse_version(vers['version'])
vers['capabilities'] = {}
for name in opts['optional']:
vers['capabilities'][name] = check(parsed_version, name)
failed = False
for name in opts['required']:
have = check(parsed_version, name)
vers['capabilities'][name] = have
if not have:
vers['error'] = 'client required capability `' + name + \
'` is not supported by this server'
return vers
| Python | 0 |
97545d3055a0e0044723e0cb4b7ffd7803d1dbd5 | Make class constants. | qipipe/staging/airc_collection.py | qipipe/staging/airc_collection.py | import re
from .staging_error import StagingError
__all__ = ['with_name']
EXTENT = {}
"""A name => collection dictionary for all supported AIRC collections."""
def collection_with_name(name):
"""
@param name: the OHSU QIN collection name
@return: the corresponding AIRC collection
"""
return EXTENT[name]
class AIRCCollection(object):
"""The AIRC Study characteristics."""
def __init__(self, collection, subject_pattern, session_pattern, dicom_pattern):
"""
@param collection: the collection name
@param subject_pattern: the subject directory name match regular expression pattern
@param session_pattern: the session directory name match regular expression pattern
@param dicom_pattern: the DICOM directory name match glob pattern
"""
self.collection = collection
self.subject_pattern = subject_pattern
self.session_pattern = session_pattern
self.dicom_pattern = dicom_pattern
EXTENT[collection] = self
def path2subject_number(self, path):
"""
@param path: the directory path
@return: the subject number
"""
match = re.search(self.subject_pattern, path)
if not match:
raise StagingError("The directory path %s does not match the subject pattern %s" % (path, self.subject_pattern))
return int(match.group(1))
def path2session_number(self, path):
"""
@param path: the directory path
@return: the session number
"""
return int(re.search(self.session_pattern, path).group(1))
class AIRCCollection:
BREAST = AIRCCollection('Breast', 'BreastChemo(\d+)', 'Visit(\d+)', '*concat*/*')
"""The Breast collection."""
SARCOMA = AIRCCollection('Sarcoma', 'Subj_(\d+)', '(?:Visit_|S\d+V)(\d+)', '*concat*/*')
"""The Sarcoma collection.""" | import re
from .staging_error import StagingError
__all__ = ['with_name']
EXTENT = {}
"""A name => collection dictionary for all supported AIRC collections."""
def collection_with_name(name):
"""
@param name: the OHSU QIN collection name
@return: the corresponding AIRC collection
"""
return EXTENT[name]
class AIRCCollection(object):
"""The AIRC Study characteristics."""
def __init__(self, collection, subject_pattern, session_pattern, dicom_pattern):
"""
@param collection: the collection name
@param subject_pattern: the subject directory name match regular expression pattern
@param session_pattern: the session directory name match regular expression pattern
@param dicom_pattern: the DICOM directory name match glob pattern
"""
self.collection = collection
self.subject_pattern = subject_pattern
self.session_pattern = session_pattern
self.dicom_pattern = dicom_pattern
EXTENT[collection] = self
def path2subject_number(self, path):
"""
@param path: the directory path
@return: the subject number
"""
match = re.search(self.subject_pattern, path)
if not match:
raise StagingError("The directory path %s does not match the subject pattern %s" % (path, self.subject_pattern))
return int(match.group(1))
def path2session_number(self, path):
"""
@param path: the directory path
@return: the session number
"""
return int(re.search(self.session_pattern, path).group(1))
BREAST = AIRCCollection('Breast', 'BreastChemo(\d+)', 'Visit(\d+)', '*concat*/*')
SARCOMA = AIRCCollection('Sarcoma', 'Subj_(\d+)', '(?:Visit_|S\d+V)(\d+)', '*concat*/*') | Python | 0 |
ed263e083dcb49bdd3f2d6cc707008cb5fe8ce1b | remove account.reconcile before deleting a account.move | account_statement_ext/account.py | account_statement_ext/account.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Joel Grand-Guillaume
# Copyright 2011-2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv.orm import Model
from openerp.osv import fields
class account_move(Model):
_inherit = 'account.move'
def unlink(self, cr, uid, ids, context=None):
"""
Delete the reconciliation when we delete the moves. This
allow an easier way of cancelling the bank statement.
"""
reconcile_to_delete = []
reconcile_obj = self.pool.get('account.move.reconcile')
for move in self.browse(cr, uid, ids, context=context):
for move_line in move.line_id:
if move_line.reconcile_id:
reconcile_to_delete.append(move_line.reconcile_id.id)
reconcile_obj.unlink(cr,uid,reconcile_to_delete,context=context)
return super(account_move, self).unlink(cr, uid, ids, context=context)
| # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Joel Grand-Guillaume
# Copyright 2011-2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv.orm import Model
from openerp.osv import fields
class account_move(Model):
_inherit = 'account.move'
def unlink(self, cr, uid, ids, context=None):
"""
Delete the reconciliation when we delete the moves. This
allow an easier way of cancelling the bank statement.
"""
for move in self.browse(cr, uid, ids, context=context):
for move_line in move.line_id:
if move_line.reconcile_id:
move_line.reconcile_id.unlink(context=context)
return super(account_move, self).unlink(cr, uid, ids, context=context)
| Python | 0 |
55373ddcf68641ec0654b58b8471c01e749366f9 | Use a single redis client object for the module | tinman/handlers/redis.py | tinman/handlers/redis.py | """The RedisRequestHandler uses tornado-redis to support Redis. It will
auto-establish a single redis connection when initializing the connection.
"""
import logging
import tornadoredis
from tornado import web
LOGGER = logging.getLogger(__name__)
redis_client = None
class RedisRequestHandler(web.RequestHandler):
"""This request handler will connect to Redis on initialize if the
connection is not previously set.
"""
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
REDIS_DB = 0
def _connect_to_redis(self):
"""Connect to a Redis server returning the handle to the redis
connection.
:rtype: tornadoredis.Redis
"""
settings = self._redis_settings
LOGGER.debug('Connecting to redis: %r', settings)
client = tornadoredis.Client(**settings)
client.connect()
return client
def _new_redis_client(self):
"""Create a new redis client and assign it to the module level handle.
"""
global redis_client
redis_client = self._connect_to_redis()
@property
def _redis_settings(self):
"""Return the Redis settings from configuration as a dict, defaulting
to localhost:6379:0 if it's not set in configuration. The dict format
is set to be passed as kwargs into the Client object.
:rtype: dict
"""
settings = self.application.settings.get('redis', dict())
return {'host': settings.get('host', self.REDIS_HOST),
'port': settings.get('port', self.REDIS_PORT),
'selected_db': settings.get('db', self.REDIS_DB)}
def prepare(self):
"""Prepare RedisRequestHandler requests, ensuring that there is a
connected tornadoredis.Client object.
"""
global redis_client
super(RedisRequestHandler, self).prepare()
if redis_client is None or not redis_client.connection.connected:
LOGGER.info('Creating new Redis instance')
self._new_redis_client()
@property
def redis_client(self):
"""Return a handle to the active redis client.
:rtype: tornadoredis.Redis
"""
global redis_client
return redis_client
| """The RedisRequestHandler uses tornado-redis to support Redis. It will
auto-establish a single redis connection when initializing the connection.
"""
import logging
import tornadoredis
from tornado import web
LOGGER = logging.getLogger(__name__)
class RedisRequestHandler(web.RequestHandler):
"""This request handler will connect to Redis on initialize if the
connection is not previously set.
"""
REDIS_CLIENT = 'redis'
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
REDIS_DB = 0
def prepare(self):
super(RedisRequestHandler, self).prepare()
if not self._has_redis_client:
self._set_redis_client(self._connect_to_redis())
@property
def _has_redis_client(self):
return hasattr(self.application.tinman, self.REDIS_CLIENT)
def _connect_to_redis(self):
LOGGER.debug('Connecting to redis: %r', self._redis_connection_settings)
client = tornadoredis.Client(**self._redis_connection_settings)
client.connect()
return client
@property
def _redis_connection_settings(self):
return {'host': self._redis_settings.get('host', self.REDIS_HOST),
'port': self._redis_settings.get('port', self.REDIS_PORT),
'selected_db': self._redis_settings.get('db', self.REDIS_DB)}
@property
def _redis_settings(self):
LOGGER.debug('Redis settings')
return self.application.settings.get('redis', dict())
def _set_redis_client(self, client):
setattr(self.application.tinman, self.REDIS_CLIENT, client)
@property
def redis_client(self):
LOGGER.debug('Returning redis client')
return getattr(self.application.tinman, self.REDIS_CLIENT, None)
| Python | 0 |
10766f6f0e66ed3fbe5c6ec23d81926076129163 | delete test code | jellyblog/views.py | jellyblog/views.py | from django.shortcuts import render, get_object_or_404, redirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import Category, Document
def sorted_category():
return_category = list(Category.objects.all())
childList = []
for category in return_category:
if (category.parent.id == 1):
continue
else:
parent_index = return_category.index(category.parent)
return_category[parent_index].children.append(category)
childList.append(category)
for child in childList:
return_category.remove(child)
return return_category
categoryList = sorted_category()
def index(request):
return redirect('/page/1')
def index_with_page(request, page):
document_list = list(Document.objects.all())
document_list.reverse()
paginator = Paginator(document_list, 4)
documents = get_documents(paginator, page)
context = {'documents': documents, 'category_list': categoryList, 'page_range': get_page_number_range(
paginator, documents)}
return render(request, 'jellyblog/index.html', context)
def category_detail(request, category_id):
return redirect("/category/" + category_id + "/page/1")
def category_with_page(request, category_id, page):
selectedCategory = Category.objects.get(id=category_id)
document_list = []
if (selectedCategory.parent == categoryList[0]):
children = Category.objects.all().filter(parent=selectedCategory.id)
for child in children:
document_list += Document.objects.all().filter(category_id=child.id)
document_list += Document.objects.all().filter(category=category_id)
document_list.sort(key=id, reverse=True)
paginator = Paginator(document_list, 4)
documents = get_documents(paginator, page)
context = {'documents': documents, 'category_list': categoryList, 'category_id': category_id,
'page_range': get_page_number_range(paginator, documents)}
return render(request, 'jellyblog/category.html', context)
def get_documents(paginator, page):
try:
documents = paginator.page(page)
except PageNotAnInteger:
documents = paginator.page(1)
except EmptyPage:
documents = paginator.page(paginator.num_pages)
return documents
def get_page_number_range(paginator, page):
if (paginator.num_pages < 11):
return range(1, paginator.num_pages+1)
elif (page.number - 5 > 1):
if (page.number + 4 < paginator.num_pages):
return range(page.number - 5, page.number + 5)
else:
return range(page.number - 5, paginator.num_pages + 1)
else:
return range(1,11)
def detail(request, document_id):
document = get_object_or_404(Document, pk=document_id)
document.view_count += 1
document.save()
return render(request, 'jellyblog/detail.html', {'document': document, 'category_list': categoryList})
| from django.shortcuts import render, get_object_or_404, redirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import Category, Document
def sorted_category():
return_category = list(Category.objects.all())
childList = []
for category in return_category:
if (category.parent.id == 1):
continue
else:
parent_index = return_category.index(category.parent)
return_category[parent_index].children.append(category)
childList.append(category)
for child in childList:
return_category.remove(child)
return return_category
categoryList = sorted_category()
def index(request):
return redirect('/page/1')
def index_with_page(request, page):
document_list = list(Document.objects.all())
document_list.reverse()
paginator = Paginator(document_list, 4)
documents = get_documents(paginator, page)
context = {'documents': documents, 'category_list': categoryList, 'page_range': get_page_number_range(
paginator, documents)}
return render(request, 'jellyblog/index.html', context)
def category_detail(request, category_id):
return redirect("/category/" + category_id + "/page/1")
def category_with_page(request, category_id, page):
selectedCategory = Category.objects.get(id=category_id)
document_list = []
if (selectedCategory.parent == categoryList[0]):
children = Category.objects.all().filter(parent=selectedCategory.id)
for child in children:
document_list += Document.objects.all().filter(category_id=child.id)
document_list += Document.objects.all().filter(category=category_id)
document_list.sort(key=id, reverse=True)
paginator = Paginator(document_list, 4)
documents = get_documents(paginator, page)
context = {'documents': documents, 'category_list': categoryList, 'category_id': category_id,
'page_range': get_page_number_range(paginator, documents)}
return render(request, 'jellyblog/category.html', context)
def get_documents(paginator, page):
try:
documents = paginator.page(page)
except PageNotAnInteger:
documents = paginator.page(1)
except EmptyPage:
documents = paginator.page(paginator.num_pages)
return documents
def get_page_number_range(paginator, page):
print(paginator.num_pages)
if (paginator.num_pages < 11):
return range(1, paginator.num_pages+1)
elif (page.number - 5 > 1):
if (page.number + 4 < paginator.num_pages):
return range(page.number - 5, page.number + 5)
else:
return range(page.number - 5, paginator.num_pages + 1)
else:
return range(1,11)
def detail(request, document_id):
document = get_object_or_404(Document, pk=document_id)
document.view_count += 1
document.save()
return render(request, 'jellyblog/detail.html', {'document': document, 'category_list': categoryList})
| Python | 0.000001 |
65972062c03133a79ff77d90f8a11fd16f7d16ff | Correct column name | luigi/tasks/rfam/pgload_go_term_mapping.py | luigi/tasks/rfam/pgload_go_term_mapping.py | # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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 tasks.utils.pgloader import PGLoader
from tasks.go_terms.pgload_go_terms import PGLoadGoTerms
from .go_term_mapping_csv import RfamGoTermsCSV
from .pgload_families import RfamPGLoadFamilies
CONTROL_FILE = """LOAD CSV
FROM '{filename}' WITH ENCODING ISO-8859-14
HAVING FIELDS
(
go_term_id,
rfam_model_id
)
INTO {db_url}
TARGET COLUMNS
(
go_term_id,
rfam_model_id
)
SET
search_path = '{search_path}'
WITH
skip header = 1,
fields escaped by double-quote,
fields terminated by ','
BEFORE LOAD DO
$$
create table if not exists load_rfam_go_terms (
go_term_id character varying(10) COLLATE pg_catalog."default" NOT NULL,
rfam_model_id character varying(20) COLLATE pg_catalog."default" NOT NULL
);
$$,
$$
truncate table load_rfam_go_terms;
$$
AFTER LOAD DO
$$ insert into rfam_go_terms (
go_term_id,
rfam_model_id
) (
select
go_term_id,
rfam_model_id
from load_rfam_go_terms
)
ON CONFLICT (go_term_id, rfam_model_id) DO UPDATE SET
go_term_id = excluded.go_term_id,
rfam_model_id = excluded.rfam_model_id
;
$$,
$$
drop table load_rfam_go_terms;
$$
;
"""
class RfamPGLoadGoTerms(PGLoader): # pylint: disable=R0904
"""
This will run pgloader on the Rfam go term mapping CSV file. The importing
will update any existing mappings and will not produce duplicates.
"""
def requires(self):
return [
RfamGoTermsCSV(),
PGLoadGoTerms(),
RfamPGLoadFamilies(),
]
def control_file(self):
filename = RfamGoTermsCSV().output().fn
return CONTROL_FILE.format(
filename=filename,
db_url=self.db_url(table='load_rfam_go_terms'),
search_path=self.db_search_path(),
)
| # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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 tasks.utils.pgloader import PGLoader
from tasks.go_terms.pgload_go_terms import PGLoadGoTerms
from .go_term_mapping_csv import RfamGoTermsCSV
from .pgload_families import RfamPGLoadFamilies
CONTROL_FILE = """LOAD CSV
FROM '{filename}' WITH ENCODING ISO-8859-14
HAVING FIELDS
(
go_term_id,
rfam_model_id
)
INTO {db_url}
TARGET COLUMNS
(
go_term_id,
name
)
SET
search_path = '{search_path}'
WITH
skip header = 1,
fields escaped by double-quote,
fields terminated by ','
BEFORE LOAD DO
$$
create table if not exists load_rfam_go_terms (
go_term_id character varying(10) COLLATE pg_catalog."default" NOT NULL,
rfam_model_id character varying(20) COLLATE pg_catalog."default" NOT NULL
);
$$,
$$
truncate table load_rfam_go_terms;
$$
AFTER LOAD DO
$$ insert into rfam_go_terms (
go_term_id,
rfam_model_id
) (
select
go_term_id,
rfam_model_id
from load_rfam_go_terms
)
ON CONFLICT (go_term_id, rfam_model_id) DO UPDATE SET
go_term_id = excluded.go_term_id,
rfam_model_id = excluded.rfam_model_id
;
$$,
$$
drop table load_rfam_go_terms;
$$
;
"""
class RfamPGLoadGoTerms(PGLoader): # pylint: disable=R0904
"""
This will run pgloader on the Rfam go term mapping CSV file. The importing
will update any existing mappings and will not produce duplicates.
"""
def requires(self):
return [
RfamGoTermsCSV(),
PGLoadGoTerms(),
RfamPGLoadFamilies(),
]
def control_file(self):
filename = RfamGoTermsCSV().output().fn
return CONTROL_FILE.format(
filename=filename,
db_url=self.db_url(table='load_rfam_go_terms'),
search_path=self.db_search_path(),
)
| Python | 0 |
a9aad224d6875e774cd0f7db7e30965ea6a3fbdc | Fix simple typo: taget -> target (#591) | algorithms/search/jump_search.py | algorithms/search/jump_search.py | import math
def jump_search(arr,target):
"""Jump Search
Worst-case Complexity: O(√n) (root(n))
All items in list must be sorted like binary search
Find block that contains target value and search it linearly in that block
It returns a first target value in array
reference: https://en.wikipedia.org/wiki/Jump_search
"""
n = len(arr)
block_size = int(math.sqrt(n))
block_prev = 0
block= block_size
# return -1 means that array doesn't contain target value
# find block that contains target value
if arr[n - 1] < target:
return -1
while block <= n and arr[block - 1] < target:
block_prev = block
block += block_size
# find target value in block
while arr[block_prev] < target :
block_prev += 1
if block_prev == min(block, n) :
return -1
# if there is target value in array, return it
if arr[block_prev] == target :
return block_prev
else :
return -1
| import math
def jump_search(arr,target):
"""Jump Search
Worst-case Complexity: O(√n) (root(n))
All items in list must be sorted like binary search
Find block that contains target value and search it linearly in that block
It returns a first target value in array
reference: https://en.wikipedia.org/wiki/Jump_search
"""
n = len(arr)
block_size = int(math.sqrt(n))
block_prev = 0
block= block_size
# return -1 means that array doesn't contain taget value
# find block that contains target value
if arr[n - 1] < target:
return -1
while block <= n and arr[block - 1] < target:
block_prev = block
block += block_size
# find target value in block
while arr[block_prev] < target :
block_prev += 1
if block_prev == min(block, n) :
return -1
# if there is target value in array, return it
if arr[block_prev] == target :
return block_prev
else :
return -1
| Python | 0.999977 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.