Get number of blocks mined by each pool.

    :param str time_span: duration of the chart.
    Default is 4days (optional)
    :param str api_code: Blockchain.info API code (optional)
    :return: an instance of dict:{str,int}
10307
def get_pools(time_span=None, api_code=None):
    

    resource = 'pools'
    if time_span is not None:
        resource += '?timespan=' + time_span
    if api_code is not None:
        resource += '&api_code=' + api_code
    response = util.call_api(resource, base_url='https://api.blockchain.info/')
    json_response = json.loads(response)
    return {k: v for (k, v) in json_response.items()}
1321692
def parse_timemap_from_blocks(profile_block_list):
    
    prefix_list = []
    timemap = ut.ddict(list)
    for ix in range(len(profile_block_list)):
        block = profile_block_list[ix]
        total_time = get_block_totaltime(block)
        # Blocks without time go at the front of sorted output
        if total_time is None:
            prefix_list.append(block)
        # Blocks that are not run are not appended to output
        elif total_time != 0:
            timemap[total_time].append(block)
    return prefix_list, timemap
378867
def get_prev_block_hash(block_representation, coin_symbol='btc', api_key=None):
    '''
    
    '''
    return get_block_overview(block_representation=block_representation,
            coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['prev_block']
7810
def count(self, until=None):
        

        until = rationalize_until(until)
        return self.connection.zcount(self.scheduled_jobs_key, 0, until)
102399
def get_transactions_details(tx_hash_list, coin_symbol='btc', limit=None, api_key=None):
    

    for tx_hash in tx_hash_list:
        assert is_valid_hash(tx_hash)
    assert is_valid_coin_symbol(coin_symbol)

    if len(tx_hash_list) == 0:
        return []
    elif len(tx_hash_list) == 1:
        return [get_transaction_details(tx_hash=tx_hash_list[0],
                                        coin_symbol=coin_symbol,
                                        limit=limit,
                                        api_key=api_key
                                        )]

        url = make_url(coin_symbol, **dict(txs=';'.join(tx_hash_list)))

    params = {}
    if api_key:
        params['token'] = api_key
    if limit:
        params['limit'] = limit

    r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
    response_dict_list = get_valid_json(r)

    cleaned_dict_list = []

    for response_dict in response_dict_list:
        if 'error' not in response_dict:
            if response_dict['block_height'] > 0:
                response_dict['confirmed'] = parser.parse(response_dict['confirmed'])
            else:
                # Blockcypher reports fake times if it's not in a block
                response_dict['confirmed'] = None
                response_dict['block_height'] = None

            # format this string as a datetime object
            response_dict['received'] = parser.parse(response_dict['received'])
        cleaned_dict_list.append(response_dict)

    return cleaned_dict_list
1160278
def GET_blockchain_ops( self, path_info, blockchain_name, blockheight ):
        
        try:
            blockheight = int(blockheight)
            assert check_block(blockheight)
        except:
            return self._reply_json({'error': 'Invalid block'}, status_code=400)

        if blockchain_name != 'bitcoin':
            # not supported
            return self._reply_json({'error': 'Unsupported blockchain'}, status_code=404)
        
        blockstackd_url = get_blockstackd_url()
        nameops = blockstackd_client.get_blockstack_transactions_at(int(blockheight), hostport=blockstackd_url)
        if json_is_error(nameops):
            # error
            status_code = nameops.get('http_status', 502)
            return self._reply_json({'error': nameops['error']}, status_code=status_code)

        self._reply_json(nameops)
        return
1058103
def get_blockstack_transactions_at(block_id, proxy=None, hostport=None):
    
    assert proxy or hostport, 'Need proxy or hostport'
    if proxy is None:
        proxy = connect_hostport(hostport)

    history_schema = {
        'type': 'array',
        'items': {
            'type': 'object',
            'properties': OP_HISTORY_SCHEMA['properties'],
            'required': [
                'op',
                'opcode',
                'txid',
                'vtxindex',
            ]
        }
    }

    nameop_history_schema = {
        'type': 'object',
        'properties': {
            'nameops': history_schema,
        },
        'required': [
            'nameops',
        ],
    }

    history_count_schema = {
        'type': 'object',
        'properties': {
            'count': {
                'type': 'integer',
                'minimum': 0,
            },
        },
        'required': [
            'count',
        ],
    }
    
    count_schema = json_response_schema( history_count_schema )
    nameop_schema = json_response_schema( nameop_history_schema )

    # how many nameops?
    num_nameops = None
    try:
        num_nameops = proxy.get_num_blockstack_ops_at(block_id)
        num_nameops = json_validate(count_schema, num_nameops)
        if json_is_error(num_nameops):
            return num_nameops

    except ValidationError as e:
        if BLOCKSTACK_DEBUG:
            log.exception(e)

        resp = {'error': 'Server response did not match expected schema.  You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
        return resp

    except socket.timeout:
        log.error("Connection timed out")
        resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
        return resp

    except socket.error as se:
        log.error("Connection error {}".format(se.errno))
        resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
        return resp

    except Exception as ee:
        if BLOCKSTACK_DEBUG:
            log.exception(ee)

        log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
        resp = {'error': 'Failed to contact Blockstack node.  Try again with `--debug`.', 'http_status': 500}
        return resp

    num_nameops = num_nameops['count']

    # grab at most 10 of these at a time
    all_nameops = []
    page_size = 10
    while len(all_nameops) < num_nameops:
        resp = {}
        try:
            resp = proxy.get_blockstack_ops_at(block_id, len(all_nameops), page_size)
            resp = json_validate(nameop_schema, resp)
            if json_is_error(resp):
                return resp

            if len(resp['nameops']) == 0:
                return {'error': 'Got zero-length nameops reply', 'http_status': 503}

            all_nameops += resp['nameops']

        except ValidationError as e:
            if BLOCKSTACK_DEBUG:
                log.exception(e)

            resp = {'error': 'Server response did not match expected schema.  You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
            return resp

        except socket.timeout:
            log.error("Connection timed out")
            resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
            return resp

        except socket.error as se:
            log.error("Connection error {}".format(se.errno))
            resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
            return resp

        except Exception as ee:
            if BLOCKSTACK_DEBUG:
                log.exception(ee)

            log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
            resp = {'error': 'Failed to contact Blockstack node.  Try again with `--debug`.', 'http_status': 500}
            return resp

    return all_nameops
505244
def getinfo(self):
        
        try:
            old_getinfo = AuthServiceProxy(self.__service_url, 'getinfo', self.__timeout, self.__conn, True)
            res = old_getinfo()
            if 'error' not in res:
                # 0.13 and earlier
                return res

        except JSONRPCException:
            pass

        network_info = self.getnetworkinfo()
        blockchain_info = self.getblockchaininfo()
        try:
            wallet_info = self.getwalletinfo()
        except:
            wallet_info = {
                'walletversion': None,
                'balance': None,
                'keypoololdest': None,
                'keypoolsize': None,
                'paytxfee': None,
            }

        res = {
            'version': network_info['version'],
            'protocolversion': network_info['protocolversion'],
            'walletversion': wallet_info['walletversion'],
            'balance': wallet_info['balance'],
            'blocks': blockchain_info['blocks'],
            'timeoffset': network_info['timeoffset'],
            'connections': network_info['connections'],
            'proxy': network_info['networks'],
            'difficulty': blockchain_info['difficulty'],
            'testnet': blockchain_info['chain'] == 'testnet',
            'keypoololdest': wallet_info['keypoololdest'],
            'keypoolsize': wallet_info['keypoolsize'],
            'paytxfee': wallet_info['paytxfee'],
            'errors': network_info['warnings'],
        }
        
        for k in ['unlocked_until', 'relayfee', 'paytxfee']:
            if wallet_info.has_key(k):
                res[k] = wallet_info[k]

        return res
646666
def read_block(self, size=None, from_date=None):
        

        # Get quarters corresponding to All items (Incremental mode NOT SUPPORTED)
        quarters = self.__quarters()

        for quarter in quarters:

            logger.info(self.__log_prefix + " Quarter: " + str(quarter))

            date_range = {self._timeframe_field: {'gte': quarter.start_time, 'lte': quarter.end_time}}

            orgs = self.__list_uniques(date_range, self.AUTHOR_ORG)
            projects = self.__list_uniques(date_range, self.PROJECT)

            # Get global data
            s = self.__build_search(date_range)
            response = s.execute()

            for timing in response.aggregations[self.TIMEFRAME].buckets:
                yield self.__build_dataframe(timing).copy()

            # Get global data by Org
            for org_name in orgs:

                logger.info(self.__log_prefix + " Quarter: " + str(quarter) + "  Org: " + org_name)

                s = self.__build_search(date_range, org_name=org_name)
                response = s.execute()

                for timing in response.aggregations[self.TIMEFRAME].buckets:
                    yield self.__build_dataframe(timing, org_name=org_name).copy()

            # Get project specific data
            for project in projects:

                logger.info(self.__log_prefix + " Quarter: " + str(quarter) + "  Project: " + project)

                # Global project
                s = self.__build_search(date_range, project_name=project)
                response = s.execute()

                for timing in response.aggregations[self.TIMEFRAME].buckets:
                    yield self.__build_dataframe(timing, project_name=project).copy()

                # Split by Org
                for org_name in orgs:

                    logger.info(self.__log_prefix + " Quarter: " + str(quarter) + "  Project: " + project + "  Org: " + org_name)

                    s = self.__build_search(date_range, project_name=project, org_name=org_name)
                    response = s.execute()

                    for timing in response.aggregations[self.TIMEFRAME].buckets:
                        yield self.__build_dataframe(timing, project_name=project, org_name=org_name).copy()
1059211
def namedb_get_num_block_vtxs( cur, block_number ):
     
    select_query = "SELECT vtxindex FROM history WHERE history_id = ?;"
    args = (block_number,)

    rows = namedb_query_execute( cur, select_query, args )
    count = 0
    for r in rows:
        count += 1

    return count
1117467
async def main():
    
    # Create Client from endpoint string in Duniter format
    client = Client(BMAS_ENDPOINT)

    # Get the node summary infos by dedicated method (with json schema validation)
    print("\nCall bma.node.summary:")
    response = await client(bma.node.summary)
    print(response)

    # Get the money parameters located in the first block
    print("\nCall bma.blockchain.parameters:")
    response = await client(bma.blockchain.parameters)
    print(response)

    # Get the current block
    print("\nCall bma.blockchain.current:")
    response = await client(bma.blockchain.current)
    print(response)

    # Get the block number 10
    print("\nCall bma.blockchain.block(10):")
    response = await client(bma.blockchain.block, 10)
    print(response)

    # jsonschema validator
    summary_schema = {
        "type": "object",
        "properties": {
            "duniter": {
                "type": "object",
                "properties": {
                    "software": {
                        "type": "string"
                    },
                    "version": {
                        "type": "string",
                    },
                    "forkWindowSize": {
                        "type": "number"
                    }
                },
                "required": ["software", "version"]
            },
        },
        "required": ["duniter"]
    }

    # Get the node summary infos (direct REST GET request)
    print("\nCall direct get on node/summary")
    response = await client.get('node/summary', rtype=RESPONSE_AIOHTTP, schema=summary_schema)
    print(response)

    # Close client aiohttp session
    await client.close()
1199910
def get_bits(block_representation, coin_symbol='btc', api_key=None):
    '''
    
    '''
    return get_block_overview(block_representation=block_representation,
            coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['bits']
460190
def service_count(self, block_identifier: BlockSpecification) -> int:
        """"""
        result = self.proxy.contract.functions.serviceCount().call(
            block_identifier=block_identifier,
        )
        return result
1235874
def get_count(self, using):
        # TODO maybe can be removed soon
        
        obj = self.clone()
        obj.add_annotation(Count('pk'), alias='x_sf_count', is_summary=True)  # pylint: disable=no-member
        number = obj.get_aggregation(using, ['x_sf_count'])['x_sf_count']  # pylint: disable=no-member
        if number is None:
            number = 0
        return number
838672
def count(self) -> int:
        ''''''
        counter = 0

        for pool in self._host_pools.values():
            counter += pool.count()

        return counter
950439
def length(time_flags):
        # type: (int) -> int
        '''
        
        '''
        tf_each_size = 7
        if time_flags & (1 << 7):
            tf_each_size = 17
        time_flags &= 0x7f
        tf_num = 0
        while time_flags:
            time_flags &= time_flags - 1
            tf_num += 1

        return 5 + tf_each_size * tf_num
900258
def get_block_statistics(cls, block_id):
        
        if not os.environ.get("BLOCKSTACK_TEST"):
            raise Exception("This method is only available in the test framework")

        global STATISTICS
        return STATISTICS.get(block_id)