sys.platform.lower.startswith

Here are the examples of the python api sys.platform.lower.startswith taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

69 Examples 7

Example 1

Project: membase-cli
Source File: pump.py
View license
    def bar(self, current, total):
        if not total:
            return '.'
        if sys.platform.lower().startswith('win'):
            cr = "\r"
        else:
            cr = chr(27) + "[A\n"
        pct = float(current) / total
        max_hash = 20
        num_hash = int(round(pct * max_hash))
        return ("  [%s%s] %0.1f%% (%s/%s msgs)%s" %
                ('#' * num_hash, ' ' * (max_hash - num_hash),
                 100.0 * pct, current, total, cr))

Example 2

Project: pyviennacl-dev
Source File: aksetup_helper.py
View license
    def __init__(self, options, conf_file="siteconf.py", conf_dir="."):
        self.optdict = dict((opt.name, opt) for opt in options)
        self.options = options
        self.conf_dir = conf_dir
        self.conf_file = conf_file

        from os.path import expanduser
        self.user_conf_file = expanduser("~/.aksetup-defaults.py")

        import sys
        if not sys.platform.lower().startswith("win"):
            self.global_conf_file = "/etc/aksetup-defaults.py"
        else:
            self.global_conf_file = None

Example 3

Project: pexpect
Source File: test_expect.py
View license
    def test_expect_setecho_off(self):
        '''This tests that echo may be toggled off.
        '''
        p = pexpect.spawn('cat', echo=True, timeout=5)
        try:
            self._expect_echo_toggle(p)
        except IOError:
            if sys.platform.lower().startswith('sunos'):
                if hasattr(unittest, 'SkipTest'):
                    raise unittest.SkipTest("Not supported on this platform.")
                return 'skip'
            raise

Example 4

Project: hedge
Source File: aksetup_helper.py
View license
    def __init__(self, options, conf_file="siteconf.py", conf_dir="."):
        self.optdict = dict((opt.name, opt) for opt in options)
        self.options = options
        self.conf_dir = conf_dir
        self.conf_file = conf_file

        from os.path import expanduser
        self.user_conf_file = expanduser("~/.aksetup-defaults.py")

        import sys
        if not sys.platform.lower().startswith("win"):
            self.global_conf_file = "/etc/aksetup-defaults.py"
        else:
            self.global_conf_file = None

Example 5

Project: xraylarch
Source File: periodictable.py
View license
    def __init__(self, parent, title='Select Element',
                 onselect=None, tooltip_msg=None, size=(-1, -1), **kws):
        wx.Panel.__init__(self, parent, -1, size=size, name='PeriodicTable', **kws)
        self.parent = parent
        self.onselect = onselect
        self.tooltip_msg = tooltip_msg
        self.wids = {}
        self.ctrls = {}
        self.SetBackgroundColour(self.FRAME_BG)
        self.selected = None
        self.titlefont    = wx.Font(10,  wx.DEFAULT, wx.NORMAL, wx.BOLD)
        self.elemfont     = wx.Font( 9,  wx.SWISS,   wx.NORMAL, wx.NORMAL)
        self.subtitlefont = wx.Font( 7,  wx.DEFAULT, wx.NORMAL, wx.BOLD)
        if sys.platform.lower().startswith('win'):
            self.elemfont     = wx.Font( 8,  wx.SWISS,   wx.NORMAL, wx.BOLD)
            self.subtitlefont = wx.Font( 8,  wx.DEFAULT, wx.NORMAL, wx.BOLD)
            
        self.BuildPanel()

Example 6

Project: membase-cli
Source File: pump.py
View license
    def bar(self, current, total):
        if not total:
            return '.'
        if sys.platform.lower().startswith('win'):
            cr = "\r"
        else:
            cr = chr(27) + "[A\n"
        pct = float(current) / total
        max_hash = 20
        num_hash = int(round(pct * max_hash))
        return ("  [%s%s] %0.1f%% (%s/%s msgs)%s" %
                ('#' * num_hash, ' ' * (max_hash - num_hash),
                 100.0 * pct, current, total, cr))

Example 7

Project: pexpect
Source File: test_unicode.py
View license
    def test_expect_setecho_toggle_exact(self):
        p = pexpect.spawnu('cat', timeout=5)
        p.expect = p.expect_exact
        try:
            self._expect_echo_toggle_off(p)
        except IOError:
            if sys.platform.lower().startswith('sunos'):
                if hasattr(unittest, 'SkipTest'):
                    raise unittest.SkipTest("Not supported on this platform.")
                return 'skip'
            raise
        self._expect_echo_toggle_on(p)

Example 8

Project: nupic
Source File: syntactic_sugar_test.py
View license
  @unittest.skipIf(sys.platform.lower().startswith("win"),
                   "Not supported on Windows, yet!")
  def testSpec(self):
    ns = net.Region.getSpecFromType('py.TestNode')
    self.assertEqual(ns.description,
                     'The node spec of the NuPIC 2 Python TestNode')

    n = net.Network()
    r = n.addRegion('r', 'py.TestNode', '')

    ns2 = r.spec
    self.assertEqual(ns.singleNodeOnly, ns2.singleNodeOnly)
    self.assertEqual(ns.description, ns2.description)
    self.assertEqual(ns.inputs, ns2.inputs)
    self.assertEqual(ns.outputs, ns2.outputs)
    self.assertEqual(ns.parameters, ns2.parameters)
    self.assertEqual(ns.commands, ns2.commands)

Example 9

Project: FunkLoad
Source File: BenchRunner.py
View license
    def __init__(self, test_module, test_class, test_name, options,
                 cycle, cvus, thread_id, thread_signaller, sleep_time,
                 debug=False, feedback=None):
        meta_method_name = mmn_encode(test_name, cycle, cvus, thread_id)
        threading.Thread.__init__(self, target=self.run, name=meta_method_name,
                                  args=())
        self.test = load_unittest(test_module, test_class, meta_method_name,
                                  options)
        if sys.platform.lower().startswith('win'):
            self.color = False
        else:
            self.color = not options.no_color
        self.sleep_time = sleep_time
        self.debug = debug
        self.thread_signaller = thread_signaller
        # this makes threads endings if main stop with a KeyboardInterupt
        self.setDaemon(1)
        self.feedback = feedback

Example 10

Project: pexpect
Source File: test_isalive.py
View license
    def test_expect_isalive_dead_after_SIGHUP(self):
        p = pexpect.spawn('cat', timeout=5, ignore_sighup=False)
        assert p.isalive()
        force = False
        if sys.platform.lower().startswith('sunos'):
            # On Solaris (SmartOs), and only when executed from cron(1), SIGKILL
            # is required to end the sub-process. This is done using force=True
            force = True
        assert p.terminate(force) == True
        p.expect(pexpect.EOF)
        assert not p.isalive()

Example 11

Project: PyChecker
Source File: setup.py
View license
def get_site_packages_path():
   """
   Returns the platform-specific location of the site-packages directory.
   This directory is usually something like /usr/share/python2.3/site-packages
   on UNIX platforms and /Python23/Lib/site-packages on Windows platforms.
   """
   if sys.platform.lower().startswith('win'):
      return os.path.join(sys.prefix, "Lib", "site-packages")
   else:
      return os.path.join(sys.prefix, "lib", 
                          "python%s" % sys.version[:3], 
                          "site-packages")

Example 12

Project: pexpect
Source File: test_expect.py
View license
    def test_expect_setecho_off_exact(self):
        p = pexpect.spawn('cat', echo=True, timeout=5)
        p.expect = p.expect_exact
        try:
            self._expect_echo_toggle(p)
        except IOError:
            if sys.platform.lower().startswith('sunos'):
                if hasattr(unittest, 'SkipTest'):
                    raise unittest.SkipTest("Not supported on this platform.")
                return 'skip'
            raise

Example 13

Project: pexpect
Source File: test_misc.py
View license
    def test_isatty(self):
        " Test isatty() is True after spawning process on most platforms. "
        child = pexpect.spawn('cat')
        if not child.isatty() and sys.platform.lower().startswith('sunos'):
            if hasattr(unittest, 'SkipTest'):
                raise unittest.SkipTest("Not supported on this platform.")
            return 'skip'
        assert child.isatty()

Example 14

Project: pexpect
Source File: test_expect.py
View license
    def test_waitnoecho(self):
        " Tests setecho(False) followed by waitnoecho() "
        p = pexpect.spawn('cat', echo=False, timeout=5)
        try:
            p.setecho(False)
            p.waitnoecho()
        except IOError:
            if sys.platform.lower().startswith('sunos'):
                if hasattr(unittest, 'SkipTest'):
                    raise unittest.SkipTest("Not supported on this platform.")
                return 'skip'
            raise

Example 15

Project: pexpect
Source File: test_unicode.py
View license
    def test_expect_setecho_toggle(self):
        '''This tests that echo may be toggled off.
        '''
        p = pexpect.spawnu('cat', timeout=5)
        try:
            self._expect_echo_toggle_off(p)
        except IOError:
            if sys.platform.lower().startswith('sunos'):
                if hasattr(unittest, 'SkipTest'):
                    raise unittest.SkipTest("Not supported on this platform.")
                return 'skip'
            raise
        self._expect_echo_toggle_on(p)

Example 16

Project: benchbase
Source File: util.py
View license
def gnuplot(script_path):
    """Execute a gnuplot script."""
    path = os.path.dirname(os.path.abspath(script_path))
    if sys.platform.lower().startswith('win'):
        # commands module doesn't work on win and gnuplot is named
        # wgnuplot
        ret = os.system('cd "%s" && wgnuplot "%s"' %
                        path, script_path)
        if ret != 0:
            raise RuntimeError("Failed to run wgnuplot cmd on " +
                               script_path)

    else:
        cmd = 'cd %s && gnuplot %s' % (path, os.path.abspath(script_path))
        ret, output = getstatusoutput(cmd)
        if ret != 0:
            print "ERROR on " + cmd

Example 17

Project: FunkLoad
Source File: ReportRenderHtmlGnuPlot.py
View license
def gnuplot(script_path):
    """Execute a gnuplot script."""
    path = os.path.dirname(os.path.abspath(script_path))
    if sys.platform.lower().startswith('win'):
        # commands module doesn't work on win and gnuplot is named
        # wgnuplot
        ret = os.system('cd "' + path + '" && wgnuplot "' +
                        os.path.abspath(script_path) + '"')
        if ret != 0:
            raise RuntimeError("Failed to run wgnuplot cmd on " +
                               os.path.abspath(script_path))

    else:
        cmd = 'cd "' + path + '"; gnuplot "' + os.path.abspath(script_path) + '"'
        ret, output = getstatusoutput(cmd)
        if ret != 0:
            raise RuntimeError("Failed to run gnuplot cmd: " + cmd +
                               "\n" + str(output))

Example 18

Project: nupic
Source File: syntactic_sugar_test.py
View license
  @unittest.skipIf(sys.platform.lower().startswith("win"),
                   "Not supported on Windows, yet!")
  def testRegion(self):
    r = net.Network().addRegion('r', 'py.TestNode', '')

    print r.spec
    self.assertEqual(r.type, 'py.TestNode')
    self.assertEqual(r.name, 'r')
    self.assertTrue(r.dimensions.isUnspecified())

Example 19

Project: FunkLoad
Source File: test_Install.py
View license
    def test_xmlrpc(self):
        # windows os does not support the monitor server
        if not sys.platform.lower().startswith('win'):
            # extract demo example and run the xmlrpc test
            from tempfile import mkdtemp
            pwd = os.getcwd()
            tmp_path = mkdtemp('funkload')
            os.chdir(tmp_path)
            self.system('fl-install-demo')
            os.chdir(os.path.join(tmp_path, 'funkload-demo', 'xmlrpc'))
            self.system("fl-credential-ctl cred.conf restart")
            self.system("fl-monitor-ctl monitor.conf restart")
            self.system("fl-run-test -v test_Credential.py")
            self.system("fl-run-bench -c 1:10:20 -D 4 "
                        "test_Credential.py Credential.test_credential")
            self.system("fl-monitor-ctl monitor.conf stop")
            self.system("fl-credential-ctl cred.conf stop")
            self.system("fl-build-report credential-bench.xml --html")
            os.chdir(pwd)

Example 20

Project: FunkLoad
Source File: BenchRunner.py
View license
    def __init__(self, test_module, test_class, test_name, options,
                 cycle, cvus, thread_id, thread_signaller, sleep_time,
                 debug=False, feedback=None):
        meta_method_name = mmn_encode(test_name, cycle, cvus, thread_id)
        threading.Thread.__init__(self, target=self.run, name=meta_method_name,
                                  args=())
        self.test = load_unittest(test_module, test_class, meta_method_name,
                                  options)
        if sys.platform.lower().startswith('win'):
            self.color = False
        else:
            self.color = not options.no_color
        self.sleep_time = sleep_time
        self.debug = debug
        self.thread_signaller = thread_signaller
        # this makes threads endings if main stop with a KeyboardInterupt
        self.setDaemon(1)
        self.feedback = feedback

Example 21

Project: FunkLoad
Source File: test_Install.py
View license
    def system(self, cmd, expected_code=0):
        """Execute a cmd and exit on fail return cmd output."""

        if sys.platform.lower().startswith('win'):
            ret = winplatform_getstatusoutput(cmd)
            if not ret:
                self.fail('Cannot run self.system on windows without the subprocess module (python 2.6)')
        else:
            ret = commands.getstatusoutput(cmd)

        if ret[0] != expected_code:
            self.fail("exec [%s] return code %s != %s output:\n%s" %
                      (cmd, ret[0], expected_code, ret[1]))
        return ret[1]

Example 22

Project: xraylarch
Source File: site_config.py
View license
def system_settings():
    """set system-specific Environmental Variables, and make sure
    that the user larchdirs exist.
    This is run by the interpreter on startup."""
    # ubuntu / unity hack
    if sys.platform.lower().startswith('linux'):
        if 'ubuntu' in os.uname()[3].lower():
            os.environ['UBUNTU_MENUPROXY'] = '0'
    make_user_larchdirs()

Example 23

Project: FunkLoad
Source File: test_Install.py
View license
    def test_xmlrpc(self):
        # windows os does not support the monitor server
        if not sys.platform.lower().startswith('win'):
            # extract demo example and run the xmlrpc test
            from tempfile import mkdtemp
            pwd = os.getcwd()
            tmp_path = mkdtemp('funkload')
            os.chdir(tmp_path)
            self.system('fl-install-demo')
            os.chdir(os.path.join(tmp_path, 'funkload-demo', 'xmlrpc'))
            self.system("fl-credential-ctl cred.conf restart")
            self.system("fl-monitor-ctl monitor.conf restart")
            self.system("fl-run-test -v test_Credential.py")
            self.system("fl-run-bench -c 1:10:20 -D 4 "
                        "test_Credential.py Credential.test_credential")
            self.system("fl-monitor-ctl monitor.conf stop")
            self.system("fl-credential-ctl cred.conf stop")
            self.system("fl-build-report credential-bench.xml --html")
            os.chdir(pwd)

Example 24

Project: focus
Source File: daemon.py
View license
    def _prepare(self):
        """ Setup initial requirements for daemon run.
            """

        super(TaskRunner, self)._prepare()
        self._setup_root_plugins()

        # set the default x-window display for non-mac systems
        if not sys.platform.lower().startswith('darwin'):
            if not 'DISPLAY' in os.environ:
                os.environ['DISPLAY'] = ':0.0'

Example 25

Project: nupic
Source File: syntactic_sugar_test.py
View license
  @unittest.skipIf(sys.platform.lower().startswith("win"),
                   "Not supported on Windows, yet!")
  def testRegion(self):
    r = net.Network().addRegion('r', 'py.TestNode', '')

    print r.spec
    self.assertEqual(r.type, 'py.TestNode')
    self.assertEqual(r.name, 'r')
    self.assertTrue(r.dimensions.isUnspecified())

Example 26

Project: FunkLoad
Source File: ReportRenderHtmlGnuPlot.py
View license
def gnuplot(script_path):
    """Execute a gnuplot script."""
    path = os.path.dirname(os.path.abspath(script_path))
    if sys.platform.lower().startswith('win'):
        # commands module doesn't work on win and gnuplot is named
        # wgnuplot
        ret = os.system('cd "' + path + '" && wgnuplot "' +
                        os.path.abspath(script_path) + '"')
        if ret != 0:
            raise RuntimeError("Failed to run wgnuplot cmd on " +
                               os.path.abspath(script_path))

    else:
        cmd = 'cd "' + path + '"; gnuplot "' + os.path.abspath(script_path) + '"'
        ret, output = getstatusoutput(cmd)
        if ret != 0:
            raise RuntimeError("Failed to run gnuplot cmd: " + cmd +
                               "\n" + str(output))

Example 27

Project: catkin
Source File: builder.py
View license
def get_multiarch():
    if not sys.platform.lower().startswith('linux'):
        return ''
    # this function returns the suffix for lib directories on supported systems or an empty string
    # it uses two step approach to look for multiarch: first run gcc -print-multiarch and if
    # failed try to run dpkg-architecture
    p = subprocess.Popen(
        ['gcc', '-print-multiarch'],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate()
    if p.returncode != 0:
        out, err = subprocess.Popen(
            ['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

    # be sure of returning empty string or a valid multiarch tuple format
    assert(not out.strip() or out.strip().count('-') == 2)
    return out.strip()

Example 28

Project: FunkLoad
Source File: test_Install.py
View license
    def system(self, cmd, expected_code=0):
        """Execute a cmd and exit on fail return cmd output."""

        if sys.platform.lower().startswith('win'):
            ret = winplatform_getstatusoutput(cmd)
            if not ret:
                self.fail('Cannot run self.system on windows without the subprocess module (python 2.6)')
        else:
            ret = commands.getstatusoutput(cmd)

        if ret[0] != expected_code:
            self.fail("exec [%s] return code %s != %s output:\n%s" %
                      (cmd, ret[0], expected_code, ret[1]))
        return ret[1]

Example 29

Project: nupic
Source File: syntactic_sugar_test.py
View license
  @unittest.skipIf(sys.platform.lower().startswith("win"),
                   "Not supported on Windows, yet!")
  def testSpec(self):
    ns = net.Region.getSpecFromType('py.TestNode')
    self.assertEqual(ns.description,
                     'The node spec of the NuPIC 2 Python TestNode')

    n = net.Network()
    r = n.addRegion('r', 'py.TestNode', '')

    ns2 = r.spec
    self.assertEqual(ns.singleNodeOnly, ns2.singleNodeOnly)
    self.assertEqual(ns.description, ns2.description)
    self.assertEqual(ns.inputs, ns2.inputs)
    self.assertEqual(ns.outputs, ns2.outputs)
    self.assertEqual(ns.parameters, ns2.parameters)
    self.assertEqual(ns.commands, ns2.commands)

Example 30

Project: pexpect
Source File: test_isalive.py
View license
    def test_expect_isalive_dead_after_SIGINT(self):
        p = pexpect.spawn('cat', timeout=5)
        assert p.isalive()
        force = False
        if sys.platform.lower().startswith('sunos'):
            # On Solaris (SmartOs), and only when executed from cron(1), SIGKILL
            # is required to end the sub-process. This is done using force=True
            force = True
        assert p.terminate(force) == True
        p.expect(pexpect.EOF)
        assert not p.isalive()

Example 31

Project: couchbase-cli
Source File: pump.py
View license
    def bar(self, current, total):
        if not total:
            return '.'
        if sys.platform.lower().startswith('win'):
            cr = "\r"
        else:
            cr = chr(27) + "[A\n"
        pct = float(current) / total
        max_hash = 20
        num_hash = int(round(pct * max_hash))
        return ("  [%s%s] %0.1f%% (%s/estimated %s msgs)%s" %
                ('#' * num_hash, ' ' * (max_hash - num_hash),
                 100.0 * pct, current, total, cr))

Example 32

Project: Ropper
Source File: options.py
View license
    def isWindows(self):
      return sys.platform.lower().startswith('win')

Example 33

Project: dit
Source File: setup.py
View license
def hack_distutils(debug=False, fast_link=True):
    # hack distutils.sysconfig to eliminate debug flags
    # stolen from mpi4py

    def remove_prefixes(optlist, bad_prefixes):
        for bad_prefix in bad_prefixes:
            for i, flag in enumerate(optlist):
                if flag.startswith(bad_prefix):
                    optlist.pop(i)
                    break
        return optlist

    import sys
    if not sys.platform.lower().startswith("win"):
        from distutils import sysconfig

        cvars = sysconfig.get_config_vars()
        cflags = cvars.get('OPT')
        if cflags:
            cflags = remove_prefixes(cflags.split(),
                    ['-g', '-O', '-Wstrict-prototypes', '-DNDEBUG'])
            if debug:
                cflags.append("-g")
            else:
                cflags.append("-O3")
                cflags.append("-DNDEBUG")
            cvars['OPT'] = str.join(' ', cflags)
            cvars["CFLAGS"] = cvars["BASECFLAGS"] + " " + cvars["OPT"]

        if fast_link:
            for varname in ["LDSHARED", "BLDSHARED"]:
                ldsharedflags = cvars.get(varname)
                if ldsharedflags:
                    ldsharedflags = remove_prefixes(ldsharedflags.split(),
                            ['-Wl,-O'])
                    cvars[varname] = str.join(' ', ldsharedflags)

Example 34

Project: txstatsd
Source File: test_process.py
View license
    def test_cpu_counters(self):
        """System cpu counters are collected through psutil."""
        cpu_times = psutil.cpu_times()
        with mock.patch("psutil.cpu_times"):
            psutil.cpu_times.return_value = cpu_times
            result = report_system_stats()
            psutil.cpu_times.assert_called_once_with(percpu=False)
        # cpu_times is platform-dependent
        if sys.platform.lower().startswith("linux"):
            self.assertEqual(cpu_times.user, result["sys.cpu.user"])
            self.assertEqual(cpu_times.system, result["sys.cpu.system"])
            self.assertEqual(cpu_times.idle, result["sys.cpu.idle"])
            self.assertEqual(cpu_times.iowait, result["sys.cpu.iowait"])
            self.assertEqual(cpu_times.irq, result["sys.cpu.irq"])
        elif sys.platform.lower().startswith("win32"):
            self.assertEqual(cpu_times.user, result["sys.cpu.user"])
            self.assertEqual(cpu_times.system, result["sys.cpu.system"])
            self.assertEqual(cpu_times.idle, result["sys.cpu.idle"])
        elif sys.platform.lower().startswith("darwin"):
            self.assertEqual(cpu_times.user, result["sys.cpu.user"])
            self.assertEqual(cpu_times.system, result["sys.cpu.system"])
            self.assertEqual(cpu_times.idle, result["sys.cpu.idle"])
            self.assertEqual(cpu_times.nice, result["sys.cpu.nice"])
        elif sys.platform.lower().startswith("freebsd"):
            self.assertEqual(cpu_times.user, result["sys.cpu.user"])
            self.assertEqual(cpu_times.system, result["sys.cpu.system"])
            self.assertEqual(cpu_times.idle, result["sys.cpu.idle"])
            self.assertEqual(cpu_times.irq, result["sys.cpu.irq"])

Example 35

Project: hedge
Source File: aksetup_helper.py
View license
def hack_distutils(debug=False, fast_link=True, what_opt=3):
    # hack distutils.sysconfig to eliminate debug flags
    # stolen from mpi4py

    def remove_prefixes(optlist, bad_prefixes):
        for bad_prefix in bad_prefixes:
            for i, flag in enumerate(optlist):
                if flag.startswith(bad_prefix):
                    optlist.pop(i)
                    break
        return optlist

    import sys
    if not sys.platform.lower().startswith("win"):
        from distutils import sysconfig

        cvars = sysconfig.get_config_vars()
        cflags = cvars.get('OPT')
        if cflags:
            cflags = remove_prefixes(cflags.split(),
                    ['-g', '-O', '-Wstrict-prototypes', '-DNDEBUG'])
            if debug:
                cflags.append("-g")
            else:
                if what_opt is None:
                    pass
                else:
                    cflags.append("-O%s" % what_opt)
                    cflags.append("-DNDEBUG")

            cvars['OPT'] = str.join(' ', cflags)
            cvars["CFLAGS"] = cvars["BASECFLAGS"] + " " + cvars["OPT"]

        if fast_link:
            for varname in ["LDSHARED", "BLDSHARED"]:
                ldsharedflags = cvars.get(varname)
                if ldsharedflags:
                    ldsharedflags = remove_prefixes(ldsharedflags.split(),
                            ['-Wl,-O'])
                    cvars[varname] = str.join(' ', ldsharedflags)

Example 36

Project: larva-lang
Source File: to_go.py
View license
def _gen_makefile():
    if sys.platform.lower().startswith("win"):
        f = open(os.path.join(out_dir, "make.bat"), "w")
        print >> f, "@set GOPATH=%s" % out_dir
        print >> f, "go build -o %s.exe src/lar_prog_%s/lar_prog.%s.go" % (main_module_name, main_module_name, main_module_name)
        print >> f, "@if %ERRORLEVEL% == 0 goto success"
        print >> f, "@pause"
        print >> f, ":success"
        f = open(os.path.join(out_dir, "make_and_run.bat"), "w")
        print >> f, "@set GOPATH=%s" % out_dir
        print >> f, "go build -o %s.exe src/lar_prog_%s/lar_prog.%s.go" % (main_module_name, main_module_name, main_module_name)
        print >> f, "@if %ERRORLEVEL% == 0 goto success"
        print >> f, "@pause"
        print >> f, "@exit"
        print >> f, ":success"
        print >> f, "%s.exe" % main_module_name
        print >> f, "@pause"
        print >> f, "@exit"
    else:
        raise Exception("Not implemented on '%s'" % sys.platform)

Example 37

Project: txstatsd
Source File: test_process.py
View license
    def test_per_cpu_counters(self):
        """System percpu counters are collected through psutil."""
        cpu_times = psutil.cpu_times()
        with mock.patch("psutil.cpu_times"):
            psutil.cpu_times.return_value = [cpu_times, cpu_times]
            result = report_system_stats(percpu=True)
            psutil.cpu_times.assert_called_once_with(percpu=True)
        # cpu_times is platform-dependent
        if sys.platform.lower().startswith("linux"):
            self.assertEqual(cpu_times.user, result["sys.cpu.000.user"])
            self.assertEqual(cpu_times.system, result["sys.cpu.000.system"])
            self.assertEqual(cpu_times.idle, result["sys.cpu.000.idle"])
            self.assertEqual(cpu_times.iowait, result["sys.cpu.000.iowait"])
            self.assertEqual(cpu_times.irq, result["sys.cpu.001.irq"])
            self.assertEqual(cpu_times.user, result["sys.cpu.001.user"])
            self.assertEqual(cpu_times.system, result["sys.cpu.001.system"])
            self.assertEqual(cpu_times.idle, result["sys.cpu.001.idle"])
            self.assertEqual(cpu_times.iowait, result["sys.cpu.001.iowait"])
            self.assertEqual(cpu_times.irq, result["sys.cpu.001.irq"])
        elif sys.platform.lower().startswith("win32"):
            self.assertEqual(cpu_times.user, result["sys.cpu.000.user"])
            self.assertEqual(cpu_times.system, result["sys.cpu.000.system"])
            self.assertEqual(cpu_times.idle, result["sys.cpu.000.idle"])
            self.assertEqual(cpu_times.user, result["sys.cpu.001.user"])
            self.assertEqual(cpu_times.system, result["sys.cpu.001.system"])
            self.assertEqual(cpu_times.idle, result["sys.cpu.001.idle"])
        elif sys.platform.lower().startswith("darwin"):
            self.assertEqual(cpu_times.user, result["sys.cpu.000.user"])
            self.assertEqual(cpu_times.system, result["sys.cpu.000.system"])
            self.assertEqual(cpu_times.idle, result["sys.cpu.000.idle"])
            self.assertEqual(cpu_times.nice, result["sys.cpu.000.nice"])
            self.assertEqual(cpu_times.user, result["sys.cpu.001.user"])
            self.assertEqual(cpu_times.system, result["sys.cpu.001.system"])
            self.assertEqual(cpu_times.idle, result["sys.cpu.001.idle"])
            self.assertEqual(cpu_times.nice, result["sys.cpu.001.nice"])
        elif sys.platform.lower().startswith("freebsd"):
            self.assertEqual(cpu_times.user, result["sys.cpu.000.user"])
            self.assertEqual(cpu_times.system, result["sys.cpu.000.system"])
            self.assertEqual(cpu_times.idle, result["sys.cpu.000.idle"])
            self.assertEqual(cpu_times.irq, result["sys.cpu.000.irq"])
            self.assertEqual(cpu_times.user, result["sys.cpu.001.user"])
            self.assertEqual(cpu_times.system, result["sys.cpu.001.system"])
            self.assertEqual(cpu_times.idle, result["sys.cpu.001.idle"])
            self.assertEqual(cpu_times.irq, result["sys.cpu.001.irq"])

Example 38

Project: larva-lang
Source File: to_go.py
View license
def _gen_makefile():
    if sys.platform.lower().startswith("win"):
        f = open(os.path.join(out_dir, "make.bat"), "w")
        print >> f, "@set GOPATH=%s" % out_dir
        print >> f, "go build -o %s.exe src/lar_prog_%s/lar_prog.%s.go" % (main_module_name, main_module_name, main_module_name)
        print >> f, "@if %ERRORLEVEL% == 0 goto success"
        print >> f, "@pause"
        print >> f, ":success"
        f = open(os.path.join(out_dir, "make_and_run.bat"), "w")
        print >> f, "@set GOPATH=%s" % out_dir
        print >> f, "go build -o %s.exe src/lar_prog_%s/lar_prog.%s.go" % (main_module_name, main_module_name, main_module_name)
        print >> f, "@if %ERRORLEVEL% == 0 goto success"
        print >> f, "@pause"
        print >> f, "@exit"
        print >> f, ":success"
        print >> f, "%s.exe" % main_module_name
        print >> f, "@pause"
        print >> f, "@exit"
    else:
        raise Exception("Not implemented on '%s'" % sys.platform)

Example 39

Project: jaydebeapi
Source File: test_integration.py
View license
def is_jython():
    return sys.platform.lower().startswith('java')

Example 40

Project: nupic
Source File: network_test.py
View license
  @unittest.skipIf(sys.platform.lower().startswith("win"),
                   "Not supported on Windows, yet!")
  def testErrorHandling(self):
    n = engine.Network()

    # Test trying to add non-existent node
    with self.assertRaises(Exception) as cm:
      n.addRegion('r', 'py.NonExistingNode', '')

    self.assertEqual(cm.exception.message, "Matching Python module for NonExistingNode not found.")

    orig_import = __import__
    def import_mock(name, *args):
      if name == "nupic.regions.UnimportableNode":
        raise SyntaxError("invalid syntax (UnimportableNode.py, line 5)")

      return orig_import(name, *args)

    with patch('__builtin__.__import__', side_effect=import_mock):
      # Test failure during import
      with self.assertRaises(Exception) as cm:
        n.addRegion('r', 'py.UnimportableNode', '')

      self.assertEqual(cm.exception.message, "invalid syntax (UnimportableNode.py, line 5)")

    # Test failure in the __init__() method
    with self.assertRaises(Exception) as cm:
      n.addRegion('r', 'py.TestNode', '{ failInInit: 1 }')

    self.assertEqual(cm.exception.message, "TestNode.__init__() Failing on purpose as requested")

    # Test failure inside the compute() method
    with self.assertRaises(Exception) as cm:
      r = n.addRegion('r', 'py.TestNode', '{ failInCompute: 1 }')
      r.dimensions = engine.Dimensions([4, 4])
      n.initialize()
      n.run(1)

    self.assertEqual(str(cm.exception),
      'TestNode.compute() Failing on purpose as requested')

    # Test failure in the static getSpec
    from nupic.bindings.regions.TestNode import TestNode
    TestNode._failIngetSpec = True

    with self.assertRaises(Exception) as cm:
      TestNode.getSpec()

    self.assertEqual(str(cm.exception),
      'Failing in TestNode.getSpec() as requested')

    del TestNode._failIngetSpec

Example 41

Project: nupic
Source File: network_test.py
View license
  @unittest.skipIf(sys.platform.lower().startswith("win"),
                   "Not supported on Windows, yet!")
  def testTwoRegionNetwork(self):
    n = engine.Network()

    region1 = n.addRegion("region1", "TestNode", "")
    region2 = n.addRegion("region2", "TestNode", "")

    names = []
    for name in n.regions:
      names.append(name)
    self.assertEqual(names, ['region1', 'region2'])
    print n.getPhases('region1')
    self.assertEqual(n.getPhases('region1'), (0,))
    self.assertEqual(n.getPhases('region2'), (1,))

    n.link("region1", "region2", "TestFanIn2", "")

    print "Initialize should fail..."
    with self.assertRaises(Exception):
      n.initialize()

    print "Setting region1 dims"
    r1dims = engine.Dimensions([6, 4])
    region1.setDimensions(r1dims)

    print "Initialize should now succeed"
    n.initialize()

    r2dims = region2.dimensions
    self.assertEqual(len(r2dims), 2)
    self.assertEqual(r2dims[0], 3)
    self.assertEqual(r2dims[1], 2)

    # Negative test
    with self.assertRaises(Exception):
      region2.setDimensions(r1dims)

Example 42

Project: nupic
Source File: network_test.py
View license
  @unittest.skipIf(sys.platform.lower().startswith("win"),
                   "Not supported on Windows, yet!")
  def testPyNodeGetSetParameter(self):
    n = engine.Network()

    r = n.addRegion("region", "py.TestNode", "")

    print "Setting region1 dims"
    r.dimensions = engine.Dimensions([6, 4])

    print "Initialize should now succeed"
    n.initialize()

    result = r.getParameterReal64('real64Param')
    self.assertEqual(result, 64.1)

    r.setParameterReal64('real64Param', 77.7)

    result = r.getParameterReal64('real64Param')
    self.assertEqual(result, 77.7)

Example 43

Project: abjad
Source File: IOManager.py
View license
    @staticmethod
    def open_file(file_path, application=None, line_number=None):
        r'''Opens `file_path`.

        Uses `application` when `application` is not none.

        Uses Abjad configuration file `text_editor` when
        `application` is none.

        Takes best guess at operating system-specific file opener when both
        `application` and Abjad configuration file `text_editor` are none.

        Respects `line_number` when `file_path` can be opened with text editor.

        Returns none.
        '''
        from abjad import abjad_configuration
        if sys.platform.lower().startswith('win'):
            os.startfile(file_path)
            return
        viewer = None
        if sys.platform.lower().startswith('linux'):
            viewer = application or 'xdg-open'
        elif file_path.endswith('.pdf'):
            viewer = application or abjad_configuration['pdf_viewer']
        elif file_path.endswith((
            '.log',
            '.py',
            '.rst',
            '.txt',
            )):
            viewer = application or abjad_configuration['text_editor']
        elif file_path.endswith((
            '.mid',
            '.midi',
            )):
            viewer = application or abjad_configuration['midi_player']
        viewer = viewer or 'open'
        if line_number:
            command = '{} +{} {}'.format(viewer, line_number, file_path)
        else:
            command = '{} {}'.format(viewer, file_path)
        IOManager.spawn_subprocess(command)

Example 44

Project: nupic
Source File: network_test.py
View license
  @unittest.skipIf(sys.platform.lower().startswith("win"),
                   "Not supported on Windows, yet!")
  def testPyNodeGetNodeSpec(self):
    n = engine.Network()

    r = n.addRegion("region", "py.TestNode", "")

    print "Setting region1 dims"
    r.setDimensions(engine.Dimensions([6, 4]))

    print "Initialize should now succeed"
    n.initialize()

    ns = r.spec

    self.assertEqual(len(ns.inputs), 1)
    i = ns.inputs['bottomUpIn']
    self.assertEqual(i.description, 'Primary input for the node')

    self.assertEqual(len(ns.outputs), 1)
    i = ns.outputs['bottomUpOut']
    self.assertEqual(i.description, 'Primary output for the node')

Example 45

Project: pyviennacl-dev
Source File: aksetup_helper.py
View license
def hack_distutils(debug=False, fast_link=True, what_opt=3):
    # hack distutils.sysconfig to eliminate debug flags
    # stolen from mpi4py

    def remove_prefixes(optlist, bad_prefixes):
        for bad_prefix in bad_prefixes:
            for i, flag in enumerate(optlist):
                if flag.startswith(bad_prefix):
                    optlist.pop(i)
                    break
        return optlist

    import sys
    if not sys.platform.lower().startswith("win"):
        from distutils import sysconfig

        cvars = sysconfig.get_config_vars()
        cflags = cvars.get('OPT')
        if cflags:
            cflags = remove_prefixes(cflags.split(),
                    ['-g', '-O', '-Wstrict-prototypes', '-DNDEBUG'])
            if debug:
                cflags.append("-g")
            else:
                if what_opt is None:
                    pass
                else:
                    cflags.append("-O%s" % what_opt)
                    cflags.append("-DNDEBUG")

            cvars['OPT'] = str.join(' ', cflags)
            cvars["CFLAGS"] = cvars["BASECFLAGS"] + " " + cvars["OPT"]

        if fast_link:
            for varname in ["LDSHARED", "BLDSHARED"]:
                ldsharedflags = cvars.get(varname)
                if ldsharedflags:
                    ldsharedflags = remove_prefixes(ldsharedflags.split(),
                            ['-Wl,-O'])
                    cvars[varname] = str.join(' ', ldsharedflags)

Example 46

Project: nupic
Source File: network_test.py
View license
  @unittest.skipIf(sys.platform.lower().startswith("win"),
                   "Not supported on Windows, yet!")
  def testTwoRegionPyNodeNetwork(self):
    n = engine.Network()

    region1 = n.addRegion("region1", "py.TestNode", "")
    region2 = n.addRegion("region2", "py.TestNode", "")

    n.link("region1", "region2", "TestFanIn2", "")

    print "Initialize should fail..."
    with self.assertRaises(Exception):
      n.initialize()

    print "Setting region1 dims"
    r1dims = engine.Dimensions([6, 4])
    region1.setDimensions(r1dims)

    print "Initialize should now succeed"
    n.initialize()

    r2dims = region2.dimensions
    self.assertEqual(len(r2dims), 2)
    self.assertEqual(r2dims[0], 3)
    self.assertEqual(r2dims[1], 2)

Example 47

Project: pexpect
Source File: test_expect.py
View license
    def test_waitnoecho_order(self):

        ''' This tests that we can wait on a child process to set echo mode.
        For example, this tests that we could wait for SSH to set ECHO False
        when asking of a password. This makes use of an external script
        echo_wait.py. '''

        p1 = pexpect.spawn('%s echo_wait.py' % self.PYTHONBIN)
        start = time.time()
        try:
            p1.waitnoecho(timeout=10)
        except IOError:
            if sys.platform.lower().startswith('sunos'):
                if hasattr(unittest, 'SkipTest'):
                    raise unittest.SkipTest("Not supported on this platform.")
                return 'skip'
            raise


        end_time = time.time() - start
        assert end_time < 10 and end_time > 2, "waitnoecho did not set ECHO off in the expected window of time."

        # test that we actually timeout and return False if ECHO is never set off.
        p1 = pexpect.spawn('cat')
        start = time.time()
        retval = p1.waitnoecho(timeout=4)
        end_time = time.time() - start
        assert end_time > 3, "waitnoecho should have waited longer than 2 seconds. retval should be False, retval=%d"%retval
        assert retval==False, "retval should be False, retval=%d"%retval

        # This one is mainly here to test default timeout for code coverage.
        p1 = pexpect.spawn('%s echo_wait.py' % self.PYTHONBIN)
        start = time.time()
        p1.waitnoecho()
        end_time = time.time() - start
        assert end_time < 10, "waitnoecho did not set ECHO off in the expected window of time."

Example 48

View license
    def should_use_httplib(self):
        if sys.platform.lower().startswith('win') and self.cert_file:
            # On Windows, auto-detect between Windows Store Certificate
            # (winhttp) and OpenSSL .pem certificate file (httplib).
            #
            # We used to only support certificates installed in the Windows
            # Certificate Store.
            #   cert_file example: CURRENT_USER\my\CertificateName
            #
            # We now support using an OpenSSL .pem certificate file,
            # for a consistent experience across all platforms.
            #   cert_file example: account\certificate.pem
            #
            # When using OpenSSL .pem certificate file on Windows, make sure
            # you are on CPython 2.7.4 or later.

            # If it's not an existing file on disk, then treat it as a path in
            # the Windows Certificate Store, which means we can't use httplib.
            if not os.path.isfile(self.cert_file):
                return False

        return True

Example 49

Project: nupic
Source File: network_test.py
View license
  @unittest.skipIf(sys.platform.lower().startswith("win"),
                   "Not supported on Windows, yet!")
  def testErrorHandling(self):
    n = engine.Network()

    # Test trying to add non-existent node
    with self.assertRaises(Exception) as cm:
      n.addRegion('r', 'py.NonExistingNode', '')

    self.assertEqual(cm.exception.message, "Matching Python module for NonExistingNode not found.")

    orig_import = __import__
    def import_mock(name, *args):
      if name == "nupic.regions.UnimportableNode":
        raise SyntaxError("invalid syntax (UnimportableNode.py, line 5)")

      return orig_import(name, *args)

    with patch('__builtin__.__import__', side_effect=import_mock):
      # Test failure during import
      with self.assertRaises(Exception) as cm:
        n.addRegion('r', 'py.UnimportableNode', '')

      self.assertEqual(cm.exception.message, "invalid syntax (UnimportableNode.py, line 5)")

    # Test failure in the __init__() method
    with self.assertRaises(Exception) as cm:
      n.addRegion('r', 'py.TestNode', '{ failInInit: 1 }')

    self.assertEqual(cm.exception.message, "TestNode.__init__() Failing on purpose as requested")

    # Test failure inside the compute() method
    with self.assertRaises(Exception) as cm:
      r = n.addRegion('r', 'py.TestNode', '{ failInCompute: 1 }')
      r.dimensions = engine.Dimensions([4, 4])
      n.initialize()
      n.run(1)

    self.assertEqual(str(cm.exception),
      'TestNode.compute() Failing on purpose as requested')

    # Test failure in the static getSpec
    from nupic.bindings.regions.TestNode import TestNode
    TestNode._failIngetSpec = True

    with self.assertRaises(Exception) as cm:
      TestNode.getSpec()

    self.assertEqual(str(cm.exception),
      'Failing in TestNode.getSpec() as requested')

    del TestNode._failIngetSpec

Example 50

Project: nupic
Source File: network_test.py
View license
  @unittest.skipIf(sys.platform.lower().startswith("win"),
                   "Not supported on Windows, yet!")
  def testTwoRegionNetwork(self):
    n = engine.Network()

    region1 = n.addRegion("region1", "TestNode", "")
    region2 = n.addRegion("region2", "TestNode", "")

    names = []
    for name in n.regions:
      names.append(name)
    self.assertEqual(names, ['region1', 'region2'])
    print n.getPhases('region1')
    self.assertEqual(n.getPhases('region1'), (0,))
    self.assertEqual(n.getPhases('region2'), (1,))

    n.link("region1", "region2", "TestFanIn2", "")

    print "Initialize should fail..."
    with self.assertRaises(Exception):
      n.initialize()

    print "Setting region1 dims"
    r1dims = engine.Dimensions([6, 4])
    region1.setDimensions(r1dims)

    print "Initialize should now succeed"
    n.initialize()

    r2dims = region2.dimensions
    self.assertEqual(len(r2dims), 2)
    self.assertEqual(r2dims[0], 3)
    self.assertEqual(r2dims[1], 2)

    # Negative test
    with self.assertRaises(Exception):
      region2.setDimensions(r1dims)