sys.version_info.major

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

153 Examples 7

Example 51

Project: Emoji-Tools Source File: py23_test.py
	def test_binary_pipe_built_in_io_open(self):
		if sys.version_info.major < 3 and sys.platform == 'win32':
			# On Windows Python 2.x, the piped input and output data are
			# expected to be different when using io.open, because of issue
			# https://bugs.python.org/issue10841.
			expected = True
		else:
			expected = False
		result = self.diff_piped(TEST_BIN_DATA, "from io import open")
		self.assertEqual(result, expected)

Example 52

Project: onitu Source File: driver.py
    def write(self, filename, content):
        if sys.version_info.major == 3 and not isinstance(content, bytes):
            content = content.encode()
        s = IOStream(content)
        self.conn.upload(filename, s)
        s.close()

Example 53

Project: Pyonic-interpreter Source File: interpreter.py
Function: init
    def __init__(self, gui):
        self.gui = gui

        self.subprocess = None

        self.start_interpreter()

        self.input_index = 0  # The current input number
        self.inputs = {}  # All the inputs so far

        py_ver = sys.version_info.major
        self.interpreter_port = 3000 + 10 * py_ver
        self.receive_port = 3001 + 10 * py_ver

        Clock.schedule_interval(self.read_osc_queue, 0.05)

        self.init_osc()

        self._interpreter_state = 'waiting'

Example 54

Project: python-mapnik Source File: setup.py
def find_boost_library(_id):
    suffixes = [
        "",  # standard naming
        "-mt"  # former naming schema for multithreading build
    ]
    if "python" in _id:
        # Debian naming convention for versions installed in parallel
        suffixes.insert(0, "-py%d%d" % (sys.version_info.major,
                                        sys.version_info.minor))
        # standard suffix for Python3
        suffixes.insert(1, sys.version_info.major)
    for suf in suffixes:
        name = "%s%s" % (_id, suf)
        lib = find_library(name)
        if lib is not None:
            return name

Example 55

Project: imutils Source File: encodings.py
def base64_decode_image(a):
	# grab the array, data type, and shape from the JSON-decoded object
	(a, dtype, shape) = json.loads(a)

	# if this is Python 3, then we need the extra step of encoding the
	# string as byte object
	if sys.version_info.major == 3:
		a = bytes(a, encoding="utf-8")

	# set the correct data type and reshape the matrix into an image
	a = base64_decode_array(a, dtype).reshape(shape)

	# return the loaded image
	return a

Example 56

Project: gluish Source File: utils_test.py
    @unittest.skipIf(sys.version_info.major > 2, 'skip on Python 3 for now.')
    def test_shellout_encoding(self):
        """ Test shellout encoding. """
        word = u'Catégorie'
        self.assertRaises(UnicodeEncodeError, shellout, 'echo {word}', word=word)

        output = shellout('echo {word} > {output}', word=word, encoding='utf-8')
        self.assertTrue(os.path.exists(output))
        with open(output) as handle:
            content = handle.read().strip()
            self.assertEquals('Cat\xc3\xa9gorie', content)
            self.assertEquals(u'Catégorie', content.decode('utf-8'))

Example 57

Project: clinacl Source File: clinacl.py
Function: write_to_stdout
def write_to_stdout(bytes):
    # Python 2 has no sys.stdout.buffer.
    if sys.version_info.major == 2:
        return sys.stdout.write(bytes)
    else:
        return sys.stdout.buffer.write(bytes)

Example 58

Project: SMF-Extension Source File: yahoo.py
def query_yahoo(self, ticker, stat):
    """Query Yahoo for the data we want""" 
    url = 'http://finance.yahoo.com/d/quotes.csv?s=%s&f=%s' % (ticker, stat)
    req = Request(url)
    try:
        response = urlopen(req)
    #Catch errors.
    except URLError as e:
        self.yahoo_flag[0] = '1'
        if hasattr(e, 'reason'):
            return e.reason
        elif hasattr(e,'code'):
            return 'Error', e.code
    if sys.version_info.major == 3:
        return csv.reader(iterdecode(response,'utf-8'))
    return csv.reader(response)

Example 59

Project: freezer Source File: test_checksum.py
    @unittest.skipIf(sys.version_info.major == 2, 'Not supported on python v 2.7')
    @patch('builtins.open')
    @patch('freezer.utils.checksum.os.path.isfile')
    def test_get_hash_files(self, mock_isfile, mock_open):
        """
        Test calculating the hash of a file
        """
        mock_isfile.return_value = True
        mock_open.return_value = self.fake_file
        chksum = CheckSum('onefile')
        chksum.get_hash('onefile')
        self.assertEqual(self.increment_hash_one, chksum._increment_hash)
        chksum.get_hash('otherfile')
        self.assertEqual(self.increment_hash_multi, chksum._increment_hash)

Example 60

Project: netjsonconfig Source File: setup.py
Function: get_install_requires
def get_install_requires():
    """
    parse requirements.txt, ignore links, exclude comments
    """
    requirements = []
    for line in open('requirements.txt').readlines():
        # skip to next iteration if comment or empty line
        if line.startswith('#') or line == '' or line.startswith('http') or line.startswith('git'):
            continue
        # add line to requirements
        requirements.append(line.replace('\n', ''))
    # add py2-ipaddress if python2
    if sys.version_info.major < 3:
        requirements.append('py2-ipaddress')
    return requirements

Example 61

Project: milk Source File: test_regression.py
def test_svm_crash():
    from sys import version_info
    if version_info.major >= 3:
        pickle_load = lambda f: pickle.load(f, encoding='latin1')
    else:
        pickle_load = pickle.load

    X,Y,kernel, C, eps ,tol, = pickle_load(GzipFile(path.dirname(__file__) + '/data/regression-2-Dec-2009.pp.gz'))
    X = X[2:-2,:].copy()
    Y = Y[2:-2].copy()
    N = len(Y)
    Y = Y.astype(np.int32)
    p = -np.ones(N,np.double)
    params = np.array([0,C,eps,tol],np.double)
    Alphas0 = np.zeros(N, np.double)
    cache_size = (1<<20)
    # The line below crashed milk:
    milk.supervised._svm.eval_LIBSVM(X,Y,Alphas0,p,params,kernel,cache_size)

Example 62

Project: sublime-robot-framework-assistant Source File: get_keyword.py
Function: is_string
    def is_string(self, str_):
        if version_info.major > 2:
            status = isinstance(str_, str)
        else:
            status = isinstance(str_, basestring)
        return status

Example 63

Project: magic-constraints Source File: test_types.py
@pytest.mark.xfail(
    sys.version_info.major < 3,
    reason="future problem.",
)
def test_repr_python3():
    assert conditional_to_bytes('Sequence') == repr(Sequence)
    assert conditional_to_bytes('Sequence[int]') == repr(Sequence[int])
    assert conditional_to_bytes('Sequence[int, float]') ==\
        repr(Sequence[int, float])

    assert conditional_to_bytes('Callable[[int, float], float]') ==\
        repr(Callable[[int, float], float])

Example 64

Project: menpofit Source File: io.py
def filename_for_fitter(name):
    r"""
    Returns the filename of a fitter with the identifier ``name`` accounting
    for the Python version and menpofit binary compatibility version number.

    Parameters
    ----------
    name : `str`
        The name of the fitter, e.g. `balanced_frontal_face_aam`

    Returns
    -------
    filename : `str`
        The filename of the fitter
    """
    return '{}_v{}_py{}.pkl'.format(name, MENPOFIT_BINARY_VERSION,
                                    sys.version_info.major)

Example 65

Project: sorl-thumbnail Source File: test_backends.py
    @unittest.skipIf('pgmagick_engine' in settings.THUMBNAIL_ENGINE and sys.version_info.major == 2,
                     'No output has been received in the last 10 minutes,'
                     'this potentially indicates something wrong with the build itself.')
    def test_write(self):
        with same_open_fd_count(self):
            with self.assertRaises(Exception):
                self.ENGINE.write(image=self.ENGINE.get_image(StringIO(b'xxx')),
                                  options={'format': 'JPEG', 'quality': 90, 'image_info': {}},
                                  thumbnail=ImageFile('whatever_thumb.jpg', default.storage))

Example 66

Project: nOBEX Source File: map.py
def gen_handle():
    """Generate a random 64 bit hex handle"""
    rb = os.urandom(8)
    if sys.version_info.major >= 3:
        return "".join(["%02X" % i for i in rb])
    else:
        return "".join(["%02X" % ord(c) for c in rb])

Example 67

Project: lemur Source File: manage.py
Function: unicode
def unicode_(data):
    import sys

    if sys.version_info.major < 3:
        return data.decode('UTF-8')
    return data

Example 68

Project: openshift-ansible Source File: test_utils.py
    def setUp(self):
        self.debug_all_params = {
            'OPENSHIFT_FOO': 'bar',
            'ANSIBLE_FOO': 'bar',
            'OO_FOO': 'bar'
        }

        self.expected = [
            mock.call('ANSIBLE_FOO: bar'),
            mock.call('OPENSHIFT_FOO: bar'),
            mock.call('OO_FOO: bar'),
        ]

        # python 2.x has assertItemsEqual, python 3.x has assertCountEqual
        if sys.version_info.major > 3:
            self.assertItemsEqual = self.assertCountEqual

Example 69

Project: django-heartbeat Source File: python.py
Function: check
def check(request):
    return {
            'version': '{major}.{minor}.{micro}'.format(
                major=sys.version_info.major,
                minor=sys.version_info.minor,
                micro=sys.version_info.micro
            ),
            'info': sys.version,
            'executable': sys.executable,
            'platform': sys.platform
        }

Example 70

Project: Beehive Source File: beehive.py
Function: check_python_version
def checkPythonVersion(major=2, minorLowest=6):
    if sys.version_info.major != major or \
       sys.version_info.minor < minorLowest:
        errInfo = 'your python version is too low, version>=%d.%d.x '\
                  'is needed.' % (major, minorLowest)
        raise BeeScanLaunchException(errInfo)
    return True

Example 71

Project: python-javabridge Source File: test_jutil.py
    def test_13_01_unicode_arg(self):
        # On 2.x, check that a unicode argument is properly prepared
        s = u"Hola ni\u00F1os"
        s1, s2 = s.split(" ")
        if sys.version_info.major == 2:
            s2 = s2.encode("utf-8")
        env = javabridge.get_env()
        js1 = env.new_string(s1+" ")
        result = javabridge.call(
            js1, "concat", "(Ljava/lang/String;)Ljava/lang/String;", s2)
        self.assertEqual(s, result)

Example 72

Project: anaconda-client Source File: pypi.py
def python_version_check(filedata):
    python_version = sys.version_info.major

    if python_version == 3:
        filedata = Parser().parsestr(filedata).items()
    else:
        filedata = Parser().parsestr(filedata.encode("UTF-8", "replace")).items()

    return filedata

Example 73

Project: okcupyd Source File: misc.py
def get_credentials():
    if not settings.USERNAME:
        input_function = input if sys.version_info.major == 3 else raw_input
        settings.USERNAME = input_function('username: ').strip()
    if not settings.PASSWORD:
        settings.PASSWORD = getpass.getpass('password: ')

Example 74

Project: botchallenge Source File: message_test.py
  def testHighPrecisionFloatPrinting(self):
    message = unittest_pb2.TestAllTypes()
    message.optional_double = 0.12345678912345678
    if sys.version_info.major >= 3:
      self.assertEqual(str(message), 'optional_double: 0.12345678912345678\n')
    else:
      self.assertEqual(str(message), 'optional_double: 0.123456789123\n')

Example 75

Project: prospector Source File: message.py
Function: init
    def __init__(self, path, module, function, line, character, absolute_path=True):
        if sys.version_info.major == 2 and isinstance(path, str):
            # If this is not a unicode object, make it one! Some tools return
            # paths as unicode, some as bytestring, so to ensure that they are
            # all the same, we normalise here. For Python3 this is (probably)
            # always a str so no need to do anything.
            path = path.decode(sys.getfilesystemencoding())
        self.path = path
        self._path_is_absolute = absolute_path
        self.module = module or None
        self.function = function or None
        self.line = None if line == -1 else line
        self.character = None if character == -1 else character

Example 76

Project: pytweening Source File: basicTests.py
Function: test_wrong_input
    def test_wrong_input(self):
        for name in TWEENS:
            func = getattr(pytweening, name)
            for input in [-1, -0.5, 1.5, 2]:
                kwargs = {}
                if sys.version_info.major >= 3 and sys.version_info.minor >= 3:
                    # msg parameter was added in Python 3.3:
                    # https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises
                    kwargs['msg'] = '{0}({1}) should raise ValueError'.format(name, input)

                with self.assertRaises(ValueError, **kwargs):
                    func(input)

Example 77

Project: pgi Source File: test_import_machinery.py
Function: test_invalid_repository_module_name
    def test_invalid_repository_module_name(self):
        with self.assertRaises(ImportError) as context:
            from gi.repository import InvalidGObjectRepositoryModuleName
            InvalidGObjectRepositoryModuleName  # pyflakes

        exception_string = str(context.exception)

        self.assertTrue('InvalidGObjectRepositoryModuleName' in exception_string)

        # The message of the custom exception in gi/importer.py is eaten in Python 2.7
        if sys.version_info.major < 3 and not _is_pypy:
            self.assertTrue('introspection typelib' not in exception_string)
        else:
            self.assertTrue('introspection typelib' in exception_string)

Example 78

Project: OpenTrader Source File: tabview.py
Function: process_data
def process_data(data, enc=None, delim=None, **kwargs):
    """Given a data input, determine the input type and process data accordingly.

    Returns a dictionary containing two entries: 'header', which corresponds to
    the header row, and 'data', which corresponds to the data rows.

    """

    process_type = input_type(data)

    if process_type == 'dict':
        # If data is from a dict object.
        if kwargs['orient'] == 'columns':
            header = [str(i) for i in data.keys()]
            data = list(zip(*[data[i] for i in data.keys()]))
        elif kwargs['orient'] == 'index':
            data =  [[i[0]] + i[1] for i in data.items()]
            header = [str(i) for i in range(len(data[0]))]
        if sys.version_info.major < 3:
            data = pad_data(py2_list_to_unicode(data))
        else:
            data = [[str(j) for j in i] for i in pad_data(data)]
        return {'data' : data, 'header' : header}

    elif process_type == 'pandas':
        # If data is from a pandas object.
        import numpy as np
        if data.__class__.__name__ != 'DataFrame':
            import pandas as pd
            if data.__class__.__name__ == 'Series':
                data = pd.DataFrame(data)
            elif data.__class__.__name__ == 'Panel':
                data = data.to_frame()
        data = data.reset_index()
        header = [str(i) for i in data.columns]
        try:
            unicode_convert = np.vectorize(str)
            data = unicode_convert(data.values)
        except:
            np_codec = detect_encoding(data.select_dtypes(include=['object']).values.ravel().tolist())
            unicode_convert = np.vectorize(lambda x: np_decode(x, np_codec))
            data = unicode_convert(data.values)
        data[np.where(data == 'nan')] = ''
        return {'data': data.tolist(), 'header': header}

    elif process_type == 'numpy':
        # If data is from a numpy object.
        import numpy as np
        try:
            unicode_convert = np.vectorize(str)
            data = unicode_convert(data)
        except:
            np_codec = detect_encoding(data.ravel().tolist())
            unicode_convert = np.vectorize(lambda x: np_decode(x, np_codec))
            data = unicode_convert(data)
        data[np.where(data == 'nan')] = ''
        if len(data.shape) == 1:
            data = np.array((data,))
        header = [str(i) for i in range(data.shape[1])]
        data = data.tolist()
        return {'data': data, 'header': header}

    elif process_type == 'file':
        # If data is from a file.
        if enc is None:
            enc = detect_encoding(data)
        if delim is None:
            delim = csv_sniff(data[0], enc)
        csv_data = []
        if sys.version_info.major < 3:
            csv_obj = csv.reader(data, delimiter=delim.encode(enc))
            for row in csv_obj:
                row = [str(x, enc) for x in row]
                csv_data.append(row)
        else:
            data = [i.decode(enc) for i in data]
            csv_obj = csv.reader(data, delimiter=delim)
            for row in csv_obj:
                csv_data.append(row)
        csv_data = [[str(j) for j in i] for i in pad_data(csv_data)]
        if len(csv_data) > 1:
            csv_header = csv_data[0]
            csv_data = csv_data[1:]
        else:
            csv_header = [str(i) for i in range(len(csv_data[0]))]
        return {'data': csv_data, 'header': csv_header}

    else:
        # If data is from a list of lists.
        if sys.version_info.major < 3:
            data = pad_data(py2_list_to_unicode(data))
        else:
            data = [[str(j) for j in i] for i in pad_data(data)]
        if len(data) > 1:
            header = data[0]
            data = data[1:]
        else:
            header = [str(i) for i in range(len(data[0]))]
        return {'data' : data, 'header' : header}

Example 79

Project: pyxmpp2 Source File: settings.py
    @classmethod
    def get_arg_parser(cls, settings = None, option_prefix = u'--',
                                                            add_help = False):
        """Make a command-line option parser.

        The returned parser may be used as a parent parser for application
        argument parser.

        :Parameters:
            - `settings`: list of PyXMPP2 settings to consider. By default
              all 'basic' settings are provided.
            - `option_prefix`: custom prefix for PyXMPP2 options. E.g.
              ``'--xmpp'`` to differentiate them from not xmpp-related
              application options.
            - `add_help`: when `True` a '--help' option will be included
              (probably already added in the application parser object)
        :Types:
            - `settings`: list of `unicode`
            - `option_prefix`: `str`
            - `add_help`:

        :return: an argument parser object.
        :returntype: :std:`argparse.ArgumentParser`
        """
        # pylint: disable-msg=R0914,R0912
        parser = argparse.ArgumentParser(add_help = add_help,
                                            prefix_chars = option_prefix[0])
        if settings is None:
            settings = cls.list_all(basic = True)

        if sys.version_info.major < 3:
            # pylint: disable-msg=W0404
            from locale import getpreferredencoding
            encoding = getpreferredencoding()
            def decode_string_option(value):
                """Decode a string option."""
                return value.decode(encoding)

        for name in settings:
            if name not in cls._defs:
                logger.debug("get_arg_parser: ignoring unknown option {0}"
                                                                .format(name))
                return
            setting = cls._defs[name]
            if not setting.cmdline_help:
                logger.debug("get_arg_parser: option {0} has no cmdline"
                                                                .format(name))
                return
            if sys.version_info.major < 3:
                name = name.encode(encoding, "replace")
            option = option_prefix + name.replace("_", "-")
            dest = "pyxmpp2_" + name
            if setting.validator:
                opt_type = setting.validator
            elif setting.type is unicode and sys.version_info.major < 3:
                opt_type = decode_string_option
            else:
                opt_type = setting.type
            if setting.default_d:
                default_s = setting.default_d
                if sys.version_info.major < 3:
                    default_s = default_s.encode(encoding, "replace")
            elif setting.default is not None:
                default_s = repr(setting.default)
            else:
                default_s = None
            opt_help = setting.cmdline_help
            if sys.version_info.major < 3:
                opt_help = opt_help.encode(encoding, "replace")
            if default_s:
                opt_help += " (Default: {0})".format(default_s)
            if opt_type is bool:
                opt_action = _YesNoAction
            else:
                opt_action = "store"
            parser.add_argument(option,
                                action = opt_action,
                                default = setting.default,
                                type = opt_type,
                                help = opt_help,
                                metavar = name.upper(),
                                dest = dest)
        return parser

Example 80

Project: pyxmpp2 Source File: check_version.py
def main():
    """Parse the command-line arguments and run the tool."""
    parser = argparse.ArgumentParser(description = 'XMPP version checker',
                                    parents = [XMPPSettings.get_arg_parser()])
    parser.add_argument('source', metavar = 'SOURCE', 
                                        help = 'Source JID')
    parser.add_argument('target', metavar = 'TARGET', nargs = '?',
                            help = 'Target JID (default: domain of SOURCE)')
    parser.add_argument('--debug',
                        action = 'store_const', dest = 'log_level',
                        const = logging.DEBUG, default = logging.INFO,
                        help = 'Print debug messages')
    parser.add_argument('--quiet', const = logging.ERROR,
                        action = 'store_const', dest = 'log_level',
                        help = 'Print only error messages')
    args = parser.parse_args()
    settings = XMPPSettings()
    settings.load_arguments(args)
    
    if settings.get("password") is None:
        password = getpass("{0!r} password: ".format(args.source))
        if sys.version_info.major < 3:
            password = password.decode("utf-8")
        settings["password"] = password

    if sys.version_info.major < 3:
        args.source = args.source.decode("utf-8")

    source = JID(args.source)

    if args.target:
        if sys.version_info.major < 3:
            args.target = args.target.decode("utf-8")
        target = JID(args.target)
    else:
        target = JID(source.domain)

    logging.basicConfig(level = args.log_level)

    checker = VersionChecker(source, target, settings)
    try:
        checker.run()
    except KeyboardInterrupt:
        checker.disconnect()

Example 81

Project: txmsgpackrpc Source File: protocol.py
    def callRemoteMethod(self, msgid, methodName, params):
        try:
            method = self.getRemoteMethod(self, methodName)
        except Exception:
            if self._sendErrors:
                raise
            raise InvalidRequest("Client attempted to call unimplemented method: remote_%s" % methodName)

        send_msgid = False
        try:
            # If the remote_method has a keyword argment called msgid, then pass
            # it the msgid as a keyword argument. 'params' is always a list.
            if sys.version_info.major == 2:
                method_arguments = method.func_code.co_varnames
            elif sys.version_info.major == 3:
                method_arguments = method.__code__.co_varnames
            else:
                raise NotImplementedError('Unsupported Python version %s' % sys.version_info.major)

            if 'msgid' in method_arguments:
                send_msgid = True
        except Exception:
            pass

        try:
            if send_msgid:
                result = method(*params, msgid=msgid)
            else:
                result = method(*params)
        except TypeError:
            if self._sendErrors:
                raise
            raise InvalidRequest("Wrong number of arguments for %s" % methodName)

        return result

Example 82

Project: libtaxii Source File: clients.py
Function: init
    def __init__(self, host, port=None, key_file=None, cert_file=None,
                 key_password=None, strict=None,
                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
                 source_address=None, verify_server=False, ca_certs=None):

        # The httplib.HTTPSConnection init arguments have changed over different Python versions:
        # Py 2.6: httplib.HTTPSConnection(host[, port[, key_file[, cert_file[, strict[, timeout]]]]])
        # Py 2.7: httplib.HTTPSConnection(host[, port[, key_file[, cert_file[, strict[, timeout[, source_address[, context]]]]]]])
        # Py 3.4: http.client.HTTPSConnection(host, port=None, key_file=None, cert_file=None, [timeout, ]source_address=None, *, context=None, check_hostname=None)

        self.context = None

        if sys.version_info.major == 2 and sys.version_info.minor == 6:
            six.moves.http_client.HTTPSConnection.__init__(
                self, host, port, key_file, cert_file, strict, timeout)

            if key_password:
                warnings.warn('Key password is not supported in Python 2.6. Ignoring')

        elif ((sys.version_info.major == 2 and sys.version_info.minor == 7)
                or (sys.version_info.major == 3 and sys.version_info.minor == 4)):

            if hasattr(ssl, "create_default_context"):
                self.context = ssl.create_default_context(
                    ssl.Purpose.CLIENT_AUTH, cafile=ca_certs)

                if cert_file or key_file:
                    self.context.load_cert_chain(
                        cert_file, key_file, password=key_password)

            if not self.context and key_password:
                warnings.warn('Key password is not supported in Python <2.7.9. Ignoring')

            if sys.version_info.major == 2 and sys.version_info.minor == 7:
                if self.context:
                    six.moves.http_client.HTTPSConnection.__init__(
                        self, host, port, strict=strict, timeout=timeout,
                        source_address=source_address, context=self.context)
                else:
                    six.moves.http_client.HTTPSConnection.__init__(
                        self, host, port, strict=strict, timeout=timeout,
                        source_address=source_address)

            elif sys.version_info.major == 3 and sys.version_info.minor == 4:
                super(VerifiableHTTPSConnection, self).__init__(
                    host, port, timeout=timeout, source_address=source_address,
                    context=self.context)
        else:
            raise RuntimeError("Unsupported Python version: '{0}'".format(sys.version))

        self.cert_file = cert_file
        self.key_file = key_file

        if verify_server:
            self.cert_reqs = ssl.CERT_REQUIRED
        else:
            self.cert_reqs = ssl.CERT_NONE
        self.ca_certs = ca_certs

Example 83

Project: qutebrowser Source File: build_release.py
def build_windows():
    """Build windows executables/setups."""
    utils.print_title("Updating 3rdparty content")
    update_3rdparty.update_pdfjs()

    utils.print_title("Building Windows binaries")
    parts = str(sys.version_info.major), str(sys.version_info.minor)
    ver = ''.join(parts)
    dotver = '.'.join(parts)
    python_x86 = r'C:\Python{}_x32'.format(ver)
    python_x64 = r'C:\Python{}'.format(ver)

    artifacts = []

    utils.print_title("Rebuilding tox environment")
    call_tox('cxfreeze-windows', '-r', '--notest')
    utils.print_title("Running 32bit freeze.py build_exe")
    call_tox('cxfreeze-windows', 'build_exe', python=python_x86)
    utils.print_title("Running 32bit freeze.py bdist_msi")
    call_tox('cxfreeze-windows', 'bdist_msi', python=python_x86)
    utils.print_title("Running 64bit freeze.py build_exe")
    call_tox('cxfreeze-windows', 'build_exe', python=python_x64)
    utils.print_title("Running 64bit freeze.py bdist_msi")
    call_tox('cxfreeze-windows', 'bdist_msi', python=python_x64)

    name_32 = 'qutebrowser-{}-win32.msi'.format(qutebrowser.__version__)
    name_64 = 'qutebrowser-{}-amd64.msi'.format(qutebrowser.__version__)

    artifacts += [
        (os.path.join('dist', name_32), 'application/x-msi',
         'Windows 32bit installer'),
        (os.path.join('dist', name_64), 'application/x-msi',
         'Windows 64bit installer'),
    ]

    utils.print_title("Running 32bit smoke test")
    smoke_test('build/exe.win32-{}/qutebrowser.exe'.format(dotver))
    utils.print_title("Running 64bit smoke test")
    smoke_test('build/exe.win-amd64-{}/qutebrowser.exe'.format(dotver))

    basedirname = 'qutebrowser-{}'.format(qutebrowser.__version__)
    builddir = os.path.join('build', basedirname)
    _maybe_remove(builddir)

    utils.print_title("Zipping 32bit standalone...")
    name = 'qutebrowser-{}-windows-standalone-win32'.format(
        qutebrowser.__version__)
    origin = os.path.join('build', 'exe.win32-{}'.format(dotver))
    os.rename(origin, builddir)
    shutil.make_archive(name, 'zip', 'build', basedirname)
    shutil.rmtree(builddir)
    artifacts.append(('{}.zip'.format(name),
                      'application/zip',
                      'Windows 32bit standalone'))

    utils.print_title("Zipping 64bit standalone...")
    name = 'qutebrowser-{}-windows-standalone-amd64'.format(
        qutebrowser.__version__)
    origin = os.path.join('build', 'exe.win-amd64-{}'.format(dotver))
    os.rename(origin, builddir)
    shutil.make_archive(name, 'zip', 'build', basedirname)
    shutil.rmtree(builddir)
    artifacts.append(('{}.zip'.format(name),
                      'application/zip',
                      'Windows 64bit standalone'))

    return artifacts

Example 84

Project: python3-trepan Source File: deparse.py
Function: run
    def run(self, args):
        co = self.proc.curframe.f_code
        name = co.co_name

        try:
            opts, args = getopt(args[1:], "hpAPo:",
                                ["help", "parent", "pretty", "tree", "AST",
                                 "offset"])
        except GetoptError as err:
            # print help information and exit:
            print(str(err))  # will print something like "option -a not recognized"
            return

        pretty = False
        show_parent = False
        show_ast = False
        offset = None
        for o, a in opts:
            if o in ("-h", "--help"):
                self.proc.commands['help'].run(['help', 'deparse'])
                return
            elif o in ("-p", "--parent"):
                show_parent = True
            elif o in ("-P", "--pretty"):
                pretty = True
            elif o in ("-A", "--tree", '--AST'):
                show_ast = True
            elif o in ("-o", '--offset'):
                offset = a
            else:
                self.errmsg("unhandled option %s" % o)
            pass
        pass

        sys_version = version_info.major + (version_info.minor / 10.0)
        if len(args) >= 1 and args[0] == '.':
            try:
                if pretty:
                    deparsed = deparse_code(sys_version, co)
                    text = deparsed.text
                else:
                    out = StringIO()
                    deparsed = deparse_code_pretty(sys_version, co, out)
                    text = out.getvalue()
                    pass
            except:
                self.errmsg("error in deparsing code")

                return
            self.print_text(text)
            return

        elif offset:
            mess = ("The 'deparse' command when given an argument requires an"
                    " instruction offset. Got: %s" % offset)
            last_i = self.proc.get_an_int(offset, mess)
            if last_i is None:
                return
        else:
            last_i = self.proc.curframe.f_lasti
            if last_i == -1: last_i = 0

        try:
            deparsed = deparse_code(sys_version, co)
        except:
            self.errmsg("error in deparsing code at %d" % last_i)
            return
        if (name, last_i) in deparsed.offsets.keys():
            nodeInfo =  deparsed.offsets[name, last_i]
            extractInfo = deparsed.extract_node_info(nodeInfo)
            parentInfo = None
            # print extractInfo
            if show_ast:
                p = deparsed.ast
                if show_parent:
                    parentInfo, p = deparsed.extract_parent_info(nodeInfo.node)
                self.msg(p)
            if extractInfo:
                self.msg("opcode: %s" % nodeInfo.node.type)
                self.print_text(extractInfo.selectedLine)
                self.msg(extractInfo.markerLine)
                if show_parent:
                    if not parentInfo:
                        parentInfo, p = deparsed.extract_parent_info(nodeInfo.node)
                    if parentInfo:
                        self.msg("Contained in...")
                        self.print_text(parentInfo.selectedLine)
                        self.msg(parentInfo.markerLine)
                        self.msg("parsed type: %s" % p.type)
                    pass
                pass
            pass
        elif last_i == -1:
            if name:
                self.msg("At beginning of %s " % name)
            elif self.core.filename(None):
                self.msg("At beginning of program %s" % self.core.filename(None))
            else:
                self.msg("At beginning")
        else:
            self.errmsg("haven't recorded info for offset %d. Offsets I know are:"
                        % last_i)
            offsets = sorted([(str(x[0]), str(x[1])) for x in tuple(deparsed.offsets)])
            m = self.columnize_commands(offsets)
            self.msg_nocr(m)
        return

Example 85

Project: rlundo Source File: undoableipython.py
def raw_input_original(prompt):
    """Replace raw_input_original property in TerminalInteractiveShell.

    Add code to implement undo feature in IPython terminal. The original
    IPython code is wrapped into comments, the rest is part of the hack.

    Args:
        prompt: Prompt input from the user.

    Returns:
        The input from the user processed.
    """

    from functools import partial
    import socket

    if sys.version_info.major == 2:
        ConnectionRefusedError = socket.error

    def connect_and_wait_for_close(addr):
        s = socket.socket(family=socket.AF_UNIX)
        try:
            s.connect(addr)
        except ConnectionRefusedError:
            pass
        else:
            assert b'' == s.recv(1024)

    save = partial(connect_and_wait_for_close, addr=os.environ['RLUNDO_SAVE'])
    restore = partial(connect_and_wait_for_close, addr=os.environ['RLUNDO_RESTORE'])

    while True:
        save()
        try:
            # cuem******************************************
            # --------BEGIN of Original IPython code--------
            # **********************************************
            if py3compat.PY3:
                line = input(prompt)
            else:
                line = raw_input(prompt)
            # **********************************************
            # --------END of Original IPython code--------
            # **********************************************
        except KeyboardInterrupt:
            line = "undo"

        if line == "undo":
            time.sleep(.001) # race condition, see issue #29
            restore()
            os._exit(42)

        pid = os.fork()
        is_child = pid == 0

        # if the process is not the parent, just carry on
        if is_child:
            break

        else:
            while True:
                try:
                    status = os.waitpid(pid, 0)
                    break
                except KeyboardInterrupt:
                    pass
            exit_code = status[1] // 256
            if not exit_code == 42:
                os._exit(exit_code)

    return line

Example 86

Project: rlundo Source File: pity.py
Function: spawn
def spawn(argv, master_read=pty._read, stdin_read=pty._read, handle_window_size=False,
          terminal_output_lock=None):
    # copied from pty.py, with modifications
    # note that it references a few private functions - would be nice to not
    # do that, but you know
    if type(argv) == type(''):
        argv = (argv,)
    pid, master_fd, slave_name = fork(handle_window_size)
    if pid == CHILD:
        os.execlp(argv[0], *argv)
    try:
        mode = tty.tcgetattr(STDIN_FILENO)
        tty.setraw(STDIN_FILENO)
        restore = 1
    except tty.error:    # This is the same as termios.error
        restore = 0

    if handle_window_size:
        signal.signal(
            signal.SIGWINCH,
            lambda signum, frame: _winch(slave_name, pid)
        )

    while True:
        try:
            _copy(master_fd, master_read, stdin_read, terminal_output_lock)
        except OSError as e:
            if e.errno == errno.EINTR:
                continue
            if restore:
                tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)
        except select.error as e:
            if not sys.version_info.major == 2:  # in Python 2 EINTR is a select.error
                raise
            if e[0] == errno.EINTR:
                continue
            raise
        break

    os.close(master_fd)
    return os.waitpid(pid, 0)[1]

Example 87

Project: PyClassLessons Source File: etree_lxml.py
def testSerializer(element):
    rv = []
    finalText = None
    infosetFilter = ihatexml.InfosetFilter()

    def serializeElement(element, indent=0):
        if not hasattr(element, "tag"):
            if hasattr(element, "getroot"):
                # Full tree case
                rv.append("#docuement")
                if element.docinfo.internalDTD:
                    if not (element.docinfo.public_id or
                            element.docinfo.system_url):
                        dtd_str = "<!DOCTYPE %s>" % element.docinfo.root_name
                    else:
                        dtd_str = """<!DOCTYPE %s "%s" "%s">""" % (
                            element.docinfo.root_name,
                            element.docinfo.public_id,
                            element.docinfo.system_url)
                    rv.append("|%s%s" % (' ' * (indent + 2), dtd_str))
                next_element = element.getroot()
                while next_element.getprevious() is not None:
                    next_element = next_element.getprevious()
                while next_element is not None:
                    serializeElement(next_element, indent + 2)
                    next_element = next_element.getnext()
            elif isinstance(element, str) or isinstance(element, bytes):
                # Text in a fragment
                assert isinstance(element, str) or sys.version_info.major == 2
                rv.append("|%s\"%s\"" % (' ' * indent, element))
            else:
                # Fragment case
                rv.append("#docuement-fragment")
                for next_element in element:
                    serializeElement(next_element, indent + 2)
        elif element.tag == comment_type:
            rv.append("|%s<!-- %s -->" % (' ' * indent, element.text))
            if hasattr(element, "tail") and element.tail:
                rv.append("|%s\"%s\"" % (' ' * indent, element.tail))
        else:
            assert isinstance(element, etree._Element)
            nsmatch = etree_builders.tag_regexp.match(element.tag)
            if nsmatch is not None:
                ns = nsmatch.group(1)
                tag = nsmatch.group(2)
                prefix = constants.prefixes[ns]
                rv.append("|%s<%s %s>" % (' ' * indent, prefix,
                                          infosetFilter.fromXmlName(tag)))
            else:
                rv.append("|%s<%s>" % (' ' * indent,
                                       infosetFilter.fromXmlName(element.tag)))

            if hasattr(element, "attrib"):
                attributes = []
                for name, value in element.attrib.items():
                    nsmatch = tag_regexp.match(name)
                    if nsmatch is not None:
                        ns, name = nsmatch.groups()
                        name = infosetFilter.fromXmlName(name)
                        prefix = constants.prefixes[ns]
                        attr_string = "%s %s" % (prefix, name)
                    else:
                        attr_string = infosetFilter.fromXmlName(name)
                    attributes.append((attr_string, value))

                for name, value in sorted(attributes):
                    rv.append('|%s%s="%s"' % (' ' * (indent + 2), name, value))

            if element.text:
                rv.append("|%s\"%s\"" % (' ' * (indent + 2), element.text))
            indent += 2
            for child in element:
                serializeElement(child, indent)
            if hasattr(element, "tail") and element.tail:
                rv.append("|%s\"%s\"" % (' ' * (indent - 2), element.tail))
    serializeElement(element, 0)

    if finalText is not None:
        rv.append("|%s\"%s\"" % (' ' * 2, finalText))

    return "\n".join(rv)

Example 88

Project: shellsploit-framework Source File: xor_b3m.py
def xorme(shellcode):
    cache = shellcode
    mylist = ["".join(x) for x in list(product("ABCDEF", repeat=2))]
    insert = mylist[randint(0, len(mylist) - 1)]
    xorfirst = [
        r"\x40",  # inc eax
        r"\x43",  # inc ebx
        r"\x42",  # inc edx
        r"\x47",  # inc edi
    ]
    header = xorfirst[randint(0, len(xorfirst) - 1)]
    header += r"\xEB\x0D"
    header += xorfirst[randint(0, len(xorfirst) - 1)]
    header += r"\x5E"
    header += xorfirst[randint(0, len(xorfirst) - 1)]
    header += r"\x80\x36"
    header += r"\x" + insert
    header += r"\x74\x0A\x46"
    header += xorfirst[randint(0, len(xorfirst) - 1)]
    header += r"\xEB\xF7"
    header += xorfirst[randint(0, len(xorfirst) - 1)]
    header += r"\xE8\xEF\xFF\xFF\xFF"

    encode = ""
    if version_info.major >= 3:
        for x in hexlify(cache.encode('utf8')):	
            y = x ^ int("0x" + insert, 16)
            test = r'\x%02x' % y
            encode += test
    else:
        for x in bytearray(cache.decode("hex")):
            y = x ^ int("0x" + insert, 16)
            test = r'\x%02x' % y
            encode += test

    header += encode.upper()
    header += r"\x" + insert

    if r"\x00" in header.lower():
        xorme(shellcode)
    return header.lower().replace("\\x", "")

Example 89

Project: RenderPipeline Source File: submodule_downloader.py
def download_file(url, chunk_size=100 * 1024):
    """ Helper method to download a file displaying a progress bar """
    print("Fetching:", url)
    file_content = None
    progressbar = None

    if sys.version_info.major <= 2:

        # Import progressbar library
        from rplibs.progressbar import FileTransferSpeed, ETA, ProgressBar, Percentage
        from rplibs.progressbar import Bar
        widgets = ['\tDownloading: ', FileTransferSpeed(), ' ', Bar(), Percentage(), '   ', ETA()]
        file_content = []
        bytes_read = 0

        # Progressively download the file
        try:
            usock = urllib.request.urlopen(url)
            file_size = int(usock.headers.get("Content-Length", 1e10))
            print("File size is", round(file_size / (1024**2), 2), "MB")
            progressbar = ProgressBar(widgets=widgets, maxval=file_size).start()
            while True:
                data = usock.read(chunk_size)
                file_content.append(data)
                bytes_read += len(data)
                progressbar.update(bytes_read)
                if not data:
                    break
            usock.close()
        except Exception:
            print("ERROR: Could not fetch", url, "!", file=sys.stderr)
            raise
    else:
        # Don't use progressbar in python 3
        print("Downloading .. (progressbar disabled due to python 3 build)")
        try:
            usock = urllib.request.urlopen(url)
            file_content = []
            while True:
                data = usock.read(chunk_size)
                file_content.append(data)
                if not data:
                    break
            usock.close()
        except Exception:
            print("ERROR: Could not fetch", url, "!", file=sys.stderr)
            raise

    if progressbar:
        progressbar.finish()

    return binary_type().join(file_content)

Example 90

Project: bloom Source File: generator.py
def generate_substitutions_from_package(
    package,
    os_name,
    os_version,
    ros_distro,
    installation_prefix='/usr',
    rpm_inc=0,
    peer_packages=None,
    releaser_history=None,
    fallback_resolver=None
):
    peer_packages = peer_packages or []
    data = {}
    # Name, Version, Description
    data['Name'] = package.name
    data['Version'] = package.version
    data['Description'] = rpmify_string(package.description)
    # License
    if not package.licenses or not package.licenses[0]:
        error("No license set for package '{0}', aborting.".format(package.name), exit=True)
    data['License'] = package.licenses[0]
    # Websites
    websites = [str(url) for url in package.urls if url.type == 'website']
    data['Homepage'] = websites[0] if websites else ''
    if data['Homepage'] == '':
        warning("No homepage set")
    # RPM Increment Number
    data['RPMInc'] = rpm_inc
    # Package name
    data['Package'] = sanitize_package_name(package.name)
    # Installation prefix
    data['InstallationPrefix'] = installation_prefix
    # Resolve dependencies
    depends = package.run_depends + package.buildtool_export_depends
    build_depends = package.build_depends + package.buildtool_depends + package.test_depends
    unresolved_keys = depends + build_depends + package.replaces + package.conflicts
    # The installer key is not considered here, but it is checked when the keys are checked before this
    resolved_deps = resolve_dependencies(unresolved_keys, os_name,
                                         os_version, ros_distro,
                                         peer_packages + [d.name for d in package.replaces + package.conflicts],
                                         fallback_resolver)
    data['Depends'] = sorted(
        set(format_depends(depends, resolved_deps))
    )
    data['BuildDepends'] = sorted(
        set(format_depends(build_depends, resolved_deps))
    )
    data['Replaces'] = sorted(
        set(format_depends(package.replaces, resolved_deps))
    )
    data['Conflicts'] = sorted(
        set(format_depends(package.conflicts, resolved_deps))
    )
    # Set the distribution
    data['Distribution'] = os_version
    # Use the time stamp to set the date strings
    stamp = datetime.datetime.now(tz.tzlocal())
    data['Date'] = stamp.strftime('%a %b %d %Y')
    # Maintainers
    maintainers = []
    for m in package.maintainers:
        maintainers.append(str(m))
    data['Maintainer'] = maintainers[0]
    data['Maintainers'] = ', '.join(maintainers)
    # Changelog
    if releaser_history:
        sorted_releaser_history = sorted(releaser_history,
                                         key=lambda k: LooseVersion(k), reverse=True)
        sorted_releaser_history = sorted(sorted_releaser_history,
                                         key=lambda k: strptime(releaser_history.get(k)[0], '%a %b %d %Y'),
                                         reverse=True)
        changelogs = [(v, releaser_history[v]) for v in sorted_releaser_history]
    else:
        # Ensure at least a minimal changelog
        changelogs = []
    if package.version + '-' + str(rpm_inc) not in [x[0] for x in changelogs]:
        changelogs.insert(0, (
            package.version + '-' + str(rpm_inc), (
                data['Date'],
                package.maintainers[0].name,
                package.maintainers[0].email
            )
        ))
    exported_tags = [e.tagname for e in package.exports]
    data['NoArch'] = 'metapackage' in exported_tags or 'architecture_independent' in exported_tags
    data['changelogs'] = changelogs
    # Summarize dependencies
    summarize_dependency_mapping(data, depends, build_depends, resolved_deps)

    def convertToUnicode(obj):
        if sys.version_info.major == 2:
            if isinstance(obj, str):
                return unicode(obj.decode('utf8'))
            elif isinstance(obj, unicode):
                return obj
        else:
            if isinstance(obj, bytes):
                return str(obj.decode('utf8'))
            elif isinstance(obj, str):
                return obj
        if isinstance(obj, list):
            for i, val in enumerate(obj):
                obj[i] = convertToUnicode(val)
            return obj
        elif isinstance(obj, type(None)):
            return None
        elif isinstance(obj, tuple):
            obj_tmp = list(obj)
            for i, val in enumerate(obj_tmp):
                obj_tmp[i] = convertToUnicode(obj_tmp[i])
            return tuple(obj_tmp)
        elif isinstance(obj, int):
            return obj
        elif isinstance(obj, int):
            return obj
        raise RuntimeError('need to deal with type %s' % (str(type(obj))))

    for item in data.items():
        data[item[0]] = convertToUnicode(item[1])

    return data

Example 91

Project: liveandletdie Source File: __init__.py
Function: wrap
    @classmethod
    def wrap(cls, app):
        """
        Adds test live server capability to a Flask app module.
        
        :param app:
            A :class:`flask.Flask` app instance.
        """

        host, port = cls.parse_args()
        ssl = cls._argument_parser.parse_args().ssl
        ssl_context = None

        if host:
            if ssl:
                try:
                    import OpenSSL
                except ImportError:
                    # OSX fix
                    sys.path.append(
                        '/System/Library/Frameworks/Python.framework/Versions/'
                        '{0}.{1}/Extras/lib/python/'
                        .format(sys.version_info.major, sys.version_info.minor)
                    )

                try:
                    import OpenSSL
                except ImportError:
                    # Linux fix
                    sys.path.append(
                        '/usr/lib/python{0}.{1}/dist-packages/'
                        .format(sys.version_info.major, sys.version_info.minor)
                    )

                try:
                    import OpenSSL
                except ImportError:
                    raise LiveAndLetDieError(
                        'Flask app could not be launched because the pyopenssl '
                        'library is not installed on your system!'
                    )
                ssl_context = 'adhoc'

            app.run(host=host, port=port, ssl_context=ssl_context)
            sys.exit()

Example 92

Project: pyFFTW Source File: setup.py
    def finalize_options(self):

        build_ext.finalize_options(self)

        if self.compiler is None:
            compiler = get_default_compiler()
        else:
            compiler = self.compiler

        if compiler == 'msvc':
            # Add msvc specific hacks

            if (sys.version_info.major, sys.version_info.minor) < (3, 3):
                # The check above is a nasty hack. We're using the python
                # version as a proxy for the MSVC version. 2008 doesn't
                # have stdint.h, so is needed. 2010 does.
                #
                # We need to add the path to msvc includes

                msvc_2008_path = (
                    os.path.join(os.getcwd(), 'include', 'msvc_2008'))

                if self.include_dirs is not None:
                    self.include_dirs.append(msvc_2008_path)

                else:
                    self.include_dirs = [msvc_2008_path]

            elif (sys.version_info.major, sys.version_info.minor) < (3, 5):
                # Actually, it seems that appveyor doesn't have a stdint that
                # works, so even for 2010 we use our own (hacked) version
                # of stdint.
                # This should be pretty safe in whatever case.
                msvc_2010_path = (
                    os.path.join(os.getcwd(), 'include', 'msvc_2010'))

                if self.include_dirs is not None:
                    self.include_dirs.append(msvc_2010_path)

                else:
                    self.include_dirs = [msvc_2010_path]

            # We need to prepend lib to all the library names
            _libraries = []
            for each_lib in self.libraries:
                _libraries.append('lib' + each_lib)

            self.libraries = _libraries

Example 93

Project: catkin_pkg Source File: package.py
Function: parse_package
def parse_package(path, warnings=None):
    """
    Parse package manifest.

    :param path: The path of the package.xml file, it may or may not
        include the filename
    :param warnings: Print warnings if None or return them in the given list

    :returns: return :class:`Package` instance, populated with parsed fields
    :raises: :exc:`InvalidPackage`
    :raises: :exc:`IOError`
    """
    if os.path.isfile(path):
        filename = path
    elif package_exists_at(path):
        filename = os.path.join(path, PACKAGE_MANIFEST_FILENAME)
        if not os.path.isfile(filename):
            raise IOError('Directory "%s" does not contain a "%s"' % (path, PACKAGE_MANIFEST_FILENAME))
    else:
        raise IOError('Path "%s" is neither a directory containing a "%s" file nor a file' % (path, PACKAGE_MANIFEST_FILENAME))

    # Force utf8 encoding for python3.
    # This way unicode files can still be processed on non-unicode locales.
    kwargs = {}
    if sys.version_info.major >= 3:
        kwargs['encoding'] = 'utf8'

    with open(filename, 'r', **kwargs) as f:
        try:
            return parse_package_string(f.read(), filename, warnings=warnings)
        except InvalidPackage as e:
            e.args = ['Invalid package manifest "%s": %s' % (filename, e.message)]
            raise

Example 94

Project: netstat-monitor Source File: netstat.py
    def __init__(self, interval = DEFAULT_MONITOR_INTERVAL, ignore_loopback = False, state_changes = False, filter_files = None):
        """Create a Monitor that monitors every interval seconds using the specified filters."
        
        Keyword arguments:

        interval -- Number of seconds between each time Monitor creates a Netstat. Defaults
          to DEFAULT_MONITOR_INTERVAL.
        ignore_loopback -- Ignore local connections.
        state_changes -- Report connection state changes.
        filters -- List of filters to limit what SocketInfos are displayed to the user. Any 
          SocketInfos that match a filter are not displayed. Optional.

        """
        if interval < MIN_MONITOR_INTERVAL:
            raise MonitorException("ERROR: Monitor interval needs to be at least {0}".format(MIN_MONITOR_INTERVAL))

        self._interval = interval
        self._ignore_loopback = ignore_loopback
        self._state_changes = state_changes
        self._seen = {}

        self._netstat_id = 0

        # Check for root permissions, so filters work and connection details can be looked up.
        if os.geteuid() != 0:
            raise MonitorException("ERROR: Root permissions needed, to lookup connection details.")

        # Check python version.
        if sys.version_info.major != 3 or sys.version_info.minor < 2:
            raise MonitorException("ERROR: Python 3.2 or greater needed.")

        # Do a basic check of kernel version, by looking comparing /proc/net headers to expected headers.
        tcp_header = Monitor._read_first_line(PROC_TCP)
        udp_header = Monitor._read_first_line(PROC_UDP)
        if (tcp_header != "sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode" or
            udp_header != "sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode ref pointer drops"):
            raise MonitorException("ERROR: Unexpected /proc/net file format. This could be due to kernel version. Current kernel: {0}. Tested kernel: {1}.".format(
                platform.uname()[2], TESTED_KERNEL))

        # Load filters
        self._load_filters(filter_files)

Example 95

Project: mlxtend Source File: names.py
def generalize_names(name, output_sep=' ', firstname_output_letters=1):
    """Generalize a person's first and last name.

    Description : Returns a person's name in the format
    `<last_name><separator><firstname letter(s)> (all lowercase)`

    Parameters
    ----------
    name : `str`
        Name of the player
    output_sep : `str` (default: ' ')
        String for separating last name and first name in the output.
    firstname_output_letters : `int`
        Number of letters in the abbreviated first name.

    Returns
    ----------
    gen_name : `str`
        The generalized name.

    """
    # set first and last name positions
    last, first = 'last', 'first'
    last_pos = -1

    name = name.lower()

    # fix primarily Dutch names
    exc = ['van der ', 'de ', 'van ', 'von ', 'di ']
    for e in exc:
        if name.startswith(e):
            repl = e.replace(' ', '')
            name = (repl + name[len(e) - 1:].strip())

    exc = [' van der ', ' de ', ' van ', ' von ', ' di ',
           ', van der ', ', de', ', van ', ', von ', ', di ']

    for e in exc:
        name = name.replace(e, ' ' + e.replace(' ', ''))

    if ',' in name:
        last, first = first, last
        name = name.replace(',', '')
        last_pos = 1

    spl = name.split()
    if len(spl) > 2:
        name = '%s %s' % (spl[0], spl[last_pos])

    # remove accents
    if sys.version_info.major == 2:
        name = name.decode('utf-8')

    name = ''.join(x for x in unicodedata.normalize('NFKD', name)
                   if x in string.ascii_letters + ' ')

    # get first and last name if applicable
    m = re.match('(?P<first>\w+)\W+(?P<last>\w+)', name)
    if m:
        output = '%s%s%s' % (m.group(last),
                             output_sep,
                             m.group(first)[:firstname_output_letters])
    else:
        output = name

    gen_name = output.strip()
    return gen_name

Example 96

Project: statsmodels Source File: update_web.py
def install_branch(branch):
    """
    Installs the branch in a virtualenv.
    """
    # if it's already in the virtualenv, remove it
    ver = '.'.join(map(str, (sys.version_info.major, sys.version_info.minor)))
    sitepack = os.path.join(virtual_dir, 'lib', 'python'+ver, 'site-packages')
    if os.path.exists(sitepack):
        dir_list = os.listdir(sitepack)
    else:
        dir_list = []
    for f in dir_list:
        if 'statsmodels' in f:
            shutil.rmtree(os.path.join(sitepack, f))

    # checkout the branch
    os.chdir(gitdname)
    retcode = subprocess.call('git checkout ' + branch, shell=True,
                              stdout=sys.stdout, stderr=sys.stderr)
    if retcode != 0:
        msg = """Could not checkout out branch %s""" % branch
        raise Exception(msg)

    p = subprocess.Popen('git rev-parse HEAD ', shell=True,
                              stdout=subprocess.PIPE, stderr=sys.stderr)
    version = p.communicate()[0][:7]

    # build and install
    retcode = subprocess.call(" ".join([virtual_python, 'setup.py', 'build']),
                              shell=True, stdout=sys.stdout, stderr=sys.stderr)
    if retcode != 0:
        msg = """Could not build branch %s""" % branch
        raise Exception(msg)
    retcode = subprocess.call(" ".join([virtual_python, os.path.join(gitdname,
                                        'setup.py'), 'install']), shell=True,
                              stdout=sys.stdout, stderr=sys.stderr)
    if retcode != 0:
        os.chdir(dname)
        msg = """Could not install branch %s""" % branch
        raise Exception(msg)
    os.chdir(dname)
    return version

Example 97

Project: tbk Source File: test_payment.py
    @mock.patch('tbk.webpay.payment.requests')
    @mock.patch('tbk.webpay.payment.Payment.get_validation_url')
    @mock.patch('tbk.webpay.payment.Payment.params')
    def test_fetch_token(self, params, get_validation_url, requests):
        """
        payment.fetch_token must post data to get_validation_url and get token from response
        """
        python_version = "%d.%d" % (sys.version_info.major, sys.version_info.minor)
        user_agent = "TBK/%(TBK_VERSION_KCC)s (Python/%(PYTHON_VERSION)s)" % {
            'TBK_VERSION_KCC': TBK_VERSION_KCC,
            'PYTHON_VERSION': python_version
        }
        commerce = self.payment_kwargs['commerce']
        payment = Payment(**self.payment_kwargs)
        response = requests.post.return_value
        response.status_code = 200
        response.is_redirect = False
        decrypted = 'ERROR=0\nTOKEN=e975ffc4f0605ddf3afc299eee6aeffb59efba24769548acf58e34a89ae4e228\n'
        signature = "signature" * 20
        commerce.webpay_decrypt.return_value = decrypted, signature

        token = payment.fetch_token()

        requests.post.assert_called_once_with(
            get_validation_url.return_value,
            data={
                'TBK_VERSION_KCC': TBK_VERSION_KCC,
                'TBK_CODIGO_COMERCIO': commerce.id,
                'TBK_KEY_ID': commerce.webpay_key_id,
                'TBK_PARAM': params
            },
            headers={
                'User-Agent': user_agent
            },
            allow_redirects=False
        )
        commerce.webpay_decrypt.assert_called_once_with(response.content)

        self.assertEqual(token, 'e975ffc4f0605ddf3afc299eee6aeffb59efba24769548acf58e34a89ae4e228')

Example 98

Project: auth0-python Source File: rest.py
    def __init__(self, jwt, telemetry=True):
        self.jwt = jwt

        if telemetry:
            py_version = '%i.%i.%i' % (sys.version_info.major,
                                       sys.version_info.minor,
                                       sys.version_info.micro)

            # FIXME: is there a nicer way to do this?
            from ... import __version__ as version

            auth0_client = json.dumps({
                'name': 'auth0-python', 'version': version,
                'dependencies': [
                    {
                        'name': 'requests',
                        'version': requests.__version__,
                    }
                ],
                'environment': [
                    {
                        'name': 'python',
                        'version': py_version,
                    }
                ]
            }).encode('utf-8')

            self.base_headers = {
                'User-Agent': 'Python/%s' % py_version,
                'Auth0-Client': base64.b64encode(auth0_client),
                'Content-Type': 'application/json'
            }
        else:
            self.base_headers = {}

Example 99

Project: soup-strainer Source File: etree_lxml.py
def testSerializer(element):
    rv = []
    finalText = None
    infosetFilter = ihatexml.InfosetFilter()
    def serializeElement(element, indent=0):
        if not hasattr(element, u"tag"):
            if  hasattr(element, u"getroot"):
                #Full tree case
                rv.append(u"#docuement")
                if element.docinfo.internalDTD:
                    if not (element.docinfo.public_id or 
                            element.docinfo.system_url):
                        dtd_str = u"<!DOCTYPE %s>"%element.docinfo.root_name
                    else:
                        dtd_str = u"""<!DOCTYPE %s "%s" "%s">"""%(
                            element.docinfo.root_name, 
                            element.docinfo.public_id,
                            element.docinfo.system_url)
                    rv.append(u"|%s%s"%(u' '*(indent+2), dtd_str))
                next_element = element.getroot()
                while next_element.getprevious() is not None:
                    next_element = next_element.getprevious()
                while next_element is not None:
                    serializeElement(next_element, indent+2)
                    next_element = next_element.getnext()
            elif isinstance(element, unicode) or isinstance(element, str):
                #Text in a fragment
                assert isinstance(element, unicode) or sys.version_info.major == 2
                rv.append(u"|%s\"%s\""%(u' '*indent, element))
            else:
                #Fragment case
                rv.append(u"#docuement-fragment")
                for next_element in element:
                    serializeElement(next_element, indent+2)
        elif type(element.tag) == type(etree.Comment):
            rv.append(u"|%s<!-- %s -->"%(u' '*indent, element.text))
            if hasattr(element, u"tail") and element.tail:
                rv.append(u"|%s\"%s\"" %(u' '*indent, element.tail))
        else:
            assert isinstance(element, etree._Element)
            nsmatch = etree_builders.tag_regexp.match(element.tag)
            if nsmatch is not None:
                ns = nsmatch.group(1)
                tag = nsmatch.group(2)
                prefix = constants.prefixes[ns]
                rv.append(u"|%s<%s %s>"%(u' '*indent, prefix,
                                        infosetFilter.fromXmlName(tag)))
            else:
                rv.append(u"|%s<%s>"%(u' '*indent,
                                     infosetFilter.fromXmlName(element.tag)))

            if hasattr(element, u"attrib"):
                attributes = []
                for name, value in element.attrib.items():
                    nsmatch = tag_regexp.match(name)
                    if nsmatch is not None:
                        ns, name = nsmatch.groups()
                        name = infosetFilter.fromXmlName(name)
                        prefix = constants.prefixes[ns]
                        attr_string = u"%s %s"%(prefix, name)
                    else:
                        attr_string = infosetFilter.fromXmlName(name)
                    attributes.append((attr_string, value))

                for name, value in sorted(attributes):
                    rv.append(u'|%s%s="%s"' % (u' '*(indent+2), name, value))

            if element.text:
                rv.append(u"|%s\"%s\"" %(u' '*(indent+2), element.text))
            indent += 2
            for child in element.getchildren():
                serializeElement(child, indent)
            if hasattr(element, u"tail") and element.tail:
                rv.append(u"|%s\"%s\"" %(u' '*(indent-2), element.tail))
    serializeElement.func_annotations = {}
    serializeElement(element, 0)

    if finalText is not None:
        rv.append(u"|%s\"%s\""%(u' '*2, finalText))

    return u"\n".join(rv)

Example 100

Project: SublimeLinter3 Source File: util.py
@lru_cache(maxsize=None)
def find_python(version=None, script=None, module=None):
    """
    Return the path to and version of python and an optional related script.

    If not None, version should be a string/numeric version of python to locate, e.g.
    '3' or '3.3'. Only major/minor versions are examined. This method then does
    its best to locate a version of python that satisfies the requested version.
    If module is not None, Sublime Text's python version is tested against the
    requested version.

    If version is None, the path to the default system python is used, unless
    module is not None, in which case '<builtin>' is returned.

    If not None, script should be the name of a python script that is typically
    installed with easy_install or pip, e.g. 'pep8' or 'pyflakes'.

    A tuple of the python path, script path, major version, minor version is returned.

    """

    from . import persist
    persist.debug(
        'find_python(version={!r}, script={!r}, module={!r})'
        .format(version, script, module)
    )

    path = None
    script_path = None

    requested_version = {'major': None, 'minor': None}

    if module is None:
        available_version = {'major': None, 'minor': None}
    else:
        available_version = {
            'major': sys.version_info.major,
            'minor': sys.version_info.minor
        }

    if version is None:
        # If no specific version is requested and we have a module,
        # assume the linter will run using ST's python.
        if module is not None:
            result = ('<builtin>', script, available_version['major'], available_version['minor'])
            persist.debug('find_python: <=', repr(result))
            return result

        # No version was specified, get the default python
        path = find_executable('python')
        persist.debug('find_python: default python =', path)
    else:
        version = str(version)
        requested_version = extract_major_minor_version(version)
        persist.debug('find_python: requested version =', repr(requested_version))

        # If there is no module, we will use a system python.
        # If there is a module, a specific version was requested,
        # and the builtin version does not fulfill the request,
        # use the system python.
        if module is None:
            need_system_python = True
        else:
            persist.debug('find_python: available version =', repr(available_version))
            need_system_python = not version_fulfills_request(available_version, requested_version)
            path = '<builtin>'

        if need_system_python:
            if sublime.platform() in ('osx', 'linux'):
                path = find_posix_python(version)
            else:
                path = find_windows_python(version)

            persist.debug('find_python: system python =', path)

    if path and path != '<builtin>':
        available_version = get_python_version(path)
        persist.debug('find_python: available version =', repr(available_version))

        if version_fulfills_request(available_version, requested_version):
            if script:
                script_path = find_python_script(path, script)
                persist.debug('find_python: {!r} path = {}'.format(script, script_path))

                if script_path is None:
                    path = None
                elif script_path.endswith('.exe'):
                    path = script_path
                    script_path = None
        else:
            path = script_path = None

    result = (path, script_path, available_version['major'], available_version['minor'])
    persist.debug('find_python: <=', repr(result))
    return result
See More Examples - Go to Next Page
Page 1 Page 2 Selected Page 3 Page 4