_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q51500
prepare_xml_read
train
def prepare_xml_read(data, objectify=False): """Prepare various input types for XML parsing. Args: data (iter): Data to read objectify (bool): Parse using lxml's objectify data binding Returns: etree.ElementTree: Tree suitable for parsing Raises: TypeError: Invalid val...
python
{ "resource": "" }
q51501
element_creator
train
def element_creator(namespace=None): """Create a simple namespace-aware objectify element creator. Args: namespace (str): Namespace to work in Returns: function: Namespace-aware element creator """ ELEMENT_MAKER = _objectify.ElementMaker(namespace=namespace, ...
python
{ "resource": "" }
q51502
to_dms
train
def to_dms(angle, style='dms'): """Convert decimal angle to degrees, minutes and possibly seconds. Args: angle (float): Angle to convert style (str): Return fractional or whole minutes values Returns: tuple of int: Angle converted to degrees, minutes and possibly seconds Raise...
python
{ "resource": "" }
q51503
to_dd
train
def to_dd(degrees, minutes, seconds=0): """Convert degrees, minutes and optionally seconds to decimal angle. Args: degrees (float): Number of degrees minutes (float): Number of minutes seconds (float): Number of seconds Returns: float: Angle converted to decimal degrees ...
python
{ "resource": "" }
q51504
__chunk
train
def __chunk(segment, abbr=False): """Generate a ``tuple`` of compass direction names. Args: segment (list): Compass segment to generate names for abbr (bool): Names should use single letter abbreviations Returns: bool: Direction names for compass segment """ names = ('north...
python
{ "resource": "" }
q51505
angle_to_name
train
def angle_to_name(angle, segments=8, abbr=False): """Convert angle in to direction name. Args: angle (float): Angle in degrees to convert to direction name segments (int): Number of segments to split compass in to abbr (bool): Whether to return abbreviated direction string Returns:...
python
{ "resource": "" }
q51506
from_iso6709
train
def from_iso6709(coordinates): """Parse ISO 6709 coordinate strings. This function will parse ISO 6709-1983(E) "Standard representation of latitude, longitude and altitude for geographic point locations" elements. Unfortunately, the standard is rather convoluted and this implementation is incomplet...
python
{ "resource": "" }
q51507
to_iso6709
train
def to_iso6709(latitude, longitude, altitude=None, format='dd', precision=4): """Produce ISO 6709 coordinate strings. This function will produce ISO 6709-1983(E) "Standard representation of latitude, longitude and altitude for geographic point locations" elements. See also: from_iso6709 Ar...
python
{ "resource": "" }
q51508
angle_to_distance
train
def angle_to_distance(angle, units='metric'): """Convert angle in to distance along a great circle. Args: angle (float): Angle in degrees to convert to distance units (str): Unit type to be used for distances Returns: float: Distance in ``units`` Raises: ValueError: Un...
python
{ "resource": "" }
q51509
distance_to_angle
train
def distance_to_angle(distance, units='metric'): """Convert a distance in to an angle along a great circle. Args: distance (float): Distance to convert to degrees units (str): Unit type to be used for distances Returns: float: Angle in degrees Raises: ValueError: Unkno...
python
{ "resource": "" }
q51510
to_grid_locator
train
def to_grid_locator(latitude, longitude, precision='square'): """Calculate Maidenhead locator from latitude and longitude. Args: latitude (float): Position's latitude longitude (float): Position's longitude precision (str): Precision with which generate locator string Returns: ...
python
{ "resource": "" }
q51511
parse_location
train
def parse_location(location): """Parse latitude and longitude from string location. Args: location (str): String to parse Returns: tuple of float: Latitude and longitude of location """ def split_dms(text, hemisphere): """Split degrees, minutes and seconds string. ...
python
{ "resource": "" }
q51512
sun_rise_set
train
def sun_rise_set(latitude, longitude, date, mode='rise', timezone=0, zenith=None): """Calculate sunrise or sunset for a specific location. This function calculates the time sunrise or sunset, or optionally the beginning or end of a specified twilight period. Source:: Almanac ...
python
{ "resource": "" }
q51513
sun_events
train
def sun_events(latitude, longitude, date, timezone=0, zenith=None): """Convenience function for calculating sunrise and sunset. Civil twilight starts/ends when the Sun's centre is 6 degrees below the horizon. Nautical twilight starts/ends when the Sun's centre is 12 degrees below the horizon. ...
python
{ "resource": "" }
q51514
dump_xearth_markers
train
def dump_xearth_markers(markers, name='identifier'): """Generate an Xearth compatible marker file. ``dump_xearth_markers()`` writes a simple Xearth_ marker file from a dictionary of :class:`trigpoints.Trigpoint` objects. It expects a dictionary in one of the following formats. For support of :clas...
python
{ "resource": "" }
q51515
calc_radius
train
def calc_radius(latitude, ellipsoid='WGS84'): """Calculate earth radius for a given latitude. This function is most useful when dealing with datasets that are very localised and require the accuracy of an ellipsoid model without the complexity of code necessary to actually use one. The results are mea...
python
{ "resource": "" }
q51516
Timestamp.isoformat
train
def isoformat(self): """Generate an ISO 8601 formatted time stamp. Returns: str: `ISO 8601`_ formatted time stamp .. _ISO 8601: http://www.cl.cam.ac.uk/~mgk25/iso-time.html """ text = [self.strftime('%Y-%m-%dT%H:%M:%S'), ] if self.tzinfo: text.ap...
python
{ "resource": "" }
q51517
Timestamp.parse_isoformat
train
def parse_isoformat(timestamp): """Parse an ISO 8601 formatted time stamp. Args: timestamp (str): Timestamp to parse Returns: Timestamp: Parsed timestamp """ if len(timestamp) == 20: zone = TzOffset('+00:00') timestamp = timestamp...
python
{ "resource": "" }
q51518
WeakGeneratorWrapper._wait
train
def _wait(self, generator, method, timeout=None, *args, **kwargs): """Wait until generator is paused before running 'method'.""" if self.debug: print("waiting for %s to pause" % generator) original_timeout = timeout while timeout is None or timeout > 0: last_time...
python
{ "resource": "" }
q51519
WeakGeneratorWrapper.can_resume
train
def can_resume(self): """Test if the generator can be resumed, i.e. is not running or closed.""" # TOCHECK relies on generator.gi_frame # Equivalent to `inspect.getgeneratorstate(self.generator) in # (inspect.GEN_CREATED, inspect.GEN_SUSPENDED)`, # which is only available startin...
python
{ "resource": "" }
q51520
SampleManifest.load_content
train
def load_content(self, path): "Attempts to open the file and read the content." log.debug('Opening {0} in {1} load_content'.format(path, __name__)) with open(path) as fin: self.path = path self.content = fin.read()
python
{ "resource": "" }
q51521
Baken.locator
train
def locator(self, value): """Update the locator, and trigger a latitude and longitude update. Args: value (str): New Maidenhead locator string """ self._locator = value self._latitude, self._longitude = utils.from_grid_locator(value)
python
{ "resource": "" }
q51522
Bakens.import_locations
train
def import_locations(self, baken_file): """Import baken data files. ``import_locations()`` returns a dictionary with keys containing the section title, and values consisting of a collection :class:`Baken` objects. It expects data files in the format used by the baken_ amateur r...
python
{ "resource": "" }
q51523
SQLAlchemyScheduler.setup_schedule
train
def setup_schedule(self): "Called when schedule is intialized. Fetch schedules from DB etc here" log.info("SQLAlchemyScheduler.setup_schedule called") if 'celery.backend_cleanup' not in self._schedule: self._schedule['celery.backend_cleanup'] = ScheduleEntry( name='...
python
{ "resource": "" }
q51524
Funds.funds
train
def funds(self, term, field=None, **kwargs): """Search for funds matching a search term. Args: term (str): Fund id to search on field (str): The field to search on. Options are title, amount, org_name and type. kwargs (dict): additional keywords passed into ...
python
{ "resource": "" }
q51525
format_office_label
train
def format_office_label(office, division_label): """ Format the label for office into something we like for twitter. """ if office.body: if office.body.slug == "senate": return "the Senate in {}".format(division_label) else: if office.division.code == "00": ...
python
{ "resource": "" }
q51526
EffectStream.get_gene
train
def get_gene(self, gene_name): """Get a gene from the cache or attempt to disambiguate or add a new record. """ if not gene_name: return gene_pk = self.genes.get(gene_name) if gene_pk: return gene_pk chrom = self.chromosomes[self.variants...
python
{ "resource": "" }
q51527
EffectStream.get_transcript
train
def get_transcript(self, gene_pk, refseq_id): "Get a transcript from the cache or add a new record." if not refseq_id: return transcript_pk = self.transcripts.get(refseq_id) if transcript_pk: return transcript_pk gene = Gene(pk=gene_pk) transcript ...
python
{ "resource": "" }
q51528
SentenceSegementationLabelProcessor.result
train
def result(self) -> workflow.IntervalGeneratorType: """ Generate intervals indicating the valid sentences. """ config = cast(SentenceSegementationConfig, self.config) index = -1 labels = None while True: # 1. Find the start of the sentence. ...
python
{ "resource": "" }
q51529
Seq
train
def Seq(sequence, annotations=None, block_length=10, blocks_per_line=6, style=DEFAULT_STYLE): """ Pretty-printed sequence object that's displayed nicely in the IPython Notebook. :arg style: Custom CSS as a `format string`, where a selector for the top-level ``<pre>`` element is substitu...
python
{ "resource": "" }
q51530
Locations.import_locations
train
def import_locations(self, data): """Parse geonames.org country database exports. ``import_locations()`` returns a list of :class:`trigpoints.Trigpoint` objects generated from the data exported by geonames.org_. It expects data files in the following tab separated format:: ...
python
{ "resource": "" }
q51531
Locations.import_timezones_file
train
def import_timezones_file(self, data): """Parse geonames.org_ timezone exports. ``import_timezones_file()`` returns a dictionary with keys containing the timezone identifier, and values consisting of a UTC offset and UTC offset during daylight savings time in minutes. It expect...
python
{ "resource": "" }
q51532
add_user
train
def add_user(bridge_user): """ Add the bridge_user given Return a list of BridgeUser objects with custom fields """ resp = post_resource(admin_uid_url(None) + ("?%s" % CUSTOM_FIELD), json.dumps(bridge_user.to_json_post(), ...
python
{ "resource": "" }
q51533
replace_uid
train
def replace_uid(old_uwnetid, new_uwnetid, no_custom_fields=True): """ Return a list of BridgeUser objects without custom fields """ url = author_uid_url(old_uwnetid) if not no_custom_fields: url += ("?%s" % CUSTOM_FIELD) resp = patch_resource(url, '{"user":{"uid":"%s@uw.edu"}}' % new_uwn...
python
{ "resource": "" }
q51534
get_user
train
def get_user(uwnetid, include_course_summary=True): """ Return a list of BridgeUsers objects with custom fields """ url = author_uid_url(uwnetid) + "?%s" % CUSTOM_FIELD if include_course_summary: url = "%s&%s" % (url, COURSE_SUMMARY) resp = get_resource(url) return _process_json_resp...
python
{ "resource": "" }
q51535
get_all_users
train
def get_all_users(include_course_summary=True): """ Return a list of BridgeUser objects with custom fields. """ url = author_uid_url(None) + "?%s" % CUSTOM_FIELD if include_course_summary: url = "%s&%s" % (url, COURSE_SUMMARY) url = "%s&%s" % (url, PAGE_MAX_ENTRY) resp = get_resou...
python
{ "resource": "" }
q51536
update_user
train
def update_user(bridge_user): """ Update only the user attributes provided. Return a list of BridgeUsers objects with custom fields. """ if bridge_user.bridge_id: url = author_id_url(bridge_user.bridge_id) else: url = author_uid_url(bridge_user.netid) resp = patch_resource(ur...
python
{ "resource": "" }
q51537
_process_json_resp_data
train
def _process_json_resp_data(resp, no_custom_fields=False): """ process the response and return a list of BridgeUser """ bridge_users = [] while True: resp_data = json.loads(resp) link_url = None if "meta" in resp_data and\ "next" in resp_data["meta"]: ...
python
{ "resource": "" }
q51538
BinaryTable._report
train
def _report(self, blocknr, blocksize, size): ''' helper for downloading the file ''' current = blocknr * blocksize sys.stdout.write("\r{0:.2f}%".format(100.0 * current / size))
python
{ "resource": "" }
q51539
BinaryTable._downloadfile
train
def _downloadfile(self, url, fname): ''' Download the image ''' print("The file %s need to be download - Wait\n " % (fname.split('/')[-1])) urllib.urlretrieve(url, fname, self._report) print("\n The download of the file %s has succeded \n " % (fname.split('/'...
python
{ "resource": "" }
q51540
BinaryTable._user_yes_no_query
train
def _user_yes_no_query(self, question): """ Helper asking if the user want to download the file Note: Dowloading huge file can take a while """ sys.stdout.write('%s [y/n]\n' % question) while True: try: return strtobool(raw_input().lower(...
python
{ "resource": "" }
q51541
BinaryTable._detect_size
train
def _detect_size(self, url): """ Helper that detect the size of the image to be download""" site = urllib.urlopen(url) meta = site.info() return float(meta.getheaders("Content-Length")[0]) / 1e6
python
{ "resource": "" }
q51542
BinaryTable._maybe_download
train
def _maybe_download(self): """ Helper to downlaod the image if not in path """ if self.grid == 'WAC': urlpath = 'http://lroc.sese.asu.edu/data/LRO-L-LROC-5-RDR-V1.0/LROLRC_2001/DATA/BDR/WAC_GLOBAL/' r = requests.get(urlpath) # List file in the cloud images = [elt.spl...
python
{ "resource": "" }
q51543
BinaryTable._load_info_lbl
train
def _load_info_lbl(self): """ Load info on the image Note: If the image is from LOLA, the .LBL is parsed and the information is returned. If the image is from WAC, the .IMG file is parsed using the library `pvl`_ which provide nice method to extract ...
python
{ "resource": "" }
q51544
BinaryTable.lat_id
train
def lat_id(self, line): ''' Return the corresponding latitude Args: line (int): Line number Returns: Correponding latitude in degree ''' if self.grid == 'WAC': lat = ((1 + self.LINE_PROJECTION_OFFSET - line) * self.MAP_SCAL...
python
{ "resource": "" }
q51545
BinaryTable.long_id
train
def long_id(self, sample): ''' Return the corresponding longitude Args: sample (int): sample number on a line Returns: Correponding longidude in degree ''' if self.grid == 'WAC': lon = self.CENTER_LONGITUDE + (sample - self.SAMPLE_PROJECTION_...
python
{ "resource": "" }
q51546
BinaryTable._control_sample
train
def _control_sample(self, sample): ''' Control the asked sample is ok ''' if sample > float(self.SAMPLE_LAST_PIXEL): return int(self.SAMPLE_LAST_PIXEL) elif sample < float(self.SAMPLE_FIRST_PIXEL): return int(self.SAMPLE_FIRST_PIXEL) else: return sampl...
python
{ "resource": "" }
q51547
BinaryTable.sample_id
train
def sample_id(self, lon): ''' Return the corresponding sample Args: lon (int): longidute in degree Returns: Correponding sample ''' if self.grid == 'WAC': sample = np.rint(float(self.SAMPLE_PROJECTION_OFFSET) + 1.0 + ...
python
{ "resource": "" }
q51548
BinaryTable._control_line
train
def _control_line(self, line): ''' Control the asked line is ok ''' if line > float(self.LINE_LAST_PIXEL): return int(self.LINE_LAST_PIXEL) elif line < float(self.LINE_FIRST_PIXEL): return int(self.LINE_FIRST_PIXEL) else: return line
python
{ "resource": "" }
q51549
BinaryTable.line_id
train
def line_id(self, lat): ''' Return the corresponding line Args: lat (int): latitude in degree Returns: Correponding line ''' if self.grid == 'WAC': line = np.rint(1.0 + self.LINE_PROJECTION_OFFSET - self.A_AXIS_RAD...
python
{ "resource": "" }
q51550
BinaryTable.array
train
def array(self, size_chunk, start, bytesize): ''' Read part of the binary file Args: size_chunk (int) : Size of the chunk to read start (int): Starting byte bytesize (int): Ending byte Returns: (np.array): array of the corresponding values ...
python
{ "resource": "" }
q51551
BinaryTable.extract_all
train
def extract_all(self): ''' Extract all the image Returns: A tupple of three arrays ``(X,Y,Z)`` with ``X`` contains the longitudes, ``Y`` contains the latitude and ``Z`` the values extracted from the image. Note: All return arrays have the same si...
python
{ "resource": "" }
q51552
BinaryTable.extract_grid
train
def extract_grid(self, longmin, longmax, latmin, latmax): ''' Extract part of the image ``img`` Args: longmin (float): Minimum longitude of the window longmax (float): Maximum longitude of the window latmin (float): Minimum latitude of the window latmax (...
python
{ "resource": "" }
q51553
BinaryTable.boundary
train
def boundary(self): """ Get the image boundary Returns: A tupple composed by the westernmost_longitude, the westernmost_longitude, the minimum_latitude and the maximum_latitude. """ return (int(self.WESTERNMOST_LONGITUDE), int(self.E...
python
{ "resource": "" }
q51554
WacMap._control_longitude
train
def _control_longitude(self): ''' Control on longitude values ''' if self.lonm < 0.0: self.lonm = 360.0 + self.lonm if self.lonM < 0.0: self.lonM = 360.0 + self.lonM if self.lonm > 360.0: self.lonm = self.lonm - 360.0 if self.lonM > 360.0: ...
python
{ "resource": "" }
q51555
WacMap._confirm_resolution
train
def _confirm_resolution(self, implemented_res): ''' Control on resolution ''' assert self.ppd in implemented_res, \ ' Resolution %d ppd not implemented yet\n.\ Consider using one of the implemented resolutions %s'\ % (self.ppd, ', '.join([f + ' ppd' for f in map(str,...
python
{ "resource": "" }
q51556
WacMap._format_lon
train
def _format_lon(self, lon): ''' Format longitude to fit the image name ''' lonf = self._map_center('long', lon) st = str(lonf).split('.') loncenter = ''.join(("{0:0>3}".format(st[0]), st[1])) return loncenter
python
{ "resource": "" }
q51557
WacMap._format_lat
train
def _format_lat(self, lat): ''' Format latitude to fit the image name ''' if self.ppd in [4, 8, 16, 32, 64]: latcenter = '000N' elif self.ppd in [128]: if lat < 0: latcenter = '450S' else: latcenter = '450N' return lat...
python
{ "resource": "" }
q51558
WacMap._cas_1
train
def _cas_1(self): '''1 - The desired structure is entirely contained into one image.''' lonc = self._format_lon(self.lonm) latc = self._format_lat(self.latm) img = self._format_name_map(lonc, latc) img_map = BinaryTable(img, self.path_pdsfiles) return img_map.extract_gr...
python
{ "resource": "" }
q51559
LolaMap._format_lon
train
def _format_lon(self, lon): ''' Returned a formated longitude format for the file ''' if self.ppd in [4, 16, 64, 128]: return None else: return map(lambda x: "{0:0>3}".format(int(x)), self._map_center('long', lon))
python
{ "resource": "" }
q51560
LolaMap._format_lat
train
def _format_lat(self, lat): ''' Returned a formated latitude format for the file ''' if self.ppd in [4, 16, 64, 128]: return None else: if lat < 0: return map(lambda x: "{0:0>2}" .format(int(np.abs(x))) + 'S', self._map_center('l...
python
{ "resource": "" }
q51561
last_modified_date
train
def last_modified_date(filename): """Last modified timestamp as a UTC datetime""" mtime = os.path.getmtime(filename) dt = datetime.datetime.utcfromtimestamp(mtime) return dt.replace(tzinfo=pytz.utc)
python
{ "resource": "" }
q51562
SerfConnection.call
train
def call(self, command, params=None, expect_body=True, stream=False): """ Sends the provided command to Serf for evaluation, with any parameters as the message body. """ if self._socket is None: raise SerfConnectionError('handshake must be made first') header...
python
{ "resource": "" }
q51563
SerfConnection.handshake
train
def handshake(self): """ Sets up the connection with the Serf agent and does the initial handshake. """ if self._socket is None: self._socket = self._connect() return self.call('handshake', {"Version": 1}, expect_body=False)
python
{ "resource": "" }
q51564
SerfConnection.auth
train
def auth(self, auth_key): """ Performs the initial authentication on connect """ if self._socket is None: self._socket = self._connect() return self.call('auth', {"AuthKey": auth_key}, expect_body=False)
python
{ "resource": "" }
q51565
SerfConnection._decode_addr_key
train
def _decode_addr_key(self, obj_dict): """ Callback function to handle the decoding of the 'Addr' field. Serf msgpack 'Addr' as an IPv6 address, and the data needs to be unpack using socket.inet_ntop(). See: https://github.com/KushalP/serfclient-py/issues/20 :param obj_...
python
{ "resource": "" }
q51566
wait_for_service
train
def wait_for_service(host, port, timeout=DEFAULT_TIMEOUT): """ Return True if connection to the host and port is successful within the timeout. @param host: str: hostname of the server @param port: int: TCP port to which to connect @param timeout: int: length of time in seconds to try to connect be...
python
{ "resource": "" }
q51567
wait_for_url
train
def wait_for_url(url, timeout=DEFAULT_TIMEOUT): """ Return True if connection to the host and port specified in url is successful within the timeout. @param url: str: connection url for a TCP service @param timeout: int: length of time in seconds to try to connect before giving up @raise Runtim...
python
{ "resource": "" }
q51568
ServiceURL.is_available
train
def is_available(self): """ Return True if the connection to the host and port is successful. @return: bool """ if self.scheme in NOOP_PROTOCOLS: return True if not self.port: raise RuntimeError('port is required') s = socket.socket() ...
python
{ "resource": "" }
q51569
Area.change_window
train
def change_window(self, size_window): ''' Change the region of interest Args: size_window (float): Radius of the region of interest (km) Notes: Change the attributes ``size_window`` and ``window`` to correspond to the new region of interest. ''' ...
python
{ "resource": "" }
q51570
Area._add_scale
train
def _add_scale(self, m, ax1): ''' Add scale to the map instance ''' lol, loM, lam, laM = self.lambert_window( 0.6 * self.size_window, self.lat0, self.lon0) m.drawmapscale(loM, lam, self.lon0, self.lat0, 10, barstyle='fancy', units='km', ...
python
{ "resource": "" }
q51571
Area._add_colorbar
train
def _add_colorbar(self, m, CS, ax, name): ''' Add colorbar to the map instance ''' cb = m.colorbar(CS, "right", size="5%", pad="2%") cb.set_label(name, size=34) cb.ax.tick_params(labelsize=18)
python
{ "resource": "" }
q51572
Area.get_arrays
train
def get_arrays(self, type_img): ''' Return arrays the region of interest Args: type_img (str): Either lola or wac. Returns: A tupple of three arrays ``(X,Y,Z)`` with ``X`` contains the longitudes, ``Y`` contains the latitude and ``Z`` the values ...
python
{ "resource": "" }
q51573
Area.lola_image
train
def lola_image(self, save=False, name='BaseLola.png'): ''' Draw the topography of the region of interest Args: save (Optional[bool]): Weither or not to save the image. Defaults to False. name (Optional[str]): Absolut path to save the resulting ima...
python
{ "resource": "" }
q51574
make_file_system_tree
train
def make_file_system_tree(root_folder, _parent=None): """This function makes a tree from folders and files. """ root_node = Node(os.path.basename(root_folder), _parent) root_node.path = root_folder for item in os.listdir(root_folder): item_path = os.path.join(root_folder, item) if os...
python
{ "resource": "" }
q51575
URLMapper.add
train
def add(self, name: str, pattern: str) -> None: """ add url pattern for name """ self.patterns[name] = URITemplate( pattern, converters=self.converters)
python
{ "resource": "" }
q51576
URLMapper.lookup
train
def lookup(self, path_info: str) -> MatchResult: """ lookup url match for path_info """ for name, pattern in self.patterns.items(): match = pattern.match(path_info) if match is None: continue match.name = name return match r...
python
{ "resource": "" }
q51577
URLMapper.generate
train
def generate(self, name: str, **kwargs: Dict[str, str]) -> str: """ generate url for named url pattern with kwargs """ template = self.patterns[name] return template.substitute(kwargs)
python
{ "resource": "" }
q51578
URLGenerator.generate
train
def generate(self, name: str, **kwargs): """ generate full qualified url for named url pattern with kwargs """ path = self.urlmapper.generate(name, **kwargs) return self.make_full_qualified_url(path)
python
{ "resource": "" }
q51579
URLGenerator.make_full_qualified_url
train
def make_full_qualified_url(self, path: str) -> str: """ append application url to path""" return self.application_uri.rstrip('/') + '/' + path.lstrip('/')
python
{ "resource": "" }
q51580
URLDispatcher.add_url
train
def add_url(self, name: str, pattern: str, application: Callable) -> None: """ add url pattern dispatching to application""" self.urlmapper.add(name, self.prefix + pattern) self.register_app(name, application)
python
{ "resource": "" }
q51581
URLDispatcher.add_subroute
train
def add_subroute(self, pattern: str) -> "URLDispatcher": """ create new URLDispatcher routed by pattern """ return URLDispatcher( urlmapper=self.urlmapper, prefix=self.prefix + pattern, applications=self.applications, extra_environ=self.extra_environ)
python
{ "resource": "" }
q51582
URLDispatcher.detect_view_name
train
def detect_view_name(self, environ: Dict[str, Any]) -> str: """ detect view name from environ """ script_name = environ.get('SCRIPT_NAME', '') path_info = environ.get('PATH_INFO', '') match = self.urlmapper.lookup(path_info) if match is None: return None spli...
python
{ "resource": "" }
q51583
URLDispatcher.on_view_not_found
train
def on_view_not_found( self, environ: Dict[str, Any], start_response: Callable[[str, List[Tuple[str, str]]], None], ) -> Iterable[bytes]: """ called when views not found""" start_response('404 Not Found', [('Content-type', 'text/plain')]) return [b'Not fou...
python
{ "resource": "" }
q51584
BaseWrapper.check_path
train
def check_path(self, path): """ turns path into an absolute path and checks that it exists, then returns it as a string. """ path = os.path.abspath(path) if os.path.exists(path): return path else: utils.die("input file does not exists:\n {...
python
{ "resource": "" }
q51585
GS1NumericalIdentifier.calc_check_digit
train
def calc_check_digit(digits): """Calculate and return the GS1 check digit.""" ints = [int(d) for d in digits] l = len(ints) odds = slice((l - 1) % 2, l, 2) even = slice(l % 2, l, 2) checksum = 3 * sum(ints[odds]) + sum(ints[even]) return str(-checksum % 10)
python
{ "resource": "" }
q51586
GS1NumericalIdentifier.company_prefix
train
def company_prefix(self): """Return the identifier's company prefix part.""" offset = self.EXTRA_DIGITS return self._id[offset:self._ref_idx]
python
{ "resource": "" }
q51587
GS1NumericalIdentifier.elements
train
def elements(self): """Return the identifier's elements as tuple.""" offset = self.EXTRA_DIGITS if offset: return (self._id[:offset], self.company_prefix, self._reference, self.check_digit) else: return (self.company_prefix, self._reference, se...
python
{ "resource": "" }
q51588
GS1NumericalIdentifier.separated
train
def separated(self, separator='-'): """Return a string representation of the identifier with its elements separated by the given separator.""" return separator.join((part for part in self.elements() if part))
python
{ "resource": "" }
q51589
GeneManager.find
train
def find(self, symbol, chrom=None, create=False): """ Find a gene based on the symbol or disambiguate using synonyms. If no gene is found, if the create is True, a new instance will be created with that symbol. """ queryset = self.get_query_set() # Filter by chro...
python
{ "resource": "" }
q51590
graphdata
train
def graphdata(data): """returns ratings and episode number to be used for making graphs""" data = jh.get_ratings(data) num = 1 rating_final = [] episode_final = [] for k,v in data.iteritems(): rating=[] epinum=[] for r in v: if r != None: r...
python
{ "resource": "" }
q51591
graph
train
def graph(data): """Draws graph of rating vs episode number""" title = data['name'] + ' (' + data['rating'] + ') ' plt.title(title) plt.xlabel('Episode Number') plt.ylabel('Ratings') rf,ef=graphdata(data) col=['red', 'green' , 'orange'] for i in range(len(rf)): x,y=ef[i],rf[i] ...
python
{ "resource": "" }
q51592
BaseSerializer.to_simple
train
def to_simple(self, value, **options): # nolint " Simplify object. " # (string, unicode) if isinstance(value, basestring): return smart_unicode(value) # (int, long, float, real, complex, decimal) if isinstance(value, Number): return float(str(value)) if...
python
{ "resource": "" }
q51593
BaseSerializer.to_simple_model
train
def to_simple_model(self, instance, **options): # noqa """ Convert model to simple python structure. """ options = self.init_options(**options) fields, include, exclude, related = options['fields'], options['include'], options['exclude'], options['related'] # noqa result = dict(...
python
{ "resource": "" }
q51594
get_memcached_usage
train
def get_memcached_usage(socket=None): """ Returns memcached statistics. :param socket: Path to memcached's socket file. """ cmd = 'echo \'stats\' | nc -U {0}'.format(socket) output = getoutput(cmd) curr_items = None bytes_ = None rows = output.split('\n')[:-1] for row in rows:...
python
{ "resource": "" }
q51595
QueryField.get_absolute_name
train
def get_absolute_name(self): """ Returns the full dotted name of this field """ res = [] current = self while type(current) != type(None): if current.__matched_index: res.append('$') res.append(current.get_type().db_field) current = cu...
python
{ "resource": "" }
q51596
QueryField.startswith
train
def startswith(self, prefix, ignore_case=False, options=None): """ A query to check if a field starts with a given prefix string **Example**: ``session.query(Spell).filter(Spells.name.startswith("abra", ignore_case=True))`` .. note:: This is a shortcut to .regex('^' + re.escape(prefix)...
python
{ "resource": "" }
q51597
QueryField.endswith
train
def endswith(self, suffix, ignore_case=False, options=None): """ A query to check if a field ends with a given suffix string **Example**: ``session.query(Spell).filter(Spells.name.endswith("cadabra", ignore_case=True))`` """ return self.regex(re.escape(suffix) + '$', ignore_case=ig...
python
{ "resource": "" }
q51598
QueryField.near
train
def near(self, x, y, max_distance=None): """ Return documents near the given point """ expr = { self : {'$near' : [x, y]} } if max_distance is not None: expr[self]['$maxDistance'] = max_distance # if bucket_size is not None: # expr['$bu...
python
{ "resource": "" }
q51599
QueryField.near_sphere
train
def near_sphere(self, x, y, max_distance=None): """ Return documents near the given point using sphere distances """ expr = { self : {'$nearSphere' : [x, y]} } if max_distance is not None: expr[self]['$maxDistance'] = max_distance return QueryExpre...
python
{ "resource": "" }