signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def move(self, x, y):
self.x = x<EOL>self.y = y<EOL>
Move Rectangle to x,y coordinates Arguments: x (int, float): X coordinate y (int, float): Y coordinate
f424:c4:m15
def contains(self, rect):
return (rect.y >= self.y andrect.x >= self.x andrect.y+rect.height <= self.y+self.height andrect.x+rect.width <= self.x+self.width)<EOL>
Tests if another rectangle is contained by this one Arguments: rect (Rectangle): The other rectangle Returns: bool: True if it is container, False otherwise
f424:c4:m16
def intersects(self, rect, edges=False):
<EOL>if (self.bottom > rect.top orself.top < rect.bottom orself.left > rect.right orself.right < rect.left):<EOL><INDENT>return False<EOL><DEDENT>if not edges:<EOL><INDENT>if (self.bottom == rect.top orself.top == rect.bottom orself.left == rect.right orself.right == rect.left):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>if (self.left == rect.right and self.bottom == rect.top orself.left == rect.right and rect.bottom == self.top orrect.left == self.right and self.bottom == rect.top orrect.left == self.right and rect.bottom == self.top):<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
Detect intersections between this rectangle and rect. Args: rect (Rectangle): Rectangle to test for intersections. edges (bool): Accept edge touching rectangles as intersects or not Returns: bool: True if the rectangles intersect, False otherwise
f424:c4:m17
def intersection(self, rect, edges=False):
if not self.intersects(rect, edges=edges):<EOL><INDENT>return None<EOL><DEDENT>bottom = max(self.bottom, rect.bottom)<EOL>left = max(self.left, rect.left)<EOL>top = min(self.top, rect.top)<EOL>right = min(self.right, rect.right)<EOL>return Rectangle(left, bottom, right-left, top-bottom)<EOL>
Returns the rectangle resulting of the intersection between this and another rectangle. If the rectangles are only touching by their edges, and the argument 'edges' is True the rectangle returned will have an area of 0. Returns None if there is no intersection. Arguments: rect (Rectangle): The other rectangle. edges (bool): If true touching edges are considered an intersection, and a rectangle of 0 height or width will be returned Returns: Rectangle: Intersection. None: There was no intersection.
f424:c4:m18
def join(self, other):
if self.contains(other):<EOL><INDENT>return True<EOL><DEDENT>if other.contains(self):<EOL><INDENT>self.x = other.x<EOL>self.y = other.y<EOL>self.width = other.width<EOL>self.height = other.height<EOL>return True<EOL><DEDENT>if not self.intersects(other, edges=True):<EOL><INDENT>return False<EOL><DEDENT>if self.left == other.left and self.width == other.width:<EOL><INDENT>y_min = min(self.bottom, other.bottom)<EOL>y_max = max(self.top, other.top) <EOL>self.y = y_min<EOL>self.height = y_max-y_min<EOL>return True<EOL><DEDENT>if self.bottom == other.bottom and self.height == other.height:<EOL><INDENT>x_min = min(self.left, other.left)<EOL>x_max = max(self.right, other.right)<EOL>self.x = x_min<EOL>self.width = x_max-x_min<EOL>return True<EOL><DEDENT>return False<EOL>
Try to join a rectangle to this one, if the result is also a rectangle and the operation is successful and this rectangle is modified to the union. Arguments: other (Rectangle): Rectangle to join Returns: bool: True when successfully joined, False otherwise
f424:c4:m19
def __init__(self, width, height, rot=True, merge=True, *args, **kwargs):
self._merge = merge<EOL>super(Guillotine, self).__init__(width, height, rot, *args, **kwargs)<EOL>
Arguments: width (int, float): height (int, float): merge (bool): Optional keyword argument
f425:c0:m0
def _add_section(self, section):
section.rid = <NUM_LIT:0> <EOL>plen = <NUM_LIT:0><EOL>while self._merge and self._sections and plen != len(self._sections):<EOL><INDENT>plen = len(self._sections)<EOL>self._sections = [s for s in self._sections if not section.join(s)]<EOL><DEDENT>self._sections.append(section)<EOL>
Adds a new section to the free section list, but before that and if section merge is enabled, tries to join the rectangle with all existing sections, if successful the resulting section is again merged with the remaining sections until the operation fails. The result is then appended to the list. Arguments: section (Rectangle): New free section.
f425:c0:m1
def _split_horizontal(self, section, width, height):
<EOL>if height < section.height:<EOL><INDENT>self._add_section(Rectangle(section.x, section.y+height,<EOL>section.width, section.height-height))<EOL><DEDENT>if width < section.width:<EOL><INDENT>self._add_section(Rectangle(section.x+width, section.y,<EOL>section.width-width, height))<EOL><DEDENT>
For an horizontal split the rectangle is placed in the lower left corner of the section (section's xy coordinates), the top most side of the rectangle and its horizontal continuation, marks the line of division for the split. +-----------------+ | | | | | | | | +-------+---------+ |#######| | |#######| | |#######| | +-------+---------+ If the rectangle width is equal to the the section width, only one section is created over the rectangle. If the rectangle height is equal to the section height, only one section to the right of the rectangle is created. If both width and height are equal, no sections are created.
f425:c0:m2
def _split_vertical(self, section, width, height):
<EOL>if height < section.height:<EOL><INDENT>self._add_section(Rectangle(section.x, section.y+height,<EOL>width, section.height-height))<EOL><DEDENT>if width < section.width:<EOL><INDENT>self._add_section(Rectangle(section.x+width, section.y,<EOL>section.width-width, section.height))<EOL><DEDENT>
For a vertical split the rectangle is placed in the lower left corner of the section (section's xy coordinates), the right most side of the rectangle and its vertical continuation, marks the line of division for the split. +-------+---------+ | | | | | | | | | | | | +-------+ | |#######| | |#######| | |#######| | +-------+---------+ If the rectangle width is equal to the the section width, only one section is created over the rectangle. If the rectangle height is equal to the section height, only one section to the right of the rectangle is created. If both width and height are equal, no sections are created.
f425:c0:m3
def _split(self, section, width, height):
raise NotImplementedError<EOL>
Selects the best split for a section, given a rectangle of dimmensions width and height, then calls _split_vertical or _split_horizontal, to do the dirty work. Arguments: section (Rectangle): Section to split width (int, float): Rectangle width height (int, float): Rectangle height
f425:c0:m4
def _section_fitness(self, section, width, height):
raise NotImplementedError<EOL>
The subclass for each one of the Guillotine selection methods, BAF, BLSF.... will override this method, this is here only to asure a valid value return if the worst happens.
f425:c0:m5
def add_rect(self, width, height, rid=None):
assert(width > <NUM_LIT:0> and height ><NUM_LIT:0>)<EOL>section, rotated = self._select_fittest_section(width, height)<EOL>if not section:<EOL><INDENT>return None<EOL><DEDENT>if rotated:<EOL><INDENT>width, height = height, width<EOL><DEDENT>self._sections.remove(section)<EOL>self._split(section, width, height)<EOL>rect = Rectangle(section.x, section.y, width, height, rid)<EOL>self.rectangles.append(rect)<EOL>return rect<EOL>
Add rectangle of widthxheight dimensions. Arguments: width (int, float): Rectangle width height (int, float): Rectangle height rid: Optional rectangle user id Returns: Rectangle: Rectangle with placemente coordinates None: If the rectangle couldn be placed.
f425:c0:m7
def fitness(self, width, height):
assert(width > <NUM_LIT:0> and height > <NUM_LIT:0>)<EOL>section, rotated = self._select_fittest_section(width, height)<EOL>if not section:<EOL><INDENT>return None<EOL><DEDENT>if rotated:<EOL><INDENT>return self._section_fitness(section, height, width)<EOL><DEDENT>else:<EOL><INDENT>return self._section_fitness(section, width, height)<EOL><DEDENT>
In guillotine algorithm case, returns the min of the fitness of all free sections, for the given dimension, both normal and rotated (if rotation enabled.)
f425:c0:m8
def __init__(self, width, height, rot=True, bid=None, *args, **kwargs):
self.width = width<EOL>self.height = height<EOL>self.rot = rot<EOL>self.rectangles = []<EOL>self.bid = bid<EOL>self._surface = Rectangle(<NUM_LIT:0>, <NUM_LIT:0>, width, height)<EOL>self.reset()<EOL>
Initialize packing algorithm Arguments: width (int, float): Packing surface width height (int, float): Packing surface height rot (bool): Rectangle rotation enabled or disabled bid (string|int|...): Packing surface identification
f426:c0:m0
def _fits_surface(self, width, height):
assert(width > <NUM_LIT:0> and height > <NUM_LIT:0>)<EOL>if self.rot and (width > self.width or height > self.height):<EOL><INDENT>width, height = height, width<EOL><DEDENT>if width > self.width or height > self.height:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT>
Test surface is big enough to place a rectangle Arguments: width (int, float): Rectangle width height (int, float): Rectangle height Returns: boolean: True if it could be placed, False otherwise
f426:c0:m3
def __getitem__(self, key):
return self.rectangles[key]<EOL>
Return rectangle in selected position.
f426:c0:m4
def used_area(self):
return sum(r.area() for r in self)<EOL>
Total area of rectangles placed Returns: int, float: Area
f426:c0:m5
def fitness(self, width, height, rot = False):
raise NotImplementedError<EOL>
Metric used to rate how much space is wasted if a rectangle is placed. Returns a value greater or equal to zero, the smaller the value the more 'fit' is the rectangle. If the rectangle can't be placed, returns None. Arguments: width (int, float): Rectangle width height (int, float): Rectangle height rot (bool): Enable rectangle rotation Returns: int, float: Rectangle fitness None: Rectangle can't be placed
f426:c0:m6
def add_rect(self, width, height, rid=None):
raise NotImplementedError<EOL>
Add rectangle of widthxheight dimensions. Arguments: width (int, float): Rectangle width height (int, float): Rectangle height rid: Optional rectangle user id Returns: Rectangle: Rectangle with placemente coordinates None: If the rectangle couldn be placed.
f426:c0:m7
def rect_list(self):
rectangle_list = []<EOL>for r in self:<EOL><INDENT>rectangle_list.append((r.x, r.y, r.width, r.height, r.rid))<EOL><DEDENT>return rectangle_list<EOL>
Returns a list with all rectangles placed into the surface. Returns: List: Format [(rid, x, y, width, height), ...]
f426:c0:m8
def validate_packing(self):
surface = Rectangle(<NUM_LIT:0>, <NUM_LIT:0>, self.width, self.height)<EOL>for r in self:<EOL><INDENT>if not surface.contains(r):<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT><DEDENT>rectangles = [r for r in self]<EOL>if len(rectangles) <= <NUM_LIT:1>:<EOL><INDENT>return<EOL><DEDENT>for r1 in range(<NUM_LIT:0>, len(rectangles)-<NUM_LIT:2>):<EOL><INDENT>for r2 in range(r1+<NUM_LIT:1>, len(rectangles)-<NUM_LIT:1>):<EOL><INDENT>if rectangles[r1].intersects(rectangles[r2]):<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>
Check for collisions between rectangles, also check all are placed inside surface.
f426:c0:m9
def __init__(self, rectangles=[], max_width=None, max_height=None, rotation=True):
<EOL>self._max_width = max_width<EOL>self._max_height = max_height<EOL>self._rotation = rotation<EOL>self._pack_algo = SkylineBlWm<EOL>self._rectangles = []<EOL>for r in rectangles:<EOL><INDENT>self.add_rect(*r)<EOL><DEDENT>
Arguments: rectangles (list): Rectangle to be enveloped [(width1, height1), (width2, height2), ...] max_width (number|None): Enveloping rectangle max allowed width. max_height (number|None): Enveloping rectangle max allowed height. rotation (boolean): Enable/Disable rectangle rotation.
f428:c0:m0
def _container_candidates(self):
if not self._rectangles:<EOL><INDENT>return []<EOL><DEDENT>if self._rotation:<EOL><INDENT>sides = sorted(side for rect in self._rectangles for side in rect)<EOL>max_height = sum(max(r[<NUM_LIT:0>], r[<NUM_LIT:1>]) for r in self._rectangles)<EOL>min_width = max(min(r[<NUM_LIT:0>], r[<NUM_LIT:1>]) for r in self._rectangles)<EOL>max_width = max_height<EOL><DEDENT>else:<EOL><INDENT>sides = sorted(r[<NUM_LIT:0>] for r in self._rectangles)<EOL>max_height = sum(r[<NUM_LIT:1>] for r in self._rectangles)<EOL>min_width = max(r[<NUM_LIT:0>] for r in self._rectangles)<EOL>max_width = sum(sides)<EOL><DEDENT>if self._max_width and self._max_width < max_width:<EOL><INDENT>max_width = self._max_width<EOL><DEDENT>if self._max_height and self._max_height < max_height:<EOL><INDENT>max_height = self._max_height<EOL><DEDENT>assert(max_width>min_width)<EOL>candidates = [max_width, min_width]<EOL>width = <NUM_LIT:0><EOL>for s in reversed(sides):<EOL><INDENT>width += s<EOL>candidates.append(width)<EOL><DEDENT>width = <NUM_LIT:0><EOL>for s in sides:<EOL><INDENT>width += s<EOL>candidates.append(width)<EOL><DEDENT>candidates.append(max_width)<EOL>candidates.append(min_width)<EOL>seen = set()<EOL>seen_add = seen.add<EOL>candidates = [x for x in candidates if not(x in seen or seen_add(x))] <EOL>candidates = [x for x in candidates if not(x>max_width or x<min_width)]<EOL>min_area = sum(r[<NUM_LIT:0>]*r[<NUM_LIT:1>] for r in self._rectangles)<EOL>return [(c, max_height) for c in candidates if c*max_height>=min_area]<EOL>
Generate container candidate list Returns: tuple list: [(width1, height1), (width2, height2), ...]
f428:c0:m1
def _refine_candidate(self, width, height):
packer = newPacker(PackingMode.Offline, PackingBin.BFF, <EOL>pack_algo=self._pack_algo, sort_algo=SORT_LSIDE,<EOL>rotation=self._rotation)<EOL>packer.add_bin(width, height)<EOL>for r in self._rectangles:<EOL><INDENT>packer.add_rect(*r)<EOL><DEDENT>packer.pack()<EOL>if len(packer[<NUM_LIT:0>]) != len(self._rectangles):<EOL><INDENT>return None<EOL><DEDENT>new_height = max(packer[<NUM_LIT:0>], key=lambda x: x.top).top<EOL>return(width, new_height, packer)<EOL>
Use bottom-left packing algorithm to find a lower height for the container. Arguments: width height Returns: tuple (width, height, PackingAlgorithm):
f428:c0:m2
def add_rect(self, width, height):
self._rectangles.append((width, height))<EOL>
Add anoter rectangle to be enclosed Arguments: width (number): Rectangle width height (number): Rectangle height
f428:c0:m4
def add_waste(self, x, y, width, height):
self._add_section(Rectangle(x, y, width, height))<EOL>
Add new waste section
f429:c0:m1
def sub_dfs_by_size(df, size):
for i in range(<NUM_LIT:0>, len(df), size):<EOL><INDENT>yield (df.iloc[i:i + size])<EOL><DEDENT>
Get a generator yielding consecutive sub-dataframes of the given size. Arguments --------- df : pandas.DataFrame The dataframe for which to get sub-dataframes. size : int The size of each sub-dataframe. Returns ------- generator A generator yielding consecutive sub-dataframe of the given size. Example ------- >>> import pandas as pd; import pdutil; >>> data = [[23, "Jen"], [42, "Ray"], [15, "Fin"]] >>> df = pd.DataFrame(data, columns=['age', 'name']) >>> for subdf in pdutil.iter.sub_dfs_by_size(df, 2): print(subdf) age name 0 23 Jen 1 42 Ray age name 2 15 Fin
f432:m0
def sub_dfs_by_num(df, num):
size = len(df) / float(num)<EOL>for i in range(num):<EOL><INDENT>yield df.iloc[int(round(size * i)): int(round(size * (i + <NUM_LIT:1>)))]<EOL><DEDENT>
Get a generator yielding num consecutive sub-dataframes of the given df. Arguments --------- df : pandas.DataFrame The dataframe for which to get sub-dataframes. num : int The number of sub-dataframe to divide the given dataframe into. Returns ------- generator A generator yielding n consecutive sub-dataframes of the given df. Example ------- >>> import pandas as pd; import pdutil; >>> data = [[23, "Jen"], [42, "Ray"], [15, "Fin"]] >>> df = pd.DataFrame(data, columns=['age', 'name']) >>> for subdf in pdutil.iter.sub_dfs_by_num(df, 2): print(subdf) age name 0 23 Jen 1 42 Ray age name 2 15 Fin
f432:m1
@classmethod<EOL><INDENT>def by_name(cls, name):<DEDENT>
return cls.__NAME_TO_OBJ__[name]<EOL>
Returns a SerializationFormat object by the format name. Parameters ---------- name : str The name of the serialization format. E.g. 'csv' or 'feather'. Returns ------- SerializationFormat An object representing the given serialization format. Example ------- >>> SerializationFormat.by_name('csv') <pdutil.serial.SerializationFormat.csv>
f435:c0:m2
def get_keywords():
<EOL>git_refnames = "<STR_LIT>"<EOL>git_full = "<STR_LIT>"<EOL>git_date = "<STR_LIT>"<EOL>keywords = {"<STR_LIT>": git_refnames, "<STR_LIT>": git_full, "<STR_LIT:date>": git_date}<EOL>return keywords<EOL>
Get the keywords needed to look up the version information.
f436:m0
def get_config():
<EOL>cfg = VersioneerConfig()<EOL>cfg.VCS = "<STR_LIT>"<EOL>cfg.style = "<STR_LIT>"<EOL>cfg.tag_prefix = "<STR_LIT:v>"<EOL>cfg.parentdir_prefix = "<STR_LIT>"<EOL>cfg.versionfile_source = "<STR_LIT>"<EOL>cfg.verbose = False<EOL>return cfg<EOL>
Create, populate and return the VersioneerConfig() object.
f436:m1
def register_vcs_handler(vcs, method):
def decorate(f):<EOL><INDENT>"""<STR_LIT>"""<EOL>if vcs not in HANDLERS:<EOL><INDENT>HANDLERS[vcs] = {}<EOL><DEDENT>HANDLERS[vcs][method] = f<EOL>return f<EOL><DEDENT>return decorate<EOL>
Decorator to mark a method as the handler for a particular VCS.
f436:m2
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,<EOL>env=None):
assert isinstance(commands, list)<EOL>p = None<EOL>for c in commands:<EOL><INDENT>try:<EOL><INDENT>dispcmd = str([c] + args)<EOL>p = subprocess.Popen([c] + args, cwd=cwd, env=env,<EOL>stdout=subprocess.PIPE,<EOL>stderr=(subprocess.PIPE if hide_stderr<EOL>else None))<EOL>break<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>e = sys.exc_info()[<NUM_LIT:1>]<EOL>if e.errno == errno.ENOENT:<EOL><INDENT>continue<EOL><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print(e)<EOL><DEDENT>return None, None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % (commands,))<EOL><DEDENT>return None, None<EOL><DEDENT>stdout = p.communicate()[<NUM_LIT:0>].strip()<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>stdout = stdout.decode()<EOL><DEDENT>if p.returncode != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print("<STR_LIT>" % stdout)<EOL><DEDENT>return None, p.returncode<EOL><DEDENT>return stdout, p.returncode<EOL>
Call the given command(s).
f436:m3
def versions_from_parentdir(parentdir_prefix, root, verbose):
rootdirs = []<EOL>for i in range(<NUM_LIT:3>):<EOL><INDENT>dirname = os.path.basename(root)<EOL>if dirname.startswith(parentdir_prefix):<EOL><INDENT>return {"<STR_LIT:version>": dirname[len(parentdir_prefix):],<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None, "<STR_LIT:date>": None}<EOL><DEDENT>else:<EOL><INDENT>rootdirs.append(root)<EOL>root = os.path.dirname(root) <EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" %<EOL>(str(rootdirs), parentdir_prefix))<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL>
Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory
f436:m4
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_get_keywords(versionfile_abs):
<EOL>keywords = {}<EOL>try:<EOL><INDENT>f = open(versionfile_abs, "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT:date>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>return keywords<EOL>
Extract version information from the given file.
f436:m5
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_versions_from_keywords(keywords, tag_prefix, verbose):
if not keywords:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>date = keywords.get("<STR_LIT:date>")<EOL>if date is not None:<EOL><INDENT>date = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL><DEDENT>refnames = keywords["<STR_LIT>"].strip()<EOL>if refnames.startswith("<STR_LIT>"):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refs = set([r.strip() for r in refnames.strip("<STR_LIT>").split("<STR_LIT:U+002C>")])<EOL>TAG = "<STR_LIT>"<EOL>tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])<EOL>if not tags:<EOL><INDENT>tags = set([r for r in refs if re.search(r'<STR_LIT>', r)])<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(refs - tags))<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(sorted(tags)))<EOL><DEDENT>for ref in sorted(tags):<EOL><INDENT>if ref.startswith(tag_prefix):<EOL><INDENT>r = ref[len(tag_prefix):]<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % r)<EOL><DEDENT>return {"<STR_LIT:version>": r,<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None,<EOL>"<STR_LIT:date>": date}<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": "<STR_LIT>", "<STR_LIT:date>": None}<EOL>
Get version information from git keywords.
f436:m6
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root,<EOL>hide_stderr=True)<EOL>if rc != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % root)<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>" % tag_prefix],<EOL>cwd=root)<EOL>if describe_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out = describe_out.strip()<EOL>full_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root)<EOL>if full_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>full_out = full_out.strip()<EOL>pieces = {}<EOL>pieces["<STR_LIT>"] = full_out<EOL>pieces["<STR_LIT>"] = full_out[:<NUM_LIT:7>] <EOL>pieces["<STR_LIT:error>"] = None<EOL>git_describe = describe_out<EOL>dirty = git_describe.endswith("<STR_LIT>")<EOL>pieces["<STR_LIT>"] = dirty<EOL>if dirty:<EOL><INDENT>git_describe = git_describe[:git_describe.rindex("<STR_LIT>")]<EOL><DEDENT>if "<STR_LIT:->" in git_describe:<EOL><INDENT>mo = re.search(r'<STR_LIT>', git_describe)<EOL>if not mo:<EOL><INDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% describe_out)<EOL>return pieces<EOL><DEDENT>full_tag = mo.group(<NUM_LIT:1>)<EOL>if not full_tag.startswith(tag_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>fmt = "<STR_LIT>"<EOL>print(fmt % (full_tag, tag_prefix))<EOL><DEDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% (full_tag, tag_prefix))<EOL>return pieces<EOL><DEDENT>pieces["<STR_LIT>"] = full_tag[len(tag_prefix):]<EOL>pieces["<STR_LIT>"] = int(mo.group(<NUM_LIT:2>))<EOL>pieces["<STR_LIT>"] = mo.group(<NUM_LIT:3>)<EOL><DEDENT>else:<EOL><INDENT>pieces["<STR_LIT>"] = None<EOL>count_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)<EOL>pieces["<STR_LIT>"] = int(count_out) <EOL><DEDENT>date = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)[<NUM_LIT:0>].strip()<EOL>pieces["<STR_LIT:date>"] = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL>return pieces<EOL>
Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree.
f436:m7
def plus_or_dot(pieces):
if "<STR_LIT:+>" in pieces.get("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return "<STR_LIT:.>"<EOL><DEDENT>return "<STR_LIT:+>"<EOL>
Return a + if we don't already have one, else return a .
f436:m8
def render_pep440(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % (pieces["<STR_LIT>"],<EOL>pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>
Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
f436:m9
def render_pep440_pre(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>
TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE
f436:m10
def render_pep440_post(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>
TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]
f436:m11
def render_pep440_old(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>
TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0]
f436:m12
def render_git_describe(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>
TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix)
f436:m13
def render_git_describe_long(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>
TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix)
f436:m14
def render(pieces, style):
if pieces["<STR_LIT:error>"]:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": pieces.get("<STR_LIT>"),<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": pieces["<STR_LIT:error>"],<EOL>"<STR_LIT:date>": None}<EOL><DEDENT>if not style or style == "<STR_LIT:default>":<EOL><INDENT>style = "<STR_LIT>" <EOL><DEDENT>if style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_pre(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_post(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_old(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe_long(pieces)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % style)<EOL><DEDENT>return {"<STR_LIT:version>": rendered, "<STR_LIT>": pieces["<STR_LIT>"],<EOL>"<STR_LIT>": pieces["<STR_LIT>"], "<STR_LIT:error>": None,<EOL>"<STR_LIT:date>": pieces.get("<STR_LIT:date>")}<EOL>
Render the given version pieces into the requested style.
f436:m15
def get_versions():
<EOL>cfg = get_config()<EOL>verbose = cfg.verbose<EOL>try:<EOL><INDENT>return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,<EOL>verbose)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>root = os.path.realpath(__file__)<EOL>for i in cfg.versionfile_source.split('<STR_LIT:/>'):<EOL><INDENT>root = os.path.dirname(root)<EOL><DEDENT><DEDENT>except NameError:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": "<STR_LIT>",<EOL>"<STR_LIT:date>": None}<EOL><DEDENT>try:<EOL><INDENT>pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)<EOL>return render(pieces, cfg.style)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>if cfg.parentdir_prefix:<EOL><INDENT>return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)<EOL><DEDENT><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": "<STR_LIT>", "<STR_LIT:date>": None}<EOL>
Get version information or return default if unable to do so.
f436:m16
def x_y_by_col_lbl(df, y_col_lbl):
x_cols = [col for col in df.columns if col != y_col_lbl]<EOL>return df[x_cols], df[y_col_lbl]<EOL>
Returns an X dataframe and a y series by the given column name. Parameters ---------- df : pandas.DataFrame The dataframe to split. y_col_lbl : object The label of the y column. Returns ------- X, y : pandas.DataFrame, pandas.Series A dataframe made up of all columns but the column with the given name and a series made up of the same column, respectively. Example ------- >>> import pandas as pd >>> data = [[23, 'Jo', 4], [19, 'Mi', 3]] >>> df = pd.DataFrame(data, [1, 2] , ['Age', 'Name', 'D']) >>> X, y = x_y_by_col_lbl(df, 'D') >>> X Age Name 1 23 Jo 2 19 Mi >>> y 1 4 2 3 Name: D, dtype: int64
f438:m0
def x_y_by_col_lbl_inplace(df, y_col_lbl):
y = df[y_col_lbl]<EOL>df.drop(<EOL>labels=y_col_lbl,<EOL>axis=<NUM_LIT:1>,<EOL>inplace=True,<EOL>)<EOL>return df, y<EOL>
Breaks the given dataframe into an X frame and a y series by the given column name. The original frame is returned, without the y series column, as the X frame, so no new dataframes are created. Parameters ---------- df : pandas.DataFrame The dataframe to split. y_col_lbl : object The label of the y column. Returns ------- X, y : pandas.DataFrame, pandas.Series A dataframe made up of all columns but the column with the given name and a series made up of the same column, respectively. Example ------- >>> import pandas as pd >>> data = [[23, 'Jo', 4], [19, 'Mi', 3]] >>> df = pd.DataFrame(data, [1, 2] , ['Age', 'Name', 'D']) >>> X, y = x_y_by_col_lbl(df, 'D') >>> X Age Name 1 23 Jo 2 19 Mi >>> y 1 4 2 3 Name: D, dtype: int64
f438:m1
def or_by_masks(df, masks):
if len(masks) < <NUM_LIT:1>:<EOL><INDENT>return df<EOL><DEDENT>if len(masks) == <NUM_LIT:1>:<EOL><INDENT>return df[masks[<NUM_LIT:0>]]<EOL><DEDENT>overall_mask = masks[<NUM_LIT:0>] | masks[<NUM_LIT:1>]<EOL>for mask in masks[<NUM_LIT:2>:]:<EOL><INDENT>overall_mask = overall_mask | mask<EOL><DEDENT>return df[overall_mask]<EOL>
Returns a sub-dataframe by the logical or over the given masks. Parameters ---------- df : pandas.DataFrame The dataframe to take a subframe of. masks : list A list of pandas.Series of dtype bool, indexed identically to the given dataframe. Returns ------- pandas.DataFrame The sub-dataframe resulting from applying the masks to the dataframe. Example ------- >>> import pandas as pd >>> data = [[23, 'Jo'], [19, 'Mi'], [15, 'Di']] >>> df = pd.DataFrame(data, [1, 2, 3] , ['Age', 'Name']) >>> mask1 = pd.Series([False, True, True], df.index) >>> mask2 = pd.Series([False, False, True], df.index) >>> or_by_masks(df, [mask1, mask2]) Age Name 2 19 Mi 3 15 Di
f438:m2
def or_by_mask_conditions(df, mask_conditions):
return or_by_masks(df, [cond(df) for cond in mask_conditions])<EOL>
Returns a sub-dataframe by the logical-or over given mask conditions, Parameters ---------- df : pandas.DataFrame The dataframe to take a subframe of. mask_conditions : list A list of functions that, when applied to a dataframe, produce each a pandas.Series of dtype bool, indexed identically to the dataframe. Returns ------- pandas.DataFrame The sub-dataframe resulting from applying the mask conditions to the dataframe. Example ------- >>> import pandas as pd >>> data = [[23, 'Jo'], [19, 'Mi'], [15, 'Di']] >>> df = pd.DataFrame(data, [1, 2, 3] , ['Age', 'Name']) >>> mask_cond1 = lambda df: df.Age < 18 >>> mask_cond2 = lambda df: df.Age > 20 >>> or_by_mask_conditions(df, [mask_cond1, mask_cond2]) Age Name 1 23 Jo 3 15 Di
f438:m3
def df_string(df, percentage_columns=(), format_map=None, **kwargs):
formatters_map = {}<EOL>for col, dtype in df.dtypes.iteritems():<EOL><INDENT>if col in percentage_columns:<EOL><INDENT>formatters_map[col] = '<STR_LIT>'.format<EOL><DEDENT>elif dtype == '<STR_LIT>':<EOL><INDENT>formatters_map[col] = '<STR_LIT>'.format<EOL><DEDENT><DEDENT>if format_map:<EOL><INDENT>for key in format_map:<EOL><INDENT>formatters_map[key] = format_map[key]<EOL><DEDENT><DEDENT>return df.to_string(formatters=formatters_map, **kwargs)<EOL>
Return a nicely formatted string for the given dataframe. Arguments --------- df : pandas.DataFrame A dataframe object. percentage_columns : iterable A list of cloumn names to be displayed with a percentage sign. Returns ------- str A nicely formatted string for the given dataframe. Example ------- >>> import pandas as pd >>> df = pd.DataFrame([[8,'a'],[5,'b']],[1,2],['num', 'char']) >>> print(df_string(df)) num char 1 8 a 2 5 b
f440:m0
def big_dataframe_setup():
pd.set_option('<STR_LIT>', sys.maxsize)<EOL>pd.set_option('<STR_LIT>', sys.maxsize)<EOL>pd.set_option('<STR_LIT>', sys.maxsize)<EOL>pd.set_option('<STR_LIT>', sys.maxsize)<EOL>pd.set_option('<STR_LIT>', '<STR_LIT>')<EOL>pd.set_option('<STR_LIT>', sys.maxsize)<EOL>pd.set_option('<STR_LIT>', sys.maxsize)<EOL>pd.set_option('<STR_LIT>', True)<EOL>
Sets pandas to display really big data frames.
f440:m1
def df_to_html(df, percentage_columns=None):
big_dataframe_setup()<EOL>try:<EOL><INDENT>res = '<STR_LIT>'.format(df.name)<EOL><DEDENT>except AttributeError:<EOL><INDENT>res = '<STR_LIT>'<EOL><DEDENT>df.style.set_properties(**{'<STR_LIT>': '<STR_LIT>'})<EOL>res += df.to_html(formatters=_formatters_dict(<EOL>input_df=df,<EOL>percentage_columns=percentage_columns<EOL>))<EOL>res += '<STR_LIT>'<EOL>return res<EOL>
Return a nicely formatted HTML code string for the given dataframe. Arguments --------- df : pandas.DataFrame A dataframe object. percentage_columns : iterable A list of cloumn names to be displayed with a percentage sign. Returns ------- str A nicely formatted string for the given dataframe.
f440:m4
def get_root():
root = os.path.realpath(os.path.abspath(os.getcwd()))<EOL>setup_py = os.path.join(root, "<STR_LIT>")<EOL>versioneer_py = os.path.join(root, "<STR_LIT>")<EOL>if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):<EOL><INDENT>root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[<NUM_LIT:0>])))<EOL>setup_py = os.path.join(root, "<STR_LIT>")<EOL>versioneer_py = os.path.join(root, "<STR_LIT>")<EOL><DEDENT>if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):<EOL><INDENT>err = ("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>raise VersioneerBadRootError(err)<EOL><DEDENT>try:<EOL><INDENT>me = os.path.realpath(os.path.abspath(__file__))<EOL>me_dir = os.path.normcase(os.path.splitext(me)[<NUM_LIT:0>])<EOL>vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[<NUM_LIT:0>])<EOL>if me_dir != vsr_dir:<EOL><INDENT>print("<STR_LIT>"<EOL>% (os.path.dirname(me), versioneer_py))<EOL><DEDENT><DEDENT>except NameError:<EOL><INDENT>pass<EOL><DEDENT>return root<EOL>
Get the project root directory. We require that all commands are run from the project root, i.e. the directory that contains setup.py, setup.cfg, and versioneer.py .
f443:m0
def get_config_from_root(root):
<EOL>setup_cfg = os.path.join(root, "<STR_LIT>")<EOL>parser = configparser.SafeConfigParser()<EOL>with open(setup_cfg, "<STR_LIT:r>") as f:<EOL><INDENT>parser.readfp(f)<EOL><DEDENT>VCS = parser.get("<STR_LIT>", "<STR_LIT>") <EOL>def get(parser, name):<EOL><INDENT>if parser.has_option("<STR_LIT>", name):<EOL><INDENT>return parser.get("<STR_LIT>", name)<EOL><DEDENT>return None<EOL><DEDENT>cfg = VersioneerConfig()<EOL>cfg.VCS = VCS<EOL>cfg.style = get(parser, "<STR_LIT>") or "<STR_LIT>"<EOL>cfg.versionfile_source = get(parser, "<STR_LIT>")<EOL>cfg.versionfile_build = get(parser, "<STR_LIT>")<EOL>cfg.tag_prefix = get(parser, "<STR_LIT>")<EOL>if cfg.tag_prefix in ("<STR_LIT>", '<STR_LIT>'):<EOL><INDENT>cfg.tag_prefix = "<STR_LIT>"<EOL><DEDENT>cfg.parentdir_prefix = get(parser, "<STR_LIT>")<EOL>cfg.verbose = get(parser, "<STR_LIT>")<EOL>return cfg<EOL>
Read the project setup.cfg file to determine Versioneer config.
f443:m1
def register_vcs_handler(vcs, method):
def decorate(f):<EOL><INDENT>"""<STR_LIT>"""<EOL>if vcs not in HANDLERS:<EOL><INDENT>HANDLERS[vcs] = {}<EOL><DEDENT>HANDLERS[vcs][method] = f<EOL>return f<EOL><DEDENT>return decorate<EOL>
Decorator to mark a method as the handler for a particular VCS.
f443:m2
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,<EOL>env=None):
assert isinstance(commands, list)<EOL>p = None<EOL>for c in commands:<EOL><INDENT>try:<EOL><INDENT>dispcmd = str([c] + args)<EOL>p = subprocess.Popen([c] + args, cwd=cwd, env=env,<EOL>stdout=subprocess.PIPE,<EOL>stderr=(subprocess.PIPE if hide_stderr<EOL>else None))<EOL>break<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>e = sys.exc_info()[<NUM_LIT:1>]<EOL>if e.errno == errno.ENOENT:<EOL><INDENT>continue<EOL><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print(e)<EOL><DEDENT>return None, None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % (commands,))<EOL><DEDENT>return None, None<EOL><DEDENT>stdout = p.communicate()[<NUM_LIT:0>].strip()<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>stdout = stdout.decode()<EOL><DEDENT>if p.returncode != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print("<STR_LIT>" % stdout)<EOL><DEDENT>return None, p.returncode<EOL><DEDENT>return stdout, p.returncode<EOL>
Call the given command(s).
f443:m3
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_get_keywords(versionfile_abs):
<EOL>keywords = {}<EOL>try:<EOL><INDENT>f = open(versionfile_abs, "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT:date>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>return keywords<EOL>
Extract version information from the given file.
f443:m4
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_versions_from_keywords(keywords, tag_prefix, verbose):
if not keywords:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>date = keywords.get("<STR_LIT:date>")<EOL>if date is not None:<EOL><INDENT>date = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL><DEDENT>refnames = keywords["<STR_LIT>"].strip()<EOL>if refnames.startswith("<STR_LIT>"):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refs = set([r.strip() for r in refnames.strip("<STR_LIT>").split("<STR_LIT:U+002C>")])<EOL>TAG = "<STR_LIT>"<EOL>tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])<EOL>if not tags:<EOL><INDENT>tags = set([r for r in refs if re.search(r'<STR_LIT>', r)])<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(refs - tags))<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(sorted(tags)))<EOL><DEDENT>for ref in sorted(tags):<EOL><INDENT>if ref.startswith(tag_prefix):<EOL><INDENT>r = ref[len(tag_prefix):]<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % r)<EOL><DEDENT>return {"<STR_LIT:version>": r,<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None,<EOL>"<STR_LIT:date>": date}<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": "<STR_LIT>", "<STR_LIT:date>": None}<EOL>
Get version information from git keywords.
f443:m5
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root,<EOL>hide_stderr=True)<EOL>if rc != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % root)<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>" % tag_prefix],<EOL>cwd=root)<EOL>if describe_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out = describe_out.strip()<EOL>full_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root)<EOL>if full_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>full_out = full_out.strip()<EOL>pieces = {}<EOL>pieces["<STR_LIT>"] = full_out<EOL>pieces["<STR_LIT>"] = full_out[:<NUM_LIT:7>] <EOL>pieces["<STR_LIT:error>"] = None<EOL>git_describe = describe_out<EOL>dirty = git_describe.endswith("<STR_LIT>")<EOL>pieces["<STR_LIT>"] = dirty<EOL>if dirty:<EOL><INDENT>git_describe = git_describe[:git_describe.rindex("<STR_LIT>")]<EOL><DEDENT>if "<STR_LIT:->" in git_describe:<EOL><INDENT>mo = re.search(r'<STR_LIT>', git_describe)<EOL>if not mo:<EOL><INDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% describe_out)<EOL>return pieces<EOL><DEDENT>full_tag = mo.group(<NUM_LIT:1>)<EOL>if not full_tag.startswith(tag_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>fmt = "<STR_LIT>"<EOL>print(fmt % (full_tag, tag_prefix))<EOL><DEDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% (full_tag, tag_prefix))<EOL>return pieces<EOL><DEDENT>pieces["<STR_LIT>"] = full_tag[len(tag_prefix):]<EOL>pieces["<STR_LIT>"] = int(mo.group(<NUM_LIT:2>))<EOL>pieces["<STR_LIT>"] = mo.group(<NUM_LIT:3>)<EOL><DEDENT>else:<EOL><INDENT>pieces["<STR_LIT>"] = None<EOL>count_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)<EOL>pieces["<STR_LIT>"] = int(count_out) <EOL><DEDENT>date = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)[<NUM_LIT:0>].strip()<EOL>pieces["<STR_LIT:date>"] = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL>return pieces<EOL>
Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree.
f443:m6
def do_vcs_install(manifest_in, versionfile_source, ipy):
GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>files = [manifest_in, versionfile_source]<EOL>if ipy:<EOL><INDENT>files.append(ipy)<EOL><DEDENT>try:<EOL><INDENT>me = __file__<EOL>if me.endswith("<STR_LIT>") or me.endswith("<STR_LIT>"):<EOL><INDENT>me = os.path.splitext(me)[<NUM_LIT:0>] + "<STR_LIT>"<EOL><DEDENT>versioneer_file = os.path.relpath(me)<EOL><DEDENT>except NameError:<EOL><INDENT>versioneer_file = "<STR_LIT>"<EOL><DEDENT>files.append(versioneer_file)<EOL>present = False<EOL>try:<EOL><INDENT>f = open("<STR_LIT>", "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith(versionfile_source):<EOL><INDENT>if "<STR_LIT>" in line.strip().split()[<NUM_LIT:1>:]:<EOL><INDENT>present = True<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>if not present:<EOL><INDENT>f = open("<STR_LIT>", "<STR_LIT>")<EOL>f.write("<STR_LIT>" % versionfile_source)<EOL>f.close()<EOL>files.append("<STR_LIT>")<EOL><DEDENT>run_command(GITS, ["<STR_LIT>", "<STR_LIT>"] + files)<EOL>
Git-specific installation logic for Versioneer. For Git, this means creating/changing .gitattributes to mark _version.py for export-subst keyword substitution.
f443:m7
def versions_from_parentdir(parentdir_prefix, root, verbose):
rootdirs = []<EOL>for i in range(<NUM_LIT:3>):<EOL><INDENT>dirname = os.path.basename(root)<EOL>if dirname.startswith(parentdir_prefix):<EOL><INDENT>return {"<STR_LIT:version>": dirname[len(parentdir_prefix):],<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None, "<STR_LIT:date>": None}<EOL><DEDENT>else:<EOL><INDENT>rootdirs.append(root)<EOL>root = os.path.dirname(root) <EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" %<EOL>(str(rootdirs), parentdir_prefix))<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL>
Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory
f443:m8
def versions_from_file(filename):
try:<EOL><INDENT>with open(filename) as f:<EOL><INDENT>contents = f.read()<EOL><DEDENT><DEDENT>except EnvironmentError:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>mo = re.search(r"<STR_LIT>",<EOL>contents, re.M | re.S)<EOL>if not mo:<EOL><INDENT>mo = re.search(r"<STR_LIT>",<EOL>contents, re.M | re.S)<EOL><DEDENT>if not mo:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>return json.loads(mo.group(<NUM_LIT:1>))<EOL>
Try to determine the version from _version.py if present.
f443:m9
def write_to_version_file(filename, versions):
os.unlink(filename)<EOL>contents = json.dumps(versions, sort_keys=True,<EOL>indent=<NUM_LIT:1>, separators=("<STR_LIT:U+002C>", "<STR_LIT>"))<EOL>with open(filename, "<STR_LIT:w>") as f:<EOL><INDENT>f.write(SHORT_VERSION_PY % contents)<EOL><DEDENT>print("<STR_LIT>" % (filename, versions["<STR_LIT:version>"]))<EOL>
Write the given version number to the given _version.py file.
f443:m10
def plus_or_dot(pieces):
if "<STR_LIT:+>" in pieces.get("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return "<STR_LIT:.>"<EOL><DEDENT>return "<STR_LIT:+>"<EOL>
Return a + if we don't already have one, else return a .
f443:m11
def render_pep440(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % (pieces["<STR_LIT>"],<EOL>pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>
Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
f443:m12
def render_pep440_pre(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>
TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE
f443:m13
def render_pep440_post(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>
TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]
f443:m14
def render_pep440_old(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>
TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0]
f443:m15
def render_git_describe(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>
TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix)
f443:m16
def render_git_describe_long(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>
TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix)
f443:m17
def render(pieces, style):
if pieces["<STR_LIT:error>"]:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": pieces.get("<STR_LIT>"),<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": pieces["<STR_LIT:error>"],<EOL>"<STR_LIT:date>": None}<EOL><DEDENT>if not style or style == "<STR_LIT:default>":<EOL><INDENT>style = "<STR_LIT>" <EOL><DEDENT>if style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_pre(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_post(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_old(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe_long(pieces)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % style)<EOL><DEDENT>return {"<STR_LIT:version>": rendered, "<STR_LIT>": pieces["<STR_LIT>"],<EOL>"<STR_LIT>": pieces["<STR_LIT>"], "<STR_LIT:error>": None,<EOL>"<STR_LIT:date>": pieces.get("<STR_LIT:date>")}<EOL>
Render the given version pieces into the requested style.
f443:m18
def get_versions(verbose=False):
if "<STR_LIT>" in sys.modules:<EOL><INDENT>del sys.modules["<STR_LIT>"]<EOL><DEDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>assert cfg.VCS is not None, "<STR_LIT>"<EOL>handlers = HANDLERS.get(cfg.VCS)<EOL>assert handlers, "<STR_LIT>" % cfg.VCS<EOL>verbose = verbose or cfg.verbose<EOL>assert cfg.versionfile_source is not None,"<STR_LIT>"<EOL>assert cfg.tag_prefix is not None, "<STR_LIT>"<EOL>versionfile_abs = os.path.join(root, cfg.versionfile_source)<EOL>get_keywords_f = handlers.get("<STR_LIT>")<EOL>from_keywords_f = handlers.get("<STR_LIT>")<EOL>if get_keywords_f and from_keywords_f:<EOL><INDENT>try:<EOL><INDENT>keywords = get_keywords_f(versionfile_abs)<EOL>ver = from_keywords_f(keywords, cfg.tag_prefix, verbose)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % ver)<EOL><DEDENT>return ver<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>try:<EOL><INDENT>ver = versions_from_file(versionfile_abs)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % (versionfile_abs, ver))<EOL><DEDENT>return ver<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>from_vcs_f = handlers.get("<STR_LIT>")<EOL>if from_vcs_f:<EOL><INDENT>try:<EOL><INDENT>pieces = from_vcs_f(cfg.tag_prefix, root, verbose)<EOL>ver = render(pieces, cfg.style)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % ver)<EOL><DEDENT>return ver<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>try:<EOL><INDENT>if cfg.parentdir_prefix:<EOL><INDENT>ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % ver)<EOL><DEDENT>return ver<EOL><DEDENT><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None, "<STR_LIT:error>": "<STR_LIT>",<EOL>"<STR_LIT:date>": None}<EOL>
Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'.
f443:m19
def get_version():
return get_versions()["<STR_LIT:version>"]<EOL>
Get the short version string for this project.
f443:m20
def get_cmdclass():
if "<STR_LIT>" in sys.modules:<EOL><INDENT>del sys.modules["<STR_LIT>"]<EOL><DEDENT>cmds = {}<EOL>from distutils.core import Command<EOL>class cmd_version(Command):<EOL><INDENT>description = "<STR_LIT>"<EOL>user_options = []<EOL>boolean_options = []<EOL>def initialize_options(self):<EOL><INDENT>pass<EOL><DEDENT>def finalize_options(self):<EOL><INDENT>pass<EOL><DEDENT>def run(self):<EOL><INDENT>vers = get_versions(verbose=True)<EOL>print("<STR_LIT>" % vers["<STR_LIT:version>"])<EOL>print("<STR_LIT>" % vers.get("<STR_LIT>"))<EOL>print("<STR_LIT>" % vers.get("<STR_LIT>"))<EOL>print("<STR_LIT>" % vers.get("<STR_LIT:date>"))<EOL>if vers["<STR_LIT:error>"]:<EOL><INDENT>print("<STR_LIT>" % vers["<STR_LIT:error>"])<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT:version>"] = cmd_version<EOL>if "<STR_LIT>" in sys.modules:<EOL><INDENT>from setuptools.command.build_py import build_py as _build_py<EOL><DEDENT>else:<EOL><INDENT>from distutils.command.build_py import build_py as _build_py<EOL><DEDENT>class cmd_build_py(_build_py):<EOL><INDENT>def run(self):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>versions = get_versions()<EOL>_build_py.run(self)<EOL>if cfg.versionfile_build:<EOL><INDENT>target_versionfile = os.path.join(self.build_lib,<EOL>cfg.versionfile_build)<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile, versions)<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_build_py<EOL>if "<STR_LIT>" in sys.modules: <EOL><INDENT>from cx_Freeze.dist import build_exe as _build_exe<EOL>class cmd_build_exe(_build_exe):<EOL><INDENT>def run(self):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>versions = get_versions()<EOL>target_versionfile = cfg.versionfile_source<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile, versions)<EOL>_build_exe.run(self)<EOL>os.unlink(target_versionfile)<EOL>with open(cfg.versionfile_source, "<STR_LIT:w>") as f:<EOL><INDENT>LONG = LONG_VERSION_PY[cfg.VCS]<EOL>f.write(LONG %<EOL>{"<STR_LIT>": "<STR_LIT:$>",<EOL>"<STR_LIT>": cfg.style,<EOL>"<STR_LIT>": cfg.tag_prefix,<EOL>"<STR_LIT>": cfg.parentdir_prefix,<EOL>"<STR_LIT>": cfg.versionfile_source,<EOL>})<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_build_exe<EOL>del cmds["<STR_LIT>"]<EOL><DEDENT>if '<STR_LIT>' in sys.modules: <EOL><INDENT>try:<EOL><INDENT>from py2exe.distutils_buildexe import py2exe as _py2exe <EOL><DEDENT>except ImportError:<EOL><INDENT>from py2exe.build_exe import py2exe as _py2exe <EOL><DEDENT>class cmd_py2exe(_py2exe):<EOL><INDENT>def run(self):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>versions = get_versions()<EOL>target_versionfile = cfg.versionfile_source<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile, versions)<EOL>_py2exe.run(self)<EOL>os.unlink(target_versionfile)<EOL>with open(cfg.versionfile_source, "<STR_LIT:w>") as f:<EOL><INDENT>LONG = LONG_VERSION_PY[cfg.VCS]<EOL>f.write(LONG %<EOL>{"<STR_LIT>": "<STR_LIT:$>",<EOL>"<STR_LIT>": cfg.style,<EOL>"<STR_LIT>": cfg.tag_prefix,<EOL>"<STR_LIT>": cfg.parentdir_prefix,<EOL>"<STR_LIT>": cfg.versionfile_source,<EOL>})<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_py2exe<EOL><DEDENT>if "<STR_LIT>" in sys.modules:<EOL><INDENT>from setuptools.command.sdist import sdist as _sdist<EOL><DEDENT>else:<EOL><INDENT>from distutils.command.sdist import sdist as _sdist<EOL><DEDENT>class cmd_sdist(_sdist):<EOL><INDENT>def run(self):<EOL><INDENT>versions = get_versions()<EOL>self._versioneer_generated_versions = versions<EOL>self.distribution.metadata.version = versions["<STR_LIT:version>"]<EOL>return _sdist.run(self)<EOL><DEDENT>def make_release_tree(self, base_dir, files):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>_sdist.make_release_tree(self, base_dir, files)<EOL>target_versionfile = os.path.join(base_dir, cfg.versionfile_source)<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile,<EOL>self._versioneer_generated_versions)<EOL><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_sdist<EOL>return cmds<EOL>
Get the custom setuptools/distutils subclasses used by Versioneer.
f443:m21
def do_setup():
root = get_root()<EOL>try:<EOL><INDENT>cfg = get_config_from_root(root)<EOL><DEDENT>except (EnvironmentError, configparser.NoSectionError,<EOL>configparser.NoOptionError) as e:<EOL><INDENT>if isinstance(e, (EnvironmentError, configparser.NoSectionError)):<EOL><INDENT>print("<STR_LIT>",<EOL>file=sys.stderr)<EOL>with open(os.path.join(root, "<STR_LIT>"), "<STR_LIT:a>") as f:<EOL><INDENT>f.write(SAMPLE_CONFIG)<EOL><DEDENT><DEDENT>print(CONFIG_ERROR, file=sys.stderr)<EOL>return <NUM_LIT:1><EOL><DEDENT>print("<STR_LIT>" % cfg.versionfile_source)<EOL>with open(cfg.versionfile_source, "<STR_LIT:w>") as f:<EOL><INDENT>LONG = LONG_VERSION_PY[cfg.VCS]<EOL>f.write(LONG % {"<STR_LIT>": "<STR_LIT:$>",<EOL>"<STR_LIT>": cfg.style,<EOL>"<STR_LIT>": cfg.tag_prefix,<EOL>"<STR_LIT>": cfg.parentdir_prefix,<EOL>"<STR_LIT>": cfg.versionfile_source,<EOL>})<EOL><DEDENT>ipy = os.path.join(os.path.dirname(cfg.versionfile_source),<EOL>"<STR_LIT>")<EOL>if os.path.exists(ipy):<EOL><INDENT>try:<EOL><INDENT>with open(ipy, "<STR_LIT:r>") as f:<EOL><INDENT>old = f.read()<EOL><DEDENT><DEDENT>except EnvironmentError:<EOL><INDENT>old = "<STR_LIT>"<EOL><DEDENT>if INIT_PY_SNIPPET not in old:<EOL><INDENT>print("<STR_LIT>" % ipy)<EOL>with open(ipy, "<STR_LIT:a>") as f:<EOL><INDENT>f.write(INIT_PY_SNIPPET)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % ipy)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % ipy)<EOL>ipy = None<EOL><DEDENT>manifest_in = os.path.join(root, "<STR_LIT>")<EOL>simple_includes = set()<EOL>try:<EOL><INDENT>with open(manifest_in, "<STR_LIT:r>") as f:<EOL><INDENT>for line in f:<EOL><INDENT>if line.startswith("<STR_LIT>"):<EOL><INDENT>for include in line.split()[<NUM_LIT:1>:]:<EOL><INDENT>simple_includes.add(include)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>if "<STR_LIT>" not in simple_includes:<EOL><INDENT>print("<STR_LIT>")<EOL>with open(manifest_in, "<STR_LIT:a>") as f:<EOL><INDENT>f.write("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>if cfg.versionfile_source not in simple_includes:<EOL><INDENT>print("<STR_LIT>" %<EOL>cfg.versionfile_source)<EOL>with open(manifest_in, "<STR_LIT:a>") as f:<EOL><INDENT>f.write("<STR_LIT>" % cfg.versionfile_source)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>do_vcs_install(manifest_in, cfg.versionfile_source, ipy)<EOL>return <NUM_LIT:0><EOL>
Main VCS-independent setup function for installing Versioneer.
f443:m22
def scan_setup_py():
found = set()<EOL>setters = False<EOL>errors = <NUM_LIT:0><EOL>with open("<STR_LIT>", "<STR_LIT:r>") as f:<EOL><INDENT>for line in f.readlines():<EOL><INDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>setters = True<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>setters = True<EOL><DEDENT><DEDENT><DEDENT>if len(found) != <NUM_LIT:3>:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>errors += <NUM_LIT:1><EOL><DEDENT>if setters:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>errors += <NUM_LIT:1><EOL><DEDENT>return errors<EOL>
Validate the contents of setup.py against Versioneer's expectations.
f443:m23
def parse_line(line):
if not line.startswith(b'<STR_LIT>'):<EOL><INDENT>raise exc.InvalidLine('<STR_LIT>', line)<EOL><DEDENT>if not line.endswith(CRLF):<EOL><INDENT>raise exc.InvalidLine('<STR_LIT>', line)<EOL><DEDENT>parts = line[:-len(CRLF)].split(b'<STR_LIT:U+0020>')<EOL>if len(parts) != <NUM_LIT:6>:<EOL><INDENT>raise exc.InvalidLine('<STR_LIT>', line)<EOL><DEDENT>inet, src_addr, dst_addr = parts[<NUM_LIT:1>:<NUM_LIT:4>]<EOL>if inet == b'<STR_LIT>':<EOL><INDENT>try:<EOL><INDENT>socket.inet_pton(socket.AF_INET, src_addr)<EOL>socket.inet_pton(socket.AF_INET, dst_addr)<EOL><DEDENT>except socket.error:<EOL><INDENT>raise exc.InvalidLine('<STR_LIT>'.format(inet), line)<EOL><DEDENT><DEDENT>elif inet == b'<STR_LIT>':<EOL><INDENT>try:<EOL><INDENT>socket.inet_pton(socket.AF_INET6, src_addr)<EOL>socket.inet_pton(socket.AF_INET6, dst_addr)<EOL><DEDENT>except socket.error:<EOL><INDENT>raise exc.InvalidLine('<STR_LIT>'.format(inet), line)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise exc.InvalidLine('<STR_LIT>'.format(inet), line)<EOL><DEDENT>try:<EOL><INDENT>src_port = int(parts[<NUM_LIT:4>])<EOL>dst_port = int(parts[<NUM_LIT:5>])<EOL><DEDENT>except (TypeError, ValueError):<EOL><INDENT>raise exc.InvalidLine(line, '<STR_LIT>')<EOL><DEDENT>return ProxyInfo(<EOL>source_address=src_addr,<EOL>source_port=src_port,<EOL>destination_address=dst_addr,<EOL>destination_port=dst_port,<EOL>)<EOL>
Parses a byte string like: PROXY TCP4 192.168.0.1 192.168.0.11 56324 443\r\n to a `ProxyInfo`.
f445:m1
def proxy_authenticate(self, info):
return (info.destination_address, info.destination_port) == self.client_address<EOL>
Authentication hook for parsed proxy information. Defaults to ensuring destination (i.e. proxy) is the peer. :param info: Parsed ``ProxyInfo`` instance. :returns: ``True`` if authenticated, otherwise ``False``.
f445:c0:m0
def proxy_protocol(self, error='<STR_LIT>', default=None, limit=None, authenticate=False):
if error not in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if not isinstance(self.request, SocketBuffer):<EOL><INDENT>self.request = SocketBuffer(self.request)<EOL><DEDENT>if default == '<STR_LIT>':<EOL><INDENT>default = ProxyInfo(<EOL>self.client_address[<NUM_LIT:0>], self.client_address[<NUM_LIT:1>],<EOL>self.client_address[<NUM_LIT:0>], self.client_address[<NUM_LIT:1>],<EOL>)<EOL><DEDENT>try:<EOL><INDENT>line = read_line(<EOL>self.request.sock,<EOL>self.request.buf,<EOL>limit=limit,<EOL>)<EOL><DEDENT>except exc.ReadError:<EOL><INDENT>if error == '<STR_LIT>':<EOL><INDENT>raise<EOL><DEDENT>return default<EOL><DEDENT>try:<EOL><INDENT>info = parse_line(line)<EOL><DEDENT>except exc.ParseError:<EOL><INDENT>if error == '<STR_LIT>':<EOL><INDENT>raise<EOL><DEDENT>self.request.unread(line)<EOL>return default<EOL><DEDENT>if authenticate and not self.proxy_authenticate(info):<EOL><INDENT>logger.info('<STR_LIT>', info)<EOL>return default<EOL><DEDENT>return info<EOL>
Parses, and optionally authenticates, proxy protocol information from request. Note that ``self.request`` is wrapped by ``SocketBuffer``. :param error: How read (``exc.ReadError``) and parse (``exc.ParseError``) errors are handled. One of: - "raise" to propagate. - "unread" to suppress exceptions and unread back to socket. :param default: What to return when no ``ProxyInfo`` was found. Only meaningful with error "unread". :param limit: Maximum number of bytes to read when probing request for ``ProxyInfo``. :returns: Parsed ``ProxyInfo`` instance or **default** if none found.
f445:c0:m1
def touch_model(self, model, **data):
instance, created = model.objects.get_or_create(**data)<EOL>if not created:<EOL><INDENT>if instance.updated < self.import_start_datetime:<EOL><INDENT>instance.save() <EOL><DEDENT><DEDENT>return (instance, created)<EOL>
This method create or look up a model with the given data it saves the given model if it exists, updating its updated field
f448:c0:m2
@transaction.atomic<EOL><INDENT>def manage_mep(self, mep_json):<DEDENT>
<EOL>responses = representative_pre_import.send(sender=self,<EOL>representative_data=mep_json)<EOL>for receiver, response in responses:<EOL><INDENT>if response is False:<EOL><INDENT>logger.debug(<EOL>'<STR_LIT>', mep_json['<STR_LIT:Name>']['<STR_LIT>'])<EOL>return<EOL><DEDENT><DEDENT>changed = False<EOL>slug = slugify('<STR_LIT>' % (<EOL>mep_json["<STR_LIT:Name>"]["<STR_LIT>"] if '<STR_LIT>' in mep_json["<STR_LIT:Name>"]<EOL>else mep_json["<STR_LIT:Name>"]["<STR_LIT>"] + "<STR_LIT:U+0020>" + mep_json["<STR_LIT:Name>"]["<STR_LIT>"],<EOL>_parse_date(mep_json["<STR_LIT>"]["<STR_LIT:date>"])<EOL>))<EOL>try:<EOL><INDENT>representative = Representative.objects.get(slug=slug)<EOL><DEDENT>except Representative.DoesNotExist:<EOL><INDENT>representative = Representative(slug=slug)<EOL>changed = True<EOL><DEDENT>self.import_representative_details(representative, mep_json, changed)<EOL>self.add_mandates(representative, mep_json)<EOL>self.add_contacts(representative, mep_json)<EOL>logger.debug('<STR_LIT>', unicode(representative))<EOL>return representative<EOL>
Import a mep as a representative from the json dict fetched from parltrack
f448:c1:m2
def _get_path(dict_, path):
cur = dict_<EOL>for part in path.split('<STR_LIT:/>'):<EOL><INDENT>cur = cur[part]<EOL><DEDENT>return cur<EOL>
Get value at specific path in dictionary. Path is specified by slash- separated string, eg _get_path(foo, 'bar/baz') returns foo['bar']['baz']
f451:m3
def ensure_chambers():
france = Country.objects.get(name="<STR_LIT>")<EOL>for key in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>variant = FranceDataVariants[key]<EOL>Chamber.objects.get_or_create(name=variant['<STR_LIT>'],<EOL>abbreviation=variant['<STR_LIT>'],<EOL>country=france)<EOL><DEDENT>
Ensures chambers are created
f451:m4
def touch_model(self, model, **data):
instance, created = model.objects.get_or_create(**data)<EOL>if not created:<EOL><INDENT>if instance.updated < self.import_start_datetime:<EOL><INDENT>instance.save() <EOL><DEDENT><DEDENT>return (instance, created)<EOL>
This method create or look up a model with the given data it saves the given model if it exists, updating its updated field
f451:c0:m1
@transaction.atomic<EOL><INDENT>def manage_rep(self, rep_json):<DEDENT>
<EOL>responses = representative_pre_import.send(sender=self,<EOL>representative_data=rep_json)<EOL>for receiver, response in responses:<EOL><INDENT>if response is False:<EOL><INDENT>logger.debug(<EOL>'<STR_LIT>', rep_json['<STR_LIT>'])<EOL>return<EOL><DEDENT><DEDENT>changed = False<EOL>slug = slugify('<STR_LIT>' % (<EOL>rep_json['<STR_LIT>'] if '<STR_LIT>' in rep_json<EOL>else rep_json['<STR_LIT>'] + "<STR_LIT:U+0020>" + rep_json['<STR_LIT>'],<EOL>_parse_date(rep_json["<STR_LIT>"])<EOL>))<EOL>try:<EOL><INDENT>representative = Representative.objects.get(slug=slug)<EOL><DEDENT>except Representative.DoesNotExist:<EOL><INDENT>representative = Representative(slug=slug)<EOL>changed = True<EOL><DEDENT>if rep_json['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>rep_json['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>self.import_representative_details(representative, rep_json, changed)<EOL>self.add_mandates(representative, rep_json)<EOL>self.add_contacts(representative, rep_json)<EOL>logger.debug('<STR_LIT>', unicode(representative))<EOL>return representative<EOL>
Import a rep as a representative from the json dict fetched from FranceData (which comes from nosdeputes.fr)
f451:c1:m2
def add_mandates(self, representative, rep_json):
<EOL>if rep_json.get('<STR_LIT>'):<EOL><INDENT>constituency, _ = Constituency.objects.get_or_create(<EOL>name=rep_json.get('<STR_LIT>'), country=self.france)<EOL>group, _ = self.touch_model(model=Group,<EOL>abbreviation=self.france.code,<EOL>kind='<STR_LIT>',<EOL>name=self.france.name)<EOL>_create_mandate(representative, group, constituency, '<STR_LIT>')<EOL><DEDENT>for mdef in self.variant['<STR_LIT>']:<EOL><INDENT>if mdef.get('<STR_LIT>', False):<EOL><INDENT>chamber = self.chamber<EOL><DEDENT>else:<EOL><INDENT>chamber = None<EOL><DEDENT>if '<STR_LIT>' in mdef:<EOL><INDENT>elems = mdef['<STR_LIT>'](rep_json)<EOL><DEDENT>else:<EOL><INDENT>elems = [rep_json]<EOL><DEDENT>for elem in elems:<EOL><INDENT>name = _get_mdef_item(mdef, '<STR_LIT:name>', elem, '<STR_LIT>')<EOL>abbr = _get_mdef_item(mdef, '<STR_LIT>', elem, '<STR_LIT>')<EOL>group, _ = self.touch_model(model=Group,<EOL>abbreviation=abbr,<EOL>kind=mdef['<STR_LIT>'],<EOL>chamber=chamber,<EOL>name=name)<EOL>role = _get_mdef_item(mdef, '<STR_LIT>', elem, '<STR_LIT>')<EOL>start = _get_mdef_item(mdef, '<STR_LIT:start>', elem, None)<EOL>if start is not None:<EOL><INDENT>start = _parse_date(start)<EOL><DEDENT>end = _get_mdef_item(mdef, '<STR_LIT:end>', elem, None)<EOL>if end is not None:<EOL><INDENT>end = _parse_date(end)<EOL><DEDENT>_create_mandate(representative, group, self.ch_constituency,<EOL>role, start, end)<EOL>logger.debug(<EOL>'<STR_LIT>' % (rep_json['<STR_LIT>'],<EOL>mdef['<STR_LIT>'], role, name, abbr, start, end))<EOL><DEDENT><DEDENT>
Create mandates from rep data based on variant configuration
f451:c1:m4
def update_slugs(apps, schema_editor):
<EOL>Representative = apps.get_model("<STR_LIT>", "<STR_LIT>")<EOL>for rep in Representative.objects.all():<EOL><INDENT>rep.slug = '<STR_LIT>' % (rep.slug, rep.birth_date)<EOL>rep.save()<EOL><DEDENT>
Include birthdate in slugs
f462:m0
def create_parl_websites(apps, schema_editor):
<EOL>Representative = apps.get_model("<STR_LIT>", "<STR_LIT>")<EOL>WebSite = apps.get_model("<STR_LIT>", "<STR_LIT>")<EOL>today = datetime.date.today()<EOL>ep_url = '<STR_LIT>'<EOL>qs = Representative.objects.filter(<EOL>models.Q(mandates__end_date__gte=today) |<EOL>models.Q(mandates__end_date__isnull=True),<EOL>mandates__group__chamber__abbreviation='<STR_LIT>'<EOL>)<EOL>for rep in qs:<EOL><INDENT>changed = False<EOL>url = ep_url % rep.remote_id<EOL>try:<EOL><INDENT>site = WebSite.objects.get(representative=rep, kind='<STR_LIT>')<EOL><DEDENT>except WebSite.DoesNotExist:<EOL><INDENT>site = WebSite(representative=rep, kind='<STR_LIT>', url=url)<EOL>changed = True<EOL><DEDENT>if site.url != url:<EOL><INDENT>site.url = url<EOL>changed = True<EOL><DEDENT>if changed:<EOL><INDENT>site.save()<EOL><DEDENT><DEDENT>for chamber in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>qs = Representative.objects.filter(<EOL>models.Q(mandates__end_date__gte=today) |<EOL>models.Q(mandates__end_date__isnull=True),<EOL>mandates__group__chamber__abbreviation=chamber<EOL>)<EOL>for rep in qs:<EOL><INDENT>changed = False<EOL>url = rep.remote_id<EOL>try:<EOL><INDENT>site = WebSite.objects.get(representative=rep, kind=chamber)<EOL><DEDENT>except WebSite.DoesNotExist:<EOL><INDENT>site = WebSite(representative=rep, kind=chamber, url=url)<EOL>changed = True<EOL><DEDENT>if site.url != url:<EOL><INDENT>site.url = url<EOL>changed = True<EOL><DEDENT>if changed:<EOL><INDENT>site.save()<EOL><DEDENT><DEDENT><DEDENT>
Prepare for remote_id removal by creating WebSite entities from it.
f462:m1
def migrate_constituencies(apps, schema_editor):
Constituency = apps.get_model("<STR_LIT>", "<STR_LIT>")<EOL>for c in Constituency.objects.all():<EOL><INDENT>c.save()<EOL><DEDENT>
Re-save constituencies to recompute fingerprints
f465:m0
def update_kinds(apps, schema_editor):
<EOL>Group = apps.get_model("<STR_LIT>", "<STR_LIT>")<EOL>qs = Group.objects.filter(<EOL>models.Q(name__iregex=r'<STR_LIT>') |<EOL>models.Q(name__iregex=r'<STR_LIT>')<EOL>)<EOL>for g in qs:<EOL><INDENT>g.kind = '<STR_LIT>'<EOL>g.save()<EOL><DEDENT>
Downgrade FR special committees to delegations
f466:m0
def update_abbreviations(apps, schema_editor):
<EOL>Group = apps.get_model("<STR_LIT>", "<STR_LIT>")<EOL>amap = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>}<EOL>for old, new in amap.items():<EOL><INDENT>for g in Group.objects.filter(abbreviation=old):<EOL><INDENT>g.abbreviation = new<EOL>g.save()<EOL><DEDENT><DEDENT>
Migrate to new FR committee abbreviations
f466:m1
def unload_fixture(apps, schema_editor):
MyModel = apps.get_model("<STR_LIT>", "<STR_LIT>")<EOL>MyModel.objects.all().delete()<EOL>
Brutally deleting all entries for this model...
f474:m1
def calculate_hash(obj):
hashable_fields = {<EOL>'<STR_LIT>': ['<STR_LIT:name>', '<STR_LIT>', '<STR_LIT>'],<EOL>'<STR_LIT>': ['<STR_LIT:name>'],<EOL>'<STR_LIT>': ['<STR_LIT:name>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'],<EOL>'<STR_LIT>': ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>']<EOL>}<EOL>fingerprint = hashlib.sha1()<EOL>for field_name in hashable_fields[obj.__class__.__name__]:<EOL><INDENT>field = obj._meta.get_field(field_name)<EOL>if field.is_relation:<EOL><INDENT>related = getattr(obj, field_name)<EOL>if related is None:<EOL><INDENT>fingerprint.update(smart_str(related))<EOL><DEDENT>else:<EOL><INDENT>fingerprint.update(related.fingerprint)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>fingerprint.update(smart_str(getattr(obj, field_name)))<EOL><DEDENT><DEDENT>obj.fingerprint = fingerprint.hexdigest()<EOL>return obj.fingerprint<EOL>
Computes fingerprint for an object, this code is duplicated from representatives.models.HashableModel because we don't have access to model methods in a migration scenario.
f477:m0
def get_or_create(cls, **kwargs):
try:<EOL><INDENT>obj = cls.objects.get(**kwargs)<EOL>created = False<EOL><DEDENT>except cls.DoesNotExist:<EOL><INDENT>obj = cls(**kwargs)<EOL>created = True<EOL>calculate_hash(obj)<EOL>obj.save()<EOL><DEDENT>return (obj, created)<EOL>
Implements get_or_create logic for models that inherit from representatives.models.HashableModel because we don't have access to model methods in a migration scenario.
f477:m1
def request(identifier, namespace='<STR_LIT>', domain='<STR_LIT>', operation=None, output='<STR_LIT>', searchtype=None, **kwargs):
if not identifier:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if isinstance(identifier, int):<EOL><INDENT>identifier = str(identifier)<EOL><DEDENT>if not isinstance(identifier, text_types):<EOL><INDENT>identifier = '<STR_LIT:U+002C>'.join(str(x) for x in identifier)<EOL><DEDENT>kwargs = dict((k, v) for k, v in kwargs.items() if v is not None)<EOL>urlid, postdata = None, None<EOL>if namespace == '<STR_LIT>':<EOL><INDENT>identifier = identifier.replace('<STR_LIT:/>', '<STR_LIT:.>')<EOL><DEDENT>if namespace in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']or searchtype == '<STR_LIT>'or (searchtype and namespace == '<STR_LIT>') or domain == '<STR_LIT>':<EOL><INDENT>urlid = quote(identifier.encode('<STR_LIT:utf8>'))<EOL><DEDENT>else:<EOL><INDENT>postdata = urlencode([(namespace, identifier)]).encode('<STR_LIT:utf8>')<EOL><DEDENT>comps = filter(None, [API_BASE, domain, searchtype, namespace, urlid, operation, output])<EOL>apiurl = '<STR_LIT:/>'.join(comps)<EOL>if kwargs:<EOL><INDENT>apiurl += '<STR_LIT>' % urlencode(kwargs)<EOL><DEDENT>try:<EOL><INDENT>log.debug('<STR_LIT>', apiurl)<EOL>log.debug('<STR_LIT>', postdata)<EOL>response = urlopen(apiurl, postdata)<EOL>return response<EOL><DEDENT>except HTTPError as e:<EOL><INDENT>raise PubChemHTTPError(e)<EOL><DEDENT>
Construct API request from parameters and return the response. Full specification at http://pubchem.ncbi.nlm.nih.gov/pug_rest/PUG_REST.html
f498:m0
def get(identifier, namespace='<STR_LIT>', domain='<STR_LIT>', operation=None, output='<STR_LIT>', searchtype=None, **kwargs):
if (searchtype and searchtype != '<STR_LIT>') or namespace in ['<STR_LIT>']:<EOL><INDENT>response = request(identifier, namespace, domain, None, '<STR_LIT>', searchtype, **kwargs).read()<EOL>status = json.loads(response.decode())<EOL>if '<STR_LIT>' in status and '<STR_LIT>' in status['<STR_LIT>']:<EOL><INDENT>identifier = status['<STR_LIT>']['<STR_LIT>']<EOL>namespace = '<STR_LIT>'<EOL>while '<STR_LIT>' in status and '<STR_LIT>' in status['<STR_LIT>']:<EOL><INDENT>time.sleep(<NUM_LIT:2>)<EOL>response = request(identifier, namespace, domain, operation, '<STR_LIT>', **kwargs).read()<EOL>status = json.loads(response.decode())<EOL><DEDENT>if not output == '<STR_LIT>':<EOL><INDENT>response = request(identifier, namespace, domain, operation, output, searchtype, **kwargs).read()<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>response = request(identifier, namespace, domain, operation, output, searchtype, **kwargs).read()<EOL><DEDENT>return response<EOL>
Request wrapper that automatically handles async requests.
f498:m1
def get_json(identifier, namespace='<STR_LIT>', domain='<STR_LIT>', operation=None, searchtype=None, **kwargs):
try:<EOL><INDENT>return json.loads(get(identifier, namespace, domain, operation, '<STR_LIT>', searchtype, **kwargs).decode())<EOL><DEDENT>except NotFoundError as e:<EOL><INDENT>log.info(e)<EOL>return None<EOL><DEDENT>
Request wrapper that automatically parses JSON response and supresses NotFoundError.
f498:m2
def get_sdf(identifier, namespace='<STR_LIT>', domain='<STR_LIT>',operation=None, searchtype=None, **kwargs):
try:<EOL><INDENT>return get(identifier, namespace, domain, operation, '<STR_LIT>', searchtype, **kwargs).decode()<EOL><DEDENT>except NotFoundError as e:<EOL><INDENT>log.info(e)<EOL>return None<EOL><DEDENT>
Request wrapper that automatically parses SDF response and supresses NotFoundError.
f498:m3
def get_compounds(identifier, namespace='<STR_LIT>', searchtype=None, as_dataframe=False, **kwargs):
results = get_json(identifier, namespace, searchtype=searchtype, **kwargs)<EOL>compounds = [Compound(r) for r in results['<STR_LIT>']] if results else []<EOL>if as_dataframe:<EOL><INDENT>return compounds_to_frame(compounds)<EOL><DEDENT>return compounds<EOL>
Retrieve the specified compound records from PubChem. :param identifier: The compound identifier to use as a search query. :param namespace: (optional) The identifier type, one of cid, name, smiles, sdf, inchi, inchikey or formula. :param searchtype: (optional) The advanced search type, one of substructure, superstructure or similarity. :param as_dataframe: (optional) Automatically extract the :class:`~pubchempy.Compound` properties into a pandas :class:`~pandas.DataFrame` and return that.
f498:m4