Search is not available for this dataset
text
stringlengths
75
104k
def copy(self, dest): """ Copy file to destination """ if isinstance(dest, File): dest_dir = dest.get_directory() dest_dir.create() dest = dest.filename elif isinstance(dest, Directory): dest = dest.dirname shutil.copy2(self.filename, dest...
def get_directory(self): """ Returns the directory where the file is placed in or None if the path to the file doesn't contain a directory """ dirname = os.path.dirname(self.filename) if dirname: return Directory(dirname) else: return None
def backup_file(self, file, dest_dir, copy_empty=False): """ Backup file in dest_dir Directory. The return value is a File object pointing to the copied file in the destination directory or None if no file is copied. If file exists and it is not empty it is copied to dest_dir. I...
def refresh(self, patch_name=None, edit=False): """ Refresh patch with patch_name or applied top patch if patch_name is None """ if patch_name: patch = Patch(patch_name) else: patch = self.db.top_patch() if not patch: raise Qui...
def unapply_patch(self, patch_name, force=False): """ Unapply patches up to patch_name. patch_name will end up as top patch """ self._check(force) patches = self.db.patches_after(Patch(patch_name)) for patch in reversed(patches): self._unapply_patch(patch) ...
def unapply_top_patch(self, force=False): """ Unapply top patch """ self._check(force) patch = self.db.top_patch() self._unapply_patch(patch) self.db.save() self.unapplied(self.db.top_patch())
def unapply_all(self, force=False): """ Unapply all patches """ self._check(force) for patch in reversed(self.db.applied_patches()): self._unapply_patch(patch) self.db.save() self.unapplied(self.db.top_patch())
def apply_patch(self, patch_name, force=False, quiet=False): """ Apply all patches up to patch_name """ self._check() patch = Patch(patch_name) patches = self.series.patches_until(patch)[:] applied = self.db.applied_patches() for patch in applied: if patch in...
def apply_next_patch(self, force=False, quiet=False): """ Apply next patch in series file """ self._check() top = self.db.top_patch() if not top: patch = self.series.first_patch() else: patch = self.series.patch_after(top) if not patch: ...
def apply_all(self, force=False, quiet=False): """ Apply all patches in series file """ self._check() top = self.db.top_patch() if top: patches = self.series.patches_after(top) else: patches = self.series.patches() if not patches: rais...
def read(self): """ Reads all patches from the series file """ self.patchlines = [] self.patch2line = dict() if self.exists(): with open(self.series_file, "r") as f: for line in f: self.add_patch(line)
def save(self): """ Saves current patches list in the series file """ with open(self.series_file, "wb") as f: for patchline in self.patchlines: f.write(_encode_str(str(patchline))) f.write(b"\n")
def add_patch(self, patch): """ Add a patch to the patches list """ patchline = PatchLine(patch) patch = patchline.get_patch() if patch: self.patch2line[patch] = patchline self.patchlines.append(patchline)
def insert_patches(self, patches): """ Insert list of patches at the front of the curent patches list """ patchlines = [] for patch_name in patches: patchline = PatchLine(patch_name) patch = patchline.get_patch() if patch: self.patch2line[patch...
def add_patches(self, patches, after=None): """ Add a list of patches to the patches list """ if after is None: self.insert_patches(patches) else: self._check_patch(after) patchlines = self._patchlines_before(after) patchlines.append(self.patch2lin...
def remove_patch(self, patch): """ Remove a patch from the patches list """ self._check_patch(patch) patchline = self.patch2line[patch] del self.patch2line[patch] self.patchlines.remove(patchline)
def patches_after(self, patch): """ Returns a list of patches after patch from the patches list """ return [line.get_patch() for line in self._patchlines_after(patch) if line.get_patch()]
def patches_before(self, patch): """ Returns a list of patches before patch from the patches list """ return [line.get_patch() for line in self._patchlines_before(patch) if line.get_patch()]
def patches_until(self, patch): """ Returns a list of patches before patch from the patches list including the provided patch """ return [line.get_patch() for line in self._patchlines_until(patch) if line.get_patch()]
def replace(self, old_patch, new_patch): """ Replace old_patch with new_patch The method only replaces the patch and doesn't change any comments. """ self._check_patch(old_patch) old_patchline = self.patch2line[old_patch] index = self.patchlines.index(old_patchline) ...
def create(self): """ Creates the dirname and inserts a .version file """ if not os.path.exists(self.dirname): os.makedirs(self.dirname) self._create_version(self.version_file)
def check_version(self, version_file): """ Checks if the .version file in dirname has the correct supported version number """ # The file contains a version number as a decimal integer, optionally # followed by a newline with open(version_file, "r") as f: version ...
def add_to_parser(self, parser): """ Adds the group and its arguments to a argparse.ArgumentParser instance @param parser A argparse.ArgumentParser instance """ self.group = parser.add_argument_group(self.title, self.description) for arg in self.arguments: ar...
def add_to_parser(self, parser): """ Adds the argument to an argparse.ArgumentParser instance @param parser An argparse.ArgumentParser instance """ kwargs = self._get_kwargs() args = self._get_args() parser.add_argument(*args, **kwargs)
def add_to_parser(self, subparsers): """ Adds this SubParser to the subparsers created by argparse.ArgumentParser.add_subparsers method. @param subparsers Normally a _SubParsersAction instance created by argparse.ArgumentParser.add_subparsers method """ parser = ...
def set_subparsers_args(self, *args, **kwargs): """ Sets args and kwargs that are passed when creating a subparsers group in an argparse.ArgumentParser i.e. when calling argparser.ArgumentParser.add_subparsers """ self.subparsers_args = args self.subparsers_kwargs...
def add_subparsers(self, parser): """ Adds the subparsers to an argparse.ArgumentParser @param parser An argparse.ArgumentParser instance """ sgroup = getattr(self, "subparser_group", None) if sgroup: sgroup.add_to_parser(self) if not self.subparsers...
def _file_in_patch(self, filename, patch): """ Checks if a backup file of the filename in the current patch exists and raises a QuiltError if not. """ pc_dir = self.quilt_pc + patch.get_name() file = pc_dir + File(filename) if not file.exists(): raise QuiltErr...
def _file_in_next_patches(self, filename, patch): """ Checks if a backup file of the filename in the applied patches after patch exists """ if not self.db.is_patch(patch): # no patches applied return patches = self.db.patches_after(patch) for patch in pa...
def revert_file(self, filename, patch_name=None): """ Revert not added changes of filename. If patch_name is None or empty the topmost patch will be used. """ file = File(filename) if patch_name: patch = Patch(patch_name) else: patch = self.db.top...
def import_patch(self, patch_name, new_name=None): """ Import patch into the patch queue The patch is inserted as the next unapplied patch. """ if new_name: dir_name = os.path.dirname(new_name) name = os.path.basename(new_name) dest_dir = self.quilt_pa...
def import_patches(self, patches): """ Import several patches into the patch queue """ dest_dir = self.quilt_patches patch_names = [] for patch in patches: patch_name = os.path.basename(patch) patch_file = File(patch) dest_file = dest_dir + File(patc...
def way(self, w): """Process each way.""" if w.id not in self.way_ids: return way_points = [] for n in w.nodes: try: way_points.append(Point(n.location.lon, n.location.lat)) except o.InvalidLocationError: logging.debug(...
def missing_node_ids(self): """Get a list of nodes not found in OSM data.""" present_node_ids = self.nodes.keys() for nid in self.node_ids: if nid not in present_node_ids: yield nid
def node(self, n): """Process each node.""" if n.id not in self.node_ids: return try: self.nodes[n.id] =\ Node(n.id, n.location.lon, n.location.lat, {t.k: t.v for t in n.tags}) except o.Invali...
def build_route(relation): """Extract information of one route.""" if relation.tags.get('type') != 'route': # Build route only for relations of type `route` return short_name = create_route_short_name(relation) color = relation.tags.get('color') return\ Route(relation.id, ...
def create_route_long_name(relation, short_name): """Create a meaningful route name.""" if relation.tags.get('from') and relation.tags.get('to'): return "{0}-to-{1}".format(relation.tags.get('from'), relation.tags.get('to')) name = relation.tags.get('name') or\ ...
def get_agency_id(relation): """Construct an id for agency using its tags.""" op = relation.tags.get('operator') if op: return int(hashlib.sha256(op.encode('utf-8')).hexdigest(), 16) % 10**8 return -1
def process(self): """Process the files and collect necessary data.""" # Extract relations self.rh = RelationHandler() self.rh.apply_file(self.filename) logging.debug('Found %d public transport relations.', len(self.rh.relations)) # Collect ids of interest node...
def relation(self, rel): """Process each relation.""" rel_type = rel.tags.get('type') if any([rel.deleted, not rel.visible, not self.is_new_version(rel), rel_type not in ['route', 'public_transport']]): return route_tag = rel.t...
def create_dummy_data(routes, stops): """Create `calendar`, `stop_times`, `trips` and `shapes`. :return: DummyData namedtuple """ # Build stops per route auxiliary map stops_per_route = defaultdict(lambda: []) stops_map = {} for s in stops: if not s.route_id: continue ...
def patch_agencies(agencies): """Fill the fields that are necessary for passing transitfeed checks.""" # First return the unknown agency entry yield Agency(-1, 'http://hiposfer.com', 'Unknown agency', 'Europe/Berlin') # Then return the rest. for agency_id, agency_url, agency_name, agency_timezone i...
def _create_dummy_trip_stoptimes(trip_id, stops, first_service_time): """Create station stop times for each trip.""" waiting = datetime.timedelta(seconds=30) arrival = first_service_time last_departure = first_service_time last_departure_hour = (arrival + waiting).hour last_stop = None depa...
def write_zipped(self, filepath): """Write the GTFS feed in the given file.""" with zipfile.ZipFile(filepath, mode='w', compression=zipfile.ZIP_DEFLATED) as zfile: for name, buffer in self._buffers.items(): encoded_values = io.BytesIO(buffer.getvalue().encode('utf-8')) ...
def write_unzipped(self, destination): """Write GTFS text files in the given path.""" for name, buffer in self._buffers.items(): with open(os.path.join(destination, '{}.txt'.format(name)), 'w', encoding='utf-8') as file: ...
def build_agency(relation, nodes): """Extract agency information.""" # TODO: find out the operator for routes without operator tag. # See: http://wiki.openstreetmap.org/wiki/Key:operator # Quote from the above link: # # If the vast majority of a certain object in an area is operated by a cert...
def extract_stops(relation, nodes, visited_stop_ids, stop_to_station_map): """Extract stops in a relation.""" # member_role: stop, halt, platform, terminal, etc. for member_type, member_id, member_role in relation.member_info: if member_id not in visited_stop_ids and \ member_id in node...
def build_shape(relation, nodes, ways): """Extract shape of one route.""" sequence_index = 0 for member_type, member_id, member_role in relation.member_info: if member_id in nodes: yield Shape( relation.id, nodes[member_id].lat, nodes[mem...
def get_supported_versions(self): """ Gets a list of supported U2F versions from the device. """ if not hasattr(self, '_versions'): try: self._versions = [self.send_apdu(INS_GET_VERSION).decode()] except exc.APDUError as e: # v0 did...
def send_apdu(self, ins, p1=0, p2=0, data=b''): """ Sends an APDU to the device, and waits for a response. """ if data is None: data = b'' elif isinstance(data, int): data = int2byte(data) size = len(data) l0 = size >> 16 & 0xff l1...
def authenticate(devices, params, facet, check_only): """ Interactively authenticates a AuthenticateRequest using an attached U2F device. """ for device in devices[:]: try: device.open() except: devices.remove(device) try: prompted = False ...
def register(device, data, facet): """ Register a U2F device data = { "version": "U2F_V2", "challenge": string, //b64 encoded challenge "appId": string, //app_id } """ if isinstance(data, string_types): data = json.loads(data) if data['version'] != VERSION...
def authenticate(device, data, facet, check_only=False): """ Signs an authentication challenge data = { 'version': "U2F_V2", 'challenge': websafe_encode(self.challenge), 'appId': self.binding.app_id, 'keyHandle': websafe_encode(self.binding.key_handle) } """ if...
def register(devices, params, facet): """ Interactively registers a single U2F device, given the RegistrationRequest. """ for device in devices[:]: try: device.open() except: devices.remove(device) sys.stderr.write('\nTouch the U2F device you wish to register...
def u2str(data): """Recursively converts unicode objects to UTF-8 encoded byte strings.""" if isinstance(data, dict): return {u2str(k): u2str(v) for k, v in data.items()} elif isinstance(data, list): return [u2str(x) for x in data] elif isinstance(data, text_type): return data.en...
def wrap_function(func=None, error_threshold=None, reraise_exception=True, save_current_stack_trace=True): ''' Wraps a function with reporting to errors backend ''' # This if/else allows wrap_function to behave like a normal decorator when # used like: # @wrap_function # def some_fun...
def wrap_class(cls, error_threshold=None): ''' Wraps a class with reporting to errors backend by decorating each function of the class. Decorators are injected under the classmethod decorator if they exist. ''' methods = inspect.getmembers(cls, inspect.ismethod) + inspect.getmembers(cls, inspect...
def _blame_line(self, traceback): '''Figures out which line in traceback is to blame for the error. Returns a 3-tuple of (ErrorKey, StackTraceEntry, [email recipients])''' key = None blamed_entry = None email_recipients = [] for stack_line in traceback: line_t...
def _matches_filepath_pattern(self, filepath): '''Given a filepath, and a list of regex patterns, this function returns true if filepath matches any one of those patterns''' if not self.only_blame_patterns: return True for pattern in self.only_blame_patterns: if ...
def _get_email(self, email): '''Given an email address, check the email_remapping table to see if the email should be sent to a different address. This function also handles overriding the email domain if ignore_vcs_email_domain is set or the domain was missing''' if not email or "@" not...
def _get_entry(self, entry, entry_tree): '''Helper function for retrieving a particular entry from the prefix trees''' for e in entry_tree[entry.filename]: if entry == e: return e
def markdown_to_reST(text): '''This is not a general purpose converter. Only converts this readme''' # Convert parameters to italics and prepend a newline text = re.sub(pattern=r"\n (\w+) - (.+)\n", repl=r"\n\n *\g<1>* - \g<2>\n", string=text) # Parse [ht...
def serve(conf_path, storage_factory=None): """This method starts the server. There are two processes, one is an HTTP server that shows and admin interface and the second is a Thrift server that the client code calls. Arguments: `conf_path` - The path to your flawless.cfg file `storage_fact...
def record_error(hostname, exc_info, preceding_stack=None, error_threshold=None, additional_info=None): ''' Helper function to record errors to the flawless backend ''' stack = [] exc_type, exc_value, sys_traceback = exc_info while sys_traceback is not None: stack.append(sys_traceback) ...
def migrate_thrift_obj(self, obj): """Helper function that can be called when serializing/deserializing thrift objects whose definitions have changed, we need to make sure we initialize the new attributes to their default value""" if not hasattr(obj, "thrift_spec"): return o...
def url_to_image(url): """ Fetch an image from url and convert it into a Pillow Image object """ r = requests.get(url) image = StringIO(r.content) return image
def string_to_image(image_string): """ Convert string datas into a Pillow Image object """ image_filelike = StringIO(image_string) image = Image.open(image_filelike) return image
def validate(validator): """ Return a decorator that validates arguments with provided `validator` function. This will also store the validator function as `func.validate`. The decorator returned by this function, can bypass the validator if `validate=False` is passed as argument otherwise the ...
def _is_big_enough(image, size): """Check that the image's size superior to `size`""" if (size[0] > image.size[0]) and (size[1] > image.size[1]): raise ImageSizeError(image.size, size)
def _width_is_big_enough(image, width): """Check that the image width is superior to `width`""" if width > image.size[0]: raise ImageSizeError(image.size[0], width)
def _height_is_big_enough(image, height): """Check that the image height is superior to `height`""" if height > image.size[1]: raise ImageSizeError(image.size[1], height)
def resize_crop(image, size): """ Crop the image with a centered rectangle of the specified size image: a Pillow image instance size: a list of two integers [width, height] """ img_format = image.format image = image.copy() old_size = image.size left = (old_size[0] - size[...
def resize_cover(image, size, resample=Image.LANCZOS): """ Resize image according to size. image: a Pillow image instance size: a list of two integers [width, height] """ img_format = image.format img = image.copy() img_size = img.size ratio = max(size[0] / img_size[0], si...
def resize_contain(image, size, resample=Image.LANCZOS, bg_color=(255, 255, 255, 0)): """ Resize image according to size. image: a Pillow image instance size: a list of two integers [width, height] """ img_format = image.format img = image.copy() img.thumbnail((size[0], size[1...
def resize_width(image, size, resample=Image.LANCZOS): """ Resize image according to size. image: a Pillow image instance size: an integer or a list or tuple of two integers [width, height] """ try: width = size[0] except: width = size img_format = image.format...
def resize_height(image, size, resample=Image.LANCZOS): """ Resize image according to size. image: a Pillow image instance size: an integer or a list or tuple of two integers [width, height] """ try: height = size[1] except: height = size img_format = image.for...
def resize_thumbnail(image, size, resample=Image.LANCZOS): """ Resize image according to size. image: a Pillow image instance size: a list of two integers [width, height] """ img_format = image.format img = image.copy() img.thumbnail((size[0], size[1]), resample) img.form...
def resize(method, *args, **kwargs): """ Helper function to access one of the resize function. method: one among 'crop', 'cover', 'contain', 'width', 'height' or 'thumbnail' image: a Pillow image instance size: a list or tuple of two integers [width, height] """ if method not ...
def parse_category(self, item, field_name, source_name): """ Converts the text category to a tasks.Category instance. """ # Get and checks for the corresponding slug slug = category_map.get(self.get_value(item, source_name), None) if not slug: return None ...
def parse_date(self, item, field_name, source_name): """ Converts the date in the format: Thu 03. As only the day is provided, tries to find the best match based on the current date, considering that dates are on the past. """ # Get the current date now =...
def parse_totals(self, item, field_name, source_name): """ Parse numeric fields. """ val = self.get_value(item, source_name) try: return int(val) except: return 0
def get_items(self): """ Iterator of the list of items in the XML source. """ # Use `iterparse`, it's more efficient, specially for big files for event, item in ElementTree.iterparse(self.source): if item.tag == self.item_tag_name: yield item ...
def get_value(self, item, source_name): """ This method receives an item from the source and a source name, and returns the text content for the `source_name` node. """ return force_text(smart_str(item.findtext(source_name))).strip()
def save_error(self, data, exception_info): """ Saves an error in the error list. """ # TODO: what to do with errors? Let it flow? Write to a log file? self.errors.append({'data': data, 'exception': ''.join(format_exception(*exception_info)), ...
def parse(self): """ Parses all data from the source, saving model instances. """ # Checks if the source is loaded if not self.loaded: self.load(self.source) for item in self.get_items(): # Parse the fields from the source into a dict ...
def parse_item(self, item): """ Receives an item and returns a dictionary of field values. """ # Create a dictionary from values for each field parsed_data = {} for field_name in self.fields: # A field-name may be mapped to another identifier on the s...
def get_instance(self, data): """ Get an item from the database or an empty one if not found. """ # Get unique fields unique_fields = self.unique_fields # If there are no unique fields option, all items are new if not unique_fields: return sel...
def feed_instance(self, data, instance): """ Feeds a model instance using parsed data (usually from `parse_item`). """ for prop, val in data.items(): setattr(instance, prop, val) return instance
def save_item(self, item, data, instance, commit=True): """ Saves a model instance to the database. """ if commit: instance.save() return instance
def download_file(url, dest): """ Downloads a HTTP resource from `url` and save to `dest`. Capable of dealing with Gzip compressed content. """ # Create the HTTP request request = urllib2.Request(url) # Add the header to accept gzip encoding request.add_header('Accept-enco...
def load(self, source): """ Opens the source file. """ self.source = open(self.source, 'rb') self.loaded = True
def get_items(self): """ Iterator to read the rows of the CSV file. """ # Get the csv reader reader = csv.reader(self.source) # Get the headers from the first line headers = reader.next() # Read each line yielding a dictionary mapping # the column ...
def get_value(self, item, source_name): """ This method receives an item from the source and a source name, and returns the text content for the `source_name` node. """ val = item.get(source_name.encode('utf-8'), None) if val is not None: val = convert_string(...
def get_package_meta(meta_name): """Return value of variable set in the package where said variable is named in the Python meta format `__<meta_name>__`. """ regex = "__{0}__ = ['\"]([^'\"]+)['\"]".format(meta_name) return re.search(regex, package_file).group(1)
def allow_network_access(self, value: bool): """ Raises ValueError if this sandbox instance is currently running. """ if self._is_running: raise ValueError( "Cannot change network access settings on a running sandbox") self._allow_network_access = val...
def run_command(self, args: List[str], max_num_processes: int=None, max_stack_size: int=None, max_virtual_memory: int=None, as_root: bool=False, stdin: FileIO=None, timeout: int=No...
def add_files(self, *filenames: str, owner: str=SANDBOX_USERNAME, read_only: bool=False): """ Copies the specified files into the working directory of this sandbox. The filenames specified can be absolute paths or relative paths to the current working directory. :param o...
def add_and_rename_file(self, filename: str, new_filename: str) -> None: """ Copies the specified file into the working directory of this sandbox and renames it to new_filename. """ dest = os.path.join( self.name + ':' + SANDBOX_WORKING_DIR_NAME, new_filen...
def get_enrollments_for_course(self, course_id, params={}): """ Return a list of all enrollments for the passed course_id. https://canvas.instructure.com/doc/api/enrollments.html#method.enrollments_api.index """ url = COURSES_API.format(course_id) + "/enrollments" enrol...
def get_enrollments_for_course_by_sis_id(self, sis_course_id, params={}): """ Return a list of all enrollments for the passed course sis id. """ return self.get_enrollments_for_course( self._sis_id(sis_course_id, sis_field="course"), params)