_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q265200 | join_dicts | validation | def join_dicts(*dicts):
'''Join a bunch of dicts'''
out_dict = {}
for d in dicts:
for k, v in d.iteritems():
if not type(v) in JOINERS:
raise KeyError('Invalid type in dict: {}'.format(type(v)))
JOINERS[type(v)](out_dict, k, v)
return out_dict | python | {
"resource": ""
} |
q265201 | env_to_dict | validation | def env_to_dict(env, pathsep=os.pathsep):
'''
Convert a dict containing environment variables into a standard dict.
Variables containing multiple values will be split into a list based on
the argument passed to pathsep.
:param env: Environment dict like os.environ.data
:param pathsep: Path sepa... | python | {
"resource": ""
} |
q265202 | dict_to_env | validation | def dict_to_env(d, pathsep=os.pathsep):
'''
Convert a python dict to a dict containing valid environment variable
values.
:param d: Dict to convert to an env dict
:param pathsep: Path separator used to join lists(default os.pathsep)
'''
out_env = {}
for k, v in d.iteritems():
... | python | {
"resource": ""
} |
q265203 | expand_envvars | validation | def expand_envvars(env):
'''
Expand all environment variables in an environment dict
:param env: Environment dict
'''
out_env = {}
for k, v in env.iteritems():
out_env[k] = Template(v).safe_substitute(env)
# Expand twice to make sure we expand everything we possibly can
for k... | python | {
"resource": ""
} |
q265204 | get_store_env_tmp | validation | def get_store_env_tmp():
'''Returns an unused random filepath.'''
tempdir = tempfile.gettempdir()
temp_name = 'envstore{0:0>3d}'
temp_path = unipath(tempdir, temp_name.format(random.getrandbits(9)))
if not os.path.exists(temp_path):
return temp_path
else:
return get_store_env_tm... | python | {
"resource": ""
} |
q265205 | store_env | validation | def store_env(path=None):
'''Encode current environment as yaml and store in path or a temporary
file. Return the path to the stored environment.
'''
path = path or get_store_env_tmp()
env_dict = yaml.safe_dump(os.environ.data, default_flow_style=False)
with open(path, 'w') as f:
f.wr... | python | {
"resource": ""
} |
q265206 | BaseHandler.upstream_url | validation | def upstream_url(self, uri):
"Returns the URL to the upstream data source for the given URI based on configuration"
return self.application.options.upstream + self.request.uri | python | {
"resource": ""
} |
q265207 | ProxyHandler.make_upstream_request | validation | def make_upstream_request(self):
"Return request object for calling the upstream"
url = self.upstream_url(self.request.uri)
return tornado.httpclient.HTTPRequest(url,
method=self.request.method,
headers=self.request.headers,
body=self.request.body if self.requ... | python | {
"resource": ""
} |
q265208 | ProxyHandler.ttl | validation | def ttl(self, response):
"""Returns time to live in seconds. 0 means no caching.
Criteria:
- response code 200
- read-only method (GET, HEAD, OPTIONS)
Plus http headers:
- cache-control: option1, option2, ...
where options are:
private | public
... | python | {
"resource": ""
} |
q265209 | manifest | validation | def manifest():
"""Guarantee the existence of a basic MANIFEST.in.
manifest doc: http://docs.python.org/distutils/sourcedist.html#manifest
`options.paved.dist.manifest.include`: set of files (or globs) to include with the `include` directive.
`options.paved.dist.manifest.recursive_include`: set of fi... | python | {
"resource": ""
} |
q265210 | format_pathname | validation | def format_pathname(
pathname,
max_length):
"""
Format a pathname
:param str pathname: Pathname to format
:param int max_length: Maximum length of result pathname (> 3)
:return: Formatted pathname
:rtype: str
:raises ValueError: If *max_length* is not larger than 3
This... | python | {
"resource": ""
} |
q265211 | format_uuid | validation | def format_uuid(
uuid,
max_length=10):
"""
Format a UUID string
:param str uuid: UUID to format
:param int max_length: Maximum length of result string (> 3)
:return: Formatted UUID
:rtype: str
:raises ValueError: If *max_length* is not larger than 3
This function format... | python | {
"resource": ""
} |
q265212 | paginate_update | validation | def paginate_update(update):
"""
attempts to get next and previous on updates
"""
from happenings.models import Update
time = update.pub_time
event = update.event
try:
next = Update.objects.filter(
event=event,
pub_time__gt=time
).order_by('pub_time').... | python | {
"resource": ""
} |
q265213 | notify_client | validation | def notify_client(
notifier_uri,
client_id,
status_code,
message=None):
"""
Notify the client of the result of handling a request
The payload contains two elements:
- client_id
- result
The *client_id* is the id of the client to notify. It is assumed
that t... | python | {
"resource": ""
} |
q265214 | Plugin.setting | validation | def setting(self, name_hyphen):
"""
Retrieves the setting value whose name is indicated by name_hyphen.
Values starting with $ are assumed to reference environment variables,
and the value stored in environment variables is retrieved. It's an
error if thes corresponding environm... | python | {
"resource": ""
} |
q265215 | Plugin._update_settings | validation | def _update_settings(self, new_settings, enforce_helpstring=True):
"""
This method does the work of updating settings. Can be passed with
enforce_helpstring = False which you may want if allowing end users to
add arbitrary metadata via the settings system.
Preferable to use upda... | python | {
"resource": ""
} |
q265216 | Plugin.settings_and_attributes | validation | def settings_and_attributes(self):
"""Return a combined dictionary of setting values and attribute values."""
attrs = self.setting_values()
attrs.update(self.__dict__)
skip = ["_instance_settings", "aliases"]
for a in skip:
del attrs[a]
return attrs | python | {
"resource": ""
} |
q265217 | PluginMeta.get_reference_to_class | validation | def get_reference_to_class(cls, class_or_class_name):
"""
Detect if we get a class or a name, convert a name to a class.
"""
if isinstance(class_or_class_name, type):
return class_or_class_name
elif isinstance(class_or_class_name, string_types):
if ":" in... | python | {
"resource": ""
} |
q265218 | PluginMeta.check_docstring | validation | def check_docstring(cls):
"""
Asserts that the class has a docstring, returning it if successful.
"""
docstring = inspect.getdoc(cls)
if not docstring:
breadcrumbs = " -> ".join(t.__name__ for t in inspect.getmro(cls)[:-1][::-1])
msg = "docstring required ... | python | {
"resource": ""
} |
q265219 | logbookForm.resourcePath | validation | def resourcePath(self, relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
from os import path
import sys
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exc... | python | {
"resource": ""
} |
q265220 | logbookForm.addLogbook | validation | def addLogbook(self, physDef= "LCLS", mccDef="MCC", initialInstance=False):
'''Add new block of logbook selection windows. Only 5 allowed.'''
if self.logMenuCount < 5:
self.logMenus.append(LogSelectMenu(self.logui.multiLogLayout, initialInstance))
self.logMenus[-1].addLogbooks(se... | python | {
"resource": ""
} |
q265221 | logbookForm.removeLogbook | validation | def removeLogbook(self, menu=None):
'''Remove logbook menu set.'''
if self.logMenuCount > 1 and menu is not None:
menu.removeMenu()
self.logMenus.remove(menu)
self.logMenuCount -= 1 | python | {
"resource": ""
} |
q265222 | logbookForm.selectedLogs | validation | def selectedLogs(self):
'''Return selected log books by type.'''
mcclogs = []
physlogs = []
for i in range(len(self.logMenus)):
logType = self.logMenus[i].selectedType()
log = self.logMenus[i].selectedProgram()
if logType == "MCC":
if l... | python | {
"resource": ""
} |
q265223 | logbookForm.acceptedUser | validation | def acceptedUser(self, logType):
'''Verify enetered user name is on accepted MCC logbook list.'''
from urllib2 import urlopen, URLError, HTTPError
import json
isApproved = False
userName = str(self.logui.userName.text())
if userName == "":
re... | python | {
"resource": ""
} |
q265224 | logbookForm.prettify | validation | def prettify(self, elem):
"""Parse xml elements for pretty printing"""
from xml.etree import ElementTree
from re import sub
rawString = ElementTree.tostring(elem, 'utf-8')
parsedString = sub(r'(?=<[^/].*>)', '\n', rawString) # Adds newline after each closing ta... | python | {
"resource": ""
} |
q265225 | logbookForm.prepareImages | validation | def prepareImages(self, fileName, logType):
"""Convert supplied QPixmap object to image file."""
import subprocess
if self.imageType == "png":
self.imagePixmap.save(fileName + ".png", "PNG", -1)
if logType == "Physics":
makePostScript = "convert "... | python | {
"resource": ""
} |
q265226 | logbookForm.submitEntry | validation | def submitEntry(self):
"""Process user inputs and subit logbook entry when user clicks Submit button"""
# logType = self.logui.logType.currentText()
mcclogs, physlogs = self.selectedLogs()
success = True
if mcclogs != []:
if not self.acceptedUser("MC... | python | {
"resource": ""
} |
q265227 | logbookForm.sendToLogbook | validation | def sendToLogbook(self, fileName, logType, location=None):
'''Process log information and push to selected logbooks.'''
import subprocess
success = True
if logType == "MCC":
fileString = ""
if not self.imagePixmap.isNull():
fileString = fi... | python | {
"resource": ""
} |
q265228 | LogSelectMenu.setupUI | validation | def setupUI(self):
'''Create graphical objects for menus.'''
labelSizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
labelSizePolicy.setHorizontalStretch(0)
labelSizePolicy.setVerticalStretch(0)
menuSizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.... | python | {
"resource": ""
} |
q265229 | LogSelectMenu.show | validation | def show(self):
'''Display menus and connect even signals.'''
self.parent.addLayout(self._logSelectLayout)
self.menuCount += 1
self._connectSlots() | python | {
"resource": ""
} |
q265230 | LogSelectMenu.addLogbooks | validation | def addLogbooks(self, type=None, logs=[], default=""):
'''Add or change list of logbooks.'''
if type is not None and len(logs) != 0:
if type in self.logList:
for logbook in logs:
if logbook not in self.logList.get(type)[0]:
# print(... | python | {
"resource": ""
} |
q265231 | LogSelectMenu.removeLogbooks | validation | def removeLogbooks(self, type=None, logs=[]):
'''Remove unwanted logbooks from list.'''
if type is not None and type in self.logList:
if len(logs) == 0 or logs == "All":
del self.logList[type]
else:
for logbook in logs:
if logbo... | python | {
"resource": ""
} |
q265232 | LogSelectMenu.changeLogType | validation | def changeLogType(self):
'''Populate log program list to correspond with log type selection.'''
logType = self.selectedType()
programs = self.logList.get(logType)[0]
default = self.logList.get(logType)[1]
if logType in self.logList:
self.programName.clear()
... | python | {
"resource": ""
} |
q265233 | LogSelectMenu.addMenu | validation | def addMenu(self):
'''Add menus to parent gui.'''
self.parent.multiLogLayout.addLayout(self.logSelectLayout)
self.getPrograms(logType, programName) | python | {
"resource": ""
} |
q265234 | LogSelectMenu.removeLayout | validation | def removeLayout(self, layout):
'''Iteratively remove graphical objects from layout.'''
for cnt in reversed(range(layout.count())):
item = layout.takeAt(cnt)
widget = item.widget()
if widget is not None:
widget.deleteLater()
else:
... | python | {
"resource": ""
} |
q265235 | addlabel | validation | def addlabel(ax=None, toplabel=None, xlabel=None, ylabel=None, zlabel=None, clabel=None, cb=None, windowlabel=None, fig=None, axes=None):
"""Adds labels to a plot."""
if (axes is None) and (ax is not None):
axes = ax
if (windowlabel is not None) and (fig is not None):
fig.canvas.set_window... | python | {
"resource": ""
} |
q265236 | linkcode_resolve | validation | def linkcode_resolve(domain, info):
"""
Determine the URL corresponding to Python object
"""
if domain != 'py':
return None
modname = info['module']
fullname = info['fullname']
submod = sys.modules.get(modname)
if submod is None:
return None
obj = submod
for pa... | python | {
"resource": ""
} |
q265237 | syncdb | validation | def syncdb(args):
"""Update the database with model schema. Shorthand for `paver manage syncdb`.
"""
cmd = args and 'syncdb %s' % ' '.join(options.args) or 'syncdb --noinput'
call_manage(cmd)
for fixture in options.paved.django.syncdb.fixtures:
call_manage("loaddata %s" % fixture) | python | {
"resource": ""
} |
q265238 | start | validation | def start(info):
"""Run the dev server.
Uses `django_extensions <http://pypi.python.org/pypi/django-extensions/0.5>`, if
available, to provide `runserver_plus`.
Set the command to use with `options.paved.django.runserver`
Set the port to use with `options.paved.django.runserver_port`
"""
c... | python | {
"resource": ""
} |
q265239 | schema | validation | def schema(args):
"""Run South's schemamigration command.
"""
try:
import south
cmd = args and 'schemamigration %s' % ' '.join(options.args) or 'schemamigration'
call_manage(cmd)
except ImportError:
error('Could not import south.') | python | {
"resource": ""
} |
q265240 | MapperDefinition.validate | validation | def validate(cls, definition):
'''
This static method validates a BioMapMapper definition.
It returns None on success and throws an exception otherwise.
'''
schema_path = os.path.join(os.path.dirname(__file__),
'../../schema/mapper_definition_sc... | python | {
"resource": ""
} |
q265241 | Mapper.map | validation | def map(self, ID_s,
FROM=None,
TO=None,
target_as_set=False,
no_match_sub=None):
'''
The main method of this class and the essence of the package.
It allows to "map" stuff.
Args:
ID_s: Nested lists with... | python | {
"resource": ""
} |
q265242 | Mapper.get_all | validation | def get_all(self, key=None):
'''
Returns all data entries for a particular key. Default is the main key.
Args:
key (str): key whose values to return (default: main key)
Returns:
List of all data entries for the key
'''
key = self.definition.mai... | python | {
"resource": ""
} |
q265243 | FieldCutter.line | validation | def line(self, line):
"""Returns list of strings split by input delimeter
Argument:
line - Input line to cut
"""
# Remove empty strings in case of multiple instances of delimiter
return [x for x in re.split(self.delimiter, line.rstrip()) if x != ''] | python | {
"resource": ""
} |
q265244 | Messages.get_message | validation | def get_message(self, message_id):
"""
Get Existing Message
http://dev.wheniwork.com/#get-existing-message
"""
url = "/2/messages/%s" % message_id
return self.message_from_json(self._get_resource(url)["message"]) | python | {
"resource": ""
} |
q265245 | Messages.create_message | validation | def create_message(self, params={}):
"""
Creates a message
http://dev.wheniwork.com/#create/update-message
"""
url = "/2/messages/"
body = params
data = self._post_resource(url, body)
return self.message_from_json(data["message"]) | python | {
"resource": ""
} |
q265246 | Messages.update_message | validation | def update_message(self, message):
"""
Modify an existing message.
http://dev.wheniwork.com/#create/update-message
"""
url = "/2/messages/%s" % message.message_id
data = self._put_resource(url, message.json_data())
return self.message_from_json(data) | python | {
"resource": ""
} |
q265247 | Messages.delete_messages | validation | def delete_messages(self, messages):
"""
Delete existing messages.
http://dev.wheniwork.com/#delete-existing-message
"""
url = "/2/messages/?%s" % urlencode([('ids', ",".join(messages))])
data = self._delete_resource(url)
return data | python | {
"resource": ""
} |
q265248 | Sites.get_site | validation | def get_site(self, site_id):
"""
Returns site data.
http://dev.wheniwork.com/#get-existing-site
"""
url = "/2/sites/%s" % site_id
return self.site_from_json(self._get_resource(url)["site"]) | python | {
"resource": ""
} |
q265249 | Sites.get_sites | validation | def get_sites(self):
"""
Returns a list of sites.
http://dev.wheniwork.com/#listing-sites
"""
url = "/2/sites"
data = self._get_resource(url)
sites = []
for entry in data['sites']:
sites.append(self.site_from_json(entry))
return site... | python | {
"resource": ""
} |
q265250 | Sites.create_site | validation | def create_site(self, params={}):
"""
Creates a site
http://dev.wheniwork.com/#create-update-site
"""
url = "/2/sites/"
body = params
data = self._post_resource(url, body)
return self.site_from_json(data["site"]) | python | {
"resource": ""
} |
q265251 | admin_link_move_up | validation | def admin_link_move_up(obj, link_text='up'):
"""Returns a link to a view that moves the passed in object up in rank.
:param obj:
Object to move
:param link_text:
Text to display in the link. Defaults to "up"
:returns:
HTML link code to view for moving the object
"""
if ... | python | {
"resource": ""
} |
q265252 | admin_link_move_down | validation | def admin_link_move_down(obj, link_text='down'):
"""Returns a link to a view that moves the passed in object down in rank.
:param obj:
Object to move
:param link_text:
Text to display in the link. Defaults to "down"
:returns:
HTML link code to view for moving the object
"""... | python | {
"resource": ""
} |
q265253 | showfig | validation | def showfig(fig, aspect="auto"):
"""
Shows a figure with a typical orientation so that x and y axes are set up as expected.
"""
ax = fig.gca()
# Swap y axis if needed
alim = list(ax.axis())
if alim[3] < alim[2]:
temp = alim[2]
alim[2] = alim[3]
alim[3] = temp
... | python | {
"resource": ""
} |
q265254 | _setup_index | validation | def _setup_index(index):
"""Shifts indicies as needed to account for one based indexing
Positive indicies need to be reduced by one to match with zero based
indexing.
Zero is not a valid input, and as such will throw a value error.
Arguments:
index - index to shift
"""
index =... | python | {
"resource": ""
} |
q265255 | Cutter.cut | validation | def cut(self, line):
"""Returns selected positions from cut input source in desired
arrangement.
Argument:
line - input to cut
"""
result = []
line = self.line(line)
for i, field in enumerate(self.positions):
try:
ind... | python | {
"resource": ""
} |
q265256 | Cutter._setup_positions | validation | def _setup_positions(self, positions):
"""Processes positions to account for ranges
Arguments:
positions - list of positions and/or ranges to process
"""
updated_positions = []
for i, position in enumerate(positions):
ranger = re.search(r'(?P<start>-... | python | {
"resource": ""
} |
q265257 | Cutter._cut_range | validation | def _cut_range(self, line, start, current_position):
"""Performs cut for range from start position to end
Arguments:
line - input to cut
start - start of range
current_position - current position in main cut function
"""
resu... | python | {
"resource": ""
} |
q265258 | Cutter._extendrange | validation | def _extendrange(self, start, end):
"""Creates list of values in a range with output delimiters.
Arguments:
start - range start
end - range end
"""
range_positions = []
for i in range(start, end):
if i != 0:
range_pos... | python | {
"resource": ""
} |
q265259 | lock_file | validation | def lock_file(filename):
"""Locks the file by writing a '.lock' file.
Returns True when the file is locked and
False when the file was locked already"""
lockfile = "%s.lock"%filename
if isfile(lockfile):
return False
else:
with open(lockfile, "w"):
pass
ret... | python | {
"resource": ""
} |
q265260 | unlock_file | validation | def unlock_file(filename):
"""Unlocks the file by remove a '.lock' file.
Returns True when the file is unlocked and
False when the file was unlocked already"""
lockfile = "%s.lock"%filename
if isfile(lockfile):
os.remove(lockfile)
return True
else:
return False | python | {
"resource": ""
} |
q265261 | cmd_init_push_to_cloud | validation | def cmd_init_push_to_cloud(args):
"""Initiate the local catalog and push it the cloud"""
(lcat, ccat) = (args.local_catalog, args.cloud_catalog)
logging.info("[init-push-to-cloud]: %s => %s"%(lcat, ccat))
if not isfile(lcat):
args.error("[init-push-to-cloud] The local catalog does not exist: %... | python | {
"resource": ""
} |
q265262 | cmd_init_pull_from_cloud | validation | def cmd_init_pull_from_cloud(args):
"""Initiate the local catalog by downloading the cloud catalog"""
(lcat, ccat) = (args.local_catalog, args.cloud_catalog)
logging.info("[init-pull-from-cloud]: %s => %s"%(ccat, lcat))
if isfile(lcat):
args.error("[init-pull-from-cloud] The local catalog alre... | python | {
"resource": ""
} |
q265263 | ChangesetDAG.path | validation | def path(self, a_hash, b_hash):
"""Return nodes in the path between 'a' and 'b' going from
parent to child NOT including 'a' """
def _path(a, b):
if a is b:
return [a]
else:
assert len(a.children) == 1
return [a] + _path(a.... | python | {
"resource": ""
} |
q265264 | _rindex | validation | def _rindex(mylist: Sequence[T], x: T) -> int:
"""Index of the last occurrence of x in the sequence."""
return len(mylist) - mylist[::-1].index(x) - 1 | python | {
"resource": ""
} |
q265265 | create_admin | validation | def create_admin(username='admin', email='admin@admin.com', password='admin'):
"""Create and save an admin user.
:param username:
Admin account's username. Defaults to 'admin'
:param email:
Admin account's email address. Defaults to 'admin@admin.com'
:param password:
Admin acc... | python | {
"resource": ""
} |
q265266 | messages_from_response | validation | def messages_from_response(response):
"""Returns a list of the messages from the django MessageMiddleware
package contained within the given response. This is to be used during
unit testing when trying to see if a message was set properly in a view.
:param response: HttpResponse object, likely obtaine... | python | {
"resource": ""
} |
q265267 | AdminToolsMixin.authorize | validation | def authorize(self):
"""Authenticates the superuser account via the web login."""
response = self.client.login(username=self.USERNAME,
password=self.PASSWORD)
self.assertTrue(response)
self.authed = True | python | {
"resource": ""
} |
q265268 | AdminToolsMixin.authed_get | validation | def authed_get(self, url, response_code=200, headers={}, follow=False):
"""Does a django test client ``get`` against the given url after
logging in the admin first.
:param url:
URL to fetch
:param response_code:
Expected response code from the URL fetch. This va... | python | {
"resource": ""
} |
q265269 | AdminToolsMixin.authed_post | validation | def authed_post(self, url, data, response_code=200, follow=False,
headers={}):
"""Does a django test client ``post`` against the given url after
logging in the admin first.
:param url:
URL to fetch
:param data:
Dictionary to form contents to post
... | python | {
"resource": ""
} |
q265270 | AdminToolsMixin.field_value | validation | def field_value(self, admin_model, instance, field_name):
"""Returns the value displayed in the column on the web interface for
a given instance.
:param admin_model:
Instance of a :class:`admin.ModelAdmin` object that is responsible
for displaying the change list
... | python | {
"resource": ""
} |
q265271 | Imshow_Slider_Array.imgmax | validation | def imgmax(self):
"""
Highest value of input image.
"""
if not hasattr(self, '_imgmax'):
imgmax = _np.max(self.images[0])
for img in self.images:
imax = _np.max(img)
if imax > imgmax:
imgmax = imax
s... | python | {
"resource": ""
} |
q265272 | Imshow_Slider_Array.imgmin | validation | def imgmin(self):
"""
Lowest value of input image.
"""
if not hasattr(self, '_imgmin'):
imgmin = _np.min(self.images[0])
for img in self.images:
imin = _np.min(img)
if imin > imgmin:
imgmin = imin
se... | python | {
"resource": ""
} |
q265273 | spawn | validation | def spawn(func, *args, **kwargs):
""" spawns a greenlet that does not print exceptions to the screen.
if you use this function you MUST use this module's join or joinall otherwise the exception will be lost """
return gevent.spawn(wrap_uncaught_greenlet_exceptions(func), *args, **kwargs) | python | {
"resource": ""
} |
q265274 | _usage | validation | def _usage(prog_name=os.path.basename(sys.argv[0])):
'''Returns usage string with no trailing whitespace.'''
spacer = ' ' * len('usage: ')
usage = prog_name + ' -b LIST [-S SEPARATOR] [file ...]\n' \
+ spacer + prog_name + ' -c LIST [-S SEPERATOR] [file ...]\n' \
+ spacer + prog_name \
... | python | {
"resource": ""
} |
q265275 | _parse_args | validation | def _parse_args(args):
"""Setup argparser to process arguments and generate help"""
# parser uses custom usage string, with 'usage: ' removed, as it is
# added automatically via argparser.
parser = argparse.ArgumentParser(description="Remove and/or rearrange "
+ "se... | python | {
"resource": ""
} |
q265276 | open_s3 | validation | def open_s3(bucket):
"""
Opens connection to S3 returning bucket and key
"""
conn = boto.connect_s3(options.paved.s3.access_id, options.paved.s3.secret)
try:
bucket = conn.get_bucket(bucket)
except boto.exception.S3ResponseError:
bucket = conn.create_bucket(bucket)
return buc... | python | {
"resource": ""
} |
q265277 | upload_s3 | validation | def upload_s3(file_path, bucket_name, file_key, force=False, acl='private'):
"""Upload a local file to S3.
"""
file_path = path(file_path)
bucket = open_s3(bucket_name)
if file_path.isdir():
# Upload the contents of the dir path.
paths = file_path.listdir()
paths_keys = list... | python | {
"resource": ""
} |
q265278 | download_s3 | validation | def download_s3(bucket_name, file_key, file_path, force=False):
"""Download a remote file from S3.
"""
file_path = path(file_path)
bucket = open_s3(bucket_name)
file_dir = file_path.dirname()
file_dir.makedirs()
s3_key = bucket.get_key(file_key)
if file_path.exists():
file_data... | python | {
"resource": ""
} |
q265279 | create_ical | validation | def create_ical(request, slug):
""" Creates an ical .ics file for an event using python-card-me. """
event = get_object_or_404(Event, slug=slug)
# convert dates to datetimes.
# when we change code to datetimes, we won't have to do this.
start = event.start_date
start = datetime.datetime(start.ye... | python | {
"resource": ""
} |
q265280 | event_all_comments_list | validation | def event_all_comments_list(request, slug):
"""
Returns a list view of all comments for a given event.
Combines event comments and update comments in one list.
"""
event = get_object_or_404(Event, slug=slug)
comments = event.all_comments
page = int(request.GET.get('page', 99999)) # feed emp... | python | {
"resource": ""
} |
q265281 | event_update_list | validation | def event_update_list(request, slug):
"""
Returns a list view of updates for a given event.
If the event is over, it will be in chronological order.
If the event is upcoming or still going,
it will be in reverse chronological order.
"""
event = get_object_or_404(Event, slug=slug)
updates... | python | {
"resource": ""
} |
q265282 | video_list | validation | def video_list(request, slug):
"""
Displays list of videos for given event.
"""
event = get_object_or_404(Event, slug=slug)
return render(request, 'video/video_list.html', {
'event': event,
'video_list': event.eventvideo_set.all()
}) | python | {
"resource": ""
} |
q265283 | add_event | validation | def add_event(request):
""" Public form to add an event. """
form = AddEventForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.sites = settings.SITE_ID
instance.submitted_by = request.user
instance.approved = True
instance.slug ... | python | {
"resource": ""
} |
q265284 | add_memory | validation | def add_memory(request, slug):
""" Adds a memory to an event. """
event = get_object_or_404(Event, slug=slug)
form = MemoryForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.event = event
... | python | {
"resource": ""
} |
q265285 | SketchRunner.__register_library | validation | def __register_library(self, module_name: str, attr: str, fallback: str = None):
"""Inserts Interpreter Library of imports into sketch in a very non-consensual way"""
# Import the module Named in the string
try:
module = importlib.import_module(module_name)
# If module is n... | python | {
"resource": ""
} |
q265286 | EllipseBeam.set_moments | validation | def set_moments(self, sx, sxp, sxxp):
"""
Sets the beam moments directly.
Parameters
----------
sx : float
Beam moment where :math:`\\text{sx}^2 = \\langle x^2 \\rangle`.
sxp : float
Beam moment where :math:`\\text{sxp}^2 = \\langle x'^2 \\rangle`... | python | {
"resource": ""
} |
q265287 | EllipseBeam.set_Courant_Snyder | validation | def set_Courant_Snyder(self, beta, alpha, emit=None, emit_n=None):
"""
Sets the beam moments indirectly using Courant-Snyder parameters.
Parameters
----------
beta : float
Courant-Snyder parameter :math:`\\beta`.
alpha : float
Courant-Snyder param... | python | {
"resource": ""
} |
q265288 | normalize_slice | validation | def normalize_slice(slice_obj, length):
"""
Given a slice object, return appropriate values for use in the range function
:param slice_obj: The slice object or integer provided in the `[]` notation
:param length: For negative indexing we need to know the max length of the object.
"""
if isinsta... | python | {
"resource": ""
} |
q265289 | BaseValidator.error | validation | def error(self, error_code, value, **kwargs):
"""
Helper to add error to messages field. It fills placeholder with extra call parameters
or values from message_value map.
:param error_code: Error code to use
:rparam error_code: str
:param value: Value checked
:pa... | python | {
"resource": ""
} |
q265290 | copy | validation | def copy(src, dst):
"""File copy that support compress and decompress of zip files"""
(szip, dzip) = (src.endswith(".zip"), dst.endswith(".zip"))
logging.info("Copy: %s => %s"%(src, dst))
if szip and dzip:#If both zipped, we can simply use copy
shutil.copy2(src, dst)
elif szip:
wit... | python | {
"resource": ""
} |
q265291 | apply_changesets | validation | def apply_changesets(args, changesets, catalog):
"""Apply to the 'catalog' the changesets in the metafile list 'changesets'"""
tmpdir = tempfile.mkdtemp()
tmp_patch = join(tmpdir, "tmp.patch")
tmp_lcat = join(tmpdir, "tmp.lcat")
for node in changesets:
remove(tmp_patch)
copy(node.... | python | {
"resource": ""
} |
q265292 | AddEventForm.clean | validation | def clean(self):
"""
Validate that an event with this name on this date does not exist.
"""
cleaned = super(EventForm, self).clean()
if Event.objects.filter(name=cleaned['name'], start_date=cleaned['start_date']).count():
raise forms.ValidationError(u'This event appea... | python | {
"resource": ""
} |
q265293 | loop_in_background | validation | def loop_in_background(interval, callback):
"""
When entering the context, spawns a greenlet that sleeps for `interval` seconds between `callback` executions.
When leaving the context stops the greenlet.
The yielded object is the `GeventLoop` object so the loop can be stopped from within the context.
... | python | {
"resource": ""
} |
q265294 | GeventLoopBase._loop | validation | def _loop(self):
"""Main loop - used internally."""
while True:
try:
with uncaught_greenlet_exception_context():
self._loop_callback()
except gevent.GreenletExit:
break
if self._stop_event.wait(self._interval):
... | python | {
"resource": ""
} |
q265295 | GeventLoopBase.start | validation | def start(self):
"""
Starts the loop. Calling a running loop is an error.
"""
assert not self.has_started(), "called start() on an active GeventLoop"
self._stop_event = Event()
# note that we don't use safe_greenlets.spawn because we take care of it in _loop by ourselves
... | python | {
"resource": ""
} |
q265296 | GeventLoopBase.kill | validation | def kill(self):
"""Kills the running loop and waits till it gets killed."""
assert self.has_started(), "called kill() on a non-active GeventLoop"
self._stop_event.set()
self._greenlet.kill()
self._clear() | python | {
"resource": ""
} |
q265297 | NonUniformImage | validation | def NonUniformImage(x, y, z, ax=None, fig=None, cmap=None, alpha=None, scalex=True, scaley=True, add_cbar=True, **kwargs):
"""
Used to plot a set of coordinates.
Parameters
----------
x, y : :class:`numpy.ndarray`
1-D ndarrays of lengths N and M, respectively, specifying pixel centers
... | python | {
"resource": ""
} |
q265298 | LatexFixer._sentence_to_interstitial_spacing | validation | def _sentence_to_interstitial_spacing(self):
"""Fix common spacing errors caused by LaTeX's habit
of using an inter-sentence space after any full stop."""
not_sentence_end_chars = [' ']
abbreviations = ['i.e.', 'e.g.', ' v.',
' w.', ' wh.']
titles = ['Prof.', 'Mr.', ... | python | {
"resource": ""
} |
q265299 | LatexFixer._hyphens_to_dashes | validation | def _hyphens_to_dashes(self):
"""Transform hyphens to various kinds of dashes"""
problematic_hyphens = [(r'-([.,!)])', r'---\1'),
(r'(?<=\d)-(?=\d)', '--'),
(r'(?<=\s)-(?=\s)', '---')]
for problem_case in problematic_hyphens:
self._... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.