<commit_before># -*- coding: utf-8 -*-

#from functools import wraps
import hmac
import hashlib
import time
import warnings
import json
import base64
import collections

import requests

class BitfinexError(Exception):
    pass

"""
class TransRange(object):
"""
    #Enum like object used in transaction method to specify time range
    #from which to get list of transactions
"""
    HOUR = 'hour'
    MINUTE = 'minute'
"""
class BaseClient(object):
    """
    A base class for the API Client methods that handles interaction with
    the requests library.
    """
    api_url = 'https://api.bitfinex.com/v1/'
    exception_on_error = True
    symbols = []
    #authenticated = False

    def __init__(self, proxydict=None, *args, **kwargs):
        self.proxydict = proxydict
        # Request available symbols
        self.symbols = self._get("symbols/", return_json=True)

    def _check_symbol(self, symbol):
        """
        Check if symbol is availble. If not raise a BitfinexError
        """
        if symbol.lower() in self.symbols:
            return True
        else:
            # Raise an error, the symbol is not avalaible.
            raise BitfinexError("Symbol not supported")
            return False

    def _get(self, *args, **kwargs):
        """
        Make a GET request.
        """
        return self._request(requests.get, *args, **kwargs)

    def _post(self, *args, **kwargs):
        """
        Make a POST request.
        """
        data = {}
        #if not self.authenticated:
        data['X-BFX-APIKEY'] = self.key

        msg={ 'request' : '/v1/' + args[0]}
        msg.update(self._default_data(*args, **kwargs))
        if 'data' in kwargs:
            msg.update(kwargs.pop('data'))
        data['X-BFX-PAYLOAD'] = base64.standard_b64encode(json.dumps(msg).encode('utf-8'))

        signature = hmac.new(
            self.secret.encode('utf-8'), msg=data['X-BFX-PAYLOAD'],
            digestmod=hashlib.sha384).hexdigest()
        data['X-BFX-SIGNATURE'] = signature
        kwargs['headers'] = data
        return self._request(requests.post, *args, **kwargs)

    def _default_data(self, *args, **kwargs):
        """
        Default data for a POST request.
        """
        return {}

    def _request(self, func, url, *args, **kwargs):
        """
        Make a generic request, adding in any proxy defined by the instance.
        Raises a ``requests.HTTPError`` if the response status isn't 200, and
        raises a :class:`BitfinexError` if the response contains a json encoded
        error message.
        """
        return_json = kwargs.pop('return_json', False)
        url = self.api_url + url
        
        try :
            response = func(url, *args, **kwargs)
        except (requests.exceptions.ConnectionError, #requests.exceptions.ConnectTimeout,
                requests.exceptions.Timeout) as error:
            json_response = None
            raise BitfinexError('Connection to Bitfinex failed: %s'%error)
        
        if 'proxies' not in kwargs:
            kwargs['proxies'] = self.proxydict

        # Check for error, raising an exception if appropriate.
        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError as e:
            print (e)
            raise BitfinexError("Error %s: "%(e.code,e.read()))

        if response.status_code == 400:
            try:
                json_response = response.json()
            except ValueError:
                json_response = None
            if isinstance(json_response, dict):
                error = json_response.get('message')
                if error:
                    raise BitfinexError(error)

        try:
            json_response = response.json()
        except ValueError:
            json_response = None
        if isinstance(json_response, dict):
            error = json_response.get('message')
            if error:
                raise BitfinexError(error)

        if return_json:
            if json_response is None:
                raise BitfinexError(
                    "Could not decode json for: " + response.text)
            return json_response
<commit_msg>Bug in HTTPerror handling has been corrected<commit_after># -*- coding: utf-8 -*-

#from functools import wraps
import hmac
import hashlib
import time
import warnings
import json
import base64
import collections

import requests

class BitfinexError(Exception):
    pass

"""
class TransRange(object):
"""
    #Enum like object used in transaction method to specify time range
    #from which to get list of transactions
"""
    HOUR = 'hour'
    MINUTE = 'minute'
"""
class BaseClient(object):
    """
    A base class for the API Client methods that handles interaction with
    the requests library.
    """
    api_url = 'https://api.bitfinex.com/v1/'
    exception_on_error = True
    symbols = []
    #authenticated = False

    def __init__(self, proxydict=None, *args, **kwargs):
        self.proxydict = proxydict
        # Request available symbols
        self.symbols = self._get("symbols/", return_json=True)

    def _check_symbol(self, symbol):
        """
        Check if symbol is availble. If not raise a BitfinexError
        """
        if symbol.lower() in self.symbols:
            return True
        else:
            # Raise an error, the symbol is not avalaible.
            raise BitfinexError("Symbol not supported")
            return False

    def _get(self, *args, **kwargs):
        """
        Make a GET request.
        """
        return self._request(requests.get, *args, **kwargs)

    def _post(self, *args, **kwargs):
        """
        Make a POST request.
        """
        data = {}
        #if not self.authenticated:
        data['X-BFX-APIKEY'] = self.key

        msg={ 'request' : '/v1/' + args[0]}
        msg.update(self._default_data(*args, **kwargs))
        if 'data' in kwargs:
            msg.update(kwargs.pop('data'))
        data['X-BFX-PAYLOAD'] = base64.standard_b64encode(json.dumps(msg).encode('utf-8'))

        signature = hmac.new(
            self.secret.encode('utf-8'), msg=data['X-BFX-PAYLOAD'],
            digestmod=hashlib.sha384).hexdigest()
        data['X-BFX-SIGNATURE'] = signature
        kwargs['headers'] = data
        return self._request(requests.post, *args, **kwargs)

    def _default_data(self, *args, **kwargs):
        """
        Default data for a POST request.
        """
        return {}

    def _request(self, func, url, *args, **kwargs):
        """
        Make a generic request, adding in any proxy defined by the instance.
        Raises a ``requests.HTTPError`` if the response status isn't 200, and
        raises a :class:`BitfinexError` if the response contains a json encoded
        error message.
        """
        return_json = kwargs.pop('return_json', False)
        url = self.api_url + url
        
        try :
            response = func(url, *args, **kwargs)
        except (requests.exceptions.ConnectionError, #requests.exceptions.ConnectTimeout,
                requests.exceptions.Timeout) as error:
            json_response = None
            raise BitfinexError('Connection to Bitfinex failed: %s'%error)
        
        if 'proxies' not in kwargs:
            kwargs['proxies'] = self.proxydict

        # Check for error, raising an exception if appropriate.
        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError as e:
            print (e)
            raise BitfinexError("HTTP Error %s"%e.response.status_code)

        if response.status_code == 400:
            try:
                json_response = response.json()
            except ValueError:
                json_response = None
            if isinstance(json_response, dict):
                error = json_response.get('message')
                if error:
                    raise BitfinexError(error)

        try:
            json_response = response.json()
        except ValueError:
            json_response = None
        if isinstance(json_response, dict):
            error = json_response.get('message')
            if error:
                raise BitfinexError(error)

        if return_json:
            if json_response is None:
                raise BitfinexError(
                    "Could not decode json for: " + response.text)
            return json_response

{'fraction_non_alphanumeric': 0.10365781007982842, 'fraction_numerical': 0.0050041701417848205, 'mean_word_length': 2.0118406889128093, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7264558', 'n_tokens_mistral': 2380, 'n_tokens_neox': 2283, 'n_words': 660}