_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q51700 | batch_stream | train | def batch_stream(buff, stream, size=DEFAULT_BATCH_SIZE):
"""Writes a batch of `size` lines to `buff`.
Returns boolean of whether the stream has been exhausted.
"""
buff.truncate(0)
for _ in xrange(size):
if hasattr(stream, 'readline'):
line = stream.readline()
else:
... | python | {
"resource": ""
} |
q51701 | Notification.to_binary_string | train | def to_binary_string(self):
"""Pack the notification to binary form and return it as string."""
if self.priority not in self.PRIORITIES:
raise NotificationInvalidPriorityError()
try:
token = binascii.unhexlify(self.token)
except TypeError as error:
ra... | python | {
"resource": ""
} |
q51702 | Notification.from_binary_string | train | def from_binary_string(self, notification):
"""Unpack the notification from binary string."""
command = struct.unpack('>B', notification[0])[0]
if command != self.COMMAND:
raise NotificationInvalidCommandError()
length = struct.unpack('>I', notification[1:5])[0]
not... | python | {
"resource": ""
} |
q51703 | HttpTransport.open | train | def open(self, request):
"""
Open a SOAP WSDL
:param request: :class:`suds.transport.Request <suds.transport.Request>` object
:return: WSDL Content as a file-like object
:rtype: io.BytesIO
"""
url = request.url
logger.debug('Opening WSDL: %s ' % url)
... | python | {
"resource": ""
} |
q51704 | HttpTransport.send | train | def send(self, request):
"""
Send a SOAP method call
:param request: :class:`suds.transport.Request <suds.transport.Request>` object
:return: :class:`suds.transport.Reply <suds.transport.Reply>` object
:rtype: suds.transport.Reply
"""
url = request.url
ms... | python | {
"resource": ""
} |
q51705 | HttpTransport.proxies | train | def proxies(self, url):
"""
Get the transport proxy configuration
:param url: string
:return: Proxy configuration dictionary
:rtype: Dictionary
"""
netloc = urllib.parse.urlparse(url).netloc
proxies = {}
if settings.PROXIES and settings.PROXIES.ge... | python | {
"resource": ""
} |
q51706 | _parse_flags | train | def _parse_flags(element):
"""Parse OSM XML element for generic data.
Args:
element (etree.Element): Element to parse
Returns:
tuple: Generic OSM data for object instantiation
"""
visible = True if element.get('visible') else False
user = element.get('user')
timestamp = ele... | python | {
"resource": ""
} |
q51707 | _get_flags | train | def _get_flags(osm_obj):
"""Create element independent flags output.
Args:
osm_obj (Node): Object with OSM-style metadata
Returns:
list: Human readable flags output
"""
flags = []
if osm_obj.visible:
flags.append('visible')
if osm_obj.user:
flags.append('use... | python | {
"resource": ""
} |
q51708 | get_area_url | train | def get_area_url(location, distance):
"""Generate URL for downloading OSM data within a region.
This function defines a boundary box where the edges touch a circle of
``distance`` kilometres in radius. It is important to note that the box is
neither a square, nor bounded within the circle.
The bo... | python | {
"resource": ""
} |
q51709 | Node.toosm | train | def toosm(self):
"""Generate a OSM node element subtree.
Returns:
etree.Element: OSM node element
"""
node = create_elem('node', {'id': str(self.ident),
'lat': str(self.latitude),
'lon': str(self.longitu... | python | {
"resource": ""
} |
q51710 | Node.parse_elem | train | def parse_elem(element):
"""Parse a OSM node XML element.
Args:
element (etree.Element): XML Element to parse
Returns:
Node: Object representing parsed element
"""
ident = int(element.get('id'))
latitude = element.get('lat')
longitude = e... | python | {
"resource": ""
} |
q51711 | Osm.import_locations | train | def import_locations(self, osm_file):
"""Import OSM data files.
``import_locations()`` returns a list of ``Node`` and ``Way`` objects.
It expects data files conforming to the `OpenStreetMap 0.5 DTD`_, which
is XML such as::
<?xml version="1.0" encoding="UTF-8"?>
... | python | {
"resource": ""
} |
q51712 | Osm.export_osm_file | train | def export_osm_file(self):
"""Generate OpenStreetMap element tree from ``Osm``."""
osm = create_elem('osm', {'generator': self.generator,
'version': self.version})
osm.extend(obj.toosm() for obj in self)
return etree.ElementTree(osm) | python | {
"resource": ""
} |
q51713 | resolve_url_ext | train | def resolve_url_ext(to, params_=None, anchor_=None, args=None, kwargs=None):
"""
Advanced resolve_url which can includes GET-parameters and anchor.
"""
url = resolve_url(to, *(args or ()), **(kwargs or {}))
if params_:
url += '?' + urllib.urlencode(encode_url_query_params(params_))
if an... | python | {
"resource": ""
} |
q51714 | redirect_ext | train | def redirect_ext(to, params_=None, anchor_=None, permanent_=False, args=None, kwargs=None):
"""
Advanced redirect which can includes GET-parameters and anchor.
"""
if permanent_:
redirect_class = HttpResponsePermanentRedirect
else:
redirect_class = HttpResponseRedirect
return red... | python | {
"resource": ""
} |
q51715 | Service.log | train | def log(self, level, *args, **kwargs):
"""Log something.
.. seealso:: Proxy:
:class:`.Logger`.level
"""
target = getattr(self.__logger, level)
target(*args, **kwargs) | python | {
"resource": ""
} |
q51716 | json_pretty_print | train | def json_pretty_print(s):
'''pretty print JSON'''
s = json.loads(s)
return json.dumps(s,
sort_keys=True,
indent=4,
separators=(',', ': ')) | python | {
"resource": ""
} |
q51717 | resample | train | def resample(old_wavelengths, new_wavelengths):
"""
Resample a spectrum to a new wavelengths map while conserving total flux.
:param old_wavelengths:
The original wavelengths array.
:type old_wavelengths:
:class:`numpy.array`
:param new_wavelengths:
The new wavelengths arr... | python | {
"resource": ""
} |
q51718 | _process_json | train | def _process_json(data):
"""
return a list of GradLeave objects.
"""
requests = []
for item in data:
leave = GradLeave()
leave.reason = item.get('leaveReason')
leave.submit_date = datetime_from_string(item.get('submitDate'))
if item.get('status') is not None and len(i... | python | {
"resource": ""
} |
q51719 | Pagure._call_api | train | def _call_api(self, url, method='GET', params=None, data=None):
""" Method used to call the API.
It returns the raw JSON returned by the API or raises an exception
if something goes wrong.
:arg url: the URL to call
:kwarg method: the HTTP method to use when calling the specified... | python | {
"resource": ""
} |
q51720 | Pagure.create_basic_url | train | def create_basic_url(self):
""" Create URL prefix for API calls based on type of repo.
Repo may be forked and may be in namespace. That makes total 4
different types of URL.
:return:
"""
if self.username is None:
if self.namespace is None:
re... | python | {
"resource": ""
} |
q51721 | Pagure.user_activity_stats | train | def user_activity_stats(self, username, format=None):
"""
Retrieve the activity stats about a specific user over the last year.
Params:
username (string): filters the username of the user whose activity you are interested in.
format (string): Allows changing the of the d... | python | {
"resource": ""
} |
q51722 | Pagure.user_activity_stats_by_date | train | def user_activity_stats_by_date(self, username, date, grouped=None):
"""
Retrieve activity information about a specific user on the specified date.
Params:
username (string): filters the username of the user whose activity you are interested in.
date (string): filters b... | python | {
"resource": ""
} |
q51723 | Pagure.list_pull_requests | train | def list_pull_requests(self, username, page, status=None):
"""
List pull-requests filed by user.
Params:
username (string): filters the username of the user whose activity you are interested in.
page (integer): the page requested. Defaults to 1.
status (strin... | python | {
"resource": ""
} |
q51724 | determine_pool_size | train | def determine_pool_size(job_vector):
"""This function determines how large of a pool to make based on the
system resources currently available and how many jobs there are
to complete.
"""
available_threads = cpu_count()
total_jobs = len(job_vector)
threads_to_pass = total_jobs
if total_... | python | {
"resource": ""
} |
q51725 | main | train | def main():
"""1. Parse args
2. Figure out which directories are actually meraculous run directories
3. Make an instance for each directory and generate a report
"""
home = os.getcwd()
options = parse_arguments()
print(options)
print()
#get a list of all directories in the cwd
d... | python | {
"resource": ""
} |
q51726 | MessageThread.run | train | def run(self):
"""Run message thread."""
while not self.stopped:
try:
# grab a message from queue
message = self.gc100_client.queue.get(True, 5)
except queue.Empty:
_LOGGER.debug("message thread: no messages")
... | python | {
"resource": ""
} |
q51727 | GC100SocketClient.send | train | def send(self, data):
"""Send data to socket."""
# send message
_LOGGER.debug("send: " + data)
self.socket.send(data.encode('ascii'))
# sleep needed to prevent flooding the GC100 with sends
sleep(.01) | python | {
"resource": ""
} |
q51728 | GC100SocketClient.receive | train | def receive(self):
"""Receive data from socket."""
while True:
try:
# read data from the buffer
data = self.socket.recv(self._socket_recv)
except socket.timeout as e:
_LOGGER.debug(e)
sleep(1)
... | python | {
"resource": ""
} |
q51729 | GC100SocketClient.quit | train | def quit(self):
"""Close threads and socket."""
# stop all threads and close the socket
self.receive_thread.stopped = True
# self.receive_thread._Thread__stop()
self.message_thread.stopped = True
# self.message_thread._Thread__stop()
# self.ping_thread.... | python | {
"resource": ""
} |
q51730 | GC100SocketClient.write_switch | train | def write_switch(self, module_address, state, callback_fn):
"""Set relay state."""
_LOGGER.info("write_switch: setstate,{},{}{}"
.format(module_address, str(state), chr(13)))
self.subscribe("state," + module_address, callback_fn)
self.send("setstate,{},{}{}"
... | python | {
"resource": ""
} |
q51731 | ConfigLoader.load_application_info | train | def load_application_info(path):
"""Will load info.json at given path.
The info.json is used to store build/version information.
:param path: directory where to find your config files. Example: resources/
:return: info.json as dictionary.
"""
with open(path + 'info.json... | python | {
"resource": ""
} |
q51732 | auto_delete_cohort | train | def auto_delete_cohort(instance, **kwargs):
"Deletes and auto-created cohort named after the instance."
cohorts = Cohort.objects.filter(autocreated=True)
if isinstance(instance, Project):
cohorts = cohorts.filter(project=instance)
elif isinstance(instance, Batch):
cohorts = cohorts.filt... | python | {
"resource": ""
} |
q51733 | update_batch_count | train | def update_batch_count(instance, **kwargs):
"""Sample post-save handler to update the sample's batch count.
Batches are unpublished by default (to prevent publishing empty batches).
If the `AUTO_PUBLISH_BATCH` setting is true, the batch will be published
automatically when at least one published sample... | python | {
"resource": ""
} |
q51734 | get_ratings | train | def get_ratings(data):
"""Ratings of all the episodes of all the seasons"""
episodes = data['episodes']
ratings = {}
for season in episodes:
ratings[season] = collapse(episodes[season])
return co.OrderedDict(sorted(ratings.items())) | python | {
"resource": ""
} |
q51735 | luhn | train | def luhn(base, num_only=False, allow_lower_case=False):
"""Return the Luhn check digit for the given string.
Args:
base(str): string for which to calculate the check digit
num_only(bool): allow only digits in `base` (default: False)
allow_lower_case(bool): allow lower case letters in `b... | python | {
"resource": ""
} |
q51736 | get_db_session | train | def get_db_session(engine):
"Given a DB engine return a DB session bound to that engine"
db = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
db.configure(bind=engine)
db.autoflush = True
return db | python | {
"resource": ""
} |
q51737 | weakref_proxy | train | def weakref_proxy(obj):
"""returns either a weakref.proxy for the object, or if object is already a proxy,
returns itself."""
if type(obj) in weakref.ProxyTypes:
return obj
else:
return weakref.proxy(obj) | python | {
"resource": ""
} |
q51738 | Writer.write | train | def write(self, byte):
"""
Writes a byte buffer to the underlying output file.
Raise exception when file is already closed.
"""
if self.is_closed_flag:
raise Exception("Unable to write - already closed!")
self.written += len(byte)
self.file.write(byte) | python | {
"resource": ""
} |
q51739 | Writer.write_bool | train | def write_bool(self, flag):
""" Writes a boolean to the underlying output file as a 1-byte value. """
if flag:
self.write(b"\x01")
else:
self.write(b"\x00") | python | {
"resource": ""
} |
q51740 | Writer.write_short | train | def write_short(self, number):
""" Writes a short integer to the underlying output file as a 2-byte value. """
buf = pack(self.byte_order + "h", number)
self.write(buf) | python | {
"resource": ""
} |
q51741 | Writer.write_int | train | def write_int(self, number):
""" Writes a integer to the underlying output file as a 4-byte value. """
buf = pack(self.byte_order + "i", number)
self.write(buf) | python | {
"resource": ""
} |
q51742 | Writer.write_long | train | def write_long(self, number):
""" Writes a long integer to the underlying output file as a 8-byte value. """
buf = pack(self.byte_order + "q", number)
self.write(buf) | python | {
"resource": ""
} |
q51743 | Writer.write_string | train | def write_string(self, string):
""" Writes a string to the underlying output file as a buffer of chars with UTF-8 encoding. """
buf = bytes(string, 'UTF-8')
length = len(buf)
self.write_int(length)
self.write(buf) | python | {
"resource": ""
} |
q51744 | Writer.write_float | train | def write_float(self, number):
""" Writes a float to the underlying output file as a 4-byte value. """
buf = pack(self.byte_order + "f", number)
self.write(buf) | python | {
"resource": ""
} |
q51745 | Writer.write_double | train | def write_double(self, number):
""" Writes a double to the underlying output file as a 8-byte value. """
buf = pack(self.byte_order + "d", number)
self.write(buf) | python | {
"resource": ""
} |
q51746 | ivorn_present | train | def ivorn_present(session, ivorn):
"""
Predicate, returns whether the IVORN is in the database.
"""
return bool(
session.query(Voevent.id).filter(Voevent.ivorn == ivorn).count()) | python | {
"resource": ""
} |
q51747 | ivorn_prefix_present | train | def ivorn_prefix_present(session, ivorn_prefix):
"""
Predicate, returns whether there is an entry in the database with matching
IVORN prefix.
"""
n_matches = session.query(Voevent.ivorn).filter(
Voevent.ivorn.like('{}%'.format(ivorn_prefix))).count()
return bool(n_matches) | python | {
"resource": ""
} |
q51748 | safe_insert_voevent | train | def safe_insert_voevent(session, etree):
"""
Insert a VOEvent, or skip with a warning if it's a duplicate.
NB XML contents are checked to confirm duplication - if there's a mismatch,
we raise a ValueError.
"""
new_row = Voevent.from_etree(etree)
if not ivorn_present(session, new_row.ivorn):... | python | {
"resource": ""
} |
q51749 | cmd | train | def cmd(binary, subcommand, *args, **kwargs):
"""
Construct a command line for a "modern UNIX" command.
Modern UNIX command do a closely-related-set-of-things and do it well.
Examples include :code:`apt-get` or :code:`git`.
:param binary: the name of the command
:param subcommand: the subcomma... | python | {
"resource": ""
} |
q51750 | _FormatTypeCheck | train | def _FormatTypeCheck(type_):
"""Pretty format of type check."""
if isinstance(type_, tuple):
items = [_FormatTypeCheck(t) for t in type_]
return "(%s)" % ", ".join(items)
elif hasattr(type_, "__name__"):
return type_.__name__
else:
return repr(type_) | python | {
"resource": ""
} |
q51751 | _ValidateValue | train | def _ValidateValue(value, type_check):
"""Validate a single value with type_check."""
if inspect.isclass(type_check):
return isinstance(value, type_check)
if isinstance(type_check, tuple):
return _ValidateTuple(value, type_check)
elif callable(type_check):
return type_check(value)
else:
raise ... | python | {
"resource": ""
} |
q51752 | _ParseTypeCheckString | train | def _ParseTypeCheckString(type_check_string, stack_location, self_name):
"""Convert string version of a type_check into a python instance.
Type checks can be either defined directly in python code or in a string.
The syntax is exactly the same since we use eval to parse the string.
:param int stack_location: ... | python | {
"resource": ""
} |
q51753 | _ParseDocstring | train | def _ParseDocstring(function):
"""Parses the functions docstring into a dictionary of type checks."""
if not function.__doc__:
return {}
type_check_dict = {}
for match in param_regexp.finditer(function.__doc__):
param_str = match.group(1).strip()
param_splitted = param_str.split(" ")
if len(par... | python | {
"resource": ""
} |
q51754 | _CollectArguments | train | def _CollectArguments(function, args, kwargs):
"""Merges positional and keyword arguments into a single dict."""
all_args = dict(kwargs)
arg_names = inspect.getargspec(function)[0]
for position, arg in enumerate(args):
if position < len(arg_names):
all_args[arg_names[position]] = arg
return all_args | python | {
"resource": ""
} |
q51755 | _CollectTypeChecks | train | def _CollectTypeChecks(function, parent_type_check_dict, stack_location,
self_name):
"""Collect all type checks for this function."""
type_check_dict = dict(parent_type_check_dict)
type_check_dict.update(_ParseDocstring(function))
# Convert any potential string based checks into python in... | python | {
"resource": ""
} |
q51756 | _ValidateArguments | train | def _ValidateArguments(arg_dict, type_check_dict):
"""Validate dictionary of arguments and return list of errors messages."""
messages = []
for arg_name, arg_value in arg_dict.items():
if arg_name in type_check_dict:
type_check = type_check_dict[arg_name]
res = _ValidateValue(arg_value, type_check... | python | {
"resource": ""
} |
q51757 | _ValidateReturnValue | train | def _ValidateReturnValue(return_value, type_check_dict):
"""Validate return value and return list of errors messages."""
return_check = type_check_dict.get("returns", None)
if not return_check:
return []
messages = []
if not _ValidateValue(return_value, return_check):
message = ("Invalid return value... | python | {
"resource": ""
} |
q51758 | _TypecheckFunction | train | def _TypecheckFunction(function, parent_type_check_dict, stack_location,
self_name):
"""Decorator function to collect and execute type checks."""
type_check_dict = _CollectTypeChecks(function, parent_type_check_dict,
stack_location + 1, self_name)
if not... | python | {
"resource": ""
} |
q51759 | _TypecheckDecorator | train | def _TypecheckDecorator(subject=None, **kwargs):
"""Dispatches type checks based on what the subject is.
Functions or methods are annotated directly. If this method is called
with keyword arguments only, return a decorator.
"""
if subject is None:
return _TypecheckDecoratorFactory(kwargs)
elif inspect.... | python | {
"resource": ""
} |
q51760 | TypecheckMeta.Decorate | train | def Decorate(cls, class_name, member, parent_member):
"""Decorates a member with @typecheck. Inherit checks from parent member."""
if isinstance(member, property):
fget = cls.DecorateMethod(class_name, member.fget, parent_member)
fset = None
if member.fset:
fset = cls.DecorateMethod(cl... | python | {
"resource": ""
} |
q51761 | TypecheckMeta.FindTypecheckParent | train | def FindTypecheckParent(cls, parents):
"""Find parent class that uses this metaclass."""
for parent in parents:
if hasattr(parent, "__metaclass__") and parent.__metaclass__ == cls:
return parent
return None | python | {
"resource": ""
} |
q51762 | TypecheckMeta.FindParentMember | train | def FindParentMember(cls, typecheck_parent, name):
"""Returns member by name from parent class if it exists."""
if typecheck_parent and hasattr(typecheck_parent, name):
return getattr(typecheck_parent, name)
return None | python | {
"resource": ""
} |
q51763 | submit_results | train | def submit_results(job_id, errors, log_file, results_uri, results_data=None):
"""Receive the submission of the results of a crawl job.
Then it spawns the appropiate workflow according to whichever workflow
the crawl job specifies.
:param job_id: Id of the crawler job.
:param errors: Errors that ha... | python | {
"resource": ""
} |
q51764 | schedule_crawl | train | def schedule_crawl(spider, workflow, **kwargs):
"""Schedule a crawl using configuration from the workflow objects."""
from inspire_crawler.utils import get_crawler_instance
crawler = get_crawler_instance()
crawler_settings = current_app.config.get('CRAWLER_SETTINGS')
crawler_settings.update(kwargs.... | python | {
"resource": ""
} |
q51765 | SchemaGenerator.get_link | train | def get_link(self, path, method, callback, view):
"""
Return a `coreapi.Link` instance for the given endpoint.
"""
fields = self.get_path_fields(path, method, callback, view)
fields += self.get_serializer_fields(path, method, callback, view)
fields += self.get_pagination_... | python | {
"resource": ""
} |
q51766 | Placemark.tokml | train | def tokml(self):
"""Generate a KML Placemark element subtree.
Returns:
etree.Element: KML Placemark element
"""
placemark = create_elem('Placemark')
if self.name:
placemark.set('id', self.name)
placemark.name = create_elem('name', text=self.na... | python | {
"resource": ""
} |
q51767 | Placemarks.import_locations | train | def import_locations(self, kml_file):
"""Import KML data files.
``import_locations()`` returns a dictionary with keys containing the
section title, and values consisting of :class:`Placemark` objects.
It expects data files in KML format, as specified in `KML Reference`_,
which ... | python | {
"resource": ""
} |
q51768 | Placemarks.export_kml_file | train | def export_kml_file(self):
"""Generate KML element tree from ``Placemarks``.
Returns:
etree.ElementTree: KML element tree depicting ``Placemarks``
"""
kml = create_elem('kml')
kml.Document = create_elem('Document')
for place in sorted(self.values(), key=lambd... | python | {
"resource": ""
} |
q51769 | Paginator.to_simple | train | def to_simple(self, serializer=None):
""" Prepare to serialization.
:return dict: paginator params
"""
return dict(
count=self.paginator.count,
page=self.page_number,
num_pages=self.paginator.num_pages,
next=self.next_page,
pr... | python | {
"resource": ""
} |
q51770 | Paginator.page | train | def page(self):
""" Get current page.
:return int: page number
"""
if not self._page:
try:
self._page = self.paginator.page(
self.query_dict.get('page', 1))
except InvalidPage:
raise HttpError("Invalid page", s... | python | {
"resource": ""
} |
q51771 | Paginator.next_page | train | def next_page(self):
""" Return URL for next page.
:return str:
"""
if self.page.has_next():
self.query_dict['page'] = self.page.next_page_number()
return "%s?%s" % (self.path, urlencode(self.query_dict))
return "" | python | {
"resource": ""
} |
q51772 | Paginator.previous_page | train | def previous_page(self):
""" Return URL for previous page.
:return str:
"""
if self.page.has_previous():
previous = self.page.previous_page_number()
if previous == 1:
if 'page' in self.query_dict:
del self.query_dict['page']
... | python | {
"resource": ""
} |
q51773 | shuffle_characters | train | def shuffle_characters(s):
'''Randomly shuffle the characters in a string'''
s = list(s)
random.shuffle(s)
s =''.join(s)
return s | python | {
"resource": ""
} |
q51774 | monkey_patch | train | def monkey_patch():
"""monkey patch `time` module to use out versions"""
reset()
time_mod.time = time
time_mod.sleep = sleep
time_mod.gmtime = gmtime
time_mod.localtime = localtime
time_mod.ctime = ctime
time_mod.asctime = asctime
time_mod.strftime = strftime | python | {
"resource": ""
} |
q51775 | monkey_restore | train | def monkey_restore():
"""restore real versions. Inverse of `monkey_patch`"""
for k, v in originals.items():
setattr(time_mod, k, v)
global epoch
epoch = None | python | {
"resource": ""
} |
q51776 | _grab_xpath | train | def _grab_xpath(root, xpath, converter=lambda x: x):
"""
XML convenience - grabs the first element at xpath if present, else returns None.
"""
elements = root.xpath(xpath)
if elements:
return converter(str(elements[0]))
else:
return None | python | {
"resource": ""
} |
q51777 | _has_bad_coords | train | def _has_bad_coords(root, stream):
"""
Predicate function encapsulating 'data clean up' filter code.
Currently minimal, but these sort of functions tend to grow over time.
Problem 1:
Some of the GCN packets have an RA /Dec equal to (0,0) in the WhereWhen,
and a flag in the What signify... | python | {
"resource": ""
} |
q51778 | OdictMixin.to_odict | train | def to_odict(self, exclude=None):
"""
Returns an OrderedDict representation of the SQLalchemy table row.
"""
if exclude is None:
exclude = tuple()
colnames = [c.name for c in self.__table__.columns
if c.name not in exclude]
return OrderedDi... | python | {
"resource": ""
} |
q51779 | Voevent.from_etree | train | def from_etree(root, received=pytz.UTC.localize(datetime.utcnow())):
"""
Init a Voevent row from an LXML etree loaded with voevent-parse
"""
ivorn = root.attrib['ivorn']
# Stream- Everything except before the '#' separator,
# with the prefix 'ivo://' removed:
stre... | python | {
"resource": ""
} |
q51780 | Cite.from_etree | train | def from_etree(root):
"""
Load up the citations, if present, for initializing with the Voevent.
"""
cite_list = []
citations = root.xpath('Citations/EventIVORN')
if citations:
description = root.xpath('Citations/Description')
if description:
... | python | {
"resource": ""
} |
q51781 | Coord.from_etree | train | def from_etree(root):
"""
Load up the coords, if present, for initializing with the Voevent.
.. note::
Current implementation is quite slack with regard to co-ordinate
systems - it is assumed that, for purposes of searching the database
using spatial queries... | python | {
"resource": ""
} |
q51782 | URLMapperMixin.generate_url | train | def generate_url(self, name: str, **kwargs) -> str:
""" generate url with urlgenerator used by urldispatch"""
return self.urlmapper.generate(name, **kwargs) | python | {
"resource": ""
} |
q51783 | floor | train | def floor(start, resolution):
"""Floor a datetime by a resolution.
>>> now = datetime(2012, 7, 6, 20, 33, 16, 573225)
>>> floor(now, STEP_1_HOUR)
datetime.datetime(2012, 7, 6, 20, 0)
"""
if resolution == STEP_10_SEC:
return datetime(start.year, start.month, start.day, start.hour,
... | python | {
"resource": ""
} |
q51784 | _timedelta_total_seconds | train | def _timedelta_total_seconds(td):
"""Python 2.6 backward compatibility function for timedelta.total_seconds.
:type td: timedelta object
:param td: timedelta object
:rtype: float
:return: The total number of seconds for the given timedelta object.
"""
if hasattr(timedelta, "total_seconds")... | python | {
"resource": ""
} |
q51785 | _process_json | train | def _process_json(data):
"""
return a list of GradCommittee objects.
"""
requests = []
for item in data:
committee = GradCommittee()
committee.status = item.get('status')
committee.committee_type = item.get('committeeType')
committee.dept = item.get('dept')
co... | python | {
"resource": ""
} |
q51786 | Similar.results | train | def results(self):
"""
Returns a list of tuple, ordered by similarity.
"""
d = dict()
words = [word.strip() for word in self.haystack]
if not words:
raise NoResultException('No similar word found.')
for w in words:
d[w] = Levenshtein.rati... | python | {
"resource": ""
} |
q51787 | json_to_csv | train | def json_to_csv(json_input):
'''
Convert simple JSON to CSV
Accepts a JSON string or JSON object
'''
try:
json_input = json.loads(json_input)
except:
pass # If loads fails, it's probably already parsed
headers = set()
for json_row in json_input:
headers.update(jso... | python | {
"resource": ""
} |
q51788 | tarfile_xml_generator | train | def tarfile_xml_generator(fname):
"""
Generator for iterating through xml files in a tarball.
Returns strings.
Example usage::
xmlgen = tarfile_xml_generator(fname)
xml0 = next(xmlgen)
for pkt in xmlgen:
foo(pkt)
"""
tf = tarfile.open(fname, mode='r')
... | python | {
"resource": ""
} |
q51789 | get_email_forwarding | train | def get_email_forwarding(netid):
"""
Return a restclients.models.uwnetid.UwEmailForwarding object
on the given uwnetid
"""
subscriptions = get_netid_subscriptions(netid, Subscription.SUBS_CODE_U_FORWARDING)
for subscription in subscriptions:
if subscription.subscription_code == Subscript... | python | {
"resource": ""
} |
q51790 | Xearths.import_locations | train | def import_locations(self, marker_file):
"""Parse Xearth data files.
``import_locations()`` returns a dictionary with keys containing the
xearth_ name, and values consisting of a :class:`Xearth` object and
a string containing any comment found in the marker file.
It expects Xea... | python | {
"resource": ""
} |
q51791 | ScryptureAPI.get | train | def get(self, uri, params={}):
'''A generic method to make GET requests'''
logging.debug("Requesting URL: "+str(urlparse.urljoin(self.BASE_URL, uri)))
return requests.get(urlparse.urljoin(self.BASE_URL, uri),
params=params, verify=False,
auth=self.auth) | python | {
"resource": ""
} |
q51792 | ScryptureAPI.post | train | def post(self, uri, params={}, data={}):
'''A generic method to make POST requests on the given URI.'''
return requests.post(
urlparse.urljoin(self.BASE_URL, uri),
params=params, data=json.dumps(data), verify=False,
auth=self.auth, headers = {'Content-type': 'applicat... | python | {
"resource": ""
} |
q51793 | as_tuple | train | def as_tuple(obj):
" Given obj return a tuple "
if not obj:
return tuple()
if isinstance(obj, (tuple, set, list)):
return tuple(obj)
if hasattr(obj, '__iter__') and not isinstance(obj, dict):
return obj
return obj, | python | {
"resource": ""
} |
q51794 | gen_url_name | train | def gen_url_name(resource):
" URL name for resource class generator. "
if resource._meta.parent:
yield resource._meta.parent._meta.url_name
if resource._meta.prefix:
yield resource._meta.prefix
for p in resource._meta.url_params:
yield p
yield resource._meta.name | python | {
"resource": ""
} |
q51795 | gen_url_regex | train | def gen_url_regex(resource):
" URL regex for resource class generator. "
if resource._meta.parent:
yield resource._meta.parent._meta.url_regex.rstrip('/$').lstrip('^')
for p in resource._meta.url_params:
yield '%(name)s/(?P<%(name)s>[^/]+)' % dict(name=p)
if resource._meta.prefix:
... | python | {
"resource": ""
} |
q51796 | FileSea.postURL | train | def postURL(self, url, headers, body):
"""
Implement post using a get call
"""
new_url = url
if body is not None:
new_url = FileSea.convert_body(url, body)
return self.getURL(new_url, headers) | python | {
"resource": ""
} |
q51797 | PGPMixin.contribute_to_class | train | def contribute_to_class(self, cls, name, **kwargs):
"""
Add a decrypted field proxy to the model.
Add to the field model an `EncryptedProxyField` to get the decrypted
values of the field.
The decrypted value can be accessed using the field's name attribute on
the model ... | python | {
"resource": ""
} |
q51798 | HkAVR._exec_appcommand_post | train | def _exec_appcommand_post(self, command, param):
"""
Prepare xml command for AVR
"""
xml = """<?xml version="1.0" encoding="UTF-8"?>
<harman>
<avr>
<common>
<control>
<name>""" + command + """</name>
... | python | {
"resource": ""
} |
q51799 | HkAVR.power_on | train | def power_on(self):
"""Turn off receiver via command."""
try:
self.send_command("POWER_ON")
self._power = POWER_ON
self._state = STATE_ON
return True
except requests.exceptions.RequestException:
_LOGGER.error("Connection error: power on... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.