prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>subscription_manifest.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Andrew Kofink <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: subscription_manifest
version_added: 1.0.0
short_description: Manage Subscription Manifests
description:
- Upload, refresh and delete Subscription Manifests
author: "Andrew Kofink (@akofink)"
options:
manifest_path:
description:
- Path to the manifest zip file
- This parameter will be ignored if I(state=absent) or I(state=refreshed)
type: path
state:
description:
- The state of the manifest
default: present
choices:
- absent
- present
- refreshed
type: str
repository_url:
description:
- URL to retrieve content from
aliases: [ redhat_repository_url ]
type: str
extends_documentation_fragment:
- theforeman.foreman.foreman
- theforeman.foreman.foreman.organization
'''
EXAMPLES = '''
- name: "Upload the RHEL developer edition manifest"
theforeman.foreman.subscription_manifest:
username: "admin"
password: "changeme"
server_url: "https://foreman.example.com"
organization: "Default Organization"
state: present
manifest_path: "/tmp/manifest.zip"
'''
RETURN = ''' # '''
from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule
def main():
module = KatelloEntityAnsibleModule(
argument_spec=dict(
manifest_path=dict(type='path'),
state=dict(default='present', choices=['absent', 'present', 'refreshed']),
repository_url=dict(aliases=['redhat_repository_url']),
),
foreman_spec=dict(
organization=dict(type='entity', required=True, thin=False),
),
required_if=[
['state', 'present', ['manifest_path']],
],
supports_check_mode=False,
)
module.task_timeout = 5 * 60
with module.api_connection():
organization = module.lookup_entity('organization')
scope = module.scope_for('organization')
try:
existing_manifest = organization['owner_details']['upstreamConsumer']
except KeyError:
existing_manifest = None
if module.state == 'present':
if 'repository_url' in module.foreman_params:
payload = {'redhat_repository_url': module.foreman_params['repository_url']}
org_spec = dict(id=dict(), redhat_repository_url=dict())
organization = module.ensure_entity('organizations', payload, organization, state='present', foreman_spec=org_spec)
try:
with open(module.foreman_params['manifest_path'], 'rb') as manifest_file:
files = {'content': (module.foreman_params['manifest_path'], manifest_file, 'application/zip')}
params = {}
if 'repository_url' in module.foreman_params:
params['repository_url'] = module.foreman_params['repository_url']
params.update(scope)
result = module.resource_action('subscriptions', 'upload', params, files=files, record_change=False, ignore_task_errors=True)
for error in result['humanized']['errors']:
if "same as existing data" in error:
# Nothing changed, but everything ok
break
if "older than existing data" in error:
module.fail_json(msg="Manifest is older than existing data.")
else:
module.fail_json(msg="Upload of the manifest failed: %s" % error)
else:
module.set_changed()
except IOError as e:
module.fail_json(msg="Unable to read the manifest file: %s" % e)
elif module.desired_absent and existing_manifest:
<|fim_middle|>
elif module.state == 'refreshed':
if existing_manifest:
module.resource_action('subscriptions', 'refresh_manifest', scope)
else:
module.fail_json(msg="No manifest found to refresh.")
if __name__ == '__main__':
main()
<|fim▁end|> | module.resource_action('subscriptions', 'delete_manifest', scope) |
<|file_name|>subscription_manifest.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Andrew Kofink <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: subscription_manifest
version_added: 1.0.0
short_description: Manage Subscription Manifests
description:
- Upload, refresh and delete Subscription Manifests
author: "Andrew Kofink (@akofink)"
options:
manifest_path:
description:
- Path to the manifest zip file
- This parameter will be ignored if I(state=absent) or I(state=refreshed)
type: path
state:
description:
- The state of the manifest
default: present
choices:
- absent
- present
- refreshed
type: str
repository_url:
description:
- URL to retrieve content from
aliases: [ redhat_repository_url ]
type: str
extends_documentation_fragment:
- theforeman.foreman.foreman
- theforeman.foreman.foreman.organization
'''
EXAMPLES = '''
- name: "Upload the RHEL developer edition manifest"
theforeman.foreman.subscription_manifest:
username: "admin"
password: "changeme"
server_url: "https://foreman.example.com"
organization: "Default Organization"
state: present
manifest_path: "/tmp/manifest.zip"
'''
RETURN = ''' # '''
from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule
def main():
module = KatelloEntityAnsibleModule(
argument_spec=dict(
manifest_path=dict(type='path'),
state=dict(default='present', choices=['absent', 'present', 'refreshed']),
repository_url=dict(aliases=['redhat_repository_url']),
),
foreman_spec=dict(
organization=dict(type='entity', required=True, thin=False),
),
required_if=[
['state', 'present', ['manifest_path']],
],
supports_check_mode=False,
)
module.task_timeout = 5 * 60
with module.api_connection():
organization = module.lookup_entity('organization')
scope = module.scope_for('organization')
try:
existing_manifest = organization['owner_details']['upstreamConsumer']
except KeyError:
existing_manifest = None
if module.state == 'present':
if 'repository_url' in module.foreman_params:
payload = {'redhat_repository_url': module.foreman_params['repository_url']}
org_spec = dict(id=dict(), redhat_repository_url=dict())
organization = module.ensure_entity('organizations', payload, organization, state='present', foreman_spec=org_spec)
try:
with open(module.foreman_params['manifest_path'], 'rb') as manifest_file:
files = {'content': (module.foreman_params['manifest_path'], manifest_file, 'application/zip')}
params = {}
if 'repository_url' in module.foreman_params:
params['repository_url'] = module.foreman_params['repository_url']
params.update(scope)
result = module.resource_action('subscriptions', 'upload', params, files=files, record_change=False, ignore_task_errors=True)
for error in result['humanized']['errors']:
if "same as existing data" in error:
# Nothing changed, but everything ok
break
if "older than existing data" in error:
module.fail_json(msg="Manifest is older than existing data.")
else:
module.fail_json(msg="Upload of the manifest failed: %s" % error)
else:
module.set_changed()
except IOError as e:
module.fail_json(msg="Unable to read the manifest file: %s" % e)
elif module.desired_absent and existing_manifest:
module.resource_action('subscriptions', 'delete_manifest', scope)
elif module.state == 'refreshed':
<|fim_middle|>
if __name__ == '__main__':
main()
<|fim▁end|> | if existing_manifest:
module.resource_action('subscriptions', 'refresh_manifest', scope)
else:
module.fail_json(msg="No manifest found to refresh.") |
<|file_name|>subscription_manifest.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Andrew Kofink <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: subscription_manifest
version_added: 1.0.0
short_description: Manage Subscription Manifests
description:
- Upload, refresh and delete Subscription Manifests
author: "Andrew Kofink (@akofink)"
options:
manifest_path:
description:
- Path to the manifest zip file
- This parameter will be ignored if I(state=absent) or I(state=refreshed)
type: path
state:
description:
- The state of the manifest
default: present
choices:
- absent
- present
- refreshed
type: str
repository_url:
description:
- URL to retrieve content from
aliases: [ redhat_repository_url ]
type: str
extends_documentation_fragment:
- theforeman.foreman.foreman
- theforeman.foreman.foreman.organization
'''
EXAMPLES = '''
- name: "Upload the RHEL developer edition manifest"
theforeman.foreman.subscription_manifest:
username: "admin"
password: "changeme"
server_url: "https://foreman.example.com"
organization: "Default Organization"
state: present
manifest_path: "/tmp/manifest.zip"
'''
RETURN = ''' # '''
from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule
def main():
module = KatelloEntityAnsibleModule(
argument_spec=dict(
manifest_path=dict(type='path'),
state=dict(default='present', choices=['absent', 'present', 'refreshed']),
repository_url=dict(aliases=['redhat_repository_url']),
),
foreman_spec=dict(
organization=dict(type='entity', required=True, thin=False),
),
required_if=[
['state', 'present', ['manifest_path']],
],
supports_check_mode=False,
)
module.task_timeout = 5 * 60
with module.api_connection():
organization = module.lookup_entity('organization')
scope = module.scope_for('organization')
try:
existing_manifest = organization['owner_details']['upstreamConsumer']
except KeyError:
existing_manifest = None
if module.state == 'present':
if 'repository_url' in module.foreman_params:
payload = {'redhat_repository_url': module.foreman_params['repository_url']}
org_spec = dict(id=dict(), redhat_repository_url=dict())
organization = module.ensure_entity('organizations', payload, organization, state='present', foreman_spec=org_spec)
try:
with open(module.foreman_params['manifest_path'], 'rb') as manifest_file:
files = {'content': (module.foreman_params['manifest_path'], manifest_file, 'application/zip')}
params = {}
if 'repository_url' in module.foreman_params:
params['repository_url'] = module.foreman_params['repository_url']
params.update(scope)
result = module.resource_action('subscriptions', 'upload', params, files=files, record_change=False, ignore_task_errors=True)
for error in result['humanized']['errors']:
if "same as existing data" in error:
# Nothing changed, but everything ok
break
if "older than existing data" in error:
module.fail_json(msg="Manifest is older than existing data.")
else:
module.fail_json(msg="Upload of the manifest failed: %s" % error)
else:
module.set_changed()
except IOError as e:
module.fail_json(msg="Unable to read the manifest file: %s" % e)
elif module.desired_absent and existing_manifest:
module.resource_action('subscriptions', 'delete_manifest', scope)
elif module.state == 'refreshed':
if existing_manifest:
<|fim_middle|>
else:
module.fail_json(msg="No manifest found to refresh.")
if __name__ == '__main__':
main()
<|fim▁end|> | module.resource_action('subscriptions', 'refresh_manifest', scope) |
<|file_name|>subscription_manifest.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Andrew Kofink <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: subscription_manifest
version_added: 1.0.0
short_description: Manage Subscription Manifests
description:
- Upload, refresh and delete Subscription Manifests
author: "Andrew Kofink (@akofink)"
options:
manifest_path:
description:
- Path to the manifest zip file
- This parameter will be ignored if I(state=absent) or I(state=refreshed)
type: path
state:
description:
- The state of the manifest
default: present
choices:
- absent
- present
- refreshed
type: str
repository_url:
description:
- URL to retrieve content from
aliases: [ redhat_repository_url ]
type: str
extends_documentation_fragment:
- theforeman.foreman.foreman
- theforeman.foreman.foreman.organization
'''
EXAMPLES = '''
- name: "Upload the RHEL developer edition manifest"
theforeman.foreman.subscription_manifest:
username: "admin"
password: "changeme"
server_url: "https://foreman.example.com"
organization: "Default Organization"
state: present
manifest_path: "/tmp/manifest.zip"
'''
RETURN = ''' # '''
from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule
def main():
module = KatelloEntityAnsibleModule(
argument_spec=dict(
manifest_path=dict(type='path'),
state=dict(default='present', choices=['absent', 'present', 'refreshed']),
repository_url=dict(aliases=['redhat_repository_url']),
),
foreman_spec=dict(
organization=dict(type='entity', required=True, thin=False),
),
required_if=[
['state', 'present', ['manifest_path']],
],
supports_check_mode=False,
)
module.task_timeout = 5 * 60
with module.api_connection():
organization = module.lookup_entity('organization')
scope = module.scope_for('organization')
try:
existing_manifest = organization['owner_details']['upstreamConsumer']
except KeyError:
existing_manifest = None
if module.state == 'present':
if 'repository_url' in module.foreman_params:
payload = {'redhat_repository_url': module.foreman_params['repository_url']}
org_spec = dict(id=dict(), redhat_repository_url=dict())
organization = module.ensure_entity('organizations', payload, organization, state='present', foreman_spec=org_spec)
try:
with open(module.foreman_params['manifest_path'], 'rb') as manifest_file:
files = {'content': (module.foreman_params['manifest_path'], manifest_file, 'application/zip')}
params = {}
if 'repository_url' in module.foreman_params:
params['repository_url'] = module.foreman_params['repository_url']
params.update(scope)
result = module.resource_action('subscriptions', 'upload', params, files=files, record_change=False, ignore_task_errors=True)
for error in result['humanized']['errors']:
if "same as existing data" in error:
# Nothing changed, but everything ok
break
if "older than existing data" in error:
module.fail_json(msg="Manifest is older than existing data.")
else:
module.fail_json(msg="Upload of the manifest failed: %s" % error)
else:
module.set_changed()
except IOError as e:
module.fail_json(msg="Unable to read the manifest file: %s" % e)
elif module.desired_absent and existing_manifest:
module.resource_action('subscriptions', 'delete_manifest', scope)
elif module.state == 'refreshed':
if existing_manifest:
module.resource_action('subscriptions', 'refresh_manifest', scope)
else:
<|fim_middle|>
if __name__ == '__main__':
main()
<|fim▁end|> | module.fail_json(msg="No manifest found to refresh.") |
<|file_name|>subscription_manifest.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Andrew Kofink <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: subscription_manifest
version_added: 1.0.0
short_description: Manage Subscription Manifests
description:
- Upload, refresh and delete Subscription Manifests
author: "Andrew Kofink (@akofink)"
options:
manifest_path:
description:
- Path to the manifest zip file
- This parameter will be ignored if I(state=absent) or I(state=refreshed)
type: path
state:
description:
- The state of the manifest
default: present
choices:
- absent
- present
- refreshed
type: str
repository_url:
description:
- URL to retrieve content from
aliases: [ redhat_repository_url ]
type: str
extends_documentation_fragment:
- theforeman.foreman.foreman
- theforeman.foreman.foreman.organization
'''
EXAMPLES = '''
- name: "Upload the RHEL developer edition manifest"
theforeman.foreman.subscription_manifest:
username: "admin"
password: "changeme"
server_url: "https://foreman.example.com"
organization: "Default Organization"
state: present
manifest_path: "/tmp/manifest.zip"
'''
RETURN = ''' # '''
from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule
def main():
module = KatelloEntityAnsibleModule(
argument_spec=dict(
manifest_path=dict(type='path'),
state=dict(default='present', choices=['absent', 'present', 'refreshed']),
repository_url=dict(aliases=['redhat_repository_url']),
),
foreman_spec=dict(
organization=dict(type='entity', required=True, thin=False),
),
required_if=[
['state', 'present', ['manifest_path']],
],
supports_check_mode=False,
)
module.task_timeout = 5 * 60
with module.api_connection():
organization = module.lookup_entity('organization')
scope = module.scope_for('organization')
try:
existing_manifest = organization['owner_details']['upstreamConsumer']
except KeyError:
existing_manifest = None
if module.state == 'present':
if 'repository_url' in module.foreman_params:
payload = {'redhat_repository_url': module.foreman_params['repository_url']}
org_spec = dict(id=dict(), redhat_repository_url=dict())
organization = module.ensure_entity('organizations', payload, organization, state='present', foreman_spec=org_spec)
try:
with open(module.foreman_params['manifest_path'], 'rb') as manifest_file:
files = {'content': (module.foreman_params['manifest_path'], manifest_file, 'application/zip')}
params = {}
if 'repository_url' in module.foreman_params:
params['repository_url'] = module.foreman_params['repository_url']
params.update(scope)
result = module.resource_action('subscriptions', 'upload', params, files=files, record_change=False, ignore_task_errors=True)
for error in result['humanized']['errors']:
if "same as existing data" in error:
# Nothing changed, but everything ok
break
if "older than existing data" in error:
module.fail_json(msg="Manifest is older than existing data.")
else:
module.fail_json(msg="Upload of the manifest failed: %s" % error)
else:
module.set_changed()
except IOError as e:
module.fail_json(msg="Unable to read the manifest file: %s" % e)
elif module.desired_absent and existing_manifest:
module.resource_action('subscriptions', 'delete_manifest', scope)
elif module.state == 'refreshed':
if existing_manifest:
module.resource_action('subscriptions', 'refresh_manifest', scope)
else:
module.fail_json(msg="No manifest found to refresh.")
if __name__ == '__main__':
<|fim_middle|>
<|fim▁end|> | main() |
<|file_name|>subscription_manifest.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Andrew Kofink <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: subscription_manifest
version_added: 1.0.0
short_description: Manage Subscription Manifests
description:
- Upload, refresh and delete Subscription Manifests
author: "Andrew Kofink (@akofink)"
options:
manifest_path:
description:
- Path to the manifest zip file
- This parameter will be ignored if I(state=absent) or I(state=refreshed)
type: path
state:
description:
- The state of the manifest
default: present
choices:
- absent
- present
- refreshed
type: str
repository_url:
description:
- URL to retrieve content from
aliases: [ redhat_repository_url ]
type: str
extends_documentation_fragment:
- theforeman.foreman.foreman
- theforeman.foreman.foreman.organization
'''
EXAMPLES = '''
- name: "Upload the RHEL developer edition manifest"
theforeman.foreman.subscription_manifest:
username: "admin"
password: "changeme"
server_url: "https://foreman.example.com"
organization: "Default Organization"
state: present
manifest_path: "/tmp/manifest.zip"
'''
RETURN = ''' # '''
from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule
def <|fim_middle|>():
module = KatelloEntityAnsibleModule(
argument_spec=dict(
manifest_path=dict(type='path'),
state=dict(default='present', choices=['absent', 'present', 'refreshed']),
repository_url=dict(aliases=['redhat_repository_url']),
),
foreman_spec=dict(
organization=dict(type='entity', required=True, thin=False),
),
required_if=[
['state', 'present', ['manifest_path']],
],
supports_check_mode=False,
)
module.task_timeout = 5 * 60
with module.api_connection():
organization = module.lookup_entity('organization')
scope = module.scope_for('organization')
try:
existing_manifest = organization['owner_details']['upstreamConsumer']
except KeyError:
existing_manifest = None
if module.state == 'present':
if 'repository_url' in module.foreman_params:
payload = {'redhat_repository_url': module.foreman_params['repository_url']}
org_spec = dict(id=dict(), redhat_repository_url=dict())
organization = module.ensure_entity('organizations', payload, organization, state='present', foreman_spec=org_spec)
try:
with open(module.foreman_params['manifest_path'], 'rb') as manifest_file:
files = {'content': (module.foreman_params['manifest_path'], manifest_file, 'application/zip')}
params = {}
if 'repository_url' in module.foreman_params:
params['repository_url'] = module.foreman_params['repository_url']
params.update(scope)
result = module.resource_action('subscriptions', 'upload', params, files=files, record_change=False, ignore_task_errors=True)
for error in result['humanized']['errors']:
if "same as existing data" in error:
# Nothing changed, but everything ok
break
if "older than existing data" in error:
module.fail_json(msg="Manifest is older than existing data.")
else:
module.fail_json(msg="Upload of the manifest failed: %s" % error)
else:
module.set_changed()
except IOError as e:
module.fail_json(msg="Unable to read the manifest file: %s" % e)
elif module.desired_absent and existing_manifest:
module.resource_action('subscriptions', 'delete_manifest', scope)
elif module.state == 'refreshed':
if existing_manifest:
module.resource_action('subscriptions', 'refresh_manifest', scope)
else:
module.fail_json(msg="No manifest found to refresh.")
if __name__ == '__main__':
main()
<|fim▁end|> | main |
<|file_name|>server.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
"""
from datetime import datetime, timedelta
import os
from flask import request
from flask import Flask
import pytz
import db
from utils import get_remote_addr, get_location_data<|fim▁hole|>
app = Flask(__name__)
@app.route('/yo-water/', methods=['POST', 'GET'])
def yowater():
payload = request.args if request.args else request.get_json(force=True)
username = payload.get('username')
reminder = db.reminders.find_one({'username': username})
reply_object = payload.get('reply')
if reply_object is None:
if db.reminders.find_one({'username': username}) is None:
address = get_remote_addr(request)
data = get_location_data(address)
if not data:
return 'Timezone needed'
user_data = {'created': datetime.now(pytz.utc),
'username': username}
if data.get('time_zone'):
user_data.update({'timezone': data.get('time_zone')})
db.reminders.insert(user_data)
return 'OK'
else:
reply_text = reply_object.get('text')
if reply_text == u'Can\'t right now 😖':
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=15)
else:
reminder['step'] += 1
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=60)
reminder['last_reply_date'] = datetime.now(pytz.utc)
db.reminders.update({'username': username},
reminder)
db.replies.insert({'username': username,
'created': datetime.now(pytz.utc),
'reply': reply_text})
return 'OK'
if __name__ == "__main__":
app.debug = True
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000")))<|fim▁end|> | |
<|file_name|>server.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
"""
from datetime import datetime, timedelta
import os
from flask import request
from flask import Flask
import pytz
import db
from utils import get_remote_addr, get_location_data
app = Flask(__name__)
@app.route('/yo-water/', methods=['POST', 'GET'])
def yowater():
<|fim_middle|>
if __name__ == "__main__":
app.debug = True
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000")))
<|fim▁end|> | payload = request.args if request.args else request.get_json(force=True)
username = payload.get('username')
reminder = db.reminders.find_one({'username': username})
reply_object = payload.get('reply')
if reply_object is None:
if db.reminders.find_one({'username': username}) is None:
address = get_remote_addr(request)
data = get_location_data(address)
if not data:
return 'Timezone needed'
user_data = {'created': datetime.now(pytz.utc),
'username': username}
if data.get('time_zone'):
user_data.update({'timezone': data.get('time_zone')})
db.reminders.insert(user_data)
return 'OK'
else:
reply_text = reply_object.get('text')
if reply_text == u'Can\'t right now 😖':
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=15)
else:
reminder['step'] += 1
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=60)
reminder['last_reply_date'] = datetime.now(pytz.utc)
db.reminders.update({'username': username},
reminder)
db.replies.insert({'username': username,
'created': datetime.now(pytz.utc),
'reply': reply_text})
return 'OK'
|
<|file_name|>server.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
"""
from datetime import datetime, timedelta
import os
from flask import request
from flask import Flask
import pytz
import db
from utils import get_remote_addr, get_location_data
app = Flask(__name__)
@app.route('/yo-water/', methods=['POST', 'GET'])
def yowater():
payload = request.args if request.args else request.get_json(force=True)
username = payload.get('username')
reminder = db.reminders.find_one({'username': username})
reply_object = payload.get('reply')
if reply_object is None:
<|fim_middle|>
else:
reply_text = reply_object.get('text')
if reply_text == u'Can\'t right now 😖':
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=15)
else:
reminder['step'] += 1
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=60)
reminder['last_reply_date'] = datetime.now(pytz.utc)
db.reminders.update({'username': username},
reminder)
db.replies.insert({'username': username,
'created': datetime.now(pytz.utc),
'reply': reply_text})
return 'OK'
if __name__ == "__main__":
app.debug = True
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000")))
<|fim▁end|> | if db.reminders.find_one({'username': username}) is None:
address = get_remote_addr(request)
data = get_location_data(address)
if not data:
return 'Timezone needed'
user_data = {'created': datetime.now(pytz.utc),
'username': username}
if data.get('time_zone'):
user_data.update({'timezone': data.get('time_zone')})
db.reminders.insert(user_data)
return 'OK' |
<|file_name|>server.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
"""
from datetime import datetime, timedelta
import os
from flask import request
from flask import Flask
import pytz
import db
from utils import get_remote_addr, get_location_data
app = Flask(__name__)
@app.route('/yo-water/', methods=['POST', 'GET'])
def yowater():
payload = request.args if request.args else request.get_json(force=True)
username = payload.get('username')
reminder = db.reminders.find_one({'username': username})
reply_object = payload.get('reply')
if reply_object is None:
if db.reminders.find_one({'username': username}) is None:
<|fim_middle|>
else:
reply_text = reply_object.get('text')
if reply_text == u'Can\'t right now 😖':
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=15)
else:
reminder['step'] += 1
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=60)
reminder['last_reply_date'] = datetime.now(pytz.utc)
db.reminders.update({'username': username},
reminder)
db.replies.insert({'username': username,
'created': datetime.now(pytz.utc),
'reply': reply_text})
return 'OK'
if __name__ == "__main__":
app.debug = True
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000")))
<|fim▁end|> | address = get_remote_addr(request)
data = get_location_data(address)
if not data:
return 'Timezone needed'
user_data = {'created': datetime.now(pytz.utc),
'username': username}
if data.get('time_zone'):
user_data.update({'timezone': data.get('time_zone')})
db.reminders.insert(user_data)
return 'OK' |
<|file_name|>server.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
"""
from datetime import datetime, timedelta
import os
from flask import request
from flask import Flask
import pytz
import db
from utils import get_remote_addr, get_location_data
app = Flask(__name__)
@app.route('/yo-water/', methods=['POST', 'GET'])
def yowater():
payload = request.args if request.args else request.get_json(force=True)
username = payload.get('username')
reminder = db.reminders.find_one({'username': username})
reply_object = payload.get('reply')
if reply_object is None:
if db.reminders.find_one({'username': username}) is None:
address = get_remote_addr(request)
data = get_location_data(address)
if not data:
<|fim_middle|>
user_data = {'created': datetime.now(pytz.utc),
'username': username}
if data.get('time_zone'):
user_data.update({'timezone': data.get('time_zone')})
db.reminders.insert(user_data)
return 'OK'
else:
reply_text = reply_object.get('text')
if reply_text == u'Can\'t right now 😖':
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=15)
else:
reminder['step'] += 1
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=60)
reminder['last_reply_date'] = datetime.now(pytz.utc)
db.reminders.update({'username': username},
reminder)
db.replies.insert({'username': username,
'created': datetime.now(pytz.utc),
'reply': reply_text})
return 'OK'
if __name__ == "__main__":
app.debug = True
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000")))
<|fim▁end|> | return 'Timezone needed' |
<|file_name|>server.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
"""
from datetime import datetime, timedelta
import os
from flask import request
from flask import Flask
import pytz
import db
from utils import get_remote_addr, get_location_data
app = Flask(__name__)
@app.route('/yo-water/', methods=['POST', 'GET'])
def yowater():
payload = request.args if request.args else request.get_json(force=True)
username = payload.get('username')
reminder = db.reminders.find_one({'username': username})
reply_object = payload.get('reply')
if reply_object is None:
if db.reminders.find_one({'username': username}) is None:
address = get_remote_addr(request)
data = get_location_data(address)
if not data:
return 'Timezone needed'
user_data = {'created': datetime.now(pytz.utc),
'username': username}
if data.get('time_zone'):
<|fim_middle|>
db.reminders.insert(user_data)
return 'OK'
else:
reply_text = reply_object.get('text')
if reply_text == u'Can\'t right now 😖':
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=15)
else:
reminder['step'] += 1
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=60)
reminder['last_reply_date'] = datetime.now(pytz.utc)
db.reminders.update({'username': username},
reminder)
db.replies.insert({'username': username,
'created': datetime.now(pytz.utc),
'reply': reply_text})
return 'OK'
if __name__ == "__main__":
app.debug = True
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000")))
<|fim▁end|> | user_data.update({'timezone': data.get('time_zone')}) |
<|file_name|>server.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
"""
from datetime import datetime, timedelta
import os
from flask import request
from flask import Flask
import pytz
import db
from utils import get_remote_addr, get_location_data
app = Flask(__name__)
@app.route('/yo-water/', methods=['POST', 'GET'])
def yowater():
payload = request.args if request.args else request.get_json(force=True)
username = payload.get('username')
reminder = db.reminders.find_one({'username': username})
reply_object = payload.get('reply')
if reply_object is None:
if db.reminders.find_one({'username': username}) is None:
address = get_remote_addr(request)
data = get_location_data(address)
if not data:
return 'Timezone needed'
user_data = {'created': datetime.now(pytz.utc),
'username': username}
if data.get('time_zone'):
user_data.update({'timezone': data.get('time_zone')})
db.reminders.insert(user_data)
return 'OK'
else:
<|fim_middle|>
if __name__ == "__main__":
app.debug = True
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000")))
<|fim▁end|> | reply_text = reply_object.get('text')
if reply_text == u'Can\'t right now 😖':
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=15)
else:
reminder['step'] += 1
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=60)
reminder['last_reply_date'] = datetime.now(pytz.utc)
db.reminders.update({'username': username},
reminder)
db.replies.insert({'username': username,
'created': datetime.now(pytz.utc),
'reply': reply_text})
return 'OK'
|
<|file_name|>server.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
"""
from datetime import datetime, timedelta
import os
from flask import request
from flask import Flask
import pytz
import db
from utils import get_remote_addr, get_location_data
app = Flask(__name__)
@app.route('/yo-water/', methods=['POST', 'GET'])
def yowater():
payload = request.args if request.args else request.get_json(force=True)
username = payload.get('username')
reminder = db.reminders.find_one({'username': username})
reply_object = payload.get('reply')
if reply_object is None:
if db.reminders.find_one({'username': username}) is None:
address = get_remote_addr(request)
data = get_location_data(address)
if not data:
return 'Timezone needed'
user_data = {'created': datetime.now(pytz.utc),
'username': username}
if data.get('time_zone'):
user_data.update({'timezone': data.get('time_zone')})
db.reminders.insert(user_data)
return 'OK'
else:
reply_text = reply_object.get('text')
if reply_text == u'Can\'t right now 😖':
rem <|fim_middle|>
else:
reminder['step'] += 1
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=60)
reminder['last_reply_date'] = datetime.now(pytz.utc)
db.reminders.update({'username': username},
reminder)
db.replies.insert({'username': username,
'created': datetime.now(pytz.utc),
'reply': reply_text})
return 'OK'
if __name__ == "__main__":
app.debug = True
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000")))
<|fim▁end|> | inder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=15)
|
<|file_name|>server.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
"""
from datetime import datetime, timedelta
import os
from flask import request
from flask import Flask
import pytz
import db
from utils import get_remote_addr, get_location_data
app = Flask(__name__)
@app.route('/yo-water/', methods=['POST', 'GET'])
def yowater():
payload = request.args if request.args else request.get_json(force=True)
username = payload.get('username')
reminder = db.reminders.find_one({'username': username})
reply_object = payload.get('reply')
if reply_object is None:
if db.reminders.find_one({'username': username}) is None:
address = get_remote_addr(request)
data = get_location_data(address)
if not data:
return 'Timezone needed'
user_data = {'created': datetime.now(pytz.utc),
'username': username}
if data.get('time_zone'):
user_data.update({'timezone': data.get('time_zone')})
db.reminders.insert(user_data)
return 'OK'
else:
reply_text = reply_object.get('text')
if reply_text == u'Can\'t right now 😖':
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=15)
else:
rem <|fim_middle|>
reminder['last_reply_date'] = datetime.now(pytz.utc)
db.reminders.update({'username': username},
reminder)
db.replies.insert({'username': username,
'created': datetime.now(pytz.utc),
'reply': reply_text})
return 'OK'
if __name__ == "__main__":
app.debug = True
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000")))
<|fim▁end|> | inder['step'] += 1
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=60)
|
<|file_name|>server.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
"""
from datetime import datetime, timedelta
import os
from flask import request
from flask import Flask
import pytz
import db
from utils import get_remote_addr, get_location_data
app = Flask(__name__)
@app.route('/yo-water/', methods=['POST', 'GET'])
def yowater():
payload = request.args if request.args else request.get_json(force=True)
username = payload.get('username')
reminder = db.reminders.find_one({'username': username})
reply_object = payload.get('reply')
if reply_object is None:
if db.reminders.find_one({'username': username}) is None:
address = get_remote_addr(request)
data = get_location_data(address)
if not data:
return 'Timezone needed'
user_data = {'created': datetime.now(pytz.utc),
'username': username}
if data.get('time_zone'):
user_data.update({'timezone': data.get('time_zone')})
db.reminders.insert(user_data)
return 'OK'
else:
reply_text = reply_object.get('text')
if reply_text == u'Can\'t right now 😖':
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=15)
else:
reminder['step'] += 1
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=60)
reminder['last_reply_date'] = datetime.now(pytz.utc)
db.reminders.update({'username': username},
reminder)
db.replies.insert({'username': username,
'created': datetime.now(pytz.utc),
'reply': reply_text})
return 'OK'
if __name__ == "__main__":
app <|fim_middle|>
<|fim▁end|> | .debug = True
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000")))
|
<|file_name|>server.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
"""
from datetime import datetime, timedelta
import os
from flask import request
from flask import Flask
import pytz
import db
from utils import get_remote_addr, get_location_data
app = Flask(__name__)
@app.route('/yo-water/', methods=['POST', 'GET'])
def <|fim_middle|>():
payload = request.args if request.args else request.get_json(force=True)
username = payload.get('username')
reminder = db.reminders.find_one({'username': username})
reply_object = payload.get('reply')
if reply_object is None:
if db.reminders.find_one({'username': username}) is None:
address = get_remote_addr(request)
data = get_location_data(address)
if not data:
return 'Timezone needed'
user_data = {'created': datetime.now(pytz.utc),
'username': username}
if data.get('time_zone'):
user_data.update({'timezone': data.get('time_zone')})
db.reminders.insert(user_data)
return 'OK'
else:
reply_text = reply_object.get('text')
if reply_text == u'Can\'t right now 😖':
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=15)
else:
reminder['step'] += 1
reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=60)
reminder['last_reply_date'] = datetime.now(pytz.utc)
db.reminders.update({'username': username},
reminder)
db.replies.insert({'username': username,
'created': datetime.now(pytz.utc),
'reply': reply_text})
return 'OK'
if __name__ == "__main__":
app.debug = True
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000")))
<|fim▁end|> | yowater |
<|file_name|>discover.py<|end_file_name|><|fim▁begin|><|fim▁hole|>
import soco
""" Prints the name of each discovered player in the network. """
for zone in soco.discover():
print(zone.player_name)<|fim▁end|> | from __future__ import print_function |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date<|fim▁hole|>class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0<|fim▁end|> | |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
<|fim_middle|>
<|fim▁end|> | """
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0 |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
<|fim_middle|>
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0
<|fim▁end|> | TodoBase.__init__(self, p_str)
self.attributes = {} |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
<|fim_middle|>
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0
<|fim▁end|> | """ Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
<|fim_middle|>
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0
<|fim▁end|> | """ Returns a date object of the todo's start date. """
return self.get_date(config().tag_start()) |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
<|fim_middle|>
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0
<|fim▁end|> | """ Returns a date object of the todo's due date. """
return self.get_date(config().tag_due()) |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
<|fim_middle|>
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0
<|fim▁end|> | """
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today()) |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
<|fim_middle|>
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0
<|fim▁end|> | """
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0 |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
<|fim_middle|>
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0
<|fim▁end|> | """
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0 |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
<|fim_middle|>
<|fim▁end|> | """
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0 |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
<|fim_middle|>
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0
<|fim▁end|> | diff = due - date.today()
return diff.days |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
<|fim_middle|>
else:
return 0
<|fim▁end|> | diff = due - start
return diff.days |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
<|fim_middle|>
<|fim▁end|> | return 0 |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def <|fim_middle|>(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0
<|fim▁end|> | __init__ |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def <|fim_middle|>(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0
<|fim▁end|> | get_date |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def <|fim_middle|>(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0
<|fim▁end|> | start_date |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def <|fim_middle|>(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0
<|fim▁end|> | due_date |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def <|fim_middle|>(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0
<|fim▁end|> | is_active |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def <|fim_middle|>(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0
<|fim▁end|> | is_overdue |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def <|fim_middle|>(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0
<|fim▁end|> | days_till_due |
<|file_name|>Todo.py<|end_file_name|><|fim▁begin|># Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def <|fim_middle|>(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0
<|fim▁end|> | length |
<|file_name|>ch4_ex4.1.4.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Created by Samvel Khalatyan on Mar 23, 2014
# Copyright (c) 2014 Samvel Khalatyan. All rights reserved
#
# Use of this source code is governed by a license that can be found in
# the LICENSE file.
import random
import unittest
from lib import unigraph
class UnigraphExtra(unigraph.Unigraph):
def has_edge(self, left_vertex, right_vertex):
if left_vertex == right_vertex:
return True
else:
return right_vertex in self._vertices[left_vertex]
class UnigraphEdgeTestCase(unittest.TestCase):
def setUp(self):
self.graph = UnigraphExtra(random.randrange(10, 15))
for edge in range(2 * self.graph.vertices()):
f, t = (random.randrange(self.graph.vertices()) for x in range(2))
self.graph.add_edge(f, t)
def test_edge(self):
for vertex in range(self.graph.vertices()):
existing_vertices = set(self.graph._vertices[vertex])
all_vertices = set(range(self.graph.vertices()))
missing_vertices = all_vertices - all_vertices
for adj_vertex in existing_vertices:
self.assertTrue(self.graph.has_edge(vertex, adj_vertex))
for adj_vertex in missing_vertices:
self.assertFalse(self.graph.has_edge(vertex, adj_vertex))
def test_self_loop(self):
for vertex in range(self.graph.vertices()):
self.assertTrue(self.graph.has_edge(vertex, vertex))
<|fim▁hole|> unittest.main()<|fim▁end|> | if "__main__" == __name__: |
<|file_name|>ch4_ex4.1.4.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Created by Samvel Khalatyan on Mar 23, 2014
# Copyright (c) 2014 Samvel Khalatyan. All rights reserved
#
# Use of this source code is governed by a license that can be found in
# the LICENSE file.
import random
import unittest
from lib import unigraph
class UnigraphExtra(unigraph.Unigraph):
<|fim_middle|>
class UnigraphEdgeTestCase(unittest.TestCase):
def setUp(self):
self.graph = UnigraphExtra(random.randrange(10, 15))
for edge in range(2 * self.graph.vertices()):
f, t = (random.randrange(self.graph.vertices()) for x in range(2))
self.graph.add_edge(f, t)
def test_edge(self):
for vertex in range(self.graph.vertices()):
existing_vertices = set(self.graph._vertices[vertex])
all_vertices = set(range(self.graph.vertices()))
missing_vertices = all_vertices - all_vertices
for adj_vertex in existing_vertices:
self.assertTrue(self.graph.has_edge(vertex, adj_vertex))
for adj_vertex in missing_vertices:
self.assertFalse(self.graph.has_edge(vertex, adj_vertex))
def test_self_loop(self):
for vertex in range(self.graph.vertices()):
self.assertTrue(self.graph.has_edge(vertex, vertex))
if "__main__" == __name__:
unittest.main()
<|fim▁end|> | def has_edge(self, left_vertex, right_vertex):
if left_vertex == right_vertex:
return True
else:
return right_vertex in self._vertices[left_vertex] |
<|file_name|>ch4_ex4.1.4.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Created by Samvel Khalatyan on Mar 23, 2014
# Copyright (c) 2014 Samvel Khalatyan. All rights reserved
#
# Use of this source code is governed by a license that can be found in
# the LICENSE file.
import random
import unittest
from lib import unigraph
class UnigraphExtra(unigraph.Unigraph):
def has_edge(self, left_vertex, right_vertex):
<|fim_middle|>
class UnigraphEdgeTestCase(unittest.TestCase):
def setUp(self):
self.graph = UnigraphExtra(random.randrange(10, 15))
for edge in range(2 * self.graph.vertices()):
f, t = (random.randrange(self.graph.vertices()) for x in range(2))
self.graph.add_edge(f, t)
def test_edge(self):
for vertex in range(self.graph.vertices()):
existing_vertices = set(self.graph._vertices[vertex])
all_vertices = set(range(self.graph.vertices()))
missing_vertices = all_vertices - all_vertices
for adj_vertex in existing_vertices:
self.assertTrue(self.graph.has_edge(vertex, adj_vertex))
for adj_vertex in missing_vertices:
self.assertFalse(self.graph.has_edge(vertex, adj_vertex))
def test_self_loop(self):
for vertex in range(self.graph.vertices()):
self.assertTrue(self.graph.has_edge(vertex, vertex))
if "__main__" == __name__:
unittest.main()
<|fim▁end|> | if left_vertex == right_vertex:
return True
else:
return right_vertex in self._vertices[left_vertex] |
<|file_name|>ch4_ex4.1.4.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Created by Samvel Khalatyan on Mar 23, 2014
# Copyright (c) 2014 Samvel Khalatyan. All rights reserved
#
# Use of this source code is governed by a license that can be found in
# the LICENSE file.
import random
import unittest
from lib import unigraph
class UnigraphExtra(unigraph.Unigraph):
def has_edge(self, left_vertex, right_vertex):
if left_vertex == right_vertex:
return True
else:
return right_vertex in self._vertices[left_vertex]
class UnigraphEdgeTestCase(unittest.TestCase):
<|fim_middle|>
if "__main__" == __name__:
unittest.main()
<|fim▁end|> | def setUp(self):
self.graph = UnigraphExtra(random.randrange(10, 15))
for edge in range(2 * self.graph.vertices()):
f, t = (random.randrange(self.graph.vertices()) for x in range(2))
self.graph.add_edge(f, t)
def test_edge(self):
for vertex in range(self.graph.vertices()):
existing_vertices = set(self.graph._vertices[vertex])
all_vertices = set(range(self.graph.vertices()))
missing_vertices = all_vertices - all_vertices
for adj_vertex in existing_vertices:
self.assertTrue(self.graph.has_edge(vertex, adj_vertex))
for adj_vertex in missing_vertices:
self.assertFalse(self.graph.has_edge(vertex, adj_vertex))
def test_self_loop(self):
for vertex in range(self.graph.vertices()):
self.assertTrue(self.graph.has_edge(vertex, vertex)) |
<|file_name|>ch4_ex4.1.4.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Created by Samvel Khalatyan on Mar 23, 2014
# Copyright (c) 2014 Samvel Khalatyan. All rights reserved
#
# Use of this source code is governed by a license that can be found in
# the LICENSE file.
import random
import unittest
from lib import unigraph
class UnigraphExtra(unigraph.Unigraph):
def has_edge(self, left_vertex, right_vertex):
if left_vertex == right_vertex:
return True
else:
return right_vertex in self._vertices[left_vertex]
class UnigraphEdgeTestCase(unittest.TestCase):
def setUp(self):
<|fim_middle|>
def test_edge(self):
for vertex in range(self.graph.vertices()):
existing_vertices = set(self.graph._vertices[vertex])
all_vertices = set(range(self.graph.vertices()))
missing_vertices = all_vertices - all_vertices
for adj_vertex in existing_vertices:
self.assertTrue(self.graph.has_edge(vertex, adj_vertex))
for adj_vertex in missing_vertices:
self.assertFalse(self.graph.has_edge(vertex, adj_vertex))
def test_self_loop(self):
for vertex in range(self.graph.vertices()):
self.assertTrue(self.graph.has_edge(vertex, vertex))
if "__main__" == __name__:
unittest.main()
<|fim▁end|> | self.graph = UnigraphExtra(random.randrange(10, 15))
for edge in range(2 * self.graph.vertices()):
f, t = (random.randrange(self.graph.vertices()) for x in range(2))
self.graph.add_edge(f, t) |
<|file_name|>ch4_ex4.1.4.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Created by Samvel Khalatyan on Mar 23, 2014
# Copyright (c) 2014 Samvel Khalatyan. All rights reserved
#
# Use of this source code is governed by a license that can be found in
# the LICENSE file.
import random
import unittest
from lib import unigraph
class UnigraphExtra(unigraph.Unigraph):
def has_edge(self, left_vertex, right_vertex):
if left_vertex == right_vertex:
return True
else:
return right_vertex in self._vertices[left_vertex]
class UnigraphEdgeTestCase(unittest.TestCase):
def setUp(self):
self.graph = UnigraphExtra(random.randrange(10, 15))
for edge in range(2 * self.graph.vertices()):
f, t = (random.randrange(self.graph.vertices()) for x in range(2))
self.graph.add_edge(f, t)
def test_edge(self):
<|fim_middle|>
def test_self_loop(self):
for vertex in range(self.graph.vertices()):
self.assertTrue(self.graph.has_edge(vertex, vertex))
if "__main__" == __name__:
unittest.main()
<|fim▁end|> | for vertex in range(self.graph.vertices()):
existing_vertices = set(self.graph._vertices[vertex])
all_vertices = set(range(self.graph.vertices()))
missing_vertices = all_vertices - all_vertices
for adj_vertex in existing_vertices:
self.assertTrue(self.graph.has_edge(vertex, adj_vertex))
for adj_vertex in missing_vertices:
self.assertFalse(self.graph.has_edge(vertex, adj_vertex)) |
<|file_name|>ch4_ex4.1.4.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Created by Samvel Khalatyan on Mar 23, 2014
# Copyright (c) 2014 Samvel Khalatyan. All rights reserved
#
# Use of this source code is governed by a license that can be found in
# the LICENSE file.
import random
import unittest
from lib import unigraph
class UnigraphExtra(unigraph.Unigraph):
def has_edge(self, left_vertex, right_vertex):
if left_vertex == right_vertex:
return True
else:
return right_vertex in self._vertices[left_vertex]
class UnigraphEdgeTestCase(unittest.TestCase):
def setUp(self):
self.graph = UnigraphExtra(random.randrange(10, 15))
for edge in range(2 * self.graph.vertices()):
f, t = (random.randrange(self.graph.vertices()) for x in range(2))
self.graph.add_edge(f, t)
def test_edge(self):
for vertex in range(self.graph.vertices()):
existing_vertices = set(self.graph._vertices[vertex])
all_vertices = set(range(self.graph.vertices()))
missing_vertices = all_vertices - all_vertices
for adj_vertex in existing_vertices:
self.assertTrue(self.graph.has_edge(vertex, adj_vertex))
for adj_vertex in missing_vertices:
self.assertFalse(self.graph.has_edge(vertex, adj_vertex))
def test_self_loop(self):
<|fim_middle|>
if "__main__" == __name__:
unittest.main()
<|fim▁end|> | for vertex in range(self.graph.vertices()):
self.assertTrue(self.graph.has_edge(vertex, vertex)) |
<|file_name|>ch4_ex4.1.4.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Created by Samvel Khalatyan on Mar 23, 2014
# Copyright (c) 2014 Samvel Khalatyan. All rights reserved
#
# Use of this source code is governed by a license that can be found in
# the LICENSE file.
import random
import unittest
from lib import unigraph
class UnigraphExtra(unigraph.Unigraph):
def has_edge(self, left_vertex, right_vertex):
if left_vertex == right_vertex:
<|fim_middle|>
else:
return right_vertex in self._vertices[left_vertex]
class UnigraphEdgeTestCase(unittest.TestCase):
def setUp(self):
self.graph = UnigraphExtra(random.randrange(10, 15))
for edge in range(2 * self.graph.vertices()):
f, t = (random.randrange(self.graph.vertices()) for x in range(2))
self.graph.add_edge(f, t)
def test_edge(self):
for vertex in range(self.graph.vertices()):
existing_vertices = set(self.graph._vertices[vertex])
all_vertices = set(range(self.graph.vertices()))
missing_vertices = all_vertices - all_vertices
for adj_vertex in existing_vertices:
self.assertTrue(self.graph.has_edge(vertex, adj_vertex))
for adj_vertex in missing_vertices:
self.assertFalse(self.graph.has_edge(vertex, adj_vertex))
def test_self_loop(self):
for vertex in range(self.graph.vertices()):
self.assertTrue(self.graph.has_edge(vertex, vertex))
if "__main__" == __name__:
unittest.main()
<|fim▁end|> | return True |
<|file_name|>ch4_ex4.1.4.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Created by Samvel Khalatyan on Mar 23, 2014
# Copyright (c) 2014 Samvel Khalatyan. All rights reserved
#
# Use of this source code is governed by a license that can be found in
# the LICENSE file.
import random
import unittest
from lib import unigraph
class UnigraphExtra(unigraph.Unigraph):
def has_edge(self, left_vertex, right_vertex):
if left_vertex == right_vertex:
return True
else:
<|fim_middle|>
class UnigraphEdgeTestCase(unittest.TestCase):
def setUp(self):
self.graph = UnigraphExtra(random.randrange(10, 15))
for edge in range(2 * self.graph.vertices()):
f, t = (random.randrange(self.graph.vertices()) for x in range(2))
self.graph.add_edge(f, t)
def test_edge(self):
for vertex in range(self.graph.vertices()):
existing_vertices = set(self.graph._vertices[vertex])
all_vertices = set(range(self.graph.vertices()))
missing_vertices = all_vertices - all_vertices
for adj_vertex in existing_vertices:
self.assertTrue(self.graph.has_edge(vertex, adj_vertex))
for adj_vertex in missing_vertices:
self.assertFalse(self.graph.has_edge(vertex, adj_vertex))
def test_self_loop(self):
for vertex in range(self.graph.vertices()):
self.assertTrue(self.graph.has_edge(vertex, vertex))
if "__main__" == __name__:
unittest.main()
<|fim▁end|> | return right_vertex in self._vertices[left_vertex] |
<|file_name|>ch4_ex4.1.4.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Created by Samvel Khalatyan on Mar 23, 2014
# Copyright (c) 2014 Samvel Khalatyan. All rights reserved
#
# Use of this source code is governed by a license that can be found in
# the LICENSE file.
import random
import unittest
from lib import unigraph
class UnigraphExtra(unigraph.Unigraph):
def has_edge(self, left_vertex, right_vertex):
if left_vertex == right_vertex:
return True
else:
return right_vertex in self._vertices[left_vertex]
class UnigraphEdgeTestCase(unittest.TestCase):
def setUp(self):
self.graph = UnigraphExtra(random.randrange(10, 15))
for edge in range(2 * self.graph.vertices()):
f, t = (random.randrange(self.graph.vertices()) for x in range(2))
self.graph.add_edge(f, t)
def test_edge(self):
for vertex in range(self.graph.vertices()):
existing_vertices = set(self.graph._vertices[vertex])
all_vertices = set(range(self.graph.vertices()))
missing_vertices = all_vertices - all_vertices
for adj_vertex in existing_vertices:
self.assertTrue(self.graph.has_edge(vertex, adj_vertex))
for adj_vertex in missing_vertices:
self.assertFalse(self.graph.has_edge(vertex, adj_vertex))
def test_self_loop(self):
for vertex in range(self.graph.vertices()):
self.assertTrue(self.graph.has_edge(vertex, vertex))
if "__main__" == __name__:
<|fim_middle|>
<|fim▁end|> | unittest.main() |
<|file_name|>ch4_ex4.1.4.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Created by Samvel Khalatyan on Mar 23, 2014
# Copyright (c) 2014 Samvel Khalatyan. All rights reserved
#
# Use of this source code is governed by a license that can be found in
# the LICENSE file.
import random
import unittest
from lib import unigraph
class UnigraphExtra(unigraph.Unigraph):
def <|fim_middle|>(self, left_vertex, right_vertex):
if left_vertex == right_vertex:
return True
else:
return right_vertex in self._vertices[left_vertex]
class UnigraphEdgeTestCase(unittest.TestCase):
def setUp(self):
self.graph = UnigraphExtra(random.randrange(10, 15))
for edge in range(2 * self.graph.vertices()):
f, t = (random.randrange(self.graph.vertices()) for x in range(2))
self.graph.add_edge(f, t)
def test_edge(self):
for vertex in range(self.graph.vertices()):
existing_vertices = set(self.graph._vertices[vertex])
all_vertices = set(range(self.graph.vertices()))
missing_vertices = all_vertices - all_vertices
for adj_vertex in existing_vertices:
self.assertTrue(self.graph.has_edge(vertex, adj_vertex))
for adj_vertex in missing_vertices:
self.assertFalse(self.graph.has_edge(vertex, adj_vertex))
def test_self_loop(self):
for vertex in range(self.graph.vertices()):
self.assertTrue(self.graph.has_edge(vertex, vertex))
if "__main__" == __name__:
unittest.main()
<|fim▁end|> | has_edge |
<|file_name|>ch4_ex4.1.4.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Created by Samvel Khalatyan on Mar 23, 2014
# Copyright (c) 2014 Samvel Khalatyan. All rights reserved
#
# Use of this source code is governed by a license that can be found in
# the LICENSE file.
import random
import unittest
from lib import unigraph
class UnigraphExtra(unigraph.Unigraph):
def has_edge(self, left_vertex, right_vertex):
if left_vertex == right_vertex:
return True
else:
return right_vertex in self._vertices[left_vertex]
class UnigraphEdgeTestCase(unittest.TestCase):
def <|fim_middle|>(self):
self.graph = UnigraphExtra(random.randrange(10, 15))
for edge in range(2 * self.graph.vertices()):
f, t = (random.randrange(self.graph.vertices()) for x in range(2))
self.graph.add_edge(f, t)
def test_edge(self):
for vertex in range(self.graph.vertices()):
existing_vertices = set(self.graph._vertices[vertex])
all_vertices = set(range(self.graph.vertices()))
missing_vertices = all_vertices - all_vertices
for adj_vertex in existing_vertices:
self.assertTrue(self.graph.has_edge(vertex, adj_vertex))
for adj_vertex in missing_vertices:
self.assertFalse(self.graph.has_edge(vertex, adj_vertex))
def test_self_loop(self):
for vertex in range(self.graph.vertices()):
self.assertTrue(self.graph.has_edge(vertex, vertex))
if "__main__" == __name__:
unittest.main()
<|fim▁end|> | setUp |
<|file_name|>ch4_ex4.1.4.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Created by Samvel Khalatyan on Mar 23, 2014
# Copyright (c) 2014 Samvel Khalatyan. All rights reserved
#
# Use of this source code is governed by a license that can be found in
# the LICENSE file.
import random
import unittest
from lib import unigraph
class UnigraphExtra(unigraph.Unigraph):
def has_edge(self, left_vertex, right_vertex):
if left_vertex == right_vertex:
return True
else:
return right_vertex in self._vertices[left_vertex]
class UnigraphEdgeTestCase(unittest.TestCase):
def setUp(self):
self.graph = UnigraphExtra(random.randrange(10, 15))
for edge in range(2 * self.graph.vertices()):
f, t = (random.randrange(self.graph.vertices()) for x in range(2))
self.graph.add_edge(f, t)
def <|fim_middle|>(self):
for vertex in range(self.graph.vertices()):
existing_vertices = set(self.graph._vertices[vertex])
all_vertices = set(range(self.graph.vertices()))
missing_vertices = all_vertices - all_vertices
for adj_vertex in existing_vertices:
self.assertTrue(self.graph.has_edge(vertex, adj_vertex))
for adj_vertex in missing_vertices:
self.assertFalse(self.graph.has_edge(vertex, adj_vertex))
def test_self_loop(self):
for vertex in range(self.graph.vertices()):
self.assertTrue(self.graph.has_edge(vertex, vertex))
if "__main__" == __name__:
unittest.main()
<|fim▁end|> | test_edge |
<|file_name|>ch4_ex4.1.4.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Created by Samvel Khalatyan on Mar 23, 2014
# Copyright (c) 2014 Samvel Khalatyan. All rights reserved
#
# Use of this source code is governed by a license that can be found in
# the LICENSE file.
import random
import unittest
from lib import unigraph
class UnigraphExtra(unigraph.Unigraph):
def has_edge(self, left_vertex, right_vertex):
if left_vertex == right_vertex:
return True
else:
return right_vertex in self._vertices[left_vertex]
class UnigraphEdgeTestCase(unittest.TestCase):
def setUp(self):
self.graph = UnigraphExtra(random.randrange(10, 15))
for edge in range(2 * self.graph.vertices()):
f, t = (random.randrange(self.graph.vertices()) for x in range(2))
self.graph.add_edge(f, t)
def test_edge(self):
for vertex in range(self.graph.vertices()):
existing_vertices = set(self.graph._vertices[vertex])
all_vertices = set(range(self.graph.vertices()))
missing_vertices = all_vertices - all_vertices
for adj_vertex in existing_vertices:
self.assertTrue(self.graph.has_edge(vertex, adj_vertex))
for adj_vertex in missing_vertices:
self.assertFalse(self.graph.has_edge(vertex, adj_vertex))
def <|fim_middle|>(self):
for vertex in range(self.graph.vertices()):
self.assertTrue(self.graph.has_edge(vertex, vertex))
if "__main__" == __name__:
unittest.main()
<|fim▁end|> | test_self_loop |
<|file_name|>cleanup_addon_premium.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from django.core.management.base import BaseCommand
import amo
from mkt.webapps.models import AddonPremium
class Command(BaseCommand):
help = 'Clean up existing AddonPremium objects for free apps.'
def handle(self, *args, **options):
(AddonPremium.objects.filter(addon__premium_type__in=amo.ADDON_FREES)
.delete())<|fim▁end|> | |
<|file_name|>cleanup_addon_premium.py<|end_file_name|><|fim▁begin|>from django.core.management.base import BaseCommand
import amo
from mkt.webapps.models import AddonPremium
class Command(BaseCommand):
<|fim_middle|>
<|fim▁end|> | help = 'Clean up existing AddonPremium objects for free apps.'
def handle(self, *args, **options):
(AddonPremium.objects.filter(addon__premium_type__in=amo.ADDON_FREES)
.delete()) |
<|file_name|>cleanup_addon_premium.py<|end_file_name|><|fim▁begin|>from django.core.management.base import BaseCommand
import amo
from mkt.webapps.models import AddonPremium
class Command(BaseCommand):
help = 'Clean up existing AddonPremium objects for free apps.'
def handle(self, *args, **options):
<|fim_middle|>
<|fim▁end|> | (AddonPremium.objects.filter(addon__premium_type__in=amo.ADDON_FREES)
.delete()) |
<|file_name|>cleanup_addon_premium.py<|end_file_name|><|fim▁begin|>from django.core.management.base import BaseCommand
import amo
from mkt.webapps.models import AddonPremium
class Command(BaseCommand):
help = 'Clean up existing AddonPremium objects for free apps.'
def <|fim_middle|>(self, *args, **options):
(AddonPremium.objects.filter(addon__premium_type__in=amo.ADDON_FREES)
.delete())
<|fim▁end|> | handle |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
rohmu
Copyright (c) 2016 Ohmu Ltd
See LICENSE for details
"""
from . errors import InvalidConfigurationError
<|fim▁hole|>
def get_class_for_transfer(storage_type):
if storage_type == "azure":
from .object_storage.azure import AzureTransfer
return AzureTransfer
elif storage_type == "google":
from .object_storage.google import GoogleTransfer
return GoogleTransfer
elif storage_type == "local":
from .object_storage.local import LocalTransfer
return LocalTransfer
elif storage_type == "s3":
from .object_storage.s3 import S3Transfer
return S3Transfer
elif storage_type == "swift":
from .object_storage.swift import SwiftTransfer
return SwiftTransfer
raise InvalidConfigurationError("unsupported storage type {0!r}".format(storage_type))
def get_transfer(storage_config, *, storage_type=None):
# TODO: drop storage_type from the function signature, always read it from the config
if "storage_type" in storage_config:
storage_config = storage_config.copy()
storage_type = storage_config.pop("storage_type")
storage_class = get_class_for_transfer(storage_type)
return storage_class(**storage_config)<|fim▁end|> |
IO_BLOCK_SIZE = 2 ** 20 # 1 MiB
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
rohmu
Copyright (c) 2016 Ohmu Ltd
See LICENSE for details
"""
from . errors import InvalidConfigurationError
IO_BLOCK_SIZE = 2 ** 20 # 1 MiB
def get_class_for_transfer(storage_type):
<|fim_middle|>
def get_transfer(storage_config, *, storage_type=None):
# TODO: drop storage_type from the function signature, always read it from the config
if "storage_type" in storage_config:
storage_config = storage_config.copy()
storage_type = storage_config.pop("storage_type")
storage_class = get_class_for_transfer(storage_type)
return storage_class(**storage_config)
<|fim▁end|> | if storage_type == "azure":
from .object_storage.azure import AzureTransfer
return AzureTransfer
elif storage_type == "google":
from .object_storage.google import GoogleTransfer
return GoogleTransfer
elif storage_type == "local":
from .object_storage.local import LocalTransfer
return LocalTransfer
elif storage_type == "s3":
from .object_storage.s3 import S3Transfer
return S3Transfer
elif storage_type == "swift":
from .object_storage.swift import SwiftTransfer
return SwiftTransfer
raise InvalidConfigurationError("unsupported storage type {0!r}".format(storage_type)) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
rohmu
Copyright (c) 2016 Ohmu Ltd
See LICENSE for details
"""
from . errors import InvalidConfigurationError
IO_BLOCK_SIZE = 2 ** 20 # 1 MiB
def get_class_for_transfer(storage_type):
if storage_type == "azure":
from .object_storage.azure import AzureTransfer
return AzureTransfer
elif storage_type == "google":
from .object_storage.google import GoogleTransfer
return GoogleTransfer
elif storage_type == "local":
from .object_storage.local import LocalTransfer
return LocalTransfer
elif storage_type == "s3":
from .object_storage.s3 import S3Transfer
return S3Transfer
elif storage_type == "swift":
from .object_storage.swift import SwiftTransfer
return SwiftTransfer
raise InvalidConfigurationError("unsupported storage type {0!r}".format(storage_type))
def get_transfer(storage_config, *, storage_type=None):
# TODO: drop storage_type from the function signature, always read it from the config
<|fim_middle|>
<|fim▁end|> | if "storage_type" in storage_config:
storage_config = storage_config.copy()
storage_type = storage_config.pop("storage_type")
storage_class = get_class_for_transfer(storage_type)
return storage_class(**storage_config) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
rohmu
Copyright (c) 2016 Ohmu Ltd
See LICENSE for details
"""
from . errors import InvalidConfigurationError
IO_BLOCK_SIZE = 2 ** 20 # 1 MiB
def get_class_for_transfer(storage_type):
if storage_type == "azure":
<|fim_middle|>
elif storage_type == "google":
from .object_storage.google import GoogleTransfer
return GoogleTransfer
elif storage_type == "local":
from .object_storage.local import LocalTransfer
return LocalTransfer
elif storage_type == "s3":
from .object_storage.s3 import S3Transfer
return S3Transfer
elif storage_type == "swift":
from .object_storage.swift import SwiftTransfer
return SwiftTransfer
raise InvalidConfigurationError("unsupported storage type {0!r}".format(storage_type))
def get_transfer(storage_config, *, storage_type=None):
# TODO: drop storage_type from the function signature, always read it from the config
if "storage_type" in storage_config:
storage_config = storage_config.copy()
storage_type = storage_config.pop("storage_type")
storage_class = get_class_for_transfer(storage_type)
return storage_class(**storage_config)
<|fim▁end|> | from .object_storage.azure import AzureTransfer
return AzureTransfer |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
rohmu
Copyright (c) 2016 Ohmu Ltd
See LICENSE for details
"""
from . errors import InvalidConfigurationError
IO_BLOCK_SIZE = 2 ** 20 # 1 MiB
def get_class_for_transfer(storage_type):
if storage_type == "azure":
from .object_storage.azure import AzureTransfer
return AzureTransfer
elif storage_type == "google":
<|fim_middle|>
elif storage_type == "local":
from .object_storage.local import LocalTransfer
return LocalTransfer
elif storage_type == "s3":
from .object_storage.s3 import S3Transfer
return S3Transfer
elif storage_type == "swift":
from .object_storage.swift import SwiftTransfer
return SwiftTransfer
raise InvalidConfigurationError("unsupported storage type {0!r}".format(storage_type))
def get_transfer(storage_config, *, storage_type=None):
# TODO: drop storage_type from the function signature, always read it from the config
if "storage_type" in storage_config:
storage_config = storage_config.copy()
storage_type = storage_config.pop("storage_type")
storage_class = get_class_for_transfer(storage_type)
return storage_class(**storage_config)
<|fim▁end|> | from .object_storage.google import GoogleTransfer
return GoogleTransfer |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
rohmu
Copyright (c) 2016 Ohmu Ltd
See LICENSE for details
"""
from . errors import InvalidConfigurationError
IO_BLOCK_SIZE = 2 ** 20 # 1 MiB
def get_class_for_transfer(storage_type):
if storage_type == "azure":
from .object_storage.azure import AzureTransfer
return AzureTransfer
elif storage_type == "google":
from .object_storage.google import GoogleTransfer
return GoogleTransfer
elif storage_type == "local":
<|fim_middle|>
elif storage_type == "s3":
from .object_storage.s3 import S3Transfer
return S3Transfer
elif storage_type == "swift":
from .object_storage.swift import SwiftTransfer
return SwiftTransfer
raise InvalidConfigurationError("unsupported storage type {0!r}".format(storage_type))
def get_transfer(storage_config, *, storage_type=None):
# TODO: drop storage_type from the function signature, always read it from the config
if "storage_type" in storage_config:
storage_config = storage_config.copy()
storage_type = storage_config.pop("storage_type")
storage_class = get_class_for_transfer(storage_type)
return storage_class(**storage_config)
<|fim▁end|> | from .object_storage.local import LocalTransfer
return LocalTransfer |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
rohmu
Copyright (c) 2016 Ohmu Ltd
See LICENSE for details
"""
from . errors import InvalidConfigurationError
IO_BLOCK_SIZE = 2 ** 20 # 1 MiB
def get_class_for_transfer(storage_type):
if storage_type == "azure":
from .object_storage.azure import AzureTransfer
return AzureTransfer
elif storage_type == "google":
from .object_storage.google import GoogleTransfer
return GoogleTransfer
elif storage_type == "local":
from .object_storage.local import LocalTransfer
return LocalTransfer
elif storage_type == "s3":
<|fim_middle|>
elif storage_type == "swift":
from .object_storage.swift import SwiftTransfer
return SwiftTransfer
raise InvalidConfigurationError("unsupported storage type {0!r}".format(storage_type))
def get_transfer(storage_config, *, storage_type=None):
# TODO: drop storage_type from the function signature, always read it from the config
if "storage_type" in storage_config:
storage_config = storage_config.copy()
storage_type = storage_config.pop("storage_type")
storage_class = get_class_for_transfer(storage_type)
return storage_class(**storage_config)
<|fim▁end|> | from .object_storage.s3 import S3Transfer
return S3Transfer |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
rohmu
Copyright (c) 2016 Ohmu Ltd
See LICENSE for details
"""
from . errors import InvalidConfigurationError
IO_BLOCK_SIZE = 2 ** 20 # 1 MiB
def get_class_for_transfer(storage_type):
if storage_type == "azure":
from .object_storage.azure import AzureTransfer
return AzureTransfer
elif storage_type == "google":
from .object_storage.google import GoogleTransfer
return GoogleTransfer
elif storage_type == "local":
from .object_storage.local import LocalTransfer
return LocalTransfer
elif storage_type == "s3":
from .object_storage.s3 import S3Transfer
return S3Transfer
elif storage_type == "swift":
<|fim_middle|>
raise InvalidConfigurationError("unsupported storage type {0!r}".format(storage_type))
def get_transfer(storage_config, *, storage_type=None):
# TODO: drop storage_type from the function signature, always read it from the config
if "storage_type" in storage_config:
storage_config = storage_config.copy()
storage_type = storage_config.pop("storage_type")
storage_class = get_class_for_transfer(storage_type)
return storage_class(**storage_config)
<|fim▁end|> | from .object_storage.swift import SwiftTransfer
return SwiftTransfer |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
rohmu
Copyright (c) 2016 Ohmu Ltd
See LICENSE for details
"""
from . errors import InvalidConfigurationError
IO_BLOCK_SIZE = 2 ** 20 # 1 MiB
def get_class_for_transfer(storage_type):
if storage_type == "azure":
from .object_storage.azure import AzureTransfer
return AzureTransfer
elif storage_type == "google":
from .object_storage.google import GoogleTransfer
return GoogleTransfer
elif storage_type == "local":
from .object_storage.local import LocalTransfer
return LocalTransfer
elif storage_type == "s3":
from .object_storage.s3 import S3Transfer
return S3Transfer
elif storage_type == "swift":
from .object_storage.swift import SwiftTransfer
return SwiftTransfer
raise InvalidConfigurationError("unsupported storage type {0!r}".format(storage_type))
def get_transfer(storage_config, *, storage_type=None):
# TODO: drop storage_type from the function signature, always read it from the config
if "storage_type" in storage_config:
<|fim_middle|>
storage_class = get_class_for_transfer(storage_type)
return storage_class(**storage_config)
<|fim▁end|> | storage_config = storage_config.copy()
storage_type = storage_config.pop("storage_type") |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
rohmu
Copyright (c) 2016 Ohmu Ltd
See LICENSE for details
"""
from . errors import InvalidConfigurationError
IO_BLOCK_SIZE = 2 ** 20 # 1 MiB
def <|fim_middle|>(storage_type):
if storage_type == "azure":
from .object_storage.azure import AzureTransfer
return AzureTransfer
elif storage_type == "google":
from .object_storage.google import GoogleTransfer
return GoogleTransfer
elif storage_type == "local":
from .object_storage.local import LocalTransfer
return LocalTransfer
elif storage_type == "s3":
from .object_storage.s3 import S3Transfer
return S3Transfer
elif storage_type == "swift":
from .object_storage.swift import SwiftTransfer
return SwiftTransfer
raise InvalidConfigurationError("unsupported storage type {0!r}".format(storage_type))
def get_transfer(storage_config, *, storage_type=None):
# TODO: drop storage_type from the function signature, always read it from the config
if "storage_type" in storage_config:
storage_config = storage_config.copy()
storage_type = storage_config.pop("storage_type")
storage_class = get_class_for_transfer(storage_type)
return storage_class(**storage_config)
<|fim▁end|> | get_class_for_transfer |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""
rohmu
Copyright (c) 2016 Ohmu Ltd
See LICENSE for details
"""
from . errors import InvalidConfigurationError
IO_BLOCK_SIZE = 2 ** 20 # 1 MiB
def get_class_for_transfer(storage_type):
if storage_type == "azure":
from .object_storage.azure import AzureTransfer
return AzureTransfer
elif storage_type == "google":
from .object_storage.google import GoogleTransfer
return GoogleTransfer
elif storage_type == "local":
from .object_storage.local import LocalTransfer
return LocalTransfer
elif storage_type == "s3":
from .object_storage.s3 import S3Transfer
return S3Transfer
elif storage_type == "swift":
from .object_storage.swift import SwiftTransfer
return SwiftTransfer
raise InvalidConfigurationError("unsupported storage type {0!r}".format(storage_type))
def <|fim_middle|>(storage_config, *, storage_type=None):
# TODO: drop storage_type from the function signature, always read it from the config
if "storage_type" in storage_config:
storage_config = storage_config.copy()
storage_type = storage_config.pop("storage_type")
storage_class = get_class_for_transfer(storage_type)
return storage_class(**storage_config)
<|fim▁end|> | get_transfer |
<|file_name|>201511251405_33a1d6f25951_add_timetable_related_tables.py<|end_file_name|><|fim▁begin|>"""Add timetable related tables
Revision ID: 33a1d6f25951
Revises: 225d0750c216
Create Date: 2015-11-25 14:05:51.856236
"""
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum, UTCDateTime
from indico.modules.events.timetable.models.entries import TimetableEntryType
# revision identifiers, used by Alembic.
revision = '33a1d6f25951'
down_revision = '225d0750c216'
def upgrade():
# Break
op.create_table(
'breaks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=False),
sa.Column('description', sa.Text(), nullable=False),
sa.Column('duration', sa.Interval(), nullable=False),
sa.Column('text_color', sa.String(), nullable=False),
sa.Column('background_color', sa.String(), nullable=False),
sa.Column('room_name', sa.String(), nullable=False),
sa.Column('inherit_location', sa.Boolean(), nullable=False),
sa.Column('address', sa.Text(), nullable=False),
sa.Column('venue_id', sa.Integer(), nullable=True, index=True),
sa.Column('venue_name', sa.String(), nullable=False),
sa.Column('room_id', sa.Integer(), nullable=True, index=True),
sa.CheckConstraint("(room_id IS NULL) OR (venue_name = '' AND room_name = '')",
name='no_custom_location_if_room'),
sa.CheckConstraint("(venue_id IS NULL) OR (venue_name = '')", name='no_venue_name_if_venue_id'),
sa.CheckConstraint("(room_id IS NULL) OR (venue_id IS NOT NULL)", name='venue_id_if_room_id'),<|fim▁hole|> "room_name = '' AND address = '')", name='inherited_location'),
sa.CheckConstraint("(text_color = '') = (background_color = '')", name='both_or_no_colors'),
sa.CheckConstraint("text_color != '' AND background_color != ''", name='colors_not_empty'),
sa.ForeignKeyConstraint(['room_id'], ['roombooking.rooms.id']),
sa.ForeignKeyConstraint(['venue_id'], ['roombooking.locations.id']),
sa.ForeignKeyConstraint(['venue_id', 'room_id'], ['roombooking.rooms.location_id', 'roombooking.rooms.id']),
sa.PrimaryKeyConstraint('id'),
schema='events'
)
# TimetableEntry
op.create_table(
'timetable_entries',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('event_id', sa.Integer(), nullable=False, index=True),
sa.Column('parent_id', sa.Integer(), nullable=True, index=True),
sa.Column('session_block_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('contribution_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('break_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('type', PyIntEnum(TimetableEntryType), nullable=False),
sa.Column('start_dt', UTCDateTime, nullable=False),
sa.Index('ix_timetable_entries_start_dt_desc', sa.text('start_dt DESC')),
sa.CheckConstraint('type != 1 OR parent_id IS NULL', name='valid_parent'),
sa.CheckConstraint('type != 1 OR (contribution_id IS NULL AND break_id IS NULL AND '
'session_block_id IS NOT NULL)', name='valid_session_block'),
sa.CheckConstraint('type != 2 OR (session_block_id IS NULL AND break_id IS NULL AND '
'contribution_id IS NOT NULL)', name='valid_contribution'),
sa.CheckConstraint('type != 3 OR (contribution_id IS NULL AND session_block_id IS NULL AND '
'break_id IS NOT NULL)', name='valid_break'),
sa.ForeignKeyConstraint(['break_id'], ['events.breaks.id']),
sa.ForeignKeyConstraint(['contribution_id'], ['events.contributions.id']),
sa.ForeignKeyConstraint(['event_id'], ['events.events.id']),
sa.ForeignKeyConstraint(['parent_id'], ['events.timetable_entries.id']),
sa.ForeignKeyConstraint(['session_block_id'], ['events.session_blocks.id']),
sa.PrimaryKeyConstraint('id'),
schema='events'
)
def downgrade():
op.drop_table('timetable_entries', schema='events')
op.drop_table('breaks', schema='events')<|fim▁end|> | sa.CheckConstraint("NOT inherit_location OR (venue_id IS NULL AND room_id IS NULL AND venue_name = '' AND " |
<|file_name|>201511251405_33a1d6f25951_add_timetable_related_tables.py<|end_file_name|><|fim▁begin|>"""Add timetable related tables
Revision ID: 33a1d6f25951
Revises: 225d0750c216
Create Date: 2015-11-25 14:05:51.856236
"""
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum, UTCDateTime
from indico.modules.events.timetable.models.entries import TimetableEntryType
# revision identifiers, used by Alembic.
revision = '33a1d6f25951'
down_revision = '225d0750c216'
def upgrade():
# Break
<|fim_middle|>
def downgrade():
op.drop_table('timetable_entries', schema='events')
op.drop_table('breaks', schema='events')
<|fim▁end|> | op.create_table(
'breaks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=False),
sa.Column('description', sa.Text(), nullable=False),
sa.Column('duration', sa.Interval(), nullable=False),
sa.Column('text_color', sa.String(), nullable=False),
sa.Column('background_color', sa.String(), nullable=False),
sa.Column('room_name', sa.String(), nullable=False),
sa.Column('inherit_location', sa.Boolean(), nullable=False),
sa.Column('address', sa.Text(), nullable=False),
sa.Column('venue_id', sa.Integer(), nullable=True, index=True),
sa.Column('venue_name', sa.String(), nullable=False),
sa.Column('room_id', sa.Integer(), nullable=True, index=True),
sa.CheckConstraint("(room_id IS NULL) OR (venue_name = '' AND room_name = '')",
name='no_custom_location_if_room'),
sa.CheckConstraint("(venue_id IS NULL) OR (venue_name = '')", name='no_venue_name_if_venue_id'),
sa.CheckConstraint("(room_id IS NULL) OR (venue_id IS NOT NULL)", name='venue_id_if_room_id'),
sa.CheckConstraint("NOT inherit_location OR (venue_id IS NULL AND room_id IS NULL AND venue_name = '' AND "
"room_name = '' AND address = '')", name='inherited_location'),
sa.CheckConstraint("(text_color = '') = (background_color = '')", name='both_or_no_colors'),
sa.CheckConstraint("text_color != '' AND background_color != ''", name='colors_not_empty'),
sa.ForeignKeyConstraint(['room_id'], ['roombooking.rooms.id']),
sa.ForeignKeyConstraint(['venue_id'], ['roombooking.locations.id']),
sa.ForeignKeyConstraint(['venue_id', 'room_id'], ['roombooking.rooms.location_id', 'roombooking.rooms.id']),
sa.PrimaryKeyConstraint('id'),
schema='events'
)
# TimetableEntry
op.create_table(
'timetable_entries',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('event_id', sa.Integer(), nullable=False, index=True),
sa.Column('parent_id', sa.Integer(), nullable=True, index=True),
sa.Column('session_block_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('contribution_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('break_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('type', PyIntEnum(TimetableEntryType), nullable=False),
sa.Column('start_dt', UTCDateTime, nullable=False),
sa.Index('ix_timetable_entries_start_dt_desc', sa.text('start_dt DESC')),
sa.CheckConstraint('type != 1 OR parent_id IS NULL', name='valid_parent'),
sa.CheckConstraint('type != 1 OR (contribution_id IS NULL AND break_id IS NULL AND '
'session_block_id IS NOT NULL)', name='valid_session_block'),
sa.CheckConstraint('type != 2 OR (session_block_id IS NULL AND break_id IS NULL AND '
'contribution_id IS NOT NULL)', name='valid_contribution'),
sa.CheckConstraint('type != 3 OR (contribution_id IS NULL AND session_block_id IS NULL AND '
'break_id IS NOT NULL)', name='valid_break'),
sa.ForeignKeyConstraint(['break_id'], ['events.breaks.id']),
sa.ForeignKeyConstraint(['contribution_id'], ['events.contributions.id']),
sa.ForeignKeyConstraint(['event_id'], ['events.events.id']),
sa.ForeignKeyConstraint(['parent_id'], ['events.timetable_entries.id']),
sa.ForeignKeyConstraint(['session_block_id'], ['events.session_blocks.id']),
sa.PrimaryKeyConstraint('id'),
schema='events'
) |
<|file_name|>201511251405_33a1d6f25951_add_timetable_related_tables.py<|end_file_name|><|fim▁begin|>"""Add timetable related tables
Revision ID: 33a1d6f25951
Revises: 225d0750c216
Create Date: 2015-11-25 14:05:51.856236
"""
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum, UTCDateTime
from indico.modules.events.timetable.models.entries import TimetableEntryType
# revision identifiers, used by Alembic.
revision = '33a1d6f25951'
down_revision = '225d0750c216'
def upgrade():
# Break
op.create_table(
'breaks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=False),
sa.Column('description', sa.Text(), nullable=False),
sa.Column('duration', sa.Interval(), nullable=False),
sa.Column('text_color', sa.String(), nullable=False),
sa.Column('background_color', sa.String(), nullable=False),
sa.Column('room_name', sa.String(), nullable=False),
sa.Column('inherit_location', sa.Boolean(), nullable=False),
sa.Column('address', sa.Text(), nullable=False),
sa.Column('venue_id', sa.Integer(), nullable=True, index=True),
sa.Column('venue_name', sa.String(), nullable=False),
sa.Column('room_id', sa.Integer(), nullable=True, index=True),
sa.CheckConstraint("(room_id IS NULL) OR (venue_name = '' AND room_name = '')",
name='no_custom_location_if_room'),
sa.CheckConstraint("(venue_id IS NULL) OR (venue_name = '')", name='no_venue_name_if_venue_id'),
sa.CheckConstraint("(room_id IS NULL) OR (venue_id IS NOT NULL)", name='venue_id_if_room_id'),
sa.CheckConstraint("NOT inherit_location OR (venue_id IS NULL AND room_id IS NULL AND venue_name = '' AND "
"room_name = '' AND address = '')", name='inherited_location'),
sa.CheckConstraint("(text_color = '') = (background_color = '')", name='both_or_no_colors'),
sa.CheckConstraint("text_color != '' AND background_color != ''", name='colors_not_empty'),
sa.ForeignKeyConstraint(['room_id'], ['roombooking.rooms.id']),
sa.ForeignKeyConstraint(['venue_id'], ['roombooking.locations.id']),
sa.ForeignKeyConstraint(['venue_id', 'room_id'], ['roombooking.rooms.location_id', 'roombooking.rooms.id']),
sa.PrimaryKeyConstraint('id'),
schema='events'
)
# TimetableEntry
op.create_table(
'timetable_entries',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('event_id', sa.Integer(), nullable=False, index=True),
sa.Column('parent_id', sa.Integer(), nullable=True, index=True),
sa.Column('session_block_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('contribution_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('break_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('type', PyIntEnum(TimetableEntryType), nullable=False),
sa.Column('start_dt', UTCDateTime, nullable=False),
sa.Index('ix_timetable_entries_start_dt_desc', sa.text('start_dt DESC')),
sa.CheckConstraint('type != 1 OR parent_id IS NULL', name='valid_parent'),
sa.CheckConstraint('type != 1 OR (contribution_id IS NULL AND break_id IS NULL AND '
'session_block_id IS NOT NULL)', name='valid_session_block'),
sa.CheckConstraint('type != 2 OR (session_block_id IS NULL AND break_id IS NULL AND '
'contribution_id IS NOT NULL)', name='valid_contribution'),
sa.CheckConstraint('type != 3 OR (contribution_id IS NULL AND session_block_id IS NULL AND '
'break_id IS NOT NULL)', name='valid_break'),
sa.ForeignKeyConstraint(['break_id'], ['events.breaks.id']),
sa.ForeignKeyConstraint(['contribution_id'], ['events.contributions.id']),
sa.ForeignKeyConstraint(['event_id'], ['events.events.id']),
sa.ForeignKeyConstraint(['parent_id'], ['events.timetable_entries.id']),
sa.ForeignKeyConstraint(['session_block_id'], ['events.session_blocks.id']),
sa.PrimaryKeyConstraint('id'),
schema='events'
)
def downgrade():
<|fim_middle|>
<|fim▁end|> | op.drop_table('timetable_entries', schema='events')
op.drop_table('breaks', schema='events') |
<|file_name|>201511251405_33a1d6f25951_add_timetable_related_tables.py<|end_file_name|><|fim▁begin|>"""Add timetable related tables
Revision ID: 33a1d6f25951
Revises: 225d0750c216
Create Date: 2015-11-25 14:05:51.856236
"""
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum, UTCDateTime
from indico.modules.events.timetable.models.entries import TimetableEntryType
# revision identifiers, used by Alembic.
revision = '33a1d6f25951'
down_revision = '225d0750c216'
def <|fim_middle|>():
# Break
op.create_table(
'breaks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=False),
sa.Column('description', sa.Text(), nullable=False),
sa.Column('duration', sa.Interval(), nullable=False),
sa.Column('text_color', sa.String(), nullable=False),
sa.Column('background_color', sa.String(), nullable=False),
sa.Column('room_name', sa.String(), nullable=False),
sa.Column('inherit_location', sa.Boolean(), nullable=False),
sa.Column('address', sa.Text(), nullable=False),
sa.Column('venue_id', sa.Integer(), nullable=True, index=True),
sa.Column('venue_name', sa.String(), nullable=False),
sa.Column('room_id', sa.Integer(), nullable=True, index=True),
sa.CheckConstraint("(room_id IS NULL) OR (venue_name = '' AND room_name = '')",
name='no_custom_location_if_room'),
sa.CheckConstraint("(venue_id IS NULL) OR (venue_name = '')", name='no_venue_name_if_venue_id'),
sa.CheckConstraint("(room_id IS NULL) OR (venue_id IS NOT NULL)", name='venue_id_if_room_id'),
sa.CheckConstraint("NOT inherit_location OR (venue_id IS NULL AND room_id IS NULL AND venue_name = '' AND "
"room_name = '' AND address = '')", name='inherited_location'),
sa.CheckConstraint("(text_color = '') = (background_color = '')", name='both_or_no_colors'),
sa.CheckConstraint("text_color != '' AND background_color != ''", name='colors_not_empty'),
sa.ForeignKeyConstraint(['room_id'], ['roombooking.rooms.id']),
sa.ForeignKeyConstraint(['venue_id'], ['roombooking.locations.id']),
sa.ForeignKeyConstraint(['venue_id', 'room_id'], ['roombooking.rooms.location_id', 'roombooking.rooms.id']),
sa.PrimaryKeyConstraint('id'),
schema='events'
)
# TimetableEntry
op.create_table(
'timetable_entries',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('event_id', sa.Integer(), nullable=False, index=True),
sa.Column('parent_id', sa.Integer(), nullable=True, index=True),
sa.Column('session_block_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('contribution_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('break_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('type', PyIntEnum(TimetableEntryType), nullable=False),
sa.Column('start_dt', UTCDateTime, nullable=False),
sa.Index('ix_timetable_entries_start_dt_desc', sa.text('start_dt DESC')),
sa.CheckConstraint('type != 1 OR parent_id IS NULL', name='valid_parent'),
sa.CheckConstraint('type != 1 OR (contribution_id IS NULL AND break_id IS NULL AND '
'session_block_id IS NOT NULL)', name='valid_session_block'),
sa.CheckConstraint('type != 2 OR (session_block_id IS NULL AND break_id IS NULL AND '
'contribution_id IS NOT NULL)', name='valid_contribution'),
sa.CheckConstraint('type != 3 OR (contribution_id IS NULL AND session_block_id IS NULL AND '
'break_id IS NOT NULL)', name='valid_break'),
sa.ForeignKeyConstraint(['break_id'], ['events.breaks.id']),
sa.ForeignKeyConstraint(['contribution_id'], ['events.contributions.id']),
sa.ForeignKeyConstraint(['event_id'], ['events.events.id']),
sa.ForeignKeyConstraint(['parent_id'], ['events.timetable_entries.id']),
sa.ForeignKeyConstraint(['session_block_id'], ['events.session_blocks.id']),
sa.PrimaryKeyConstraint('id'),
schema='events'
)
def downgrade():
op.drop_table('timetable_entries', schema='events')
op.drop_table('breaks', schema='events')
<|fim▁end|> | upgrade |
<|file_name|>201511251405_33a1d6f25951_add_timetable_related_tables.py<|end_file_name|><|fim▁begin|>"""Add timetable related tables
Revision ID: 33a1d6f25951
Revises: 225d0750c216
Create Date: 2015-11-25 14:05:51.856236
"""
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum, UTCDateTime
from indico.modules.events.timetable.models.entries import TimetableEntryType
# revision identifiers, used by Alembic.
revision = '33a1d6f25951'
down_revision = '225d0750c216'
def upgrade():
# Break
op.create_table(
'breaks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=False),
sa.Column('description', sa.Text(), nullable=False),
sa.Column('duration', sa.Interval(), nullable=False),
sa.Column('text_color', sa.String(), nullable=False),
sa.Column('background_color', sa.String(), nullable=False),
sa.Column('room_name', sa.String(), nullable=False),
sa.Column('inherit_location', sa.Boolean(), nullable=False),
sa.Column('address', sa.Text(), nullable=False),
sa.Column('venue_id', sa.Integer(), nullable=True, index=True),
sa.Column('venue_name', sa.String(), nullable=False),
sa.Column('room_id', sa.Integer(), nullable=True, index=True),
sa.CheckConstraint("(room_id IS NULL) OR (venue_name = '' AND room_name = '')",
name='no_custom_location_if_room'),
sa.CheckConstraint("(venue_id IS NULL) OR (venue_name = '')", name='no_venue_name_if_venue_id'),
sa.CheckConstraint("(room_id IS NULL) OR (venue_id IS NOT NULL)", name='venue_id_if_room_id'),
sa.CheckConstraint("NOT inherit_location OR (venue_id IS NULL AND room_id IS NULL AND venue_name = '' AND "
"room_name = '' AND address = '')", name='inherited_location'),
sa.CheckConstraint("(text_color = '') = (background_color = '')", name='both_or_no_colors'),
sa.CheckConstraint("text_color != '' AND background_color != ''", name='colors_not_empty'),
sa.ForeignKeyConstraint(['room_id'], ['roombooking.rooms.id']),
sa.ForeignKeyConstraint(['venue_id'], ['roombooking.locations.id']),
sa.ForeignKeyConstraint(['venue_id', 'room_id'], ['roombooking.rooms.location_id', 'roombooking.rooms.id']),
sa.PrimaryKeyConstraint('id'),
schema='events'
)
# TimetableEntry
op.create_table(
'timetable_entries',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('event_id', sa.Integer(), nullable=False, index=True),
sa.Column('parent_id', sa.Integer(), nullable=True, index=True),
sa.Column('session_block_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('contribution_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('break_id', sa.Integer(), nullable=True, index=True, unique=True),
sa.Column('type', PyIntEnum(TimetableEntryType), nullable=False),
sa.Column('start_dt', UTCDateTime, nullable=False),
sa.Index('ix_timetable_entries_start_dt_desc', sa.text('start_dt DESC')),
sa.CheckConstraint('type != 1 OR parent_id IS NULL', name='valid_parent'),
sa.CheckConstraint('type != 1 OR (contribution_id IS NULL AND break_id IS NULL AND '
'session_block_id IS NOT NULL)', name='valid_session_block'),
sa.CheckConstraint('type != 2 OR (session_block_id IS NULL AND break_id IS NULL AND '
'contribution_id IS NOT NULL)', name='valid_contribution'),
sa.CheckConstraint('type != 3 OR (contribution_id IS NULL AND session_block_id IS NULL AND '
'break_id IS NOT NULL)', name='valid_break'),
sa.ForeignKeyConstraint(['break_id'], ['events.breaks.id']),
sa.ForeignKeyConstraint(['contribution_id'], ['events.contributions.id']),
sa.ForeignKeyConstraint(['event_id'], ['events.events.id']),
sa.ForeignKeyConstraint(['parent_id'], ['events.timetable_entries.id']),
sa.ForeignKeyConstraint(['session_block_id'], ['events.session_blocks.id']),
sa.PrimaryKeyConstraint('id'),
schema='events'
)
def <|fim_middle|>():
op.drop_table('timetable_entries', schema='events')
op.drop_table('breaks', schema='events')
<|fim▁end|> | downgrade |
<|file_name|>kwarqs_drive_mech.py<|end_file_name|><|fim▁begin|>import wpilib
import hal
from wpilib import RobotDrive
class KwarqsDriveMech(RobotDrive):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.weight_multiplier = 1
def set_multiplier(self, in_multi = None):
if in_multi != None :
self.weight_multiplier = in_multi
else:
self.weight_multiplier = 1
def mecanumDrive_Cartesian(self, x, y, rotation, gyroAngle):
"""Drive method for Mecanum wheeled robots.
A method for driving with Mecanum wheeled robots. There are 4 wheels
on the robot, arranged so that the front and back wheels are toed in
45 degrees. When looking at the wheels from the top, the roller
axles should form an X across the robot.
<|fim▁hole|> [-1.0..1.0]
:param y: The speed that the robot should drive in the Y direction.
This input is inverted to match the forward == -1.0 that
joysticks produce. [-1.0..1.0]
:param rotation: The rate of rotation for the robot that is
completely independent of the translation. [-1.0..1.0]
:param gyroAngle: The current angle reading from the gyro. Use this
to implement field-oriented controls.
"""
if not wpilib.RobotDrive.kMecanumCartesian_Reported:
hal.HALReport(hal.HALUsageReporting.kResourceType_RobotDrive,
self.getNumMotors(),
hal.HALUsageReporting.kRobotDrive_MecanumCartesian)
RobotDrive.kMecanumCartesian_Reported = True
xIn = x
yIn = y
# Negate y for the joystick.
yIn = -yIn
# Compenstate for gyro angle.
xIn, yIn = RobotDrive.rotateVector(xIn, yIn, gyroAngle)
wheelSpeeds = [0]*self.kMaxNumberOfMotors
wheelSpeeds[self.MotorType.kFrontLeft] = xIn + yIn + rotation
wheelSpeeds[self.MotorType.kFrontRight] = -xIn + yIn - rotation
wheelSpeeds[self.MotorType.kRearLeft] = -xIn + yIn + ( rotation * self.weight_multiplier )
wheelSpeeds[self.MotorType.kRearRight] = xIn + yIn - ( rotation * self.weight_multiplier )
RobotDrive.normalize(wheelSpeeds)
self.frontLeftMotor.set(wheelSpeeds[self.MotorType.kFrontLeft] * self.invertedMotors[self.MotorType.kFrontLeft] * self.maxOutput, self.syncGroup)
self.frontRightMotor.set(wheelSpeeds[self.MotorType.kFrontRight] * self.invertedMotors[self.MotorType.kFrontRight] * self.maxOutput, self.syncGroup)
self.rearLeftMotor.set(wheelSpeeds[self.MotorType.kRearLeft] * self.invertedMotors[self.MotorType.kRearLeft] * self.maxOutput, self.syncGroup)
self.rearRightMotor.set(wheelSpeeds[self.MotorType.kRearRight] * self.invertedMotors[self.MotorType.kRearRight] * self.maxOutput, self.syncGroup)
if self.syncGroup != 0:
wpilib.CANJaguar.updateSyncGroup(self.syncGroup)
self.feed()<|fim▁end|> | This is designed to be directly driven by joystick axes.
:param x: The speed that the robot should drive in the X direction. |
<|file_name|>kwarqs_drive_mech.py<|end_file_name|><|fim▁begin|>import wpilib
import hal
from wpilib import RobotDrive
class KwarqsDriveMech(RobotDrive):
<|fim_middle|>
<|fim▁end|> | def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.weight_multiplier = 1
def set_multiplier(self, in_multi = None):
if in_multi != None :
self.weight_multiplier = in_multi
else:
self.weight_multiplier = 1
def mecanumDrive_Cartesian(self, x, y, rotation, gyroAngle):
"""Drive method for Mecanum wheeled robots.
A method for driving with Mecanum wheeled robots. There are 4 wheels
on the robot, arranged so that the front and back wheels are toed in
45 degrees. When looking at the wheels from the top, the roller
axles should form an X across the robot.
This is designed to be directly driven by joystick axes.
:param x: The speed that the robot should drive in the X direction.
[-1.0..1.0]
:param y: The speed that the robot should drive in the Y direction.
This input is inverted to match the forward == -1.0 that
joysticks produce. [-1.0..1.0]
:param rotation: The rate of rotation for the robot that is
completely independent of the translation. [-1.0..1.0]
:param gyroAngle: The current angle reading from the gyro. Use this
to implement field-oriented controls.
"""
if not wpilib.RobotDrive.kMecanumCartesian_Reported:
hal.HALReport(hal.HALUsageReporting.kResourceType_RobotDrive,
self.getNumMotors(),
hal.HALUsageReporting.kRobotDrive_MecanumCartesian)
RobotDrive.kMecanumCartesian_Reported = True
xIn = x
yIn = y
# Negate y for the joystick.
yIn = -yIn
# Compenstate for gyro angle.
xIn, yIn = RobotDrive.rotateVector(xIn, yIn, gyroAngle)
wheelSpeeds = [0]*self.kMaxNumberOfMotors
wheelSpeeds[self.MotorType.kFrontLeft] = xIn + yIn + rotation
wheelSpeeds[self.MotorType.kFrontRight] = -xIn + yIn - rotation
wheelSpeeds[self.MotorType.kRearLeft] = -xIn + yIn + ( rotation * self.weight_multiplier )
wheelSpeeds[self.MotorType.kRearRight] = xIn + yIn - ( rotation * self.weight_multiplier )
RobotDrive.normalize(wheelSpeeds)
self.frontLeftMotor.set(wheelSpeeds[self.MotorType.kFrontLeft] * self.invertedMotors[self.MotorType.kFrontLeft] * self.maxOutput, self.syncGroup)
self.frontRightMotor.set(wheelSpeeds[self.MotorType.kFrontRight] * self.invertedMotors[self.MotorType.kFrontRight] * self.maxOutput, self.syncGroup)
self.rearLeftMotor.set(wheelSpeeds[self.MotorType.kRearLeft] * self.invertedMotors[self.MotorType.kRearLeft] * self.maxOutput, self.syncGroup)
self.rearRightMotor.set(wheelSpeeds[self.MotorType.kRearRight] * self.invertedMotors[self.MotorType.kRearRight] * self.maxOutput, self.syncGroup)
if self.syncGroup != 0:
wpilib.CANJaguar.updateSyncGroup(self.syncGroup)
self.feed() |
<|file_name|>kwarqs_drive_mech.py<|end_file_name|><|fim▁begin|>import wpilib
import hal
from wpilib import RobotDrive
class KwarqsDriveMech(RobotDrive):
def __init__(self, *args, **kwargs):
<|fim_middle|>
def set_multiplier(self, in_multi = None):
if in_multi != None :
self.weight_multiplier = in_multi
else:
self.weight_multiplier = 1
def mecanumDrive_Cartesian(self, x, y, rotation, gyroAngle):
"""Drive method for Mecanum wheeled robots.
A method for driving with Mecanum wheeled robots. There are 4 wheels
on the robot, arranged so that the front and back wheels are toed in
45 degrees. When looking at the wheels from the top, the roller
axles should form an X across the robot.
This is designed to be directly driven by joystick axes.
:param x: The speed that the robot should drive in the X direction.
[-1.0..1.0]
:param y: The speed that the robot should drive in the Y direction.
This input is inverted to match the forward == -1.0 that
joysticks produce. [-1.0..1.0]
:param rotation: The rate of rotation for the robot that is
completely independent of the translation. [-1.0..1.0]
:param gyroAngle: The current angle reading from the gyro. Use this
to implement field-oriented controls.
"""
if not wpilib.RobotDrive.kMecanumCartesian_Reported:
hal.HALReport(hal.HALUsageReporting.kResourceType_RobotDrive,
self.getNumMotors(),
hal.HALUsageReporting.kRobotDrive_MecanumCartesian)
RobotDrive.kMecanumCartesian_Reported = True
xIn = x
yIn = y
# Negate y for the joystick.
yIn = -yIn
# Compenstate for gyro angle.
xIn, yIn = RobotDrive.rotateVector(xIn, yIn, gyroAngle)
wheelSpeeds = [0]*self.kMaxNumberOfMotors
wheelSpeeds[self.MotorType.kFrontLeft] = xIn + yIn + rotation
wheelSpeeds[self.MotorType.kFrontRight] = -xIn + yIn - rotation
wheelSpeeds[self.MotorType.kRearLeft] = -xIn + yIn + ( rotation * self.weight_multiplier )
wheelSpeeds[self.MotorType.kRearRight] = xIn + yIn - ( rotation * self.weight_multiplier )
RobotDrive.normalize(wheelSpeeds)
self.frontLeftMotor.set(wheelSpeeds[self.MotorType.kFrontLeft] * self.invertedMotors[self.MotorType.kFrontLeft] * self.maxOutput, self.syncGroup)
self.frontRightMotor.set(wheelSpeeds[self.MotorType.kFrontRight] * self.invertedMotors[self.MotorType.kFrontRight] * self.maxOutput, self.syncGroup)
self.rearLeftMotor.set(wheelSpeeds[self.MotorType.kRearLeft] * self.invertedMotors[self.MotorType.kRearLeft] * self.maxOutput, self.syncGroup)
self.rearRightMotor.set(wheelSpeeds[self.MotorType.kRearRight] * self.invertedMotors[self.MotorType.kRearRight] * self.maxOutput, self.syncGroup)
if self.syncGroup != 0:
wpilib.CANJaguar.updateSyncGroup(self.syncGroup)
self.feed()
<|fim▁end|> | super().__init__(*args, **kwargs)
self.weight_multiplier = 1 |
<|file_name|>kwarqs_drive_mech.py<|end_file_name|><|fim▁begin|>import wpilib
import hal
from wpilib import RobotDrive
class KwarqsDriveMech(RobotDrive):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.weight_multiplier = 1
def set_multiplier(self, in_multi = None):
<|fim_middle|>
def mecanumDrive_Cartesian(self, x, y, rotation, gyroAngle):
"""Drive method for Mecanum wheeled robots.
A method for driving with Mecanum wheeled robots. There are 4 wheels
on the robot, arranged so that the front and back wheels are toed in
45 degrees. When looking at the wheels from the top, the roller
axles should form an X across the robot.
This is designed to be directly driven by joystick axes.
:param x: The speed that the robot should drive in the X direction.
[-1.0..1.0]
:param y: The speed that the robot should drive in the Y direction.
This input is inverted to match the forward == -1.0 that
joysticks produce. [-1.0..1.0]
:param rotation: The rate of rotation for the robot that is
completely independent of the translation. [-1.0..1.0]
:param gyroAngle: The current angle reading from the gyro. Use this
to implement field-oriented controls.
"""
if not wpilib.RobotDrive.kMecanumCartesian_Reported:
hal.HALReport(hal.HALUsageReporting.kResourceType_RobotDrive,
self.getNumMotors(),
hal.HALUsageReporting.kRobotDrive_MecanumCartesian)
RobotDrive.kMecanumCartesian_Reported = True
xIn = x
yIn = y
# Negate y for the joystick.
yIn = -yIn
# Compenstate for gyro angle.
xIn, yIn = RobotDrive.rotateVector(xIn, yIn, gyroAngle)
wheelSpeeds = [0]*self.kMaxNumberOfMotors
wheelSpeeds[self.MotorType.kFrontLeft] = xIn + yIn + rotation
wheelSpeeds[self.MotorType.kFrontRight] = -xIn + yIn - rotation
wheelSpeeds[self.MotorType.kRearLeft] = -xIn + yIn + ( rotation * self.weight_multiplier )
wheelSpeeds[self.MotorType.kRearRight] = xIn + yIn - ( rotation * self.weight_multiplier )
RobotDrive.normalize(wheelSpeeds)
self.frontLeftMotor.set(wheelSpeeds[self.MotorType.kFrontLeft] * self.invertedMotors[self.MotorType.kFrontLeft] * self.maxOutput, self.syncGroup)
self.frontRightMotor.set(wheelSpeeds[self.MotorType.kFrontRight] * self.invertedMotors[self.MotorType.kFrontRight] * self.maxOutput, self.syncGroup)
self.rearLeftMotor.set(wheelSpeeds[self.MotorType.kRearLeft] * self.invertedMotors[self.MotorType.kRearLeft] * self.maxOutput, self.syncGroup)
self.rearRightMotor.set(wheelSpeeds[self.MotorType.kRearRight] * self.invertedMotors[self.MotorType.kRearRight] * self.maxOutput, self.syncGroup)
if self.syncGroup != 0:
wpilib.CANJaguar.updateSyncGroup(self.syncGroup)
self.feed()
<|fim▁end|> | if in_multi != None :
self.weight_multiplier = in_multi
else:
self.weight_multiplier = 1 |
<|file_name|>kwarqs_drive_mech.py<|end_file_name|><|fim▁begin|>import wpilib
import hal
from wpilib import RobotDrive
class KwarqsDriveMech(RobotDrive):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.weight_multiplier = 1
def set_multiplier(self, in_multi = None):
if in_multi != None :
self.weight_multiplier = in_multi
else:
self.weight_multiplier = 1
def mecanumDrive_Cartesian(self, x, y, rotation, gyroAngle):
<|fim_middle|>
<|fim▁end|> | """Drive method for Mecanum wheeled robots.
A method for driving with Mecanum wheeled robots. There are 4 wheels
on the robot, arranged so that the front and back wheels are toed in
45 degrees. When looking at the wheels from the top, the roller
axles should form an X across the robot.
This is designed to be directly driven by joystick axes.
:param x: The speed that the robot should drive in the X direction.
[-1.0..1.0]
:param y: The speed that the robot should drive in the Y direction.
This input is inverted to match the forward == -1.0 that
joysticks produce. [-1.0..1.0]
:param rotation: The rate of rotation for the robot that is
completely independent of the translation. [-1.0..1.0]
:param gyroAngle: The current angle reading from the gyro. Use this
to implement field-oriented controls.
"""
if not wpilib.RobotDrive.kMecanumCartesian_Reported:
hal.HALReport(hal.HALUsageReporting.kResourceType_RobotDrive,
self.getNumMotors(),
hal.HALUsageReporting.kRobotDrive_MecanumCartesian)
RobotDrive.kMecanumCartesian_Reported = True
xIn = x
yIn = y
# Negate y for the joystick.
yIn = -yIn
# Compenstate for gyro angle.
xIn, yIn = RobotDrive.rotateVector(xIn, yIn, gyroAngle)
wheelSpeeds = [0]*self.kMaxNumberOfMotors
wheelSpeeds[self.MotorType.kFrontLeft] = xIn + yIn + rotation
wheelSpeeds[self.MotorType.kFrontRight] = -xIn + yIn - rotation
wheelSpeeds[self.MotorType.kRearLeft] = -xIn + yIn + ( rotation * self.weight_multiplier )
wheelSpeeds[self.MotorType.kRearRight] = xIn + yIn - ( rotation * self.weight_multiplier )
RobotDrive.normalize(wheelSpeeds)
self.frontLeftMotor.set(wheelSpeeds[self.MotorType.kFrontLeft] * self.invertedMotors[self.MotorType.kFrontLeft] * self.maxOutput, self.syncGroup)
self.frontRightMotor.set(wheelSpeeds[self.MotorType.kFrontRight] * self.invertedMotors[self.MotorType.kFrontRight] * self.maxOutput, self.syncGroup)
self.rearLeftMotor.set(wheelSpeeds[self.MotorType.kRearLeft] * self.invertedMotors[self.MotorType.kRearLeft] * self.maxOutput, self.syncGroup)
self.rearRightMotor.set(wheelSpeeds[self.MotorType.kRearRight] * self.invertedMotors[self.MotorType.kRearRight] * self.maxOutput, self.syncGroup)
if self.syncGroup != 0:
wpilib.CANJaguar.updateSyncGroup(self.syncGroup)
self.feed() |
<|file_name|>kwarqs_drive_mech.py<|end_file_name|><|fim▁begin|>import wpilib
import hal
from wpilib import RobotDrive
class KwarqsDriveMech(RobotDrive):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.weight_multiplier = 1
def set_multiplier(self, in_multi = None):
if in_multi != None :
<|fim_middle|>
else:
self.weight_multiplier = 1
def mecanumDrive_Cartesian(self, x, y, rotation, gyroAngle):
"""Drive method for Mecanum wheeled robots.
A method for driving with Mecanum wheeled robots. There are 4 wheels
on the robot, arranged so that the front and back wheels are toed in
45 degrees. When looking at the wheels from the top, the roller
axles should form an X across the robot.
This is designed to be directly driven by joystick axes.
:param x: The speed that the robot should drive in the X direction.
[-1.0..1.0]
:param y: The speed that the robot should drive in the Y direction.
This input is inverted to match the forward == -1.0 that
joysticks produce. [-1.0..1.0]
:param rotation: The rate of rotation for the robot that is
completely independent of the translation. [-1.0..1.0]
:param gyroAngle: The current angle reading from the gyro. Use this
to implement field-oriented controls.
"""
if not wpilib.RobotDrive.kMecanumCartesian_Reported:
hal.HALReport(hal.HALUsageReporting.kResourceType_RobotDrive,
self.getNumMotors(),
hal.HALUsageReporting.kRobotDrive_MecanumCartesian)
RobotDrive.kMecanumCartesian_Reported = True
xIn = x
yIn = y
# Negate y for the joystick.
yIn = -yIn
# Compenstate for gyro angle.
xIn, yIn = RobotDrive.rotateVector(xIn, yIn, gyroAngle)
wheelSpeeds = [0]*self.kMaxNumberOfMotors
wheelSpeeds[self.MotorType.kFrontLeft] = xIn + yIn + rotation
wheelSpeeds[self.MotorType.kFrontRight] = -xIn + yIn - rotation
wheelSpeeds[self.MotorType.kRearLeft] = -xIn + yIn + ( rotation * self.weight_multiplier )
wheelSpeeds[self.MotorType.kRearRight] = xIn + yIn - ( rotation * self.weight_multiplier )
RobotDrive.normalize(wheelSpeeds)
self.frontLeftMotor.set(wheelSpeeds[self.MotorType.kFrontLeft] * self.invertedMotors[self.MotorType.kFrontLeft] * self.maxOutput, self.syncGroup)
self.frontRightMotor.set(wheelSpeeds[self.MotorType.kFrontRight] * self.invertedMotors[self.MotorType.kFrontRight] * self.maxOutput, self.syncGroup)
self.rearLeftMotor.set(wheelSpeeds[self.MotorType.kRearLeft] * self.invertedMotors[self.MotorType.kRearLeft] * self.maxOutput, self.syncGroup)
self.rearRightMotor.set(wheelSpeeds[self.MotorType.kRearRight] * self.invertedMotors[self.MotorType.kRearRight] * self.maxOutput, self.syncGroup)
if self.syncGroup != 0:
wpilib.CANJaguar.updateSyncGroup(self.syncGroup)
self.feed()
<|fim▁end|> | self.weight_multiplier = in_multi |
<|file_name|>kwarqs_drive_mech.py<|end_file_name|><|fim▁begin|>import wpilib
import hal
from wpilib import RobotDrive
class KwarqsDriveMech(RobotDrive):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.weight_multiplier = 1
def set_multiplier(self, in_multi = None):
if in_multi != None :
self.weight_multiplier = in_multi
else:
<|fim_middle|>
def mecanumDrive_Cartesian(self, x, y, rotation, gyroAngle):
"""Drive method for Mecanum wheeled robots.
A method for driving with Mecanum wheeled robots. There are 4 wheels
on the robot, arranged so that the front and back wheels are toed in
45 degrees. When looking at the wheels from the top, the roller
axles should form an X across the robot.
This is designed to be directly driven by joystick axes.
:param x: The speed that the robot should drive in the X direction.
[-1.0..1.0]
:param y: The speed that the robot should drive in the Y direction.
This input is inverted to match the forward == -1.0 that
joysticks produce. [-1.0..1.0]
:param rotation: The rate of rotation for the robot that is
completely independent of the translation. [-1.0..1.0]
:param gyroAngle: The current angle reading from the gyro. Use this
to implement field-oriented controls.
"""
if not wpilib.RobotDrive.kMecanumCartesian_Reported:
hal.HALReport(hal.HALUsageReporting.kResourceType_RobotDrive,
self.getNumMotors(),
hal.HALUsageReporting.kRobotDrive_MecanumCartesian)
RobotDrive.kMecanumCartesian_Reported = True
xIn = x
yIn = y
# Negate y for the joystick.
yIn = -yIn
# Compenstate for gyro angle.
xIn, yIn = RobotDrive.rotateVector(xIn, yIn, gyroAngle)
wheelSpeeds = [0]*self.kMaxNumberOfMotors
wheelSpeeds[self.MotorType.kFrontLeft] = xIn + yIn + rotation
wheelSpeeds[self.MotorType.kFrontRight] = -xIn + yIn - rotation
wheelSpeeds[self.MotorType.kRearLeft] = -xIn + yIn + ( rotation * self.weight_multiplier )
wheelSpeeds[self.MotorType.kRearRight] = xIn + yIn - ( rotation * self.weight_multiplier )
RobotDrive.normalize(wheelSpeeds)
self.frontLeftMotor.set(wheelSpeeds[self.MotorType.kFrontLeft] * self.invertedMotors[self.MotorType.kFrontLeft] * self.maxOutput, self.syncGroup)
self.frontRightMotor.set(wheelSpeeds[self.MotorType.kFrontRight] * self.invertedMotors[self.MotorType.kFrontRight] * self.maxOutput, self.syncGroup)
self.rearLeftMotor.set(wheelSpeeds[self.MotorType.kRearLeft] * self.invertedMotors[self.MotorType.kRearLeft] * self.maxOutput, self.syncGroup)
self.rearRightMotor.set(wheelSpeeds[self.MotorType.kRearRight] * self.invertedMotors[self.MotorType.kRearRight] * self.maxOutput, self.syncGroup)
if self.syncGroup != 0:
wpilib.CANJaguar.updateSyncGroup(self.syncGroup)
self.feed()
<|fim▁end|> | self.weight_multiplier = 1 |
<|file_name|>kwarqs_drive_mech.py<|end_file_name|><|fim▁begin|>import wpilib
import hal
from wpilib import RobotDrive
class KwarqsDriveMech(RobotDrive):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.weight_multiplier = 1
def set_multiplier(self, in_multi = None):
if in_multi != None :
self.weight_multiplier = in_multi
else:
self.weight_multiplier = 1
def mecanumDrive_Cartesian(self, x, y, rotation, gyroAngle):
"""Drive method for Mecanum wheeled robots.
A method for driving with Mecanum wheeled robots. There are 4 wheels
on the robot, arranged so that the front and back wheels are toed in
45 degrees. When looking at the wheels from the top, the roller
axles should form an X across the robot.
This is designed to be directly driven by joystick axes.
:param x: The speed that the robot should drive in the X direction.
[-1.0..1.0]
:param y: The speed that the robot should drive in the Y direction.
This input is inverted to match the forward == -1.0 that
joysticks produce. [-1.0..1.0]
:param rotation: The rate of rotation for the robot that is
completely independent of the translation. [-1.0..1.0]
:param gyroAngle: The current angle reading from the gyro. Use this
to implement field-oriented controls.
"""
if not wpilib.RobotDrive.kMecanumCartesian_Reported:
<|fim_middle|>
xIn = x
yIn = y
# Negate y for the joystick.
yIn = -yIn
# Compenstate for gyro angle.
xIn, yIn = RobotDrive.rotateVector(xIn, yIn, gyroAngle)
wheelSpeeds = [0]*self.kMaxNumberOfMotors
wheelSpeeds[self.MotorType.kFrontLeft] = xIn + yIn + rotation
wheelSpeeds[self.MotorType.kFrontRight] = -xIn + yIn - rotation
wheelSpeeds[self.MotorType.kRearLeft] = -xIn + yIn + ( rotation * self.weight_multiplier )
wheelSpeeds[self.MotorType.kRearRight] = xIn + yIn - ( rotation * self.weight_multiplier )
RobotDrive.normalize(wheelSpeeds)
self.frontLeftMotor.set(wheelSpeeds[self.MotorType.kFrontLeft] * self.invertedMotors[self.MotorType.kFrontLeft] * self.maxOutput, self.syncGroup)
self.frontRightMotor.set(wheelSpeeds[self.MotorType.kFrontRight] * self.invertedMotors[self.MotorType.kFrontRight] * self.maxOutput, self.syncGroup)
self.rearLeftMotor.set(wheelSpeeds[self.MotorType.kRearLeft] * self.invertedMotors[self.MotorType.kRearLeft] * self.maxOutput, self.syncGroup)
self.rearRightMotor.set(wheelSpeeds[self.MotorType.kRearRight] * self.invertedMotors[self.MotorType.kRearRight] * self.maxOutput, self.syncGroup)
if self.syncGroup != 0:
wpilib.CANJaguar.updateSyncGroup(self.syncGroup)
self.feed()
<|fim▁end|> | hal.HALReport(hal.HALUsageReporting.kResourceType_RobotDrive,
self.getNumMotors(),
hal.HALUsageReporting.kRobotDrive_MecanumCartesian)
RobotDrive.kMecanumCartesian_Reported = True |
<|file_name|>kwarqs_drive_mech.py<|end_file_name|><|fim▁begin|>import wpilib
import hal
from wpilib import RobotDrive
class KwarqsDriveMech(RobotDrive):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.weight_multiplier = 1
def set_multiplier(self, in_multi = None):
if in_multi != None :
self.weight_multiplier = in_multi
else:
self.weight_multiplier = 1
def mecanumDrive_Cartesian(self, x, y, rotation, gyroAngle):
"""Drive method for Mecanum wheeled robots.
A method for driving with Mecanum wheeled robots. There are 4 wheels
on the robot, arranged so that the front and back wheels are toed in
45 degrees. When looking at the wheels from the top, the roller
axles should form an X across the robot.
This is designed to be directly driven by joystick axes.
:param x: The speed that the robot should drive in the X direction.
[-1.0..1.0]
:param y: The speed that the robot should drive in the Y direction.
This input is inverted to match the forward == -1.0 that
joysticks produce. [-1.0..1.0]
:param rotation: The rate of rotation for the robot that is
completely independent of the translation. [-1.0..1.0]
:param gyroAngle: The current angle reading from the gyro. Use this
to implement field-oriented controls.
"""
if not wpilib.RobotDrive.kMecanumCartesian_Reported:
hal.HALReport(hal.HALUsageReporting.kResourceType_RobotDrive,
self.getNumMotors(),
hal.HALUsageReporting.kRobotDrive_MecanumCartesian)
RobotDrive.kMecanumCartesian_Reported = True
xIn = x
yIn = y
# Negate y for the joystick.
yIn = -yIn
# Compenstate for gyro angle.
xIn, yIn = RobotDrive.rotateVector(xIn, yIn, gyroAngle)
wheelSpeeds = [0]*self.kMaxNumberOfMotors
wheelSpeeds[self.MotorType.kFrontLeft] = xIn + yIn + rotation
wheelSpeeds[self.MotorType.kFrontRight] = -xIn + yIn - rotation
wheelSpeeds[self.MotorType.kRearLeft] = -xIn + yIn + ( rotation * self.weight_multiplier )
wheelSpeeds[self.MotorType.kRearRight] = xIn + yIn - ( rotation * self.weight_multiplier )
RobotDrive.normalize(wheelSpeeds)
self.frontLeftMotor.set(wheelSpeeds[self.MotorType.kFrontLeft] * self.invertedMotors[self.MotorType.kFrontLeft] * self.maxOutput, self.syncGroup)
self.frontRightMotor.set(wheelSpeeds[self.MotorType.kFrontRight] * self.invertedMotors[self.MotorType.kFrontRight] * self.maxOutput, self.syncGroup)
self.rearLeftMotor.set(wheelSpeeds[self.MotorType.kRearLeft] * self.invertedMotors[self.MotorType.kRearLeft] * self.maxOutput, self.syncGroup)
self.rearRightMotor.set(wheelSpeeds[self.MotorType.kRearRight] * self.invertedMotors[self.MotorType.kRearRight] * self.maxOutput, self.syncGroup)
if self.syncGroup != 0:
<|fim_middle|>
self.feed()
<|fim▁end|> | wpilib.CANJaguar.updateSyncGroup(self.syncGroup) |
<|file_name|>kwarqs_drive_mech.py<|end_file_name|><|fim▁begin|>import wpilib
import hal
from wpilib import RobotDrive
class KwarqsDriveMech(RobotDrive):
def <|fim_middle|>(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.weight_multiplier = 1
def set_multiplier(self, in_multi = None):
if in_multi != None :
self.weight_multiplier = in_multi
else:
self.weight_multiplier = 1
def mecanumDrive_Cartesian(self, x, y, rotation, gyroAngle):
"""Drive method for Mecanum wheeled robots.
A method for driving with Mecanum wheeled robots. There are 4 wheels
on the robot, arranged so that the front and back wheels are toed in
45 degrees. When looking at the wheels from the top, the roller
axles should form an X across the robot.
This is designed to be directly driven by joystick axes.
:param x: The speed that the robot should drive in the X direction.
[-1.0..1.0]
:param y: The speed that the robot should drive in the Y direction.
This input is inverted to match the forward == -1.0 that
joysticks produce. [-1.0..1.0]
:param rotation: The rate of rotation for the robot that is
completely independent of the translation. [-1.0..1.0]
:param gyroAngle: The current angle reading from the gyro. Use this
to implement field-oriented controls.
"""
if not wpilib.RobotDrive.kMecanumCartesian_Reported:
hal.HALReport(hal.HALUsageReporting.kResourceType_RobotDrive,
self.getNumMotors(),
hal.HALUsageReporting.kRobotDrive_MecanumCartesian)
RobotDrive.kMecanumCartesian_Reported = True
xIn = x
yIn = y
# Negate y for the joystick.
yIn = -yIn
# Compenstate for gyro angle.
xIn, yIn = RobotDrive.rotateVector(xIn, yIn, gyroAngle)
wheelSpeeds = [0]*self.kMaxNumberOfMotors
wheelSpeeds[self.MotorType.kFrontLeft] = xIn + yIn + rotation
wheelSpeeds[self.MotorType.kFrontRight] = -xIn + yIn - rotation
wheelSpeeds[self.MotorType.kRearLeft] = -xIn + yIn + ( rotation * self.weight_multiplier )
wheelSpeeds[self.MotorType.kRearRight] = xIn + yIn - ( rotation * self.weight_multiplier )
RobotDrive.normalize(wheelSpeeds)
self.frontLeftMotor.set(wheelSpeeds[self.MotorType.kFrontLeft] * self.invertedMotors[self.MotorType.kFrontLeft] * self.maxOutput, self.syncGroup)
self.frontRightMotor.set(wheelSpeeds[self.MotorType.kFrontRight] * self.invertedMotors[self.MotorType.kFrontRight] * self.maxOutput, self.syncGroup)
self.rearLeftMotor.set(wheelSpeeds[self.MotorType.kRearLeft] * self.invertedMotors[self.MotorType.kRearLeft] * self.maxOutput, self.syncGroup)
self.rearRightMotor.set(wheelSpeeds[self.MotorType.kRearRight] * self.invertedMotors[self.MotorType.kRearRight] * self.maxOutput, self.syncGroup)
if self.syncGroup != 0:
wpilib.CANJaguar.updateSyncGroup(self.syncGroup)
self.feed()
<|fim▁end|> | __init__ |
<|file_name|>kwarqs_drive_mech.py<|end_file_name|><|fim▁begin|>import wpilib
import hal
from wpilib import RobotDrive
class KwarqsDriveMech(RobotDrive):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.weight_multiplier = 1
def <|fim_middle|>(self, in_multi = None):
if in_multi != None :
self.weight_multiplier = in_multi
else:
self.weight_multiplier = 1
def mecanumDrive_Cartesian(self, x, y, rotation, gyroAngle):
"""Drive method for Mecanum wheeled robots.
A method for driving with Mecanum wheeled robots. There are 4 wheels
on the robot, arranged so that the front and back wheels are toed in
45 degrees. When looking at the wheels from the top, the roller
axles should form an X across the robot.
This is designed to be directly driven by joystick axes.
:param x: The speed that the robot should drive in the X direction.
[-1.0..1.0]
:param y: The speed that the robot should drive in the Y direction.
This input is inverted to match the forward == -1.0 that
joysticks produce. [-1.0..1.0]
:param rotation: The rate of rotation for the robot that is
completely independent of the translation. [-1.0..1.0]
:param gyroAngle: The current angle reading from the gyro. Use this
to implement field-oriented controls.
"""
if not wpilib.RobotDrive.kMecanumCartesian_Reported:
hal.HALReport(hal.HALUsageReporting.kResourceType_RobotDrive,
self.getNumMotors(),
hal.HALUsageReporting.kRobotDrive_MecanumCartesian)
RobotDrive.kMecanumCartesian_Reported = True
xIn = x
yIn = y
# Negate y for the joystick.
yIn = -yIn
# Compenstate for gyro angle.
xIn, yIn = RobotDrive.rotateVector(xIn, yIn, gyroAngle)
wheelSpeeds = [0]*self.kMaxNumberOfMotors
wheelSpeeds[self.MotorType.kFrontLeft] = xIn + yIn + rotation
wheelSpeeds[self.MotorType.kFrontRight] = -xIn + yIn - rotation
wheelSpeeds[self.MotorType.kRearLeft] = -xIn + yIn + ( rotation * self.weight_multiplier )
wheelSpeeds[self.MotorType.kRearRight] = xIn + yIn - ( rotation * self.weight_multiplier )
RobotDrive.normalize(wheelSpeeds)
self.frontLeftMotor.set(wheelSpeeds[self.MotorType.kFrontLeft] * self.invertedMotors[self.MotorType.kFrontLeft] * self.maxOutput, self.syncGroup)
self.frontRightMotor.set(wheelSpeeds[self.MotorType.kFrontRight] * self.invertedMotors[self.MotorType.kFrontRight] * self.maxOutput, self.syncGroup)
self.rearLeftMotor.set(wheelSpeeds[self.MotorType.kRearLeft] * self.invertedMotors[self.MotorType.kRearLeft] * self.maxOutput, self.syncGroup)
self.rearRightMotor.set(wheelSpeeds[self.MotorType.kRearRight] * self.invertedMotors[self.MotorType.kRearRight] * self.maxOutput, self.syncGroup)
if self.syncGroup != 0:
wpilib.CANJaguar.updateSyncGroup(self.syncGroup)
self.feed()
<|fim▁end|> | set_multiplier |
<|file_name|>kwarqs_drive_mech.py<|end_file_name|><|fim▁begin|>import wpilib
import hal
from wpilib import RobotDrive
class KwarqsDriveMech(RobotDrive):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.weight_multiplier = 1
def set_multiplier(self, in_multi = None):
if in_multi != None :
self.weight_multiplier = in_multi
else:
self.weight_multiplier = 1
def <|fim_middle|>(self, x, y, rotation, gyroAngle):
"""Drive method for Mecanum wheeled robots.
A method for driving with Mecanum wheeled robots. There are 4 wheels
on the robot, arranged so that the front and back wheels are toed in
45 degrees. When looking at the wheels from the top, the roller
axles should form an X across the robot.
This is designed to be directly driven by joystick axes.
:param x: The speed that the robot should drive in the X direction.
[-1.0..1.0]
:param y: The speed that the robot should drive in the Y direction.
This input is inverted to match the forward == -1.0 that
joysticks produce. [-1.0..1.0]
:param rotation: The rate of rotation for the robot that is
completely independent of the translation. [-1.0..1.0]
:param gyroAngle: The current angle reading from the gyro. Use this
to implement field-oriented controls.
"""
if not wpilib.RobotDrive.kMecanumCartesian_Reported:
hal.HALReport(hal.HALUsageReporting.kResourceType_RobotDrive,
self.getNumMotors(),
hal.HALUsageReporting.kRobotDrive_MecanumCartesian)
RobotDrive.kMecanumCartesian_Reported = True
xIn = x
yIn = y
# Negate y for the joystick.
yIn = -yIn
# Compenstate for gyro angle.
xIn, yIn = RobotDrive.rotateVector(xIn, yIn, gyroAngle)
wheelSpeeds = [0]*self.kMaxNumberOfMotors
wheelSpeeds[self.MotorType.kFrontLeft] = xIn + yIn + rotation
wheelSpeeds[self.MotorType.kFrontRight] = -xIn + yIn - rotation
wheelSpeeds[self.MotorType.kRearLeft] = -xIn + yIn + ( rotation * self.weight_multiplier )
wheelSpeeds[self.MotorType.kRearRight] = xIn + yIn - ( rotation * self.weight_multiplier )
RobotDrive.normalize(wheelSpeeds)
self.frontLeftMotor.set(wheelSpeeds[self.MotorType.kFrontLeft] * self.invertedMotors[self.MotorType.kFrontLeft] * self.maxOutput, self.syncGroup)
self.frontRightMotor.set(wheelSpeeds[self.MotorType.kFrontRight] * self.invertedMotors[self.MotorType.kFrontRight] * self.maxOutput, self.syncGroup)
self.rearLeftMotor.set(wheelSpeeds[self.MotorType.kRearLeft] * self.invertedMotors[self.MotorType.kRearLeft] * self.maxOutput, self.syncGroup)
self.rearRightMotor.set(wheelSpeeds[self.MotorType.kRearRight] * self.invertedMotors[self.MotorType.kRearRight] * self.maxOutput, self.syncGroup)
if self.syncGroup != 0:
wpilib.CANJaguar.updateSyncGroup(self.syncGroup)
self.feed()
<|fim▁end|> | mecanumDrive_Cartesian |
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bugman.settings")
from django.core.management import execute_from_command_line
<|fim▁hole|><|fim▁end|> | execute_from_command_line(sys.argv) |
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
<|fim_middle|>
<|fim▁end|> | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bugman.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
<|file_name|>PoolTest.py<|end_file_name|><|fim▁begin|>from multiprocessing import Pool
import os, time, random
def long_time_task(name):
print 'Run task %s (%s)...' % (name, os.getpid())
start = time.time()
time.sleep(random.random() * 3)
end = time.time()
print 'Task %s runs %0.2f seconds.' % (name, (end - start))
if __name__ == '__main__':
print 'Parent process %s.' % os.getpid()
p = Pool()
for i in range(5):
p.apply_async(long_time_task, args=(i,))
print 'Waiting for all subprocesses done...'
p.close()<|fim▁hole|> """
代码解读:
对Pool对象调用join()方法会等待所有子进程执行完毕,调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process了。
请注意输出的结果,task 0,1,2,3是立刻执行的,而task 4要等待前面某个task完成后才执行,这是因为Pool的默认大小在我的电脑上是4,因此,最多同时执行4个进程。这是Pool有意设计的限制,并不是操作系统的限制。如果改成:
p = Pool(5)
"""<|fim▁end|> | p.join()
print 'All subprocesses done.' |
<|file_name|>PoolTest.py<|end_file_name|><|fim▁begin|>from multiprocessing import Pool
import os, time, random
def long_time_task(name):
<|fim_middle|>
if __name__ == '__main__':
print 'Parent process %s.' % os.getpid()
p = Pool()
for i in range(5):
p.apply_async(long_time_task, args=(i,))
print 'Waiting for all subprocesses done...'
p.close()
p.join()
print 'All subprocesses done.'
"""
代码解读:
对Pool对象调用join()方法会等待所有子进程执行完毕,调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process了。
请注意输出的结果,task 0,1,2,3是立刻执行的,而task 4要等待前面某个task完成后才执行,这是因为Pool的默认大小在我的电脑上是4,因此,最多同时执行4个进程。这是Pool有意设计的限制,并不是操作系统的限制。如果改成:
p = Pool(5)
"""<|fim▁end|> | print 'Run task %s (%s)...' % (name, os.getpid())
start = time.time()
time.sleep(random.random() * 3)
end = time.time()
print 'Task %s runs %0.2f seconds.' % (name, (end - start)) |
<|file_name|>PoolTest.py<|end_file_name|><|fim▁begin|>from multiprocessing import Pool
import os, time, random
def long_time_task(name):
print 'Run task %s (%s)...' % (name, os.getpid())
start = time.time()
time.sleep(random.random() * 3)
end = time.time()
print 'Task %s runs %0.2f seconds.' % (name, (end - start))
if __name__ == '__main__':
<|fim_middle|>
<|fim▁end|> | print 'Parent process %s.' % os.getpid()
p = Pool()
for i in range(5):
p.apply_async(long_time_task, args=(i,))
print 'Waiting for all subprocesses done...'
p.close()
p.join()
print 'All subprocesses done.'
"""
代码解读:
对Pool对象调用join()方法会等待所有子进程执行完毕,调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process了。
请注意输出的结果,task 0,1,2,3是立刻执行的,而task 4要等待前面某个task完成后才执行,这是因为Pool的默认大小在我的电脑上是4,因此,最多同时执行4个进程。这是Pool有意设计的限制,并不是操作系统的限制。如果改成:
p = Pool(5)
""" |
<|file_name|>PoolTest.py<|end_file_name|><|fim▁begin|>from multiprocessing import Pool
import os, time, random
def <|fim_middle|>(name):
print 'Run task %s (%s)...' % (name, os.getpid())
start = time.time()
time.sleep(random.random() * 3)
end = time.time()
print 'Task %s runs %0.2f seconds.' % (name, (end - start))
if __name__ == '__main__':
print 'Parent process %s.' % os.getpid()
p = Pool()
for i in range(5):
p.apply_async(long_time_task, args=(i,))
print 'Waiting for all subprocesses done...'
p.close()
p.join()
print 'All subprocesses done.'
"""
代码解读:
对Pool对象调用join()方法会等待所有子进程执行完毕,调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process了。
请注意输出的结果,task 0,1,2,3是立刻执行的,而task 4要等待前面某个task完成后才执行,这是因为Pool的默认大小在我的电脑上是4,因此,最多同时执行4个进程。这是Pool有意设计的限制,并不是操作系统的限制。如果改成:
p = Pool(5)
"""<|fim▁end|> | long_time_task |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
<|fim▁hole|><|fim▁end|> | send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders) |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
<|fim_middle|>
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
<|fim▁end|> | if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24 |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
<|fim_middle|>
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
<|fim▁end|> | input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown") |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
<|fim_middle|>
<|fim▁end|> | reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders) |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
<|fim_middle|>
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
<|fim▁end|> | return float(time) |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
<|fim_middle|>
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
<|fim▁end|> | return float(time) * 60 |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
<|fim_middle|>
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
<|fim▁end|> | return float(time) * 60 * 60 |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
<|fim_middle|>
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
<|fim▁end|> | return float(time) * 60 * 60 * 24 |
<|file_name|>reminders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`'
action = 'typing'
hidden = True
reminders = load_json('data/reminders.json')
def to_seconds(time, unit):
if unit == 's':
return float(time)
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
<|fim_middle|>
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
if not is_int(time) or is_int(unit):
message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.'
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
try:
alarm = now() + to_seconds(time, unit)
except:
return send_message(msg['chat']['id'], message, parse_mode="Markdown")
text = all_but_first_word(input)
if not text:
send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
reminders[int(now())] = reminder
save_json('data/reminders.json', reminders)
if unit == 's':
delay = delay.replace('s', ' seconds')
if unit == 'm':
delay = delay.replace('m', ' minutes')
if unit == 'h':
delay = delay.replace('h', ' hours')
if unit == 'd':
delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
if now() > reminder['alarm']:
send_message(reminder['chat_id'], reminder['text'])
del reminders[id]
save_json('data/reminders.json', reminders)
<|fim▁end|> | doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.