Example #1
1
def update_winapp2(url, hash_expected, append_text, cb_success):
    """Download latest winapp2.ini file.  Hash is sha512 or None to disable checks"""
    # first, determine whether an update is necessary
    from Common import personal_cleaners_dir

    fn = os.path.join(personal_cleaners_dir, "winapp2.ini")
    delete_current = False
    if os.path.exists(fn):
        f = open(fn, "r")
        hash_current = hashlib.sha512(f.read()).hexdigest()
        if not hash_expected or hash_current == hash_expected:
            # update is same as current
            return
        f.close()
        delete_current = True
    # download update
    opener = urllib2.build_opener()
    opener.addheaders = [("User-Agent", user_agent())]
    doc = opener.open(url).read()
    # verify hash
    hash_actual = hashlib.sha512(doc).hexdigest()
    if hash_expected and not hash_actual == hash_expected:
        raise RuntimeError("hash for %s actually %s instead of %s" % (url, hash_actual, hash_expected))
    # delete current
    if delete_current:
        from FileUtilities import delete

        delete(fn, True)
    # write file
    if not os.path.exists(personal_cleaners_dir):
        os.mkdir(personal_cleaners_dir)
    f = open(fn, "w")
    f.write(doc)
    append_text(_("New winapp2.ini was downloaded."))
    cb_success()
Example #2
1
def main():
    if len(sys.argv) != 5:
        PrintUsage()
        return

    apply_tag_exe = sys.argv[1]
    input_file = sys.argv[2]
    file_name = sys.argv[3]
    output_dir = sys.argv[4]

    if not os.path.exists(apply_tag_exe):
        print "Could not find applytag.exe"
        PrintUsage()
        return

    if not os.path.exists(file_name):
        print "Invalid filename %s" % file_name
        PrintUsage()
        return

    if not os.path.exists(input_file):
        print "Invalid directory %s" % input_file
        PrintUsage()
        return

    if not os.path.exists(output_dir):
        os.mkdir(output_dir)

    # Read in the installers.txt file.
    apps = ReadBundleInstallerFile(file_name)

    SetOutputFileNames(input_file, apps, output_dir)
    TagBinary(apps, input_file, apply_tag_exe)
Example #3
1
    def _validate_tmpdir(self):
        tmpdir = self.p.get_conf_or_none("mount", "tmpdir")
        if not tmpdir:
            raise InvalidConfig("mounttool is configured but there is no tmpdir configuration which is required")

        if not os.path.isabs(tmpdir):
            tmpdir = self.c.resolve_var_dir(tmpdir)

        if not os.path.exists(tmpdir):
            try:
                os.mkdir(tmpdir)
            except:
                exception_type = sys.exc_type
                try:
                    exceptname = exception_type.__name__
                except AttributeError:
                    exceptname = exception_type
                errstr = " - problem creating tmpdir '%s': %s: %s" % (tmpdir, str(exceptname), str(sys.exc_value))

                fullerrstr = (
                    "tmpdir does not have valid permissions and cannot be made to have valid permissions: '%s'" % tmpdir
                )
                fullerrstr += errstr
                self.c.log.error(fullerrstr)
                raise IncompatibleEnvironment(fullerrstr)

        if os.access(tmpdir, os.R_OK):
            self.c.log.debug("tmp directory (for mount tasks) is readable: %s" % tmpdir)
        else:
            raise IncompatibleEnvironment("tmp directory (for mount tasks) is not readable: %s" % tmpdir)

        self.tmpdir = tmpdir
def mkpath(outpath):
    pos_slash = [pos for pos, c in enumerate(outpath) if c == "/"]
    for pos in pos_slash:
        try:
            os.mkdir(outpath[:pos])
        except:
            pass
Example #5
1
 def _generate_xml(self):
     self.xml_filename = "%s-root-device.xml" % self.friendly_name
     self.xml_filename = self.xml_filename.replace(" ", "")
     self._xml_filepath = path.join(config.manager.brisa_home, "tmp_xml")
     if not path.exists(self._xml_filepath):
         mkdir(self._xml_filepath)
     self._xml_filepath = path.join(self._xml_filepath, self.xml_filename)
Example #6
1
def bound_tests(solver, save_format):
    print ">>>", datetime.now(), "Begin bound tests"
    solver.net.set_phase_test()
    solver.test_nets[0].share_with(solver.net)
    net = solver.test_nets[0]
    save_dir = save_format.format(solver.iter)
    os.mkdir(save_dir)
    hist = np.zeros((2, 2))
    for fname in fnames_val:
        net.forward()
        im = Image.fromarray(net.blobs["cscore"].data[0].argmax(0).astype(np.uint8), mode="P")
        im.save(os.path.join(save_dir, fname + ".png"))
        h, _, _ = np.histogram2d(
            net.blobs["gt"].data[0, 0].flatten(),
            net.blobs["cscore"].data[0].argmax(0).flatten(),
            bins=2,
            range=[[0, 2], [0, 2]],
        )
        hist += h
    print ">>>", datetime.now(), "Iteration", solver.iter, "overall accuracy", np.diag(hist).sum() / hist.sum()
    print ">>>", datetime.now(), "Iteration", solver.iter, "total IU", hist[1, 1] / (
        hist[0, 1] + hist[1, 0] + hist[1, 1]
    )
    r = hist[1, 1] / hist[1].sum()
    p = hist[1, 1] / hist[:, 1].sum()
    print ">>>", datetime.now(), "Iteration", solver.iter, "recall", r
    print ">>>", datetime.now(), "Iteration", solver.iter, "precision", p
    print ">>>", datetime.now(), "Iteration", solver.iter, "F1", 2 * r * p / (r + p)
    solver.net.set_phase_train()
Example #7
1
def conn_tests(solver, save_format):
    print ">>>", datetime.now(), "Begin conn tests"
    solver.net.set_phase_test()
    solver.test_nets[0].share_with(solver.net)
    net = solver.test_nets[0]
    save_dir = save_format.format(solver.iter)
    os.mkdir(save_dir)
    hist = np.zeros((2, 2))
    for fname in fnames_val:
        net.forward()
        im = Image.fromarray(net.blobs["left-conn"].data[0].argmax(0).astype(np.uint8), mode="P")
        im.save(os.path.join(save_dir, fname + "-L.png"))
        im = Image.fromarray(net.blobs["top-conn"].data[0].argmax(0).astype(np.uint8), mode="P")
        im.save(os.path.join(save_dir, fname + "-T.png"))
        h, _, _ = np.histogram2d(
            net.blobs["left-gt"].data[0, 0].flatten(),
            net.blobs["left-conn"].data[0].argmax(0).flatten(),
            bins=2,
            range=[[0, 2], [0, 2]],
        )
        hist += h
        h, _, _ = np.histogram2d(
            net.blobs["top-gt"].data[0, 0].flatten(),
            net.blobs["top-conn"].data[0].argmax(0).flatten(),
            bins=2,
            range=[[0, 2], [0, 2]],
        )
        hist += h
    print ">>>", datetime.now(), "Iteration", solver.iter, "overall accuracy", np.diag(hist).sum() / hist.sum()
    print ">>>", datetime.now(), "Iteration", solver.iter, "total IU", hist[1, 1] / (
        hist[0, 1] + hist[1, 0] + hist[1, 1]
    )
    solver.net.set_phase_train()
 def test_init_manifest_packageid(self):
     comm.setUp()
     os.chdir(comm.XwalkPath)
     comm.clear("org.xwalk.test")
     os.mkdir("org.xwalk.test")
     cmd = (
         comm.HOST_PREFIX
         + comm.PackTools
         + "crosswalk-app manifest "
         + comm.XwalkPath
         + "org.xwalk.test --platforms=android --package-id=org.xwalk.test"
     )
     os.system(cmd)
     with open(comm.ConstPath + "/../tools/org.xwalk.test/manifest.json") as json_file:
         data = json.load(json_file)
     updatecmd = (
         comm.HOST_PREFIX
         + comm.PackTools
         + "crosswalk-app manifest "
         + comm.XwalkPath
         + "org.xwalk.test --platforms=android --package-id=org.test.foo"
     )
     os.system(updatecmd)
     with open(comm.ConstPath + "/../tools/org.xwalk.test/manifest.json") as json_file_update:
         updatedata = json.load(json_file_update)
     comm.clear("org.xwalk.test")
     self.assertEquals(data["xwalk_package_id"].strip(os.linesep), "org.xwalk.test")
     self.assertEquals(updatedata["xwalk_package_id"].strip(os.linesep), "org.test.foo")
    def __init__(self, config, episode):
        try:
            self.m4bFolderPath = config.get("XMLTarget", "m4bFolder")
            self.mp3FilePath = config.get("XMLTarget", "mp3FilePath")
            self.chapterToolPath = config.get("XMLTarget", "chapterToolPath")
            self.withArtwork = config.get("XMLTarget", "includeArt")
            self.defaultArtwork = config.get("XMLTarget", "defaultArt")
            self.withLinks = config.get("XMLTarget", "includeLinks")
            self.linkUrl = config.get("XMLTarget", "linkUrl")
            self.queryUrl = config.get("XMLTarget", "queryUrl")
        except ConfigParser.NoSectionError:
            print("%s: No [MakeM4B] section in config") % (self.pluginName)
            return
        except ConfigParser.NoOptionError:
            print("%s: Missing values in config") % (self.pluginName)
            return

        # make the destination folder
        self.m4bFolderPath = os.path.expanduser(self.m4bFolderPath + "-Episode " + episode)
        if not os.path.exists(self.m4bFolderPath):
            os.mkdir(self.m4bFolderPath)

        # make the desired xml in the folder
        self.theFileName = "Episode_%s.xml" % (str(episode))
        fh = open(self.m4bFolderPath + "/" + self.theFileName, "w")
        fh.write('<?xml version="1.0" encoding="utf-8"?>\n')
        fh.write('<chapters version="1">\n')
        fh.close()
Example #10
0
    def GenerateCoverageReportIfNeeded(self):
        """Uses the Emma to generate a coverage report and a html page."""
        if not self.coverage:
            return
        cmd = [
            "java",
            "-classpath",
            TestRunner._EMMA_JAR,
            "emma",
            "report",
            "-r",
            "html",
            "-in",
            TestRunner._COVERAGE_MERGED_FILENAME,
            "-in",
            TestRunner._COVERAGE_META_INFO_PATH,
        ]
        cmd_helper.RunCmd(cmd)
        new_dir = os.path.join(TestRunner._COVERAGE_WEB_ROOT_DIR, time.strftime("Coverage_for_%Y_%m_%d_%a_%H:%M"))
        shutil.copytree("coverage", new_dir)

        latest_dir = os.path.join(TestRunner._COVERAGE_WEB_ROOT_DIR, "Latest_Coverage_Run")
        if os.path.exists(latest_dir):
            shutil.rmtree(latest_dir)
        os.mkdir(latest_dir)
        webserver_new_index = os.path.join(new_dir, "index.html")
        webserver_new_files = os.path.join(new_dir, "_files")
        webserver_latest_index = os.path.join(latest_dir, "index.html")
        webserver_latest_files = os.path.join(latest_dir, "_files")
        # Setup new softlinks to last result.
        os.symlink(webserver_new_index, webserver_latest_index)
        os.symlink(webserver_new_files, webserver_latest_files)
        cmd_helper.RunCmd(["chmod", "755", "-R", latest_dir, new_dir])
Example #11
0
 def check_user_config(self):
     if not os.path.isdir(self.user_config_dir):
         try:
             os.mkdir(self.user_config_dir, 0777)
         except (IOError, os.error), value:
             sys.stderr("Cannot write preferences into %s." % user_config_dir)
             sys.exit(1)
    def __init__(self):
        config_dir = os.path.join(xdg_config_home, OWN_NAME)
        if not os.path.isdir(config_dir):
            os.mkdir(config_dir)

        self._clientId = CLIENT_ID
        self._clientSecret = CLIENT_SECRET

        self._config_lock = Lock()
        self.config_file = os.path.join(config_dir, "{}.conf".format(OWN_NAME))
        self.config = ConfigParser()
        self.config.read(self.config_file)

        self.label_device = self.config_get_optional("interface", "LABEL_DEVICE", "")
        self.label_sensor = self.config_get_optional("interface", "LABEL_SENSOR", "")
        self.show_battery = self.config_get_optional("interface", "SHOW_BATTERY", True)
        self.show_signal = self.config_get_optional("interface", "SHOW_SIGNAL", True)

        try:
            with self._config_lock:
                self._accessToken = self.config.get("auth", "ACCESS_TOKEN")
                self.refreshToken = self.config.get("auth", "REFRESH_TOKEN")
                self.expiration = self.config.getint("auth", "TOKEN_EXPIRATION")
            self.accessToken
        except:
            try:
                (account, password) = self.request_credentials()
                super(ConfigAuth, self).__init__(CLIENT_ID, CLIENT_SECRET, account, password)
                self.update_auth_config()
            except:
                print(traceback.format_exc())
                raise Exception("Impossible to connect with provided credentials")
Example #13
0
 def handle(self, *args, **options):
     """Request pages and build output."""
     settings.DEBUG = False
     if args:
         pages = args
         available = list(get_pages())
         invalid = []
         for page in pages:
             if page not in available:
                 invalid.append(page)
         if invalid:
             msg = "Invalid pages: {}".format(", ".join(invalid))
             raise CommandError(msg)
     else:
         pages = get_pages()
         if os.path.exists(settings.SITE_OUTPUT_DIRECTORY):
             shutil.rmtree(settings.SITE_OUTPUT_DIRECTORY)
         os.mkdir(settings.SITE_OUTPUT_DIRECTORY)
         os.makedirs(settings.STATIC_ROOT)
     call_command("collectstatic", interactive=False, clear=True, verbosity=0)
     call_command("compress", interactive=False, force=True)
     client = Client()
     for page in get_pages():
         url = reverse("page", kwargs={"slug": page})
         response = client.get(url)
         if page == "index":
             output_dir = settings.SITE_OUTPUT_DIRECTORY
         else:
             output_dir = os.path.join(settings.SITE_OUTPUT_DIRECTORY, page)
             os.makedirs(output_dir)
         with open(os.path.join(output_dir, "index.html"), "wb") as f:
             f.write(response.content)
Example #14
0
def execute(script, data_dir, rev):
    rename1_map = os.path.join(data_dir, "rename1.txt")
    rename2_map = os.path.join(data_dir, "rename2.txt")
    fieldsep = DataConverter.LIST_FIELDSEP
    if fieldsep == u"\t":
        fieldsep = u"TAB"
    if not os.path.exists(rename2_map):
        print "You must first edit %s." % rename1_map
        print "For editing it, please use an editor that is able to edit UTF-8 encoded files."
        print "Carefully edit - the fields are separated by a %s char, do not change this!" % fieldsep
        print "Entries in this file look like:"
        print "PAGE OLDPAGENAME NEWPAGENAME"
        print "FILE OLDPAGENAME OLDFILENAME NEWFILENAME"
        print "You may ONLY edit the rightmost field (the new name - in case you want to rename the page or file)."
        print
        print "After you have finished editing, rename the file to %s and re-issue the moin migrate command." % rename2_map
        return None  # terminate here
    # the second pass does the conversion, reading <data_dir>/rename2.txt
    src_data_dir = os.path.abspath(os.path.join(data_dir, "..", "data.pre160"))  # keep the orig data_dir here
    dst_data_dir = data_dir
    shutil.move(data_dir, src_data_dir)
    # the 1.5 parser checks page existance, so we must use the orig, fully populated dir:
    saved_data_dir = script.request.cfg.data_dir
    script.request.cfg.data_dir = src_data_dir
    os.mkdir(dst_data_dir)
    shutil.move(os.path.join(src_data_dir, "cache"), os.path.join(dst_data_dir, "cache"))  # mig script has locks there
    dc = DataConverter(script.request, src_data_dir, dst_data_dir)
    dc.pass2()
    # restore correct data dir:
    script.request.cfg.data_dir = saved_data_dir
    return 1060000
Example #15
0
 def setUp(self):
     PluginTestCase.setUp(self)
     try:
         shutil.rmtree(pluginsPath)
     except:
         pass
     os.mkdir(pluginsPath)
Example #16
0
def check_build():
    build_dirs = ["build", "build/doctrees", "build/html", "_static", "_templates"]
    for d in build_dirs:
        try:
            os.mkdir(d)
        except OSError:
            pass
Example #17
0
def get_config_filename(name, level="global", mode="r"):
    dir = None
    if level == "global":
        if os.name in ("posix", "nt"):
            dir = (
                (site_config and site_config.BKCHEM_MODULE_PATH)
                or os.getenv("BKCHEM_MODULE_PATH")
                or os.path.join("..", ".bkchem")
            )
    elif level == "local":
        if os.name in ("posix", "nt"):
            dir = (site_config and site_config.BKCHEM_MODULE_PATH) or os.getenv("BKCHEM_MODULE_PATH") or None
    if level == "personal":
        if os.name in ("posix", "nt"):
            dir = get_personal_config_directory()

    if dir:
        if mode == "w":
            if not os.path.isdir(dir):
                try:
                    os.mkdir(dir)
                except:
                    return None
            if os.access(dir, os.W_OK):
                return os.path.join(dir, name)
            else:
                return None
        elif mode == "r":
            path = os.path.join(dir, name)
            if os.access(path, os.R_OK):
                return path
            else:
                return None
    return None
Example #18
0
    def run(self):
        # Here we write a mini config for the server
        smbConfig = ConfigParser.ConfigParser()
        smbConfig.add_section("global")
        smbConfig.set("global", "server_name", "server_name")
        smbConfig.set("global", "server_os", "UNIX")
        smbConfig.set("global", "server_domain", "WORKGROUP")
        smbConfig.set("global", "log_file", SMBSERVER_DIR + "/smb.log")
        smbConfig.set("global", "credentials_file", "")

        # Let's add a dummy share
        smbConfig.add_section(DUMMY_SHARE)
        smbConfig.set(DUMMY_SHARE, "comment", "")
        smbConfig.set(DUMMY_SHARE, "read only", "no")
        smbConfig.set(DUMMY_SHARE, "share type", "0")
        smbConfig.set(DUMMY_SHARE, "path", SMBSERVER_DIR)

        # IPC always needed
        smbConfig.add_section("IPC$")
        smbConfig.set("IPC$", "comment", "")
        smbConfig.set("IPC$", "read only", "yes")
        smbConfig.set("IPC$", "share type", "3")
        smbConfig.set("IPC$", "path")

        self.smb = smbserver.SMBSERVER(("0.0.0.0", 445), config_parser=smbConfig)
        logging.info("Creating tmp directory")
        try:
            os.mkdir(SMBSERVER_DIR)
        except Exception, e:
            logging.critical(str(e))
            pass
Example #19
0
    def archive(self, bucket, path, compress=False):

        # make root path, if it does not exist
        if not os.path.exists(path):
            os.mkdir(path)

        bckt = self.conn.get_bucket(bucket)
        count = 0

        for item in bckt.list():

            # build local path
            local_path = os.path.join(path, item.key)

            # find local dir and create intermediate dirs
            # if they don't exist
            local_dir = os.path.dirname(local_path)
            if not os.path.exists(local_dir):
                os.makedirs(local_dir)

            if not os.path.isdir(local_path):
                with open(local_path, "w") as local_file:
                    item.get_contents_to_file(local_file)
                    logging.info("copying %s:%s" % (bucket, item.key))
                    count += 1

        if compress:
            tarpath = "%s.tar.gz" % path
            with tarfile.open(tarpath, "w:gz") as tar:
                tar.add(path, arcname=path.split(os.sep)[-1], recursive=True)
            shutil.rmtree(path)
            logging.info("compressed archive and removed working directory")

        logging.info("archived %d files in %s" % (count, bucket))
Example #20
0
    def __init__(
        self,
        cache_dir,
        mwrender_cmd,
        mwrender_logfile,
        mwzip_cmd,
        mwzip_logfile,
        mwpost_cmd,
        mwpost_logfile,
        queue_dir,
        default_writer="rl",
        report_from_mail=None,
        report_recipients=None,
    ):
        self.cache_dir = utils.ensure_dir(cache_dir)
        self.mwrender_cmd = mwrender_cmd
        self.mwrender_logfile = mwrender_logfile
        self.mwzip_cmd = mwzip_cmd
        self.mwzip_logfile = mwzip_logfile
        self.mwpost_cmd = mwpost_cmd
        self.mwpost_logfile = mwpost_logfile
        self.queue_upload_job = self.queue_render_job = no_job_queue
        if queue_dir:
            self.queue_render_job = filequeue.FileJobQueuer(utils.ensure_dir(queue_dir))
        self.default_writer = default_writer
        self.report_from_mail = report_from_mail
        self.report_recipients = report_recipients

        for i in range(0x100, 0x200):
            p = os.path.join(self.cache_dir, hex(i)[3:])
            if not os.path.isdir(p):
                os.mkdir(p)
Example #21
0
def create_structure(struct, prefix=None, update=False):
    """
    Manifests a directory structure in the filesystem

    :param struct: directory structure as dictionary of dictionaries
    :param prefix: prefix path for the structure
    :param update: update an existing directory structure as boolean
    """
    if prefix is None:
        prefix = os.getcwd()
    for name, content in struct.items():
        if isinstance(content, string_types):
            with open(join_path(prefix, name), "w") as fh:
                fh.write(utils.utf8_encode(content))
        elif isinstance(content, dict):
            try:
                os.mkdir(join_path(prefix, name))
            except OSError:
                if not update:
                    raise
            create_structure(struct[name], prefix=join_path(prefix, name), update=update)
        elif content is None:
            pass
        else:
            raise RuntimeError("Don't know what to do with content type " "{type}.".format(type=type(content)))
Example #22
0
 def _copy_tempfiles(self):
     """
     Copies created images from tempfiles to a subfolder of baseline images.
     """
     try:
         filenames = self._get_final_filenames()
         directory = self.output_path
         if os.path.exists(directory):
             if not os.path.isdir(directory):
                 msg = (
                     "Could not keep output image, target directory " "exists but is no directory: %s"
                 ) % directory
                 warnings.warn(msg)
                 return
         else:
             os.mkdir(directory)
         if os.path.isfile(self.diff_filename):
             shutil.copy(self.diff_filename, filenames["diff"])
         shutil.copy(self.name, filenames["actual"])
     except Exception as e:
         msg = ("Failed to copy images from temporary directory " "(caught %s: %s).") % (
             e.__class__.__name__,
             str(e),
         )
         warnings.warn(msg)
Example #23
0
def generate_big_data(l=200, t=20, mode="npy"):
    """ 
    Generate synthetic data to test visualizer

    Parameters
    ----------

    l: int, optional
        Linear size of output data

    t: int, optional
        Number of samples to generate

    mode: string in {'npy', 'h5', 'raw'}, optional
        Format in which to save data. Can be
        * 'npy' (numpy binary format)
        * 'h5' (hdf5)
        * 'raw' (raw binary data)
    """
    x, y, z = np.mgrid[0 : 5 : l * 1j, 0 : 5 : l * 1j, 0 : 5 : l * 1j]
    if os.path.exists("data"):
        [os.remove(filename) for filename in glob("data/data*")]
    else:
        os.mkdir("data")
    for t in np.linspace(0, 1, t + 1):
        field = np.sin(2 * np.pi * ((x % 1) * (y % 1) * (z % 1) + t))
        if mode == "npy":
            np.save(os.path.join("data", "data_%.2f.npy" % t), field)
        if mode == "raw":
            field.tofile(os.path.join("data", "data_%.2f.raw" % t))
        if mode == "h5":
            f = tb.openFile(os.path.join("data", "data_%.2f.h5" % t), "a")
            f.createArray(f.root, "image", field)
            f.close()
def pullPhotos(query):

    print "looking for", query
    url1 = "https://www.google.com/search?biw=1309&bih=704&sei=bsHjUbvaEILqrQeA-YCYDw&tbs=itp:lineart&tbm=isch&"
    query2 = urllib.urlencode({"q": query})

    req = urllib2.Request(url1 + query2, headers={"User-Agent": "Chrome"})
    response = urllib2.urlopen(req).read()
    parser = MyHTMLParser()
    parser.feed(response)

    print image_lib + "\\buffer\\" + query

    if not os.path.exists(image_lib + "\\buffer"):
        os.mkdir(image_lib + "\\buffer")  # make directory to put them in

    if not os.path.exists(image_lib + "\\buffer\\" + query):
        os.mkdir(image_lib + "\\buffer\\" + query)  # make directory to put them in

    for i in xrange(5):
        req_cat = urllib2.Request(cat_urls[i], headers={"User-Agent": "Chrome"})
        response_cat = urllib2.urlopen(req_cat).read()
        name = query + os.sep + query + str(i) + ".jpg"
        fd = open(image_lib + "\\buffer\\" + name, "wb")
        fd.write(response_cat)
        fd.close()
        print name, "written", "complexity is ", countComponents(image_lib + "\\buffer\\" + name)

    print "done"
Example #25
0
    def __init__(self, dbdir, dbname):

        self.dbenv = os.path.join(dbdir, dbname)
        if not os.path.isdir(self.dbenv):
            os.mkdir(self.dbenv)

        self.fieldsep = "\n"
Example #26
0
def parseblocks(blocklycode):
    # this is where blockly code is parsed into a python file with the command list
    # saved in memory for transimission.
    global webotcommands
    panya = Panya()
    t = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    savedir = os.path.join(sdir, g.user.nickname, "sketches")
    if not os.path.exists(savedir):
        os.mkdir(savedir)
    filename = os.path.join(savedir, t + ".py")
    print "Saving python code to ", filename
    target = open(filename, "w")
    target.write(blocklycode)
    target.close()
    # We now compile the generated python strings in the blocklycode
    # into bytecode and execute the resultant .pyc through the exec function
    # in our current namespace (I can't figure out a better way to have the
    # webot class instance variables accessible)
    # Read about caveats here - http://lucumr.pocoo.org/2011/2/1/exec-in-python/
    compiledcode = compile(blocklycode, "<string>", "exec")
    exec compiledcode
    print webotcommands
    sessionresponse = portsetup(webotcommands)
    webotcommands = ""
    return sessionresponse
Example #27
0
def move_album(album, destination):
    """Move an Album to destination

    If the destination exists and is a file, FileExistsError will be raised.
    If the destination exists and is a folder, album will be placed inside
    of the folder. If the album is moving into a subpath of the existing path,
    the tracks will be moved (ie collection/artist -> collection/artist/album).
    """
    if os.path.isdir(destination):
        album_folder = os.path.basename(album.path)
        destination_path = os.path.join(destination, album_folder)
    elif os.path.exists(destination):
        raise FileExistsError(
            ("File {} cannot be moved to destination:" + "{} (Already Exists)").format(album.path, destination)
        )
    else:
        destination_path = destination

    if album.path in destination_path:
        if not os.path.isdir(destination_path):
            os.mkdir(destination_path)

        for track in [x.path for x in album]:
            shutil.move(track, destination_path)
    else:
        shutil.move(album.path, destination)

    controller.set_album_path(album, destination_path)
    def test_user_site(self):
        import site

        dist = Distribution({"name": "xx"})
        cmd = build_ext(dist)

        # making sure the user option is there
        options = [name for name, short, label in cmd.user_options]
        self.assertIn("user", options)

        # setting a value
        cmd.user = 1

        # setting user based lib and include
        lib = os.path.join(site.USER_BASE, "lib")
        incl = os.path.join(site.USER_BASE, "include")
        os.mkdir(lib)
        os.mkdir(incl)

        cmd.ensure_finalized()

        # see if include_dirs and library_dirs were set
        self.assertIn(lib, cmd.library_dirs)
        self.assertIn(lib, cmd.rpath)
        self.assertIn(incl, cmd.include_dirs)
Example #29
0
    def create(cls, idml_package, story_id, xml_element_id, xml_element_tag, working_copy_path):
        dirname = os.path.join(working_copy_path, STORIES_DIRNAME)
        if not os.path.exists(dirname):
            os.mkdir(dirname)
        story_name = "%s/Story_%s.xml" % (STORIES_DIRNAME, story_id)
        story = Story(idml_package, story_name, working_copy_path)

        # Difficult to do it in .fobj() because we don't always need
        # to create a unexisting file.
        filename = os.path.join(working_copy_path, story_name)
        story._fobj = open(filename, mode="w+")
        story.fobj.write(
            """<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
   <idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="7.5">
     <Story Self="%(story_id)s" AppliedTOCStyle="n" TrackChanges="false" StoryTitle="$ID/" AppliedNamedGrid="n">
       <StoryPreference OpticalMarginAlignment="false" OpticalMarginSize="12" FrameType="TextFrameType" StoryOrientation="Horizontal" StoryDirection="LeftToRightDirection"/>
       <InCopyExportOption IncludeGraphicProxies="true" IncludeAllResources="false"/>
       <XMLElement Self="%(xml_element_id)s" MarkupTag="XMLTag/%(xml_element_tag)s" XMLContent="%(story_id)s" />
     </Story>
</idPkg:Story>
"""
            % {"story_id": story_id, "xml_element_tag": xml_element_tag, "xml_element_id": xml_element_id}
        )

        story.fobj.close()
        story._fobj = None
        return story
Example #30
0
def slice(dir=dat):
    os.mkdir(dat)
    README = open(os.path.join(dat, "README.txt"), "w")
    README.write(
        """
        THE FILES IN THIS DIRECTORY ARE GENERATE
        AND WILL BE AUTOMATICALLY DELETED
        """
    )
    README.flush()
    README.close()
    call(
        """slice2freezej \
--dict ome.services.sharing.data.ShareMap,\
long,ome::services::sharing::data::ShareData \
--dict-index ome.services.sharing.data.ShareMap,id \
--dict-index ome.services.sharing.data.ShareMap,owner \
--output-dir %s Share.ice"""
        % src
    )
    call(
        """slice2freezej \
--dict ome.services.sharing.data.ShareItems,\
long,ome::services::sharing::data::ShareItem \
--dict-index ome.services.sharing.data.ShareItems,type \
--dict-index ome.services.sharing.data.ShareItems,share \
--output-dir %s Share.ice"""
        % src
    )
    call("""slice2java --output-dir %s Share.ice""" % src)