<EOL>segments = <NUM_LIT:50><EOL>star_points = <NUM_LIT:5><EOL>star_radius = <NUM_LIT:2><EOL>ring_thickness = <NUM_LIT:1><EOL>sphere_radius = <NUM_LIT:2> * (star_radius + <NUM_LIT:3> * ring_thickness)<EOL>polygon_radius = star_radius /(<NUM_LIT:1> + math.tan(math.radians(<NUM_LIT> / star_points)) /<EOL>math.tan(math.radians(<NUM_LIT> / star_points)))<EOL>width = polygon_radius * math.tan(math.radians(<NUM_LIT> / star_points))<EOL>height = width / math.tan(math.radians(<NUM_LIT> / star_points))<EOL>shield = mlx.FilterScript(file_out="<STR_LIT>")<EOL>mlx.create.annulus(shield, radius=star_radius, cir_segments=segments, color='<STR_LIT>')<EOL>mlx.create.annulus(shield,<EOL>radius1=star_radius + ring_thickness,<EOL>radius2=star_radius,<EOL>cir_segments=segments,<EOL>color='<STR_LIT>')<EOL>mlx.create.annulus(shield,<EOL>radius1=star_radius + <NUM_LIT:2> * ring_thickness,<EOL>radius2=star_radius + ring_thickness,<EOL>cir_segments=segments,<EOL>color='<STR_LIT>')<EOL>mlx.create.annulus(shield,<EOL>radius1=star_radius + <NUM_LIT:3> * ring_thickness,<EOL>radius2=star_radius + <NUM_LIT:2> * ring_thickness,<EOL>cir_segments=segments,<EOL>color='<STR_LIT>')<EOL>mlx.layers.join(shield)<EOL>mlx.subdivide.midpoint(shield, iterations=<NUM_LIT:2>)<EOL>mlx.create.annulus(shield,<EOL>radius1=star_radius + <NUM_LIT:3> * ring_thickness,<EOL>cir_segments=segments,<EOL>color='<STR_LIT>')<EOL>mlx.transform.rotate(shield, axis='<STR_LIT:y>', angle=<NUM_LIT>)<EOL>mlx.transform.translate(shield, value=[<NUM_LIT:0>, <NUM_LIT:0>, -<NUM_LIT>])<EOL>mlx.subdivide.midpoint(shield, iterations=<NUM_LIT:4>)<EOL>mlx.create.grid(shield,<EOL>size=math.sqrt(<NUM_LIT:2>),<EOL>x_segments=<NUM_LIT:10>,<EOL>y_segments=<NUM_LIT:10>,<EOL>center=True,<EOL>color='<STR_LIT>')<EOL>mlx.transform.rotate(shield, axis='<STR_LIT:z>', angle=<NUM_LIT>)<EOL>mlx.transform.scale(shield, value=[width, height, <NUM_LIT:1>])<EOL>mlx.transform.translate(shield, value=[<NUM_LIT:0>, polygon_radius, <NUM_LIT>])<EOL>for _ in range(<NUM_LIT:1>, star_points):<EOL><INDENT>mlx.layers.duplicate(shield)<EOL>mlx.transform.rotate(shield, axis='<STR_LIT:z>', angle=<NUM_LIT> / star_points)<EOL><DEDENT>mlx.layers.join(shield)<EOL>mlx.transform.vert_function(shield,<EOL>z_func='<STR_LIT>' %<EOL>(sphere_radius**<NUM_LIT:2>, sphere_radius))<EOL>shield.run_script()<EOL>return None<EOL>


start_time = time.time()<EOL>os.chdir(THIS_SCRIPTPATH)<EOL>ml_version = '<STR_LIT>'<EOL>meshlabserver_path = '<STR_LIT>'<EOL>"""<STR_LIT>"""<EOL>os.environ['<STR_LIT>'] = meshlabserver_path + os.pathsep + os.environ['<STR_LIT>']<EOL>length = math.radians(<NUM_LIT>)<EOL>tube_size = [<NUM_LIT:10>, <NUM_LIT:10>, length]<EOL>segments = [<NUM_LIT:64>, <NUM_LIT:64>, <NUM_LIT>*<NUM_LIT:2>]<EOL>inner_radius = <NUM_LIT><EOL>amplitude = <NUM_LIT><EOL>freq = <NUM_LIT:4><EOL>phase = <NUM_LIT><EOL>center = '<STR_LIT:r>'<EOL>start_pt = <NUM_LIT:0><EOL>increment = '<STR_LIT>'.format(start_pt)<EOL>c_start_pt = <NUM_LIT:0><EOL>c_freq = <NUM_LIT:5><EOL>c_phase_shift = <NUM_LIT:0> <EOL>c_phase = (<NUM_LIT:0> + c_phase_shift, <NUM_LIT> + c_phase_shift, <NUM_LIT> + c_phase_shift, <NUM_LIT:0>)<EOL>holes = [<NUM_LIT:2>, <NUM_LIT:2>, <NUM_LIT>] <EOL>web_thickness = <NUM_LIT:0.5><EOL>solid_radius = <NUM_LIT> <EOL>faces_surface = <NUM_LIT><EOL>voxel = <NUM_LIT:0.5><EOL>thickness = <NUM_LIT><EOL>faces_solid = <NUM_LIT><EOL>size = <NUM_LIT> <EOL>curve_max_size = <NUM_LIT:2>*(<NUM_LIT:1> + <NUM_LIT>) <EOL>scale = (size-<NUM_LIT:2>*(thickness + amplitude) - tube_size[<NUM_LIT:1>])/curve_max_size<EOL>file_color = '<STR_LIT>'<EOL>file_voronoi_surf = '<STR_LIT>'<EOL>file_voronoi_solid = '<STR_LIT>'<EOL>file_voronoi_color = '<STR_LIT>'<EOL>quatrefoil_color = mlx.FilterScript(<EOL>file_in=None, file_out=file_color, ml_version=ml_version)<EOL>quatrefoil_voronoi_surf = mlx.FilterScript(<EOL>file_in=file_color, file_out=file_voronoi_surf, ml_version=ml_version)<EOL>quatrefoil_voronoi_solid = mlx.FilterScript(<EOL>file_in=file_voronoi_surf, file_out=file_voronoi_solid,<EOL>ml_version=ml_version)<EOL>quatrefoil_voronoi_color = mlx.FilterScript(<EOL>file_in=[file_color, file_voronoi_solid], file_out=file_voronoi_color,<EOL>ml_version=ml_version)<EOL>print('<STR_LIT>')<EOL>mlx.create.cube_open_hires(<EOL>quatrefoil_color, size=tube_size, x_segments=segments[<NUM_LIT:0>],<EOL>y_segments=segments[<NUM_LIT:1>], z_segments=segments[<NUM_LIT:2>], center=True)<EOL>mlx.transform.translate(quatrefoil_color, [<NUM_LIT:0>, <NUM_LIT:0>, length/<NUM_LIT:2>])<EOL>r_func = '<STR_LIT>'.format(<EOL>f=freq, i=increment, p=math.radians(phase), a=amplitude, c=center)<EOL>mlx.transform.function_cyl_co(<EOL>quatrefoil_color, r_func=r_func, theta_func='<STR_LIT>', z_func='<STR_LIT:z>')<EOL>max_radius = math.sqrt((tube_size[<NUM_LIT:0>]/<NUM_LIT:2>)**<NUM_LIT:2>+(tube_size[<NUM_LIT:1>]/<NUM_LIT:2>)**<NUM_LIT:2>) <EOL>q_func = '<STR_LIT>'.format(<EOL>f=freq, i=increment, p=math.radians(phase), a=amplitude, c=max_radius)<EOL>mlx.mp_func.vq_function(quatrefoil_color, function=q_func)<EOL>mlx.vert_color.cyclic_rainbow(<EOL>quatrefoil_color, direction='<STR_LIT:z>', start_pt=c_start_pt, amplitude=<NUM_LIT:255> / <NUM_LIT:2>,<EOL>center=<NUM_LIT:255> / <NUM_LIT:2>, freq=c_freq, phase=c_phase)<EOL>quatrefoil_func = mlx.transform.deform2curve(<EOL>quatrefoil_color,<EOL>curve=mlx.mp_func.torus_knot('<STR_LIT:t>', p=<NUM_LIT:3>, q=<NUM_LIT:4>, scale=scale,<EOL>radius=inner_radius))<EOL>mlx.clean.merge_vert(quatrefoil_color, threshold=<NUM_LIT>)<EOL>mlx.layers.delete_lower(quatrefoil_color)<EOL>quatrefoil_color.run_script(output_mask='<STR_LIT>')<EOL>print('<STR_LIT>')<EOL>mlx.mp_func.vert_attr(quatrefoil_voronoi_surf, name='<STR_LIT>', function='<STR_LIT:q>')<EOL>mlx.create.cube_open_hires(<EOL>quatrefoil_voronoi_surf, size=tube_size, x_segments=holes[<NUM_LIT:0>]+<NUM_LIT:1>,<EOL>y_segments=holes[<NUM_LIT:1>]+<NUM_LIT:1>, z_segments=holes[<NUM_LIT:2>]+<NUM_LIT:1>, center=True)<EOL>mlx.select.all(quatrefoil_voronoi_surf, vert=False)<EOL>mlx.delete.selected(quatrefoil_voronoi_surf, vert=False)<EOL>mlx.select.cylindrical_vert(quatrefoil_voronoi_surf,<EOL>radius=max_radius-<NUM_LIT>, inside=False)<EOL>mlx.transform.translate(quatrefoil_voronoi_surf, [<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:20>])<EOL>mlx.delete.selected(quatrefoil_voronoi_surf, face=False)<EOL>mlx.transform.function_cyl_co(quatrefoil_voronoi_surf, r_func=r_func,<EOL>theta_func='<STR_LIT>', z_func='<STR_LIT:z>')<EOL>mlx.transform.vert_function(<EOL>quatrefoil_voronoi_surf, x_func=quatrefoil_func[<NUM_LIT:0>],<EOL>y_func=quatrefoil_func[<NUM_LIT:1>], z_func=quatrefoil_func[<NUM_LIT:2>])<EOL>mlx.layers.change(quatrefoil_voronoi_surf, <NUM_LIT:0>)<EOL>mlx.vert_color.voronoi(quatrefoil_voronoi_surf)<EOL>if quatrefoil_voronoi_surf.ml_version == '<STR_LIT>':<EOL><INDENT>sel_func = '<STR_LIT>'.format(web_thickness, solid_radius)<EOL><DEDENT>else:<EOL><INDENT>sel_func = '<STR_LIT>'.format(web_thickness, solid_radius)<EOL><DEDENT>mlx.select.vert_function(quatrefoil_voronoi_surf, function=sel_func)<EOL>mlx.select.invert(quatrefoil_voronoi_surf, face=False)<EOL>mlx.delete.selected(quatrefoil_voronoi_surf, face=False)<EOL>mlx.smooth.laplacian(quatrefoil_voronoi_surf, iterations=<NUM_LIT:3>)<EOL>mlx.remesh.simplify(quatrefoil_voronoi_surf, texture=False, faces=faces_surface)<EOL>mlx.layers.delete_lower(quatrefoil_voronoi_surf)<EOL>quatrefoil_voronoi_surf.run_script(script_file=None, output_mask='<STR_LIT>')<EOL>print('<STR_LIT>')<EOL>mlx.remesh.uniform_resampling(quatrefoil_voronoi_solid, voxel=voxel,<EOL>offset=thickness/<NUM_LIT:2>, thicken=True)<EOL>mlx.layers.delete_lower(quatrefoil_voronoi_solid)<EOL>quatrefoil_voronoi_solid.run_script()<EOL>print('<STR_LIT>')<EOL>mlx.delete.small_parts(quatrefoil_voronoi_color)<EOL>mlx.delete.unreferenced_vert(quatrefoil_voronoi_color)<EOL>mlx.delete.faces_from_nonmanifold_edges(quatrefoil_voronoi_color)<EOL>mlx.clean.split_vert_on_nonmanifold_face(quatrefoil_voronoi_color)<EOL>mlx.clean.close_holes(quatrefoil_voronoi_color)<EOL>mlx.remesh.simplify(quatrefoil_voronoi_color, texture=False, faces=faces_solid)<EOL>mlx.subdivide.ls3loop(quatrefoil_voronoi_color, iterations=<NUM_LIT:1>)<EOL>mlx.smooth.laplacian(quatrefoil_voronoi_color, iterations=<NUM_LIT:3>)<EOL>mlx.transfer.vert_attr_2_meshes(<EOL>quatrefoil_voronoi_color, source_mesh=<NUM_LIT:0>, target_mesh=<NUM_LIT:1>, color=True,<EOL>max_distance=<NUM_LIT:7>)<EOL>mlx.layers.delete_lower(quatrefoil_voronoi_color)<EOL>quatrefoil_voronoi_color.run_script(script_file=None)<EOL>print('<STR_LIT>' % (time.time() - start_time))<EOL>return None<EOL>

Rainbow colored voronoi quatrefoil (3,4) torus knot


path = os.path.realpath(file)<EOL>version_ns = {}<EOL>with io.open(path, encoding="<STR_LIT:utf8>") as f:<EOL><INDENT>exec(f.read(), {}, version_ns)<EOL><DEDENT>return version_ns[name]<EOL>

Get the version of the package from the given file by
    executing it and extracting the given `name`.


if not isinstance(specs, (list, tuple)):<EOL><INDENT>specs = [specs]<EOL><DEDENT>v = sys.version_info<EOL>part = '<STR_LIT>' % (v.major, v.minor)<EOL>for spec in specs:<EOL><INDENT>if part == spec:<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>if eval(part + spec):<EOL><INDENT>return<EOL><DEDENT><DEDENT>except SyntaxError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>raise ValueError('<STR_LIT>' % part)<EOL>

Given a list of range specifiers for python, ensure compatibility.


packages = []<EOL>for d, dirs, _ in os.walk(top, followlinks=True):<EOL><INDENT>if os.path.exists(pjoin(d, '<STR_LIT>')):<EOL><INDENT>packages.append(os.path.relpath(d, top).replace(os.path.sep, '<STR_LIT:.>'))<EOL><DEDENT>elif d != top:<EOL><INDENT>dirs[:] = []<EOL><DEDENT><DEDENT>return packages<EOL>


build_py = distribution.get_command_obj('<STR_LIT>')<EOL>build_py.finalize_options()<EOL>

update build_py options to get package_data changes


wrapped = [prerelease_cmd] if prerelease_cmd else []<EOL>if package_data_spec or data_files_spec:<EOL><INDENT>wrapped.append('<STR_LIT>')<EOL><DEDENT>wrapper = functools.partial(_wrap_command, wrapped)<EOL>handle_files = _get_file_handler(package_data_spec, data_files_spec)<EOL>if '<STR_LIT>' in sys.argv:<EOL><INDENT>egg = wrapper(bdist_egg, strict=True)<EOL><DEDENT>else:<EOL><INDENT>egg = bdist_egg_disabled<EOL><DEDENT>cmdclass = dict(<EOL>build_py=wrapper(build_py, strict=is_repo),<EOL>bdist_egg=egg,<EOL>sdist=wrapper(sdist, strict=True),<EOL>handle_files=handle_files,<EOL>)<EOL>if bdist_wheel:<EOL><INDENT>cmdclass['<STR_LIT>'] = wrapper(bdist_wheel, strict=True)<EOL><DEDENT>cmdclass['<STR_LIT>'] = wrapper(develop, strict=True)<EOL>return cmdclass<EOL>

Create a command class with the given optional prerelease class.

    Parameters
    ----------
    prerelease_cmd: (name, Command) tuple, optional
        The command to run before releasing.
    package_data_spec: dict, optional
        A dictionary whose keys are the dotted package names and
        whose values are a list of glob patterns.
    data_files_spec: list, optional
        A list of (path, dname, pattern) tuples where the path is the
        `data_files` install path, dname is the source directory, and the
        pattern is a glob pattern.

    Notes
    -----
    We use specs so that we can find the files *after* the build
    command has run.

    The package data glob patterns should be relative paths from the package
    folder containing the __init__.py file, which is given as the package
    name.
    e.g. `dict(foo=['./bar/*', './baz/**'])`

    The data files directories should be absolute paths or relative paths
    from the root directory of the repository.  Data files are specified
    differently from `package_data` because we need a separate path entry
    for each nested folder in `data_files`, and this makes it easier to
    parse.
    e.g. `('share/foo/bar', 'pkgname/bizz, '*')`


class FuncCommand(BaseCommand):<EOL><INDENT>def run(self):<EOL><INDENT>func()<EOL>update_package_data(self.distribution)<EOL><DEDENT><DEDENT>return FuncCommand<EOL>

Create a command that calls the given function.


log.info('<STR_LIT>' + list2cmdline(cmd))<EOL>kwargs.setdefault('<STR_LIT>', HERE)<EOL>kwargs.setdefault('<STR_LIT>', os.name == '<STR_LIT>')<EOL>if not isinstance(cmd, (list, tuple)) and os.name != '<STR_LIT>':<EOL><INDENT>cmd = shlex.split(cmd)<EOL><DEDENT>cmd[<NUM_LIT:0>] = which(cmd[<NUM_LIT:0>])<EOL>return subprocess.check_call(cmd, **kwargs)<EOL>

Echo a command before running it.  Defaults to repo as cwd


if not os.path.exists(target):<EOL><INDENT>return True<EOL><DEDENT>target_mtime = recursive_mtime(target) or <NUM_LIT:0><EOL>return compare_recursive_mtime(source, cutoff=target_mtime)<EOL>

Test whether the target file/directory is stale based on the source
       file/directory.


class CombinedCommand(Command):<EOL><INDENT>user_options = []<EOL>def initialize_options(self):<EOL><INDENT>self.commands = []<EOL>for C in commands:<EOL><INDENT>self.commands.append(C(self.distribution))<EOL><DEDENT>for c in self.commands:<EOL><INDENT>c.initialize_options()<EOL><DEDENT><DEDENT>def finalize_options(self):<EOL><INDENT>for c in self.commands:<EOL><INDENT>c.finalize_options()<EOL><DEDENT><DEDENT>def run(self):<EOL><INDENT>for c in self.commands:<EOL><INDENT>c.run()<EOL><DEDENT><DEDENT><DEDENT>return CombinedCommand<EOL>

Return a Command that combines several commands.


def compare_recursive_mtime(path, cutoff, newest=True):

if os.path.isfile(path):<EOL><INDENT>mt = mtime(path)<EOL>if newest:<EOL><INDENT>if mt > cutoff:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>elif mt < cutoff:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>for dirname, _, filenames in os.walk(path, topdown=False):<EOL><INDENT>for filename in filenames:<EOL><INDENT>mt = mtime(pjoin(dirname, filename))<EOL>if newest:  <EOL><INDENT>if mt > cutoff:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>elif mt < cutoff:<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT>return False<EOL>

Compare the newest/oldest mtime for all files in a directory.

    Cutoff should be another mtime to be compared against. If an mtime that is
    newer/older than the cutoff is found it will return True.
    E.g. if newest=True, and a file in path is newer than the cutoff, it will
    return True.


if os.path.isfile(path):<EOL><INDENT>return mtime(path)<EOL><DEDENT>current_extreme = None<EOL>for dirname, dirnames, filenames in os.walk(path, topdown=False):<EOL><INDENT>for filename in filenames:<EOL><INDENT>mt = mtime(pjoin(dirname, filename))<EOL>if newest:  <EOL><INDENT>if mt >= (current_extreme or mt):<EOL><INDENT>current_extreme = mt<EOL><DEDENT><DEDENT>elif mt <= (current_extreme or mt):<EOL><INDENT>current_extreme = mt<EOL><DEDENT><DEDENT><DEDENT>return current_extreme<EOL>

Gets the newest/oldest mtime for all files in a directory.


return os.stat(path).st_mtime<EOL>


def install_npm(path=None, build_dir=None, source_dir=None, build_cmd='<STR_LIT>', force=False, npm=None):

class NPM(BaseCommand):<EOL><INDENT>description = '<STR_LIT>'<EOL>def run(self):<EOL><INDENT>if skip_npm:<EOL><INDENT>log.info('<STR_LIT>')<EOL>return<EOL><DEDENT>node_package = path or HERE<EOL>node_modules = pjoin(node_package, '<STR_LIT>')<EOL>is_yarn = os.path.exists(pjoin(node_package, '<STR_LIT>'))<EOL>npm_cmd = npm<EOL>if npm is None:<EOL><INDENT>if is_yarn:<EOL><INDENT>npm_cmd = ['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>npm_cmd = ['<STR_LIT>']<EOL><DEDENT><DEDENT>if not which(npm_cmd[<NUM_LIT:0>]):<EOL><INDENT>log.error("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>.format(npm_cmd[<NUM_LIT:0>]))<EOL>return<EOL><DEDENT>if force or is_stale(node_modules, pjoin(node_package, '<STR_LIT>')):<EOL><INDENT>log.info('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>run(npm_cmd + ['<STR_LIT>'], cwd=node_package)<EOL><DEDENT>if build_dir and source_dir and not force:<EOL><INDENT>should_build = is_stale(build_dir, source_dir)<EOL><DEDENT>else:<EOL><INDENT>should_build = True<EOL><DEDENT>if should_build:<EOL><INDENT>run(npm_cmd + ['<STR_LIT>', build_cmd], cwd=node_package)<EOL><DEDENT><DEDENT><DEDENT>return NPM<EOL>

Return a Command for managing an npm installation.

    Note: The command is skipped if the `--skip-npm` flag is used.

    Parameters
    ----------
    path: str, optional
        The base path of the node package.  Defaults to the repo root.
    build_dir: str, optional
        The target build directory.  If this and source_dir are given,
        the JavaScript will only be build if necessary.
    source_dir: str, optional
        The source code directory.
    build_cmd: str, optional
        The npm command to build assets to the build_dir.
    npm: str or list, optional.
        The npm executable name, or a tuple of ['node', executable].


class TargetsCheck(BaseCommand):<EOL><INDENT>def run(self):<EOL><INDENT>if skip_npm:<EOL><INDENT>log.info('<STR_LIT>')<EOL>return<EOL><DEDENT>missing = [t for t in targets if not os.path.exists(t)]<EOL>if missing:<EOL><INDENT>raise ValueError(('<STR_LIT>' % missing))<EOL><DEDENT><DEDENT><DEDENT>return TargetsCheck<EOL>

Return a Command that checks that certain files exist.

    Raises a ValueError if any of the files are missing.

    Note: The check is skipped if the `--skip-npm` flag is used.


def which(cmd, mode=os.F_OK | os.X_OK, path=None):

<EOL>def _access_check(fn, mode):<EOL><INDENT>return (os.path.exists(fn) and os.access(fn, mode) and<EOL>not os.path.isdir(fn))<EOL><DEDENT>if _access_check(cmd, mode):<EOL><INDENT>return cmd<EOL><DEDENT>path = (path or os.environ.get("<STR_LIT>", os.defpath)).split(os.pathsep)<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>if os.curdir not in path:<EOL><INDENT>path.insert(<NUM_LIT:0>, os.curdir)<EOL><DEDENT>pathext = os.environ.get("<STR_LIT>", "<STR_LIT>").split(os.pathsep)<EOL>matches = [cmd for ext in pathext if cmd.lower().endswith(ext.lower())]<EOL>files = [cmd] if matches else [cmd + ext.lower() for ext in pathext]<EOL><DEDENT>else:<EOL><INDENT>files = [cmd]<EOL><DEDENT>seen = set()<EOL>for dir in path:<EOL><INDENT>dir = os.path.normcase(dir)<EOL>if dir not in seen:<EOL><INDENT>seen.add(dir)<EOL>for thefile in files:<EOL><INDENT>name = os.path.join(dir, thefile)<EOL>if _access_check(name, mode):<EOL><INDENT>return name<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return None<EOL>

Given a command, mode, and a PATH string, return the path which
    conforms to the given mode on the PATH, or None if there is no such
    file.
    `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
    of os.environ.get("PATH"), or can be overridden with a custom search
    path.


def _wrap_command(cmds, cls, strict=True):

class WrappedCommand(cls):<EOL><INDENT>def run(self):<EOL><INDENT>if not getattr(self, '<STR_LIT>', None):<EOL><INDENT>try:<EOL><INDENT>[self.run_command(cmd) for cmd in cmds]<EOL><DEDENT>except Exception:<EOL><INDENT>if strict:<EOL><INDENT>raise<EOL><DEDENT>else:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>update_package_data(self.distribution)<EOL>result = cls.run(self)<EOL>return result<EOL><DEDENT><DEDENT>return WrappedCommand<EOL>

Wrap a setup command

    Parameters
    ----------
    cmds: list(str)
        The names of the other commands to run prior to the command.
    strict: boolean, optional
        Whether to raise errors when a pre-command fails.


class FileHandler(BaseCommand):<EOL><INDENT>def run(self):<EOL><INDENT>package_data = self.distribution.package_data<EOL>package_spec = package_data_spec or dict()<EOL>for (key, patterns) in package_spec.items():<EOL><INDENT>package_data[key] = _get_package_data(key, patterns)<EOL><DEDENT>self.distribution.data_files = _get_data_files(<EOL>data_files_spec, self.distribution.data_files<EOL>)<EOL><DEDENT><DEDENT>return FileHandler<EOL>

Get a package_data and data_files handler command.


<EOL>file_data = defaultdict(list)<EOL>for (path, files) in existing or []:<EOL><INDENT>file_data[path] = files<EOL><DEDENT>for (path, dname, pattern) in data_specs or []:<EOL><INDENT>dname = dname.replace(os.sep, '<STR_LIT:/>')<EOL>offset = len(dname) + <NUM_LIT:1><EOL>files = _get_files(pjoin(dname, pattern))<EOL>for fname in files:<EOL><INDENT>root = os.path.dirname(fname)<EOL>full_path = '<STR_LIT:/>'.join([path, root[offset:]])<EOL>if full_path.endswith('<STR_LIT:/>'):<EOL><INDENT>full_path = full_path[:-<NUM_LIT:1>]<EOL><DEDENT>file_data[full_path].append(fname)<EOL><DEDENT><DEDENT>data_files = []<EOL>for (path, files) in file_data.items():<EOL><INDENT>data_files.append((path, files))<EOL><DEDENT>return data_files<EOL>

Expand data file specs into valid data files metadata.

    Parameters
    ----------
    data_specs: list of tuples
        See [createcmdclass] for description.
    existing: list of tuples
        The existing distribution data_files metadata.

    Returns
    -------
    A valid list of data_files items.


if not isinstance(file_patterns, (list, tuple)):<EOL><INDENT>file_patterns = [file_patterns]<EOL><DEDENT>for i, p in enumerate(file_patterns):<EOL><INDENT>if os.path.isabs(p):<EOL><INDENT>file_patterns[i] = os.path.relpath(p, top)<EOL><DEDENT><DEDENT>matchers = [_compile_pattern(p) for p in file_patterns]<EOL>files = set()<EOL>for root, dirnames, filenames in os.walk(top):<EOL><INDENT>if '<STR_LIT>' in dirnames:<EOL><INDENT>dirnames.remove('<STR_LIT>')<EOL><DEDENT>for m in matchers:<EOL><INDENT>for filename in filenames:<EOL><INDENT>fn = os.path.relpath(pjoin(root, filename), top)<EOL>if m(fn):<EOL><INDENT>files.add(fn.replace(os.sep, '<STR_LIT:/>'))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return list(files)<EOL>

Expand file patterns to a list of paths.

    Parameters
    -----------
    file_patterns: list or str
        A list of glob patterns for the data file locations.
        The globs can be recursive if they include a `**`.
        They should be relative paths from the top directory or
        absolute paths.
    top: str
        the directory to consider for data files

    Note:
    Files in `node_modules` are ignored.


if file_patterns is None:<EOL><INDENT>file_patterns = ['<STR_LIT:*>']<EOL><DEDENT>return _get_files(file_patterns, pjoin(HERE, root))<EOL>

Expand file patterns to a list of `package_data` paths.

    Parameters
    -----------
    root: str
        The relative path to the package root from `HERE`.
    file_patterns: list or str, optional
        A list of glob patterns for the data file locations.
        The globs can be recursive if they include a `**`.
        They should be relative paths from the root or
        absolute paths.  If not given, all files will be used.

    Note:
    Files in `node_modules` are ignored.


if isinstance(pat, bytes):<EOL><INDENT>pat_str = pat.decode('<STR_LIT>')<EOL>res_str = _translate_glob(pat_str)<EOL>res = res_str.encode('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>res = _translate_glob(pat)<EOL><DEDENT>flags = re.IGNORECASE if ignore_case else <NUM_LIT:0><EOL>return re.compile(res, flags=flags).match<EOL>

Translate and compile a glob pattern to a regular expression matcher.


(head, tail) = os.path.split(path)<EOL>if not head or (not tail and head == path):<EOL><INDENT>if head:<EOL><INDENT>yield head<EOL><DEDENT>if tail or not head:<EOL><INDENT>yield tail<EOL><DEDENT>return<EOL><DEDENT>for p in _iexplode_path(head):<EOL><INDENT>yield p<EOL><DEDENT>yield tail<EOL>

Iterate over all the parts of a path.

    Splits path recursively with os.path.split().


translated_parts = []<EOL>for part in _iexplode_path(pat):<EOL><INDENT>translated_parts.append(_translate_glob_part(part))<EOL><DEDENT>os_sep_class = '<STR_LIT>' % re.escape(SEPARATORS)<EOL>res = _join_translated(translated_parts, os_sep_class)<EOL>return '<STR_LIT>'.format(res=res)<EOL>

Translate a glob PATTERN to a regular expression.


res = '<STR_LIT>'<EOL>for part in translated_parts[:-<NUM_LIT:1>]:<EOL><INDENT>if part == '<STR_LIT>':<EOL><INDENT>res += part<EOL><DEDENT>else:<EOL><INDENT>res += part + os_sep_class<EOL><DEDENT><DEDENT>if translated_parts[-<NUM_LIT:1>] == '<STR_LIT>':<EOL><INDENT>res += '<STR_LIT>'<EOL>res += '<STR_LIT>'.format(os_sep_class=os_sep_class)<EOL><DEDENT>else:<EOL><INDENT>res += translated_parts[-<NUM_LIT:1>]<EOL><DEDENT>return res<EOL>

Join translated glob pattern parts.

    This is different from a simple join, as care need to be taken
    to allow ** to match ZERO or more directories.


<EOL>if pat == '<STR_LIT>':<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>i, n = <NUM_LIT:0>, len(pat)<EOL>res = []<EOL>while i < n:<EOL><INDENT>c = pat[i]<EOL>i = i + <NUM_LIT:1><EOL>if c == '<STR_LIT:*>':<EOL><INDENT>res.append('<STR_LIT>' % SEPARATORS)<EOL><DEDENT>elif c == '<STR_LIT:?>':<EOL><INDENT>res.append('<STR_LIT>' % SEPARATORS)<EOL><DEDENT>elif c == '<STR_LIT:[>':<EOL><INDENT>j = i<EOL>if j < n and pat[j] == '<STR_LIT:!>':<EOL><INDENT>j = j + <NUM_LIT:1><EOL><DEDENT>if j < n and pat[j] == '<STR_LIT:]>':<EOL><INDENT>j = j + <NUM_LIT:1><EOL><DEDENT>while j < n and pat[j] != '<STR_LIT:]>':<EOL><INDENT>j = j + <NUM_LIT:1><EOL><DEDENT>if j >= n:<EOL><INDENT>res.append('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>stuff = pat[i:j].replace('<STR_LIT:\\>', '<STR_LIT>')<EOL>i = j + <NUM_LIT:1><EOL>if stuff[<NUM_LIT:0>] == '<STR_LIT:!>':<EOL><INDENT>stuff = '<STR_LIT>' + stuff[<NUM_LIT:1>:]<EOL><DEDENT>elif stuff[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>stuff = '<STR_LIT:\\>' + stuff<EOL><DEDENT>res.append('<STR_LIT>' % stuff)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>res.append(re.escape(c))<EOL><DEDENT><DEDENT>return '<STR_LIT>'.join(res)<EOL>

Translate a glob PATTERN PART to a regular expression.


x = x.transpose((<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:0>))<EOL>x[:, :, <NUM_LIT:0>] += <NUM_LIT><EOL>x[:, :, <NUM_LIT:1>] += <NUM_LIT><EOL>x[:, :, <NUM_LIT:2>] += <NUM_LIT><EOL>x = x[:,:,::-<NUM_LIT:1>]  <EOL>return x<EOL>

Decondition an image from the VGG16 model.


x = x[:,:,::-<NUM_LIT:1>]  <EOL>x[:, :, <NUM_LIT:0>] -= <NUM_LIT><EOL>x[:, :, <NUM_LIT:1>] -= <NUM_LIT><EOL>x[:, :, <NUM_LIT:2>] -= <NUM_LIT><EOL>x = x.transpose((<NUM_LIT:2>, <NUM_LIT:0>, <NUM_LIT:1>))<EOL>return x<EOL>

Condition an image for use with the VGG16 model.


inputs = [self.net_input]<EOL>if self.learning_phase is not None:<EOL><INDENT>inputs.append(K.learning_phase())<EOL><DEDENT>return K.function(inputs, [self.get_layer_output(layer_name)])<EOL>

Create a function for the response of a layer.


if not name in self._f_layer_outputs:<EOL><INDENT>layer = self.net.get_layer(name)<EOL>self._f_layer_outputs[name] = layer.output<EOL><DEDENT>return self._f_layer_outputs[name]<EOL>


if not layers:<EOL><INDENT>return None<EOL><DEDENT>inputs = [self.net.input]<EOL>if self.learning_phase is not None:<EOL><INDENT>inputs.append(self.learning_phase)<EOL><DEDENT>f = K.function(inputs, [self.get_layer_output(layer_name) for layer_name in layers])<EOL>feature_outputs = f([x])<EOL>features = dict(zip(layers, feature_outputs))<EOL>return features<EOL>


toks = []<EOL>if not values:<EOL><INDENT>return toks<EOL><DEDENT>if not isinstance(delimiter, (list, tuple)):<EOL><INDENT>delimiter = [delimiter]<EOL><DEDENT>last = len(values) - <NUM_LIT:1><EOL>for i, value in enumerate(values):<EOL><INDENT>toks.append(value)<EOL>if i < last:<EOL><INDENT>toks.extend(delimiter)<EOL><DEDENT><DEDENT>return toks<EOL>

Returns a list of tokens interleaved with the delimiter.


if not isinstance(value, Token):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if not hasattr(value, '<STR_LIT>'):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if not value.identifier:<EOL><INDENT>value = value.__class__(**value.__dict__)<EOL>value.identifier = '<STR_LIT:v>'<EOL><DEDENT>ident = Identifier(value.identifier)<EOL>return Query([<EOL>OptionalMatch(value),<EOL>Return(Predicate(ident, '<STR_LIT>')),<EOL>Limit(<NUM_LIT:1>),<EOL>])<EOL>


if not isinstance(value, Token):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if not hasattr(value, '<STR_LIT>'):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if not value.identifier:<EOL><INDENT>value = value.__class__(**value.__dict__)<EOL>value.identifier = '<STR_LIT:v>'<EOL><DEDENT>ident = Identifier(value.identifier)<EOL>return Query([<EOL>Match(value),<EOL>Return(ident)<EOL>])<EOL>


print( args)<EOL>


if isinstance(args[<NUM_LIT:0>], str):<EOL><INDENT>return self.encode([args[<NUM_LIT:0>]],**kwargs)<EOL><DEDENT>elif isinstance(args[<NUM_LIT:0>], int) or isinstance(args[<NUM_LIT:0>], float):<EOL><INDENT>return self.encode([[args[<NUM_LIT:0>]]],**kwargs)<EOL><DEDENT>if len(args)><NUM_LIT:1>:<EOL><INDENT>dataset = args<EOL><DEDENT>else:<EOL><INDENT>dataset = args[<NUM_LIT:0>]<EOL><DEDENT>typemap = list(map(type,dataset))<EOL>code = self.encoding[<NUM_LIT:0>]<EOL>if type('<STR_LIT>') in typemap:<EOL><INDENT>data = '<STR_LIT:U+002C>'.join(map(str,dataset))<EOL><DEDENT>elif type([]) in typemap or type(()) in typemap:<EOL><INDENT>data = self.codeset['<STR_LIT>'].join(map(self.encodedata, dataset))<EOL><DEDENT>elif len(dataset) == <NUM_LIT:1> and hasattr(dataset[<NUM_LIT:0>], '<STR_LIT>'):<EOL><INDENT>data = self.encodedata(dataset[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>data = self.encodedata(dataset)<EOL><DEDENT>except ValueError:<EOL><INDENT>data = self.encodedata('<STR_LIT:U+002C>'.join(map(unicode,dataset)))<EOL><DEDENT><DEDENT>if not '<STR_LIT:.>' in data and code == '<STR_LIT:t>':<EOL><INDENT>code = '<STR_LIT:e>'<EOL><DEDENT>return '<STR_LIT>'%(code,self.series,data)<EOL>

Encode wrapper for a dataset with maximum value

        Datasets can be one or two dimensional
        Strings are ignored as ordinal encoding


if color is None: return<EOL>color = color.lower()<EOL>if color in COLOR_MAP:<EOL><INDENT>return COLOR_MAP[color]<EOL><DEDENT>return color<EOL>

Returns the hex color for any valid css color name

>>> lookup_color('aliceblue')
'F0F8FF'


for i,arg in enumerate(args):<EOL><INDENT>if i in indexes:<EOL><INDENT>yield lookup_color(arg)<EOL><DEDENT>else:<EOL><INDENT>yield arg<EOL><DEDENT><DEDENT>

Color a list of arguments on particular indexes

>>> c = color_args([None,'blue'], 1)
>>> c.next()
None
>>> c.next()
'0000FF'


assert int(length) <= <NUM_LIT>, '<STR_LIT>'<EOL>self.data['<STR_LIT>'].append('<STR_LIT>'%(index,length))<EOL>return self.parent<EOL>

Add tick marks in order of axes by width
APIPARAM: chxtc     <axis index>,<length of tick mark>


for char in atype:<EOL><INDENT>assert char in '<STR_LIT>', '<STR_LIT>'%char<EOL><DEDENT>if not '<STR_LIT:U+002C>' in atype:<EOL><INDENT>atype = '<STR_LIT:U+002C>'.join(atype)<EOL><DEDENT>self['<STR_LIT>'] = atype<EOL>return self.parent<EOL>

Define the type of axes you wish to use
atype must be one of x,t,y,r
APIPARAM: chxt


self.data['<STR_LIT>'].append(<EOL>str('<STR_LIT>'%(index, '<STR_LIT:|>'.join(map(str,args)) )).replace('<STR_LIT:None>','<STR_LIT>')<EOL>)<EOL>return self.parent<EOL>

Label each axes one at a time
args are of the form <label 1>,...,<label n>
APIPARAM: chxl


self.data['<STR_LIT>'].append(<EOL>str('<STR_LIT>'%(index, '<STR_LIT:U+002C>'.join(map(str,args)))).replace('<STR_LIT:None>','<STR_LIT>')<EOL>)<EOL>return self.parent<EOL>

Set the label position of each axis, one at a time
args are of the form <label position 1>,...,<label position n>
APIPARAM: chxp


self.data['<STR_LIT>'].append('<STR_LIT>'%(index,<EOL>'<STR_LIT:U+002C>'.join(map(smart_str, args))))<EOL>return self.parent<EOL>

Set the range of each axis, one at a time
args are of the form <start of range>,<end of range>,<interval>
APIPARAM: chxr


args = color_args(args, <NUM_LIT:0>)<EOL>self.data['<STR_LIT>'].append(<EOL>'<STR_LIT:U+002C>'.join([str(index)]+list(map(str,args)))<EOL>)<EOL>return self.parent<EOL>

Add style to your axis, one at a time
args are of the form::
    <axis color>,
    <font size>,
    <alignment>,
    <drawing control>,
    <tick mark color>
APIPARAM: chxs


for opt,values in self.data.items():<EOL><INDENT>if opt == '<STR_LIT>':<EOL><INDENT>self['<STR_LIT>'] = '<STR_LIT:|>'.join(values)<EOL><DEDENT>else:<EOL><INDENT>self['<STR_LIT>'%opt[<NUM_LIT:0>]] = '<STR_LIT:|>'.join(values)<EOL><DEDENT><DEDENT>return self<EOL>


if isinstance(qs, dict):<EOL><INDENT>return cls(**qs)<EOL><DEDENT>return cls(**dict(parse_qsl(qs[qs.index('<STR_LIT:?>')+<NUM_LIT:1>:])))<EOL>

Reverse a chart URL or dict into a GChart instance

>>> G = GChart.fromurl('http://chart.apis.google.com/chart?...')
>>> G
<GChartWrapper.GChart instance at...>
>>> G.image().save('chart.jpg','JPEG')


assert geo in GEO, '<STR_LIT>'%geo<EOL>self._geo = geo<EOL>self._ld = country_codes<EOL>return self<EOL>

Creates a map of the defined geography with the given country/state codes
Geography choices are africa, asia, europe, middle_east, south_america, and world
ISO country codes can be found at http://code.google.com/apis/chart/isocodes.html
US state codes can be found at http://code.google.com/apis/chart/statecodes.html
APIPARAMS: chtm & chld


assert args[<NUM_LIT:0>].lower() in '<STR_LIT>', '<STR_LIT>'%level<EOL>self['<STR_LIT>'] = '<STR_LIT>'%args<EOL>return self<EOL>

Just used in QRCode for the moment
args are error_correction,margin_size
APIPARAM: chld


self['<STR_LIT>'] = '<STR_LIT:U+002C>'.join(map(str,args))<EOL>return self<EOL>

For bar charts, specify bar thickness and spacing with the args
args are <bar width>,<space between bars>,<space between groups>
bar width can be relative or absolute, see the official doc
APIPARAM: chbh


self._encoding = arg<EOL>return self<EOL>

Specifies the encoding to be used for the Encoder
Must be one of 'simple','text', or 'extended'


assert encoding in ('<STR_LIT>','<STR_LIT>','<STR_LIT>'),'<STR_LIT>'%encoding<EOL>self['<STR_LIT>'] = encoding<EOL>return self<EOL>

Output encoding to use for QRCode encoding
Must be one of 'Shift_JIS','UTF-8', or 'ISO-8859-1'
APIPARAM: choe


self._scale =  ['<STR_LIT:U+002C>'.join(map(smart_str, args))]<EOL>return self<EOL>

Scales the data down to the given size
args must be of the form::
    <data set 1 minimum value>,
    <data set 1 maximum value>,
    <data set n minimum value>,
    <data set n maximum value>
will only work with text encoding!
APIPARAM: chds


def dataset(self, data, series='<STR_LIT>'):

self._dataset = data<EOL>self._series = series<EOL>return self<EOL>

Update the chart's dataset, can be two dimensional or contain string data


if len(args[<NUM_LIT:0>]) == <NUM_LIT:1>:<EOL><INDENT>assert args[<NUM_LIT:0>] in MARKERS, '<STR_LIT>'%args[<NUM_LIT:0>]<EOL><DEDENT>assert len(args) <= <NUM_LIT:6>, '<STR_LIT>'%str(args)<EOL>args = color_args(args, <NUM_LIT:1>)<EOL>self.markers.append('<STR_LIT:U+002C>'.join(map(str,args)) )<EOL>return self<EOL>

Defines markers one at a time for your graph
args are of the form::
    <marker type>,
    <color>,
    <data set index>,
    <data point>,
    <size>,
    <priority>
see the official developers doc for the complete spec
APIPARAM: chm


def margin(self, left, right, top, bottom, lwidth=<NUM_LIT:0>, lheight=<NUM_LIT:0>):

self['<STR_LIT>'] = '<STR_LIT>'  % (left, right, top, bottom)<EOL>if lwidth or lheight:<EOL><INDENT>self['<STR_LIT>'] += '<STR_LIT>' % (lwidth, lheight)<EOL><DEDENT>return self<EOL>

Set margins for chart area
args are of the form::
    <left margin>,
    <right margin>,
    <top margin>,
    <bottom margin>|
    <legend width>,
    <legend height>

APIPARAM: chma


self.lines.append('<STR_LIT:U+002C>'.join(['<STR_LIT>'%x for x in map(float,args)]))<EOL>return self<EOL>

Called one at a time for each dataset
args are of the form::
    <data set n line thickness>,
    <length of line segment>,
    <length of blank segment>
APIPARAM: chls


a,b = args[:<NUM_LIT:2>]<EOL>assert a in ('<STR_LIT:c>','<STR_LIT>','<STR_LIT:a>'), '<STR_LIT>'%a<EOL>assert b in ('<STR_LIT:s>','<STR_LIT>','<STR_LIT>'), '<STR_LIT>'%b<EOL>if len(args) == <NUM_LIT:3>:<EOL><INDENT>args = color_args(args, <NUM_LIT:2>)<EOL><DEDENT>else:<EOL><INDENT>args = color_args(args, <NUM_LIT:3>,<NUM_LIT:5>)<EOL><DEDENT>self.fills.append('<STR_LIT:U+002C>'.join(map(str,args)))<EOL>return self<EOL>

Apply a solid fill to your chart
args are of the form <fill type>,<fill style>,...
fill type must be one of c,bg,a
fill style must be one of s,lg,ls
the rest of the args refer to the particular style
APIPARAM: chf


grids =  map(str,map(float,args))<EOL>self['<STR_LIT>'] = '<STR_LIT:U+002C>'.join(grids).replace('<STR_LIT:None>','<STR_LIT>')<EOL>return self<EOL>

Apply a grid to your chart
args are of the form::
    <x axis step size>,
    <y axis step size>,
    <length of line segment>,
    <length of blank segment>
    <x offset>,
    <y offset>
APIPARAM: chg


args = color_args(args, *range(len(args)))<EOL>self['<STR_LIT>'] = '<STR_LIT:U+002C>'.join(args)<EOL>return self<EOL>

Add a color for each dataset
args are of the form <color 1>,...<color n>
APIPARAM: chco


self['<STR_LIT>'] = self.check_type(str(type))<EOL>return self<EOL>

Set the chart type, either Google API type or regular name
APIPARAM: cht


if self['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>self['<STR_LIT>'] = '<STR_LIT>'.join(map(str,args))<EOL><DEDENT>else:<EOL><INDENT>self['<STR_LIT>'] = '<STR_LIT:|>'.join(map(str,args))<EOL><DEDENT>return self<EOL>

Add a simple label to your chart
call each time for each dataset
APIPARAM: chl


self['<STR_LIT>'] = '<STR_LIT:|>'.join(args)<EOL>return self<EOL>

Add a legend to your chart
call each time for each dataset
APIPARAM: chdl


assert pos in LEGEND_POSITIONS, '<STR_LIT>'%pos<EOL>self['<STR_LIT>'] = str(pos)<EOL>return self<EOL>

Define a position for your legend to occupy
APIPARAM: chdlp


self['<STR_LIT>'] = title<EOL>if args:<EOL><INDENT>args = color_args(args, <NUM_LIT:0>)<EOL>self['<STR_LIT>'] = '<STR_LIT:U+002C>'.join(map(str,args))<EOL><DEDENT>return self<EOL>

Add a title to your chart
args are optional style params of the form <color>,<font size>
APIPARAMS: chtt,chts


if len(args) == <NUM_LIT:2>:<EOL><INDENT>x,y = map(int,args)<EOL><DEDENT>else:<EOL><INDENT>x,y = map(int,args[<NUM_LIT:0>])<EOL><DEDENT>self.check_size(x,y)<EOL>self['<STR_LIT>'] = '<STR_LIT>'%(x,y)<EOL>return self<EOL>

Set the size of the chart, args are width,height and can be tuple
APIPARAM: chs


self['<STR_LIT>'] = '<STR_LIT>'%angle<EOL>return self<EOL>

Set the chart dataset orientation
angle is <angle in radians>
APIPARAM: chp


self.update(self.axes.render())<EOL>encoder = Encoder(self._encoding, None, self._series)<EOL>if not '<STR_LIT>' in self:<EOL><INDENT>self['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>size = self['<STR_LIT>'].split('<STR_LIT:x>')<EOL>assert len(size) == <NUM_LIT:2>, '<STR_LIT>'<EOL>self.check_size(*map(int,size))<EOL><DEDENT>assert '<STR_LIT>' in self, '<STR_LIT>'<EOL>self['<STR_LIT>'] = self.check_type(self['<STR_LIT>'])<EOL>if ('<STR_LIT>' in dir(self._dataset) and self._dataset.any()) or self._dataset:<EOL><INDENT>self['<STR_LIT>'] = encoder.encode(self._dataset)<EOL><DEDENT>elif not '<STR_LIT>' in self:<EOL><INDENT>assert '<STR_LIT>' in self, '<STR_LIT>'<EOL><DEDENT>if self._scale:<EOL><INDENT>assert self['<STR_LIT>'].startswith('<STR_LIT:t>'),'<STR_LIT>'<EOL>self['<STR_LIT>'] = '<STR_LIT:U+002C>'.join(self._scale)<EOL><DEDENT>if self._geo and self._ld:<EOL><INDENT>self['<STR_LIT>'] = self._geo<EOL>self['<STR_LIT>'] = self._ld<EOL><DEDENT>if self.lines:<EOL><INDENT>self['<STR_LIT>'] = '<STR_LIT:|>'.join(self.lines)<EOL><DEDENT>if self.markers:<EOL><INDENT>self['<STR_LIT>'] = '<STR_LIT:|>'.join(self.markers)<EOL><DEDENT>if self.fills:<EOL><INDENT>self['<STR_LIT>'] = '<STR_LIT:|>'.join(self.fills)<EOL><DEDENT>

Renders the chart context and axes into the dict data


assert x <= <NUM_LIT:1000>, '<STR_LIT>'<EOL>assert y <= <NUM_LIT:1000>, '<STR_LIT>'<EOL>assert x*y <= <NUM_LIT>, '<STR_LIT>'<EOL>

Make sure the chart size fits the standards


if type in TYPES:<EOL><INDENT>return type<EOL><DEDENT>tdict = dict(zip(TYPES,TYPES))<EOL>tdict.update({<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:bar>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT:p>',<EOL>'<STR_LIT>': '<STR_LIT:v>',<EOL>'<STR_LIT>': '<STR_LIT:s>',<EOL>'<STR_LIT>': '<STR_LIT:r>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>})<EOL>assert type in tdict, '<STR_LIT>'%type<EOL>return tdict[type]<EOL>

Check to see if the type is either in TYPES or fits type name

        Returns proper type


return self.get('<STR_LIT>','<STR_LIT>')<EOL>

Gets the name of the chart, if it exists


<EOL>return Encoder(self._encoding).decode(self['<STR_LIT>'])<EOL>

Returns the decoded dataset from chd param


self.render()        <EOL>return self._apiurl + '<STR_LIT:&>'.join(self._parts()).replace('<STR_LIT:U+0020>','<STR_LIT:+>')<EOL>


from webbrowser import open as webopen<EOL>return webopen(str(self), *args, **kwargs)<EOL>

Shows the chart URL in a webbrowser

Other arguments passed to webbrowser.open


if not fname:<EOL><INDENT>fname = self.getname()<EOL><DEDENT>assert fname != None, '<STR_LIT>'<EOL>if not fname.endswith('<STR_LIT>'):<EOL><INDENT>fname += '<STR_LIT>'<EOL><DEDENT>try:<EOL><INDENT>urlretrieve(self.url, fname)<EOL><DEDENT>except Exception:<EOL><INDENT>raise IOError('<STR_LIT>'%fname)<EOL><DEDENT>return fname<EOL>

Download the chart from the URL into a filename as a PNG

The filename defaults to the chart title (chtt) if any


safe = '<STR_LIT>' % self.url.replace('<STR_LIT:&>','<STR_LIT>').replace('<STR_LIT:<>', '<STR_LIT>').replace('<STR_LIT:>>', '<STR_LIT>').replace('<STR_LIT:">', '<STR_LIT>').replace( "<STR_LIT:'>", '<STR_LIT>')<EOL>for item in kwargs.items():<EOL><INDENT>if not item[<NUM_LIT:0>] in IMGATTRS:<EOL><INDENT>raise AttributeError('<STR_LIT>'%item[<NUM_LIT:0>])<EOL><DEDENT>safe += '<STR_LIT>'%item<EOL><DEDENT>return '<STR_LIT>'%safe<EOL>

Returns an XHTML <img/> tag of the chart

kwargs can be other img tag attributes, which are strictly enforced
uses strict escaping on the url, necessary for proper XHTML


req = Request(str(self))<EOL>try:<EOL><INDENT>return urlopen(req)<EOL><DEDENT>except HTTPError:<EOL><INDENT>_print('<STR_LIT>')<EOL><DEDENT>except URLError:<EOL><INDENT>_print('<STR_LIT>')<EOL><DEDENT>


try:<EOL><INDENT>try:<EOL><INDENT>import Image<EOL><DEDENT>except ImportError:<EOL><INDENT>from PIL import Image<EOL><DEDENT><DEDENT>except ImportError:<EOL><INDENT>raise ImportError('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>from cStringIO import StringIO<EOL><DEDENT>except ImportError:<EOL><INDENT>from StringIO import StringIO<EOL><DEDENT>return Image.open(StringIO(self.urlopen().read()))<EOL>

Returns a PngImageFile instance of the chart

You must have PIL installed for this to work


urlfp = self.urlopen().fp<EOL>while <NUM_LIT:1>:<EOL><INDENT>try:<EOL><INDENT>fp.write(urlfp.next())<EOL><DEDENT>except StopIteration:<EOL><INDENT>return<EOL><DEDENT><DEDENT>

Writes out PNG image data in chunks to file pointer fp

fp must support w or wb


self.render()<EOL>return new_sha('<STR_LIT>'.join(sorted(self._parts()))).hexdigest()<EOL>

Returns the unique SHA1 hexdigest of the chart URL param parts

good for unittesting...


def _chart_support(self, *args, **kwargs):

print(args,kwargs)<EOL>return '<STR_LIT>'<EOL>


def _dec(view_func):<EOL><INDENT>@functools.wraps(view_func, assigned=available_attrs(view_func))<EOL>def _wrapped_view(request, *args, **kwargs):<EOL><INDENT>backend = kwargs.get('<STR_LIT>', backend_name)<EOL>config = settings.INSTALLED_BACKENDS[backend]['<STR_LIT>']<EOL>validator = RequestValidator(config['<STR_LIT>'])<EOL>signature = request.META.get('<STR_LIT>', '<STR_LIT>')<EOL>url = request.build_absolute_uri()<EOL>body = {}<EOL>if request.method == '<STR_LIT:POST>':<EOL><INDENT>body = request.POST<EOL><DEDENT>require_validation = config.get('<STR_LIT>', True)<EOL>if validator.validate(url, body, signature) or not require_validation:<EOL><INDENT>return view_func(request, *args, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>return HttpResponseBadRequest()<EOL><DEDENT><DEDENT>return _wrapped_view<EOL><DEDENT>if func is None:<EOL><INDENT>return _dec<EOL><DEDENT>else:<EOL><INDENT>return _dec(func)<EOL><DEDENT>

View decorator to validate requests from Twilio per http://www.twilio.com/docs/security.


path = os.path.abspath(os.path.dirname(__file__))<EOL>filepath = os.path.join(path, filename)<EOL>with open(filepath) as f:<EOL><INDENT>return f.read()<EOL><DEDENT>


K = nx.complete_graph(k)<EOL>g1 = nx.cartesian_product(nx.create_empty_copy(graph), K)<EOL>g2 = nx.cartesian_product(graph, nx.create_empty_copy(K))<EOL>return nx.compose(g1, g2)<EOL>

the QUBO for k-coloring a graph A is as follows:

variables:
x_{v,c} = 1 if vertex v of A gets color c; x_{v,c} = 0 otherwise

constraints:
1)  each v in A gets exactly one color.
   This constraint is enforced by including the term (\sum_c x_{v,c} - 1)^2 in the QUBO,
   which is minimized when \sum_c x_{v,c} = 1.

2) If u and v in A are adjacent, then they get different colors.
   This constraint is enforced by including terms x_{v,c} x_{u,c} in the QUBO,
   which is minimzed when at most one of u and v get color c.

Total QUBO:
Q(x) = \sum_v (\sum_c x_{v,c} - 1)^2  + \sum_{u ~ v} \sum_c x_{v,c} x_{u,c}

The graph of interactions for this QUBO consists of cliques of size k (with vertices {x_{v,c} for c = 0,...,k-1})
plus k disjoint copies of the graph A (one for each color).


def chimera_blocks(M=<NUM_LIT:16>, N=<NUM_LIT:16>, L=<NUM_LIT:4>):

for x in xrange(M):<EOL><INDENT>for y in xrange(N):<EOL><INDENT>for u in (<NUM_LIT:0>, <NUM_LIT:1>):<EOL><INDENT>yield tuple((x, y, u, k) for k in xrange(L))<EOL><DEDENT><DEDENT><DEDENT>

Generator for blocks for a chimera block quotient


from networkx import Graph<EOL>from itertools import product<EOL>BG = Graph()<EOL>blockid = {}<EOL>for i, b in enumerate(blocks):<EOL><INDENT>BG.add_node(i)<EOL>if not b or not all(G.has_node(x) for x in b):<EOL><INDENT>continue<EOL><DEDENT>for q in b:<EOL><INDENT>if q in blockid:<EOL><INDENT>raise(RuntimeError, "<STR_LIT>")<EOL><DEDENT>blockid[q] = i<EOL><DEDENT><DEDENT>for q, u in blockid.items():<EOL><INDENT>ublock = blocks[u]<EOL>for p in G[q]:<EOL><INDENT>if p not in blockid:<EOL><INDENT>continue<EOL><DEDENT>v = blockid[p]<EOL>if BG.has_edge(u, v) or u == v:<EOL><INDENT>continue<EOL><DEDENT>vblock = blocks[v]<EOL>if ublock[<NUM_LIT:0>][<NUM_LIT:2>] == vblock[<NUM_LIT:0>][<NUM_LIT:2>]:<EOL><INDENT>block_edges = zip(ublock, vblock)<EOL><DEDENT>else:<EOL><INDENT>block_edges = product(ublock, vblock)<EOL><DEDENT>if all(G.has_edge(x, y) for x, y in block_edges):<EOL><INDENT>BG.add_edge(u, v)<EOL><DEDENT><DEDENT><DEDENT>return BG<EOL>

Extract the blocks from a graph, and returns a
block-quotient graph according to the acceptability
functions block_good and eblock_good

Inputs:
    G: a networkx graph
    blocks: a tuple of tuples


def embed_with_quotient(source_graph, target_graph, M=<NUM_LIT:16>, N=<NUM_LIT:16>, L=<NUM_LIT:4>, **args):

from random import sample<EOL>blocks = list(chimera_blocks(M, N, L))<EOL>BG = chimera_block_quotient(target_graph, blocks)<EOL>ublocks = {block: (block[<NUM_LIT:0>][<NUM_LIT:2>], i)<EOL>for (i, block) in enumerate(blocks) if BG.has_node(i)}<EOL>source_e = list(source_graph.edges())<EOL>source_n = {x for e in source_e for x in e}<EOL>fabric_e = list(BG.edges())<EOL>fix_chains = {}<EOL>for z in source_n:<EOL><INDENT>for u in (<NUM_LIT:0>, <NUM_LIT:1>):<EOL><INDENT>source_e.append(((z, u), z))<EOL>fix_chains[z, u] = [(z, u)]<EOL><DEDENT>for u, i in ublocks.values():<EOL><INDENT>fabric_e.append(((z, u), i))<EOL><DEDENT><DEDENT>embs = filter(None, [find_embedding(source_e, fabric_e,<EOL>fixed_chains=fix_chains,<EOL>chainlength_patience=<NUM_LIT:0>,<EOL>**args) for _ in range(<NUM_LIT:10>)])<EOL>emb = min(embs, key=lambda e: sorted((len(c)<EOL>for c in e.values()), reverse=True))<EOL>for _ in range(<NUM_LIT:10>):<EOL><INDENT>emb = find_embedding(source_e, fabric_e,<EOL>fixed_chains=fix_chains,<EOL>initial_chains=emb,<EOL>chainlength_patience=<NUM_LIT:3>,<EOL>skip_initialization=True,<EOL>**args)<EOL><DEDENT>newemb = {}<EOL>for v in source_n:<EOL><INDENT>for k in range(L):<EOL><INDENT>newemb[v, k] = [blocks[i][k] for i in emb[v]]<EOL><DEDENT><DEDENT>return newemb<EOL>

Produce an embedding in target_graph suitable to
check if source_graph is 4-colorable.  More generally,
if target_graph is a (M,N,L) Chimera subgraph, the
test is for L-colorability.  This depends heavily upon
the Chimera structure

Inputs:
    source_graph, target_graph: networkx graphs
    M,N,L: integers defining the base chimera topology

Outputs:
    emb: a dictionary mapping (v,i)


return self.error is None<EOL>


return MockSailthruError(self.error, self.code)<EOL>


return self.error<EOL>


return self.code<EOL>


def mock_ecommerce_api(self, body, course_id, status=<NUM_LIT:200>):

Mock GET requests to the ecommerce course API endpoint.


return {<EOL>"<STR_LIT:id>": course_id,<EOL>"<STR_LIT:url>": "<STR_LIT>".format(course_id),<EOL>"<STR_LIT:name>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT:type>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>".format(course_id),<EOL>"<STR_LIT>": "<STR_LIT>"<EOL>}<EOL>


send_course_refund_email(<EOL>'<STR_LIT>', self.REFUND_ID, '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', None<EOL>)<EOL>

Execute the send_course_refund_email task.


def mock_api_response(self, status, body):

httpretty.register_uri(<EOL>httpretty.POST,<EOL>'<STR_LIT>',<EOL>status=status,<EOL>body=json.dumps(body),<EOL>content_type='<STR_LIT:application/json>'<EOL>)<EOL>


send_offer_assignment_email(**self.ASSIGNMENT_TASK_KWARGS)<EOL>

Execute the send_offer_assignment_email task.


def mock_ecommerce_assignmentemail_api(self, body, status=<NUM_LIT:200>):

Mock POST requests to the ecommerce assignmentemail API endpoint.


def assert_get_sailthru_client_raises(self, exc_class, config):

overrides = {<EOL>self.SITE_CODE: {<EOL>'<STR_LIT>': config<EOL>}<EOL>}<EOL>with mock.patch.dict(self.SITE_OVERRIDES_MODULE, overrides):<EOL><INDENT>with self.assertRaises(exc_class):<EOL><INDENT>get_sailthru_client(self.SITE_CODE)<EOL><DEDENT><DEDENT>

Asserts an error is raised by a call to get_sailthru_client.


raise self.retry(countdown=config.get('<STR_LIT>'),<EOL>max_retries=config.get('<STR_LIT>'))<EOL>


def _build_purchase_item(course_id, course_url, cost_in_cents, mode, course_data, sku):

<EOL>item = {<EOL>'<STR_LIT:id>': "<STR_LIT>".format(course_id, mode),<EOL>'<STR_LIT:url>': course_url,<EOL>'<STR_LIT>': cost_in_cents,<EOL>'<STR_LIT>': <NUM_LIT:1>,<EOL>}<EOL>if '<STR_LIT:title>' in course_data:<EOL><INDENT>item['<STR_LIT:title>'] = course_data['<STR_LIT:title>']<EOL><DEDENT>else:<EOL><INDENT>item['<STR_LIT:title>'] = '<STR_LIT>'.format(course_id, mode)<EOL><DEDENT>if '<STR_LIT>' in course_data:<EOL><INDENT>item['<STR_LIT>'] = course_data['<STR_LIT>']<EOL><DEDENT>item['<STR_LIT>'] = dict(course_data.get('<STR_LIT>', {}), mode=mode, course_run_id=course_id)<EOL>item['<STR_LIT>']['<STR_LIT>'] = sku<EOL>return item<EOL>

Build and return Sailthru purchase item object


def _record_purchase(sailthru_client, email, item, purchase_incomplete, message_id, options):

try:<EOL><INDENT>sailthru_response = sailthru_client.purchase(email, [item],<EOL>incomplete=purchase_incomplete, message_id=message_id,<EOL>options=options)<EOL>if not sailthru_response.is_ok():<EOL><INDENT>error = sailthru_response.get_error()<EOL>logger.error("<STR_LIT>", error.get_message())<EOL>return not can_retry_sailthru_request(error)<EOL><DEDENT><DEDENT>except SailthruClientError as exc:<EOL><INDENT>logger.exception("<STR_LIT>", email, text_type(exc))<EOL>return False<EOL><DEDENT>return True<EOL>

Record a purchase in Sailthru

    Arguments:
        sailthru_client (object): SailthruClient
        email (str): user's email address
        item (dict): Sailthru required information about the course
        purchase_incomplete (boolean): True if adding item to shopping cart
        message_id (str): Cookie used to identify marketing campaign
        options (dict): Sailthru purchase API options (e.g. template name)

    Returns:
        False if retryable error, else True


def _get_course_content(course_id, course_url, sailthru_client, site_code, config):

<EOL>cache_key = "<STR_LIT>".format(site_code, course_url)<EOL>response = cache.get(cache_key)<EOL>if not response:<EOL><INDENT>try:<EOL><INDENT>sailthru_response = sailthru_client.api_get("<STR_LIT:content>", {"<STR_LIT:id>": course_url})<EOL>if not sailthru_response.is_ok():<EOL><INDENT>response = {}<EOL><DEDENT>else:<EOL><INDENT>response = sailthru_response.json<EOL>cache.set(cache_key, response, config.get('<STR_LIT>'))<EOL><DEDENT><DEDENT>except SailthruClientError:<EOL><INDENT>response = {}<EOL><DEDENT>if not response:<EOL><INDENT>logger.error('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>response = _get_course_content_from_ecommerce(course_id, site_code=site_code)<EOL>if response:<EOL><INDENT>cache.set(cache_key, response, config.get('<STR_LIT>'))<EOL><DEDENT><DEDENT><DEDENT>return response<EOL>

Get course information using the Sailthru content api or from cache.

    If there is an error, just return with an empty response.

    Arguments:
        course_id (str): course key of the course
        course_url (str): LMS url for course info page.
        sailthru_client (object): SailthruClient
        site_code (str): site code
        config (dict): config options

    Returns:
        course information from Sailthru


api = get_ecommerce_client(site_code=site_code)<EOL>try:<EOL><INDENT>api_response = api.courses(course_id).get()<EOL><DEDENT>except Exception:  <EOL><INDENT>logger.exception(<EOL>'<STR_LIT>',<EOL>course_id,<EOL>exc_info=True<EOL>)<EOL>return {}<EOL><DEDENT>return {<EOL>'<STR_LIT:title>': api_response.get('<STR_LIT:name>'),<EOL>'<STR_LIT>': api_response.get('<STR_LIT>')<EOL>}<EOL>

Get course information using the Ecommerce course api.

In case of error returns empty response.
Arguments:
    course_id (str): course key of the course
    site_code (str): site code

Returns:
    course information from Ecommerce


def _update_unenrolled_list(sailthru_client, email, course_url, unenroll):

try:<EOL><INDENT>sailthru_response = sailthru_client.api_get("<STR_LIT:user>", {"<STR_LIT:id>": email, "<STR_LIT>": {"<STR_LIT>": <NUM_LIT:1>}})<EOL>if not sailthru_response.is_ok():<EOL><INDENT>error = sailthru_response.get_error()<EOL>logger.error("<STR_LIT>", error.get_message())<EOL>return not can_retry_sailthru_request(error)<EOL><DEDENT>response_json = sailthru_response.json<EOL>unenroll_list = []<EOL>if response_json and "<STR_LIT>" in response_json and response_json["<STR_LIT>"]and "<STR_LIT>" in response_json["<STR_LIT>"]:<EOL><INDENT>unenroll_list = response_json["<STR_LIT>"]["<STR_LIT>"]<EOL><DEDENT>changed = False<EOL>if unenroll:<EOL><INDENT>if course_url not in unenroll_list:<EOL><INDENT>unenroll_list.append(course_url)<EOL>changed = True<EOL><DEDENT><DEDENT>elif course_url in unenroll_list:<EOL><INDENT>unenroll_list.remove(course_url)<EOL>changed = True<EOL><DEDENT>if changed:<EOL><INDENT>sailthru_response = sailthru_client.api_post(<EOL>'<STR_LIT:user>', {'<STR_LIT:id>': email, '<STR_LIT:key>': '<STR_LIT:email>', '<STR_LIT>': {'<STR_LIT>': unenroll_list}})<EOL>if not sailthru_response.is_ok():<EOL><INDENT>error = sailthru_response.get_error()<EOL>logger.error("<STR_LIT>", error.get_message())<EOL>return not can_retry_sailthru_request(error)<EOL><DEDENT><DEDENT>return True<EOL><DEDENT>except SailthruClientError as exc:<EOL><INDENT>logger.exception("<STR_LIT>", email, text_type(exc))<EOL>return False<EOL><DEDENT>

Maintain a list of courses the user has unenrolled from in the Sailthru user record

    Arguments:
        sailthru_client (object): SailthruClient
        email (str): user's email address
        course_url (str): LMS url for course info page.
        unenroll (boolean): True if unenrolling, False if enrolling

    Returns:
        False if retryable error, else True


code = error.get_error_code()<EOL>return code in (<NUM_LIT:9>, <NUM_LIT>)<EOL>

Returns True if a Sailthru request and be re-submitted after an error has occurred.

    Responses with the following codes can be retried:
         9: Internal Error
        43: Too many [type] requests this minute to /[endpoint] API

    All other errors are considered failures, that should not be retried. A complete list of error codes is available at
    https://getstarted.sailthru.com/new-for-developers-overview/api/api-response-errors/.

    Args:
        error (SailthruResponseError)

    Returns:
        bool: Indicates if the original request can be retried.


@shared_task(bind=True, ignore_result=True)<EOL>def update_course_enrollment(self, email, course_url, purchase_incomplete, mode, unit_cost=None, course_id=None,<EOL>currency=None, message_id=None, site_code=None, sku=None):

<EOL>config = get_sailthru_configuration(site_code)<EOL>try:<EOL><INDENT>sailthru_client = get_sailthru_client(site_code)<EOL><DEDENT>except SailthruError:<EOL><INDENT>return<EOL><DEDENT>new_enroll = False<EOL>send_template = None<EOL>if not purchase_incomplete:<EOL><INDENT>if mode == '<STR_LIT>':<EOL><INDENT>send_template = config.get('<STR_LIT>')<EOL><DEDENT>elif mode == '<STR_LIT>' or mode == '<STR_LIT>':<EOL><INDENT>new_enroll = True<EOL>send_template = config.get('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>new_enroll = True<EOL>send_template = config.get('<STR_LIT>')<EOL><DEDENT><DEDENT>cost_in_cents = int(unit_cost * <NUM_LIT:100>)<EOL>if new_enroll:<EOL><INDENT>if not _update_unenrolled_list(sailthru_client, email, course_url, False):<EOL><INDENT>schedule_retry(self, config)<EOL><DEDENT><DEDENT>course_data = _get_course_content(course_id, course_url, sailthru_client, site_code, config)<EOL>item = _build_purchase_item(course_id, course_url, cost_in_cents, mode, course_data, sku)<EOL>options = {}<EOL>if purchase_incomplete and config.get('<STR_LIT>'):<EOL><INDENT>options['<STR_LIT>'] = config.get('<STR_LIT>')<EOL>options['<STR_LIT>'] = "<STR_LIT>".format(config.get('<STR_LIT>'))<EOL><DEDENT>if send_template:<EOL><INDENT>options['<STR_LIT>'] = send_template<EOL><DEDENT>if not _record_purchase(sailthru_client, email, item, purchase_incomplete, message_id, options):<EOL><INDENT>schedule_retry(self, config)<EOL><DEDENT>

Adds/updates Sailthru when a user adds to cart/purchases/upgrades a course

     Args:
        email(str): The user's email address
        course_url(str): Course home page url
        purchase_incomplete(boolean): True if adding to cart
        mode(string): enroll mode (audit, verification, ...)
        unit_cost(decimal): cost if purchase event
        course_id(CourseKey): course id
        currency(str): currency if purchase event - currently ignored since Sailthru only supports USD
        message_id(str): value from Sailthru marketing campaign cookie
        site_code(str): site code

    Returns:
        None


@shared_task(bind=True, ignore_result=True)<EOL>def send_course_refund_email(self, email, refund_id, amount, course_name, order_number, order_url, site_code=None):

config = get_sailthru_configuration(site_code)<EOL>try:<EOL><INDENT>sailthru_client = get_sailthru_client(site_code)<EOL><DEDENT>except SailthruError:<EOL><INDENT>return<EOL><DEDENT>email_vars = {<EOL>'<STR_LIT>': amount,<EOL>'<STR_LIT>': course_name,<EOL>'<STR_LIT>': order_number,<EOL>'<STR_LIT>': order_url,<EOL>}<EOL>try:<EOL><INDENT>response = sailthru_client.send(<EOL>template=config['<STR_LIT>']['<STR_LIT>'],<EOL>email=email,<EOL>_vars=email_vars<EOL>)<EOL><DEDENT>except SailthruClientError:<EOL><INDENT>logger.exception(<EOL>'<STR_LIT>',<EOL>refund_id<EOL>)<EOL>return<EOL><DEDENT>if response.is_ok():<EOL><INDENT>logger.info('<STR_LIT>', refund_id)<EOL><DEDENT>else:<EOL><INDENT>error = response.get_error()<EOL>logger.error(<EOL>'<STR_LIT>',<EOL>refund_id, error.get_error_code(), error.get_message()<EOL>)<EOL>if can_retry_sailthru_request(error):<EOL><INDENT>logger.info(<EOL>'<STR_LIT>',<EOL>refund_id<EOL>)<EOL>schedule_retry(self, config)<EOL><DEDENT>else:<EOL><INDENT>logger.warning(<EOL>'<STR_LIT>',<EOL>refund_id<EOL>)<EOL><DEDENT><DEDENT>

Sends the course refund email.

    Args:
        self: Ignore.
        email (str): Recipient's email address.
        refund_id (int): ID of the refund that initiated this task.
        amount (str): Formatted amount of the refund.
        course_name (str): Name of the course for which payment was refunded.
        order_number (str): Order number of the order that was refunded.
        order_url (str): Receipt URL of the refunded order.
        site_code (str): Identifier of the site sending the email.


@shared_task(bind=True, ignore_result=True)<EOL>def send_offer_assignment_email(self, user_email, offer_assignment_id, subject, email_body, site_code=None):

config = get_sailthru_configuration(site_code)<EOL>response = _send_offer_assignment_notification_email(config, user_email, subject, email_body, site_code, self)<EOL>if response and response.is_ok():<EOL><INDENT>send_id = response.get_body().get('<STR_LIT>')  <EOL>if _update_assignment_email_status(offer_assignment_id, send_id, '<STR_LIT:success>'):<EOL><INDENT>logger.info('<STR_LIT>'.format(<EOL>message=email_body))<EOL><DEDENT>else:<EOL><INDENT>logger.exception(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(<EOL>token_offer=offer_assignment_id,<EOL>token_email=user_email,<EOL>)<EOL>)<EOL><DEDENT><DEDENT>

Sends the offer assignment email.
    Args:
        self: Ignore.
        user_email (str): Recipient's email address.
        offer_assignment_id (str): Key of the entry in the offer_assignment model.
        subject (str): Email subject.
        email_body (str): The body of the email.
        site_code (str): Identifier of the site sending the email.


def _send_offer_assignment_notification_email(config, user_email, subject, email_body, site_code, task):

Handles sending offer assignment notification emails and retrying failed emails when appropriate.


def _update_assignment_email_status(offer_assignment_id, send_id, status, site_code=None):

api = get_ecommerce_client(url_postfix='<STR_LIT>', site_code=site_code)<EOL>post_data = {<EOL>'<STR_LIT>': offer_assignment_id,<EOL>'<STR_LIT>': send_id,<EOL>'<STR_LIT:status>': status,<EOL>}<EOL>try:<EOL><INDENT>api_response = api.status().post(post_data)<EOL><DEDENT>except RequestException:<EOL><INDENT>logger.exception(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(<EOL>token_offer=offer_assignment_id,<EOL>token_send_id=send_id<EOL>)<EOL>)<EOL>return False<EOL><DEDENT>return True if api_response.get('<STR_LIT:status>') == '<STR_LIT>' else False<EOL>

Update the offer_assignment and offer_assignment_email model using the Ecommerce assignmentemail api.
Arguments:
    offer_assignment_id (str): Key of the entry in the offer_assignment model.
    send_id (str): Unique message id from Sailthru
    status (str): status to be sent to the api
    site_code (str): site code
Returns:
    True or False based on model update status from Ecommerce api


@shared_task(bind=True, ignore_result=True)<EOL>def send_offer_update_email(self, user_email, subject, email_body, site_code=None):

config = get_sailthru_configuration(site_code)<EOL>_send_offer_assignment_notification_email(config, user_email, subject, email_body, site_code, self)<EOL>

Sends the offer emails after assignment, either for revoking or reminding.
    Args:
        self: Ignore.
        user_email (str): Recipient's email address.
        subject (str): Email subject.
        email_body (str): The body of the email.
        site_code (str): Identifier of the site sending the email.


config = get_configuration('<STR_LIT>', site_code=site_code)<EOL>return config<EOL>

Returns the Sailthru configuration for the specified site.


<EOL>config = get_sailthru_configuration(site_code)<EOL>if not config.get('<STR_LIT>'):<EOL><INDENT>msg = '<STR_LIT>'.format(site_code)<EOL>log.debug(msg)<EOL>raise SailthruNotEnabled(msg)<EOL><DEDENT>key = config.get('<STR_LIT>')<EOL>secret = config.get('<STR_LIT>')<EOL>if not (key and secret):<EOL><INDENT>msg = '<STR_LIT>'.format(site_code)<EOL>log.error(msg)<EOL>raise ConfigurationError(msg)<EOL><DEDENT>return SailthruClient(key, secret)<EOL>

Returns a Sailthru client for the specified site.

Args:
    site_code (str): Site for which the client should be configured.

Returns:
    SailthruClient

Raises:
    SailthruNotEnabled: If Sailthru is not enabled for the specified site.
    ConfigurationError: If either the Sailthru API key or secret are not set for the site.


lock.acquire()<EOL>try:<EOL><INDENT>if key not in self:<EOL><INDENT>return None<EOL><DEDENT>current_time = time.time()<EOL>if self[key].expire > current_time:<EOL><INDENT>return self[key].value<EOL><DEDENT>deletes = []<EOL>for k, val in self.items():<EOL><INDENT>if val.expire <= current_time:<EOL><INDENT>deletes.append(k)<EOL><DEDENT><DEDENT>for k in deletes:<EOL><INDENT>del self[k]<EOL><DEDENT>return None<EOL><DEDENT>finally:<EOL><INDENT>lock.release()<EOL><DEDENT>

Get an object from the cache

        Arguments:
            key (str): Cache key

        Returns:
            Cached object


lock.acquire()<EOL>try:<EOL><INDENT>self[key] = CacheObject(value, duration)<EOL><DEDENT>finally:<EOL><INDENT>lock.release()<EOL><DEDENT>

Save an object in the cache

        Arguments:
            key (str): Cache key
            value (object): object to cache
            duration (int): time in seconds to keep object in cache


def _timeout_body(self, request, uri, headers):

raise exceptions.Timeout<EOL>

Helper used to force httpretty to raise Timeout exceptions.


def _retry_order(self, exception, max_fulfillment_retries, order_number):

retries = self.request.retries<EOL>if retries == max_fulfillment_retries:<EOL><INDENT>logger.exception('<STR_LIT>', order_number)<EOL><DEDENT>else:<EOL><INDENT>logger.warning('<STR_LIT>', order_number)<EOL><DEDENT>countdown = <NUM_LIT:2> ** retries<EOL>raise self.retry(exc=exception, countdown=countdown, max_retries=max_fulfillment_retries)<EOL>

Retry with exponential backoff until fulfillment
succeeds or the retry limit is reached. If the retry limit is exceeded,
the exception is re-raised.


@shared_task(bind=True, ignore_result=True)<EOL>def fulfill_order(self, order_number, site_code=None, email_opt_in=False):

max_fulfillment_retries = get_configuration('<STR_LIT>', site_code=site_code)<EOL>api = get_ecommerce_client(site_code=site_code)<EOL>try:<EOL><INDENT>logger.info('<STR_LIT>', order_number)<EOL>api.orders(order_number).fulfill.put(email_opt_in=email_opt_in)<EOL><DEDENT>except exceptions.HttpClientError as exc:<EOL><INDENT>status_code = exc.response.status_code  <EOL>if status_code == <NUM_LIT>:<EOL><INDENT>logger.info('<STR_LIT>', order_number)<EOL>raise Ignore()<EOL><DEDENT>else:<EOL><INDENT>logger.warning(<EOL>'<STR_LIT>',<EOL>order_number,<EOL>exc_info=True<EOL>)<EOL>_retry_order(self, exc, max_fulfillment_retries, order_number)<EOL><DEDENT><DEDENT>except (exceptions.HttpServerError, exceptions.Timeout, SSLError) as exc:<EOL><INDENT>_retry_order(self, exc, max_fulfillment_retries, order_number)<EOL><DEDENT>

Fulfills an order.

    Arguments:
        order_number (str): Order number indicating which order to fulfill.

    Returns:
        None


filename = os.environ.get(variable)<EOL>if filename is None:<EOL><INDENT>msg = '<STR_LIT>'.format(variable)<EOL>raise EnvironmentError(msg)<EOL><DEDENT>return filename<EOL>

Get the name of the file containing configuration overrides
from the provided environment variable.


<EOL>if local_loglevel not in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>local_loglevel = '<STR_LIT>'<EOL><DEDENT>hostname = platform.node().split('<STR_LIT:.>')[<NUM_LIT:0>]<EOL>syslog_format = (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>).format(<EOL>service_variant=service_variant,<EOL>logging_env=logging_env, hostname=hostname<EOL>)<EOL>if debug:<EOL><INDENT>handlers = ['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>handlers = ['<STR_LIT>']<EOL><DEDENT>logger_config = {<EOL>'<STR_LIT:version>': <NUM_LIT:1>,<EOL>'<STR_LIT>': False,<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': '<STR_LIT>'<EOL>'<STR_LIT>',<EOL>},<EOL>'<STR_LIT>': {'<STR_LIT>': syslog_format},<EOL>'<STR_LIT>': {'<STR_LIT>': '<STR_LIT>'},<EOL>},<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': '<STR_LIT>' if debug else '<STR_LIT>',<EOL>'<STR_LIT:class>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': sys.stdout,<EOL>},<EOL>},<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': handlers,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': True<EOL>},<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': handlers,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': False<EOL>},<EOL>}<EOL>}<EOL>if dev_env:<EOL><INDENT>edx_file_loc = os.path.join(log_dir, edx_filename)<EOL>logger_config['<STR_LIT>'].update({<EOL>'<STR_LIT>': {<EOL>'<STR_LIT:class>': '<STR_LIT>',<EOL>'<STR_LIT>': local_loglevel,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:filename>': edx_file_loc,<EOL>'<STR_LIT>': <NUM_LIT> * <NUM_LIT> * <NUM_LIT:2>,<EOL>'<STR_LIT>': <NUM_LIT:5>,<EOL>},<EOL>})<EOL><DEDENT>else:<EOL><INDENT>logger_config['<STR_LIT>'].update({<EOL>'<STR_LIT>': {<EOL>'<STR_LIT>': local_loglevel,<EOL>'<STR_LIT:class>': '<STR_LIT>',<EOL>'<STR_LIT:address>': '<STR_LIT>' if sys.platform == '<STR_LIT>' else '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': SysLogHandler.LOG_LOCAL0,<EOL>},<EOL>})<EOL><DEDENT>return logger_config<EOL>

Returns a dictionary containing logging configuration.

If dev_env is True, logging will not be done via local rsyslogd.
Instead, application logs will be dropped into log_dir. 'edx_filename'
is ignored unless dev_env is True.


name = os.environ.get(CONFIGURATION_MODULE)<EOL>__import__(name)<EOL>module = sys.modules[name]<EOL>setting_value = getattr(module, variable, None)<EOL>site_overrides = getattr(module, '<STR_LIT>', None)<EOL>if site_overrides and site_code is not None:<EOL><INDENT>site_specific_overrides = site_overrides.get(site_code)<EOL>if site_specific_overrides:<EOL><INDENT>override_value = site_specific_overrides.get(variable)<EOL>if override_value:<EOL><INDENT>setting_value = override_value<EOL><DEDENT><DEDENT><DEDENT>if setting_value is None:<EOL><INDENT>raise RuntimeError('<STR_LIT>'.format(variable, module))<EOL><DEDENT>return setting_value<EOL>

Get a value from configuration.

Retrieves the value corresponding to the given variable from the configuration module
currently in use by the app.  Specify a site_code value to check for a site-specific override.

Arguments:
    variable (str): The name of a variable from the configuration module.

Keyword Arguments:
    site_code (str): The SITE_OVERRIDES key to inspect for site-specific values

Returns:
    The value corresponding to the variable, or None if the variable is not found.


ecommerce_api_root = get_configuration('<STR_LIT>', site_code=site_code)<EOL>signing_key = get_configuration('<STR_LIT>', site_code=site_code)<EOL>issuer = get_configuration('<STR_LIT>', site_code=site_code)<EOL>service_username = get_configuration('<STR_LIT>', site_code=site_code)<EOL>return EdxRestApiClient(<EOL>ecommerce_api_root + url_postfix, signing_key=signing_key, issuer=issuer, username=service_username)<EOL>

Get client for fetching data from ecommerce API.
Arguments:
    site_code (str): (Optional) The SITE_OVERRIDES key to inspect for site-specific values
    url_postfix (str): (Optional) The URL postfix value to append to the ECOMMERCE_API_ROOT value.

Returns:
    EdxRestApiClient object


def enrichment_score_tensor(gene_mat, cor_mat, gene_sets, weighted_score_type, nperm=<NUM_LIT:1000>,<EOL>scale=False, single=False, rs=np.random.RandomState()):

<EOL>keys = sorted(gene_sets.keys())<EOL>if weighted_score_type == <NUM_LIT:0>:<EOL><INDENT>cor_mat = np.ones(cor_mat.shape)<EOL><DEDENT>elif weighted_score_type > <NUM_LIT:0>:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>logging.error("<STR_LIT>")<EOL>sys.exit(<NUM_LIT:0>)<EOL><DEDENT>cor_mat = np.abs(cor_mat)<EOL>if cor_mat.ndim ==<NUM_LIT:1>:<EOL><INDENT>N, M = len(gene_mat), len(keys)<EOL>tag_indicator = np.vstack([np.in1d(gene_mat, gene_sets[key], assume_unique=True) for key in keys])<EOL>hit_ind = [ np.flatnonzero(tag).tolist() for tag in tag_indicator ]<EOL>perm_tag_tensor = np.repeat(tag_indicator, nperm+<NUM_LIT:1>).reshape((M,N,nperm+<NUM_LIT:1>))<EOL>if nperm: np.apply_along_axis(lambda x: np.apply_along_axis(rs.shuffle,<NUM_LIT:0>,x),<NUM_LIT:1>, perm_tag_tensor[:,:,:-<NUM_LIT:1>])<EOL>no_tag_tensor = <NUM_LIT:1> - perm_tag_tensor<EOL>rank_alpha = (perm_tag_tensor*cor_mat[np.newaxis,:,np.newaxis])** weighted_score_type<EOL><DEDENT>elif cor_mat.ndim == <NUM_LIT:2>:<EOL><INDENT>cor_mat, gene_mat = cor_mat.T, gene_mat.T<EOL>perm_tag_tensor = np.stack([np.isin(gene_mat, gene_sets[key]) for key in keys], axis=<NUM_LIT:0>)<EOL>hit_ind = [ np.flatnonzero(tag).tolist() for tag in perm_tag_tensor[:,:,-<NUM_LIT:1>] ]<EOL>no_tag_tensor = <NUM_LIT:1> - perm_tag_tensor<EOL>rank_alpha = (perm_tag_tensor*cor_mat[np.newaxis,:,:])** weighted_score_type<EOL><DEDENT>else:<EOL><INDENT>logging.error("<STR_LIT>")<EOL>sys.exit(<NUM_LIT:0>)<EOL><DEDENT>axis=<NUM_LIT:1><EOL>P_GW_denominator = np.sum(rank_alpha, axis=axis, keepdims=True)<EOL>P_NG_denominator = np.sum(no_tag_tensor, axis=axis, keepdims=True)<EOL>REStensor = np.cumsum(rank_alpha / P_GW_denominator - no_tag_tensor / P_NG_denominator, axis=axis)<EOL>if scale: REStensor = REStensor / len(gene_mat)<EOL>if single:<EOL><INDENT>esmatrix = np.sum(REStensor, axis=axis)<EOL><DEDENT>else:<EOL><INDENT>esmax, esmin = REStensor.max(axis=axis), REStensor.min(axis=axis)<EOL>esmatrix = np.where(np.abs(esmax)>np.abs(esmin), esmax, esmin)<EOL><DEDENT>es, esnull, RES = esmatrix[:,-<NUM_LIT:1>], esmatrix[:,:-<NUM_LIT:1>], REStensor[:,:,-<NUM_LIT:1>]<EOL>return es, esnull, hit_ind, RES<EOL>

Next generation algorithm of GSEA and ssGSEA.

    :param gene_mat:        the ordered gene list(vector) or gene matrix.
    :param cor_mat:         correlation vector or matrix  (e.g. signal to noise scores)
                            corresponding to the genes in the gene list or matrix.
    :param dict gene_sets:  gmt file dict.
    :param float weighted_score_type:     weighting by the correlation.
                            options: 0(classic), 1, 1.5, 2. default:1 for GSEA and 0.25 for ssGSEA.
    :param int nperm:       permutation times.
    :param bool scale:      If True, normalize the scores by number of genes_mat.
    :param bool single:     If True, use ssGSEA algorithm, otherwise use GSEA.
    :param rs:              Random state for initialize gene list shuffling.
                            Default: np.random.RandomState(seed=None)
    :return:
             ES: Enrichment score (real number between -1 and +1), it's true for ssGSEA, only scaled

             ESNULL: Enrichment score calculated from random permutation

             Hits_Indices: Indices of genes if genes are included in gene_set.

             RES: Numerical vector containing the running enrichment score for
                  all locations in the gene list .


def enrichr(gene_list, gene_sets, organism='<STR_LIT>', description='<STR_LIT>',<EOL>outdir='<STR_LIT>', background='<STR_LIT>', cutoff=<NUM_LIT>,<EOL>format='<STR_LIT>', figsize=(<NUM_LIT:8>,<NUM_LIT:6>), top_term=<NUM_LIT:10>, no_plot=False, verbose=False):

enr = Enrichr(gene_list, gene_sets, organism, description, outdir,<EOL>cutoff, background, format, figsize, top_term, no_plot, verbose)<EOL>enr.run()<EOL>return enr<EOL>

Enrichr API.

    :param gene_list: Flat file with list of genes, one gene id per row, or a python list object
    :param gene_sets: Enrichr Library to query. Required enrichr library name(s). Separate each name by comma.
    :param organism: Enrichr supported organism. Select from (human, mouse, yeast, fly, fish, worm).
                     see here for details: https://amp.pharm.mssm.edu/modEnrichr
    :param description: name of analysis. optional.
    :param outdir: Output file directory
    :param float cutoff: Adjusted P-value (benjamini-hochberg correction) cutoff. Default: 0.05
    :param int background: BioMart dataset name for retrieving background gene information.
                           This argument only works when gene_sets input is a gmt file or python dict.
                           You could also specify a number by yourself, e.g. total expressed genes number.
                           In this case, you will skip retrieving background infos from biomart.

    Use the code below to see valid background dataset names from BioMart.
    Here are example code:
    >>> from gseapy.parser import Biomart
    >>> bm = Biomart(verbose=False, host="asia.ensembl.org")
    >>> ## view validated marts
    >>> marts = bm.get_marts()
    >>> ## view validated dataset
    >>> datasets = bm.get_datasets(mart='ENSEMBL_MART_ENSEMBL')

    :param str format: Output figure format supported by matplotlib,('pdf','png','eps'...). Default: 'pdf'.
    :param list figsize: Matplotlib figsize, accept a tuple or list, e.g. (width,height). Default: (6.5,6).
    :param bool no_plot: If equals to True, no figure will be drawn. Default: False.
    :param bool verbose: Increase output verbosity, print out progress of your job, Default: False.

    :return: An Enrichr object, which obj.res2d stores your last query, obj.results stores your all queries.


self._outdir = self.outdir<EOL>if self._outdir is None:<EOL><INDENT>self._tmpdir = TemporaryDirectory()<EOL>self.outdir = self._tmpdir.name<EOL><DEDENT>elif isinstance(self.outdir, str):<EOL><INDENT>mkdirs(self.outdir)<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>"%type(self.outdir))<EOL><DEDENT>logfile = os.path.join(self.outdir, "<STR_LIT>" % (self.module, self.descriptions))<EOL>return logfile<EOL>


enrichr_library = self.get_libraries()<EOL>if isinstance(self.gene_sets, list):<EOL><INDENT>gss = self.gene_sets<EOL><DEDENT>elif isinstance(self.gene_sets, str):<EOL><INDENT>gss = [ g.strip() for g in self.gene_sets.strip().split("<STR_LIT:U+002C>") ]<EOL><DEDENT>elif isinstance(self.gene_sets, dict):<EOL><INDENT>gss = [self.gene_sets]<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>gss_exist = [] <EOL>for g in gss:<EOL><INDENT>if isinstance(g, dict): <EOL><INDENT>gss_exist.append(g)<EOL>continue<EOL><DEDENT>if isinstance(g, str): <EOL><INDENT>if g in enrichr_library: <EOL><INDENT>gss_exist.append(g)<EOL>continue<EOL><DEDENT>if g.lower().endswith("<STR_LIT>") and os.path.exists(g):<EOL><INDENT>self._logger.info("<STR_LIT>"%g)<EOL>with open(g) as genesets:<EOL><INDENT>g_dict = { line.strip().split("<STR_LIT:\t>")[<NUM_LIT:0>]: line.strip().split("<STR_LIT:\t>")[<NUM_LIT:2>:]<EOL>for line in genesets.readlines() }<EOL><DEDENT>gss_exist.append(g_dict)<EOL><DEDENT><DEDENT><DEDENT>return gss_exist<EOL>


if isinstance(self.gene_list, list):<EOL><INDENT>genes = self.gene_list<EOL><DEDENT>elif isinstance(self.gene_list, pd.DataFrame):<EOL><INDENT>if self.gene_list.shape[<NUM_LIT:1>] >=<NUM_LIT:3>:<EOL><INDENT>genes= self.gene_list.iloc[:,:<NUM_LIT:3>].apply(lambda x: "<STR_LIT:\t>".join([str(i) for i in x]), axis=<NUM_LIT:1>).tolist()<EOL><DEDENT>elif self.gene_list.shape[<NUM_LIT:1>] == <NUM_LIT:2>:<EOL><INDENT>genes= self.gene_list.apply(lambda x: "<STR_LIT:U+002C>".join([str(i) for i in x]), axis=<NUM_LIT:1>).tolist()<EOL><DEDENT>else:<EOL><INDENT>genes = self.gene_list.squeeze().tolist()<EOL><DEDENT><DEDENT>elif isinstance(self.gene_list, pd.Series):<EOL><INDENT>genes = self.gene_list.squeeze().tolist()<EOL><DEDENT>else:<EOL><INDENT>genes=[]<EOL>with open(self.gene_list) as f:<EOL><INDENT>for gene in f:<EOL><INDENT>genes.append(gene.strip())<EOL><DEDENT><DEDENT><DEDENT>self._isezid = all(map(self._is_entrez_id, genes))<EOL>if self._isezid: <EOL><INDENT>self._gls = set(map(int, self._gls))<EOL><DEDENT>else:<EOL><INDENT>self._gls = genes<EOL><DEDENT>return '<STR_LIT:\n>'.join(genes)<EOL>


payload = {<EOL>'<STR_LIT:list>': (None, gene_list),<EOL>'<STR_LIT:description>': (None, self.descriptions)<EOL>}<EOL>response = requests.post(url, files=payload)<EOL>if not response.ok:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>sleep(<NUM_LIT:1>)<EOL>job_id = json.loads(response.text)<EOL>return job_id<EOL>


def check_genes(self, gene_list, usr_list_id):

response = requests.get('<STR_LIT>' % usr_list_id)<EOL>if not response.ok:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>returnedL = json.loads(response.text)["<STR_LIT>"]<EOL>returnedN = sum([<NUM_LIT:1> for gene in gene_list if gene in returnedL])<EOL>self._logger.info('<STR_LIT>'.format(returnedN))<EOL>

Compare the genes sent and received to get successfully recognized genes


ADDLIST_URL = '<STR_LIT>'%self._organism<EOL>job_id = self.send_genes(gene_list, ADDLIST_URL)<EOL>user_list_id = job_id['<STR_LIT>']<EOL>RESULTS_URL = '<STR_LIT>'%self._organism<EOL>query_string = '<STR_LIT>'<EOL>s = retry(num=<NUM_LIT:5>)<EOL>filename = "<STR_LIT>" % (self._gs, self.descriptions)<EOL>url = RESULTS_URL + query_string % (user_list_id, filename, self._gs)<EOL>response = s.get(url, stream=True, timeout=None)<EOL>sleep(<NUM_LIT:1>)<EOL>res = pd.read_csv(StringIO(response.content.decode('<STR_LIT:utf-8>')),sep="<STR_LIT:\t>")<EOL>return [job_id['<STR_LIT>'], res]<EOL>


lib_url='<STR_LIT>'%self._organism<EOL>libs_json = json.loads(requests.get(lib_url).text)<EOL>libs = [lib['<STR_LIT>'] for lib in libs_json['<STR_LIT>']]<EOL>return sorted(libs)<EOL>

return active enrichr library name. Official API


<EOL>if os.path.isfile(self.background):<EOL><INDENT>with open(self.background) as b:<EOL><INDENT>bg2 = b.readlines() <EOL><DEDENT>bg = [g.strip() for g in bg2]  <EOL>return set(bg)<EOL><DEDENT>DB_FILE = resource_filename("<STR_LIT>", "<STR_LIT>".format(self.background))<EOL>filename = os.path.join(DEFAULT_CACHE_PATH, "<STR_LIT>".format(self.background))  <EOL>if os.path.exists(filename):<EOL><INDENT>df = pd.read_csv(filename,sep="<STR_LIT:\t>")<EOL><DEDENT>elif os.path.exists(DB_FILE):<EOL><INDENT>df = pd.read_csv(DB_FILE,sep="<STR_LIT:\t>")<EOL><DEDENT>else:<EOL><INDENT>self._logger.warning("<STR_LIT>"%self.background)<EOL>bm = Biomart()<EOL>df = bm.query(dataset=self.background)<EOL>df.dropna(subset=['<STR_LIT>'], inplace=True)<EOL><DEDENT>self._logger.info("<STR_LIT>")<EOL>df.dropna(subset=['<STR_LIT>'], inplace=True)     <EOL>if self._isezid:<EOL><INDENT>bg = df['<STR_LIT>'].astype(int)<EOL><DEDENT>else:<EOL><INDENT>bg = df['<STR_LIT>']<EOL><DEDENT>return set(bg)<EOL>


organism = {'<STR_LIT:default>': ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>','<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'],<EOL>'<STR_LIT>': ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'],<EOL>'<STR_LIT>': ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'],<EOL>'<STR_LIT>': ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'],<EOL>'<STR_LIT>': ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>}<EOL>for k, v in organism.items():<EOL><INDENT>if self.organism.lower() in v :<EOL><INDENT>self._organism = k<EOL><DEDENT><DEDENT>if self._organism is None:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>if self._organism == '<STR_LIT:default>':<EOL><INDENT>self._organism = '<STR_LIT>'<EOL><DEDENT>return<EOL>

Select Enrichr organism from below:

           Human & Mouse: H. sapiens & M. musculus
           Fly: D. melanogaster
           Yeast: S. cerevisiae
           Worm: C. elegans
           Fish: D. rerio


if isscalar(self.background):<EOL><INDENT>if isinstance(self.background, int) or self.background.isdigit():<EOL><INDENT>self._bg = int(self.background)<EOL><DEDENT>elif isinstance(self.background, str):<EOL><INDENT>self._bg = self.get_background()<EOL>self._logger.info("<STR_LIT>"%(len(self._bg)))<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>it = iter(self.background)<EOL>self._bg = set(self.background)<EOL><DEDENT>except TypeError:<EOL><INDENT>self._logger.error("<STR_LIT>")<EOL><DEDENT><DEDENT>hgtest = list(calc_pvalues(query=self._gls, gene_sets=gmt, <EOL>background=self._bg))<EOL>if len(hgtest) > <NUM_LIT:0>:<EOL><INDENT>terms, pvals, olsz, gsetsz, genes = hgtest<EOL>fdrs, rej = multiple_testing_correction(ps = pvals, <EOL>alpha=self.cutoff,<EOL>method='<STR_LIT>')<EOL>odict = OrderedDict()<EOL>odict['<STR_LIT>'] = terms<EOL>odict['<STR_LIT>'] = list(map(lambda h,g: "<STR_LIT>"%(h, g), olsz, gsetsz))<EOL>odict['<STR_LIT>'] = pvals<EOL>odict['<STR_LIT>'] = fdrs<EOL>odict['<STR_LIT>'] = ["<STR_LIT:;>".join(g) for g in genes]<EOL>res = pd.DataFrame(odict)<EOL>return res<EOL><DEDENT>return<EOL>

use local mode

        p = p-value computed using the Fisher exact test (Hypergeometric test)

        Not implemented here:

            combine score = log(p)·z

        see here: http://amp.pharm.mssm.edu/Enrichr/help#background&q=4

        columns contain:

            Term Overlap P-value Adjusted_P-value Genes


<EOL>self.get_organism()<EOL>genes_list = self.parse_genelists()<EOL>gss = self.parse_genesets()<EOL>self._logger.info("<STR_LIT>")<EOL>if len(gss) < <NUM_LIT:1>:<EOL><INDENT>sys.stderr.write("<STR_LIT>")<EOL>sys.stdout.write("<STR_LIT>")<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>self.results = pd.DataFrame()<EOL>for g in gss: <EOL><INDENT>if isinstance(g, dict): <EOL><INDENT>res = self.enrich(g)<EOL>shortID, self._gs = str(id(g)), "<STR_LIT>"%id(g)<EOL>if res is None: <EOL><INDENT>self._logger.info("<STR_LIT>"%shortID)<EOL>continue<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._gs = str(g)<EOL>self._logger.debug("<STR_LIT>" % (self._gs))<EOL>self._logger.info('<STR_LIT>' % (self.descriptions, self._gs))<EOL>shortID, res = self.get_results(genes_list)<EOL><DEDENT>res.insert(<NUM_LIT:0>, "<STR_LIT>", self._gs)<EOL>self.results = self.results.append(res, ignore_index=True, sort=True)<EOL>self.res2d = res<EOL>if self._outdir is None: continue<EOL>self._logger.info('<STR_LIT>' + str(shortID))<EOL>outfile = "<STR_LIT>" % (self.outdir, self._gs, self.descriptions, self.module)<EOL>self.res2d.to_csv(outfile, index=False, encoding='<STR_LIT:utf-8>', sep="<STR_LIT:\t>")<EOL>if not self.__no_plot:<EOL><INDENT>msg = barplot(df=res, cutoff=self.cutoff, figsize=self.figsize,<EOL>top_term=self.__top_term, color='<STR_LIT>',<EOL>title=self._gs,<EOL>ofname=outfile.replace("<STR_LIT>", self.format))<EOL>if msg is not None : self._logger.warning(msg)<EOL><DEDENT>self._logger.info('<STR_LIT>')<EOL><DEDENT>if self._outdir is None: self._tmpdir.cleanup()<EOL>return<EOL>

run enrichr for one sample gene list but multi-libraries


def enrichment_score(gene_list, correl_vector, gene_set, weighted_score_type=<NUM_LIT:1>, <EOL>nperm=<NUM_LIT:1000>, rs=np.random.RandomState(), single=False, scale=False):

N = len(gene_list)<EOL>tag_indicator = np.in1d(gene_list, gene_set, assume_unique=True).astype(int)  <EOL>if weighted_score_type == <NUM_LIT:0> :<EOL><INDENT>correl_vector = np.repeat(<NUM_LIT:1>, N)<EOL><DEDENT>else:<EOL><INDENT>correl_vector = np.abs(correl_vector)**weighted_score_type<EOL><DEDENT>hit_ind = np.flatnonzero(tag_indicator).tolist()<EOL>axis = <NUM_LIT:1><EOL>tag_indicator = np.tile(tag_indicator, (nperm+<NUM_LIT:1>,<NUM_LIT:1>))<EOL>correl_vector = np.tile(correl_vector,(nperm+<NUM_LIT:1>,<NUM_LIT:1>))<EOL>for i in range(nperm): rs.shuffle(tag_indicator[i])<EOL>Nhint = tag_indicator.sum(axis=axis, keepdims=True)<EOL>sum_correl_tag = np.sum(correl_vector*tag_indicator, axis=axis, keepdims=True)<EOL>no_tag_indicator = <NUM_LIT:1> - tag_indicator<EOL>Nmiss =  N - Nhint<EOL>norm_tag =  <NUM_LIT:1.0>/sum_correl_tag<EOL>norm_no_tag = <NUM_LIT:1.0>/Nmiss<EOL>RES = np.cumsum(tag_indicator * correl_vector * norm_tag - no_tag_indicator * norm_no_tag, axis=axis)<EOL>if scale: RES = RES / N<EOL>if single:<EOL><INDENT>es_vec = RES.sum(axis=axis)<EOL><DEDENT>else:<EOL><INDENT>max_ES, min_ES =  RES.max(axis=axis), RES.min(axis=axis)<EOL>es_vec = np.where(np.abs(max_ES) > np.abs(min_ES), max_ES, min_ES)<EOL><DEDENT>es, esnull, RES = es_vec[-<NUM_LIT:1>], es_vec[:-<NUM_LIT:1>], RES[-<NUM_LIT:1>,:]<EOL>return es, esnull, hit_ind, RES<EOL>

This is the most important function of GSEApy. It has the same algorithm with GSEA and ssGSEA.

    :param gene_list:       The ordered gene list gene_name_list, rank_metric.index.values
    :param gene_set:        gene_sets in gmt file, please use gsea_gmt_parser to get gene_set.
    :param weighted_score_type:  It's the same with gsea's weighted_score method. Weighting by the correlation
                            is a very reasonable choice that allows significant gene sets with less than perfect coherence.
                            options: 0(classic),1,1.5,2. default:1. if one is interested in penalizing sets for lack of
                            coherence or to discover sets with any type of nonrandom distribution of tags, a value p < 1
                            might be appropriate. On the other hand, if one uses sets with large number of genes and only
                            a small subset of those is expected to be coherent, then one could consider using p > 1.
                            Our recommendation is to use p = 1 and use other settings only if you are very experienced
                            with the method and its behavior.

    :param correl_vector:   A vector with the correlations (e.g. signal to noise scores) corresponding to the genes in
                            the gene list. Or rankings, rank_metric.values
    :param nperm:           Only use this parameter when computing esnull for statistical testing. Set the esnull value
                            equal to the permutation number.
    :param rs:              Random state for initializing gene list shuffling. Default: np.random.RandomState(seed=None)

    :return:

     ES: Enrichment score (real number between -1 and +1)

     ESNULL: Enrichment score calculated from random permutations.

     Hits_Indices: Index of a gene in gene_list, if gene is included in gene_set.

     RES: Numerical vector containing the running enrichment score for all locations in the gene list .


def enrichment_score_tensor(gene_mat, cor_mat, gene_sets, weighted_score_type, nperm=<NUM_LIT:1000>,<EOL>rs=np.random.RandomState(), single=False, scale=False):

<EOL>keys = sorted(gene_sets.keys())<EOL>if weighted_score_type == <NUM_LIT:0>:<EOL><INDENT>cor_mat = np.ones(cor_mat.shape)<EOL><DEDENT>elif weighted_score_type > <NUM_LIT:0>:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>logging.error("<STR_LIT>")<EOL>sys.exit(<NUM_LIT:0>)<EOL><DEDENT>cor_mat = np.abs(cor_mat)<EOL>if cor_mat.ndim ==<NUM_LIT:1>:<EOL><INDENT>N, M = len(gene_mat), len(keys)<EOL>tag_indicator = np.vstack([np.in1d(gene_mat, gene_sets[key], assume_unique=True) for key in keys])<EOL>tag_indicator = tag_indicator.astype(int)<EOL>hit_ind = [ np.flatnonzero(tag).tolist() for tag in tag_indicator ]<EOL>perm_tag_tensor = np.repeat(tag_indicator, nperm+<NUM_LIT:1>).reshape((M,N,nperm+<NUM_LIT:1>))<EOL>if nperm: np.apply_along_axis(lambda x: np.apply_along_axis(rs.shuffle,<NUM_LIT:0>,x),<NUM_LIT:1>, perm_tag_tensor[:,:,:-<NUM_LIT:1>])<EOL>no_tag_tensor = <NUM_LIT:1> - perm_tag_tensor<EOL>rank_alpha = (perm_tag_tensor*cor_mat[np.newaxis,:,np.newaxis])** weighted_score_type<EOL><DEDENT>elif cor_mat.ndim == <NUM_LIT:2>:<EOL><INDENT>cor_mat = cor_mat.T<EOL>genes, genes_ind = gene_mat<EOL>tag_indicator = np.vstack([np.in1d(genes, gene_sets[key], assume_unique=True) for key in keys])<EOL>tag_indicator = tag_indicator.astype(int)<EOL>perm_tag_tensor = np.stack([tag.take(genes_ind).T for tag in tag_indicator], axis=<NUM_LIT:0>)<EOL>hit_ind = [ np.flatnonzero(tag).tolist() for tag in perm_tag_tensor[:,:,-<NUM_LIT:1>] ]<EOL>no_tag_tensor = <NUM_LIT:1> - perm_tag_tensor<EOL>rank_alpha = (perm_tag_tensor*cor_mat[np.newaxis,:,:])** weighted_score_type<EOL><DEDENT>else:<EOL><INDENT>logging.error("<STR_LIT>")<EOL>sys.exit(<NUM_LIT:0>)<EOL><DEDENT>axis=<NUM_LIT:1><EOL>P_GW_denominator = np.sum(rank_alpha, axis=axis, keepdims=True)<EOL>P_NG_denominator = np.sum(no_tag_tensor, axis=axis, keepdims=True)<EOL>REStensor = np.cumsum(rank_alpha / P_GW_denominator - no_tag_tensor / P_NG_denominator, axis=axis)<EOL>if scale: REStensor = REStensor / len(gene_mat)<EOL>if single:<EOL><INDENT>esmatrix = REStensor.sum(axis=axis)<EOL><DEDENT>else:<EOL><INDENT>esmax, esmin = REStensor.max(axis=axis), REStensor.min(axis=axis)<EOL>esmatrix = np.where(np.abs(esmax)>np.abs(esmin), esmax, esmin)<EOL><DEDENT>es, esnull, RES = esmatrix[:,-<NUM_LIT:1>], esmatrix[:,:-<NUM_LIT:1>], REStensor[:,:,-<NUM_LIT:1>]<EOL>return es, esnull, hit_ind, RES<EOL>

Next generation algorithm of GSEA and ssGSEA.

        :param gene_mat:        the ordered gene list(vector) with or without gene indices matrix.
        :param cor_mat:         correlation vector or matrix  (e.g. signal to noise scores)
                                corresponding to the genes in the gene list or matrix.
        :param dict gene_sets:  gmt file dict.
        :param float weighted_score_type:     weighting by the correlation.
                                options: 0(classic), 1, 1.5, 2. default:1 for GSEA and 0.25 for ssGSEA.
        :param int nperm:       permutation times.
        :param bool scale:      If True, normalize the scores by number of genes_mat.
        :param bool single:     If True, use ssGSEA algorithm, otherwise use GSEA.
        :param rs:              Random state for initialize gene list shuffling.
                                Default: np.random.RandomState(seed=None)
        :return: a tuple contains::

                 | ES: Enrichment score (real number between -1 and +1), for ssGSEA, set scale eq to True.
                 | ESNULL: Enrichment score calculated from random permutation.
                 | Hits_Indices: Indices of genes if genes are included in gene_set.
                 | RES: The running enrichment score for all locations in the gene list.


def ranking_metric_tensor(exprs, method, permutation_num, pos, neg, classes,<EOL>ascending, rs=np.random.RandomState()):

<EOL>G, S = exprs.shape<EOL>expr_mat = exprs.values.T<EOL>perm_cor_tensor = np.tile(expr_mat, (permutation_num+<NUM_LIT:1>,<NUM_LIT:1>,<NUM_LIT:1>))<EOL>for arr in perm_cor_tensor[:-<NUM_LIT:1>]: rs.shuffle(arr)<EOL>classes = np.array(classes)<EOL>pos = classes == pos<EOL>neg = classes == neg<EOL>pos_cor_mean = perm_cor_tensor[:,pos,:].mean(axis=<NUM_LIT:1>)<EOL>neg_cor_mean = perm_cor_tensor[:,neg,:].mean(axis=<NUM_LIT:1>)<EOL>pos_cor_std = perm_cor_tensor[:,pos,:].std(axis=<NUM_LIT:1>, ddof=<NUM_LIT:1>)<EOL>neg_cor_std = perm_cor_tensor[:,neg,:].std(axis=<NUM_LIT:1>, ddof=<NUM_LIT:1>)<EOL>if method == '<STR_LIT>':<EOL><INDENT>cor_mat = (pos_cor_mean - neg_cor_mean)/(pos_cor_std + neg_cor_std)<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>denom = <NUM_LIT:1.0>/G<EOL>cor_mat = (pos_cor_mean - neg_cor_mean)/ np.sqrt(denom*pos_cor_std**<NUM_LIT:2> + denom*neg_cor_std**<NUM_LIT:2>)<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>cor_mat = pos_cor_mean / neg_cor_mean<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>cor_mat  = pos_cor_mean - neg_cor_mean<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>cor_mat  =  np.log2(pos_cor_mean / neg_cor_mean)<EOL><DEDENT>else:<EOL><INDENT>logging.error("<STR_LIT>")<EOL>sys.exit(<NUM_LIT:0>)<EOL><DEDENT>cor_mat_ind = cor_mat.argsort()<EOL>cor_mat.sort()<EOL>if ascending: return cor_mat_ind, cor_mat<EOL>return cor_mat_ind[:, ::-<NUM_LIT:1>], cor_mat[:, ::-<NUM_LIT:1>]<EOL>

Build shuffled ranking matrix when permutation_type eq to phenotype.

       :param exprs:   gene_expression DataFrame, gene_name indexed.
       :param str method:  calculate correlation or ranking. methods including:
                           1. 'signal_to_noise'.
                           2. 't_test'.
                           3. 'ratio_of_classes' (also referred to as fold change).
                           4. 'diff_of_classes'.
                           5. 'log2_ratio_of_classes'.
       :param int permuation_num: how many times of classes is being shuffled
       :param str pos: one of labels of phenotype's names.
       :param str neg: one of labels of phenotype's names.
       :param list classes:  a list of phenotype labels, to specify which column of
                             dataframe belongs to what class of phenotype.
       :param bool ascending:  bool. Sort ascending vs. descending.

       :return:
                returns two 2d ndarray with shape (nperm, gene_num).

                | cor_mat_indices: the indices of sorted and permutated (exclude last row) ranking matrix.
                | cor_mat: sorted and permutated (exclude last row) ranking matrix.


def ranking_metric(df, method, pos, neg, classes, ascending):

<EOL>df_mean = df.groupby(by=classes, axis=<NUM_LIT:1>).mean()<EOL>df_std =  df.groupby(by=classes, axis=<NUM_LIT:1>).std()<EOL>if method == '<STR_LIT>':<EOL><INDENT>ser = (df_mean[pos] - df_mean[neg])/(df_std[pos] + df_std[neg])<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>ser = (df_mean[pos] - df_mean[neg])/ np.sqrt(df_std[pos]**<NUM_LIT:2>/len(df_std)+df_std[neg]**<NUM_LIT:2>/len(df_std) )<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>ser = df_mean[pos] / df_mean[neg]<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>ser  = df_mean[pos] - df_mean[neg]<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>ser  =  np.log2(df_mean[pos] / df_mean[neg])<EOL><DEDENT>else:<EOL><INDENT>logging.error("<STR_LIT>")<EOL>sys.exit(<NUM_LIT:0>)<EOL><DEDENT>ser = ser.sort_values(ascending=ascending)<EOL>return ser<EOL>

The main function to rank an expression table.

       :param df:      gene_expression DataFrame.
       :param method:  The method used to calculate a correlation or ranking. Default: 'log2_ratio_of_classes'.
                       Others methods are:

                       1. 'signal_to_noise'

                          You must have at least three samples for each phenotype to use this metric.
                          The larger the signal-to-noise ratio, the larger the differences of the means (scaled by the standard deviations);
                          that is, the more distinct the gene expression is in each phenotype and the more the gene acts as a “class marker.”

                       2. 't_test'

                          Uses the difference of means scaled by the standard deviation and number of samples.
                          Note: You must have at least three samples for each phenotype to use this metric.
                          The larger the tTest ratio, the more distinct the gene expression is in each phenotype
                          and the more the gene acts as a “class marker.”

                       3. 'ratio_of_classes' (also referred to as fold change).

                          Uses the ratio of class means to calculate fold change for natural scale data.

                       4. 'diff_of_classes'

                          Uses the difference of class means to calculate fold change for natural scale data

                       5. 'log2_ratio_of_classes'

                          Uses the log2 ratio of class means to calculate fold change for natural scale data.
                          This is the recommended statistic for calculating fold change for log scale data.

       :param str pos: one of labels of phenotype's names.
       :param str neg: one of labels of phenotype's names.
       :param list classes:  a list of phenotype labels, to specify which column of dataframe belongs to what category of phenotype.
       :param bool ascending:  bool or list of bool. Sort ascending vs. descending.
       :return:

            returns a pd.Series of correlation to class of each variable. Gene_name is index, and value is rankings.

            visit here for more docs: http://software.broadinstitute.org/gsea/doc/GSEAUserGuideFrame.html