text stringlengths 0 1.05M | meta dict |
|---|---|
"""Add support for OAuth to let users to connect the bot various services."""
from plumeria.command import commands
from plumeria.core.storage import pool, migrations
from plumeria.core.webserver import app, render_template
from plumeria.message import Message, Response
from plumeria.perms import direct_only
from plumeria.core.oauth.manager import *
from plumeria.core.oauth.storage import *
__requires__ = ['plumeria.core.storage']
def find_endpoint(name) -> Endpoint:
try:
return oauth_manager.get_endpoint(name)
except KeyError:
raise CommandError("No such service **{}** exists.".format(name))
@commands.create('connect', cost=4, category='Services')
@direct_only
async def connect(message: Message):
"""
Authenticate yourself to a service and provide the bot with permissions of your choosing.
Example::
/connect spotify
"""
endpoint = find_endpoint(message.content.strip())
try:
url = await endpoint.request_authorization(message.author)
return Response("You will have to visit this link to connect your account: {}" \
"\n\nYou can later disable access from your account settings on the website.".format(url),
private=True)
except NotImplementedError as e:
raise CommandError("Could not connect service: {}".format(str(e)))
@app.route("/oauth2/callback/", methods=['GET'])
async def handle(request):
error = request.GET.get("error", "")
code = request.GET.get("code", "")
state = request.GET.get("state", "")
if not len(error):
try:
await oauth_manager.process_request_authorization(state, code)
return render_template("oauth/success.html")
except UnknownFlowError:
return render_template("oauth/error.html",
error="The link you have visited has expired.")
except FlowError:
return render_template("oauth/error.html",
error="We were unable to contact the service to check that you authorized access.")
else:
await oauth_manager.cancel_request_authorization(state, error)
return render_template("oauth/error.html",
error="Something went wrong while connecting to the service. The service says: {}".format(
error[:200]))
async def setup():
commands.add(connect)
app.add(handle)
store = DatabaseTokens(pool, migrations)
await store.initialize()
oauth_manager.redirect_uri = await app.get_base_url() + "/oauth2/callback/"
oauth_manager.store = store
| {
"repo_name": "sk89q/Plumeria",
"path": "plumeria/core/oauth/__init__.py",
"copies": "1",
"size": "2668",
"license": "mit",
"hash": 4938114116975566000,
"line_mean": 36.5774647887,
"line_max": 121,
"alpha_frac": 0.6495502249,
"autogenerated": false,
"ratio": 4.3881578947368425,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5537708119636843,
"avg_score": null,
"num_lines": null
} |
"""Add support for the Xiaomi TVs."""
import logging
import pymitv
import voluptuous as vol
from homeassistant.components.media_player import PLATFORM_SCHEMA, MediaPlayerDevice
from homeassistant.components.media_player.const import (
SUPPORT_TURN_OFF,
SUPPORT_TURN_ON,
SUPPORT_VOLUME_STEP,
)
from homeassistant.const import CONF_HOST, CONF_NAME, STATE_OFF, STATE_ON
import homeassistant.helpers.config_validation as cv
DEFAULT_NAME = "Xiaomi TV"
_LOGGER = logging.getLogger(__name__)
SUPPORT_XIAOMI_TV = SUPPORT_VOLUME_STEP | SUPPORT_TURN_ON | SUPPORT_TURN_OFF
# No host is needed for configuration, however it can be set.
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Xiaomi TV platform."""
# If a hostname is set. Discovery is skipped.
host = config.get(CONF_HOST)
name = config.get(CONF_NAME)
if host is not None:
# Check if there's a valid TV at the IP address.
if not pymitv.Discover().check_ip(host):
_LOGGER.error("Could not find Xiaomi TV with specified IP: %s", host)
else:
# Register TV with Home Assistant.
add_entities([XiaomiTV(host, name)])
else:
# Otherwise, discover TVs on network.
add_entities(XiaomiTV(tv, DEFAULT_NAME) for tv in pymitv.Discover().scan())
class XiaomiTV(MediaPlayerDevice):
"""Represent the Xiaomi TV for Home Assistant."""
def __init__(self, ip, name):
"""Receive IP address and name to construct class."""
# Initialize the Xiaomi TV.
self._tv = pymitv.TV(ip)
# Default name value, only to be overridden by user.
self._name = name
self._state = STATE_OFF
@property
def name(self):
"""Return the display name of this TV."""
return self._name
@property
def state(self):
"""Return _state variable, containing the appropriate constant."""
return self._state
@property
def assumed_state(self):
"""Indicate that state is assumed."""
return True
@property
def supported_features(self):
"""Flag media player features that are supported."""
return SUPPORT_XIAOMI_TV
def turn_off(self):
"""
Instruct the TV to turn sleep.
This is done instead of turning off,
because the TV won't accept any input when turned off. Thus, the user
would be unable to turn the TV back on, unless it's done manually.
"""
if self._state is not STATE_OFF:
self._tv.sleep()
self._state = STATE_OFF
def turn_on(self):
"""Wake the TV back up from sleep."""
if self._state is not STATE_ON:
self._tv.wake()
self._state = STATE_ON
def volume_up(self):
"""Increase volume by one."""
self._tv.volume_up()
def volume_down(self):
"""Decrease volume by one."""
self._tv.volume_down()
| {
"repo_name": "postlund/home-assistant",
"path": "homeassistant/components/xiaomi_tv/media_player.py",
"copies": "3",
"size": "3138",
"license": "apache-2.0",
"hash": 9102530057879929000,
"line_mean": 28.0555555556,
"line_max": 84,
"alpha_frac": 0.6290630975,
"autogenerated": false,
"ratio": 3.8268292682926828,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5955892365792683,
"avg_score": null,
"num_lines": null
} |
"""Add support for the Xiaomi TVs."""
import logging
import pymitv
import voluptuous as vol
from homeassistant.components.media_player import PLATFORM_SCHEMA, MediaPlayerEntity
from homeassistant.components.media_player.const import (
SUPPORT_TURN_OFF,
SUPPORT_TURN_ON,
SUPPORT_VOLUME_STEP,
)
from homeassistant.const import CONF_HOST, CONF_NAME, STATE_OFF, STATE_ON
import homeassistant.helpers.config_validation as cv
DEFAULT_NAME = "Xiaomi TV"
_LOGGER = logging.getLogger(__name__)
SUPPORT_XIAOMI_TV = SUPPORT_VOLUME_STEP | SUPPORT_TURN_ON | SUPPORT_TURN_OFF
# No host is needed for configuration, however it can be set.
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Xiaomi TV platform."""
# If a hostname is set. Discovery is skipped.
host = config.get(CONF_HOST)
name = config.get(CONF_NAME)
if host is not None:
# Check if there's a valid TV at the IP address.
if not pymitv.Discover().check_ip(host):
_LOGGER.error("Could not find Xiaomi TV with specified IP: %s", host)
else:
# Register TV with Home Assistant.
add_entities([XiaomiTV(host, name)])
else:
# Otherwise, discover TVs on network.
add_entities(XiaomiTV(tv, DEFAULT_NAME) for tv in pymitv.Discover().scan())
class XiaomiTV(MediaPlayerEntity):
"""Represent the Xiaomi TV for Home Assistant."""
def __init__(self, ip, name):
"""Receive IP address and name to construct class."""
# Initialize the Xiaomi TV.
self._tv = pymitv.TV(ip)
# Default name value, only to be overridden by user.
self._name = name
self._state = STATE_OFF
@property
def name(self):
"""Return the display name of this TV."""
return self._name
@property
def state(self):
"""Return _state variable, containing the appropriate constant."""
return self._state
@property
def assumed_state(self):
"""Indicate that state is assumed."""
return True
@property
def supported_features(self):
"""Flag media player features that are supported."""
return SUPPORT_XIAOMI_TV
def turn_off(self):
"""
Instruct the TV to turn sleep.
This is done instead of turning off,
because the TV won't accept any input when turned off. Thus, the user
would be unable to turn the TV back on, unless it's done manually.
"""
if self._state != STATE_OFF:
self._tv.sleep()
self._state = STATE_OFF
def turn_on(self):
"""Wake the TV back up from sleep."""
if self._state != STATE_ON:
self._tv.wake()
self._state = STATE_ON
def volume_up(self):
"""Increase volume by one."""
self._tv.volume_up()
def volume_down(self):
"""Decrease volume by one."""
self._tv.volume_down()
| {
"repo_name": "tchellomello/home-assistant",
"path": "homeassistant/components/xiaomi_tv/media_player.py",
"copies": "21",
"size": "3130",
"license": "apache-2.0",
"hash": 1234339652272674000,
"line_mean": 27.9814814815,
"line_max": 84,
"alpha_frac": 0.6274760383,
"autogenerated": false,
"ratio": 3.82640586797066,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""Add support for the Xiaomi TVs."""
import logging
import voluptuous as vol
import pymitv
from homeassistant.components.media_player import MediaPlayerDevice, PLATFORM_SCHEMA
from homeassistant.components.media_player.const import (
SUPPORT_TURN_OFF,
SUPPORT_TURN_ON,
SUPPORT_VOLUME_STEP,
)
from homeassistant.const import CONF_HOST, CONF_NAME, STATE_OFF, STATE_ON
import homeassistant.helpers.config_validation as cv
DEFAULT_NAME = "Xiaomi TV"
_LOGGER = logging.getLogger(__name__)
SUPPORT_XIAOMI_TV = SUPPORT_VOLUME_STEP | SUPPORT_TURN_ON | SUPPORT_TURN_OFF
# No host is needed for configuration, however it can be set.
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Xiaomi TV platform."""
# If a hostname is set. Discovery is skipped.
host = config.get(CONF_HOST)
name = config.get(CONF_NAME)
if host is not None:
# Check if there's a valid TV at the IP address.
if not pymitv.Discover().check_ip(host):
_LOGGER.error("Could not find Xiaomi TV with specified IP: %s", host)
else:
# Register TV with Home Assistant.
add_entities([XiaomiTV(host, name)])
else:
# Otherwise, discover TVs on network.
add_entities(XiaomiTV(tv, DEFAULT_NAME) for tv in pymitv.Discover().scan())
class XiaomiTV(MediaPlayerDevice):
"""Represent the Xiaomi TV for Home Assistant."""
def __init__(self, ip, name):
"""Receive IP address and name to construct class."""
# Initialize the Xiaomi TV.
self._tv = pymitv.TV(ip)
# Default name value, only to be overridden by user.
self._name = name
self._state = STATE_OFF
@property
def name(self):
"""Return the display name of this TV."""
return self._name
@property
def state(self):
"""Return _state variable, containing the appropriate constant."""
return self._state
@property
def assumed_state(self):
"""Indicate that state is assumed."""
return True
@property
def supported_features(self):
"""Flag media player features that are supported."""
return SUPPORT_XIAOMI_TV
def turn_off(self):
"""
Instruct the TV to turn sleep.
This is done instead of turning off,
because the TV won't accept any input when turned off. Thus, the user
would be unable to turn the TV back on, unless it's done manually.
"""
if self._state is not STATE_OFF:
self._tv.sleep()
self._state = STATE_OFF
def turn_on(self):
"""Wake the TV back up from sleep."""
if self._state is not STATE_ON:
self._tv.wake()
self._state = STATE_ON
def volume_up(self):
"""Increase volume by one."""
self._tv.volume_up()
def volume_down(self):
"""Decrease volume by one."""
self._tv.volume_down()
| {
"repo_name": "joopert/home-assistant",
"path": "homeassistant/components/xiaomi_tv/media_player.py",
"copies": "2",
"size": "3138",
"license": "apache-2.0",
"hash": -8413457378054953000,
"line_mean": 28.0555555556,
"line_max": 84,
"alpha_frac": 0.6290630975,
"autogenerated": false,
"ratio": 3.8268292682926828,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.000332079534614207,
"num_lines": 108
} |
"""Add support for the Xiaomi TVs."""
import logging
import voluptuous as vol
from homeassistant.components.media_player import MediaPlayerDevice, PLATFORM_SCHEMA
from homeassistant.components.media_player.const import (
SUPPORT_TURN_OFF,
SUPPORT_TURN_ON,
SUPPORT_VOLUME_STEP,
)
from homeassistant.const import CONF_HOST, CONF_NAME, STATE_OFF, STATE_ON
import homeassistant.helpers.config_validation as cv
DEFAULT_NAME = "Xiaomi TV"
_LOGGER = logging.getLogger(__name__)
SUPPORT_XIAOMI_TV = SUPPORT_VOLUME_STEP | SUPPORT_TURN_ON | SUPPORT_TURN_OFF
# No host is needed for configuration, however it can be set.
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Xiaomi TV platform."""
from pymitv import Discover
# If a hostname is set. Discovery is skipped.
host = config.get(CONF_HOST)
name = config.get(CONF_NAME)
if host is not None:
# Check if there's a valid TV at the IP address.
if not Discover().check_ip(host):
_LOGGER.error("Could not find Xiaomi TV with specified IP: %s", host)
else:
# Register TV with Home Assistant.
add_entities([XiaomiTV(host, name)])
else:
# Otherwise, discover TVs on network.
add_entities(XiaomiTV(tv, DEFAULT_NAME) for tv in Discover().scan())
class XiaomiTV(MediaPlayerDevice):
"""Represent the Xiaomi TV for Home Assistant."""
def __init__(self, ip, name):
"""Receive IP address and name to construct class."""
# Import pymitv library.
from pymitv import TV
# Initialize the Xiaomi TV.
self._tv = TV(ip)
# Default name value, only to be overridden by user.
self._name = name
self._state = STATE_OFF
@property
def name(self):
"""Return the display name of this TV."""
return self._name
@property
def state(self):
"""Return _state variable, containing the appropriate constant."""
return self._state
@property
def assumed_state(self):
"""Indicate that state is assumed."""
return True
@property
def supported_features(self):
"""Flag media player features that are supported."""
return SUPPORT_XIAOMI_TV
def turn_off(self):
"""
Instruct the TV to turn sleep.
This is done instead of turning off,
because the TV won't accept any input when turned off. Thus, the user
would be unable to turn the TV back on, unless it's done manually.
"""
if self._state is not STATE_OFF:
self._tv.sleep()
self._state = STATE_OFF
def turn_on(self):
"""Wake the TV back up from sleep."""
if self._state is not STATE_ON:
self._tv.wake()
self._state = STATE_ON
def volume_up(self):
"""Increase volume by one."""
self._tv.volume_up()
def volume_down(self):
"""Decrease volume by one."""
self._tv.volume_down()
| {
"repo_name": "fbradyirl/home-assistant",
"path": "homeassistant/components/xiaomi_tv/media_player.py",
"copies": "2",
"size": "3198",
"license": "apache-2.0",
"hash": 797242635017657300,
"line_mean": 28.0727272727,
"line_max": 84,
"alpha_frac": 0.6269543465,
"autogenerated": false,
"ratio": 3.871670702179177,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0002178166166688405,
"num_lines": 110
} |
"""Add support for the Xiaomi TVs."""
import logging
import voluptuous as vol
from homeassistant.components.media_player import (
MediaPlayerDevice, PLATFORM_SCHEMA)
from homeassistant.components.media_player.const import (
SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_STEP)
from homeassistant.const import CONF_HOST, CONF_NAME, STATE_OFF, STATE_ON
import homeassistant.helpers.config_validation as cv
DEFAULT_NAME = "Xiaomi TV"
_LOGGER = logging.getLogger(__name__)
SUPPORT_XIAOMI_TV = SUPPORT_VOLUME_STEP | SUPPORT_TURN_ON | \
SUPPORT_TURN_OFF
# No host is needed for configuration, however it can be set.
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Xiaomi TV platform."""
from pymitv import Discover
# If a hostname is set. Discovery is skipped.
host = config.get(CONF_HOST)
name = config.get(CONF_NAME)
if host is not None:
# Check if there's a valid TV at the IP address.
if not Discover().check_ip(host):
_LOGGER.error(
"Could not find Xiaomi TV with specified IP: %s", host)
else:
# Register TV with Home Assistant.
add_entities([XiaomiTV(host, name)])
else:
# Otherwise, discover TVs on network.
add_entities(XiaomiTV(tv, DEFAULT_NAME) for tv in Discover().scan())
class XiaomiTV(MediaPlayerDevice):
"""Represent the Xiaomi TV for Home Assistant."""
def __init__(self, ip, name):
"""Receive IP address and name to construct class."""
# Import pymitv library.
from pymitv import TV
# Initialize the Xiaomi TV.
self._tv = TV(ip)
# Default name value, only to be overridden by user.
self._name = name
self._state = STATE_OFF
@property
def name(self):
"""Return the display name of this TV."""
return self._name
@property
def state(self):
"""Return _state variable, containing the appropriate constant."""
return self._state
@property
def assumed_state(self):
"""Indicate that state is assumed."""
return True
@property
def supported_features(self):
"""Flag media player features that are supported."""
return SUPPORT_XIAOMI_TV
def turn_off(self):
"""
Instruct the TV to turn sleep.
This is done instead of turning off,
because the TV won't accept any input when turned off. Thus, the user
would be unable to turn the TV back on, unless it's done manually.
"""
if self._state is not STATE_OFF:
self._tv.sleep()
self._state = STATE_OFF
def turn_on(self):
"""Wake the TV back up from sleep."""
if self._state is not STATE_ON:
self._tv.wake()
self._state = STATE_ON
def volume_up(self):
"""Increase volume by one."""
self._tv.volume_up()
def volume_down(self):
"""Decrease volume by one."""
self._tv.volume_down()
| {
"repo_name": "jabesq/home-assistant",
"path": "homeassistant/components/xiaomi_tv/media_player.py",
"copies": "7",
"size": "3216",
"license": "apache-2.0",
"hash": 3707387483623341600,
"line_mean": 28.7777777778,
"line_max": 77,
"alpha_frac": 0.6234452736,
"autogenerated": false,
"ratio": 3.898181818181818,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8021627091781817,
"avg_score": null,
"num_lines": null
} |
"""Adds users.stripe_customer_id column and the transaction table
Revision ID: e63d9d5e76a9
Revises: 9f2495bd66de
Create Date: 2017-07-24 22:44:33.650136
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = 'e63d9d5e76a9'
down_revision = '9f2495bd66de'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('transaction',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
sa.Column('meal_id', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('payer_id', sa.Integer(), nullable=False),
sa.Column('payee_id', sa.Integer(), nullable=False),
sa.Column('transaction_went_through', sa.Boolean(), nullable=False),
sa.Column('transaction_paid_out', sa.Boolean(), nullable=False),
sa.Column('canceled', sa.Boolean(), nullable=False),
sa.Column('refunded', sa.Boolean(), nullable=False),
sa.Column('stripe_idempotency_key', postgresql.UUID(as_uuid=True), nullable=False),
sa.Column('amount', sa.Float(), nullable=False),
sa.Column('stripe_payload', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.ForeignKeyConstraint(['meal_id'], ['meal.id'], ),
sa.ForeignKeyConstraint(['payee_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['payer_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.add_column('users', sa.Column('stripe_customer_id', sa.String(length=80), nullable=True))
op.create_index(op.f('ix_users_stripe_customer_id'), 'users', ['stripe_customer_id'], unique=True)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_users_stripe_customer_id'), table_name='users')
op.drop_column('users', 'stripe_customer_id')
op.drop_table('transaction')
# ### end Alembic commands ###
| {
"repo_name": "Rdbaker/Mealbound",
"path": "migrations/versions/e63d9d5e76a9_.py",
"copies": "1",
"size": "2031",
"license": "bsd-3-clause",
"hash": -4147860588908593700,
"line_mean": 40.4489795918,
"line_max": 102,
"alpha_frac": 0.6863613983,
"autogenerated": false,
"ratio": 3.313213703099511,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9467910715808676,
"avg_score": 0.006332877118166769,
"num_lines": 49
} |
"""Adds VM to specified network by creating a NIC"""
from baseCmd import *
from baseResponse import *
class addNicToVirtualMachineCmd (baseCmd):
typeInfo = {}
def __init__(self):
self.isAsync = "true"
"""Network ID"""
"""Required"""
self.networkid = None
self.typeInfo['networkid'] = 'uuid'
"""Virtual Machine ID"""
"""Required"""
self.virtualmachineid = None
self.typeInfo['virtualmachineid'] = 'uuid'
"""IP Address for the new network"""
self.ipaddress = None
self.typeInfo['ipaddress'] = 'string'
self.required = ["networkid", "virtualmachineid", ]
class addNicToVirtualMachineResponse (baseResponse):
typeInfo = {}
def __init__(self):
"""the ID of the virtual machine"""
self.id = None
self.typeInfo['id'] = 'string'
"""the account associated with the virtual machine"""
self.account = None
self.typeInfo['account'] = 'string'
"""the number of cpu this virtual machine is running with"""
self.cpunumber = None
self.typeInfo['cpunumber'] = 'integer'
"""the speed of each cpu"""
self.cpuspeed = None
self.typeInfo['cpuspeed'] = 'integer'
"""the amount of the vm's CPU currently used"""
self.cpuused = None
self.typeInfo['cpuused'] = 'string'
"""the date when this virtual machine was created"""
self.created = None
self.typeInfo['created'] = 'date'
"""Vm details in key/value pairs."""
self.details = None
self.typeInfo['details'] = 'map'
"""the read (io) of disk on the vm"""
self.diskioread = None
self.typeInfo['diskioread'] = 'long'
"""the write (io) of disk on the vm"""
self.diskiowrite = None
self.typeInfo['diskiowrite'] = 'long'
"""the read (bytes) of disk on the vm"""
self.diskkbsread = None
self.typeInfo['diskkbsread'] = 'long'
"""the write (bytes) of disk on the vm"""
self.diskkbswrite = None
self.typeInfo['diskkbswrite'] = 'long'
"""the ID of the disk offering of the virtual machine"""
self.diskofferingid = None
self.typeInfo['diskofferingid'] = 'string'
"""the name of the disk offering of the virtual machine"""
self.diskofferingname = None
self.typeInfo['diskofferingname'] = 'string'
"""user generated name. The name of the virtual machine is returned if no displayname exists."""
self.displayname = None
self.typeInfo['displayname'] = 'string'
"""an optional field whether to the display the vm to the end user or not."""
self.displayvm = None
self.typeInfo['displayvm'] = 'boolean'
"""the name of the domain in which the virtual machine exists"""
self.domain = None
self.typeInfo['domain'] = 'string'
"""the ID of the domain in which the virtual machine exists"""
self.domainid = None
self.typeInfo['domainid'] = 'string'
"""the virtual network for the service offering"""
self.forvirtualnetwork = None
self.typeInfo['forvirtualnetwork'] = 'boolean'
"""the group name of the virtual machine"""
self.group = None
self.typeInfo['group'] = 'string'
"""the group ID of the virtual machine"""
self.groupid = None
self.typeInfo['groupid'] = 'string'
"""Os type ID of the virtual machine"""
self.guestosid = None
self.typeInfo['guestosid'] = 'string'
"""true if high-availability is enabled, false otherwise"""
self.haenable = None
self.typeInfo['haenable'] = 'boolean'
"""the ID of the host for the virtual machine"""
self.hostid = None
self.typeInfo['hostid'] = 'string'
"""the name of the host for the virtual machine"""
self.hostname = None
self.typeInfo['hostname'] = 'string'
"""the hypervisor on which the template runs"""
self.hypervisor = None
self.typeInfo['hypervisor'] = 'string'
"""instance name of the user vm; this parameter is returned to the ROOT admin only"""
self.instancename = None
self.typeInfo['instancename'] = 'string'
"""true if vm contains XS tools inorder to support dynamic scaling of VM cpu/memory."""
self.isdynamicallyscalable = None
self.typeInfo['isdynamicallyscalable'] = 'boolean'
"""an alternate display text of the ISO attached to the virtual machine"""
self.isodisplaytext = None
self.typeInfo['isodisplaytext'] = 'string'
"""the ID of the ISO attached to the virtual machine"""
self.isoid = None
self.typeInfo['isoid'] = 'string'
"""the name of the ISO attached to the virtual machine"""
self.isoname = None
self.typeInfo['isoname'] = 'string'
"""ssh key-pair"""
self.keypair = None
self.typeInfo['keypair'] = 'string'
"""the memory allocated for the virtual machine"""
self.memory = None
self.typeInfo['memory'] = 'integer'
"""the name of the virtual machine"""
self.name = None
self.typeInfo['name'] = 'string'
"""the incoming network traffic on the vm"""
self.networkkbsread = None
self.typeInfo['networkkbsread'] = 'long'
"""the outgoing network traffic on the host"""
self.networkkbswrite = None
self.typeInfo['networkkbswrite'] = 'long'
"""OS type id of the vm"""
self.ostypeid = None
self.typeInfo['ostypeid'] = 'long'
"""the password (if exists) of the virtual machine"""
self.password = None
self.typeInfo['password'] = 'string'
"""true if the password rest feature is enabled, false otherwise"""
self.passwordenabled = None
self.typeInfo['passwordenabled'] = 'boolean'
"""the project name of the vm"""
self.project = None
self.typeInfo['project'] = 'string'
"""the project id of the vm"""
self.projectid = None
self.typeInfo['projectid'] = 'string'
"""public IP address id associated with vm via Static nat rule"""
self.publicip = None
self.typeInfo['publicip'] = 'string'
"""public IP address id associated with vm via Static nat rule"""
self.publicipid = None
self.typeInfo['publicipid'] = 'string'
"""device ID of the root volume"""
self.rootdeviceid = None
self.typeInfo['rootdeviceid'] = 'long'
"""device type of the root volume"""
self.rootdevicetype = None
self.typeInfo['rootdevicetype'] = 'string'
"""the ID of the service offering of the virtual machine"""
self.serviceofferingid = None
self.typeInfo['serviceofferingid'] = 'string'
"""the name of the service offering of the virtual machine"""
self.serviceofferingname = None
self.typeInfo['serviceofferingname'] = 'string'
"""State of the Service from LB rule"""
self.servicestate = None
self.typeInfo['servicestate'] = 'string'
"""the state of the virtual machine"""
self.state = None
self.typeInfo['state'] = 'string'
"""an alternate display text of the template for the virtual machine"""
self.templatedisplaytext = None
self.typeInfo['templatedisplaytext'] = 'string'
"""the ID of the template for the virtual machine. A -1 is returned if the virtual machine was created from an ISO file."""
self.templateid = None
self.typeInfo['templateid'] = 'string'
"""the name of the template for the virtual machine"""
self.templatename = None
self.typeInfo['templatename'] = 'string'
"""the user's ID who deployed the virtual machine"""
self.userid = None
self.typeInfo['userid'] = 'string'
"""the user's name who deployed the virtual machine"""
self.username = None
self.typeInfo['username'] = 'string'
"""the vgpu type used by the virtual machine"""
self.vgpu = None
self.typeInfo['vgpu'] = 'string'
"""the ID of the availablility zone for the virtual machine"""
self.zoneid = None
self.typeInfo['zoneid'] = 'string'
"""the name of the availability zone for the virtual machine"""
self.zonename = None
self.typeInfo['zonename'] = 'string'
"""list of affinity groups associated with the virtual machine"""
self.affinitygroup = []
"""the list of nics associated with vm"""
self.nic = []
"""list of security groups associated with the virtual machine"""
self.securitygroup = []
"""the list of resource tags associated with vm"""
self.tags = []
"""the ID of the latest async job acting on this object"""
self.jobid = None
self.typeInfo['jobid'] = ''
"""the current status of the latest async job acting on this object"""
self.jobstatus = None
self.typeInfo['jobstatus'] = ''
class affinitygroup:
def __init__(self):
""""the ID of the affinity group"""
self.id = None
""""the account owning the affinity group"""
self.account = None
""""the description of the affinity group"""
self.description = None
""""the domain name of the affinity group"""
self.domain = None
""""the domain ID of the affinity group"""
self.domainid = None
""""the name of the affinity group"""
self.name = None
""""the project name of the affinity group"""
self.project = None
""""the project ID of the affinity group"""
self.projectid = None
""""the type of the affinity group"""
self.type = None
""""virtual machine IDs associated with this affinity group"""
self.virtualmachineIds = None
class nic:
def __init__(self):
""""the ID of the nic"""
self.id = None
""""the broadcast uri of the nic"""
self.broadcasturi = None
""""device id for the network when plugged into the virtual machine"""
self.deviceid = None
""""the gateway of the nic"""
self.gateway = None
""""the IPv6 address of network"""
self.ip6address = None
""""the cidr of IPv6 network"""
self.ip6cidr = None
""""the gateway of IPv6 network"""
self.ip6gateway = None
""""the ip address of the nic"""
self.ipaddress = None
""""true if nic is default, false otherwise"""
self.isdefault = None
""""the isolation uri of the nic"""
self.isolationuri = None
""""true if nic is default, false otherwise"""
self.macaddress = None
""""the netmask of the nic"""
self.netmask = None
""""the ID of the corresponding network"""
self.networkid = None
""""the name of the corresponding network"""
self.networkname = None
""""the Secondary ipv4 addr of nic"""
self.secondaryip = None
""""the traffic type of the nic"""
self.traffictype = None
""""the type of the nic"""
self.type = None
""""Id of the vm to which the nic belongs"""
self.virtualmachineid = None
class tags:
def __init__(self):
""""the account associated with the tag"""
self.account = None
""""customer associated with the tag"""
self.customer = None
""""the domain associated with the tag"""
self.domain = None
""""the ID of the domain associated with the tag"""
self.domainid = None
""""tag key name"""
self.key = None
""""the project name where tag belongs to"""
self.project = None
""""the project id the tag belongs to"""
self.projectid = None
""""id of the resource"""
self.resourceid = None
""""resource type"""
self.resourcetype = None
""""tag value"""
self.value = None
class egressrule:
def __init__(self):
""""account owning the security group rule"""
self.account = None
""""the CIDR notation for the base IP address of the security group rule"""
self.cidr = None
""""the ending IP of the security group rule"""
self.endport = None
""""the code for the ICMP message response"""
self.icmpcode = None
""""the type of the ICMP message response"""
self.icmptype = None
""""the protocol of the security group rule"""
self.protocol = None
""""the id of the security group rule"""
self.ruleid = None
""""security group name"""
self.securitygroupname = None
""""the starting IP of the security group rule"""
self.startport = None
""""the list of resource tags associated with the rule"""
self.tags = []
""""the account associated with the tag"""
self.account = None
""""customer associated with the tag"""
self.customer = None
""""the domain associated with the tag"""
self.domain = None
""""the ID of the domain associated with the tag"""
self.domainid = None
""""tag key name"""
self.key = None
""""the project name where tag belongs to"""
self.project = None
""""the project id the tag belongs to"""
self.projectid = None
""""id of the resource"""
self.resourceid = None
""""resource type"""
self.resourcetype = None
""""tag value"""
self.value = None
class tags:
def __init__(self):
""""the account associated with the tag"""
self.account = None
""""customer associated with the tag"""
self.customer = None
""""the domain associated with the tag"""
self.domain = None
""""the ID of the domain associated with the tag"""
self.domainid = None
""""tag key name"""
self.key = None
""""the project name where tag belongs to"""
self.project = None
""""the project id the tag belongs to"""
self.projectid = None
""""id of the resource"""
self.resourceid = None
""""resource type"""
self.resourcetype = None
""""tag value"""
self.value = None
class tags:
def __init__(self):
""""the account associated with the tag"""
self.account = None
""""customer associated with the tag"""
self.customer = None
""""the domain associated with the tag"""
self.domain = None
""""the ID of the domain associated with the tag"""
self.domainid = None
""""tag key name"""
self.key = None
""""the project name where tag belongs to"""
self.project = None
""""the project id the tag belongs to"""
self.projectid = None
""""id of the resource"""
self.resourceid = None
""""resource type"""
self.resourcetype = None
""""tag value"""
self.value = None
class ingressrule:
def __init__(self):
""""account owning the security group rule"""
self.account = None
""""the CIDR notation for the base IP address of the security group rule"""
self.cidr = None
""""the ending IP of the security group rule"""
self.endport = None
""""the code for the ICMP message response"""
self.icmpcode = None
""""the type of the ICMP message response"""
self.icmptype = None
""""the protocol of the security group rule"""
self.protocol = None
""""the id of the security group rule"""
self.ruleid = None
""""security group name"""
self.securitygroupname = None
""""the starting IP of the security group rule"""
self.startport = None
""""the list of resource tags associated with the rule"""
self.tags = []
""""the account associated with the tag"""
self.account = None
""""customer associated with the tag"""
self.customer = None
""""the domain associated with the tag"""
self.domain = None
""""the ID of the domain associated with the tag"""
self.domainid = None
""""tag key name"""
self.key = None
""""the project name where tag belongs to"""
self.project = None
""""the project id the tag belongs to"""
self.projectid = None
""""id of the resource"""
self.resourceid = None
""""resource type"""
self.resourcetype = None
""""tag value"""
self.value = None
class tags:
def __init__(self):
""""the account associated with the tag"""
self.account = None
""""customer associated with the tag"""
self.customer = None
""""the domain associated with the tag"""
self.domain = None
""""the ID of the domain associated with the tag"""
self.domainid = None
""""tag key name"""
self.key = None
""""the project name where tag belongs to"""
self.project = None
""""the project id the tag belongs to"""
self.projectid = None
""""id of the resource"""
self.resourceid = None
""""resource type"""
self.resourcetype = None
""""tag value"""
self.value = None
class tags:
def __init__(self):
""""the account associated with the tag"""
self.account = None
""""customer associated with the tag"""
self.customer = None
""""the domain associated with the tag"""
self.domain = None
""""the ID of the domain associated with the tag"""
self.domainid = None
""""tag key name"""
self.key = None
""""the project name where tag belongs to"""
self.project = None
""""the project id the tag belongs to"""
self.projectid = None
""""id of the resource"""
self.resourceid = None
""""resource type"""
self.resourcetype = None
""""tag value"""
self.value = None
class securitygroup:
def __init__(self):
""""the ID of the security group"""
self.id = None
""""the account owning the security group"""
self.account = None
""""the description of the security group"""
self.description = None
""""the domain name of the security group"""
self.domain = None
""""the domain ID of the security group"""
self.domainid = None
""""the name of the security group"""
self.name = None
""""the project name of the group"""
self.project = None
""""the project id of the group"""
self.projectid = None
""""the number of virtualmachines associated with this securitygroup"""
self.virtualmachinecount = None
""""the list of virtualmachine ids associated with this securitygroup"""
self.virtualmachineids = None
""""the list of egress rules associated with the security group"""
self.egressrule = []
""""account owning the security group rule"""
self.account = None
""""the CIDR notation for the base IP address of the security group rule"""
self.cidr = None
""""the ending IP of the security group rule"""
self.endport = None
""""the code for the ICMP message response"""
self.icmpcode = None
""""the type of the ICMP message response"""
self.icmptype = None
""""the protocol of the security group rule"""
self.protocol = None
""""the id of the security group rule"""
self.ruleid = None
""""security group name"""
self.securitygroupname = None
""""the starting IP of the security group rule"""
self.startport = None
""""the list of resource tags associated with the rule"""
self.tags = []
""""the account associated with the tag"""
self.account = None
""""customer associated with the tag"""
self.customer = None
""""the domain associated with the tag"""
self.domain = None
""""the ID of the domain associated with the tag"""
self.domainid = None
""""tag key name"""
self.key = None
""""the project name where tag belongs to"""
self.project = None
""""the project id the tag belongs to"""
self.projectid = None
""""id of the resource"""
self.resourceid = None
""""resource type"""
self.resourcetype = None
""""tag value"""
self.value = None
""""the list of ingress rules associated with the security group"""
self.ingressrule = []
""""account owning the security group rule"""
self.account = None
""""the CIDR notation for the base IP address of the security group rule"""
self.cidr = None
""""the ending IP of the security group rule"""
self.endport = None
""""the code for the ICMP message response"""
self.icmpcode = None
""""the type of the ICMP message response"""
self.icmptype = None
""""the protocol of the security group rule"""
self.protocol = None
""""the id of the security group rule"""
self.ruleid = None
""""security group name"""
self.securitygroupname = None
""""the starting IP of the security group rule"""
self.startport = None
""""the list of resource tags associated with the rule"""
self.tags = []
""""the account associated with the tag"""
self.account = None
""""customer associated with the tag"""
self.customer = None
""""the domain associated with the tag"""
self.domain = None
""""the ID of the domain associated with the tag"""
self.domainid = None
""""tag key name"""
self.key = None
""""the project name where tag belongs to"""
self.project = None
""""the project id the tag belongs to"""
self.projectid = None
""""id of the resource"""
self.resourceid = None
""""resource type"""
self.resourcetype = None
""""tag value"""
self.value = None
""""the list of resource tags associated with the rule"""
self.tags = []
""""the account associated with the tag"""
self.account = None
""""customer associated with the tag"""
self.customer = None
""""the domain associated with the tag"""
self.domain = None
""""the ID of the domain associated with the tag"""
self.domainid = None
""""tag key name"""
self.key = None
""""the project name where tag belongs to"""
self.project = None
""""the project id the tag belongs to"""
self.projectid = None
""""id of the resource"""
self.resourceid = None
""""resource type"""
self.resourcetype = None
""""tag value"""
self.value = None
""""the ID of the latest async job acting on this object"""
self.jobid = None
""""the current status of the latest async job acting on this object"""
self.jobstatus = None
class tags:
def __init__(self):
""""the account associated with the tag"""
self.account = None
""""customer associated with the tag"""
self.customer = None
""""the domain associated with the tag"""
self.domain = None
""""the ID of the domain associated with the tag"""
self.domainid = None
""""tag key name"""
self.key = None
""""the project name where tag belongs to"""
self.project = None
""""the project id the tag belongs to"""
self.projectid = None
""""id of the resource"""
self.resourceid = None
""""resource type"""
self.resourcetype = None
""""tag value"""
self.value = None
| {
"repo_name": "MissionCriticalCloud/marvin",
"path": "marvin/cloudstackAPI/addNicToVirtualMachine.py",
"copies": "1",
"size": "24389",
"license": "apache-2.0",
"hash": -4231563692088282600,
"line_mean": 37.7126984127,
"line_max": 131,
"alpha_frac": 0.5722661856,
"autogenerated": false,
"ratio": 4.403141361256544,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0030414756804252475,
"num_lines": 630
} |
"""Adds xref targets to the top of files."""
import os
import sys
testing = False
DONT_TOUCH = (
'./index.txt',
)
def target_name(fn):
if fn.endswith('.txt'):
fn = fn[:-4]
return '_' + fn.lstrip('./').replace('/', '-')
def process_file(fn, lines):
lines.insert(0, '\n')
lines.insert(0, '.. %s:\n' % target_name(fn))
try:
with open(fn, 'w') as fp:
fp.writelines(lines)
except IOError:
print("Can't open %s for writing. Not touching it." % fn)
def has_target(fn):
try:
with open(fn, 'r') as fp:
lines = fp.readlines()
except IOError:
print("Can't open or read %s. Not touching it." % fn)
return (True, None)
# print fn, len(lines)
if len(lines) < 1:
print("Not touching empty file %s." % fn)
return (True, None)
if lines[0].startswith('.. _'):
return (True, None)
return (False, lines)
def main(argv=None):
if argv is None:
argv = sys.argv
if len(argv) == 1:
argv.extend('.')
files = []
for root in argv[1:]:
for (dirpath, dirnames, filenames) in os.walk(root):
files.extend((dirpath, f) for f in filenames)
files.sort()
files = [os.path.join(p, fn) for p, fn in files if fn.endswith('.txt')]
# print files
for fn in files:
if fn in DONT_TOUCH:
print("Skipping blacklisted file %s." % fn)
continue
target_found, lines = has_target(fn)
if not target_found:
if testing:
print('%s: %s' % (fn, lines[0]))
else:
print("Adding xref to %s" % fn)
process_file(fn, lines)
else:
print("Skipping %s: already has a xref" % fn)
if __name__ == '__main__':
sys.exit(main())
| {
"repo_name": "maxsocl/django",
"path": "docs/_ext/applyxrefs.py",
"copies": "322",
"size": "1834",
"license": "bsd-3-clause",
"hash": -3372931339793458700,
"line_mean": 22.8181818182,
"line_max": 75,
"alpha_frac": 0.5185387132,
"autogenerated": false,
"ratio": 3.4409005628517826,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""Adds xref targets to the top of files."""
import sys
import os
testing = False
DONT_TOUCH = ('./index.txt', )
def target_name(fn):
if fn.endswith('.txt'):
fn = fn[:-4]
return '_' + fn.lstrip('./').replace('/', '-')
def process_file(fn, lines):
lines.insert(0, '\n')
lines.insert(0, '.. %s:\n' % target_name(fn))
try:
f = open(fn, 'w')
except IOError:
print("Can't open %s for writing. Not touching it." % fn)
return
try:
f.writelines(lines)
except IOError:
print("Can't write to %s. Not touching it." % fn)
finally:
f.close()
def has_target(fn):
try:
f = open(fn, 'r')
except IOError:
print("Can't open %s. Not touching it." % fn)
return (True, None)
readok = True
try:
lines = f.readlines()
except IOError:
print("Can't read %s. Not touching it." % fn)
readok = False
finally:
f.close()
if not readok:
return (True, None)
if len(lines) < 1:
print("Not touching empty file %s." % fn)
return (True, None)
if lines[0].startswith('.. _'):
return (True, None)
return (False, lines)
def main(argv=None):
if argv is None:
argv = sys.argv
if len(argv) == 1:
argv.extend('.')
files = []
for root in argv[1:]:
for (dirpath, dirnames, filenames) in os.walk(root):
files.extend([(dirpath, f) for f in filenames])
files.sort()
files = [os.path.join(p, fn) for p, fn in files if fn.endswith('.txt')]
for fn in files:
if fn in DONT_TOUCH:
print("Skipping blacklisted file %s." % fn)
continue
target_found, lines = has_target(fn)
if not target_found:
if testing:
print '%s: %s' % (fn, lines[0]),
else:
print "Adding xref to %s" % fn
process_file(fn, lines)
else:
print "Skipping %s: already has a xref" % fn
if __name__ == '__main__':
sys.exit(main())
| {
"repo_name": "rhcarvalho/kombu",
"path": "docs/_ext/applyxrefs.py",
"copies": "8",
"size": "2093",
"license": "bsd-3-clause",
"hash": -1817110058937280800,
"line_mean": 22.7840909091,
"line_max": 75,
"alpha_frac": 0.513616818,
"autogenerated": false,
"ratio": 3.4883333333333333,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8001950151333334,
"avg_score": null,
"num_lines": null
} |
"""Adds xref targets to the top of files."""
import sys
import os
testing = False
DONT_TOUCH = (
'./index.txt',
)
def target_name(fn):
if fn.endswith('.txt'):
fn = fn[:-4]
return '_' + fn.lstrip('./').replace('/', '-')
def process_file(fn, lines):
lines.insert(0, '\n')
lines.insert(0, '.. %s:\n' % target_name(fn))
try:
f = open(fn, 'w')
except IOError:
print("Can't open %s for writing. Not touching it." % fn)
return
try:
f.writelines(lines)
except IOError:
print("Can't write to %s. Not touching it." % fn)
finally:
f.close()
def has_target(fn):
try:
f = open(fn, 'r')
except IOError:
print("Can't open %s. Not touching it." % fn)
return (True, None)
readok = True
try:
lines = f.readlines()
except IOError:
print("Can't read %s. Not touching it." % fn)
readok = False
finally:
f.close()
if not readok:
return (True, None)
#print fn, len(lines)
if len(lines) < 1:
print("Not touching empty file %s." % fn)
return (True, None)
if lines[0].startswith('.. _'):
return (True, None)
return (False, lines)
def main(argv=None):
if argv is None:
argv = sys.argv
if len(argv) == 1:
argv.extend('.')
files = []
for root in argv[1:]:
for (dirpath, dirnames, filenames) in os.walk(root):
files.extend([(dirpath, f) for f in filenames])
files.sort()
files = [os.path.join(p, fn) for p, fn in files if fn.endswith('.txt')]
#print files
for fn in files:
if fn in DONT_TOUCH:
print("Skipping blacklisted file %s." % fn)
continue
target_found, lines = has_target(fn)
if not target_found:
if testing:
print('%s: %s' % (fn, lines[0]))
else:
print("Adding xref to %s" % fn)
process_file(fn, lines)
else:
print "Skipping %s: already has a xref" % fn
if __name__ == '__main__':
sys.exit(main())
| {
"repo_name": "chrishas35/django-travis-ci",
"path": "docs/_ext/applyxrefs.py",
"copies": "1",
"size": "2150",
"license": "bsd-3-clause",
"hash": 674186199167435500,
"line_mean": 23.4318181818,
"line_max": 75,
"alpha_frac": 0.511627907,
"autogenerated": false,
"ratio": 3.49025974025974,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9484044297329677,
"avg_score": 0.003568669986012785,
"num_lines": 88
} |
"""Adds xref targets to the top of files."""
import sys
import os
testing = False
DONT_TOUCH = (
'./index.txt',
)
def target_name(fn):
if fn.endswith('.txt'):
fn = fn[:-4]
return '_' + fn.lstrip('./').replace('/', '-')
def process_file(fn, lines):
lines.insert(0, '\n')
lines.insert(0, '.. %s:\n' % target_name(fn))
try:
with open(fn, 'w') as fp:
fp.writelines(lines)
except IOError:
print("Can't open %s for writing. Not touching it." % fn)
def has_target(fn):
try:
with open(fn, 'r') as fp:
lines = fp.readlines()
except IOError:
print("Can't open or read %s. Not touching it." % fn)
return (True, None)
#print fn, len(lines)
if len(lines) < 1:
print("Not touching empty file %s." % fn)
return (True, None)
if lines[0].startswith('.. _'):
return (True, None)
return (False, lines)
def main(argv=None):
if argv is None:
argv = sys.argv
if len(argv) == 1:
argv.extend('.')
files = []
for root in argv[1:]:
for (dirpath, dirnames, filenames) in os.walk(root):
files.extend([(dirpath, f) for f in filenames])
files.sort()
files = [os.path.join(p, fn) for p, fn in files if fn.endswith('.txt')]
#print files
for fn in files:
if fn in DONT_TOUCH:
print("Skipping blacklisted file %s." % fn)
continue
target_found, lines = has_target(fn)
if not target_found:
if testing:
print('%s: %s' % (fn, lines[0]))
else:
print("Adding xref to %s" % fn)
process_file(fn, lines)
else:
print("Skipping %s: already has a xref" % fn)
if __name__ == '__main__':
sys.exit(main())
| {
"repo_name": "jarvys/django-1.7-jdb",
"path": "docs/_ext/applyxrefs.py",
"copies": "61",
"size": "1834",
"license": "bsd-3-clause",
"hash": 663276803632450600,
"line_mean": 22.8181818182,
"line_max": 75,
"alpha_frac": 0.5185387132,
"autogenerated": false,
"ratio": 3.4409005628517826,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""Add syntatic sugar for configuration"""
import inspect
import warnings
default_clean = "[Tt]est*"
defaults = dict(
rewrite_asserts=True,
magics=True,
clean=default_clean,
addopts=("-q", "--color=yes"),
run_in_thread=False,
defopts=True,
display_columns=100,
)
current_config = dict(
rewrite_asserts=False,
magics=False,
clean=default_clean,
addopts=(),
run_in_thread=False,
defopts=True,
display_columns=100,
)
_rewrite_transformer = None
class sentinel:
"Adapt repr for better display in completion"
def __init__(self, name):
self.name = name
def __repr__(self):
return f"<{self.name}>"
keep = sentinel("keep")
default = sentinel("default")
def gen_default_docs(func):
defaults_docs = "\n".join(
f" * ``{key!s}``: ``{value!r}``" for key, value in defaults.items()
)
defaults_docs = defaults_docs.strip()
func.__doc__ = func.__doc__.format(defaults_docs=defaults_docs)
return func
@gen_default_docs
def autoconfig(
rewrite_asserts=default,
magics=default,
clean=default,
addopts=default,
run_in_thread=default,
defopts=default,
display_columns=default,
):
"""Configure ``ipytest`` with reasonable defaults.
Specifically, it sets:
{defaults_docs}
See :func:`ipytest.config` for details.
"""
args = collect_args()
config(
**{
key: replace_with_default(default, args[key], defaults.get(key))
for key in current_config
}
)
def config(
rewrite_asserts=keep,
magics=keep,
clean=keep,
addopts=keep,
run_in_thread=keep,
defopts=keep,
display_columns=keep,
):
"""Configure `ipytest`
To update the configuration, call this function as in::
ipytest.config(rewrite_asserts=True)
The following settings are supported:
* ``rewrite_asserts`` (default: ``False``): enable ipython AST transforms
globally to rewrite asserts
* ``magics`` (default: ``False``): if set to ``True`` register the ipytest
magics
* ``clean`` (default: ``[Tt]est*``): the pattern used to clean variables
* ``addopts`` (default: ``()``): pytest command line arguments to prepend
to every pytest invocation. For example setting
``ipytest.config(addopts=['-qq'])`` will execute pytest with the least
verbosity. Consider adding ``--color=yes`` to force color output
* ``run_in_thread`` (default: ``False``): if ``True``, pytest will be run a
separate thread. This way of running is required when testing async
code with ``pytest_asyncio`` since it starts a separate event loop
* ``defopts`` (default: ``True``): if ``True``, ipytest will add the
current module to the arguments passed to pytest. If ``False`` only the
arguments given and ``adopts`` are passed. Such a setup may be helpful
to customize the test selection
* ``display_columns`` (default: ``100``) if not `False`, configure Pytest
to use the given number of columns for its output. This option will
temporarily override the ``COLUMNS`` environment variable.
"""
args = collect_args()
new_config = {
key: replace_with_default(keep, args[key], current_config.get(key))
for key in current_config
}
if new_config["rewrite_asserts"] != current_config["rewrite_asserts"]:
configure_rewrite_asserts(new_config["rewrite_asserts"])
if new_config["magics"] != current_config["magics"]:
configure_magics(new_config["magics"])
current_config.update(new_config)
return dict(current_config)
def configure_rewrite_asserts(enable):
global _rewrite_transformer
from IPython import get_ipython
from ._impl import RewriteAssertTransformer
shell = get_ipython()
if enable:
assert _rewrite_transformer is None
_rewrite_transformer = RewriteAssertTransformer()
_rewrite_transformer.register_with_shell(shell)
else:
assert _rewrite_transformer is not None
_rewrite_transformer.unregister_with_shell(shell)
_rewrite_transformer = None
def configure_magics(enable):
from IPython import get_ipython
from ._impl import run_pytest, run_pytest_clean
if enable:
shell = get_ipython()
shell.register_magic_function(run_pytest, "cell", "run_pytest")
shell.register_magic_function(run_pytest_clean, "cell", "run_pytest[clean]")
else:
warnings.warn("IPython does not support de-registering magics.")
def replace_with_default(sentinel, value, default):
return default if value is sentinel else value
def collect_args():
frame = inspect.currentframe()
frame = frame.f_back
args, _, _, values = inspect.getargvalues(frame)
return {key: values[key] for key in args}
| {
"repo_name": "chmp/ipytest",
"path": "ipytest/_config.py",
"copies": "1",
"size": "4857",
"license": "mit",
"hash": 168747245640297470,
"line_mean": 26.9137931034,
"line_max": 84,
"alpha_frac": 0.6518427013,
"autogenerated": false,
"ratio": 3.8274231678487,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49792658691486996,
"avg_score": null,
"num_lines": null
} |
'''Add syntax highlighting to Python source code'''
__author__ = 'Raymond Hettinger'
import keyword, tokenize, cgi, re, functools
try:
import builtins
except ImportError:
import __builtin__ as builtins
#### Analyze Python Source #################################
def is_builtin(s):
'Return True if s is the name of a builtin'
return hasattr(builtins, s)
def combine_range(lines, start, end):
'Join content from a range of lines between start and end'
(srow, scol), (erow, ecol) = start, end
if srow == erow:
return lines[srow-1][scol:ecol], end
rows = [lines[srow-1][scol:]] + lines[srow: erow-1] + [lines[erow-1][:ecol]]
return ''.join(rows), end
def analyze_python(source):
'''Generate and classify chunks of Python for syntax highlighting.
Yields tuples in the form: (category, categorized_text).
'''
lines = source.splitlines(True)
lines.append('')
readline = functools.partial(next, iter(lines), '')
kind = tok_str = ''
tok_type = tokenize.COMMENT
written = (1, 0)
for tok in tokenize.generate_tokens(readline):
prev_tok_type, prev_tok_str = tok_type, tok_str
tok_type, tok_str, (srow, scol), (erow, ecol), logical_lineno = tok
kind = ''
if tok_type == tokenize.COMMENT:
kind = 'comment'
elif tok_type == tokenize.OP and tok_str[:1] not in '{}[](),.:;@':
kind = 'operator'
elif tok_type == tokenize.STRING:
kind = 'string'
if prev_tok_type == tokenize.INDENT or scol==0:
kind = 'docstring'
elif tok_type == tokenize.NAME:
if tok_str in ('def', 'class', 'import', 'from'):
kind = 'definition'
elif prev_tok_str in ('def', 'class'):
kind = 'defname'
elif keyword.iskeyword(tok_str):
kind = 'keyword'
elif is_builtin(tok_str) and prev_tok_str != '.':
kind = 'builtin'
if kind:
if written != (srow, scol):
text, written = combine_range(lines, written, (srow, scol))
yield '', text
text, written = tok_str, (erow, ecol)
yield kind, text
line_upto_token, written = combine_range(lines, written, (erow, ecol))
yield '', line_upto_token
#### Raw Output ###########################################
def raw_highlight(classified_text):
'Straight text display of text classifications'
result = []
for kind, text in classified_text:
result.append('%15s: %r\n' % (kind or 'plain', text))
return ''.join(result)
#### ANSI Output ###########################################
default_ansi = {
'comment': ('\033[0;31m', '\033[0m'),
'string': ('\033[0;32m', '\033[0m'),
'docstring': ('\033[0;32m', '\033[0m'),
'keyword': ('\033[0;33m', '\033[0m'),
'builtin': ('\033[0;35m', '\033[0m'),
'definition': ('\033[0;33m', '\033[0m'),
'defname': ('\033[0;34m', '\033[0m'),
'operator': ('\033[0;33m', '\033[0m'),
}
def ansi_highlight(classified_text, colors=default_ansi):
'Add syntax highlighting to source code using ANSI escape sequences'
# http://en.wikipedia.org/wiki/ANSI_escape_code
result = []
for kind, text in classified_text:
opener, closer = colors.get(kind, ('', ''))
result += [opener, text, closer]
return ''.join(result)
#### HTML Output ###########################################
def html_highlight(classified_text,opener='<pre class="python">\n', closer='</pre>\n'):
'Convert classified text to an HTML fragment'
result = [opener]
for kind, text in classified_text:
if kind:
result.append('<span class="%s">' % kind)
result.append(cgi.escape(text))
if kind:
result.append('</span>')
result.append(closer)
return ''.join(result)
default_css = {
'.comment': '{color: crimson;}',
'.string': '{color: forestgreen;}',
'.docstring': '{color: forestgreen; font-style:italic;}',
'.keyword': '{color: darkorange;}',
'.builtin': '{color: purple;}',
'.definition': '{color: darkorange; font-weight:bold;}',
'.defname': '{color: blue;}',
'.operator': '{color: brown;}',
}
default_html = '''\
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title> {title} </title>
<style type="text/css">
{css}
</style>
</head>
<body>
{body}
</body>
</html>
'''
def build_html_page(classified_text, title='python',
css=default_css, html=default_html):
'Create a complete HTML page with colorized source code'
css_str = '\n'.join(['%s %s' % item for item in css.items()])
result = html_highlight(classified_text)
title = cgi.escape(title)
return html.format(title=title, css=css_str, body=result)
#### LaTeX Output ##########################################
default_latex_commands = {
'comment': '{\color{red}#1}',
'string': '{\color{ForestGreen}#1}',
'docstring': '{\emph{\color{ForestGreen}#1}}',
'keyword': '{\color{orange}#1}',
'builtin': '{\color{purple}#1}',
'definition': '{\color{orange}#1}',
'defname': '{\color{blue}#1}',
'operator': '{\color{brown}#1}',
}
default_latex_document = r'''
\documentclass{article}
\usepackage{alltt}
\usepackage{upquote}
\usepackage{color}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage[cm]{fullpage}
%(macros)s
\begin{document}
\center{\LARGE{%(title)s}}
\begin{alltt}
%(body)s
\end{alltt}
\end{document}
'''
def alltt_escape(s):
'Replace backslash and braces with their escaped equivalents'
xlat = {'{': r'\{', '}': r'\}', '\\': r'\textbackslash{}'}
return re.sub(r'[\\{}]', lambda mo: xlat[mo.group()], s)
def latex_highlight(classified_text, title = 'python',
commands = default_latex_commands,
document = default_latex_document):
'Create a complete LaTeX document with colorized source code'
macros = '\n'.join(r'\newcommand{\py%s}[1]{%s}' % c for c in commands.items())
result = []
for kind, text in classified_text:
if kind:
result.append(r'\py%s{' % kind)
result.append(alltt_escape(text))
if kind:
result.append('}')
return default_latex_document % dict(title=title, macros=macros, body=''.join(result))
if __name__ == '__main__':
import sys, argparse, webbrowser, os, textwrap
parser = argparse.ArgumentParser(
description = 'Add syntax highlighting to Python source code',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog = textwrap.dedent('''
examples:
# Show syntax highlighted code in the terminal window
$ ./highlight.py myfile.py
# Colorize myfile.py and display in a browser
$ ./highlight.py -b myfile.py
# Create an HTML section to embed in an existing webpage
./highlight.py -s myfile.py
# Create a complete HTML file
$ ./highlight.py -c myfile.py > myfile.html
# Create a PDF using LaTeX
$ ./highlight.py -l myfile.py | pdflatex
'''))
parser.add_argument('sourcefile', metavar = 'SOURCEFILE',
help = 'file containing Python sourcecode')
parser.add_argument('-b', '--browser', action = 'store_true',
help = 'launch a browser to show results')
parser.add_argument('-c', '--complete', action = 'store_true',
help = 'build a complete html webpage')
parser.add_argument('-l', '--latex', action = 'store_true',
help = 'build a LaTeX document')
parser.add_argument('-r', '--raw', action = 'store_true',
help = 'raw parse of categorized text')
parser.add_argument('-s', '--section', action = 'store_true',
help = 'show an HTML section rather than a complete webpage')
args = parser.parse_args()
if args.section and (args.browser or args.complete):
parser.error('The -s/--section option is incompatible with '
'the -b/--browser or -c/--complete options')
sourcefile = args.sourcefile
with open(sourcefile) as f:
source = f.read()
classified_text = analyze_python(source)
if args.raw:
encoded = raw_highlight(classified_text)
elif args.complete or args.browser:
encoded = build_html_page(classified_text, title=sourcefile)
elif args.section:
encoded = html_highlight(classified_text)
elif args.latex:
encoded = latex_highlight(classified_text, title=sourcefile)
else:
encoded = ansi_highlight(classified_text)
if args.browser:
htmlfile = os.path.splitext(os.path.basename(sourcefile))[0] + '.html'
with open(htmlfile, 'w') as f:
f.write(encoded)
webbrowser.open('file://' + os.path.abspath(htmlfile))
else:
sys.stdout.write(encoded)
| {
"repo_name": "ActiveState/code",
"path": "recipes/Python/578178_Colorize_Pyth_Sourcecode_Syntax/recipe-578178.py",
"copies": "2",
"size": "9142",
"license": "mit",
"hash": 7039888874018337000,
"line_mean": 34.1615384615,
"line_max": 90,
"alpha_frac": 0.5752570553,
"autogenerated": false,
"ratio": 3.604889589905363,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.005927455631037706,
"num_lines": 260
} |
"""Add system roles
Revision ID: 1afc3824d35b
Revises: 5325f2b93af8
Create Date: 2013-09-20 14:12:32.846302
"""
# revision identifiers, used by Alembic.
revision = '1afc3824d35b'
down_revision = '5325f2b93af8'
import json
import sqlalchemy as sa
from alembic import op
from datetime import datetime
from sqlalchemy.sql import table, column
roles_table = table('roles',
column('id', sa.Integer),
column('name', sa.String),
column('permissions_json', sa.Text),
column('description', sa.Text),
column('modified_by_id', sa.Integer),
column('created_at', sa.DateTime),
column('updated_at', sa.DateTime),
column('context_id', sa.Integer),
)
def upgrade():
basic_objects_editable = [
'Categorization',
'Category',
'Control',
'ControlControl',
'ControlSection',
'Cycle',
'DataAsset',
'Directive',
'Contract',
'Policy',
'Regulation',
'DirectiveControl',
'Document',
'Facility',
'Help',
'Market',
'Objective',
'ObjectControl'
'ObjectDocument',
'ObjectObjective',
'ObjectPerson',
'ObjectSection',
'Option',
'OrgGroup',
'PopulationSample',
'Product',
'Project',
'Relationship',
'RelationshipType',
'Section',
'SystemOrProcess',
'System',
'Process',
'SystemControl',
'SystemSysetm',
]
basic_objects_readable = list(basic_objects_editable)
basic_objects_readable.extend([
'Person',
'Program',
'ProgramControl',
'ProgramDirective',
'Role',
#'UserRole', ?? why?
'Person',
])
current_datetime = datetime.now()
op.bulk_insert(roles_table,
[
{ 'name': 'Reader',
'description': 'This role grants a user basic, read-only, access '\
'permission to a gGRC instance.',
'permissions_json': json.dumps({
'read': basic_objects_readable,
}),
'created_at': current_datetime,
'updated_at': current_datetime,
},
{ 'name': 'ObjectEditor',
'description': 'This role grants a user basic object creation and '\
'editing permission.',
'permissions_json': json.dumps({
'create': basic_objects_editable,
'read': basic_objects_readable,
'update': basic_objects_editable,
'delete': basic_objects_editable,
}),
'created_at': current_datetime,
'updated_at': current_datetime,
},
{ 'name': 'ProgramCreator',
'description': 'This role grants a user the permission to create '\
'public and private programs.',
'permissions_json': json.dumps({
'create': ['Program',],
}),
'created_at': current_datetime,
'updated_at': current_datetime,
},
])
def downgrade():
op.execute('SET FOREIGN_KEY_CHECKS = 0')
op.execute(roles_table.delete().where(
roles_table.c.name.in_(
[ op.inline_literal('Reader'),
op.inline_literal('ObjectEditor'),
op.inline_literal('ProgramCreator'),
])))
| {
"repo_name": "uskudnik/ggrc-core",
"path": "src/ggrc_basic_permissions/migrations/versions/20130920141232_1afc3824d35b_add_system_roles.py",
"copies": "1",
"size": "3222",
"license": "apache-2.0",
"hash": 8160979454588044000,
"line_mean": 25.4098360656,
"line_max": 78,
"alpha_frac": 0.5661080074,
"autogenerated": false,
"ratio": 3.9388753056234718,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5004983313023471,
"avg_score": null,
"num_lines": null
} |
"""Add table and seed user/role (admin) for flask_security
Revision ID: 2a3fee7de8d4
Revises: 29b31f4d8de6
Create Date: 2015-06-27 01:53:52.021040
"""
# revision identifiers, used by Alembic.
revision = '2a3fee7de8d4'
down_revision = '29b31f4d8de6'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
import flask_security.utils as security_utils
role_table = op.create_table('role',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('name', sa.String(length=80), nullable=True),
sa.Column('description', sa.String(length=255), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
op.bulk_insert(role_table, [
{'id': 1, 'name': 'admin', 'description': 'admin role'},
], multiinsert=False)
from sqlalchemy.sql import text
op.get_bind().execute(text("ALTER SEQUENCE role_id_seq RESTART WITH 2;"))
user_table = op.create_table('user',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('login', sa.String(length=64), nullable=False, unique=True),
sa.Column('display', sa.String(length=255), nullable=False),
sa.Column('email', sa.String(length=255), nullable=True),
sa.Column('password', sa.String(length=255), nullable=True),
sa.Column('active', sa.Boolean(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('email')
)
hashed_password = security_utils.hash_password('password')
op.bulk_insert(user_table, [
{'id': 1, 'login': 'admin', 'display': 'Administrator',
'email': 'support@betterlife.io',
'password': hashed_password,
'active': True},
], multiinsert=False)
op.get_bind().execute(text("ALTER SEQUENCE user_id_seq RESTART WITH 2;"))
roles_users_table = op.create_table('roles_users',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('role_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['role_id'], ['role.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id'),
)
op.bulk_insert(roles_users_table, [
{'id': 1, 'user_id': 1, 'role_id': 1},
], multiinsert=False)
op.get_bind().execute(text("ALTER SEQUENCE roles_users_id_seq RESTART WITH 2;"))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('roles_users')
op.drop_table('user')
op.drop_table('role')
### end Alembic commands ###
| {
"repo_name": "betterlife/psi",
"path": "psi/migrations/versions/04_2a3fee7de8d4_.py",
"copies": "2",
"size": "3371",
"license": "mit",
"hash": 3424575459911065600,
"line_mean": 46.4788732394,
"line_max": 106,
"alpha_frac": 0.5215069712,
"autogenerated": false,
"ratio": 4.250945775535939,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.004747454989663842,
"num_lines": 71
} |
"""Add tabled_committee_report constraint
Revision ID: 8cbc3d8dd55
Revises: 17570e7e200b
Create Date: 2016-08-31 10:19:49.128041
"""
# revision identifiers, used by Alembic.
revision = '8cbc3d8dd55'
down_revision = '17570e7e200b'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.alter_column('tabled_committee_report', 'committee_id',
existing_type=sa.INTEGER(),
nullable=False)
op.create_index(op.f('ix_tabled_committee_report_committee_id'), 'tabled_committee_report', ['committee_id'], unique=False)
op.drop_constraint(u'tabled_committee_report_committee_id_fkey', 'tabled_committee_report', type_='foreignkey')
op.create_foreign_key(op.f('fk_tabled_committee_report_committee_id_committee'), 'tabled_committee_report', 'committee', ['committee_id'], ['id'])
op.drop_column('tabled_committee_report', 'summary')
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('tabled_committee_report', sa.Column('summary', sa.TEXT(), autoincrement=False, nullable=True))
op.drop_constraint(op.f('fk_tabled_committee_report_committee_id_committee'), 'tabled_committee_report', type_='foreignkey')
op.create_foreign_key(u'tabled_committee_report_committee_id_fkey', 'tabled_committee_report', 'committee', ['committee_id'], ['id'], ondelete=u'SET NULL')
op.drop_index(op.f('ix_tabled_committee_report_committee_id'), table_name='tabled_committee_report')
op.alter_column('tabled_committee_report', 'committee_id',
existing_type=sa.INTEGER(),
nullable=True)
### end Alembic commands ###
| {
"repo_name": "Code4SA/pmg-cms-2",
"path": "migrations/versions/8cbc3d8dd55_add_tabled_committee_report_constraint.py",
"copies": "1",
"size": "1744",
"license": "apache-2.0",
"hash": -8655997645879672000,
"line_mean": 44.8947368421,
"line_max": 159,
"alpha_frac": 0.6978211009,
"autogenerated": false,
"ratio": 3.2,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9352497759131175,
"avg_score": 0.009064668353764802,
"num_lines": 38
} |
"""Add table for comments
Revision ID: 0366ba6575ca
Revises: 1093835a1051
Create Date: 2020-08-14 00:46:54.161120
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "0366ba6575ca"
down_revision = "1093835a1051"
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"comments",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("type", sa.String(length=80), nullable=True),
sa.Column("content", sa.Text(), nullable=True),
sa.Column("date", sa.DateTime(), nullable=True),
sa.Column("author_id", sa.Integer(), nullable=True),
sa.Column("challenge_id", sa.Integer(), nullable=True),
sa.Column("user_id", sa.Integer(), nullable=True),
sa.Column("team_id", sa.Integer(), nullable=True),
sa.Column("page_id", sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(["author_id"], ["users.id"], ondelete="CASCADE"),
sa.ForeignKeyConstraint(
["challenge_id"], ["challenges.id"], ondelete="CASCADE"
),
sa.ForeignKeyConstraint(["page_id"], ["pages.id"], ondelete="CASCADE"),
sa.ForeignKeyConstraint(["team_id"], ["teams.id"], ondelete="CASCADE"),
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
sa.PrimaryKeyConstraint("id"),
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table("comments")
# ### end Alembic commands ###
| {
"repo_name": "isislab/CTFd",
"path": "migrations/versions/0366ba6575ca_add_table_for_comments.py",
"copies": "4",
"size": "1628",
"license": "apache-2.0",
"hash": -5681373047420389000,
"line_mean": 33.6382978723,
"line_max": 81,
"alpha_frac": 0.6283783784,
"autogenerated": false,
"ratio": 3.7,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0002594706798131811,
"num_lines": 47
} |
"""Add table for event labels
Revision ID: 266d78b1c5db
Revises: 18a1088f1ea8
Create Date: 2020-03-24 09:26:07.095052
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '266d78b1c5db'
down_revision = '18a1088f1ea8'
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'labels',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=False),
sa.Column('color', sa.String(), nullable=False),
sa.PrimaryKeyConstraint('id'),
schema='events'
)
op.create_index('ix_uq_labels_title_lower', 'labels', [sa.text('lower(title)')], unique=True, schema='events')
op.add_column('events', sa.Column('label_id', sa.Integer(), nullable=True), schema='events')
op.add_column('events', sa.Column('label_message', sa.Text(), nullable=False, server_default=''), schema='events')
op.alter_column('events', 'label_message', server_default=None, schema='events')
op.create_foreign_key(None, 'events', 'labels', ['label_id'], ['id'], source_schema='events',
referent_schema='events')
op.create_index(None, 'events', ['label_id'], unique=False, schema='events')
def downgrade():
op.drop_column('events', 'label_id', schema='events')
op.drop_column('events', 'label_message', schema='events')
op.drop_table('labels', schema='events')
| {
"repo_name": "pferreir/indico",
"path": "indico/migrations/versions/20200324_0926_266d78b1c5db_add_table_for_event_labels.py",
"copies": "5",
"size": "1436",
"license": "mit",
"hash": 8715120325631586000,
"line_mean": 34.9,
"line_max": 118,
"alpha_frac": 0.6538997214,
"autogenerated": false,
"ratio": 3.278538812785388,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6432438534185387,
"avg_score": null,
"num_lines": null
} |
"""add table for mt940 parsing errors
Revision ID: 8ff6f90b98fa
Revises: 08fa5b3cc555
Create Date: 2018-12-20 18:34:05.289624
"""
from alembic import op
import sqlalchemy as sa
import pycroft
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '8ff6f90b98fa'
down_revision = '08fa5b3cc555'
branch_labels = None
depends_on = None
def upgrade():
op.create_table('mt940_error',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('mt940', sa.Text(), nullable=False),
sa.Column('exception', sa.Text(), nullable=False),
sa.Column('author_id', sa.Integer(), nullable=False),
sa.Column('imported_at', pycroft.model.types.DateTimeTz(), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False),
sa.Column('bank_account_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['author_id'], ['user.id'], ),
sa.ForeignKeyConstraint(['bank_account_id'], ['bank_account.id'], ),
sa.PrimaryKeyConstraint('id')
)
def downgrade():
op.drop_table('mt940_error')
| {
"repo_name": "agdsn/pycroft",
"path": "pycroft/model/alembic/versions/8ff6f90b98fa_add_table_for_mt940_parsing_errors.py",
"copies": "2",
"size": "1055",
"license": "apache-2.0",
"hash": -3585272733337338400,
"line_mean": 29.1428571429,
"line_max": 124,
"alpha_frac": 0.7042654028,
"autogenerated": false,
"ratio": 3.177710843373494,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48819762461734945,
"avg_score": null,
"num_lines": null
} |
"""Add table for `Report` model.
Revision ID: 3b9f2f6e0d3c
Revises: 3e2e5299576f
Create Date: 2014-06-28 00:21:44.910113
"""
# revision identifiers, used by Alembic.
revision = '3b9f2f6e0d3c'
down_revision = '3e2e5299576f'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('reports',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('url', sa.String(), nullable=True),
sa.Column('har', postgresql.JSON(), nullable=True),
sa.Column('ref', sa.String(), nullable=True),
sa.Column('created', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_reports_ref'), 'reports', ['ref'], unique=False)
op.create_index(op.f('ix_reports_url'), 'reports', ['url'], unique=False)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_reports_url'), table_name='reports')
op.drop_index(op.f('ix_reports_ref'), table_name='reports')
op.drop_table('reports')
### end Alembic commands ###
| {
"repo_name": "cvan/arewefast",
"path": "arewefast/migrations/versions/3b9f2f6e0d3c_.py",
"copies": "1",
"size": "1193",
"license": "mit",
"hash": 4636362695809936000,
"line_mean": 31.2432432432,
"line_max": 77,
"alpha_frac": 0.6705783738,
"autogenerated": false,
"ratio": 3.1644562334217508,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.43350346072217505,
"avg_score": null,
"num_lines": null
} |
"""Add table for review conditions
Revision ID: 02bf20df06b3
Revises: 3c5462aef0b7
Create Date: 2020-04-01 17:38:54.405431
"""
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum
from indico.modules.events.editing.models.editable import EditableType
# revision identifiers, used by Alembic.
revision = '02bf20df06b3'
down_revision = '3c5462aef0b7'
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'review_conditions',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('type', PyIntEnum(EditableType), nullable=False),
sa.Column('event_id', sa.Integer(), nullable=False, index=True),
sa.ForeignKeyConstraint(['event_id'], ['events.events.id']),
sa.PrimaryKeyConstraint('id'),
schema='event_editing',
)
op.create_table(
'review_condition_file_types',
sa.Column('review_condition_id', sa.Integer(), autoincrement=False, nullable=False, index=True),
sa.Column('file_type_id', sa.Integer(), autoincrement=False, nullable=False, index=True),
sa.ForeignKeyConstraint(
['file_type_id'],
['event_editing.file_types.id'],
),
sa.ForeignKeyConstraint(
['review_condition_id'],
['event_editing.review_conditions.id'],
),
sa.PrimaryKeyConstraint('review_condition_id', 'file_type_id'),
schema='event_editing',
)
def downgrade():
op.drop_table('review_condition_file_types', schema='event_editing')
op.drop_table('review_conditions', schema='event_editing')
| {
"repo_name": "ThiefMaster/indico",
"path": "indico/migrations/versions/20200401_1738_02bf20df06b3_add_table_for_review_conditions.py",
"copies": "5",
"size": "1624",
"license": "mit",
"hash": -6788358782587876000,
"line_mean": 30.8431372549,
"line_max": 104,
"alpha_frac": 0.6600985222,
"autogenerated": false,
"ratio": 3.5692307692307694,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6729329291430769,
"avg_score": null,
"num_lines": null
} |
"""add table mailtemplates
Revision ID: 34f15d11d02
Revises: 2fadbf7a01a
Create Date: 2015-08-04 17:28:24.372803
"""
# revision identifiers, used by Alembic.
revision = '34f15d11d02'
down_revision = '2fadbf7a01a'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('mailtemplates',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=False),
sa.Column('subject', sa.String(length=79), nullable=False),
sa.Column('html', sa.Text(), nullable=False),
sa.Column('help_msg', sa.Text(), nullable=True),
sa.Column('updated_at', sa.Date(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('mailtemplates')
### end Alembic commands ###
| {
"repo_name": "uaprom-summer-2015/Meowth",
"path": "migrations/versions/2015_08_04_34f1_add_table_mailtemplates.py",
"copies": "2",
"size": "1045",
"license": "bsd-3-clause",
"hash": 3312569149242929700,
"line_mean": 28.0277777778,
"line_max": 63,
"alpha_frac": 0.6679425837,
"autogenerated": false,
"ratio": 3.3493589743589745,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5017301558058974,
"avg_score": null,
"num_lines": null
} |
"""Add tables for DB-based muting
Revision ID: 313ce21eb461
Revises: 0002ca860468
Create Date: 2018-12-10 14:53:50.525225
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '313ce21eb461'
down_revision = '0002ca860468'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('mute_guilds',
sa.Column('guild_id', sa.BigInteger(), autoincrement=False, nullable=False),
sa.Column('role_id', sa.BigInteger(), nullable=False),
sa.PrimaryKeyConstraint('guild_id', name=op.f('pk_mute_guilds'))
)
op.create_table('mute_users',
sa.Column('user_id', sa.BigInteger(), autoincrement=False, nullable=False),
sa.Column('guild_id', sa.BigInteger(), autoincrement=False, nullable=False),
sa.Column('muted_until', sa.DateTime(), nullable=True),
sa.Column('channel_id', sa.BigInteger(), nullable=True),
sa.ForeignKeyConstraint(['guild_id'], ['mute_guilds.guild_id'], name=op.f('fk_mute_users_guild_id_mute_guilds')),
sa.PrimaryKeyConstraint('user_id', 'guild_id', name=op.f('pk_mute_users'))
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('mute_users')
op.drop_table('mute_guilds')
# ### end Alembic commands ###
| {
"repo_name": "FallenWarrior2k/cardinal.py",
"path": "src/cardinal/db/migrations/versions/313ce21eb461_add_tables_for_db_based_muting.py",
"copies": "1",
"size": "1386",
"license": "mit",
"hash": 2105802998077855000,
"line_mean": 32.8048780488,
"line_max": 117,
"alpha_frac": 0.6803751804,
"autogenerated": false,
"ratio": 3.268867924528302,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4449243104928302,
"avg_score": null,
"num_lines": null
} |
"""Add tables for editing revisions
Revision ID: 4e459d27adab
Revises: 39a25a873063
Create Date: 2019-11-08 17:13:48.096553
"""
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum, UTCDateTime
from indico.modules.events.editing.models.editable import EditableType
from indico.modules.events.editing.models.revisions import FinalRevisionState, InitialRevisionState
# revision identifiers, used by Alembic.
revision = '4e459d27adab'
down_revision = '39a25a873063'
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'editables',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('contribution_id', sa.Integer(), nullable=False, index=True),
sa.Column('type', PyIntEnum(EditableType), nullable=False),
sa.Column('editor_id', sa.Integer(), nullable=True, index=True),
sa.Column('published_revision_id', sa.Integer(), nullable=True, index=True),
sa.ForeignKeyConstraint(['contribution_id'], ['events.contributions.id']),
sa.ForeignKeyConstraint(['editor_id'], ['users.users.id']),
sa.UniqueConstraint('contribution_id', 'type'),
sa.PrimaryKeyConstraint('id'),
schema='event_editing'
)
op.create_table(
'revisions',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('editable_id', sa.Integer(), nullable=False, index=True),
sa.Column('submitter_id', sa.Integer(), nullable=False, index=True),
sa.Column('editor_id', sa.Integer(), nullable=True, index=True),
sa.Column('created_dt', UTCDateTime, nullable=False),
sa.Column('initial_state', PyIntEnum(InitialRevisionState), nullable=False),
sa.Column('final_state', PyIntEnum(FinalRevisionState), nullable=False),
sa.Column('comment', sa.Text(), nullable=False),
sa.ForeignKeyConstraint(['editable_id'], ['event_editing.editables.id']),
sa.ForeignKeyConstraint(['editor_id'], ['users.users.id']),
sa.ForeignKeyConstraint(['submitter_id'], ['users.users.id']),
sa.CheckConstraint('(initial_state=1 AND final_state IN (0,1)) OR (initial_state=2) OR '
'(initial_state=3 AND (final_state IN (0,3,4)))', name='valid_state_combination'),
sa.PrimaryKeyConstraint('id'),
schema='event_editing'
)
op.create_foreign_key(None, 'editables', 'revisions', ['published_revision_id'], ['id'],
source_schema='event_editing', referent_schema='event_editing')
op.create_table(
'revision_files',
sa.Column('revision_id', sa.Integer(), nullable=False, index=True),
sa.Column('file_id', sa.Integer(), nullable=False, index=True),
sa.Column('file_type_id', sa.Integer(), nullable=True, index=True),
sa.ForeignKeyConstraint(['file_id'], ['indico.files.id']),
sa.ForeignKeyConstraint(['file_type_id'], ['event_editing.file_types.id']),
sa.ForeignKeyConstraint(['revision_id'], ['event_editing.revisions.id']),
sa.PrimaryKeyConstraint('revision_id', 'file_id'),
schema='event_editing'
)
op.create_table(
'tags',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('event_id', sa.Integer(), nullable=False, index=True),
sa.Column('title', sa.String(), nullable=False),
sa.Column('code', sa.String(), nullable=False),
sa.Column('color', sa.String(), nullable=False),
sa.Column('system', sa.Boolean(), nullable=False),
sa.ForeignKeyConstraint(['event_id'], ['events.events.id']),
sa.PrimaryKeyConstraint('id'),
schema='event_editing'
)
op.create_index('ix_uq_tags_event_id_code_lower', 'tags', ['event_id', sa.text('lower(code)')],
unique=True, schema='event_editing')
op.create_table(
'revision_tags',
sa.Column('revision_id', sa.Integer(), autoincrement=False, nullable=False, index=True),
sa.Column('tag_id', sa.Integer(), autoincrement=False, nullable=False, index=True),
sa.ForeignKeyConstraint(['revision_id'], ['event_editing.revisions.id']),
sa.ForeignKeyConstraint(['tag_id'], ['event_editing.tags.id']),
sa.PrimaryKeyConstraint('revision_id', 'tag_id'),
schema='event_editing'
)
op.create_table(
'comments',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('revision_id', sa.Integer(), nullable=False, index=True),
sa.Column('user_id', sa.Integer(), nullable=True, index=True),
sa.Column('created_dt', UTCDateTime, nullable=False),
sa.Column('modified_dt', UTCDateTime, nullable=True),
sa.Column('is_deleted', sa.Boolean(), nullable=False),
sa.Column('internal', sa.Boolean(), nullable=False),
sa.Column('system', sa.Boolean(), nullable=False),
sa.Column('text', sa.Text(), nullable=False),
sa.CheckConstraint('(user_id IS NULL) = system', name='system_comment_no_user'),
sa.ForeignKeyConstraint(['revision_id'], ['event_editing.revisions.id']),
sa.ForeignKeyConstraint(['user_id'], ['users.users.id']),
sa.PrimaryKeyConstraint('id'),
schema='event_editing'
)
def downgrade():
op.drop_table('comments', schema='event_editing')
op.drop_table('revision_tags', schema='event_editing')
op.drop_table('tags', schema='event_editing')
op.drop_table('revision_files', schema='event_editing')
op.drop_constraint('fk_editables_published_revision_id_revisions', 'editables', schema='event_editing')
op.drop_table('revisions', schema='event_editing')
op.drop_table('editables', schema='event_editing')
| {
"repo_name": "ThiefMaster/indico",
"path": "indico/migrations/versions/20191108_1713_4e459d27adab_add_tables_for_editing_revisions.py",
"copies": "5",
"size": "5709",
"license": "mit",
"hash": -2467987270037762600,
"line_mean": 45.7950819672,
"line_max": 109,
"alpha_frac": 0.6445962515,
"autogenerated": false,
"ratio": 3.695145631067961,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6839741882567961,
"avg_score": null,
"num_lines": null
} |
"""Add tables for tournaments feature
Revision ID: d172bd5e57c1
Revises: 6ef8ada19388
Create Date: 2018-12-31 11:54:48.926336
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'd172bd5e57c1'
down_revision = '6ef8ada19388'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('tournament_bots',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('elo', sa.Float(), nullable=True),
sa.Column('wins', sa.Integer(), nullable=True),
sa.Column('losses', sa.Integer(), nullable=True),
sa.Column('bot_id', sa.Integer(), nullable=False),
sa.Column('tournament_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['bot_id'], ['bots.id'], ),
sa.ForeignKeyConstraint(['tournament_id'], ['tournaments.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('tournament_games',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('tournament_id', sa.Integer(), nullable=False),
sa.Column('bot_a_id', sa.Integer(), nullable=False),
sa.Column('bot_a_elo', sa.Float(), nullable=True),
sa.Column('bot_b_id', sa.Integer(), nullable=False),
sa.Column('bot_b_elo', sa.Float(), nullable=True),
sa.Column('winner_id', sa.Integer(), nullable=True),
sa.Column('loser_id', sa.Integer(), nullable=True),
sa.Column('status', sa.Enum('completed', 'created', 'in_progress', 'internal_error', name='gamestatus'), nullable=False),
sa.Column('create_time', sa.DateTime(), nullable=True),
sa.Column('completed_time', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['bot_a_id'], ['tournament_bots.id'], ),
sa.ForeignKeyConstraint(['bot_b_id'], ['tournament_bots.id'], ),
sa.ForeignKeyConstraint(['loser_id'], ['tournament_bots.id'], ),
sa.ForeignKeyConstraint(['tournament_id'], ['tournaments.id'], ),
sa.ForeignKeyConstraint(['winner_id'], ['tournament_bots.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('tournaments',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(length=256), nullable=True),
sa.Column('create_time', sa.DateTime(), nullable=True),
sa.Column('games_per_pair', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('tournaments')
op.drop_table('tournament_games')
op.drop_table('tournament_bots')
# ### end Alembic commands ###
| {
"repo_name": "mitpokerbots/scrimmage",
"path": "migrations/versions/d172bd5e57c1_.py",
"copies": "1",
"size": "2628",
"license": "mit",
"hash": 1789128056203565300,
"line_mean": 38.8181818182,
"line_max": 125,
"alpha_frac": 0.6601978691,
"autogenerated": false,
"ratio": 3.3435114503816794,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9460979130724902,
"avg_score": 0.008546037751355234,
"num_lines": 66
} |
"""Add TagAlias table
Revision ID: 9a0f78ff57d6
Revises: d19881f4c045
Create Date: 2017-03-19 15:34:30.271997
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '9a0f78ff57d6'
down_revision = 'd19881f4c045'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('tag_alias',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('alias_name', sa.String(), nullable=False),
sa.Column('tag_id', sa.Integer(), nullable=True),
sa.Column('guild_id', sa.BigInteger(), nullable=True),
sa.Column('user_id', sa.BigInteger(), nullable=True),
sa.ForeignKeyConstraint(['guild_id'], ['guild.id'], ),
sa.ForeignKeyConstraint(['tag_id'], ['tag.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('tag_alias')
# ### end Alembic commands ###
| {
"repo_name": "MJB47/Jokusoramame",
"path": "migrations/versions/9a0f78ff57d6_add_tagalias_table.py",
"copies": "1",
"size": "1126",
"license": "mit",
"hash": -1439656927559262200,
"line_mean": 27.8717948718,
"line_max": 65,
"alpha_frac": 0.6571936057,
"autogenerated": false,
"ratio": 3.2923976608187133,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9423419745352443,
"avg_score": 0.005234304233254147,
"num_lines": 39
} |
"""add tags
Revision ID: 42f99b73b077
Revises: e59c406395d2
Create Date: 2017-02-02 16:08:12.273221
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '42f99b73b077'
down_revision = 'e59c406395d2'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('tags',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.Unicode(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
op.create_table('tag_assignments',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('tag_id', sa.Integer(), nullable=False),
sa.Column('collection_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['collection_id'], ['collections.id'], ondelete='CASCADE'),
sa.ForeignKeyConstraint(['tag_id'], ['tags.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('tag_id', 'collection_id', name='uq_tag_assignments_name_collection_id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('tag_assignments')
op.drop_table('tags')
# ### end Alembic commands ###
| {
"repo_name": "rjw57/bitsbox",
"path": "migrations/versions/42f99b73b077_add_tags.py",
"copies": "1",
"size": "1305",
"license": "mit",
"hash": 6466967251034658000,
"line_mean": 29.3488372093,
"line_max": 96,
"alpha_frac": 0.6697318008,
"autogenerated": false,
"ratio": 3.4523809523809526,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9594479420468468,
"avg_score": 0.005526666542496946,
"num_lines": 43
} |
"""Add tag table.
Revision ID: c877a04b8181
Revises: 62b3c37ee7e3
Create Date: 2017-02-05 10:52:10.408159
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c877a04b8181'
down_revision = '62b3c37ee7e3'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('tag',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('guild_id', sa.BigInteger(), nullable=True),
sa.Column('user_id', sa.BigInteger(), nullable=True),
sa.Column('name', sa.String(), nullable=False),
sa.Column('global_', sa.Boolean(), nullable=False),
sa.Column('content', sa.String(), nullable=False),
sa.Column('last_modified', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['guild_id'], ['guild.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('id')
)
op.create_index(op.f('ix_tag_name'), 'tag', ['name'], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_tag_name'), table_name='tag')
op.drop_table('tag')
# ### end Alembic commands ###
| {
"repo_name": "MJB47/Jokusoramame",
"path": "migrations/versions/c877a04b8181_add_tag_table.py",
"copies": "1",
"size": "1297",
"license": "mit",
"hash": 8854994785933981000,
"line_mean": 29.880952381,
"line_max": 71,
"alpha_frac": 0.6522744796,
"autogenerated": false,
"ratio": 3.2344139650872816,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9360308098066564,
"avg_score": 0.005276069324143452,
"num_lines": 42
} |
"""Add taken_from_default field
Revision ID: 2f1bb61ffea
Revises: e220a74734b
Create Date: 2015-04-10 17:45:16.727882
"""
# revision identifiers, used by Alembic.
revision = '2f1bb61ffea'
down_revision = 'e220a74734b'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('ActiveTranslationMessages', sa.Column('taken_from_default', sa.Boolean(), nullable=True))
op.create_index(u'ix_ActiveTranslationMessages_taken_from_default', 'ActiveTranslationMessages', ['taken_from_default'], unique=False)
op.add_column('TranslationMessageHistory', sa.Column('taken_from_default', sa.Boolean(), nullable=True))
op.create_index(u'ix_TranslationMessageHistory_parent_translation_id', 'TranslationMessageHistory', ['parent_translation_id'], unique=False)
op.create_index(u'ix_TranslationMessageHistory_taken_from_default', 'TranslationMessageHistory', ['taken_from_default'], unique=False)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_index(u'ix_TranslationMessageHistory_taken_from_default', table_name='TranslationMessageHistory')
op.drop_index(u'ix_TranslationMessageHistory_parent_translation_id', table_name='TranslationMessageHistory')
op.drop_column('TranslationMessageHistory', 'taken_from_default')
op.drop_index(u'ix_ActiveTranslationMessages_taken_from_default', table_name='ActiveTranslationMessages')
op.drop_column('ActiveTranslationMessages', 'taken_from_default')
### end Alembic commands ###
| {
"repo_name": "porduna/appcomposer",
"path": "alembic/versions/2f1bb61ffea_add_taken_from_default_field.py",
"copies": "3",
"size": "1613",
"license": "bsd-2-clause",
"hash": 8463240115839776000,
"line_mean": 46.4411764706,
"line_max": 144,
"alpha_frac": 0.7557346559,
"autogenerated": false,
"ratio": 3.6493212669683257,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5905055922868325,
"avg_score": null,
"num_lines": null
} |
"""Add talk schedule.
Revision ID: 37c84eaa437
Revises: 3bda3a710eb
Create Date: 2014-08-01 21:26:10.030252
"""
# revision identifiers, used by Alembic.
revision = '37c84eaa437'
down_revision = '3bda3a710eb'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('rooms',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=255), nullable=False),
sa.Column('order', sa.Integer(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_table('days',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('date', sa.Date(), nullable=True),
sa.Column('event_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['event_id'], ['events.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('slots',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('kind', sa.Enum('break', 'meal', 'keynote', 'talk', 'tutorial', name='slotkind'), nullable=False),
sa.Column('content_override', sa.Text(), nullable=True),
sa.Column('start', sa.Time(), nullable=False),
sa.Column('end', sa.Time(), nullable=False),
sa.Column('day_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['day_id'], ['days.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('presentations',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('slot_id', sa.Integer(), nullable=False),
sa.Column('talk_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['slot_id'], ['slots.id'], ),
sa.ForeignKeyConstraint(['talk_id'], ['talks.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('rooms_slots',
sa.Column('slot_id', sa.Integer(), nullable=True),
sa.Column('room_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['room_id'], ['rooms.id'], ),
sa.ForeignKeyConstraint(['slot_id'], ['slots.id'], )
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('rooms_slots')
op.drop_table('presentations')
op.drop_table('slots')
op.drop_table('days')
op.drop_table('rooms')
### end Alembic commands ###
context = op.get_context()
if context.bind.dialect.name == 'postgresql':
op.execute('DROP TYPE slotkind')
| {
"repo_name": "pathunstrom/pygotham",
"path": "migrations/versions/37c84eaa437_.py",
"copies": "3",
"size": "2407",
"license": "bsd-3-clause",
"hash": -9152513036722094000,
"line_mean": 33.3857142857,
"line_max": 112,
"alpha_frac": 0.6393851267,
"autogenerated": false,
"ratio": 3.3997175141242937,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.010202339713771364,
"num_lines": 70
} |
"""Add TAS history fields
Revision ID: 4dc597500734
Revises: 885280875a1c
Create Date: 2016-10-26 19:37:17.347049
"""
# revision identifiers, used by Alembic.
revision = '4dc597500734'
down_revision = '885280875a1c'
branch_labels = None
depends_on = None
from datetime import date
from alembic import op
import sqlalchemy as sa
def upgrade(engine_name):
globals()["upgrade_%s" % engine_name]()
def downgrade(engine_name):
globals()["downgrade_%s" % engine_name]()
# Helper table to make the data queries below a tad easier. We don't want to
# import TASLookup directly as its definition may change
tas_table = sa.Table(
'tas_lookup',
sa.MetaData(),
sa.Column('tas_id', sa.Integer, primary_key=True),
sa.Column('account_num', sa.Integer),
sa.Column('internal_start_date', sa.Date)
)
def upgrade_data_broker():
"""We are moving some data around: moving all of the `tas_id` info into an
`account_num` column, renumbering the `tas_id`, adding an two date columns
and initializing one to 2015-01-01"""
conn = op.get_bind()
# Create the new columns, but all null. We'll fill them with data then set
# them to be non-nullable
op.add_column('tas_lookup',
sa.Column('account_num', sa.Integer(), nullable=True))
op.add_column('tas_lookup',
sa.Column('internal_end_date', sa.Date(), nullable=True))
op.add_column('tas_lookup',
sa.Column('internal_start_date', sa.Date(), nullable=True))
# Set account_num to tas_id values
conn.execute(tas_table.update().values(account_num=tas_table.c.tas_id))
op.alter_column('tas_lookup', 'account_num', nullable=False)
op.create_index(op.f('ix_tas_lookup_account_num'), 'tas_lookup',
['account_num'], unique=False)
# Reset tas_id values; we bump up all the existing tas_ids first to
# prevent duplicates during the renumber
max_tas_id = conn.execute(
sa.sql.select([sa.func.max(tas_table.c.tas_id)])
).scalar() or 0
conn.execute(
tas_table.update().values(tas_id=tas_table.c.tas_id + max_tas_id))
op.execute("ALTER SEQUENCE tas_lookup_tas_id_seq RESTART")
op.execute(
"UPDATE tas_lookup SET tas_id = nextval('tas_lookup_tas_id_seq')")
# Finally, fill in the empty start dates with 2015-01-01, the beginning of
# our accepted submissions
conn.execute(
tas_table.update().values(internal_start_date=date(2015, 1, 1)))
op.alter_column('tas_lookup', 'internal_start_date', nullable=False)
def downgrade_data_broker():
conn = op.get_bind()
op.drop_column('tas_lookup', 'internal_start_date')
op.drop_column('tas_lookup', 'internal_end_date')
# Delete soon-to-be-duplicates (i.e. TAS entries that are no longer unique
# once we back out the account_num vs. tas_id distinction)
left, right = tas_table.alias('left'), tas_table.alias('right')
to_delete = sa.sql.select([right.c.tas_id]).select_from(
left.join(right, sa.and_(left.c.account_num == right.c.account_num,
left.c.tas_id < right.c.tas_id))
)
conn.execute(
tas_table.delete().where(tas_table.c.tas_id.in_(to_delete)))
# We also need to move the TAS entries out of the way (so there is no
# temporary tas_id conflict).
max_account_num = conn.execute(
sa.sql.select([sa.func.max(tas_table.c.account_num)])
).scalar() or 0
conn.execute(
tas_table.update().values(tas_id=tas_table.c.tas_id + max_account_num))
# Now that the space is clear and we've deleted duplicates, we can move
# the data back
op.execute("UPDATE tas_lookup SET tas_id = account_num")
op.execute("""
SELECT setval('tas_lookup_tas_id_seq', max(tas_id))
FROM tas_lookup
""")
op.drop_index(op.f('ix_tas_lookup_account_num'), table_name='tas_lookup')
op.drop_column('tas_lookup', 'account_num')
| {
"repo_name": "fedspendingtransparency/data-act-broker-backend",
"path": "dataactcore/migrations/versions/4dc597500734_add_tas_history_fields.py",
"copies": "1",
"size": "3956",
"license": "cc0-1.0",
"hash": 6322696670969928000,
"line_mean": 35.2935779817,
"line_max": 79,
"alpha_frac": 0.6519211325,
"autogenerated": false,
"ratio": 3.23996723996724,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9378573091152358,
"avg_score": 0.002663056262976486,
"num_lines": 109
} |
"""Add tas_id field to staging models
Revision ID: 6f79cf30f2d7
Revises: 807a203713a4
Create Date: 2016-11-11 17:20:25.108568
"""
# revision identifiers, used by Alembic.
revision = '6f79cf30f2d7'
down_revision = '807a203713a4'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade(engine_name):
globals()["upgrade_%s" % engine_name]()
def downgrade(engine_name):
globals()["downgrade_%s" % engine_name]()
upgrade_sql = """
UPDATE {table_name}
SET tas_id = (
SELECT min(tas.tas_id)
FROM submission AS sub
LEFT JOIN tas_lookup AS tas ON (
{table_name}.allocation_transfer_agency
IS NOT DISTINCT FROM tas.allocation_transfer_agency
AND {table_name}.agency_identifier
IS NOT DISTINCT FROM tas.agency_identifier
AND {table_name}.beginning_period_of_availa
IS NOT DISTINCT FROM tas.beginning_period_of_availability
AND {table_name}.ending_period_of_availabil
IS NOT DISTINCT FROM tas.ending_period_of_availability
AND {table_name}.availability_type_code
IS NOT DISTINCT FROM tas.availability_type_code
AND {table_name}.main_account_code
IS NOT DISTINCT FROM tas.main_account_code
AND {table_name}.sub_account_code
IS NOT DISTINCT FROM tas.sub_account_code
AND (sub.reporting_start_date, sub.reporting_end_date) OVERLAPS
-- A null end date indicates "still open". To make OVERLAPS
-- work, we'll use the day after the end date of the submission
-- to achieve the same result
(tas.internal_start_date,
COALESCE(tas.internal_end_date,
sub.reporting_end_date + interval '1 day')
)
)
WHERE sub.submission_id = {table_name}.submission_id
)
"""
def upgrade_data_broker():
### commands auto generated by Alembic - please adjust! ###
op.add_column('appropriation', sa.Column('tas_id', sa.Integer(), nullable=True))
op.create_foreign_key('fk_tas', 'appropriation', 'tas_lookup', ['tas_id'], ['tas_id'])
op.add_column('award_financial', sa.Column('tas_id', sa.Integer(), nullable=True))
op.create_foreign_key('fk_tas', 'award_financial', 'tas_lookup', ['tas_id'], ['tas_id'])
op.add_column('object_class_program_activity', sa.Column('tas_id', sa.Integer(), nullable=True))
op.create_foreign_key('fk_tas', 'object_class_program_activity', 'tas_lookup', ['tas_id'], ['tas_id'])
### end Alembic commands ###
for table_name in ('appropriation', 'award_financial',
'object_class_program_activity'):
op.execute(upgrade_sql.format(table_name=table_name))
def downgrade_data_broker():
### commands auto generated by Alembic - please adjust! ###
op.drop_constraint('fk_tas', 'object_class_program_activity', type_='foreignkey')
op.drop_column('object_class_program_activity', 'tas_id')
op.drop_constraint('fk_tas', 'award_financial', type_='foreignkey')
op.drop_column('award_financial', 'tas_id')
op.drop_constraint('fk_tas', 'appropriation', type_='foreignkey')
op.drop_column('appropriation', 'tas_id')
### end Alembic commands ###
| {
"repo_name": "fedspendingtransparency/data-act-broker-backend",
"path": "dataactcore/migrations/versions/6f79cf30f2d7_add_tas_id_field_to_staging_models.py",
"copies": "1",
"size": "3359",
"license": "cc0-1.0",
"hash": -5738765124236972000,
"line_mean": 38.9880952381,
"line_max": 106,
"alpha_frac": 0.6290562667,
"autogenerated": false,
"ratio": 3.5395152792413067,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46685715459413063,
"avg_score": null,
"num_lines": null
} |
"""add_tas_indices
Revision ID: a118bf9e4970
Revises: c0a714ade734
Create Date: 2016-04-26 22:16:33.624860
"""
# revision identifiers, used by Alembic.
revision = 'a118bf9e4970'
down_revision = '17a20023b474'
branch_labels = None
depends_on = None
from alembic import op
from dataactvalidator.models.validationModels import TASLookup
def upgrade(engine_name):
globals()["upgrade_%s" % engine_name]()
def downgrade(engine_name):
globals()["downgrade_%s" % engine_name]()
def upgrade_validation():
"""Drop existing non-PK indices to handle legacy installs & add new indices."""
# drop indexes with legacy names, if they still exist
op.execute('drop index if exists tas_lookup_allocation_transfer_agency_idx')
op.execute('drop index if exists tas_lookup_availability_type_code_idx')
op.execute('drop index if exists tas_lookup_beginning_period_of_availability_idx')
op.execute('drop index if exists tas_lookup_main_account_code_idx')
op.execute('drop index if exists tas_lookup_ending_period_of_availability_idx')
op.execute('drop index if exists tas_lookup_sub_account_code_idx')
op.execute('drop index if exists tas_lookup_agency_identifier_idx')
# add next indexes based on model definition
op.create_index(op.f('ix_tas_lookup_agency_identifier'), 'tas_lookup', ['agency_identifier'], unique=False)
op.create_index(op.f('ix_tas_lookup_allocation_transfer_agency'), 'tas_lookup', ['allocation_transfer_agency'], unique=False)
op.create_index(op.f('ix_tas_lookup_availability_type_code'), 'tas_lookup', ['availability_type_code'], unique=False)
op.create_index(op.f('ix_tas_lookup_beginning_period_of_availability'), 'tas_lookup', ['beginning_period_of_availability'], unique=False)
op.create_index(op.f('ix_tas_lookup_ending_period_of_availability'), 'tas_lookup', ['ending_period_of_availability'], unique=False)
op.create_index(op.f('ix_tas_lookup_main_account_code'), 'tas_lookup', ['main_account_code'], unique=False)
op.create_index(op.f('ix_tas_lookup_sub_account_code'), 'tas_lookup', ['sub_account_code'], unique=False)
### end Alembic commands ###
def downgrade_validation():
### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_tas_lookup_sub_account_code'), table_name='tas_lookup')
op.drop_index(op.f('ix_tas_lookup_main_account_code'), table_name='tas_lookup')
op.drop_index(op.f('ix_tas_lookup_ending_period_of_availability'), table_name='tas_lookup')
op.drop_index(op.f('ix_tas_lookup_beginning_period_of_availability'), table_name='tas_lookup')
op.drop_index(op.f('ix_tas_lookup_availability_type_code'), table_name='tas_lookup')
op.drop_index(op.f('ix_tas_lookup_allocation_transfer_agency'), table_name='tas_lookup')
op.drop_index(op.f('ix_tas_lookup_agency_identifier'), table_name='tas_lookup')
### end Alembic commands ###
| {
"repo_name": "fedspendingtransparency/data-act-validator",
"path": "dataactvalidator/migrations/versions/a118bf9e4970_add_tas_indices.py",
"copies": "1",
"size": "2903",
"license": "cc0-1.0",
"hash": 2034314512358422500,
"line_mean": 48.2033898305,
"line_max": 141,
"alpha_frac": 0.7192559421,
"autogenerated": false,
"ratio": 3.2219755826859044,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4441231524785904,
"avg_score": null,
"num_lines": null
} |
"""Add Task
Revision ID: 26dbd6ff063c
Revises: 26c0affcb18a
Create Date: 2014-01-09 17:03:39.051795
"""
# revision identifiers, used by Alembic.
revision = '26dbd6ff063c'
down_revision = '26c0affcb18a'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(
'task',
sa.Column('id', sa.GUID(), nullable=False),
sa.Column('task_name', sa.String(length=128), nullable=False),
sa.Column('parent_id', sa.GUID(), nullable=False),
sa.Column('child_id', sa.GUID(), nullable=False),
sa.Column('status', sa.Enum(), nullable=False),
sa.Column('result', sa.Enum(), nullable=False),
sa.Column('num_retries', sa.Integer(), nullable=False),
sa.Column('date_started', sa.DateTime(), nullable=True),
sa.Column('date_finished', sa.DateTime(), nullable=True),
sa.Column('date_created', sa.DateTime(), nullable=True),
sa.Column('date_modified', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('task_name', 'parent_id', 'child_id', name='unq_task_entity')
)
op.create_index('idx_task_parent_id', 'task', ['parent_id', 'task_name'])
op.create_index('idx_task_child_id', 'task', ['child_id', 'task_name'])
def downgrade():
op.drop_table('task')
| {
"repo_name": "dropbox/changes",
"path": "migrations/versions/26dbd6ff063c_add_task.py",
"copies": "4",
"size": "1320",
"license": "apache-2.0",
"hash": 5049492221648061000,
"line_mean": 32,
"line_max": 89,
"alpha_frac": 0.6356060606,
"autogenerated": false,
"ratio": 3.235294117647059,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0024064009661835745,
"num_lines": 40
} |
"""Add task parent to retain history after split
Revision ID: 5002e75c0604
Revises: 33e34b3beaa3
Create Date: 2016-05-10 22:37:31.383527
"""
# revision identifiers, used by Alembic.
revision = '5002e75c0604'
down_revision = '33e34b3beaa3'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('task', sa.Column('parent_id', sa.Integer(), nullable=True))
#task_table = table('task', column('zoom'), column('x'), column('y'))
#project_table = table('project', column('id'), column('zoom'))
project_table = sa.Table(
'project',
sa.MetaData(),
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('zoom', sa.Integer)
)
task_table = sa.Table(
'task',
sa.MetaData(),
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('project_id', sa.Integer, primary_key=True),
sa.Column('zoom', sa.Integer),
sa.Column('x', sa.Integer),
sa.Column('y', sa.Integer),
sa.Column('parent_id', sa.Integer),
)
# build a quick link for the current connection of alembic
connection = op.get_bind()
for project in connection.execute(project_table.select()
.order_by(project_table.c.id)):
print "Migrating project %i" % project.id
if project.zoom is None:
continue
query = task_table.select() \
.where(sa.and_(task_table.c.project_id == project.id,
task_table.c.zoom != project.zoom))
for task in connection.execute(query):
parent_x = task.x / 2
parent_y = task.y / 2
op.execute(
task_table.update().values(
parent_id=sa.select([task_table.c.id])
.where(sa.and_(
task_table.c.x == parent_x,
task_table.c.y == parent_y,
task_table.c.project_id == project.id
))
)
.where(sa.and_(task_table.c.id == task.id,
task_table.c.project_id == project.id))
)
def downgrade():
op.drop_column('task', 'parent_id')
| {
"repo_name": "ethan-nelson/osm-tasking-manager2",
"path": "alembic/versions/5002e75c0604_add_task_parent_to_retain_history_after_.py",
"copies": "3",
"size": "2253",
"license": "bsd-2-clause",
"hash": 1174307928787483400,
"line_mean": 31.1857142857,
"line_max": 78,
"alpha_frac": 0.5335108744,
"autogenerated": false,
"ratio": 3.6753670473083195,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.570887792170832,
"avg_score": null,
"num_lines": null
} |
"""Add tasks and task_items
Revision ID: ee6d6ae007c1
Revises:
Create Date: 2016-01-31 11:45:51.000634
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'ee6d6ae007c1'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('tasks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('uuid', sa.String(length=36), nullable=False),
sa.Column('action', sa.String(length=255), nullable=False),
sa.Column('state', sa.String(length=255), nullable=False),
sa.Column('request_id', sa.String(length=255), nullable=False),
sa.Column('user_id', sa.String(length=255), nullable=False),
sa.Column('project_id', sa.String(length=255), nullable=False),
sa.Column('params', sa.Text(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('ended_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
mysql_charset='utf8',
mysql_engine='InnoDB'
)
op.create_table('task_items',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('uuid', sa.String(length=36), nullable=False),
sa.Column('action', sa.String(length=255), nullable=False),
sa.Column('state', sa.String(length=255), nullable=False),
sa.Column('task_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('ended_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['task_id'], ['tasks.id'], ),
sa.PrimaryKeyConstraint('id'),
mysql_charset='utf8',
mysql_engine='InnoDB'
)
### end Alembic commands ###
def downgrade():
pass
| {
"repo_name": "jaypipes/enamel",
"path": "enamel/db/migrations/versions/ee6d6ae007c1_add_tasks_and_task_items.py",
"copies": "1",
"size": "1872",
"license": "apache-2.0",
"hash": -6540133832905861000,
"line_mean": 32.4285714286,
"line_max": 67,
"alpha_frac": 0.6655982906,
"autogenerated": false,
"ratio": 3.313274336283186,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.44788726268831863,
"avg_score": null,
"num_lines": null
} |
"""Add tasks
Revision ID: 305a51819d48
Revises: ae8f4b63876a
Create Date: 2019-05-24 09:38:15.831712
"""
from alembic import op
import sqlalchemy as sa
import pycroft
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '305a51819d48'
down_revision = 'ae8f4b63876a'
branch_labels = None
depends_on = None
task_type = sa.Enum('USER_MOVE_OUT', 'USER_MOVE_IN', 'USER_MOVE', name='tasktype')
task_status = sa.Enum('OPEN', 'EXECUTED', 'FAILED', 'CANCELLED', name='taskstatus')
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('task',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('task_type', sa.String(length=50), nullable=True),
sa.Column('type', task_type, nullable=False),
sa.Column('due', pycroft.model.types.DateTimeTz(), nullable=False),
sa.Column('parameters', postgresql.JSONB(astext_type=sa.Text()), nullable=False),
sa.Column('created', pycroft.model.types.DateTimeTz(), nullable=False),
sa.Column('creator_id', sa.Integer(), nullable=False),
sa.Column('status', task_status, nullable=False),
sa.Column('errors', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.ForeignKeyConstraint(['creator_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('task_log_entry',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('task_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['id'], ['log_entry.id'], ondelete='CASCADE'),
sa.ForeignKeyConstraint(['task_id'], ['task.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_task_log_entry_task_id'), 'task_log_entry', ['task_id'], unique=False)
op.create_table('user_task',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['id'], ['task.id'], ondelete='CASCADE'),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
_property = sa.table('property', sa.column('name', sa.String))
op.execute(_property.update().where(
_property.c.name == op.inline_literal('user_hosts_change'))
.values({'name': op.inline_literal('hosts_change')}))
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('user_task')
op.drop_index(op.f('ix_task_log_entry_task_id'), table_name='task_log_entry')
op.drop_table('task_log_entry')
op.drop_table('task')
# ### end Alembic commands ###
task_type.drop(op.get_bind())
task_status.drop(op.get_bind())
_property = sa.table('property', sa.column('name', sa.String))
op.execute(_property.update().where(
_property.c.name == op.inline_literal('hosts_change'))
.values({'name': op.inline_literal('user_hosts_change')}))
| {
"repo_name": "lukasjuhrich/pycroft",
"path": "pycroft/model/alembic/versions/305a51819d48_add_tasks.py",
"copies": "2",
"size": "2959",
"license": "apache-2.0",
"hash": -9179180080334842000,
"line_mean": 37.9342105263,
"line_max": 99,
"alpha_frac": 0.656978709,
"autogenerated": false,
"ratio": 3.298773690078038,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49557523990780383,
"avg_score": null,
"num_lines": null
} |
"""Add tasks
Revision ID: 58973c4a356
Revises: 25b6970745c
Create Date: 2014-04-18 14:28:49.641451
"""
# revision identifiers, used by Alembic.
revision = '58973c4a356'
down_revision = '25b6970745c'
from alembic import op
import sqlalchemy as sa
status = sa.Enum('open', 'completed', 'closed', name='status')
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('tasks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('created', sa.DateTime(timezone=True), nullable=False),
sa.Column('updated', sa.DateTime(timezone=True), nullable=False),
sa.Column('status', status, nullable=False),
sa.Column('project_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['project_id'], ['projects.id'], ),
sa.PrimaryKeyConstraint('id')
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('tasks')
status.drop(op.get_bind())
### end Alembic commands ###
| {
"repo_name": "xuhcc/airy",
"path": "alembic/versions/20140418_1428_add_tasks.py",
"copies": "1",
"size": "1144",
"license": "mit",
"hash": -2348861425984552000,
"line_mean": 27.6,
"line_max": 69,
"alpha_frac": 0.6695804196,
"autogenerated": false,
"ratio": 3.4354354354354353,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46050158550354353,
"avg_score": null,
"num_lines": null
} |
"""add tasks table
Revision ID: b764aaedf10d
Revises:
Create Date: 2017-10-29 14:56:07.313468
"""
# pylint: skip-file
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b764aaedf10d'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('tasks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=False),
sa.Column('description', sa.String(), nullable=False),
sa.Column('status', sa.String(), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
sa.PrimaryKeyConstraint('id', name=op.f('pk_tasks'))
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('tasks')
# ### end Alembic commands ###
| {
"repo_name": "kokimoribe/todo-api",
"path": "alembic/versions/b764aaedf10d_add_tasks_table.py",
"copies": "1",
"size": "1084",
"license": "mit",
"hash": 8846923853504026000,
"line_mean": 27.5263157895,
"line_max": 105,
"alpha_frac": 0.6688191882,
"autogenerated": false,
"ratio": 3.430379746835443,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4599198935035443,
"avg_score": null,
"num_lines": null
} |
"""Add team join requests table
Revision ID: fb00f6d8fded
Revises: e7c5d6a3fd01
Create Date: 2018-12-27 23:37:54.871284
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'fb00f6d8fded'
down_revision = 'e7c5d6a3fd01'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('join_requests',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('kerberos', sa.String(length=128), nullable=True),
sa.Column('team_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['team_id'], ['teams.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_join_requests_kerberos'), 'join_requests', ['kerberos'], unique=True)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_join_requests_kerberos'), table_name='join_requests')
op.drop_table('join_requests')
# ### end Alembic commands ###
| {
"repo_name": "mitpokerbots/scrimmage",
"path": "migrations/versions/fb00f6d8fded_.py",
"copies": "1",
"size": "1072",
"license": "mit",
"hash": 7024949260723837000,
"line_mean": 28.7777777778,
"line_max": 98,
"alpha_frac": 0.677238806,
"autogenerated": false,
"ratio": 3.2,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9360301384540473,
"avg_score": 0.0033874842919054474,
"num_lines": 36
} |
"""Add teams table
Revision ID: 2d8b17e13d1
Revises: 27e81ea4d86
Create Date: 2014-02-27 02:00:25.694782
"""
from alembic import context
from alembic.op import (create_index, create_table,
drop_index, drop_table, execute)
from sqlalchemy.schema import Column, PrimaryKeyConstraint
from sqlalchemy.types import DateTime, Integer, String
# revision identifiers, used by Alembic.
revision = '2d8b17e13d1'
down_revision = '27e81ea4d86'
driver_name = context.get_bind().dialect.name
def upgrade():
create_table(
'teams',
Column('id', Integer, nullable=False),
Column('name', String),
Column('created_at', DateTime(timezone=True), nullable=False),
PrimaryKeyConstraint('id')
)
create_index('ix_teams_created_at', 'teams', ['created_at'])
create_index('ix_teams_name', 'teams', ['name'])
def downgrade():
drop_index('ix_teams_name', table_name='teams')
drop_index('ix_teams_created_at', table_name='teams')
drop_table('teams')
if driver_name == 'postgresql':
execute('DROP SEQUENCE teams_id_seq')
| {
"repo_name": "clicheio/cliche",
"path": "cliche/migrations/versions/2d8b17e13d1_add_teams_table.py",
"copies": "2",
"size": "1103",
"license": "mit",
"hash": -2744772270316862000,
"line_mean": 27.2820512821,
"line_max": 70,
"alpha_frac": 0.6718041704,
"autogenerated": false,
"ratio": 3.404320987654321,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5076125158054321,
"avg_score": null,
"num_lines": null
} |
"""Add templates
Revision ID: 2b0edcfa57b4
Revises: 24be36b8c67
Create Date: 2015-11-24 17:50:13.280722
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2b0edcfa57b4'
down_revision = '24be36b8c67'
DEFAULT_LABELS = (
(u'Green', u'#22C328'),
(u'Red', u'#CC3333'),
(u'Blue', u'#3366CC'),
(u'Yellow', u'#D7D742'),
(u'Orange', u'#DD9A3C'),
(u'Purple', u'#8C28BD')
)
boards = sa.Table(
'board',
sa.MetaData(),
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('title', sa.Unicode(255)),
sa.Column('is_template', sa.Boolean, default=False),
sa.Column('comments_allowed', sa.Integer, default=1),
sa.Column('votes_allowed', sa.Integer, default=1),
sa.Column('description', sa.UnicodeText, default=u''),
sa.Column('visibility', sa.Integer, default=0),
sa.Column('version', sa.Integer, default=0, server_default='0'),
sa.Column('uri', sa.Unicode(255), index=True, unique=True),
sa.Column('archive', sa.Integer, default=0),
sa.Column('archived', sa.Boolean, default=False),
sa.Column('weighting_cards', sa.Integer, default=0),
sa.Column('weights', sa.Unicode(255), default=u'')
)
columns = sa.Table(
'column',
sa.MetaData(),
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('title', sa.Unicode(200)),
sa.Column('index', sa.Integer),
sa.Column('nb_max_cards', sa.Integer),
sa.Column('archive', sa.Boolean, default=False),
sa.Column('board_id', sa.Integer)
)
labels = sa.Table(
'label',
sa.MetaData(),
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('title', sa.Unicode(255)),
sa.Column('color', sa.Unicode(255)),
sa.Column('board_id', sa.Integer),
sa.Column('index', sa.Integer)
)
def upgrade():
bind = op.get_bind()
# Add column
op.add_column('board', sa.Column('is_template', sa.Boolean, default=lambda: False))
bind.execute(boards.update().values(is_template=False))
# Empty board
insert = boards.insert({'title': u'Empty board',
'is_template': True,
'visibility': 1})
board_id = bind.execute(insert).inserted_primary_key[0]
for index, (title, color) in enumerate(DEFAULT_LABELS):
insert = labels.insert({'title': title,
'color': color,
'index': index,
'board_id': board_id})
bind.execute(insert)
# Todo board
insert = boards.insert({'title': u'Todo',
'is_template': True,
'visibility': 1})
board_id = bind.execute(insert).inserted_primary_key[0]
for index, title in enumerate((u'To Do', u'Doing', u'Done')):
insert = columns.insert({'title': title,
'index': index,
'board_id': board_id})
bind.execute(insert)
for index, (title, color) in enumerate(DEFAULT_LABELS):
insert = labels.insert({'title': title,
'color': color,
'index': index,
'board_id': board_id})
bind.execute(insert)
def downgrade():
op.drop_column('board', 'is_template')
| {
"repo_name": "Net-ng/kansha",
"path": "kansha/alembic/versions/2b0edcfa57b4_add_templates.py",
"copies": "2",
"size": "3345",
"license": "bsd-3-clause",
"hash": -904022361724453400,
"line_mean": 29.9722222222,
"line_max": 87,
"alpha_frac": 0.5662182362,
"autogenerated": false,
"ratio": 3.4307692307692306,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49969874669692305,
"avg_score": null,
"num_lines": null
} |
"""Add the Area model
Revision ID: 54db49335a2
Revises: 2367ebea90d
Create Date: 2014-04-20 13:43:33.248879
"""
# revision identifiers, used by Alembic.
revision = '54db49335a2'
down_revision = '2367ebea90d'
from datetime import datetime
from alembic import op
import sqlalchemy as sa
def upgrade():
connection = op.get_bind()
op.create_table(
'area',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('name', sa.String(length=20), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index('ix_area_created_at', 'area', ['created_at'], unique=False)
op.create_index('ix_area_name', 'area', ['name'], unique=True)
op.add_column('device', sa.Column('area_id', sa.Integer()))
# Create two hybrid tables that represent the new table and the old
# device table with the new area_id column.
area_migrator = sa.Table(
'area',
sa.MetaData(),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('name', sa.String(length=20), nullable=True)
)
device_migrator = sa.Table(
'device',
sa.MetaData(),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('name', sa.String(length=20), nullable=True),
sa.Column('device_type', sa.Integer(), nullable=True),
sa.Column('device_sub_type', sa.Integer(), nullable=True),
sa.Column('device_id', sa.String(length=20), nullable=False),
sa.Column('area_id', sa.Integer())
)
for device in connection.execute(device_migrator.select()):
name = device.name
connection.execute(
area_migrator.insert()
.values(name=name,
created_at=datetime.utcnow()))
# After inserting, grab it back. We need to get the ID.
r = connection.execute(
area_migrator
.select().where(
area_migrator.c.name == name,
))
area = r.first()
# Update the data_point table to populate the new device_series_id.
connection.execute(
device_migrator.update().where(
device_migrator.c.id == device.id
).values(
area_id=area['id']
)
)
# Ok, now its fully populated. Disable nulls on the col. If there are still
# nulls we will get an error here, so its a good sanity check.
op.alter_column('device', 'area_id', nullable=False)
# Finally drop the old stuff as per the alembic generated code.
op.drop_column('device', 'name')
def downgrade():
op.create_index('ix_device_name', 'device', ['name'], unique=True)
op.add_column('device', sa.Column('name', sa.VARCHAR(length=20),
nullable=True))
op.drop_column('device', 'area_id')
op.drop_index('ix_area_name', table_name='area')
op.drop_index('ix_area_created_at', table_name='area')
op.drop_table('area')
| {
"repo_name": "d0ugal-archive/home",
"path": "home/migrations/versions/54db49335a2_area_model.py",
"copies": "1",
"size": "3139",
"license": "bsd-3-clause",
"hash": 5091012766178737000,
"line_mean": 31.0306122449,
"line_max": 79,
"alpha_frac": 0.602739726,
"autogenerated": false,
"ratio": 3.6039035591274398,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.470664328512744,
"avg_score": null,
"num_lines": null
} |
"""Add the FA (Frequency of Allelle) field to a VCF file.
This field is derived from other existing information in the VCF file.
Supports SomaticSniper, VarScan, Mutect, Strelka VCFs.
"""
import os
import sys
import vcf
FA_FORMAT = vcf.parser._Format('FA', 1, 'Float', 'Frequency of ALT alleles.')
def deriver_for(caller):
"""Returns the deriver for a given variant caller. The deriver is a function
which takes a VCF record and outputs a VCF record which has the FA attribute
set.
Caller must be one of 'strelka', 'somaticsniper', 'virmid', 'varscan',
'mutect'.
"""
callers = {'strelka': _derive_strelka_fa,
'somaticsniper': _derive_somaticsniper_fa,
'varscan': _derive_varscan_fa,
'mutect': lambda x: x,
'virmid': lambda x: x}
try:
return callers[caller.lower()]
except KeyError:
sys.stderr.write('ERROR: caller "' + caller + '" is not recognized.')
sys.exit(1)
def _derive_varscan_fa(record):
# Varscan outputs FA already, but in a string formatted as 'XX.XX%' under
# the key FREQ, so we just need to pull that out and process it correctly.
for sample in record.samples:
add_format_field(record, 'FA')
freq_string = sample.data.FREQ
frequency_of_allele = float(freq_string[:-1]) / 100
add_field(record, sample.sample, 'FA', frequency_of_allele)
return record
def _derive_strelka_fa(record):
alts = [str(alt) for alt in record.ALT]
for sample in record.samples:
add_format_field(record, 'FA')
read_depth = sample.data.DP
# In Strelka, allele counts are in fields AU, GU, CU, TU.
# These fields are lists of tier1 and tier2 allele counts
# with tier1 being the higher quality used.
counts = {alt: sample.data.__dict__[alt+"U"][0]
for alt in alts if alt != 'None'}
alts_total = sum(counts[allele] for allele in alts if allele != 'None')
frequency_of_allele = round(float(alts_total) / read_depth, 3)
add_field(record, sample.sample, 'FA', frequency_of_allele)
return record
def _derive_somaticsniper_fa(record):
# c.f. Somatic Sniper's manual for order of bcount alleles
bcount_index = {0: 'A', 1: 'C', 2: 'G', 3: 'T'}
alts = [str(alt) for alt in record.ALT]
for sample in record.samples:
add_format_field(record, 'FA')
read_depth = sample.data.DP
bcounts = sample.data.BCOUNT
allele_counts = {bcount_index[idx]: count
for idx, count in enumerate(bcounts)}
alts_total = sum(allele_counts[allele] for allele in alts)
frequency_of_allele = round(float(alts_total) / read_depth, 3)
add_field(record, sample.sample, 'FA', frequency_of_allele)
return record
def add_field(record, sample_name, fieldname, value):
"""Return record with the field added to the data dict of the specified
sample.
"""
sample_idx = record._sample_indexes[sample_name]
sample = record.samples[sample_idx]
data = sample.data.__dict__
data[fieldname] = value
calldata = call_data(data)
record.samples[sample_idx] = vcf.model._Call(record, sample_name, calldata)
add_format_field(record, 'FA')
return record
def add_format_field(record, fieldname):
"""Return record with fieldname added to the FORMAT field if it doesn't
already exist.
"""
format = record.FORMAT.split(':')
if fieldname not in format:
record.FORMAT = record.FORMAT + ":" + fieldname
return record
def call_data(kvs):
"""Return a CallData with the given keys (fields) and values."""
CallData = vcf.model.make_calldata_tuple(kvs.keys())
return CallData._make(kvs.values())
if __name__ == '__main__':
_, caller, infile = sys.argv
basename = os.path.splitext(infile)[0]
deriver = deriver_for(caller)
with open(infile) as vcf_in:
records = vcf.Reader(vcf_in)
records.formats['FA'] = FA_FORMAT
with open(basename + '.derivedFA.vcf', 'w') as output:
writer = vcf.Writer(output, records)
for record in records:
writer.write_record(deriver(record))
print("Derived FA for {}".format(sys.argv[1]))
| {
"repo_name": "danvk/concordance",
"path": "derive_frequency_of_alleles.py",
"copies": "2",
"size": "4294",
"license": "apache-2.0",
"hash": 2736221140092211000,
"line_mean": 33.0793650794,
"line_max": 80,
"alpha_frac": 0.6318118305,
"autogenerated": false,
"ratio": 3.4160700079554496,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0005916579990654065,
"num_lines": 126
} |
# add the following to operations in migrations
# from . import initialize_settings
# migrations.RunPython(initialize_settings),
def initialize_settings(apps, schema_editor):
SettingsCategory = apps.get_model('tethys_compute', 'SettingsCategory')
Setting = apps.get_model('tethys_compute', 'Setting')
category = SettingsCategory(name='Cluster Management')
category.save()
for setting in ['Scheduler IP', 'Scheduler Key Location', 'Default Cluster']:
s = Setting(name=setting, category=category)
s.save()
category = SettingsCategory(name='Amazon Credentials')
category.save()
for setting in ['AWS Access Key ID', 'AWS Secret Access Key', 'AWS User ID', 'Key Name', 'Key Location']:
s = Setting(name=setting, category=category)
s.save()
category = SettingsCategory(name='Azure Credentials')
category.save()
for setting in['Subscription ID', 'Certificate Path']:
s = Setting(name=setting, category=category)
s.save()
def clear_settings(apps, schema_edititor):
SettingsCategory = apps.get_model('tethys_compute', 'SettingsCategory')
Setting = apps.get_model('tethys_compute', 'Setting')
SettingsCategory.objects.all().delete()
Setting.objects.all().delete()
| {
"repo_name": "tethysplatform/tethys",
"path": "tethys_compute/migrations/__init__.py",
"copies": "2",
"size": "1271",
"license": "bsd-2-clause",
"hash": -7992456151575249000,
"line_mean": 36.3823529412,
"line_max": 109,
"alpha_frac": 0.6931549961,
"autogenerated": false,
"ratio": 4.060702875399361,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.001124564223073573,
"num_lines": 34
} |
# Add the framework to the Python path
import sys, os
PHDCODE_ROOT = os.environ['PHDCODE_ROOT']
sys.path.append("%s/python"%PHDCODE_ROOT)
#sys.path.append(os.getcwd()+"/..")
from framework.Window import Rect, Kaiser, Trig
from framework.Coordinate import Coordinate
import framework.mynumpy as np
from framework.mynumpy import pi, abs, arcsin, dot, zeros, mean, db
from numpy.fft import fft, ifft
#from gfuncs import abs
from framework.System import System
from .. import getCaponC as getCaponC
def start(s):
PROFILE = False
Xd_i= Xd[0,:,:,:]
res = getCaponC.getCapon(Xd_i, regCoef, L, nTimeAverage, V, doForwardBackwardAveraging, verbose)
img_capon_ampl = res[0]
# Steering angles:
M = s['M'][0]
d = s['d'][0]
c = s['c'][0]
fc = s['fc'][0]
D = M*d
lmda = float(c)/fc
# Get the relevant parameters. Todo: Make system.open() for this
Xd = s.data.Xd
Ni = Xd.shape[0] # No. realisations
N = Xd.shape[1] # No. time samples (y-coordinates)
Ny = N # No. y-coordinates in image
Nx = Xd.shape[2] # No. x-coordinates in image
Nm = Xd.shape[3] # No. channels
# Capon parameters
regCoef = 1.0/100 # Diagonal loading
L = 16 # Subarray size <= N/2 (e.g. 16)
nTimeAverage = 1 # Capon range-average window (+- this value)
V = np.array([]) # Subspace matrix
doForwardBackwardAveraging = False
verbose = False
Xd_i= Xd[0,:,:,:]
res = getCaponC.getCapon(Xd_i, regCoef, L, nTimeAverage, V, doForwardBackwardAveraging, verbose)
img_capon_ampl = res[0]
if '__IP' not in globals():
s = System('HISAS speckle')
start(s)
print 'hey'
| {
"repo_name": "jpaasen/cos",
"path": "framework/beamformer/capon/tests/run_getCaponC.py",
"copies": "1",
"size": "1790",
"license": "mit",
"hash": 7126535966782791000,
"line_mean": 23.5205479452,
"line_max": 99,
"alpha_frac": 0.5938547486,
"autogenerated": false,
"ratio": 2.9392446633825946,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.40330994119825947,
"avg_score": null,
"num_lines": null
} |
"""Add the generic fixed and derived content to a Classic Pygame document"""
from ext.utils import (Visitor, _unicode, as_unicode, get_name, GetError,
get_refid, as_refid, as_refuri)
from ext.indexer import get_descinfo, get_descinfo_refid
from sphinx.addnodes import (desc, desc_signature, desc_content)
try:
from sphinx.addnodes import module as section_prelude_end_class
except ImportError:
from sphinx.addnodes import index as section_prelude_end_class
from docutils.nodes import (section, literal, reference, paragraph, title,
document, Text, TextElement, inline,
table, tgroup, colspec, tbody, row, entry,
whitespace_normalize_name, SkipNode)
import os
import re
from collections import deque
DOT = as_unicode('.')
SPACE = as_unicode(' ')
EMDASH = as_unicode(r'\u2014')
def setup(app):
# This extension uses indexer collected tables.
app.setup_extension('ext.indexer')
# Documents to leave untransformed by boilerplate
app.add_config_value('boilerplate_skip_transform', [], '')
# The stages of adding boilerplate markup.
app.connect('doctree-resolved', transform_document)
app.connect('html-page-context', inject_template_globals)
# Internal nodes.
app.add_node(TocRef,
html=(visit_toc_ref_html, depart_toc_ref_html),
latex=(visit_toc_ref, depart_toc_ref),
text=(visit_toc_ref, depart_toc_ref))
app.add_node(TocTable,
html=(visit_toc_table_html, depart_toc_table_html),
latex=(visit_skip, None), text=(visit_skip, None))
app.add_node(DocTitle,
html=(visit_doc_title_html, depart_doc_title_html),
latex=(visit_doc_title, depart_doc_title))
class TocRef(reference):
pass
def visit_toc_ref(self, node):
self.visit_reference(node)
def depart_toc_ref(self, node):
self.depart_reference(node)
def visit_toc_ref_html(self, node):
refuri = node['refuri']
refid = as_refid(refuri)
docname = get_descinfo_refid(refid, self.settings.env)['docname']
link_suffix = self.builder.link_suffix
node['refuri'] = '%s%s%s' % (os.path.basename(docname), link_suffix, refuri)
visit_toc_ref(self, node)
class TocTable(table):
pass
def visit_toc_table_html(self, node):
self.visit_table(node)
def depart_toc_table_html(self, node):
self.depart_table(node)
def visit_skip(self, node):
raise SkipNode()
depart_toc_ref_html = depart_toc_ref
class DocTitle(title):
pass
visit_doc_title_html = visit_skip
depart_doc_title_html = None
def visit_doc_title(self, node):
self.visit_title(node)
def depart_doc_title(self, node):
self.depart_title(node)
def transform_document(app, doctree, docname):
if docname in app.config['boilerplate_skip_transform']:
return
doctree.walkabout(DocumentTransformer(app, doctree))
class DocumentTransformer(Visitor):
_key_re = r'(?P<key>[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*)'
key_pat = re.compile(_key_re)
def __init__(self, app, document_node):
super(DocumentTransformer, self).__init__(app, document_node)
self.module_stack = deque()
self.title_stack = deque()
def visit_section(self, node):
self.title_stack.append(None)
def depart_section(self, node):
title_node = self.title_stack.pop()
if node['ids'][0].startswith('module-'):
transform_module_section(node, title_node, self.env)
def depart_desc(self, node):
node['classes'].append('definition')
node[0]['classes'].append('title')
add_toc(node, self.env)
def visit_title(self, node):
if isinstance(node.parent.parent, document):
# Make title node a DocTitle instance. This works because DocTitle
# simply subclasses title.
node.__class__ = DocTitle
def visit_reference(self, node):
if 'toc' in node['classes']:
return
try:
child = node[0]
except IndexError:
return
if not isinstance(child, TextElement):
return
name = child.astext()
m = self.key_pat.match(name)
if m is None:
return
key = m.group('key')
try:
summary = get_descinfo_refid(key, self.env)['summary']
except GetError:
return
if summary:
node['reftitle'] = ''
node['classes'].append('tooltip')
inline_node = inline('', summary, classes=['tooltip-content'])
node.append(inline_node)
def transform_module_section(section_node, title_node, env):
fullmodname = section_node['names'][0]
where = section_node.first_child_matching_class(section_prelude_end_class)
content_children = list(ipop_child(section_node, where + 1))
if title_node is None:
signature_children = [literal('', fullmodname)]
else:
signature_children = list(ipop_child(title_node))
signature_node = desc_signature('', '', *signature_children,
classes=['title', 'module'],
names=[fullmodname])
content_node = desc_content('', *content_children)
desc_node = desc('', signature_node, content_node,
desctype='module',
objtype='module',
classes=['definition'])
section_node.append(desc_node)
add_toc(desc_node, env, section_node)
def ipop_child(node, start=0):
while len(node) > start:
yield node.pop(start)
def get_target_summary(reference_node, env):
try:
return get_descinfo_refid(reference_node['refid'], env)['summary']
except KeyError:
raise GetError("reference has no refid")
def add_toc(desc_node, env, section_node=None):
"""Add a table of contents to a desc node"""
if (section_node is not None):
refid = get_refid(section_node)
else:
refid = get_refid(desc_node)
descinfo = get_descinfo_refid(refid, env)
toc = build_toc(descinfo, env)
if toc is None:
return
content_node = desc_node[-1]
insert_at = 0
if descinfo['summary']: # if have a summary
insert_at += 1
content_node.insert(insert_at, toc)
def build_toc(descinfo, env):
"""Return a desc table of contents node tree"""
separator = EMDASH
child_ids = descinfo['children']
if not child_ids:
return None
max_fullname_len = 0
max_summary_len = 0
rows = []
for fullname, refid, summary in ichild_ids(child_ids, env):
max_fullname_len = max(max_fullname_len, len(fullname))
max_summary_len = max(max_summary_len, len(summary))
reference_node = toc_ref(fullname, refid)
ref_entry_node = entry('', paragraph('', '', reference_node))
sep_entry_node = entry('', paragraph('', separator))
sum_entry_node = entry('', paragraph('', summary))
row_node = row('', ref_entry_node, sep_entry_node, sum_entry_node)
rows.append(row_node)
col0_len = max_fullname_len + 2 # add error margin
col1_len = len(separator) # no padding
col2_len = max_summary_len + 10 # add error margin
tbody_node = tbody('', *rows)
col0_colspec_node = colspec(colwidth=col0_len)
col1_colspec_node = colspec(colwidth=col1_len)
col2_colspec_node = colspec(colwidth=col2_len)
tgroup_node = tgroup('',
col0_colspec_node,
col1_colspec_node,
col2_colspec_node,
tbody_node,
cols=3)
return TocTable('', tgroup_node, classes=['toc'])
def ichild_ids(child_ids, env):
for refid in child_ids:
descinfo = env.pyg_descinfo_tbl[refid] # A KeyError would mean a bug.
yield descinfo['fullname'], descinfo['refid'], descinfo['summary']
def toc_ref(fullname, refid):
name = whitespace_normalize_name(fullname),
return TocRef('', fullname,
name=name, refuri=as_refuri(refid), classes=['toc'])
#>>===================================================
def decorate_signatures(desc, classname):
prefix = classname + DOT
for child in desc.children:
if (isinstance(child, sphinx.addnodes.desc_signature) and
isinstance(child[0], sphinx.addnodes.desc_name) ):
new_desc_classname = sphinx.addnodes.desc_classname('', prefix)
child.insert(0, new_desc_classname)
#<<==================================================================
def inject_template_globals(app, pagename, templatename, context, doctree):
def lowercase_name(d):
return get_name(d['fullname']).lower()
env = app.builder.env
try:
sections = env.pyg_sections
except AttributeError:
sections = []
else:
sections = sorted(sections, key=lowercase_name)
context['pyg_sections'] = sections
| {
"repo_name": "gmittal/aar-nlp-research-2016",
"path": "src/pygame-pygame-6625feb3fc7f/docs/reST/ext/boilerplate.py",
"copies": "2",
"size": "9078",
"license": "mit",
"hash": 7836685349493744000,
"line_mean": 33.6488549618,
"line_max": 80,
"alpha_frac": 0.6051993831,
"autogenerated": false,
"ratio": 3.702283849918434,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.005533031993625182,
"num_lines": 262
} |
"""Add the high level classes (person/organization/etc.) to a label file."""
import argparse
import pickle
from tqdm import tqdm
def read_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('--labels_file',
type=unicode,
help='Pickled file with a list of labels')
parser.add_argument('--mapping_file',
type=unicode,
help='Pickled file with the mapping from yago labels'
'to high level labels')
return parser.parse_args()
def pickle_from_file(filename):
with open(filename, 'r') as input_file:
result = pickle.load(input_file)
return result
def main():
args = read_arguments()
print 'Reading arguments'
labels = pickle_from_file(args.labels_file)
mapping = pickle_from_file(args.mapping_file)
print 'Processing labels'
for index, label in tqdm(enumerate(labels)):
if len(label) != 5:
print 'Malformed label at index {}'.format(index)
continue
if label[0].startswith('O'):
continue
yago_category = label[1].replace('I-', '').replace('B-', '')
if not yago_category in mapping:
print 'Error, unknown yago category {}'.format(yago_category)
continue
high_level_category = label[1][0] + '-' + mapping[yago_category]
labels[index] = label[:3] + (high_level_category, ) + label[4:]
print 'Saving results'
with open(args.labels_file, 'w') as output_file:
pickle.dump(labels, output_file)
if __name__ == '__main__':
main()
| {
"repo_name": "MIREL-UNC/mirel-scripts",
"path": "preprocess/22_add_high_level_classes.py",
"copies": "1",
"size": "1652",
"license": "bsd-3-clause",
"hash": -9118652511027232000,
"line_mean": 29.5925925926,
"line_max": 77,
"alpha_frac": 0.5853510896,
"autogenerated": false,
"ratio": 4.039119804400978,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5124470894000978,
"avg_score": null,
"num_lines": null
} |
#add the number of degrees of freedom to the master table
import pandas as pd
import numpy as np
def reformat_wisp_grism_id(grism_id):
if grism_id.endswith('.ascii'):
return grism_id.split('ASCII/')[-1].split('.1D.ascii')[0].lower()
if grism_id.endswith('.dat'):
return grism_id.split('lsp_wisp_hst_wfc3_')[-1].split('a_')[0].lower()
alldata=pd.read_hdf('~/research/wisps//libraries/master_dataset.hdf', key='new')
df=pd.read_hdf('~/research/wisps//libraries/all_wisp_spectrasept162020.h5', key='hst3d')
other_keys=np.append(['wisp'], ['wisp{}'.format(x) for x in np.arange(2, 10)])
dfwisp=pd.concat(pd.read_hdf('~/research/wisps//libraries/all_wisp_spectrasept162020.h5', key=k) for k in other_keys )
dfwisp=dfwisp[dfwisp.grism_id.str.contains('g141')]
dfnjoined=pd.concat([dfwisp, df])
dfnjoined['grism_id']=dfnjoined.grism_id.apply(reformat_wisp_grism_id)
dfnjoined=dfnjoined.drop_duplicates(subset='grism_id').reset_index(drop=True)
#print (dfnjoined.shape)
merged=alldata.merge(dfnjoined, how='inner', on='grism_id')
merged.to_hdf('~/research/wisps//libraries/master_dataset.hdf', key='new')
| {
"repo_name": "caganze/wisps",
"path": "wisps/data_analysis/combinedmasters.py",
"copies": "1",
"size": "1135",
"license": "mit",
"hash": -9135919993684822000,
"line_mean": 36.8333333333,
"line_max": 118,
"alpha_frac": 0.7074889868,
"autogenerated": false,
"ratio": 2.5795454545454546,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.37870344413454543,
"avg_score": null,
"num_lines": null
} |
'''Add the parent directory ../ to one of the bash settings files.
'''
import os
import sys
print
print "To skip checks use python install_linux.py --noCheck"
print
if (len(sys.argv) <= 1) or (sys.argv[1].lower()[-7:] != "nocheck"):
print "Checking python version..",
ver = sys.version_info
if (ver < (2, 6)) or (ver >= (3, 0)):
raise RuntimeError("Please use python 2.6+, but not 3.x")
print 'Correct!'
print "Checking for mirnylib..",
try:
import mirnylib #@UnusedImport @IgnorePep8
except:
print "Mirnylib library not installed"
print "see http://bitbucket.org/mirnylab/mirnylib"
raise RuntimeError("Mirnylib library not installed")
print "Found!"
print "Checking for numpy..",
try:
import numpy
print "Found!"
except:
print "Numpy not found"
raise RuntimeError("Numpy not found")
print "Checking for numpy version..",
try:
nv = numpy.__version__
nums = tuple([int(i) for i in nv.split('.')[:2]])
assert nums >= (1, 6)
print "Correct!"
except:
print "numpy version is %s" % nv
print "Needs at least numpy 1.6"
print "See manual for numpy installation guide"
raise RuntimeError("Wrong numpy version")
print "Checking for mirnylib.h5dict install..",
from mirnylib.h5dict import h5dict
a = h5dict()
b = numpy.empty(1000000, dtype="int16")
c = "bla bla bla"
a["numpy"] = b
a["object"] = c
assert (a["numpy"] - b).sum() == 0
print "H5dict test successful!"
print "Checking for joblib..",
try:
import joblib
print "Found!"
except:
print "joblib not found"
raise RuntimeError("joblib not found")
print
os.chdir("src")
libpath = os.getcwd()
libpath = os.path.normpath(libpath.replace(os.path.expanduser('~'), '$HOME/'))
export_line = 'export PYTHONPATH="$PYTHONPATH:{0}"'.format(libpath)
profiles = [os.path.expanduser(i) for i in ['~/.bash_profile', '~/.bashrc']]
# Do nothing if the library is already exported.
for profile_path in profiles:
setflag = 1
if os.path.isfile(profile_path):
for line in open(profile_path):
if export_line in line:
print 'The PYTHONPATH is already set in {0}'.format(
profile_path)
setflag = 0
break
if setflag == 1:
profile_file = open(profile_path, 'a')
profile_file.writelines(
['\n# Added by the mirnylab install script.\n',
export_line,
'\n'])
print 'PYTHONPATH is added to {0}'.format(profile_path)
| {
"repo_name": "bxlab/HiFive_Paper",
"path": "Scripts/HiCLib/mirnylab-hiclib-460c3fbc0f72/install_linux.py",
"copies": "1",
"size": "2684",
"license": "bsd-3-clause",
"hash": -3047979890187070000,
"line_mean": 27.8602150538,
"line_max": 78,
"alpha_frac": 0.5897913562,
"autogenerated": false,
"ratio": 3.691884456671252,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47816758128712517,
"avg_score": null,
"num_lines": null
} |
"""Add the PreferredCloud table.
Revision ID: 588687c6ba4a
Revises: f83b7adaf523
Create Date: 2017-03-20 16:39:04.282582
"""
# revision identifiers, used by Alembic.
revision = '588687c6ba4a'
down_revision = 'f83b7adaf523'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.alter_column('prospect', 'employees',
existing_type=sa.Integer,
type_=sa.String(255),
)
op.drop_column('prospect', 'which_cloud')
op.create_table('which_cloud',
sa.Column('id', sa.Integer, nullable=False),
sa.Column('id_prospect', sa.Integer, nullable=False),
sa.Column('cloud', sa.String(255), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.ForeignKeyConstraint(['id_prospect'], ['prospect.id']),
)
def downgrade():
op.drop_table('which_cloud')
op.add_column('prospect',
sa.Column('which_cloud', sa.String(255), nullable=True),
)
op.alter_column('prospect', 'employees',
type_=sa.Integer,
existing_type=sa.String(255),
)
| {
"repo_name": "giubil/trackit",
"path": "api/files/api/migrations/versions/588687c6ba4a_add_the_preferredcloud_table.py",
"copies": "1",
"size": "1069",
"license": "apache-2.0",
"hash": 905030342211245800,
"line_mean": 25.0731707317,
"line_max": 67,
"alpha_frac": 0.6304957905,
"autogenerated": false,
"ratio": 3.2198795180722892,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9259823509668006,
"avg_score": 0.018110359780856747,
"num_lines": 41
} |
"""Add the Prospect table.
Revision ID: f83b7adaf523
Revises: b6533e0a4e58
Create Date: 2017-03-20 02:19:21.162055
"""
# revision identifiers, used by Alembic.
revision = 'f83b7adaf523'
down_revision = 'b6533e0a4e58'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('prospect',
sa.Column('id', sa.Integer, nullable=False),
sa.Column('name', sa.String(255), nullable=False),
sa.Column('email', sa.String(255), nullable=False),
sa.Column('phone_number', sa.String(255), nullable=True),
sa.Column('company_name', sa.String(255), nullable=True),
sa.Column('address', sa.String(255), nullable=True),
sa.Column('which_cloud', sa.String(255), nullable=True),
sa.Column('employees', sa.Integer, nullable=True),
sa.Column('annual_revenue', sa.Integer, nullable=True),
sa.PrimaryKeyConstraint('id'),
)
op.create_table('cloud_concern',
sa.Column('id', sa.Integer, nullable=False),
sa.Column('id_prospect', sa.Integer, nullable=False),
sa.Column('concern', sa.String(255), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.ForeignKeyConstraint(['id_prospect'], ['prospect.id']),
)
def downgrade():
op.drop_table('cloud_concern')
op.drop_table('prospect')
| {
"repo_name": "giubil/trackit",
"path": "api/files/api/migrations/versions/f83b7adaf523_add_the_prospect_table.py",
"copies": "1",
"size": "1410",
"license": "apache-2.0",
"hash": 7419736244529061000,
"line_mean": 31.7906976744,
"line_max": 68,
"alpha_frac": 0.6127659574,
"autogenerated": false,
"ratio": 3.357142857142857,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9449721288296031,
"avg_score": 0.00403750524936512,
"num_lines": 43
} |
"""Add the Suspendable class to classes that can be run/suspended/etc."""
from skytap.framework.ApiClient import ApiClient
from skytap.framework.Config import Config
import time
class Suspendable(object):
"""Add the change_state() functionality to the class.
This includes supporting functions, like run() and suspend().
"""
valid_states = ['running', 'suspended', 'reset', 'stopped', 'halted']
def suspend(self, wait=False):
"""Suspend the object (environment/vm)."""
self.change_state('suspended', wait)
def run(self, wait=False):
"""Run the object (environment/vm)."""
self.change_state('running', wait)
def halt(self, wait=False):
"""Halt the object (environment/vm)."""
self.change_state('halted', wait)
def reset(self, wait=False):
"""Reset the object (environment/vm)."""
self.change_state('reset', wait)
def stop(self, wait=False):
"""Stop the object (environment/vm)."""
self.change_state('stopped', wait)
def change_state(self, state, wait=False):
"""Change the state of the object (environment/vm)."""
if state not in Suspendable.valid_states:
raise ValueError(str(state) + ' not a valid state.')
self.refresh()
if self.runstate == state:
return True
if Config.add_note_on_state_change:
self.notes.add("Changing state via API to '" + state + "'")
api = ApiClient()
url = self.url + '.json'
data = {"runstate": state}
api.rest(url, {}, 'PUT', data)
if not wait:
return True
if state == 'reset':
state = 'running'
if state == 'halted':
state = 'stopped'
self.refresh()
counter = 0
while not self.runstate == state and counter < 12:
time.sleep(10)
self.refresh()
if self.runstate == state:
return True
return False
| {
"repo_name": "FulcrumIT/skytap",
"path": "skytap/framework/Suspendable.py",
"copies": "2",
"size": "2004",
"license": "mit",
"hash": -5692585542914066000,
"line_mean": 28.4705882353,
"line_max": 73,
"alpha_frac": 0.5778443114,
"autogenerated": false,
"ratio": 4.064908722109534,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5642753033509533,
"avg_score": null,
"num_lines": null
} |
"""add the sympc library into syft."""
# stdlib
import functools
from typing import Any as TypeAny
from typing import List as TypeList
from typing import Tuple as TypeTuple
# syft relative
from . import rst_share # noqa: 401
from . import session # noqa: 401
from . import share # noqa: 401
from ...ast import add_classes
from ...ast import add_methods
from ...ast import add_modules
from ...ast.globals import Globals
from ..util import generic_update_ast
LIB_NAME = "sympc"
PACKAGE_SUPPORT = {
"lib": LIB_NAME,
"torch": {"min_version": "1.6.0", "max_version": "1.8.1"},
"python": {"min_version": (3, 7), "max_version": (3, 9, 99)},
}
def create_ast(client: TypeAny = None) -> Globals:
"""Add the modules, classes and attributes from sympc to syft.
Args:
client: Client
Returns:
Globals
"""
# third party
import sympc
# syft relative
from . import rst_share # noqa: 401
from . import session # noqa: 401
from . import share # noqa: 401
ast = Globals(client=client)
modules: TypeList[TypeTuple[str, TypeAny]] = sympc.api.allowed_external_modules
add_modules(ast, modules)
classes: TypeList[TypeTuple[str, str, TypeAny]] = sympc.api.allowed_external_classes
add_classes(ast, classes)
attrs: TypeList[TypeTuple[str, str]] = sympc.api.allowed_external_attrs
add_methods(ast, attrs)
for klass in ast.classes:
klass.create_pointer_class()
klass.create_send_method()
klass.create_storable_object_attr_convenience_methods()
return ast
update_ast = functools.partial(generic_update_ast, LIB_NAME, create_ast)
| {
"repo_name": "OpenMined/PySyft",
"path": "packages/syft/src/syft/lib/sympc/__init__.py",
"copies": "1",
"size": "1652",
"license": "apache-2.0",
"hash": -6771090860509017000,
"line_mean": 24.8125,
"line_max": 88,
"alpha_frac": 0.6700968523,
"autogenerated": false,
"ratio": 3.3921971252566734,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.95604861090441,
"avg_score": 0.00036157370251471374,
"num_lines": 64
} |
'''Add the taxonomy id to the phage genomes.
NOTE: WE USE THE TAXONOMY OF THE HOST NOT THE TAXONOMY OF THE PHAGE!!
'''
import os
import sys
import re
sys.path.append('/home3/redwards/bioinformatics/phage_host')
sys.path.append('/home3/redwards/bioinformatics/Modules')
from phage import Phage
import taxon
manual = {'Acinetobacter genomosp.' : '471', 'Actinobacillus actinomycetemcomitans' : '714', 'alpha proteobacterium' : '34025', 'Bacillus clarkii' : '79879', 'Brevibacterium flavum' : '92706', 'Celeribacter sp.' : '875171', 'Escherichia sp.' : '237777', 'Geobacillus sp.' : '340407', 'Gordonia rubropertincta' : '36822', 'Iodobacter sp.' : '641420', 'Listeria sp.' : '592375', 'Marinomonas sp.' : '127794', 'Methanobacterium thermoautotrophicum' : '145262', 'methicillin-resistant Staphylococcus' : '1280', 'Nitrincola sp.' : '459834', 'Persicivirga sp.' : '859306', 'Salisaeta sp.' : '1392396', 'Sulfitobacter sp.' : '191468'}
phage = Phage()
host = phage.phageHost()
taxa = taxon.readNodes()
names,blastname,genbankname,synonym = taxon.extendedNames()
divs = taxon.readDivisions()
name2id = {names[x].name:x for x in names}
name2id.update({blastname[x].name:x for x in blastname})
name2id.update({genbankname[x].name:x for x in genbankname})
name2id.update({synonym[x].name:x for x in synonym})
for id in host:
if host[id] in manual:
i = manual[host[id]]
else:
host[id] = host[id].replace(';', '')
if host[id] not in name2id:
sys.stderr.write("'" + host[id] + "' : ' xxx '\n")
continue
i = name2id[host[id]]
print "\t".join([id, str(i)])
| {
"repo_name": "linsalrob/PhageHosts",
"path": "code/phage2taxonomy.py",
"copies": "1",
"size": "1625",
"license": "mit",
"hash": 9172165253883369000,
"line_mean": 39.625,
"line_max": 627,
"alpha_frac": 0.6713846154,
"autogenerated": false,
"ratio": 2.5958466453674123,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.37672312607674124,
"avg_score": null,
"num_lines": null
} |
'''Add the taxonomy id to the refseq list of complete genomes using gi2taxid'''
import os
import sys
import re
# start by reading the gi2taxid file
#
t={}
## add a couple that we don't have for some weird reason
t['284800255']='653938'
t['397678256']='1198627'
with open('/home/db/taxonomy/gi_taxid_nucl.dmp', 'r') as gif:
for line in gif:
line = line.strip()
gi, taxid = line.split("\t")
t[gi]=taxid
# now read the complete genomes file
with open('complete_genome_ids_taxid.txt', 'w') as out:
with open('complete_genome_ids.txt', 'r') as cgi:
for line in cgi:
line = line.strip()
p=line.split("\t")
m = re.findall('gi\|(\d+)\|', p[1])
if m == None:
sys.stderr.write("No gi found in " + p[1] + "\n")
continue
if m[0] in t:
out.write(line + "\t" + t[m[0]] + "\n")
else:
out.write(line + "\n")
sys.stderr.write("GI " + m[0] + " not found in /home/db/taxonomy/gi_taxid_nucl.dmp\n")
| {
"repo_name": "linsalrob/PhageHosts",
"path": "code/refseq2taxonomy.py",
"copies": "1",
"size": "1077",
"license": "mit",
"hash": 5054020640893986000,
"line_mean": 28.9166666667,
"line_max": 102,
"alpha_frac": 0.5357474466,
"autogenerated": false,
"ratio": 3.11271676300578,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.907635783541348,
"avg_score": 0.014421274838460044,
"num_lines": 36
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from graphics import canvas
from graphics.context import *
from nodebox.sound import PD
from math import sqrt
# SCREECHING AUDIO SNAILS!
pd = PD("04-audiosnails.pd", start=True)
class Snail:
def __init__(self, x, y):
""" An agent moving around, with a preference towards the corners of the canvas.
"""
self.x = x
self.y = y
self.r = 2
self.dx = random(-2, 2) # Snail speed.
self.dy = random(-2, 2)
self.vx = random(-0.2, 0.2) # Snail acceleration.
self.vy = random(-0.2, 0.2)
self.friction = random(0.4, 0.8) # Applied when changing position.
# Snail tail stores the previous point and draws a line to it
# (the rest of the "tail" is done using background in the main draw()).
self.tail = []
self.clr = random(.25,1.0)
def update(self):
if self.x < self.r:
self.dx = -self.dx * self.friction
self.x = self.r
if self.x > canvas.width - self.r:
self.dx = -self.dx * self.friction
self.x = canvas.width - self.r
if self.y > canvas.height - self.r:
self.dy = -self.dy * self.friction
self.y = canvas.height - self.r
if self.y < self.r:
self.dy = -self.dy * self.friction
self.y = self.r
self.dx = self.dx + self.vx / 5.0
self.dy = self.dy + self.vy / 5.0
self.x = self.x + self.dx
self.y = self.y +self.dy
self.tail.append((self.x, self.y))
if len(self.tail) > 2:
del(self.tail[0])
def draw(self):
stroke(self.clr, 0.5, 1.0-self.clr, 0.85)
fill(0.5*self.clr, 0.25, 1.0-self.clr, 0.4)
line(self.x, self.y, self.tail[0][0], self.tail[0][1])
ellipse(self.x, self.y, self.r*2, self.r*2)
class Attractor:
def __init__(self, x, y):
""" A moveable attraction field.
Snails passing through the attractor bend, accellerate and change audio pitch/LFO.
"""
self.x = x
self.y = y
self.dmin = 10
self.dmax = 250
self.mass = 5000
self.count = 0 # Number of snails inside the attractor, controls audio pitch.
self.weight = 0 # Based on attractor mass and snail distance, controls audio LFO.
def update(self, snails=[]):
self.value = 0
self.count = 0
for i, snail in enumerate(snails):
dx = self.x - snail.x
dy = self.y - snail.y
d = sqrt(dx*dx + dy*dy) # Snail-Attractor distance.
if d > self.dmin and d < self.dmax:
snail.vx += self.mass * dx / d**3 / 5.0
snail.vy += self.mass * dy / d**3 / 5.0
self.weight += self.mass * dx / d**3 / 0.01
self.count += 1
def draw(self):
fill(0, 0.025)
stroke(1, 0.025)
ellipse(self.x, self.y, 250, 250)
attractor = Attractor(200, 200)
snails = []
for i in range(50):
snails.append(Snail(
x = random(canvas.width),
y = random(canvas.height)))
def draw(canvas):
background(0.2, 0.1, 0.2, 0.1)
# Move the attractor around with the mouse:
attractor.x = canvas.mouse.x
attractor.y = canvas.mouse.y
attractor.update(snails)
attractor.draw()
# Draw the snails:
for snail in snails:
snail.update()
snail.draw()
# Send the attractor's "weight" and snail count to Pd.
# These control the audio's LFO and pitch respectively.
pd.send([attractor.weight, attractor.count], "/input", port=44001)
# Polling for output and drawing text slows everything down.
# I noticed that Pd no longer responds when too many pd.send() calls are issued too fast.
# Don't know why (yet).
fill(1)
text(pd.output or " ", 10, 10, fontsize=7, fill=(1,1,1,1))
def stop(canvas):
# Kill the Pd background process.
pd.stop()
canvas.fps = 30
canvas.size = 600, 400
canvas.run(draw, stop=stop) | {
"repo_name": "pepsipepsi/nodebox_opengl_python3",
"path": "examples/11_sound/04-audiosnails.py",
"copies": "1",
"size": "4221",
"license": "bsd-3-clause",
"hash": 7102225759970099000,
"line_mean": 33.325203252,
"line_max": 94,
"alpha_frac": 0.5548448235,
"autogenerated": false,
"ratio": 3.15,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.42048448235,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
from math import sin, cos
# The Peter De Jong attractor feeds its previous value back into the equation,
# creating a scatter of points that generates strange, attractive patterns.
# The function's return value is a Python iterator - an implicit list of (x,y)-values.
# All of the iterator's values can be retrieved one by one in a loop,
# or you can move to the next value with iterator.next().
def peter_de_jong_attractor(a, b, c, d, n=100000, scale=100):
x0, y0 = 0.0, 0.0
for i in range(n):
x1 = sin(a*y0) - cos(b*x0)
y1 = sin(c*x0) - cos(d*y0)
x0 = x1
y0 = y1
yield (x1*scale, y1*scale)
# Classic example from http://local.wasp.uwa.edu.au/~pbourke/fractals/peterdejong/
# Play around with the numbers to produce different patterns.
a = peter_de_jong_attractor(1.4, -2.3, 2.4, -2.1, n=5000000, scale=150)
def draw(canvas):
# The trick is not to clear the canvas each frame.
# Instead, we only draw a background in the first frame,
# and then gradually build up the composition with the next points each frame.
if canvas.frame == 1:
background(1)
# Translate the canvas origin point to the center.
# The attractor can yield negative (x,y)-values,
# so if we leave the origin point in the bottom left,
# part of the pattern will fall outside the drawing area.
translate(canvas.width/2, canvas.height/2)
# Note how the fill color has a very low alpha (i.e. high transparency).
# This makes the pattern more fine-grained,
# as many transparent points will need to overlap to form a thicker line.
fill(0, 0.1)
try:
for i in range(1000):
# Get the next x and y coordinates in the attractor.
# Draw a pixel at the current x and y coordinates.
x, y = a.next()
rect(x, y, 1, 1)
except StopIteration:
pass
canvas.size = 700, 700
canvas.run(draw) | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/06-math/01-attractor.py",
"copies": "1",
"size": "2121",
"license": "bsd-3-clause",
"hash": 6678192985678305000,
"line_mean": 38.2962962963,
"line_max": 86,
"alpha_frac": 0.6553512494,
"autogenerated": false,
"ratio": 3.356012658227848,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.941875666234973,
"avg_score": 0.01852144905562368,
"num_lines": 54
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
from nodebox.graphics.geometry import coordinates
from nodebox.gui import Slider
# The nodebox.gui module provides simple visual controls, such as Slider, Button, CheckBox and Field.
# Each control inherits from a Control class, which in turn inherits from Layer.
# This means that to display a control, we append it to the canvas just like a layer,
# and we set its x and y properties to define its location on the canvas.
slider1 = Slider(default=45.0, min=10.0, max=90.0, steps=9)
slider1.x = 180
slider1.y = 120
slider2 = Slider(default=3.0, min=2.0, max=10.0, steps=100)
slider2.x = 180
slider2.y = 100
canvas.append(slider1)
canvas.append(slider2)
# Now we need something to play with.
# We'll use the two sliders to control the motion of a few "snakes".
# Each snake is essentially a list of positions,
# which we draw as ellipse segments connected by lines.
class Snake:
def __init__(self, x, y):
self.x = x # Current horizontal position.
self.y = y # Current vertical position.
self.radius = 2 # Current segment size.
self.angle = random(360) # Current heading.
self.step = 1 # Next segment, add or subtract step from heading.
self.trail = [] # List of previous (x, y, radius)-tuples.
def update(self):
# Calculate new position from the current heading and segment size.
# The coordinates() function takes a point, a distance and an angle,
# and returns the point at the given angle and distance from the given point.
x, y = coordinates(self.x, self.y, self.radius*3, self.angle)
self.angle += choice((-self.step, self.step))
# Confine the snake to the visible area.
self.x = max(0, min(x, 500))
self.y = max(0, min(y, 500))
# Add the new segment.
# Snake can have 200 segments maximum.
self.trail.insert(0, (x, y, self.radius))
self.trail = self.trail[:200]
def draw(self):
for i, (x, y, r) in enumerate(self.trail):
if i > 0:
line(x, y, self.trail[i-1][0], self.trail[i-1][1])
ellipse(x, y, r*2, r*2)
snakes = [Snake(250, 250) for i in range(5)]
def draw(canvas):
canvas.clear()
v1 = slider1.value # Value from first slider controls snakes' heading.
v2 = slider2.value # Value from second slider controls snakes' segment size.
fill(0.1, 0.1, 0, 0.25)
stroke(0.1, 0.1, 0, 0.5)
for snake in snakes:
snake.step = v1
snake.radius = v2
snake.update()
snake.draw()
canvas.size = 500, 500
canvas.run(draw) | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/10-gui/01-slider.py",
"copies": "1",
"size": "2841",
"license": "bsd-3-clause",
"hash": -7903801810137005000,
"line_mean": 35.9090909091,
"line_max": 101,
"alpha_frac": 0.6290038719,
"autogenerated": false,
"ratio": 3.4023952095808383,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.45313990814808386,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
from nodebox.graphics.geometry import distance, angle, smoothstep
# Circle-packing algorithm.
# This script was used to produce one of the panels in NANOPHYSICAL:
# http://nodebox.net/code/index.php/Nanophysical
class Circle:
def __init__(self, x, y, radius, image=None):
""" An object that can be passed to pack(),
with a repulsion radius and an image to draw inside the radius.
"""
self.x = x
self.y = y
self.radius = radius
self.image = image
self.goal = Point(x,y)
def contains(self, x, y):
return distance(self.x, self.y, x, y) <= self.radius
def draw(self):
a = angle(self.x, self.y, self.goal.x, self.goal.y)
r = self.radius * 1.25 # Let the cells overlap a little bit.
push()
translate(self.x, self.y)
scale(r*2 / min(self.image.width, self.image.height))
rotate(a)
image(self.image, x=-r, y=-r) # Rotate from image center.
pop()
def pack(circles, x, y, padding=2, exclude=[]):
""" Circle-packing algorithm.
Groups the given list of Circle objects around (x,y) in an organic way.
"""
# Ported from Sean McCullough's Processing code:
# http://www.cricketschirping.com/processing/CirclePacking1/
# See also: http://en.wiki.mcneel.com/default.aspx/McNeel/2DCirclePacking
# Repulsive force: move away from intersecting circles.
for i, circle1 in enumerate(circles):
for circle2 in circles[i+1:]:
d = distance(circle1.x, circle1.y, circle2.x, circle2.y)
r = circle1.radius + circle2.radius + padding
if d < r - 0.01:
dx = circle2.x - circle1.x
dy = circle2.y - circle1.y
vx = (dx / d) * (r-d) * 0.5
vy = (dy / d) * (r-d) * 0.5
if circle1 not in exclude:
circle1.x -= vx
circle1.y -= vy
if circle2 not in exclude:
circle2.x += vx
circle2.y += vy
# Attractive force: move all circles to center.
for circle in circles:
circle.goal.x = x
circle.goal.y = y
if circle not in exclude:
damping = circle.radius ** 3 * 0.000001 # Big ones in the middle.
vx = (circle.x - x) * damping
vy = (circle.y - y) * damping
circle.x -= vx
circle.y -= vy
def cell(t):
# Returns a random PNG-image from cells/
# Some cells occur more frequently than others:
# t is a number between 0.0 and 1.0 that determines which image to pick.
# This is handy when combined with smoothstep(),
# then we can put a preference on empty blue cells,
# while still ensuring that some of each cell appear.
if t < 0.4:
img = choice([
"green-empty1.png",
"green-empty2.png",
"green-empty3.png"] + [
"green-block1.png",
"green-block2.png"] * 2)
elif t < 0.5:
img = choice([
"green-circle1.png",
"green-circle2.png"])
elif t < 0.6:
img = choice([
"green-star1.png",
"green-star2.png"])
else:
img = choice([
"blue-block.png",
"blue-circle.png",
"blue-star.png"] + [
"blue-empty1.png",
"blue-empty2.png"] * 5)
return Image(os.path.join("cells", img))
circles = []
def setup(canvas):
n = 60
global circles; circles = []
for i in range(n):
# Create a group of n cells.
# Smoothstep yields more numbers near 1.0 than near 0.0,
# so we'll got mostly empty blue cells.
t = smoothstep(0, n, i)
circles.append(
Circle(x = random(-100), # Start offscreen to the left.
y = random(canvas.height),
radius = 10 + 0.5 * t*i, # Make the blue cells bigger.
image = cell(t)))
dragged = None
def draw(canvas):
background(1)
# Cells can be dragged:
global dragged
if dragged:
dragged.x = canvas.mouse.x
dragged.y = canvas.mouse.y
if not canvas.mouse.pressed:
dragged = None
elif not dragged:
for circle in circles:
if circle.contains(canvas.mouse.x, canvas.mouse.y):
dragged = circle; break
for circle in circles:
circle.draw()
pack(circles, 300, 300, exclude=[dragged])
canvas.size = 600, 600
canvas.run(draw, setup) | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/08-physics/06-pack.py",
"copies": "1",
"size": "4759",
"license": "bsd-3-clause",
"hash": 1219613552611126800,
"line_mean": 32.7588652482,
"line_max": 79,
"alpha_frac": 0.5492750578,
"autogenerated": false,
"ratio": 3.538289962825279,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.94533615176885,
"avg_score": 0.02684070058735575,
"num_lines": 141
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
from nodebox.graphics.geometry import distance
from math import sqrt
def spider(string, x=0, y=0, radius=25, **kwargs):
""" A path filter that creates web threading along the characters of the given string.
Its output can be drawn directly to the canvas or used in a render() function.
Adapted from: http://nodebox.net/code/index.php/Path_Filters
"""
# **kwargs represents any additional optional parameters.
# For example: spider("hello", 100, 100, font="Helvetica") =>
# kwargs = {"font": "Helvetica"}
# We pass these on to the textpath() call in the function;
# so the spider() function takes the same parameters as textpath:
# x, y, font, fontsize, fontweight, ...
font(
kwargs.get("font", "Droid Sans"),
kwargs.get("fontsize", 100))
p = textpath(string, x, y, **kwargs)
n = int(p.length)
m = 2.0
radius = max(radius, 0.1 * fontsize())
points = list(p.points(n))
for i in range(n):
pt1 = choice(points)
pt2 = choice(points)
while distance(pt1.x, pt1.y, pt2.x, pt2.y) > radius:
pt2 = choice(points)
line(pt1.x + random(-m, m),
pt1.y + random(-m, m),
pt2.x + random(-m, m),
pt2.y + random(-m, m))
# Render the function's output to an image.
# Rendering the image beforehand is much faster than calling spider() every frame.
stroke(0.1, 0.1, 0, 0.5)
strokewidth(1)
img = render(spider, 500, 150,
string = "SPIDER",
font = "Droid Sans",
fontsize = 100,
bold = True,
x = 25,
y = 25,
radius = 30)
def draw(canvas):
canvas.clear()
translate(0, 200)
image(img)
canvas.size = 500, 500
canvas.run(draw) | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/05-path/05-spider.py",
"copies": "1",
"size": "1914",
"license": "bsd-3-clause",
"hash": 2210128838138338000,
"line_mean": 33.1964285714,
"line_max": 90,
"alpha_frac": 0.605015674,
"autogenerated": false,
"ratio": 3.357894736842105,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4462910410842105,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
from nodebox.graphics.physics import Node, Edge, Graph
# Create a graph with randomly connected nodes.
# Nodes and edges can be styled with fill, stroke, strokewidth parameters.
# Each node displays its id as a text label, stored as a Text object in Node.text.
# To hide the node label, set the text parameter to None.
g = Graph()
# Random nodes.
for i in range(50):
g.add_node(id=str(i+1),
radius = 5,
stroke = color(0),
text = color(0))
# Random edges.
for i in range(75):
node1 = choice(g.nodes)
node2 = choice(g.nodes)
g.add_edge(node1, node2,
length = 1.0,
weight = random(),
stroke = color(0))
# Two handy tricks to prettify the layout:
# 1) Nodes with a higher weight (i.e. incoming traffic) appear bigger.
for node in g.nodes:
node.radius = node.radius + node.radius*node.weight
# 2) Nodes with only one connection ("leaf" nodes) have a shorter connection.
for node in g.nodes:
if len(node.edges) == 1:
node.edges[0].length *= 0.1
g.prune(depth=0) # Remove orphaned nodes with no connections.
g.distance = 10 # Overall spacing between nodes.
g.layout.force = 0.01 # Strength of the attractive & repulsive force.
g.layout.repulsion = 15 # Repulsion radius.
dragged = None
def draw(canvas):
canvas.clear()
background(1)
translate(250, 250)
# With directed=True, edges have an arrowhead indicating the direction of the connection.
# With weighted=True, Node.centrality is indicated by a shadow under high-traffic nodes.
# With weighted=0.0-1.0, indicates nodes whose centrality > the given threshold.
# This requires some extra calculations.
g.draw(weighted=0.5, directed=True)
g.update(iterations=10)
# Make it interactive!
# When the mouse is pressed, remember on which node.
# Drag this node around when the mouse is moved.
dx = canvas.mouse.x - 250 # Undo translate().
dy = canvas.mouse.y - 250
global dragged
if canvas.mouse.pressed and not dragged:
dragged = g.node_at(dx, dy)
if not canvas.mouse.pressed:
dragged = None
if dragged:
dragged.x = dx
dragged.y = dy
canvas.size = 500, 500
canvas.run(draw)
| {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/08-physics/07-graph.py",
"copies": "1",
"size": "2426",
"license": "bsd-3-clause",
"hash": -5312598994929545000,
"line_mean": 33.6571428571,
"line_max": 93,
"alpha_frac": 0.6619950536,
"autogenerated": false,
"ratio": 3.485632183908046,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46476272375080463,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
from nodebox.gui import *
# A panel is a container for other GUI controls.
# Controls can be added to the panel,
# and organized by setting the controls' x and y properties
# (since all controls inherit from Layer, they all have the same properties as a layer).
panel = Panel("Example", width=200, height=200, fixed=False, modal=False)
# Alternatively, a layout manager can be added to a panel.
# A layout manager is itself a group of controls.
# By calling Layout.apply(), the manager will take care of arranging its controls.
# A simple layout manager is "Rows" layout, in which each control is drawn on a new row.
# A caption can be defined for each control in the Rows layout,
# it will be placed to the left of each control.
layout = Rows()
layout.extend([
Field(value="hello world", hint="text", id="text"),
("size", Slider(default=1.0, min=0.0, max=2.0, steps=100, id="size")),
("alpha", Slider(default=1.0, min=0.0, max=1.0, steps=100, id="alpha")),
("show?", Flag(default=True, id="show"))
])
# The panel will automatically call Layout.apply() when the layout is added.
panel.append(layout)
# With Panel.pack(), the size of the panel is condensed as much as possible.
panel.pack()
# Panel inherits from Layer,
# so we append it to the canvas just as we do with a layer:
canvas.append(panel)
def draw(canvas):
canvas.clear()
# In this simple example,
# we link the values from the controls in the panel to a displayed text.
# Controls with an id are available as properties of the panel
# (e.g. a control with id "slider" can be retrieved as Panel.slider).
# Most controls have a Control.value property that retrieves the current value:
if panel.show.value == True:
font("Droid Serif")
fontsize(50 * panel.size.value)
fill(0, panel.alpha.value)
text(panel.text.value, 50, 250)
canvas.size = 500, 500
canvas.run(draw)
# Note:
# We named one of the sliders "alpha" instead of "opacity",
# which would be a more comprehensible id, but which is already taken
# because there is a Panel.opacity property (inherited from Layer).
# In reality, it is much better to choose less ambiguous id's,
# such as "field1_text" or "slider2_opacity".
| {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/10-gui/02-panel.py",
"copies": "1",
"size": "2400",
"license": "bsd-3-clause",
"hash": -3164780760776602600,
"line_mean": 39,
"line_max": 88,
"alpha_frac": 0.7045833333,
"autogenerated": false,
"ratio": 3.513909224011713,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4718492557311713,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
from nodebox.gui import *
# Comparison between Rows and Row containers.
# Both are subclasses of Layout.
# Panel 1
# Controls in a Rows layout are drawn below each other.
# Rows.width defines the width of all controls (individual width is ignored).
# Note how the second Field has a height and wrap=True,
# which makes it a multi-line field with text wrapping.
panel1 = Panel("Panel 1", x=30, y=350)
panel1.append(
Rows([
Field(value="", hint="subject"),
Field(value="", hint="message", height=70, id="field_msg1", wrap=True),
Button("Send"),
], width=200)
)
panel1.pack()
# Panel 2
# Controls in a Row layout are drawn next to each other.
# Row.width defines the width of all controls (individual width is ignored).
# This means that each column has the same width.
# Note the align=TOP, which vertically aligns each column at the top (default is CENTER).
panel2 = Panel("Panel 2", x=30, y=200)
panel2.append(
Row([
Field(value="", hint="message", height=70, id="field_msg2", wrap=True),
Button("Send", width=400),
], width=200, align=TOP)
)
panel2.pack()
# Panel 3
# If you need columns of a different width, put a Layout in a column,
# in other words a Row or Rows nested inside a Row or Rows.
# Then put your controls in the nested layout,
# the layout's width will override the column width setting.
panel3 = Panel("Panel 3", x=30, y=30)
panel3.append(
Row([ # Field will be 200 wide, the Row column width setting.
Field(value="", hint="message", height=70, id="field_msg3", wrap=True),
("Actions:", Rows([
Button("Send"), # However, buttons will be 100 wide,
Button("Save") # because their Rows parent says so.
], width=100))
], width=200, align=TOP)
)
panel3.pack()
# Panel 4
# Without layouts, you are free to draw controls wherever you want in a panel.
# Panel.pack() will make sure that the panel fits snuggly around the controls.
# In this case, we place a button on the panel, with a field above it (hence y=40).
# The field has its own dimensions (width=300 and height=50).
panel4 = Panel("Panel 4", x=400, y=30)
panel4.extend([
Field(value="", hint="message", y=40, width=300, height=50, id="field_msg4", wrap=True, reserved=[]),
Button("Send")
])
panel4.pack()
# Note the reserved=[] with the field.
# By default, fields have ENTER and TAB keys reserved:
# enter fires Field.on_action(), tab moves away from the field.
# By clearing the reserved list we can type enter and tab inside the field.
# Panel 5
# If you don't pack the panel, you have to set its width and height manually,
# as well as the position of all controls:
panel5 = Panel("Panel 5", x=500, y=200, width=200, height=150)
panel5.extend([
Field(value="", hint="message", x=10, y=60, width=180, height=50, id="field_msg5", wrap=True),
Button("Send", x=10, y=20, width=180)
])
def draw(canvas):
canvas.clear()
canvas.append(panel1)
canvas.append(panel2)
canvas.append(panel3)
canvas.append(panel4)
canvas.append(panel5)
canvas.size = 800, 600
canvas.run(draw) | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/10-gui/05-layout.py",
"copies": "1",
"size": "3250",
"license": "bsd-3-clause",
"hash": 4331188869238414300,
"line_mean": 34.7252747253,
"line_max": 105,
"alpha_frac": 0.684,
"autogenerated": false,
"ratio": 3.306205493387589,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.947234976427167,
"avg_score": 0.003571145823183756,
"num_lines": 91
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
from nodebox.gui import *
# This example demonstrates the knob GUI control,
# and how different layout managers can be nested.
# Knobs look nice when placed next to each other.
# The "Row" layout can be used to achieve this.
# It arranges all of its controls horizontally, with their captions on top.
# The Row layout can then be nested in a Rows layout (or vice versa).
# This allows you to build many different interface grids.
panel = Panel("Example", width=300, height=200, fixed=False, modal=False)
panel.append(Rows(
[("text",Field(value="hello world", hint="text", id="field_text")),
( "size", Slider(default=1.0, min=0.0, max=2.0, steps=100, id="slider_size")),
( "opacity", Slider(default=1.0, min=0.0, max=1.0, steps=100, id="slider_opacity")),
( "color", Row([("R", Knob(id="knob_r")),
("G", Knob(id="knob_g")),
("B", Knob(id="knob_b"))
]))]))
panel.pack()
canvas.append(panel)
def draw(canvas):
canvas.clear()
font("Droid Serif")
fontsize(50 * panel.slider_size.value)
fill(panel.knob_r.relative, # Knob.value is between 0-360.
panel.knob_g.relative, # Knob.relative between 0.0-1.0.
panel.knob_b.relative,
panel.slider_opacity.value)
text(panel.field_text.value, 20, 200)
canvas.size = 500, 500
canvas.run(draw) | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/10-gui/04-knob.py",
"copies": "1",
"size": "1541",
"license": "bsd-3-clause",
"hash": -4121507587520003600,
"line_mean": 38.5384615385,
"line_max": 89,
"alpha_frac": 0.6391953277,
"autogenerated": false,
"ratio": 3.113131313131313,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4252326640831313,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
from nodebox.sound import PD, LOCALHOST, IN, OUT
# This script demonstrates how to simultaneously receive from and send to Pd.
# We need two communication ports. By default, NodeBox receives on port 44000 (IN),
# so Pd should send from port 44000. NodeBox sends on port 44001 (OUT),
# so Pd should receive om port 44001.
# With start=False, the patch will not be loaded automatically in the background.
# This means that you must open Pd manually and load the patch.
# This is necessary, because we'll use the Pd GUI to control the NodeBox animation.
pd = PD("02-in-out.pd", start=False)
def draw(canvas):
canvas.clear()
# As you can see in the Pd patch, it broadcasts three values,
# which we use to control the size, color and rotation of a rectangle.
# You may have to drag the numbers up or down in Pd in order for the rectangle to appear.
data = pd.get("/output", host=LOCALHOST, port=IN)
if data:
size, color, angle = data
translate(250, 250)
rotate(angle)
fill(0, color/255.0, 0)
rect(-size/2, -size/2, size, size)
# As a test, send the mouse position to Pd.
# If you click the NodeBox application window and move the mouse around,
# you'll see the (x,y) position printed in the main Pd window.
pd.send((canvas.mouse.x, canvas.mouse.y), "/input", host=LOCALHOST, port=OUT)
# We can send data to Pd to generate sound interactively.
# We can receive data from Pd to create an animation that responds to sound.
def stop(canvas):
pd.stop()
canvas.size = 500, 500
canvas.run(draw, stop=stop)
| {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/11-sound/02-in-out.py",
"copies": "1",
"size": "1757",
"license": "bsd-3-clause",
"hash": -6618606633107007000,
"line_mean": 40.8333333333,
"line_max": 93,
"alpha_frac": 0.6994877632,
"autogenerated": false,
"ratio": 3.479207920792079,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4678695683992079,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
from nodebox.sound import PD
from math import sin, pow
# An evolutionary melody.
# The audio tones are generated in Pd, based on data sent from the canvas.
# If you open the patch manually in Pd, set start=False.
pd = PD("03-sequencer.pd", start=True)
# Selection of piano keys to play (e.g. only black keys):
PIANO = [34, 36, 38, 41, 43, 46, 48, 50]
class Note:
def __init__(self, x, y):
""" One of eight piano keys played in a sequencer.
It regenerates after a certain amount of time to obtain variations in the melody.
"""
self.key = choice(PIANO)
self.x = x
self.y = y
self.dy = 0 # Vertical offset, changes according to time.
self.dt = random() # Time step, higher = note is repeated faster.
self.time = 0 # Increases with dt each update.
self.life = 0 # Higher than 10 = reset note.
self.play = random(10, 50) # Note is played when this far or less from the center.
@property
def played(self):
return self.dy < self.play
@property
def tone(self):
if self.played:
return pow(2, (self.key-49)/12.0) * 440
return 0
def draw(self):
fill(0,1,0) if self.played else fill(1)
nostroke()
rect(self.x, self.y + self.dy, 40, 40)
rect(self.x, self.y - self.dy, 40, 40)
def update(self):
self.time += self.dt
self.dy += float(self.key * sin(self.time/3.0)) / 5.0
if self.dy < 0:
self.life += 1
if self.life > 10:
self.__init__(self.x, self.y)
class Signal(list):
def update(self, dy=0):
self.append(dy)
if len(self) > 100:
del(self[0])
def draw(self):
""" Draws the signal wave.
Note that only the first index gets send from Pd.
To achieve a more streamlined wave you would have to send the whole array.
"""
push()
translate(0, canvas.height/2)
stroke(0,1,0)
dx = float(canvas.width) / 100
for i, dy in enumerate(self):
dy0 = self[i-1]
line(i*dx, dy, (i-1)*dx, dy0)
pop()
melody = [Note(120+i*50, canvas.height/2) for i in range(8)]
signal = Signal()
def draw(canvas):
background(0)
data = pd.get("/metro")
if data:
signal.update(100.0 * data[0])
signal.draw()
for note in melody:
note.update()
note.draw()
pd.send([note.tone for note in melody], "/input")
def stop(canvas):
pd.stop()
canvas.size = 600, 450
canvas.fps = 30
canvas.run(draw, stop=stop)
| {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/11-sound/03-sequencer.py",
"copies": "1",
"size": "2925",
"license": "bsd-3-clause",
"hash": -719127453835114200,
"line_mean": 29.46875,
"line_max": 93,
"alpha_frac": 0.5483760684,
"autogenerated": false,
"ratio": 3.3466819221967965,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4395057990596796,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
from nodebox.sound import PD
from math import sqrt
# SCREECHING AUDIO SNAILS!
pd = PD("04-audiosnails.pd", start=True)
class Snail:
def __init__(self, x, y):
""" An agent moving around, with a preference towards the corners of the canvas.
"""
self.x = x
self.y = y
self.r = 2
self.dx = random(-2, 2) # Snail speed.
self.dy = random(-2, 2)
self.vx = random(-0.2, 0.2) # Snail acceleration.
self.vy = random(-0.2, 0.2)
self.friction = random(0.4, 0.8) # Applied when changing position.
# Snail tail stores the previous point and draws a line to it
# (the rest of the "tail" is done using background in the main draw()).
self.tail = []
self.clr = random(.25,1.0)
def update(self):
if self.x < self.r:
self.dx = -self.dx * self.friction
self.x = self.r
if self.x > canvas.width - self.r:
self.dx = -self.dx * self.friction
self.x = canvas.width - self.r
if self.y > canvas.height - self.r:
self.dy = -self.dy * self.friction
self.y = canvas.height - self.r
if self.y < self.r:
self.dy = -self.dy * self.friction
self.y = self.r
self.dx = self.dx + self.vx / 5.0
self.dy = self.dy + self.vy / 5.0
self.x = self.x + self.dx
self.y = self.y +self.dy
self.tail.append((self.x, self.y))
if len(self.tail) > 2:
del(self.tail[0])
def draw(self):
stroke(self.clr, 0.5, 1.0-self.clr, 0.85)
fill(0.5*self.clr, 0.25, 1.0-self.clr, 0.4)
line(self.x, self.y, self.tail[0][0], self.tail[0][1])
ellipse(self.x, self.y, self.r*2, self.r*2)
class Attractor:
def __init__(self, x, y):
""" A moveable attraction field.
Snails passing through the attractor bend, accellerate and change audio pitch/LFO.
"""
self.x = x
self.y = y
self.dmin = 10
self.dmax = 250
self.mass = 5000
self.count = 0 # Number of snails inside the attractor, controls audio pitch.
self.weight = 0 # Based on attractor mass and snail distance, controls audio LFO.
def update(self, snails=[]):
self.value = 0
self.count = 0
for i, snail in enumerate(snails):
dx = self.x - snail.x
dy = self.y - snail.y
d = sqrt(dx*dx + dy*dy) # Snail-Attractor distance.
if d > self.dmin and d < self.dmax:
snail.vx += self.mass * dx / d**3 / 5.0
snail.vy += self.mass * dy / d**3 / 5.0
self.weight += self.mass * dx / d**3 / 0.01
self.count += 1
def draw(self):
fill(0, 0.025)
stroke(1, 0.025)
ellipse(self.x, self.y, 250, 250)
attractor = Attractor(200, 200)
snails = []
for i in range(50):
snails.append(Snail(
x = random(canvas.width),
y = random(canvas.height)))
def draw(canvas):
background(0.2, 0.1, 0.2, 0.1)
# Move the attractor around with the mouse:
attractor.x = canvas.mouse.x
attractor.y = canvas.mouse.y
attractor.update(snails)
attractor.draw()
# Draw the snails:
for snail in snails:
snail.update()
snail.draw()
# Send the attractor's "weight" and snail count to Pd.
# These control the audio's LFO and pitch respectively.
pd.send([attractor.weight, attractor.count], "/input", port=44001)
# Polling for output and drawing text slows everything down.
# I noticed that Pd no longer responds when too many pd.send() calls are issued too fast.
# Don't know why (yet).
fill(1)
text(pd.output or " ", 10, 10, fontsize=7, fill=(1,1,1,1))
def stop(canvas):
# Kill the Pd background process.
pd.stop()
canvas.fps = 30
canvas.size = 600, 400
canvas.run(draw, stop=stop) | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/11-sound/04-audiosnails.py",
"copies": "1",
"size": "4192",
"license": "bsd-3-clause",
"hash": -2296029725655640600,
"line_mean": 33.652892562,
"line_max": 94,
"alpha_frac": 0.5529580153,
"autogenerated": false,
"ratio": 3.1400749063670412,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.41930329216670414,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys;sys.path.insert(0,os.path.join("..",".."))
from nodebox.graphics import *
# A classic NodeBox example (http://nodebox.net/code/index.php/Dendrite).
# It registers the dragged mouse movements,
# and use those to draw wavering lines.
# Thanks to Karsten Wolf.
from random import seed
from math import sin
lines = []
def draw(canvas):
background(0.1, 0.0, 0.1, 0.25)
nofill()
stroke(1, 1, 1, 0.2)
strokewidth(0.5)
# Register mouse movement.
if canvas.mouse.dragged:
lines.append((LINETO, canvas.mouse.x, canvas.mouse.y, canvas.frame))
elif canvas.mouse.pressed:
lines.append((MOVETO, canvas.mouse.x, canvas.mouse.y, canvas.frame))
if len(lines) > 0:
for i in range(5):
seed(i) # Lock the seed for smooth animation.
p = BezierPath()
for cmd, x, y, t in lines:
d = sin((canvas.frame - t) / 10.0) * 10.0 # Play with the numbers.
x += random(-d, d)
y += random(-d, d)
if cmd == MOVETO:
p.moveto(x, y)
else:
p.lineto(x, y)
drawpath(p)
canvas.fps = 60
canvas.size = 600, 400
#canvas.fullscreen = True
canvas.run(draw)
| {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/05-path/08-drag.py",
"copies": "1",
"size": "1342",
"license": "bsd-3-clause",
"hash": -35289786868177628,
"line_mean": 28.8222222222,
"line_max": 82,
"alpha_frac": 0.5760059613,
"autogenerated": false,
"ratio": 3.233734939759036,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4309740901059036,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
# Blend modes are used to combine the pixels of two images,
# in different ways than standard transparency.
# NodeBox supports the most common blend modes as filters:
# add(), subtract(), darken(), lighten(), multiply(), screen(), overlay(), hue().
# These can be used to adjust the lighting in an image
# (by blending it with a copy of itself),
# or to obtain many creative texturing effects.
img1 = Image("creature.png")
img2 = Image("creature.png")
def draw(canvas):
canvas.clear()
# Press the mouse to compare the blend to normal ("source over") mode:
if not canvas.mouse.pressed:
image(
# Try changing this to another blend filter:
multiply(img1, img2,
# All blend modes (and mask()) have optional dx and dy parameters
# that define the offset of the blend layer.
dx = canvas.mouse.x - img1.width/2,
dy = canvas.mouse.y - img1.height/2))
else:
image(img1)
image(img2,
x = canvas.mouse.x - img1.width/2,
y = canvas.mouse.y - img1.height/2)
# Start the application:
canvas.fps = 30
canvas.size = 500, 500
canvas.run(draw) | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/07-filter/07-blend.py",
"copies": "1",
"size": "1356",
"license": "bsd-3-clause",
"hash": -3006431536299593000,
"line_mean": 33.7948717949,
"line_max": 81,
"alpha_frac": 0.6356932153,
"autogenerated": false,
"ratio": 3.625668449197861,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47613616644978607,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
# Create a pixels array from a solid white image:
p = Pixels(solid(200, 200, Color(1)))
# Colorize pixels with the Perlin noise() generator.
# Noise is smoother than random(), comparable to a random gradient.
# This is often used to generate terrain surface maps.
# The noise() command returns a smooth value between -1.0 and 1.0.
# The x, y, z parameters determine the coordinates in the noise landscape.
# Since the landscape is infinite, the actual value of a coordinate doesn't matter,
# only the distance between successive steps.
# The smaller the difference between steps, the smoother the noise sequence.
# Steps between 0.005 and 0.1 usually work best.
zoom = 4
for i in range(p.width):
for j in range(p.height):
t = noise(
zoom * float(i) / p.width,
zoom * float(j) / p.height
)
t = 0.5 + 0.5 * t # Map values from -1.0-1.0 to 0.0-1.0.
t = int(255*t) # Map values to 0-255.
p[i+j*p.width] = (t,t,t,255)
p.update()
def draw(canvas):
image(p, 150, 150)
canvas.size = 500, 500
canvas.run(draw) | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/03-image/06-noise.py",
"copies": "1",
"size": "1265",
"license": "bsd-3-clause",
"hash": -2205823928708194000,
"line_mean": 34.1666666667,
"line_max": 84,
"alpha_frac": 0.6561264822,
"autogenerated": false,
"ratio": 3.2025316455696204,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.43586581277696207,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
def draw(canvas):
canvas.clear()
# The origin point of the canvas is in the bottom-left corner.
# That means if you draw a shape or image at x=0 and y=0,
# it appears in the bottom-left corner.
# The origin point can be moved around with the translate() command.
# For example, here it is placed in the center of the canvas:
translate(250, 250)
# Like colors, NodeBox keeps a current transform "state".
# All subsequent drawing commands will originate from the center.
stroke(0, 0.2)
strokewidth(1)
n = 350
for i in range(n):
t = float(i) / n # A counter between 0.0 and 1.0.
fill(0.25-t, 0.15+t, 0.75, 0.15)
# The transform state logs the current scale.
# Thus, the first time when we call scale(0.99), the current scale is 99%.
# The second time the current scale becomes 99% of 99 = 98%, and so on.
# That is why each subsequent ellipse is a bit smaller than the previous one.
scale(0.99)
# In the same way, rotate() calls are cumulative.
# The first rotate(5) sets the current angle to 5, the second 10, 15, 20, ...
# That is why each subsequent ellipse appears at a different angle.
rotate(5)
# However, instead of drawing a lot of ellipses on top of each other,
# each rotated at a different angle, each ellipse is instead rotating
# around the origin point (which we placed in the center).
# This is because we draw each ellipse at x=200, so 200 pixels to the right
# of the origin, only "to the right" is relative to the current rotation.
# In the same way, "200 pixels" is relative to the current scale,
# so the ellipses spiral to the center.
ellipse(x=200, y=0, width=120, height=60)
# The order in which transformations occur is important:
# translating first and scaling / rotating afterwards
# has a different effect than scaling / rotating first.
canvas.size = 500, 500
canvas.run(draw) | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/02-transform/01-spiral.py",
"copies": "1",
"size": "2132",
"license": "bsd-3-clause",
"hash": -936883485981374300,
"line_mean": 39.2452830189,
"line_max": 82,
"alpha_frac": 0.6791744841,
"autogenerated": false,
"ratio": 3.5952782462057336,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4774452730305734,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
# Here is the "Hypnoval", a classic example in NodeBox for Mac OS X.
# It uses the canvas.frame counter to create variation in each frame.
# Math functions sin() and cos() are used to create fluid motion.
# Sine and cosine describe smooth repetitive oscillation between -1 and 1:
# sin(0)=0, sin(pi/2)=1, sin(-pi/2)=-1
# cos(0)=1, cos(pi/2)=0, cos(pi)=-1
# Values near 0 occur more frequently than those near 1 (i.e. "faster" near 1).
def draw(canvas):
canvas.clear()
# A counter based on the current frame:
i = canvas.frame * 0.1
# We also use an internal counter that modifies individual ellipses.
step = 0.0
# The grid() function yields (x,y)-coordinates in a grid.
# In this case the grid is 10 by 10 with 45 pixels spacing.
for x, y in grid(10, 10, 45, 45):
x += 50 # Displace a little bit from the left edge.
y += 50 # Displace a little bit from the bottom edge.
# Draw the ellipse:
fill(0.15, 0.25 - 0.2*sin(i+step), 0.75, 0.5)
ellipse(
x + sin(i+step) * 10.0, # Play around with the numbers!
y + cos(i+step) * 20.0, width=50, height=50)
# Increase the step so that each ellipse looks different.
step += 0.05
canvas.size = 500, 500
canvas.run(draw) | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/01-basics/03-frame.py",
"copies": "1",
"size": "1477",
"license": "bsd-3-clause",
"hash": -8309321825558048000,
"line_mean": 35.0487804878,
"line_max": 79,
"alpha_frac": 0.6255924171,
"autogenerated": false,
"ratio": 3.3042505592841165,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.44298429763841163,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
# Here, the leaf shape from the previous example is reused,
# but instead of simply coloring it with blue, we give it a nice gradient touch.
# Such effects - if your application has room to pull it off, add depth and realism.
# We'll use a clipping mask to achieve this.
# Create a leaf shape.
leaf = BezierPath()
leaf.moveto(0, 0)
leaf.curveto(50, 50, 0, 150, 0, 200)
leaf.curveto(0, 150, -50, 50, 0, 0)
def draw(canvas):
canvas.clear()
translate(250, 250)
for i in range(12):
rotate(30)
# Instead of drawing the path directly, we use it as a clipping mask.
# All shapes drawn between beginclip() and endclip() that fall
# outside the clipping path are hidden.
# Inside we use a colorplane to draw a gradient;
# comment out beginclip() and endclip() to observe what happens.
beginclip(leaf)
colorplane(-75, 0, 150, 200,
color(0.25, 0.15, 0.75, 0.65), # Gradient top color.
color(0.15, 0.45, 0.95, 0.15) # Gradient bottom color.
)
endclip()
# For a sublte finishing touch,
# we could also add the leaf stroke back on top:
drawpath(leaf, stroke=(0,0,0,0.25), strokewidth=1, fill=None)
canvas.size = 500, 500
canvas.run(draw) | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/05-path/02-clip.py",
"copies": "1",
"size": "1452",
"license": "bsd-3-clause",
"hash": -58729120294070264,
"line_mean": 34.4390243902,
"line_max": 84,
"alpha_frac": 0.6391184573,
"autogenerated": false,
"ratio": 3.3767441860465115,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9257279510900499,
"avg_score": 0.051716626489202534,
"num_lines": 41
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
# I always seem to forget how Bezier handles work.
# This example clarifies which handles control what part of a curve.
fontsize(9)
p = BezierPath()
p.moveto(50, 100)
p.curveto(100, 400, 200, 50, 450, 100)
def draw(canvas):
canvas.clear()
nofill()
stroke(0, 0.25)
strokewidth(1)
drawpath(p)
fill(0)
# BezierPath is essentially a list of PathElement objects.
# Each PathElement has a "cmd" property (MOVETO, LINETO, CURVETO or CLOSE),
# an x and y position and two control handles ctrl1 and ctrl2.
# These control handles determine how a curve bends.
for i, pt in enumerate(p):
if i > 0:
# ctrl1 describes how the curve from the previous point started.
line(p[i-1].x, p[i-1].y, pt.ctrl1.x, pt.ctrl1.y, strokestyle=DASHED)
text("pt%s.ctrl1 (%s,%s)" % (i, pt.ctrl1.x, pt.ctrl1.y),
x = pt.ctrl1.x,
y = pt.ctrl1.y+5)
if pt.ctrl2.x != pt.x \
or pt.ctrl2.y != pt.y:
# ctrl2 describes how the curve from the previous point arrives in this point.
line(pt.x, pt.y, pt.ctrl2.x, pt.ctrl2.y, strokestyle=DASHED)
t = text("pt%s.ctrl2 (%s,%s)" % (i, pt.ctrl2.x, pt.ctrl2.y),
x = pt.ctrl2.x,
y = pt.ctrl2.y+5)
ellipse(pt.x, pt.y, 4, 4)
text("pt%s"%i, x=pt.x+5, y=pt.y+5)
# If you use BezierPath.points() to generate intermediary points,
# you get DynamicPathElements whose handles need to be interpreted differently:
# - ctrl1 describes how the curve from the previous point arrives,
# - ctrl2 describes how the curve continues.
t = canvas.frame % 500 * 0.002
pt = p.point(t)
ellipse(pt.x, pt.y, 4, 4)
line(pt.x, pt.y, pt.ctrl1.x, pt.ctrl1.y, strokestyle=DASHED)
line(pt.x, pt.y, pt.ctrl2.x, pt.ctrl2.y, strokestyle=DASHED)
text("ptx", x=pt.x+5, y=pt.y+5)
text("ptx.ctrtl1", x=pt.ctrl1.x, y=pt.ctrl1.y+5)
text("ptx.ctrtl2", x=pt.ctrl2.x, y=pt.ctrl2.y+5)
canvas.size = 500, 500
canvas.run(draw) | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/05-path/06-handle.py",
"copies": "1",
"size": "2246",
"license": "bsd-3-clause",
"hash": 7587093463439322000,
"line_mean": 36.45,
"line_max": 90,
"alpha_frac": 0.6046304541,
"autogenerated": false,
"ratio": 2.8287153652392947,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8811671459641734,
"avg_score": 0.024334871939512205,
"num_lines": 60
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
img = Image("creature.png")
def draw(canvas):
canvas.clear()
# The mouse position controls the origin of the bulge.
# The bump() filter takes two parameters: dx and dy (as do most distortion filters).
# These control the origin of the bulge, as relative values between 0.0 and 1.0.
# For example: dx=0.0 means left edge, dx=0.5 means center of image.
# We divide the absolute mouse position by the image width to get relative values.
dx = canvas.mouse.x / float(img.width)
dy = canvas.mouse.y / float(img.height)
# Since the effect is interactive, we can't render it beforehand.
# We need to reapply it to the source image each frame,
# based on the current mouse position in this frame.
image(bump(img, dx, dy, radius=0.5, zoom=0.75))
# The opposite of bump() is dent():
#image(dent(img, dx, dy, radius=0.5, zoom=0.75))
# Start the application:
canvas.fps = 60
canvas.size = 500, 500
canvas.run(draw) | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/07-filter/02-bump.py",
"copies": "1",
"size": "1150",
"license": "bsd-3-clause",
"hash": 107658974857532220,
"line_mean": 36.1290322581,
"line_max": 88,
"alpha_frac": 0.6747826087,
"autogenerated": false,
"ratio": 3.44311377245509,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.461789638115509,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
img = Image("dendrite.png")
def draw(canvas):
#canvas.clear()
dx = canvas.mouse.x / float(img.width)
dy = canvas.mouse.y / float(img.height)
# The idea is that the output of each filter can be passed to another filter,
# creating a "rendering pipeline".
# For example, the "mirror" effect is a very easy way to show off.
# It reflects the image along a given horizontal (and/or vertical) axis.
# In this case, we use the mouse position as axes.
# By piping together many mirrors, we get an interesting kaleidoscopic effect.
kaleidoscope = mirror(mirror(img, dx, dy), dy, dx)
# You may have noticed the fluid, blurry transitions between patterns.
# This is because we are not clearing the canvas background (we are "painting").
# Since the image gets drawn with an alpha=0.5 (50% opacity),
# the new version is constantly pasted on top of the previous version.
image(kaleidoscope, alpha=0.5)
# Start the application.
# Open a window that is as big as the image.
canvas.fps = 60
canvas.size = img.width, img.height
canvas.run(draw) | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/07-filter/03-mirror.py",
"copies": "1",
"size": "1281",
"license": "bsd-3-clause",
"hash": -879127145784670800,
"line_mean": 37.8484848485,
"line_max": 84,
"alpha_frac": 0.6916471507,
"autogenerated": false,
"ratio": 3.558333333333333,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4749980484033333,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
# In the classic NodeBox for Mac OS X, text can easily be drawn with text(), font(), fontsize().
# This is possible here as well, but it is much faster to prepare the text beforehand:
txt = Text("hello, world", font="Droid Serif", fontsize=20, fontweight=BOLD)
# The less changes you make to the text, the faster it is drawn.
# A Text object has many different typographical parameters:
# - font: the name of the font to use (e.g. "Droid Sans", "Helvetica", ...),
# - fontsize: the fontsize in points,
# - fontweight: NORMAL, BOLD, ITALIC or a (BOLD, ITALIC)-tuple,
# - lineheight: line spacing, 1.0 by default,
# - align: LEFT, RIGHT or CENTER,
# - fill: a Color object that sets the color of the text.
def draw(canvas):
canvas.clear()
# Center the text horizontally.
# Vertically, the y position is the baseline of the text.
x = (canvas.width - textwidth(txt)) / 2
y = 250
text(txt, x, y)
canvas.size = 500, 500
canvas.run(draw) | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/04-text/01-text.py",
"copies": "1",
"size": "1141",
"license": "bsd-3-clause",
"hash": 5582692659188318000,
"line_mean": 35.8387096774,
"line_max": 96,
"alpha_frac": 0.6809815951,
"autogenerated": false,
"ratio": 3.316860465116279,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.44978420602162794,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
# In the previous examples, drawing occurs directly to the canvas.
# It is also possible to draw into different layers,
# and then transform / animate the layers individually.
# The Layer class introduces a lot of useful functionality:
# - layers can receive events from the mouse,
# - layers have an origin point (e.g. "center") from which transformations originate,
# - layers have methods such as Layer.rotate() and Layer.scale(),
# - layers can enable motion tweening (i.e. smooth, automatic transititions).
# A Layer has its personal Layer.draw() method that contains drawing commands.
# In this example, we create a subclass of Layer to display a colored, draggable rectangle:
class DraggableRect(Layer):
def __init__(self, *args, **kwargs):
# A Layer with an extra "clr" property.
Layer.__init__(self, *args, **kwargs)
self.clr = Color(0, 0.75)
def draw(self):
rect(0, 0, self.width, self.height, fill=self.clr, stroke=self.clr)
def on_mouse_enter(self, mouse):
# When the mouse hovers over the rectangle, highlight it.
mouse.cursor = HAND
self.clr.a = 0.75
def on_mouse_leave(self, mouse):
# Reset the mouse cursor when the mouse exits the rectangle.
mouse.cursor = DEFAULT
self.clr.a = 0.5
def on_mouse_drag(self, mouse):
# When the rectangle is dragged, transform it.
# Its scale increases as the mouse is moved up.
# Its angle increases as the mouse is moved left or right.
self.scale(1 + 0.005 * mouse.dy)
self.rotate(mouse.dx)
# The layer's origin defines the origin point for the layer's placement,
# its rotation and scale. If it is (0.5, 0.5), this means the layer will transform
# from its center (i.e. 50% width and 50% height). If you supply integers,
# the values will be interpreted as an absolute offset from the layer's bottom-left corner.
r1 = DraggableRect(x=200, y=200, width=200, height=200, origin=(0.5,0.5), name="blue1")
r1.clr = color(0.0, 0.5, 0.75, 0.5)
r2 = DraggableRect(x=250, y=250, width=200, height=200, origin=(0.5,0.5), name="blue2")
r2.clr = color(0.0, 0.5, 0.75, 0.5)
r3 = DraggableRect(x=300, y=300, width=200, height=200, origin=(0.5,0.5), name="purple1")
r3.clr = color(0.25, 0.15, 0.75, 0.5)
# We'll attach a layer as a child to layer r3.
# Child layers are very handy because they transform together with their parent.
# For example, if the parent layer rotates, all of its children rotate as well.
# However, all of the layers can still receive separate mouse and keyboard events.
# You can use this to (for example) create a flying creature that responds differently
# when the mouse touches its wings or its head - but where all the body parts stick together.
# Position the child's center at (100,100) relative from the parent's layer origin:
r4 = DraggableRect(x=100, y=100, width=100, height=100, origin=(0.5,0.5), name="purple2")
r4.clr = color(0.25, 0.15, 0.75, 0.5)
r3.append(r4)
# Even more nested child layers:
#r5 = DraggableRect(x=50, y=50, width=50, height=50, origin=(0.5,0.5), name="pink1")
#r5.clr = color(1.00, 0.15, 0.75, 0.5)
#r4.append(r5)
# The canvas is essentially a list of layers, just as an image in Photoshop is a list of layers.
# Appending a layer to the canvas ensures that it gets drawn each frame,
# that it receives mouse and keyboard events, and that its motion tweening is updated.
canvas.append(r1)
canvas.append(r2)
canvas.append(r3)
def draw(canvas):
# There is nothing to draw here;
# all the drawing occurs in the separate layers.
canvas.clear()
canvas.size = 500, 500
canvas.run(draw)
# Note: if you have layers that do not need to receive events,
# set Layer.enabled = False; this saves some time doing expensive matrix operations. | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/09-layer/01-drag.py",
"copies": "1",
"size": "3985",
"license": "bsd-3-clause",
"hash": -2934523947392542700,
"line_mean": 42.8021978022,
"line_max": 96,
"alpha_frac": 0.6951066499,
"autogenerated": false,
"ratio": 3.2852431986809565,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9383106671622536,
"avg_score": 0.01944863539168416,
"num_lines": 91
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
# Load an image from file.
# For performance, it's a good idea to create images once, outside the draw() loop.
# NodeBox can then keep the image in graphics card memory so it displays faster.
img = Image("creature.png")
# A simple image effect is a drop shadow.
# We create a grayscale version of the image with the colorize() filter,
# by reducing the image's R,G,B channels to zero but keeping the alpha channel.
# Then we diffuse it with the blur() filter.
# We create the shadow outside the draw() loop for performance:
shadow = colorize(img, color=(0,0,0,1))
shadow = blur(shadow, amount=3, kernel=5)
def draw(canvas):
canvas.clear()
# Some simple mouse interaction to make it more interesting.
# Moving the mouse up will move the creature up from the ground.
dy = canvas.mouse.y
# The origin point (0,0) of the canvas is in the lower left corner.
# Transformations such as rotate() and scale() originate from (0,0).
# We move (or "translate") the origin point to the center of the canvas,
# and then draw the image a bit to the left and to the bottom of it.
# This way, transformations will originate from the center.
translate(canvas.width/2, canvas.height/2)
scale(0.75 + dy*0.001)
image(img, x=-300, y=-200 + dy*0.1)
image(shadow, x=-300, y=-240, alpha=0.5 - dy*0.0005)
# Start the application:
canvas.fps = 60
canvas.size = 500, 500
canvas.run(draw) | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/07-filter/01-shadow.py",
"copies": "1",
"size": "1599",
"license": "bsd-3-clause",
"hash": 5387247098388848000,
"line_mean": 39,
"line_max": 83,
"alpha_frac": 0.6966854284,
"autogenerated": false,
"ratio": 3.468546637744035,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4665232066144035,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
# On Mac OS X, you can access the built-in iSight camera with PySight + CocoaSequenceGrabber:
# http://livingcode.blogspot.com/2005/10/pysight-preview.html (Tim Omernick, Dethe Elza)
# This example requires a bit of setup.
# You need to have the Xcode developer tools and PyObjC installed:
# - http://developer.apple.com/technologies/tools/xcode.html
# - http://pyobjc.sourceforge.net/
# You then need to build CocoaSequenceGrabber as a framework with Xcode.
# Open CococaSequenceGrabber/CocoaSequenceGrabber.xcode with Xcode and build it.
# Put the resulting CocoaSequenceGrabber.framework in /Library/Frameworks.
# The PySight folder should be in the same folder as this script.
# You can then access the iSight camera through PyObjC:
from PySight import CSGCamera
from Foundation import NSObject
from PyObjCTools import AppHelper
from time import time
class Camera(object):
class _delegate(NSObject):
# CSGCamera delegate grabs frames as a CSGImage, which can be cast to a NSBitmapImageRep.
def camera_didReceiveFrame_(self, camera, frame):
self.frame = frame
AppHelper.stopEventLoop()
def __init__(self, width=320, height=240, fps=30):
""" Starts the iSight camera with the given size.
"""
self._delegate = Camera._delegate.alloc().init()
self._width = width
self._height = height
self._fps = fps
self._time = 0
self._camera = CSGCamera.alloc().init()
self._camera.startWithSize_((width, height))
self._camera.setDelegate_(self._delegate)
@property
def width(self):
return self._width
@property
def height(self):
return self._height
def frame(self):
""" Returns a frame as a byte string of TIFF image data (or None).
The byte string can be displayed with image(None, data=Camera.frame()).
"""
try:
AppHelper.runConsoleEventLoop(installInterrupt=True)
return str(self._delegate.frame.representations()[0].TIFFRepresentation().bytes())
except:
return None
def stop(self):
AppHelper.stopEventLoop()
camera = Camera(320, 240)
def draw(canvas):
# A frame from the camera can be passed to the data parameter of the image() command.
f = camera.frame()
if f is not None:
# Draw it with a filter applied.
# Mac OS X PhotoBooth!
image(None, data=f, filter=distorted(STRETCH,
dx = canvas.mouse.relative_x,
dy = canvas.mouse.relative_y))
def stop(canvas):
camera.stop()
canvas.size = camera.width, camera.height
canvas.run(draw, stop=stop)
| {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/12-experimental/01-isight.py",
"copies": "1",
"size": "2909",
"license": "bsd-3-clause",
"hash": 9108895284115746000,
"line_mean": 34.4756097561,
"line_max": 97,
"alpha_frac": 0.6545204538,
"autogenerated": false,
"ratio": 3.768134715025907,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4922655168825907,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
# Render a radial gradient image.
# Without additional parameters, the gradient will be grayscale.
g = gradient(350, 350, type=RADIAL)
# The mask() filter covers one image with another (grayscale) image.
# You can use the grayscale() filter to make image black & white.
# The mask will hide the source image where the mask is black.
# We use the radial gradient as a mask.
# The radial gradient is white at the edges and black at the center.
# We invert it so we get black edges.
# The result is that the source image will gradually fade away at the edges.
img = Image("dendrite.png")
img = mask(img, invert(g))
# Crop the source image to the size of the mask.
# Our mask is smaller than the source image, so beyond it is still pixel data
# but we no longer need it.
img = crop(img, x=0, y=0, width=350, height=350)
def draw(canvas):
#canvas.clear()
# Each frame, paint a new image to the canvas.
# Since its edges are transparent, all images blend into each other.
# This is a useful technique if you want to create random,
# procedural textures (e.g. tree back, rust & dirt, clouded sky, ...)
translate(random(450), random(450))
rotate(random(360))
translate(-img.width/2, -img.height/2) # Rotate from image center.
image(img)
# Start the application:
canvas.fps = 5 # Slow framerate so we can observe what is happening.
canvas.size = 500, 500 # This is a bad idea since keyboard events
canvas.run(draw) # are now logged very slowly. | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/07-filter/06-mask.py",
"copies": "1",
"size": "1662",
"license": "bsd-3-clause",
"hash": -5468296554032949000,
"line_mean": 39.5609756098,
"line_max": 77,
"alpha_frac": 0.7087845969,
"autogenerated": false,
"ratio": 3.4842767295597485,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9612380994636044,
"avg_score": 0.016136066364740926,
"num_lines": 41
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
# Since a layer is a rectangular area, all mouse events are also triggered in a rectangle.
# This can be a bit clumsy in some situations.
# For example: a game environment in which objects light up when the mouse moves over them.
# Not every object fits in a rectangle - so there will be areas that light up the object
# even if the mouse is not over the actual object.
# If you want to do "hit testing" on irregular areas, you can use BezierPath.contains(x, y).
# BezierPath.contains() returns True when the given position is inside the path.
# However, on the canvas, the path might have been rotated and scaled.
# It may be part of a function, loop, and subject to several intermediary scale() and rotate() calls,
# so that its position and shape on the canvas has become entirely different.
# To check whether a position falls inside a transformed path, we first need to *apply* the transformations.
# This can be done with a Transform object from the geometry module,
# which is like a personal transform state:
#
# from nodebox.geometry import Transform
# path = star(x=50, y=50, points=7, outer=100, draw=False)
# tf = Transform()
# tf.translate(100, 0)
# tf.rotate(45)
# path = tf.transform_path(path)
#
# This effectively modifies the position of all points in the path,
# so that they are translated 100 pixels horizontally and then rotated 45 degrees.
class DraggablePolygon(Layer):
def __init__(self, *args, **kwargs):
Layer.__init__(self, *args, **kwargs)
# The actual shape of the layer is a star.
# Events should only be triggered when inside the star.
self.path = star(x=self.width/2, y=self.height/2, points=7, outer=100, draw=False)
# The layer.transform property is a Transform object
# that contains all the transformations the layer has been subjected to.
# Each time the layer is modified, we'll modify the path too.
self.area = self.transform.transform_path(self.path)
self.over = False # True when mouse is over the star.
def draw(self):
if self.over:
clr = color(0.0, 0.5, 0.75, 0.75)
else:
clr = color(0.0, 0.5, 0.75, 0.5)
drawpath(self.path, fill=clr, stroke=clr)
def on_mouse_motion(self, mouse):
# Here's the trick.
# When the mouse moves inside the layer's rectangle,
# we do an additional check to see if it is also over the transformed path:
if self.area.contains(mouse.x, mouse.y):
mouse.cursor = HAND
self.over = True
else:
mouse.cursor = DEFAULT
self.over = False
def on_mouse_drag(self, mouse):
# When inside the transformed path, dragging is enabled.
# The changes to the layer are also applied to the path.
if self.over:
self.scale(1 + 0.005 * mouse.dy)
self.rotate(mouse.vx)
self.area = self.transform.transform_path(self.path)
p = DraggablePolygon(x=250, y=250, width=200, height=200, origin=(0.5,0.5))
canvas.append(p)
canvas.size = 500, 500
canvas.run()
| {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/09-layer/02-polygon.py",
"copies": "1",
"size": "3275",
"license": "bsd-3-clause",
"hash": -6371288152049203000,
"line_mean": 43.2567567568,
"line_max": 108,
"alpha_frac": 0.6708396947,
"autogenerated": false,
"ratio": 3.683914510686164,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4854754205386164,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
# The classic NodeBox for Mac OS X has an interesting textpath() function
# that transforms a string into a BezierPath.
# This function is partly emulated in NodeBox for OpenGL, as long as
# you stick with the default fonts (Droid Sans, Droid Sans Mono, Droid Serif).
# Note: there is a way to make more fonts available - see nodebox/font/glyph.py,
# relying on the classic NodeBox to do the calculations.
path = textpath("GROW", x=40, y=200, fontname="Arial", fontsize=100, bold=True)
# Now that we have a BezierPath from the text we can use all sorts of math on it.
# Calculate a list of points (PathElement objects), evenly distributed along the path:
points = list(path.points(1000))
def draw(canvas):
fill(0.2, 0.2, 0, max(0.1, 1-canvas.frame*0.05)) # Less opacity over time.
for pt in points:
ellipse(pt.x, pt.y, 1, 1)
# Each frame, adjust the position of the point a little bit.
# Since we are not clearing the background,
# it will appear as if something is growing from the text.
pt.x += random(-1.0, 1.0)
pt.y += random(-1.0, 1.0)
canvas.fps = 20
canvas.size = 500, 500
canvas.run(draw)
| {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/05-path/04-text.py",
"copies": "1",
"size": "1347",
"license": "bsd-3-clause",
"hash": -1578689283018302200,
"line_mean": 38.6176470588,
"line_max": 86,
"alpha_frac": 0.6822568671,
"autogenerated": false,
"ratio": 3.2773722627737225,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9195321376717672,
"avg_score": 0.05286155063121,
"num_lines": 34
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
# The pixels() command yields a list of pixels from a given image.
# Since this is a relatively slow operation, this is not useful for dynamic image processing,
# but there a various other ways in which pixels can be useful. In short:
# - len(Pixels): the number of pixels in the image.
# - Pixels.width: the width of the image.
# - Pixels.height: the height of the image.
# - Pixels[i]: a list of [R,G,B,A] values between 0-255 that can be modified.
# - Pixels.get(x, y): returns a Color from the pixel at row x and column y.
# - Pixels.set(x, y, clr): sets the color of the pixel at (x,y).
# - Pixels.update() commits all the changes. You can then pass Pixels to the image() command.
img = Image("creature.png")
p = Pixels(img)
def draw(canvas):
# Since the background is a bit transparent,
# it takes some time for the previous frame to fade away.
background(1,0.03)
# Here we simply use pixels from the image as a color palette.
for i in range(15):
x = random(p.width)
y = random(p.height)
clr = p.get(x, y)
clr.alpha *= 0.5
fill(clr)
stroke(clr)
strokewidth(random(5))
r = random(5, 100)
ellipse(random(canvas.width), random(canvas.height), r*2, r*2)
canvas.size = 500, 500
canvas.run(draw) | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/03-image/05-pixels.py",
"copies": "1",
"size": "1473",
"license": "bsd-3-clause",
"hash": -1826066293080442600,
"line_mean": 36.7948717949,
"line_max": 93,
"alpha_frac": 0.6585200272,
"autogenerated": false,
"ratio": 3.251655629139073,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9297830954667359,
"avg_score": 0.02246894033434274,
"num_lines": 39
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0,os.path.join("..",".."))
from nodebox.graphics import *
# This example demonstrated how to fit text to a path using the directed() command
# (thanks to Karsten Wolf).
# Create a Text object for each character.
txt = "NodeBox for OpenGL"
glyphs = [Text(ch, fontname="Droid Sans Mono") for ch in txt]
def draw(canvas):
background(1)
# Create a path where the mouse position controls the curve.
dx = canvas.mouse.x
dy = canvas.mouse.y
path = BezierPath()
path.moveto(100, 250)
path.curveto(200, 250, dx, dy, 400, 250)
# Calculate points on the path and draw a character at each points.
# The directed() command yields (angle, point)-tuples.
# The angle can be used to rotate each character along the path curvature.
points = path.points(amount=len(glyphs), start=0.05, end=0.95)
for i, (angle, pt) in enumerate(directed(points)):
push()
translate(pt.x, pt.y)
rotate(angle)
text(glyphs[i], x=-textwidth(glyphs[i])/2)
pop()
drawpath(path, fill=None, stroke=(0,0,0,0.5))
line(path[-1].x, path[-1].y, dx, dy, stroke=(0,0,0,0.1))
canvas.fps = 30
canvas.size = 500, 500
canvas.run(draw)
| {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/05-path/07-fit.py",
"copies": "1",
"size": "1314",
"license": "bsd-3-clause",
"hash": 8453447022636691000,
"line_mean": 31.85,
"line_max": 82,
"alpha_frac": 0.6476407915,
"autogenerated": false,
"ratio": 3.166265060240964,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.43139058517409634,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
# This example demonstrates motion tweening and prototype-based inheritance on layers.
# Motion tweening is easy: set the Layer.duration parameter to the amount of seconds
# it should take for transformations to take effect.
# Prototype-based inheritance is used because we were lazy.
# Normally, you create a subclass of layer, give it extra properties (image, color, ...)
# and override its draw() method. The only problem (aside from the repetitive work)
# is Layer.copy(). This creates a copy of the layer with all of its properties,
# but NOT the custom properties we added in a subclass. So we'd have to implement
# our own copy() method for each custom layer that we want to reuse.
# Layers can also use dynamic, prototype-based inheritance, where layers are "inherited"
# instead of subclassed. Custom properties and methods can be set with Layer.set_property()
# and Layer.set_method(). This ensures that they will be copied correctly.
# Create a layer that draws an image, and has the same dimensions as the image.
# It transforms from the center, and it will take one second for transformations to complete.
creature = Layer.from_image("creature.png", x=250, y=250, origin=CENTER, duration=1.0)
# Add a new on_mouse_press handler to the prototype:
def whirl(layer, mouse):
layer.x += random(-100, 100)
layer.y += random(-100, 100)
layer.scaling += random(-0.2, 0.2)
layer.rotation += random(-360, 360)
layer.opacity = random(0.5, 1.0)
creature.set_method(whirl, "on_mouse_press")
# Add a number of copies to the canvas.
for i in range(4):
canvas.append(creature.copy())
canvas.size = 500, 500
canvas.run()
| {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/09-layer/03-tween.py",
"copies": "1",
"size": "1822",
"license": "bsd-3-clause",
"hash": -4550082474101461000,
"line_mean": 43.4390243902,
"line_max": 93,
"alpha_frac": 0.7338090011,
"autogenerated": false,
"ratio": 3.622266401590457,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9805458928189266,
"avg_score": 0.010123294900238397,
"num_lines": 41
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
# This example will make more sense after you've seen the examples in /07-filter
# NodeBox for OpenGL has a range of commands for filtering images.
# For example, blur(img) returns a new Image that is a blurred version of the given image.
# By chaining filters, e.g. twirl(bump(blur(img))), interesting effects can be achieved
# Some filters can be used directly with the image() command.
# For the filters invert(), colorize(), blur(), desaturate(), mask(), blend() and distort(),
# there are variants inverted(), colorized(), blurred(), desaturated(), masked(),
# blended() and distorted() that can be passed to the "filter" parameter of the image() command.
# The advantage is that the effect doesn't need to be rendered offscreen, which is faster.
# The disadvantage is that:
# - image() parameters "color" and "alpha" won't work (they are overridden by the filter),
# - the effect can not be chained,
# - the effect must be relatively simple, e.g. blurred() is a 3x3 Gaussian kernel
# vs. blur() which uses a 9x9 Gaussian kernel.
# In short, these variants are usually meant for testing purposes,
# but it's useful to note their existence nonetheless.
img = Image("creature.png")
def draw(canvas):
canvas.clear()
image(img, 50, 50, filter=distorted(STRETCH, dx=canvas.mouse.relative_x,
dy=canvas.mouse.relative_y))
canvas.size = 500, 500
canvas.run(draw) | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/03-image/03-filter.py",
"copies": "1",
"size": "1607",
"license": "bsd-3-clause",
"hash": -2937284567926820400,
"line_mean": 43.6666666667,
"line_max": 96,
"alpha_frac": 0.6988176727,
"autogenerated": false,
"ratio": 3.6275395033860045,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48263571760860047,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..", ".."))
import tempfile
import subprocess
import shutil
class MovieEncoderError(Exception):
pass
class Movie:
def __init__(self, canvas, fps=25, compression=0.0, encoder="ffmpeg"):
""" Creates a movie recorder for the given Canvas.
Saving the movie requires ffmpeg (http://www.ffmpeg.org/).
If fps=None, uses the actual framerate of the canvas.
Compression can be given as a number between 0.0-1.0.
The encoder parameter specifies the path to the ffmpeg executable.
"""
# You need to compile and build ffmpeg from source.
# However, if you're on Mac OS X 10.3-5 we have a precompiled binary at:
# http://cityinabottle.org/media/download/ffmpeg-osx10.5.zip
# If you place it in the same folder as this script, set encoder="./ffmpeg".
# This binary was obtained from ffmpegX.
# Binaries for Win32 can also be found online.
self._canvas = canvas
self._frames = tempfile.mkdtemp()
self._fps = fps
self._compression = compression
self._encoder = encoder
def record(self):
""" Call Movie.record() in Canvas.draw() to add the current frame to the movie.
Frames are stored as PNG-images in a temporary folder until Movie.close() is called.
"""
self._canvas.save(os.path.join(self._frames, "%09d.png" % self._canvas.frame))
def save(self, path):
""" Saves the movie at the given path (e.g. "test.mp4").
Raises MovieEncoderError if unable to launch ffmpeg from the shell.
"""
try:
f = os.path.join(self._frames, "%"+"09d.png")
r = str(int(self._fps or self._canvas.profiler.framerate))
q = str(int(max(0, min(1, self._compression)) * 30.0 + 1))
o = [self._encoder, "-y", "-r", r, "-i", f, "-qscale", q, path]
p = subprocess.Popen(o, stderr=subprocess.PIPE) # Option -y overwrites exising files.
p.wait()
except Exception, e:
self.close()
raise MovieEncoderError
def close(self):
try: shutil.rmtree(self._frames)
except:
pass
def __del__(self):
try: shutil.rmtree(self._frames)
except:
pass
from nodebox.graphics import *
movie = Movie(canvas)
def draw(canvas):
canvas.clear()
background(1)
translate(250, 250)
rotate(canvas.frame)
rect(-100, -100, 200, 200)
movie.record() # Capture each frame.
canvas.size = 500, 500
canvas.run(draw)
movie.save("test.mp4")
movie.close()
| {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/12-experimental/03-movie.py",
"copies": "1",
"size": "2786",
"license": "bsd-3-clause",
"hash": 3458786935561629700,
"line_mean": 34.2658227848,
"line_max": 97,
"alpha_frac": 0.5951184494,
"autogenerated": false,
"ratio": 3.8060109289617485,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4901129378361748,
"avg_score": null,
"num_lines": null
} |
# Add the upper directory (where the nodebox module is) to the search path.
import os, sys; sys.path.insert(0, os.path.join("..",".."))
# Import the drawing commands from the NodeBox module.
from nodebox.graphics import *
# This includes:
# - drawing primitives such as line(), rect(), ellipse(), triangle(),
# - color commands such as fill(), stroke(), strokewidth(),
# - transform commands such as translate(), rotate(), scale(), push() and pop(),
# - bezier commands such as beginpath(), endpath(), moveto(), lineto(), curveto(), drawpath(),
# - image commands such as image() and crop(),
# - image filters such as blur(), colorize(),
# - text commands such as text(), font(), fontsize(),
# - foundation classes such as Color, BezierPath, Image, Text, Layer and Canvas.
# The canvas will update several times per second.
# The idea is to write a draw() function that contains a combination of drawing commands.
# The draw() function is attached to the canvas so that its output is shown every frame.
# The canvas has a timer for the current frame and logs the position of the mouse,
# these can be used to create different animations for each frame.
def draw(canvas):
# Clear the previous frame.
# This does not happen by default, because interesting effects can be achieved
# by not clearing the background (for example, see math/1-attractor.py).
canvas.clear()
# Draw a rectangle.
# The x parameter defines the horizontal offset from the left edge of the canvas.
# The y parameter defines the vertical offset from the bottom edge of the canvas.
# The rectangle's height is 100 minimum, and grows when you move the mouse up.
# Change some numbers to observe their impact.
rect(x=100, y=10, width=300, height=max(100, canvas.mouse.y))
canvas.size = 500, 500 # Set the size of the canvas.
canvas.run(draw) # Register the draw function and start the application. | {
"repo_name": "nodebox/nodebox-opengl",
"path": "examples/01-basics/01-rect.py",
"copies": "1",
"size": "1920",
"license": "bsd-3-clause",
"hash": -9124606935647946000,
"line_mean": 52.3611111111,
"line_max": 94,
"alpha_frac": 0.7135416667,
"autogenerated": false,
"ratio": 3.983402489626556,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5196944156326556,
"avg_score": null,
"num_lines": null
} |
"""Add the user model
Revision ID: 490c5b501a3
Revises: 1e665b27760
Create Date: 2014-04-25 08:38:29.594656
"""
# revision identifiers, used by Alembic.
revision = '490c5b501a3'
down_revision = '1e665b27760'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(
'users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=20), nullable=True),
sa.Column('password', sa.String(length=250), nullable=True),
sa.Column('email', sa.String(length=50), nullable=True),
sa.Column('registered_on', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_index('ix_users_email', 'users', ['email'], unique=True)
op.create_index('ix_users_registered_on', 'users', ['registered_on'],
unique=False)
op.create_index('ix_users_username', 'users', ['username'], unique=True)
def downgrade():
op.drop_index('ix_users_username', table_name='users')
op.drop_index('ix_users_registered_on', table_name='users')
op.drop_index('ix_users_email', table_name='users')
op.drop_table('users')
| {
"repo_name": "d0ugal-archive/home",
"path": "home/migrations/versions/490c5b501a3_add_user_model.py",
"copies": "1",
"size": "1164",
"license": "bsd-3-clause",
"hash": 2743272711886673400,
"line_mean": 29.6315789474,
"line_max": 76,
"alpha_frac": 0.6520618557,
"autogenerated": false,
"ratio": 3.224376731301939,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4376438587001939,
"avg_score": null,
"num_lines": null
} |
"""Add things to old Pythons so I can pretend they are newer, for tests."""
# pylint: disable=W0622
# (Redefining built-in blah)
# The whole point of this file is to redefine built-ins, so shut up about it.
import os
# Py2 and Py3 don't agree on how to run commands in a subprocess.
try:
import subprocess
except ImportError:
def run_command(cmd, status=0):
"""Run a command in a subprocess.
Returns the exit status code and the combined stdout and stderr.
"""
_, stdouterr = os.popen4(cmd)
return status, stdouterr.read()
else:
def run_command(cmd, status=0):
"""Run a command in a subprocess.
Returns the exit status code and the combined stdout and stderr.
"""
proc = subprocess.Popen(cmd, shell=True,
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
output, _ = proc.communicate()
status = proc.returncode # pylint: disable=E1101
# Get the output, and canonicalize it to strings with newlines.
if not isinstance(output, str):
output = output.decode('utf-8')
output = output.replace('\r', '')
return status, output
# No more execfile in Py3
try:
execfile = execfile
except NameError:
def execfile(filename, globs):
"""A Python 3 implementation of execfile."""
exec(compile(open(filename).read(), filename, 'exec'), globs)
| {
"repo_name": "public/testmon",
"path": "test/coveragepy/backtest.py",
"copies": "2",
"size": "1484",
"license": "mit",
"hash": 274933852195437900,
"line_mean": 29.2857142857,
"line_max": 77,
"alpha_frac": 0.6273584906,
"autogenerated": false,
"ratio": 4.1568627450980395,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5784221235698039,
"avg_score": null,
"num_lines": null
} |
"""Add things to old Pythons so I can pretend they are newer."""
# This file does lots of tricky stuff, so disable a bunch of lintisms.
# pylint: disable=F0401,W0611,W0622
# F0401: Unable to import blah
# W0611: Unused import blah
# W0622: Redefining built-in blah
import os, re, sys
# Python 2.3 doesn't have `set`
try:
set = set # new in 2.4
except NameError:
from sets import Set as set
# Python 2.3 doesn't have `sorted`.
try:
sorted = sorted
except NameError:
def sorted(iterable):
"""A 2.3-compatible implementation of `sorted`."""
lst = list(iterable)
lst.sort()
return lst
# Python 2.3 doesn't have `reversed`.
try:
reversed = reversed
except NameError:
def reversed(iterable):
"""A 2.3-compatible implementation of `reversed`."""
lst = list(iterable)
return lst[::-1]
# rpartition is new in 2.5
try:
"".rpartition
except AttributeError:
def rpartition(s, sep):
"""Implement s.rpartition(sep) for old Pythons."""
i = s.rfind(sep)
if i == -1:
return ('', '', s)
else:
return (s[:i], sep, s[i+len(sep):])
else:
def rpartition(s, sep):
"""A common interface for new Pythons."""
return s.rpartition(sep)
# Pythons 2 and 3 differ on where to get StringIO
try:
from cStringIO import StringIO
BytesIO = StringIO
except ImportError:
from io import StringIO, BytesIO
# What's a string called?
try:
string_class = basestring
except NameError:
string_class = str
# Where do pickles come from?
try:
import cPickle as pickle
except ImportError:
import pickle
# range or xrange?
try:
range = xrange
except NameError:
range = range
# A function to iterate listlessly over a dict's items.
try:
{}.iteritems
except AttributeError:
def iitems(d):
"""Produce the items from dict `d`."""
return d.items()
else:
def iitems(d):
"""Produce the items from dict `d`."""
return d.iteritems()
# Exec is a statement in Py2, a function in Py3
if sys.version_info >= (3, 0):
def exec_code_object(code, global_map):
"""A wrapper around exec()."""
exec(code, global_map)
else:
# OK, this is pretty gross. In Py2, exec was a statement, but that will
# be a syntax error if we try to put it in a Py3 file, even if it is never
# executed. So hide it inside an evaluated string literal instead.
eval(
compile(
"def exec_code_object(code, global_map):\n"
" exec code in global_map\n",
"<exec_function>", "exec"
)
)
# Reading Python source and interpreting the coding comment is a big deal.
if sys.version_info >= (3, 0):
# Python 3.2 provides `tokenize.open`, the best way to open source files.
import tokenize
try:
open_source = tokenize.open # pylint: disable=E1101
except AttributeError:
from io import TextIOWrapper
detect_encoding = tokenize.detect_encoding # pylint: disable=E1101
# Copied from the 3.2 stdlib:
def open_source(fname):
"""Open a file in read only mode using the encoding detected by
detect_encoding().
"""
buffer = open(fname, 'rb')
encoding, _ = detect_encoding(buffer.readline)
buffer.seek(0)
text = TextIOWrapper(buffer, encoding, line_buffering=True)
text.mode = 'r'
return text
else:
def open_source(fname):
"""Open a source file the best way."""
return open(fname, "rU")
# Python 3.x is picky about bytes and strings, so provide methods to
# get them right, and make them no-ops in 2.x
if sys.version_info >= (3, 0):
def to_bytes(s):
"""Convert string `s` to bytes."""
return s.encode('utf8')
def to_string(b):
"""Convert bytes `b` to a string."""
return b.decode('utf8')
def binary_bytes(byte_values):
"""Produce a byte string with the ints from `byte_values`."""
return bytes(byte_values)
def byte_to_int(byte_value):
"""Turn an element of a bytes object into an int."""
return byte_value
def bytes_to_ints(bytes_value):
"""Turn a bytes object into a sequence of ints."""
# In Py3, iterating bytes gives ints.
return bytes_value
else:
def to_bytes(s):
"""Convert string `s` to bytes (no-op in 2.x)."""
return s
def to_string(b):
"""Convert bytes `b` to a string (no-op in 2.x)."""
return b
def binary_bytes(byte_values):
"""Produce a byte string with the ints from `byte_values`."""
return "".join([chr(b) for b in byte_values])
def byte_to_int(byte_value):
"""Turn an element of a bytes object into an int."""
return ord(byte_value)
def bytes_to_ints(bytes_value):
"""Turn a bytes object into a sequence of ints."""
for byte in bytes_value:
yield ord(byte)
# Md5 is available in different places.
try:
import hashlib
md5 = hashlib.md5
except ImportError:
import md5
md5 = md5.new
| {
"repo_name": "kevinkindom/chrome_depto_tools",
"path": "third_party/coverage/backward.py",
"copies": "211",
"size": "5187",
"license": "bsd-3-clause",
"hash": 616322560945286100,
"line_mean": 27.1902173913,
"line_max": 78,
"alpha_frac": 0.6070946597,
"autogenerated": false,
"ratio": 3.7833698030634575,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""Add things to old Pythons so I can pretend they are newer."""
# This file does lots of tricky stuff, so disable a bunch of lintisms.
# pylint: disable-msg=F0401,W0611,W0622
# F0401: Unable to import blah
# W0611: Unused import blah
# W0622: Redefining built-in blah
import os, sys
# Python 2.3 doesn't have `set`
try:
set = set # new in 2.4
except NameError:
from sets import Set as set
# Python 2.3 doesn't have `sorted`.
try:
sorted = sorted
except NameError:
def sorted(iterable):
"""A 2.3-compatible implementation of `sorted`."""
lst = list(iterable)
lst.sort()
return lst
# Pythons 2 and 3 differ on where to get StringIO
try:
from cStringIO import StringIO
BytesIO = StringIO
except ImportError:
from io import StringIO, BytesIO
# What's a string called?
try:
string_class = basestring
except NameError:
string_class = str
# Where do pickles come from?
try:
import cPickle as pickle
except ImportError:
import pickle
# range or xrange?
try:
range = xrange
except NameError:
range = range
# Exec is a statement in Py2, a function in Py3
if sys.hexversion > 0x03000000:
def exec_function(source, filename, global_map):
"""A wrapper around exec()."""
exec(compile(source, filename, "exec"), global_map)
else:
# OK, this is pretty gross. In Py2, exec was a statement, but that will
# be a syntax error if we try to put it in a Py3 file, even if it is never
# executed. So hide it inside an evaluated string literal instead.
eval(compile("""\
def exec_function(source, filename, global_map):
exec compile(source, filename, "exec") in global_map
""",
"<exec_function>", "exec"
))
| {
"repo_name": "mastizada/kuma",
"path": "vendor/packages/coverage/coverage/backward.py",
"copies": "6",
"size": "1739",
"license": "mpl-2.0",
"hash": 4905223144806365000,
"line_mean": 23.1527777778,
"line_max": 78,
"alpha_frac": 0.6722254169,
"autogenerated": false,
"ratio": 3.6153846153846154,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7287610032284615,
"avg_score": null,
"num_lines": null
} |
# Add this to crontab: 0,30 * * * * python3 /home/ubuntu/foldatlas/foldatlas/monitor.py
import traceback
import os
import urllib.request # the lib that handles the url stuff
test_url = "http://www.foldatlas.com/transcript/AT2G45180.1"
recipient = "matthew.gs.norris@gmail.com"
search_str = "AT2G45180.1"
def run_test():
try:
data = urllib.request.urlopen(test_url) # it's a file like object and works just like a file
text = str(data.read())
if search_str in text:
send_mail("FoldAtlas success", "It worked!")
print("It worked!")
else:
send_mail("FoldAtlas error", text)
except:
send_mail("FoldAtlas error", traceback.format_exc())
def send_mail(subject, body):
SENDMAIL = "/usr/sbin/sendmail" # sendmail location
p = os.popen("%s -t" % SENDMAIL, "w")
p.write("To: "+recipient+"\n")
p.write("From: FoldAtlas\n")
p.write("Subject: "+subject+"\n")
p.write("\n") # blank line separating headers from body
p.write(body)
sts = p.close()
run_test()
| {
"repo_name": "mnori/foldatlas",
"path": "foldatlas/monitor.py",
"copies": "1",
"size": "1075",
"license": "mit",
"hash": -7117426784973943000,
"line_mean": 29.7142857143,
"line_max": 100,
"alpha_frac": 0.6251162791,
"autogenerated": false,
"ratio": 3.208955223880597,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.43340715029805976,
"avg_score": null,
"num_lines": null
} |
# add this to your vimrc
#let g:ycm_global_ycm_extra_conf = "~/.vim/.ycm_extra_conf_openframeworks.py"
# Partially stolen from https://bitbucket.org/mblum/libgp/src/2537ea7329ef/.ycm_extra_conf.py
import os
import ycm_core
# These are the compilation flags that will be used in case there's no
# compilation database set (by default, one is not set).
# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR.
flags = [
'-c',
'-O3',
'-Wall',
'-march=native',
'-mtune=native',
'-DOF_USING_GTK',
'-DOF_USING_GTK',
'-DOF_USING_MPG123',
# THIS IS IMPORTANT! Without a "-std=<something>" flag, clang won't know which
# language to use when compiling headers. So it will guess. Badly. So C++
# headers will be compiled as C headers. You don't want that so ALWAYS specify
# a "-std=<something>".
# For a C project, you would set this to something like 'c99' instead of
# 'c++11'.
'-std=c++11',
# ...and the same thing goes for the magic -x option which specifies the
# language that the files to be compiled are written in. This is mostly
# relevant for c++ headers.
# For a C project, you would set this to 'c' instead of 'c++'.
'-x', 'c++',
# This path will only work on OS X, but extra paths that don't exist are not
# harmful
#'-isystem', '/System/Library/Frameworks/Python.framework/Headers',
'-isystem', '/usr/local/include',
#'-isystem', '/usr/local/include/eigen3',
'-I./src',
'-I./data',
'-I./data/model',
'-I/usr/include/cairo',
'-I/usr/include/glib-2.0',
'-I/usr/lib/x86_64-linux-gnu/glib-2.0/include',
'-I/usr/include/pixman-1',
'-I/usr/include/freetype2',
'-I/usr/include/libpng12',
'-I/usr/include/gstreamer-1.0',
'-I/usr/include/alsa',
'-I/usr/include/libdrm',
'-I/usr/include/GL',
'-I/usr/include/gtk-3.0',
'-I/usr/include/atk-1.0',
'-I/usr/include/at-spi2-atk/2.0',
'-I/usr/include/pango-1.0',
'-I/usr/include/gio-unix-2.0/',
'-I/usr/include/gdk-pixbuf-2.0',
'-I/usr/include/harfbuzz',
'-I../../../libs/cairo/include',
'-I../../../libs/cairo/include/pixman-1',
'-I../../../libs/cairo/include/cairo',
'-I../../../libs/cairo/include/libpng15',
'-I../../../libs/fmodex/include',
'-I../../../libs/glfw/include',
'-I../../../libs/glfw/include/GLFW',
'-I../../../libs/kiss/include',
'-I../../../libs/openssl/include',
'-I../../../libs/openssl/include/openssl',
'-I../../../libs/poco/include',
'-I../../../libs/rtAudio/include',
'-I../../../libs/tess2/include',
'-I../../../libs/openFrameworks',
'-I../../../libs/openFrameworks/sound',
'-I../../../libs/openFrameworks/utils',
'-I../../../libs/openFrameworks/communication',
'-I../../../libs/openFrameworks/events',
'-I../../../libs/openFrameworks/types',
'-I../../../libs/openFrameworks/app',
'-I../../../libs/openFrameworks/gl',
'-I../../../libs/openFrameworks/video',
'-I../../../libs/openFrameworks/math',
'-I../../../libs/openFrameworks/3d',
'-I../../../libs/openFrameworks/graphics',
'-I.'
]
addons = [
'-I../../../addons/ofxOpenCv/src',
'-I../../../addons/ofxOpenCv/libs',
'-I../../../addons/ofxOpenCv/libs/opencv',
'-I../../../addons/ofxOpenCv/libs/opencv/include',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/features2d',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/ts',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/contrib',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/objdetect',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/highgui',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/legacy',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/imgproc',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/video',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/ml',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/calib3d',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv',
'-I../../../addons/ofxOpenCv/libs/opencv/lib',
'-I../../../addons/ofxOpenCv/libs/opencv/lib/osx',
'-I../../../addons/ofxOpenCv/libs/opencv/lib/win_cb',
'-I../../../addons/ofxOpenCv/libs/opencv/lib/ios',
'-I../../../addons/ofxOpenCv/libs/opencv/lib/linux',
'-I../../../addons/ofxOpenCv/libs/opencv/lib/vs',
'-I../../../addons/ofxOpenCv/libs/opencv/lib/linuxarmv6l',
'-I../../../addons/ofxOpenCv/libs/opencv/lib/android',
'-I../../../addons/ofxOpenCv/libs/opencv/lib/android/armeabi',
'-I../../../addons/ofxOpenCv/libs/opencv/lib/android/armeabi-v7a',
'-I../../../addons/ofxOpenCv/libs/opencv/lib/linuxarmv7l',
'-I../../../addons/ofxOpenCv/libs/opencv/lib/linux64',
'-I../../../addons/ofxOpenCv/libs/opencv/include',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/features2d',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/ts',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/contrib',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/objdetect',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/highgui',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/legacy',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/imgproc',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/video',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/ml',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv2/calib3d',
'-I../../../addons/ofxOpenCv/libs/opencv/include/opencv',
'-I../../../addons/ofxCv/src',
'-I../../../addons/ofxCv/libs',
'-I../../../addons/ofxCv/libs/CLD',
'-I../../../addons/ofxCv/libs/CLD/include',
'-I../../../addons/ofxCv/libs/CLD/include/CLD',
'-I../../../addons/ofxCv/libs/CLD/src',
'-I../../../addons/ofxCv/libs/ofxCv',
'-I../../../addons/ofxCv/libs/ofxCv/include',
'-I../../../addons/ofxCv/libs/ofxCv/include/ofxCv',
'-I../../../addons/ofxCv/libs/ofxCv/src',
'-I../../../addons/ofxCv/libs/CLD/include',
'-I../../../addons/ofxCv/libs/CLD/include/CLD',
'-I../../../addons/ofxCv/libs/ofxCv/include',
'-I../../../addons/ofxCv/libs/ofxCv/include/ofxCv',
'-I../../../addons/ofxFaceTracker/src',
'-I../../../addons/ofxFaceTracker/libs',
'-I../../../addons/ofxFaceTracker/libs/FaceTracker',
'-I../../../addons/ofxFaceTracker/libs/FaceTracker/include',
'-I../../../addons/ofxFaceTracker/libs/FaceTracker/include/FaceTracker',
'-I../../../addons/ofxFaceTracker/libs/FaceTracker/src',
'-I../../../addons/ofxFaceTracker/libs/FaceTracker/src/lib',
'-I../../../addons/ofxFaceTracker/libs/FaceTracker/model',
'-I../../../addons/ofxFaceTracker/libs/FaceTracker/include',
'-I../../../addons/ofxFaceTracker/libs/FaceTracker/include/FaceTracker',
'-pthread',
'-D_REENTRANT'
]
#concat flags and addons
flags += addons
# Set this to the absolute path to the folder (NOT the file!) containing the
# compile_commands.json file to use that instead of 'flags'. See here for
# more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html
#
# Most projects will NOT need to set this to anything; you can just change the
# 'flags' list of compilation flags. Notice that YCM itself uses that approach.
compilation_database_folder = ''
if compilation_database_folder:
database = ycm_core.CompilationDatabase( compilation_database_folder )
else:
database = None
def DirectoryOfThisScript():
return os.path.dirname( os.path.abspath( __file__ ) )
def MakeRelativePathsInFlagsAbsolute( flags, working_directory ):
if not working_directory:
return list( flags )
new_flags = []
make_next_absolute = False
path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ]
for flag in flags:
new_flag = flag
if make_next_absolute:
make_next_absolute = False
if not flag.startswith( '/' ):
new_flag = os.path.join( working_directory, flag )
for path_flag in path_flags:
if flag == path_flag:
make_next_absolute = True
break
if flag.startswith( path_flag ):
path = flag[ len( path_flag ): ]
new_flag = path_flag + os.path.join( working_directory, path )
break
if new_flag:
new_flags.append( new_flag )
return new_flags
def FlagsForFile( filename ):
if database:
# Bear in mind that compilation_info.compiler_flags_ does NOT return a
# python list, but a "list-like" StringVec object
compilation_info = database.GetCompilationInfoForFile( filename )
final_flags = MakeRelativePathsInFlagsAbsolute(
compilation_info.compiler_flags_,
compilation_info.compiler_working_dir_ )
else:
relative_to = ''#DirectoryOfThisScript()
final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to )
return {
'flags': final_flags,
'do_cache': True
} | {
"repo_name": "James-Oldfield/dotfiles",
"path": ".vim/.ycm_extra_conf_openframeworks.py",
"copies": "1",
"size": "9136",
"license": "mit",
"hash": 977578434662569200,
"line_mean": 39.2511013216,
"line_max": 93,
"alpha_frac": 0.6500656743,
"autogenerated": false,
"ratio": 2.8267326732673266,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.39767983475673263,
"avg_score": null,
"num_lines": null
} |
"""add three-way favourite policy
Revision ID: 2bd33abe291c
Revises: 583cdac8eba1
Create Date: 2018-01-03 17:31:03.718648
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2bd33abe291c'
down_revision = '583cdac8eba1'
branch_labels = None
depends_on = None
transitional = sa.table('accounts',
sa.column('policy_keep_favourites'),
sa.column('old_policy_keep_favourites'))
def upgrade():
ThreeWayPolicyEnum = sa.Enum('keeponly', 'deleteonly', 'none',
name='enum_3way_policy')
op.alter_column('accounts', 'policy_keep_favourites',
new_column_name='old_policy_keep_favourites')
op.add_column(
'accounts',
sa.Column('policy_keep_favourites', ThreeWayPolicyEnum,
nullable=False, server_default='none'))
op.execute(transitional.update()
.where(transitional.c.old_policy_keep_favourites)
.values(policy_keep_favourites=op.inline_literal('keeponly')))
op.drop_column('accounts', 'old_policy_keep_favourites')
def downgrade():
op.alter_column('accounts', 'policy_keep_favourites',
new_column_name='old_policy_keep_favourites')
op.add_column(
'accounts',
sa.Column('policy_keep_favourites', sa.Boolean(),
nullable=False, server_default='f'))
op.execute(transitional.update()
.where(transitional.c.old_policy_keep_favourites == op.inline_literal('keeponly'))
.values(policy_keep_favourites=op.inline_literal('t')))
op.drop_column('accounts', 'old_policy_keep_favourites')
| {
"repo_name": "codl/forget",
"path": "migrations/versions/2bd33abe291c_add_three_way_favourite_policy.py",
"copies": "1",
"size": "1699",
"license": "isc",
"hash": 7531490996357763000,
"line_mean": 31.0566037736,
"line_max": 94,
"alpha_frac": 0.6362566215,
"autogenerated": false,
"ratio": 3.4462474645030428,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.45825040860030425,
"avg_score": null,
"num_lines": null
} |
"""add three-way media policy
Revision ID: 583cdac8eba1
Revises: 7e255d4ea34d
Create Date: 2017-12-28 00:46:56.023649
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '583cdac8eba1'
down_revision = '7e255d4ea34d'
branch_labels = None
depends_on = None
transitional = sa.table('accounts',
sa.column('policy_keep_media'),
sa.column('old_policy_keep_media'))
def upgrade():
ThreeWayPolicyEnum = sa.Enum('keeponly', 'deleteonly', 'none',
name='enum_3way_policy')
op.execute("""
CREATE TYPE enum_3way_policy AS ENUM ('keeponly', 'deleteonly', 'none')
""")
op.alter_column('accounts', 'policy_keep_media',
new_column_name='old_policy_keep_media')
op.add_column(
'accounts',
sa.Column('policy_keep_media', ThreeWayPolicyEnum,
nullable=False, server_default='none'))
op.execute(transitional.update()
.where(transitional.c.old_policy_keep_media)
.values(policy_keep_media=op.inline_literal('keeponly')))
op.drop_column('accounts', 'old_policy_keep_media')
def downgrade():
op.alter_column('accounts', 'policy_keep_media',
new_column_name='old_policy_keep_media')
op.add_column(
'accounts',
sa.Column('policy_keep_media', sa.Boolean(),
nullable=False, server_default='f'))
op.execute(transitional.update()
.where(transitional.c.old_policy_keep_media == op.inline_literal('keeponly'))
.values(policy_keep_media=op.inline_literal('t')))
op.drop_column('accounts', 'old_policy_keep_media')
op.execute("""
DROP TYPE enum_3way_policy
""")
| {
"repo_name": "codl/forget",
"path": "migrations/versions/583cdac8eba1_add_three_way_media_policy.py",
"copies": "1",
"size": "1796",
"license": "isc",
"hash": -2178236796467829000,
"line_mean": 29.4406779661,
"line_max": 89,
"alpha_frac": 0.6119153675,
"autogenerated": false,
"ratio": 3.5009746588693957,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9599827709560425,
"avg_score": 0.0026124633617943165,
"num_lines": 59
} |
"""Add tickets table
Revision ID: 516b5a4829e
Revises: 31cde2cf5e6
Create Date: 2014-12-05 11:13:14.203925
"""
# revision identifiers, used by Alembic.
revision = '516b5a4829e'
down_revision = '31cde2cf5e6'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('tickets',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('create_date', sa.DateTime(), nullable=False),
sa.Column('closed', sa.Boolean(), nullable=False),
sa.Column('close_date', sa.DateTime(), nullable=True),
sa.Column('subject', sa.String(), nullable=False),
sa.Column('notify_owner', sa.Boolean(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('ticket_messages',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('ticket_id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('create_date', sa.DateTime(), nullable=False),
sa.Column('content', sa.Text(), nullable=False),
sa.ForeignKeyConstraint(['ticket_id'], ['tickets.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('ticket_messages')
op.drop_table('tickets')
### end Alembic commands ###
| {
"repo_name": "bspavel/ccvpn",
"path": "alembic/versions/516b5a4829e_add_tickets_table.py",
"copies": "2",
"size": "1559",
"license": "mit",
"hash": 1676212625879606800,
"line_mean": 32.170212766,
"line_max": 63,
"alpha_frac": 0.6593970494,
"autogenerated": false,
"ratio": 3.418859649122807,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5078256698522807,
"avg_score": null,
"num_lines": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.