Ejemplo n.º 1
0
    def test_CatchOutput(self):
        """
        """
        libc = CDLL(find_library("c"))

        with CatchOutput() as out:
            os.system('echo "abc"')
            libc.printf(b"def\n")
            print("ghi")
            print("jkl", file=sys.stdout)
            os.system('echo "123" 1>&2')
            print("456", file=sys.stderr)

        if PY2:
            if platform.system() == "Windows":
                self.assertEqual(out.stdout, '"abc"\ndef\nghi\njkl\n')
                self.assertEqual(out.stderr, '"123" \n456\n')
            else:
                self.assertEqual(out.stdout, "abc\ndef\nghi\njkl\n")
                self.assertEqual(out.stderr, "123\n456\n")
        else:
            # XXX: cannot catch the printf call to def in Py3k
            if platform.system() == "Windows":
                self.assertEqual(out.stdout, '"abc"\nghi\njkl\n')
                self.assertEqual(out.stderr, '"123" \n456\n')
            else:
                self.assertEqual(out.stdout, "abc\nghi\njkl\n")
                self.assertEqual(out.stderr, "123\n456\n")
Ejemplo n.º 2
0
def download_texlive_installer(**kw):
    url = kw.get('installer_url')
    fnames = {
        'Windows' : 'install-tl.zip',
        'Linux'   : 'install-tl-unx.tar.gz'
    }
    if not url:
        url_base = kw.get('installer_url_base')
        if not url_base:
            url_base ="http://sunsite.icm.edu.pl/pub/tex/systems/texlive"
        try:
            fname = fnames[platform.system()]
        except KeyError:
            raise RuntimeError("unsupported OS %s" % platform.system())
        url="%s/tlnet/%s" % (url_base, fname)

    tempdir = kw['tempdir']
    instfile = os.path.join(tempdir, fname)
    info("downloading '%s' -> '%s'" % (url,instfile))
    if platform.system() == 'Windows':
        urlunzip(url,path = tempdir)
    elif platform.system() == 'Linux':
        urluntar(url,path = tempdir, strip_components = 1)
    else:
        raise RuntimeError("unsuported OS %s" % platform.system())
    return 0
Ejemplo n.º 3
0
def determine_db_dir():
    """Return the default location of the bitcoin data directory"""
    if platform.system() == "Darwin":
        return os.path.expanduser("~/Library/Application Support/Bitcoin/")
    elif platform.system() == "Windows":
        return os.path.join(os.environ['APPDATA'], "Bitcoin")
    return os.path.expanduser("~/.bitcoin")
Ejemplo n.º 4
0
 def __init__(self, macAddress, timeout = None):
     regCompiled = re.compile('^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$');
     checkMatch = re.match(regCompiled, macAddress);
     self.blocking = True if timeout == None else False
     if not self.blocking:
         try:
             self.timeout = float(timeout)
         except Exception:
             raise Exception(ExceptionCode.INVALID_PARAMETER)
     if (checkMatch):
         if platform.system() == 'Windows' or platform.system() == 'Linux':
             import bluetooth
             self.socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
             self.socket.connect((macAddress, 1))
             self.socket.setblocking(True)
             self.serial = False     
         else:
             raise Exception(ExceptionCode.INVALID_PLATFORM)
     elif (macAddress[0:3] == 'COM' and platform.system() == 'Windows') or (macAddress[0:5] == '/dev/' and platform.system() != 'Windows'):
         self.socket = serial.Serial(macAddress, 115200)
         self.serial = True
     else:
         raise Exception(ExceptionCode.INVALID_ADDRESS)
     self.started = False
     self.macAddress = macAddress
     self.isBitalino2 = True if float(self.version().split('_v')[1][:3]) >= 4.2 else False
Ejemplo n.º 5
0
def install_texlive(**kw):
    tempdir = kw['tempdir']
    if platform.system() == 'Windows':
        ptr = os.path.join(tempdir,'install-tl-*','install-tl-windows.bat')
        lst = glob.glob(ptr)
        if not lst:
            warn("coult not find install-tl-windows.bat", **kw)
            return 2
        cmd = lst[0]
    elif platform.system() == 'Linux':
        cmd = os.path.join(tempdir,'install-tl')
    else:
        raise RuntimeError("unsuported OS %s" % platform.system())

    repository = kw.get('repository')

    profile = os.path.join(tempdir, 'texlive.profile')

    args = [cmd, '-profile', profile]
    if repository:
        args += ['-repository', repository]

    info("starting TeX instaler", **kw)
    info("%s" % map(lambda x : str(x), args), **kw)
    spkw = {'env': os.environ.copy(), 'stdin': subprocess.PIPE}
    if sys.version_info < (3,7):
        spkw['universal_newlines'] = True
    else:
        spkw['text'] = True
    sp = subprocess.Popen(args, **spkw)
    if platform.system() == 'Windows':
        # Answer to "Press any key to continue..."
        sp.stdin.write("\n")
    sp.stdin.close()
    sp.wait()
Ejemplo n.º 6
0
def sb_revealInFileBrowser():

	n = nuke.selectedNodes("Read") + nuke.selectedNodes("Write")

	if len(n) == 0:
		nuke.message("Select at least one Read or Write node.")
		return

	if len(n) > 3:
		makeSure = nuke.ask("Are you sure you want to open {0} file browser windows?".format(len(n)))
		if not makeSure:
			return

	for i in n:
		try:
			getPath = i["file"].evaluate().split("/")[:-1]
			folderPath = "/".join(getPath)

			if platform.system() == "Windows":
				subprocess.Popen('explorer "{0}"'.format(folderPath.replace("/", "\\")))
			elif platform.system() == "Darwin":
				subprocess.Popen(["open", folderPath])
			elif platform.system() == "Linux":
				subprocess.Popen(["xdg-open", folderPath])
		except:
			continue
Ejemplo n.º 7
0
 def get_gmsh_command(self):
     self.gmsh_bin = None
     gmsh_std_location = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/Gmsh").GetBool("UseStandardGmshLocation")
     if gmsh_std_location:
         if system() == "Windows":
             gmsh_path = FreeCAD.getHomePath() + "bin/gmsh.exe"
             FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/Gmsh").SetString("gmshBinaryPath", gmsh_path)
             self.gmsh_bin = gmsh_path
         elif system() == "Linux":
             p1 = subprocess.Popen(['which', 'gmsh'], stdout=subprocess.PIPE)
             if p1.wait() == 0:
                 gmsh_path = p1.stdout.read().split('\n')[0]
             elif p1.wait() == 1:
                 error_message = "GMSH binary gmsh not found in standard system binary path. Please install gmsh or set path to binary in FEM preferences tab GMSH.\n"
                 FreeCAD.Console.PrintError(error_message)
                 raise Exception(error_message)
             self.gmsh_bin = gmsh_path
         else:
             error_message = "No standard location implemented for your operating system. Set GMHS binary path in FEM preferences.\n"
             FreeCAD.Console.PrintError(error_message)
             raise Exception(error_message)
     else:
         if not self.gmsh_bin:
             self.gmsh_bin = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/Gmsh").GetString("gmshBinaryPath", "")
         if not self.gmsh_bin:  # in prefs not set, we will try to use something reasonable
             if system() == "Linux":
                 self.gmsh_bin = "gmsh"
             elif system() == "Windows":
                 self.gmsh_bin = FreeCAD.getHomePath() + "bin/gmsh.exe"
             else:
                 self.gmsh_bin = "gmsh"
     print('  ' + self.gmsh_bin)
Ejemplo n.º 8
0
def tern_startServer(project):
  if time.time() - project.last_failed < 30: return None

  win = platform.system() == "Windows"
  env = None
  if platform.system() == "Darwin":
    env = os.environ.copy()
    env["PATH"] += ":/usr/local/bin"
  command = vim.eval("g:tern#command") + vim.eval("g:tern#arguments")
  try:
    proc = subprocess.Popen(command,
                            cwd=project.dir, env=env,
                            stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT, shell=win)
  except Exception as e:
    tern_displayError("Failed to start server: " + str(e))
    return None
  output = ""
  while True:
    line = proc.stdout.readline().decode('utf8')
    if not line:
      tern_displayError("Failed to start server" + (output and ":\n" + output))
      project.last_failed = time.time()
      return None
    match = re.match("Listening on port (\\d+)", line)
    if match:
      port = int(match.group(1))
      project.port = port
      project.proc = proc
      return port
    else:
      output += line
Ejemplo n.º 9
0
def test_os_release(output):
    supported = False
    distInfo = ""
    formatString = "{0} release {1} {2}"
    if platform.system() == "Linux":
        output['OS'] = ["PASS", "Linux"]
        distInfo = platform.dist()
        supported = False
        if distInfo[0] in ("centos", "redhat", "rhel"):
            releaseNum = ".".join(distInfo[1].split(".")[0:2]) # release goes to 3 parts in Centos/Redhat 7.x(.y)
            if releaseNum >= "6.6":
                supported = True
        elif "ubuntu" in distInfo[0].lower():
            if distInfo[1] in ("12.04", "14.04"):
                supported = True
    elif platform.system() == "Darwin":
        output["OS"] = ["PASS", "MacOS X"]
        version = platform.uname()[2]
        distInfo = ("MacOS X", version, "") # on Mac, platform.dist() is empty
        if version >= "10.8.0":
            supported = True
    else:
        output['OS'] = ["WARN", "Only supports Linux based platforms"]
        output['OS release'] = ["WARN", "Supported distributions are Ubuntu 12.04/14.04 and RedHat/CentOS 6.6 or later"]
    if not supported:
        formatString = "Unsupported release: " + formatString
    output['OS release'] = ["PASS" if supported else "WARN", formatString.format(*distInfo)]
Ejemplo n.º 10
0
def print_basic_debug_info(out=None):
    if out is None:
        out = sys.stdout
    out = functools.partial(prints, file=out)
    import platform
    from calibre.constants import (__appname__, get_version, isportable, isosx,
                                   isfrozen, is64bit)
    out(__appname__, get_version(), 'Portable' if isportable else '',
        'embedded-python:', isfrozen, 'is64bit:', is64bit)
    out(platform.platform(), platform.system(), platform.architecture())
    if iswindows and not is64bit:
        try:
            import win32process
            if win32process.IsWow64Process():
                out('32bit process running on 64bit windows')
        except:
            pass
    out(platform.system_alias(platform.system(), platform.release(),
            platform.version()))
    out('Python', platform.python_version())
    try:
        if iswindows:
            out('Windows:', platform.win32_ver())
        elif isosx:
            out('OSX:', platform.mac_ver())
        else:
            out('Linux:', platform.linux_distribution())
    except:
        pass
    from calibre.customize.ui import has_external_plugins, initialized_plugins
    if has_external_plugins():
        names = (p.name for p in initialized_plugins() if getattr(p, 'plugin_path', None) is not None)
        out('Successfully initialized third party plugins:', ' && '.join(names))
Ejemplo n.º 11
0
def print_basic_debug_info(out=None):
    if out is None:
        out = sys.stdout
    out = functools.partial(prints, file=out)
    import platform
    from calibre.constants import (__appname__, get_version, isportable, isosx,
                                   isfrozen, is64bit)
    out(__appname__, get_version(), 'Portable' if isportable else '',
        'isfrozen:', isfrozen, 'is64bit:', is64bit)
    out(platform.platform(), platform.system(), platform.architecture())
    if iswindows and not is64bit:
        try:
            import win32process
            if win32process.IsWow64Process():
                out('32bit process running on 64bit windows')
        except:
            pass
    out(platform.system_alias(platform.system(), platform.release(),
            platform.version()))
    out('Python', platform.python_version())
    try:
        if iswindows:
            out('Windows:', platform.win32_ver())
        elif isosx:
            out('OSX:', platform.mac_ver())
        else:
            out('Linux:', platform.linux_distribution())
    except:
        pass
Ejemplo n.º 12
0
def determine_clipboard():
    # Determine the OS/platform and set
    # the copy() and paste() functions accordingly.
    if 'cygwin' in platform.system().lower():
        # FIXME: pyperclip currently does not support Cygwin,
        # see https://github.com/asweigart/pyperclip/issues/55
        pass
    elif os.name == 'nt' or platform.system() == 'Windows':
        return init_windows_clipboard()
    if os.name == 'mac' or platform.system() == 'Darwin':
        return init_osx_clipboard()
    if HAS_DISPLAY:
        # Determine which command/module is installed, if any.
        try:
            import gtk  # check if gtk is installed
        except ImportError:
            pass
        else:
            return init_gtk_clipboard()

        try:
            import PyQt4  # check if PyQt4 is installed
        except ImportError:
            pass
        else:
            return init_qt_clipboard()

        if _executable_exists("xclip"):
            return init_xclip_clipboard()
        if _executable_exists("xsel"):
            return init_xsel_clipboard()
        if _executable_exists("klipper") and _executable_exists("qdbus"):
            return init_klipper_clipboard()

    return init_no_clipboard()
Ejemplo n.º 13
0
    def graj(self):
        if self.dzwiek and self.plik != "":
            if platform.system() == "Windows":
                from winsound import PlaySound, SND_FILENAME, SND_ASYNC

                PlaySound(self.plik, SND_FILENAME | SND_ASYNC)
            elif platform.system() == "Linux":
                from wave import open as waveOpen
                from ossaudiodev import open as ossOpen

                s = waveOpen(self.plik, "rb")
                (nc, sw, fr, nf, comptype, compname) = s.getparams()

                try:
                    dsp = ossOpen("/dev/dsp", "w")

                    try:
                        from ossaudiodev import AFMT_S16_NE
                    except ImportError:
                        if byteorder == "little":
                            AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
                        else:
                            AFMT_S16_NE = ossaudiodev.AFMT_S16_BE

                    dsp.setparameters(AFMT_S16_NE, nc, fr)
                    data = s.readframes(nf)
                    dsp.write(data)
                    s.close()
                    dsp.close()
                except IOError:
                    print "Błąd pisania do użądzenia /dev/dsp !"
                    print "Sprawdź czy masz możliwość zapisywania lub czy w Twoim systemie \
jest załadowany moduł snd-pcm-oss, jeżeli nie jest załaduj go jako root poleceniem"
                    print "\n\tmodprobe snd-pcm-oss"
Ejemplo n.º 14
0
def export_dl_library_path(path): 
    if platform.system()=='Linux':
        if "LD_LIBRARY_PATH" in os.environ.keys(): 
            os.environ["LD_LIBRARY_PATH"] += os.pathsep + path
        else: 
            os.environ["LD_LIBRARY_PATH"] = path
    elif platform.system()=='Darwin':
        if "DYLD_LIBRARY_PATH" in os.environ.keys(): 
            os.environ["DYLD_LIBRARY_PATH"] += os.pathsep + path
        else: 
            os.environ["DYLD_LIBRARY_PATH"] = path
    elif platform.system()=='Windows':
        if "PATH" in os.environ.keys(): 
            os.environ["PATH"] += os.pathsep + path
        else: 
            os.environ["PATH"] = path
    else: 
        if "LD_LIBRARY_PATH" in os.environ.keys(): 
            os.environ["LD_LIBRARY_PATH"] += os.pathsep + path
        else: 
            os.environ["LD_LIBRARY_PATH"] = path
        if "PATH" in os.environ.keys(): 
            os.environ["PATH"] += os.pathsep + path
        else: 
            os.environ["PATH"] = path
def determine_db_dir():
    """Return the default location of the cryptographicanomaly data directory"""
    if platform.system() == "Darwin":
        return os.path.expanduser("~/Library/Application Support/Cryptographicanomaly/")
    elif platform.system() == "Windows":
        return os.path.join(os.environ['APPDATA'], "Cryptographicanomaly")
    return os.path.expanduser("~/.cryptographicanomaly")
Ejemplo n.º 16
0
 def getmeta(self, meta_name, default=NoDefaultMeta):
     
     if meta_name == 'free_space':
         if platform.system() == 'Windows':
             try:
                 import ctypes
                 free_bytes = ctypes.c_ulonglong(0)
                 ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(self.root_path), None, None, ctypes.pointer(free_bytes))
                 return free_bytes.value
             except ImportError:
                 # Fall through to call the base class
                 pass
         else:
             stat = os.statvfs(self.root_path)
             return stat.f_bfree * stat.f_bsize
     elif meta_name == 'total_space':
         if platform.system() == 'Windows':
             try:
                 import ctypes
                 total_bytes = ctypes.c_ulonglong(0)
                 ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(self.root_path), None, ctypes.pointer(total_bytes), None)
                 return total_bytes.value
             except ImportError:
                 # Fall through to call the base class
                 pass
         else:
             stat = os.statvfs(self.root_path)
             return stat.f_blocks * stat.f_bsize
     
     return super(OSFS, self).getmeta(meta_name, default)
Ejemplo n.º 17
0
 def on_task_filter(self, task, config):
     if not task.accepted:
         log.debug('No accepted entries, not scanning for existing.')
         return
     log.verbose('Scanning path(s) for existing files.')
     config = self.prepare_config(config)
     for path in config:
         # unicode path causes crashes on some paths
         path = str(os.path.expanduser(path))
         if not os.path.exists(path):
             raise plugin.PluginWarning('Path %s does not exist' % path, log)
         # scan through
         for root, dirs, files in os.walk(path, followlinks=True):
             # convert filelists into utf-8 to avoid unicode problems
             dirs = [x.decode('utf-8', 'ignore') for x in dirs]
             files = [x.decode('utf-8', 'ignore') for x in files]
             # windows file system is not case sensitive
             if platform.system() == 'Windows':
                 dirs = [s.lower() for s in dirs]
                 files = [s.lower() for s in files]
             for entry in task.accepted:
                 # priority is: filename, location (filename only), title
                 name = check = os.path.split(entry.get('filename', 
                     entry.get('location', entry['title'])))[1]
                 if platform.system() == 'Windows':
                     check = check.lower()
                 if check in dirs or check in files:
                     log.debug('Found %s in %s' % (name, root))
                     entry.reject(os.path.join(root, name))
Ejemplo n.º 18
0
    def start(self, level):

        self._level = level
        logging.captureWarnings(True)

        # Set new log file path. Ensure that the directory exists
        # Ensure that the log directory is not too full. We'll determine this by size and not date archiving
        # This is suboptimal compared native Windows or UNIX size listing, but python does not offer anything faster
        #   without system scripting. However, based on size limit (10MB), this method will not take more than 5ms.
        if platform.system() is "Linux" or platform.system() is "Darwin":
            self.__config_unix__()
        # window case removed. TODO
        else:
            raise lexcep("Error: Incompatible OS detected. Only Linux, Mac, or Windows is supported").with_traceback(sys.exc_info()[2])

        # Verify that the file can be created and does not exist
        try:
            with open(self._fn) as f: pass
        except IOError as e:
            raise lexcep("log file\n\n" + self._fn + "\n\nexists. Uniquely named log file should not exist prior to initialization.\nPlease contact your System Administrator\n\n" + str(e)).with_traceback(sys.exc_info()[2])

        try:
            logging.basicConfig(filename=self._fn, level=self._level)
        except FileNotFoundError as e:
            raise lexcep("log file\n\n" + self._fn + "\n\nwas not created for logging.\nCheck log directory permissions or contact your System Administrator\n\n" + str(e)).with_traceback(sys.exc_info()[2])
        except ValueError as e:
            raise lexcep("ValueError was encountered while initializing logging:\n\n" + str(e)).with_traceback(sys.exc_info()[2])
        except Exception as e:
            raise lexcep("Internal Error: unhandled exception occured:\n\n" + str(e)).with_traceback(sys.exc_info()[2])
Ejemplo n.º 19
0
def open_file(path):
    if platform.system() == "Windows":
        os.startfile(path)
    elif platform.system() == "Darwin":
        subprocess.Popen(["open", path])
    else:
        subprocess.Popen(["xdg-open", path])
Ejemplo n.º 20
0
def getTeighaConverter():
    import FreeCAD,os,platform
    "finds the Teigha Converter executable"
    p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft")
    p = p.GetString("TeighaFileConverter")
    if p:
        # path set manually
        teigha = p
    else:
        # try to find teigha
        teigha = None
        if platform.system() == "Linux":
            teigha = "/usr/bin/TeighaFileConverter"
        elif platform.system() == "Windows":
            odadir = os.path.expandvars("%ProgramFiles%\ODA")
            if os.path.exists(odadir):
                subdirs = os.walk(odadir).next()[1]
                for sub in subdirs:
                    t = odadir + os.sep + sub + os.sep + "TeighaFileConverter.exe"
                    if os.path.exists(t):
                        teigha = t
    if teigha:
        if os.path.exists(teigha):
            return teigha
    from DraftTools import translate
    FreeCAD.Console.PrintMessage(translate("draft","Teigha File Converter not found, DWG support is disabled.\n"))
    return None
Ejemplo n.º 21
0
def detect_platform():
    base_mapping = {
        "gentoo base system": "gentoo",
        "centos linux": "centos",
        "mandriva linux": "mandriva",
        "elementary os": "ubuntu",
        "trisquel": "ubuntu",
        "linaro": "ubuntu",
        "linuxmint": "ubuntu",
        "amazon": "ubuntu",
        "redhat enterprise linux": "rhel",
        "red hat enterprise linux server": "rhel",
        "fedora": "rhel",
        "olpc": "rhel",
        "xo-system": "rhel",
        "kali linux": "debian",
    }

    platform_mapping = {"ubuntu": "debian", "rhel": "centos"}

    if hasattr(pyplatform, "mac_ver") and pyplatform.mac_ver()[0] != "":
        return "osx", "osx"

    if pyplatform.system() != "Linux":
        res = pyplatform.system().lower()
        return res, res

    dist = ""
    (maj, min, patch) = pyplatform.python_version_tuple()
    if (maj * 10 + min) >= 26:
        dist = pyplatform.linux_distribution()[0]
    else:
        dist = pyplatform.dist()[0]

    if dist == "":
        if os.path.exists("/etc/os-release"):
            release = open("/etc/os-release").read()
            if "Arch Linux" in release:
                dist = "arch"

    if dist == "":
        if os.path.exists("/etc/system-release"):
            release = open("/etc/system-release").read()
            if "Amazon Linux AMI" in release:
                dist = "centos"

    if dist == "":
        try:
            dist = subprocess.check_output(["strings", "-4", "/etc/issue"]).split()[0]
        except:
            dist = "unknown"

    res = dist.strip(" '\"\t\n\r").lower()
    if res in base_mapping:
        res = base_mapping[res]

    res_mapped = res
    if res in platform_mapping:
        res_mapped = platform_mapping[res]
    return res, res_mapped
Ejemplo n.º 22
0
def get_password(prompt):
    if platform.system() == "Linux":
        return getpass.unix_getpass(prompt=prompt)
    elif platform.system() == "Windows" or platform.system() == "Microsoft":
        return getpass.win_getpass(prompt=prompt)
    else:
        return getpass.getpass(prompt=prompt)
Ejemplo n.º 23
0
    def __init__(self, title=_("Title")):
        """
        Desc: Método iniciador

        title = Str: Rótulo do título
        """

        self.root = Menu(None, title)

        # Encapsulamento
        self.xml = MenuXml(self)

        # Herança
        MenuXml.__init__(self, self)


        # Configurações do menu:
        self.config = dict({
            "version": "beta 0.9.0",

            "cleanTerminal": True
        })
        if platform.system() != "Windows" and platform.system() != "Linux":
            self.config["detectKey"] = "manual"
        else:
            self.config["detectKey"] = "automatic"
Ejemplo n.º 24
0
def link(target, lnk, force=False):
    """
    Creates symbolic link 'lnk' pointing to 'target'.
    """

    if system() not in ('Linux', 'Windows', 'MSYS_NT-6.1'):
        print("{} operating system is not supported.".format(system()))
        return

    isdir = False

    lnk = path.normpath(path.expandvars(path.expanduser(lnk)))
    if path.isdir(target):
        isdir = True
    target = path.normpath(path.expandvars(path.expanduser(target)))

    if isdir:
        print("\n{} -> {} : DIR".format(lnk, target))
    else:
        print("\n{} -> {} : FILE".format(lnk, target))

    if path.isdir(lnk) or path.isfile(lnk):
        if not force:
            print("'{}': link exists".format(lnk))
            return
        else:
            remove(lnk)

    if system() in ('Linux', 'MSYS_NT-6.1'):
        Popen(['ln', '-s', target, lnk]).wait()
    elif system() == 'Windows':
        if isdir:
            CreateSymbolicLink(lnk, target, 1)
        else:
            CreateSymbolicLink(lnk, target, 0)
Ejemplo n.º 25
0
def __encode_multithreaded(f, data):
    """The base function that runs the given function f in multithreaded
    fashion.

    :param f: The function
    :param data: The data
    :return:
    """
    import multiprocessing
    import platform
    number_of_threads = multiprocessing.cpu_count() / 2

    if platform.system() == 'Windows':
        multiprocessing.set_executable('C:/Python27/pythonw.exe')
    elif platform.system() == 'Linux':
        multiprocessing.set_executable('/usr/bin/python')

    p = multiprocessing.Pool(number_of_threads)

    number_of_chunks = len(data) // 4
    chunk_per_thread = number_of_chunks / number_of_threads
    split_per_char = chunk_per_thread * 4

    thread_data = []
    for i in range(0, len(data), split_per_char):
        thread_data.append(data[i:i + split_per_char])

    data = ''.join(p.map(f, thread_data))
    p.close()
    return data
Ejemplo n.º 26
0
def main(argv):
    import optparse  # No argparse, which is new in Python 2.7.
    import platform

    parser = optparse.OptionParser()
    parser.add_option('-a', '--artifact-mode', dest='artifact_mode', action='store_true',
                      help='If true, install only the Android SDK (and not the Android NDK).')
    parser.add_option('--ndk-only', dest='ndk_only', action='store_true',
                      help='If true, install only the Android NDK (and not the Android SDK).')
    parser.add_option('--no-interactive', dest='no_interactive', action='store_true',
                      help='Accept the Android SDK licenses without user interaction.')

    options, _ = parser.parse_args(argv)

    if options.artifact_mode and options.ndk_only:
        raise NotImplementedError('Use no options to install the NDK and the SDK.')

    os_name = None
    if platform.system() == 'Darwin':
        os_name = 'macosx'
    elif platform.system() == 'Linux':
        os_name = 'linux'
    elif platform.system() == 'Windows':
        os_name = 'windows'
    else:
        raise NotImplementedError("We don't support bootstrapping the Android SDK (or Android "
                                  "NDK) on {0} yet!".format(platform.system()))

    ensure_android(os_name, artifact_mode=options.artifact_mode,
                   ndk_only=options.ndk_only,
                   no_interactive=options.no_interactive)
    suggest_mozconfig(os_name, options.artifact_mode)

    return 0
Ejemplo n.º 27
0
def configuration(parent_package='',top_path=None):
    from numpy.distutils.misc_util import Configuration
    from numpy.distutils.system_info import get_info
    config = Configuration('solvers',parent_package,top_path)
    lapack = dict(get_info('lapack_opt'))
    # Branch here for different operating systems
    if platform.system() == 'Linux':
        config.add_extension('isolab', sources=['src/isolab.pyf',
                                                'src/solab.f90',
                                                'src/isolab.f90'],
                                       libraries=['lapack'],
                                       library_dirs=lapack['library_dirs'])
    elif platform.system() == 'Darwin':
        lapack['library_dirs'] = ['/usr/lib']
        config.add_extension('isolab', sources=['src/isolab.pyf',
                                                'src/solab.f90',
                                                'src/isolab.f90'],
                                       libraries=['lapack'],
                                       library_dirs=lapack['library_dirs'])
    elif platform.system() == 'Windows':
        config.add_extension('isolab', sources=['src/isolab.pyf',
                                                'src/solab.f90',
                                                'src/isolab.f90'],
                                       libraries=['lapack'],
                                       library_dirs=lapack['library_dirs'])
    return config
Ejemplo n.º 28
0
    def __new__(cls,
                corpus=None, context_type=None,
                K=20, V=0, alpha=[], beta=[],
                multiprocessing=False, seed_or_seeds=None, n_proc=None):

        kwargs = dict(corpus=corpus, context_type=context_type,
                      K=K, V=V, alpha=alpha, beta=beta)
        
        if multiprocessing and platform.system() != 'Windows':
            if n_proc is not None:
                kwargs['n_proc'] = n_proc
            if seed_or_seeds is not None and not isinstance(seed_or_seeds, int):
                kwargs['seeds'] = seed_or_seeds

            return LdaCgsMulti(**kwargs)

        else:
            if multiprocessing and platform.system() == 'Windows':
                warnings.warn("""Multiprocessing is not implemented on Windows.
                Defaulting to sequential algorithm.""", RuntimeWarning)
                
                # extract single seed
                if seed_or_seeds is not None and not isinstance(seed_or_seeds, int):
                    seed_or_seeds = seed_or_seeds[0]
                    warnings.warn("Windows is using only the first seed: " +
                                  str(seed_or_seeds), RuntimeWarning)

            # parse seed_or_seeds argument
            if isinstance(seed_or_seeds, int):
                kwargs['seed'] = seed_or_seeds
            elif seed_or_seeds is not None:
                raise ValueError("LDA(seed_or_seeds, ...) must take an" +
                                 "integer in single-threaded mode.")

            return LdaCgsSeq(**kwargs)
Ejemplo n.º 29
0
def adb_runner(device, params='', stdout=subprocess.PIPE,
               stderr=subprocess.PIPE, cmd='shell', timeout=None):
    cmd = "adb -s %s %s %s" % (device, cmd, params)
    
    if platform.system() == 'Linux' or platform.system() == 'Dalwin':
        sh = True
    else:
        sh = False
    proc = subprocess.Popen(cmd, shell=sh, stdout=stdout,
                                 stderr=stderr)
    
    if timeout:
        begin = time.time()
        current = time.time()
        while current < begin + timeout:
            if proc.poll() is not None:
                break
            current = time.time()
        else:
            proc.terminate()
            proc.wait()
            print "adb command timeout"
        return (proc.stdout.read(), proc.stderr.read())
    else:
        stdout, stderr = proc.communicate()
        return (stdout, stderr)
Ejemplo n.º 30
0
 def get_platform(self):
     dist = ('linux', '0')
     if platform.system().lower() == 'linux':
         dist = platform.linux_distribution()
     elif platform.system().lower() == 'windows':
         dist = ('windows', platform.win32_ver()[0])
     return (self._format_string(dist[0]), self._format_string(dist[1]))
Ejemplo n.º 31
0
 def __init__(self):
     self.Des_Key = "Wang+-*%"  # Key
     self.Des_IV = b"\x19\x90\x07\x14\x06\x12\x08\x23"  # 自定IV向量
     self.authored_result = False
     if system() == "Windows":
         self.wm = wmi.WMI()
Ejemplo n.º 32
0
def to_forward_slash_path(path):
    if platform.system() == "Windows":
        path = path.replace("\\", "/")
    return path
Ejemplo n.º 33
0
	def osName(self):
		return platform.system()
Ejemplo n.º 34
0
import platform
import subprocess
import sys

from setuptools import find_packages
from setuptools import setup
from setuptools.command import install
from setuptools.command import test

PLATFORM_SUFFIXES = {
    'Linux': 'linux',
    'Windows': 'win64',
    'Darwin': 'macos',
}
DEFAULT_HEADERS_DIR = '~/.mujoco/mujoco200_{}/include'.format(
    PLATFORM_SUFFIXES[platform.system()])

# Relative paths to the binding generator script and the output directory.
AUTOWRAP_PATH = 'dm_control/autowrap/autowrap.py'
MJBINDINGS_DIR = 'dm_control/mujoco/wrapper/mjbindings'

# We specify the header filenames explicitly rather than listing the contents
# of the `HEADERS_DIR` at runtime, since it will probably contain other stuff
# (e.g. `glfw.h`).
HEADER_FILENAMES = [
    'mjdata.h',
    'mjmodel.h',
    'mjrender.h',
    'mjui.h',
    'mjvisualize.h',
    'mjxmacro.h',
Ejemplo n.º 35
0
import os
from Qt import QtWidgets, QtGui, QtCore
import nuke, nukescripts




#------------------------------------------------------------------------------
#-Header
#------------------------------------------------------------------------------




__VERSION__		= '1.0'
__OS__			= platform.system()
__AUTHOR__	 	= "Tianlun Jiang"
__WEBSITE__		= "jiangovfx.com"
__COPYRIGHT__	= "copyright (c) %s - %s" % (__AUTHOR__, __WEBSITE__)

__TITLE__		= "DeepCollect v%s" % __VERSION__


def _version_():
	ver='''

	version 1.0
	- sets a dot node as markers for all deepRecolor node
	- creates DeepMerge node to connect with DeepMarker

	'''
Ejemplo n.º 36
0
 def get_device_name(self):
     # 设备号
     if platform.system() == "Windows":
         return self.get_info('adb shell getprop | findstr "ro.serialno"')
     elif platform.system() == "Darwin":
         return self.get_info('adb shell getprop | grep "ro.serialno"')
Ejemplo n.º 37
0
def generate_common(env):
    """Add internal Builders and construction variables for LaTeX to an Environment."""

    # Add OSX system paths so TeX tools can be found
    # when a list of tools is given the exists() method is not called
    generate_darwin(env)

    # A generic tex file Action, sufficient for all tex files.
    global TeXAction
    if TeXAction is None:
        TeXAction = SCons.Action.Action("$TEXCOM", "$TEXCOMSTR")

    # An Action to build a latex file.  This might be needed more
    # than once if we are dealing with labels and bibtex.
    global LaTeXAction
    if LaTeXAction is None:
        LaTeXAction = SCons.Action.Action("$LATEXCOM", "$LATEXCOMSTR")

    # Define an action to run BibTeX on a file.
    global BibTeXAction
    if BibTeXAction is None:
        BibTeXAction = SCons.Action.Action("$BIBTEXCOM", "$BIBTEXCOMSTR")

    # Define an action to run Biber on a file.
    global BiberAction
    if BiberAction is None:
        BiberAction = SCons.Action.Action("$BIBERCOM", "$BIBERCOMSTR")

    # Define an action to run MakeIndex on a file.
    global MakeIndexAction
    if MakeIndexAction is None:
        MakeIndexAction = SCons.Action.Action("$MAKEINDEXCOM", "$MAKEINDEXCOMSTR")

    # Define an action to run MakeIndex on a file for nomenclatures.
    global MakeNclAction
    if MakeNclAction is None:
        MakeNclAction = SCons.Action.Action("$MAKENCLCOM", "$MAKENCLCOMSTR")

    # Define an action to run MakeIndex on a file for glossaries.
    global MakeGlossaryAction
    if MakeGlossaryAction is None:
        MakeGlossaryAction = SCons.Action.Action("$MAKEGLOSSARYCOM", "$MAKEGLOSSARYCOMSTR")

    # Define an action to run MakeIndex on a file for acronyms.
    global MakeAcronymsAction
    if MakeAcronymsAction is None:
        MakeAcronymsAction = SCons.Action.Action("$MAKEACRONYMSCOM", "$MAKEACRONYMSCOMSTR")

    try:
        environ = env['ENV']
    except KeyError:
        environ = {}
        env['ENV'] = environ

    # Some Linux platforms have pdflatex set up in a way
    # that requires that the HOME environment variable be set.
    # Add it here if defined.
    v = os.environ.get('HOME')
    if v:
        environ['HOME'] = v

    CDCOM = 'cd '
    if platform.system() == 'Windows':
        # allow cd command to change drives on Windows
        CDCOM = 'cd /D '

    env['TEX']      = 'tex'
    env['TEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode -recorder')
    env['TEXCOM']   = CDCOM + '${TARGET.dir} && $TEX $TEXFLAGS ${SOURCE.file}'

    env['PDFTEX']      = 'pdftex'
    env['PDFTEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode -recorder')
    env['PDFTEXCOM']   = CDCOM + '${TARGET.dir} && $PDFTEX $PDFTEXFLAGS ${SOURCE.file}'

    env['LATEX']        = 'latex'
    env['LATEXFLAGS']   = SCons.Util.CLVar('-interaction=nonstopmode -recorder')
    env['LATEXCOM']     = CDCOM + '${TARGET.dir} && $LATEX $LATEXFLAGS ${SOURCE.file}'
    env['LATEXRETRIES'] = 4

    env['PDFLATEX']      = 'pdflatex'
    env['PDFLATEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode -recorder')
    env['PDFLATEXCOM']   = CDCOM + '${TARGET.dir} && $PDFLATEX $PDFLATEXFLAGS ${SOURCE.file}'

    env['BIBTEX']      = 'bibtex'
    env['BIBTEXFLAGS'] = SCons.Util.CLVar('')
    env['BIBTEXCOM']   = CDCOM + '${TARGET.dir} && $BIBTEX $BIBTEXFLAGS ${SOURCE.filebase}'

    env['BIBER']      = 'biber'
    env['BIBERFLAGS'] = SCons.Util.CLVar('')
    env['BIBERCOM']   = CDCOM + '${TARGET.dir} && $BIBER $BIBERFLAGS ${SOURCE.filebase}'

    env['MAKEINDEX']      = 'makeindex'
    env['MAKEINDEXFLAGS'] = SCons.Util.CLVar('')
    env['MAKEINDEXCOM']   = CDCOM + '${TARGET.dir} && $MAKEINDEX $MAKEINDEXFLAGS ${SOURCE.file}'

    env['MAKEGLOSSARY']      = 'makeindex'
    env['MAKEGLOSSARYSTYLE'] = '${SOURCE.filebase}.ist'
    env['MAKEGLOSSARYFLAGS'] = SCons.Util.CLVar('-s ${MAKEGLOSSARYSTYLE} -t ${SOURCE.filebase}.glg')
    env['MAKEGLOSSARYCOM']   = CDCOM + '${TARGET.dir} && $MAKEGLOSSARY ${SOURCE.filebase}.glo $MAKEGLOSSARYFLAGS -o ${SOURCE.filebase}.gls'

    env['MAKEACRONYMS']      = 'makeindex'
    env['MAKEACRONYMSSTYLE'] = '${SOURCE.filebase}.ist'
    env['MAKEACRONYMSFLAGS'] = SCons.Util.CLVar('-s ${MAKEACRONYMSSTYLE} -t ${SOURCE.filebase}.alg')
    env['MAKEACRONYMSCOM']   = CDCOM + '${TARGET.dir} && $MAKEACRONYMS ${SOURCE.filebase}.acn $MAKEACRONYMSFLAGS -o ${SOURCE.filebase}.acr'

    env['MAKENCL']      = 'makeindex'
    env['MAKENCLSTYLE'] = 'nomencl.ist'
    env['MAKENCLFLAGS'] = '-s ${MAKENCLSTYLE} -t ${SOURCE.filebase}.nlg'
    env['MAKENCLCOM']   = CDCOM + '${TARGET.dir} && $MAKENCL ${SOURCE.filebase}.nlo $MAKENCLFLAGS -o ${SOURCE.filebase}.nls'

    env['MAKENEWGLOSSARY']      = 'makeindex'
    env['MAKENEWGLOSSARYCOM']   = CDCOM + '${TARGET.dir} && $MAKENEWGLOSSARY '
Ejemplo n.º 38
0
from glob import glob
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import relpath
from os.path import splitext

from setuptools import Extension
from setuptools import find_packages
from setuptools import setup
import numpy as np

# Enable code coverage for C code: we can't use CFLAGS=-coverage in tox.ini, since that may mess with compiling
# dependencies (e.g. numpy). Therefore we set SETUP_PY_EXT_COVERAGE after deps have been safely installed).
if os.environ.get(
        'SETUP_PY_EXT_COVERAGE') == 'yes' and platform.system() == 'Linux':
    CFLAGS = os.environ[
        'CFLAGS'] = '-fprofile-arcs -ftest-coverage -DNPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION'
    LFLAGS = os.environ['LFLAGS'] = '-lgcov'
else:
    CFLAGS = '-DNPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION -DPy_LIMITED_API'
    LFLAGS = ''

if platform.system() == 'Windows':
    CFLAGS += ' /Ox /Ob2 /Oi /Ot /d2FH4- /GS- /arch:AVX2'
else:
    CFLAGS += ' -mavx2 -fpermissive -Wno-unused-variable -Wno-unused-function -std=c++11 -pthread -falign-functions=32'

if platform.system() == 'Linux':
    LFLAGS += ' -lm'
Ejemplo n.º 39
0
    with open(os.path.join(FIXTURE_DIR, file_name), 'rb') as f:
        contents = f.read()
        return decode_string(contents), None, None


def netstat_subprocess_mock(*args, **kwargs):
    if args[0][0] == 'sh':
        raise OSError()
    elif args[0][0] == 'netstat':
        with open(os.path.join(FIXTURE_DIR, 'netstat'), 'rb') as f:
            contents = f.read()
            return decode_string(contents), None, None


@pytest.mark.skipif(platform.system() != 'Linux',
                    reason="Only runs on Unix systems")
def test_cx_state(aggregator, check):
    instance = {'collect_connection_state': True}
    with mock.patch(
            'datadog_checks.network.network.get_subprocess_output') as out:
        out.side_effect = ss_subprocess_mock
        check._collect_cx_state = True
        check.check(instance)
        for metric, value in iteritems(CX_STATE_GAUGES_VALUES):
            aggregator.assert_metric(metric, value=value)
        aggregator.reset()

        out.side_effect = netstat_subprocess_mock
        check.check(instance)
        for metric, value in iteritems(CX_STATE_GAUGES_VALUES):
Ejemplo n.º 40
0
# import platform
import os
from platform import system
# import ctypes
from ctypes import cdll, create_string_buffer
# import base64
from base64 import b64encode
from pyDes import des, CBC, PAD_PKCS5

if system() == "Windows":
    import wmi
    import json


class Register(object):
    def __init__(self):
        self.Des_Key = "Wang+-*%"  # Key
        self.Des_IV = b"\x19\x90\x07\x14\x06\x12\x08\x23"  # 自定IV向量
        self.authored_result = False
        if system() == "Windows":
            self.wm = wmi.WMI()

    # cpu 序列号
    def get_CPU_info(self):
        if system() == "Windows":
            cpu = []
            cp = self.wm.Win32_Processor()
            for u in cp:
                cpu.append({
                    "Name": u.Name,
                    "Serial Number": u.ProcessorId,
Ejemplo n.º 41
0
def get_temp_dir():
    temp_dir = '/tmp' if platform.system(
    ) == 'Darwin' else tempfile.gettempdir()
    return temp_dir
Ejemplo n.º 42
0
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
'''This file generates shell code for the setup.SHELL scripts to set environment variables'''

from __future__ import print_function
import argparse
import copy
import errno
import os
import platform
import sys

CATKIN_MARKER_FILE = '.catkin'

system = platform.system()
IS_DARWIN = (system == 'Darwin')
IS_WINDOWS = (system == 'Windows')

# subfolder of workspace prepended to CMAKE_PREFIX_PATH
ENV_VAR_SUBFOLDERS = {
    'CMAKE_PREFIX_PATH':
    '',
    'CPATH':
    'include',
    'LD_LIBRARY_PATH' if not IS_DARWIN else 'DYLD_LIBRARY_PATH':
    ['lib', os.path.join('lib', 'x86_64-linux-gnu')],
    'PATH':
    'bin',
    'PKG_CONFIG_PATH': [
        os.path.join('lib', 'pkgconfig'),
Ejemplo n.º 43
0
from setuptools import setup
import os
import sys
import platform
import imp
import argparse

version = imp.load_source('version', 'lib/version.py')

if sys.version_info[:3] < (2, 7, 0):
    sys.exit("Error: Electron Cash requires Python version >= 2.7.0...")

data_files = []

if platform.system() in ['Linux', 'FreeBSD', 'DragonFly']:
    parser = argparse.ArgumentParser()
    parser.add_argument('--root=',
                        dest='root_path',
                        metavar='dir',
                        default='/')
    opts, _ = parser.parse_known_args(sys.argv[1:])
    usr_share = os.path.join(sys.prefix, "share")
    if not os.access(opts.root_path + usr_share, os.W_OK) and \
       not os.access(opts.root_path, os.W_OK):
        if 'XDG_DATA_HOME' in os.environ.keys():
            usr_share = os.environ['XDG_DATA_HOME']
        else:
            usr_share = os.path.expanduser('~/.local/share')
    data_files += [(os.path.join(usr_share,
                                 'applications/'), ['electron.desktop']),
import os
import platform
import shutil

from helpers.CustomCI import CustomInput, CustomPrint

# Detect OS
isWindows = False
isLinux = False
if platform.system() == 'Windows':
    isWindows = True
if platform.system() == 'Linux':
    isLinux = True

# Global command line helpers
extracted = 'extracted/'
bin = 'bin/'
if(isWindows):
    sevenZip = 'bin\\7za.exe'
else:
    sevenZip = '7z'


def main():
    CustomPrint('This utility is for archiving your output folder with password to enchance it\'s security. Secure is a relative term. Choose longer password.')
    isCompressing = CustomInput('Are you (C)ompressing or (D)ecompressing? : ')
    while(True):
        if(isCompressing.upper() == 'C'):
            ListUserFolders()
            print('\n')
            userFolder = CustomInput(
Ejemplo n.º 45
0
    "scipy>=1.2.0",
    "ephem>=3.7.6.0",
    "healpy>=1.14.0",
    "scikit-sparse>=0.4.5",
    "pint-pulsar>=0.8.2",
    "libstempo>=2.4.0",
    "enterprise-pulsar>=3.1.0",
    "emcee",
    "ptmcmcsampler",
]

test_requirements = [
    "pytest",
]

if platform.system() == "Darwin":
    extra_compile_args = ["-O2", "-Xpreprocessor", "-fopenmp", "-fno-wrapv"]
    extra_link_args = ["-liomp5"] if os.getenv("NO_MKL", 0) == 0 else ["-lomp"]
else:
    extra_compile_args = ["-O2", "-fopenmp", "-fno-wrapv"]
    extra_link_args = ["-liomp5"] if os.getenv("NO_MKL", 0) == 0 else []

# Extract version
def get_version():
    with open("enterprise_extensions/__init__.py") as f:
        for line in f.readlines():
            if "__version__" in line:
                return line.split('"')[1]


setup(
Ejemplo n.º 46
0
        *[
            pytest.lazy_fixture(cloud) for cloud in [
                "real_s3",  # NOTE: moto's s3 fails in some tests
                "gs",
                "azure",
                "gdrive",
                "oss",
                "http",
                "hdfs",
            ]
        ],
        pytest.param(
            pytest.lazy_fixture("ssh"),
            marks=pytest.mark.xfail(
                raises=DvcException,
                condition=platform.system() == "Windows",
                reason="https://github.com/iterative/dvc/issues/4418",
            ),
        ),
    ],
)
def test_open_external(erepo_dir, cloud):
    erepo_dir.add_remote(config=cloud.config)

    with erepo_dir.chdir():
        erepo_dir.dvc_gen("version", "master", commit="add version")

        with erepo_dir.branch("branch", new="True"):
            # NOTE: need file to be other size for Mac
            erepo_dir.dvc_gen("version", "branchver", commit="add version")
Ejemplo n.º 47
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import imp
import platform
from socket import error, socket, AF_INET, SOCK_STREAM, SOCK_DGRAM, inet_ntoa, gethostname
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT
import struct

fcntl_module_exists = False
fcntl_module = None
if 'Linux' in platform.system():
    module = "fcntl"
    fp, pathname, description = imp.find_module(module)
    try:
        fcntl_module = imp.load_module(module, fp, pathname, description)
        fcntl_module_exists = True
    finally:
        if fp:
            fp.close()


class Network:
    def __init__(self):
        self.hostname = None
        self.domain = None
        self.assertEqual(['foo=bar'], self.conf.default_log_levels)
        self.assertIsNotNone(self.conf.logging_context_format_string)

    def test_tempest_set_log_file(self):
        log.tempest_set_log_file('foo.log')
        log.set_defaults()
        self.conf([])
        self.assertEqual('foo.log', self.conf.log_file)

    def test_log_file_defaults_to_none(self):
        log.set_defaults()
        self.conf([])
        self.assertEqual(None, self.conf.log_file)


@testtools.skipIf(platform.system() != 'Linux',
                  'pyinotify library works on Linux platform only.')
class FastWatchedFileHandlerTestCase(BaseTestCase):

    def setUp(self):
        super(FastWatchedFileHandlerTestCase, self).setUp()

    def _config(self):
        os_level, log_path = tempfile.mkstemp()
        log_dir_path = os.path.dirname(log_path)
        log_file_path = os.path.basename(log_path)
        self.CONF(['--log-dir', log_dir_path, '--log-file', log_file_path])
        self.config(use_stderr=False)
        self.config(watch_log_file=True)
        log.setup(self.CONF, 'test', 'test')
        return log_path
Ejemplo n.º 49
0
# -*- coding: utf-8 -*-
import time as _time

import platform as _platform
if _platform.system() == 'Windows':
    from. import _winmouse as _os_mouse
elif _platform.system() == 'Linux':
    from. import _nixmouse as _os_mouse
elif _platform.system() == 'Darwin':
    from. import _darwinmouse as _os_mouse
else:
    raise OSError("Unsupported platform '{}'".format(_platform.system()))

from ._mouse_event import ButtonEvent, MoveEvent, WheelEvent, LEFT, RIGHT, MIDDLE, X, X2, UP, DOWN, DOUBLE
from ._generic import GenericListener as _GenericListener

_pressed_events = set()
class _MouseListener(_GenericListener):
    def init(self):
        _os_mouse.init()
    def pre_process_event(self, event):
        if isinstance(event, ButtonEvent):
            if event.event_type in (UP, DOUBLE):
                _pressed_events.discard(event.button)
            else:
                _pressed_events.add(event.button)
        return True

    def listen(self):
        _os_mouse.listen(self.queue)
Ejemplo n.º 50
0
#!/usr/bin/env python3

"""Run the tests with https://pytest.org."""

import pathlib
import platform
import sys

import pytest

SELF = pathlib.Path(__file__)

ARGS = [#'--run-slow',
        #'--collect-only',
        '--capture=no',  # a.k.a. -s
        #'--verbose',
        #'--pdb',
        #'--exitfirst',  # a.k.a. -x
        #'-W', 'error',
       ]

if platform.system() == 'Windows' and 'idlelib' in sys.modules:
    ARGS += ['--capture=sys', '--color=no']


print('run', [SELF.name] + sys.argv[1:])
args = ARGS + sys.argv[1:]

print(f'pytest.main({args!r})')
sys.exit(pytest.main(args))
Ejemplo n.º 51
0
# -*- coding: utf-8 -*-
import sys
import os
import time
import json
import operator
from PySide import QtGui, QtCore
import cnoa
import platform
if platform.system() == "Linux":
    import dbus
from blinker import signal

class ActivityLabel(QtGui.QLabel):
    clicked = QtCore.Signal(object)
    def __init__(self):
        super(ActivityLabel, self).__init__()
    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.clicked.emit(self)

class TextInputWidget(QtGui.QTextEdit):
    commited = QtCore.Signal(str)
    def __init__(self):
        super(TextInputWidget, self).__init__()
        #QtGui.QTextEdit.__init__(self)
    def keyPressEvent(self, event):
        modifiers = QtGui.QApplication.keyboardModifiers()
        if modifiers & QtCore.Qt.ControlModifier and \
            (event.key() == QtCore.Qt.Key_Enter or \
            event.key() == QtCore.Qt.Key_Return):
# Python scrip which automatically pulls out adjacent, overlapping
# image pairs based on the pattern of the file names using regular
# expression. Examples are given at the end of the script.

import os, sys, re, platform

#initialize executables for platform
regp = ''
regj = ''
moim = ''
moimp = ''
much = ''

if platform.system() == 'Windows':
    regp = 'register_pair.exe'
    regj = 'register_joint.exe'
    moim = 'mosaic_images.exe'
    moimp = 'mosaic_image_pair.exe'
    much = 'multi_channels_2D.exe'
else:
    regp = 'register_pair'
    regj = 'register_joint'
    moim = 'mosaic_images'
    moimp = 'mosaic_image_pair'
    much = 'multi_channels_2D'
    
# A function to convert a string to a number of base 26. The input is
# assumed to be a string of character
def char_to_num(index):
    index_upper=index.upper()
    power = len(index_upper)
Ejemplo n.º 53
0
from tkinter import *
import platform
import os
import subprocess

root = Tk()
root.geometry('700x400')
root.title("Very Fun Surprise")

operatingsystem = str(platform.system())


def shutdown():
    if operatingsystem == 'Windows':
        os.system("shutdown /s /t 1")
    elif operatingsystem == 'Darwin':
        subprocess.run(['shutdown', '-r', 'now'])
        subprocess.run(['sudo', 'shutdown', '-r', 'now'])
    elif operatingsystem == 'Linux':
        subprocess.run(['shutdown', '-h', 'now'])
        subprocess.run(['sudo', 'shutdown', '-r', 'now'])


dangerWarn = Label(root, text='Fun Surprise\n', fg='#00FF00', font=('*', 30))
dangerWarn.pack()

shutdownButton = Button(root,
                        text='Click me!',
                        command=shutdown,
                        fg='#228B22',
                        font=('*', 20))
Ejemplo n.º 54
0
 def is_supported(self):
     # Only supported by Windows at the moment.
     if "windows" == platform.system().lower():
         return True
     return False
Ejemplo n.º 55
0
            out += c;
        else:
            out += '_';
    return out;

def fix_output_file_name(name):
    filename, extname = os.path.splitext(name);
    basename=os.path.basename(filename);
    dirname=os.path.dirname(filename);
    newname = os.path.normpath(os.path.join(dirname, to_var_name(basename) + extname));
    return newname;

def joinPath(root, subdir):
  return os.path.normpath(os.path.join(root, subdir))

OS_NAME=platform.system()
def toExe(name):
  if OS_NAME == 'Windows':
    return joinPath(BIN_DIR, name+'.exe')
  else:
    return joinPath(BIN_DIR, name)
	
def buildAll():
  os.system('scons')

def removeDir(path):
  if os.path.isdir(path):
     print('rmdir:' + path);
     shutil.rmtree(path)

def prepareOutputDir(name):
Ejemplo n.º 56
0
def main():
    """
    clones and runs spack to setup our third_party libs and
    creates a host-config.cmake file that can be used by
    our project.
    """
    # parse args from command line
    opts, extras = parse_args()

    # load project settings
    project_opts = load_json_file(opts["project_json"])
    if opts["install"]:
        uberenv_pkg_name = project_opts["package_name"]
    else:
        uberenv_pkg_name = project_opts["uberenv_package_name"]
    print "[uberenv project settings: %s]" % str(project_opts)
    print "[uberenv options: %s]" % str(opts)
    if "darwin" in platform.system().lower():
        if opts["macos_sdk_env_setup"]:
            # setup osx deployment target and sdk settings
            setup_osx_sdk_env_vars()
        else:
            print "[skipping MACOSX env var setup]"
    # setup default spec
    if opts["spec"] is None:
        if "darwin" in platform.system().lower():
            opts["spec"] = "%clang"
        else:
            opts["spec"] = "%gcc"
    print "[spack spec: %s]" % opts["spec"]
    # get the current working path, and the glob used to identify the
    # package files we want to hot-copy to spack
    uberenv_path = os.path.split(os.path.abspath(__file__))[0]
    pkgs = pjoin(uberenv_path, "packages", "*")
    # setup destination paths
    dest_dir = os.path.abspath(opts["prefix"])
    dest_spack = pjoin(dest_dir, "spack")
    print "[installing to: %s]" % dest_dir
    # print a warning if the dest path already exists
    if not os.path.isdir(dest_dir):
        os.mkdir(dest_dir)
    else:
        print "[info: destination '%s' already exists]" % dest_dir
    if os.path.isdir(dest_spack):
        print "[info: destination '%s' already exists]" % dest_spack

    if not os.path.isdir(dest_spack):
        print "[info: cloning spack develop branch from github]"
        os.chdir(dest_dir)
        # clone spack into the dest path
        clone_cmd = "git "
        if opts["ignore_ssl_errors"]:
            clone_cmd += "-c http.sslVerify=false "
        spack_url = "https://github.com/spack/spack.git"
        spack_branch = "develop"
        if "spack_url" in project_opts:
            spack_url = project_opts["spack_url"]
        if "spack_branch" in project_opts:
            spack_branch = project_opts["spack_branch"]
        clone_cmd += "clone -b %s %s" % (spack_branch, spack_url)
        sexe(clone_cmd, echo=True)
        if "spack_commit" in project_opts:
            sha1 = project_opts["spack_commit"]
            print "[info: using spack commit %s]" % sha1
            os.chdir(pjoin(dest_dir, "spack"))
            sexe("git checkout %s" % sha1, echo=True)

    if opts["spack_pull"]:
        # do a pull to make sure we have the latest
        os.chdir(pjoin(dest_dir, "spack"))
        sexe("git stash", echo=True)
        sexe("git pull", echo=True)

    os.chdir(dest_dir)
    # twist spack's arms
    cfg_dir = uberenv_spack_config_dir(opts, uberenv_path)
    patch_spack(dest_spack, uberenv_path, cfg_dir, pkgs)

    # show the spec for what will be built
    spec_cmd = "spack/bin/spack spec " + uberenv_pkg_name + opts["spec"]
    res = sexe(spec_cmd, echo=True)

    # clean out any temporary spack build stages
    cln_cmd = "spack/bin/spack clean "
    res = sexe(cln_cmd, echo=True)

    # check if we need to force uninstall of selected packages
    if opts["spack_clean"]:
        if project_opts.has_key("spack_clean_packages"):
            for cln_pkg in project_opts["spack_clean_packages"]:
                if not find_spack_pkg_path(cln_pkg) is None:
                    unist_cmd = "spack/bin/spack uninstall -f -y --all --dependents " + cln_pkg
                    res = sexe(unist_cmd, echo=True)

    ##########################################################
    # we now have an instance of spack configured how we
    # need it to build our tpls at this point there are two
    # possible next steps:
    #
    # *) create a mirror of the packages
    #   OR
    # *) build
    #
    ##########################################################
    if opts["create_mirror"]:
        return create_spack_mirror(opts["mirror"], uberenv_pkg_name,
                                   opts["ignore_ssl_errors"])
    else:
        if not opts["mirror"] is None:
            use_spack_mirror(dest_spack, uberenv_pkg_name, opts["mirror"])
        # use the uberenv package to trigger the right builds
        # and build an host-config.cmake file
        install_cmd = "spack/bin/spack "
        if opts["ignore_ssl_errors"]:
            install_cmd += "-k "
        install_cmd += "install "
        if opts["run_tests"]:
            install_cmd += "--test=root "
        install_cmd += uberenv_pkg_name + opts["spec"]
        res = sexe(install_cmd, echo=True)
        if res != 0:
            return res
        if "spack_activate" in project_opts:
            print "[activating dependent packages]"
            # get the full spack spec for our project
            full_spec = read_spack_full_spec(uberenv_pkg_name, opts["spec"])
            pkg_names = project_opts["spack_activate"].keys()
            for pkg_name in pkg_names:
                pkg_spec_requirements = project_opts["spack_activate"][
                    pkg_name]
                activate = True
                for req in pkg_spec_requirements:
                    if req not in full_spec:
                        activate = False
                        break
                if activate:
                    activate_cmd = "spack/bin/spack activate " + pkg_name
                    sexe(activate_cmd, echo=True)
        # note: this assumes package extends python when +python
        # this may fail general cases
        if opts["install"] and "+python" in full_spec:
            activate_cmd = "spack/bin/spack activate " + uberenv_pkg_name
            sexe(activate_cmd, echo=True)
        # if user opt'd for an install, we want to symlink the final ascent
        # install to an easy place:
        if opts["install"]:
            pkg_path = find_spack_pkg_path(uberenv_pkg_name)
            if uberenv_pkg_name != pkg_path["name"]:
                print "[ERROR: Could not find install of %s]" % uberenv_pkg_name
                return -1
            else:
                pkg_lnk_dir = "%s-install" % uberenv_pkg_name
                if os.path.islink(pkg_lnk_dir):
                    os.unlink(pkg_lnk_dir)
                print ""
                print "[symlinking install to %s]" % pjoin(
                    dest_dir, pkg_lnk_dir)
                os.symlink(pkg_path["path"], os.path.abspath(pkg_lnk_dir))
                hcfg_glob = glob.glob(pjoin(pkg_lnk_dir, "*.cmake"))
                if len(hcfg_glob) > 0:
                    hcfg_path = hcfg_glob[0]
                    hcfg_fname = os.path.split(hcfg_path)[1]
                    if os.path.islink(hcfg_fname):
                        os.unlink(hcfg_fname)
                    print "[symlinking host config file to %s]" % pjoin(
                        dest_dir, hcfg_fname)
                    os.symlink(hcfg_path, hcfg_fname)
                print ""
                print "[install complete!]"
        return res
Ejemplo n.º 57
0
import sys
import subprocess
import tempfile
import argparse


DIR_PATH = os.path.dirname(os.path.realpath(__file__))

COCOS2D_X = os.path.abspath(os.path.join(DIR_PATH, "../.."))
# ROOT_DIR/cocos2d-x
ROOT_DIR = os.path.abspath(os.path.join(COCOS2D_X, ".."))

ANDROID_NDK = os.path.join(ROOT_DIR, "android-ndk-r19")
ANDROID_SDK = os.path.join(ROOT_DIR, "android-sdk")
SDK_MANAGER = os.path.join(ROOT_DIR, "sdk_tools/tools/bin/sdkmanager")
SYSTEM = platform.system().lower()
if SYSTEM == "windows":
    SDK_MANAGER = SDK_MANAGER + ".bat"


def run(command):
    print("=" * 80)
    print(command)
    subprocess.check_call(command.split())


def run_with_yes(command):
    print("=" * 80)
    print("yes|" + command)
    f = tempfile.TemporaryFile("w")
    repeat_yes = 50
Ejemplo n.º 58
0
import pyautogui as ag
import pygetwindow as gw
import os
import subprocess
import signal
from time import time
import platform
import shutil
from PIL import Image

OS_is_MAC = False

if platform.system() == "Windows":
    bar = '\\'

elif platform.system() == "Darwin":
	OS_is_MAC = True
	bar = '/'
else:
    bar = '/'

# Perceptor
class state():
	n = 0
	nt = 0
	ct = 0.0
	def __init__(self, window,path, name):
		self.win = window
		self.name = name
		self.path = path
		if not os.path.exists(self.path+bar+'img'):
Ejemplo n.º 59
0
def word_cloud(book_name):
    # !pip install wordcloud

    import nltk
    from konlpy.corpus import kobill
    from konlpy.tag import Twitter
    t = Twitter()
    from wordcloud import WordCloud

    import matplotlib.pyplot as plt
    import platform
    import io
    import base64
    img = io.BytesIO()

    # OS별 matplotlib 한국어 처리
    path = "static/AppleGothic.ttf"  # window 사용자의 경우 path 설정 중요
    from matplotlib import font_manager, rc
    if platform.system() == 'Darwin':
        rc('font', family='AppleGothic')
    elif platform.system() == 'Windows':
        font_name = font_manager.FontProperties(fname=path).get_name()
        rc('font', family=font_name)
    else:
        print('Unknown system... sorry~~~~')

    # 워드 클라우드 만들기 시작

    files_ko = kobill.fileids()
    books_all = pd.read_csv('static/books_all.csv')

    book_name = book_name  # input으로 받음

    files_ko = kobill.fileids()

    doc_ko = books_all[books_all['name'] == book_name].iloc[0].text
    tokens_ko = t.nouns(doc_ko)

    with open('static/project_stopwords.txt', 'r', encoding='utf-8') as f:
        stop_words = f.read().split(' ')

    ko = nltk.Text(tokens_ko)
    ko = [each_word for each_word in ko if each_word not in stop_words]
    ko = nltk.Text(ko)

    data = ko.vocab().most_common(150)

    # for win : font_path='c:/Windows/Fonts/malgun.ttf'
    wordcloud = WordCloud(
        font_path='static/AppleGothic.ttf',
        relative_scaling=0.2,
        background_color='white',
    ).generate_from_frequencies(dict(data))

    plt.figure(figsize=(12, 8))
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.savefig(img, format='png')
    img.seek(0)

    return base64.b64encode(img.getvalue()).decode()
Ejemplo n.º 60
0
def is_case_insensitive_os():
    system = platform.system()
    return system != "Linux" and system != "FreeBSD" and system != "SunOS"