Exemplo n.º 1
0
    def game(self, gid):
        all_game_times = self.all_game_times()
        # print(all_game_times)
        games = list(filter(lambda g: g.id == gid, all_game_times))
        if len(games) == 0:
            return None
        gametime = games[0].time

        op = Operation(schema.Query)
        games = op.games_connection(first=60, at_or_after_time=gametime, before_time=gametime + timedelta(hours=12))
        games.nodes.id()

        home_team = games.nodes.home_team()
        home_team.region_name()
        home_team.nickname()
        home_team.abbreviation()
        home_team.name()

        away_team = games.nodes.away_team()
        away_team.region_name()
        away_team.nickname()
        away_team.abbreviation()
        away_team.name()

        status = games.nodes.status()
        status.home_team_points()
        status.away_team_points()
        status.phase()
        status.quarter()

        games.nodes.stadium().__fields__('name')
        games.nodes.stadium().address().__fields__('locality', 'administrative_area_abbreviation')

        games = self._execute(op).games_connection.nodes
        return list(filter(lambda g: g.id == gid, games))[0]
Exemplo n.º 2
0
    def get_pairs_page(self, pairs_filter, skip, **kwargs):
        op = Operation(schema.Query)
        pairs = op.pairs(
            where=pairs_filter,
            skip=skip,
            first=self.page_size,
            **kwargs
        )
        pairs.id()
        pairs.token0().symbol()
        pairs.token0().id()
        pairs.token0().decimals()
        pairs.token0_price()
        pairs.volume_token0()
        pairs.reserve0()
        pairs.token1().symbol()
        pairs.token1().id()
        pairs.token1().decimals()
        pairs.token1_price()
        pairs.volume_token1()
        pairs.reserve1()
        pairs.volume_usd()
        pairs.reserve_eth()
        pairs.reserve_usd()

        while True:
            data = self.endpoint(op)
            if 'errors' not in data.keys():
                break
            print("Error getting data. Retrying in 2 secs.")
            sleep(2)

        query = op + data
        return query.pairs if hasattr(query, 'pairs') else []
Exemplo n.º 3
0
    def get_wallet(self, pk: str, all_fields: bool = False) -> dict:
        """Gets the wallet for the specified Public Key.

        Args:
            pk: A Public Key corresponding to a currently installed
              wallet.
            all_fields: return all available fields in response

        Returns:
            dict, the "data" field of the JSON Response.
        """
        default_fields = [
            "balance",
            "nonce",
            "receipt_chain_hash",
            "delegate",
            "voting_for",
            "staking_active",
            "private_key_path",
        ]

        op = Operation(mina_schema.query)
        op.wallet(public_key=pk)

        if not all_fields:
            op.wallet.__fields__(*default_fields)

        res = self._send_sgqlc_query(op)
        return res["data"]
Exemplo n.º 4
0
    def send_payment(
        self, to_pk: str, from_pk: str, amount: Currency, fee: Currency, memo: str
    ) -> dict:
        """Send a payment from the specified wallet to specified target wallet.

        Args:
            to_pk: The target wallet where funds should be sent
            from_pk: The installed wallet which will finance the
              payment
            amount: Currency instance. The amount of Mina to send
            fee: Currency instance. The transaction fee that will be attached to
              the payment
            memo:  memo to attach to the payment

        Returns:
            dict, the "data" field of the JSON Response.
        """

        input_dict = {
            "from": from_pk,
            "to": to_pk,
            "fee": fee.nanominas(),
            "memo": memo,
            "amount": amount.nanominas(),
        }

        send_payment_input = mina_schema.SendPaymentInput(input_dict)

        op = Operation(mina_schema.mutation)
        op.send_payment(input=send_payment_input)

        res = self._send_sgqlc_query(op)
        return res["data"]
Exemplo n.º 5
0
    def get_commit_history(self, from_sha: str, to_sha: str) -> List[Commit]:
        request_uuid = (
            f"commit-history:{self.repo_owner}-{self.repo_name}-{self.branch}"
            f"-{from_sha}-{to_sha}")

        query = Operation(schema.Query)
        commits = (query.repository(
            owner=self.repo_owner, name=self.repo_name).object(
                expression=self.branch).__as__(Commit).history(
                    first=100).nodes)
        commits.__fields__("id", "oid", "message", "changed_files")
        commits.author.__as__(GitActor).name()

        prs = commits.associated_pull_requests(first=5).nodes
        prs.__fields__("id", "number", "url", "merged_at", "base_ref_name")
        prs.merged_by.__as__(User).name()
        prs.author.__as__(User).name()
        pr_commits = prs.commits(first=100)
        pr_commits.__fields__("total_count")
        pr_commits.nodes.commit.__fields__("oid", "url")

        files = prs.files(first=100)
        files.__fields__("total_count")
        files.nodes.__fields__("path", "additions", "deletions")

        response = self._get_response(query, request_uuid)
        commits_all = (query + response).repository.object.history.nodes
        result, finished = self._filter_commits_and_prs(
            commits_all, from_sha, to_sha)

        return result
Exemplo n.º 6
0
    def get_pair(self, id, **kwargs):
        op = Operation(schema.Query)
        pair = op.pair(id=id, **kwargs)
        pair.id()
        pair.token0().symbol()
        pair.token0().id()
        pair.token0().decimals()
        pair.token0_price()
        pair.volume_token0()
        pair.reserve0()
        pair.token1().symbol()
        pair.token1().id()
        pair.token1().decimals()
        pair.token1_price()
        pair.volume_token1()
        pair.reserve1()
        pair.volume_usd()
        pair.reserve_eth()
        pair.reserve_usd()

        while True:
            try:
                data = self.endpoint(op)
            except URLError:
                data = {}
            if 'errors' not in data.keys() and \
               'data' in data.keys() and \
                'pair' in data['data'].keys() and \
                'reserve0' in data['data']['pair'].keys() and \
                'reserve1' in data['data']['pair'].keys():
                break
            print("Error getting data. Retrying in 2 secs.")
            sleep(2)
        query = op + data
        return query.pair if hasattr(query, 'pair') else []
Exemplo n.º 7
0
    def get_pairs_page(self, pairs_filter, last_id, first, **kwargs):
        op = Operation(schema.Query)
        if last_id is not None:
            pairs_filter.update({"id_gt": last_id})
        pairs = op.pairs(where=pairs_filter, first=first, **kwargs)
        pairs.id()
        pairs.token0().symbol()
        pairs.token0().id()
        pairs.token0().decimals()
        pairs.token0_price()
        pairs.volume_token0()
        pairs.reserve0()
        pairs.token1().symbol()
        pairs.token1().id()
        pairs.token1().decimals()
        pairs.token1_price()
        pairs.volume_token1()
        pairs.reserve1()
        pairs.volume_usd()
        pairs.reserve_eth()
        pairs.reserve_usd()

        while True:
            data = self.endpoint(op)
            if 'errors' not in data.keys():
                break
            print("Error getting data. Retrying in 2 secs.")
            print(data['errors'])
            sleep(2)

        query = op + data
        return query.pairs if hasattr(query, 'pairs') else []
Exemplo n.º 8
0
    def get_block_by_state_hash(
        self, state_hash: str, all_fields: bool = False
    ) -> dict:
        """Get the block data by state hash.

        Returns block height, block creator and snarkJobs

        Args:
            state_hash: state hash
            all_fields: return all available fields in response

        Returns:
            dict, the "data" field of the JSON Response.
        """

        default_fields = ["creator", "protocol_state", "snark_jobs"]

        op = Operation(mina_schema.query)
        op.block(state_hash=state_hash)

        if not all_fields:
            op.block.__fields__(*default_fields)

        res = self._send_sgqlc_query(op)
        return res["data"]
Exemplo n.º 9
0
 def get_all_clients(self) -> List[Device]:
     dev_list = []
     page = 1
     end_page = 2
     while end_page >= page:
         op = Operation(schema.NyansaGraphQLQuery)
         dev = op.device_list(uuids=self.cfg.macs,
                              page=page,
                              page_size=500,
                              sort_by=['uuid'])
         dev.page()
         dev.page_count()
         dev.devices()
         dev.devices.uuid()
         dev.devices.ip_address()
         dev.devices.hostname()
         dev.devices.ap_name()
         dev.devices.ap_mac_addr()
         dev.devices.essid()
         dev.devices.snr_db()
         dev.devices.last_updated()
         dev.devices.voyance_url()
         data = self.ep(op)
         devinfo = (op + data).device_list
         for d in devinfo.devices:  # type: Device
             dev_list.append(d)
         end_page = devinfo.page_count
         print(f'Run {page} of {end_page} - Length {len(dev_list)}')
         page += 1
         sleep(.5)
     return dev_list
Exemplo n.º 10
0
    def get_list(self,
                 fields: list = [],
                 **kwargs) -> Generator[Interview, None, None]:
        where = InterviewFilter(**kwargs)
        take = 20
        skip = 0
        filtered_count = 21
        if not fields:
            fields = [
                'id',
                'questionnaire_id',
                'questionnaire_version',
                'assignment_id',
                'responsible_id',
                'errors_count',
                'status',
            ]
        while skip < filtered_count:
            op = Operation(headquarters_schema.HeadquartersQuery)
            q = op.interviews(take=take, skip=skip, where=where)
            q.__fields__('filtered_count')
            q.nodes.__fields__(*fields)
            cont = self.endpoint(op)
            errors = cont.get('errors')
            if errors:
                raise GraphQLError(errors[0]['message'])
            res = (op + cont).interviews

            filtered_count = res.filtered_count
            yield from res.nodes
            skip += take
Exemplo n.º 11
0
def create_bid(postcode: int, **kwargs) -> str:
    """
    Query the helpling API to create a new bid. Then, set the given parameters (or default values configured in
    ``DEFAULT_SEARCH_PARAMETERS``) to it. This is the first step to scraping offers for a region.
    :param postcode: The postcode for which to request a new bid
    :param kwargs: The parameters to set for the search.
    :return: The bidCode of the created bid
    """
    response = requests.post(BASE_URL + "v1/bids", {
        "bid[postcode]": postcode,
        "bid[checkout_version]": 1
    })
    bid_id = response.json().get("data").get("code")

    if bid_id is None:
        raise Exception("Bid for postcode " + str(postcode) +
                        " could not be created: " + response.text)
    print("Create bid for " + str(postcode) + " (" + bid_id + "): OK")

    op = Operation(helpling_schema.Mutation)
    op.transition_bid_to_provider_selection(**{
        **DEFAULT_SEARCH_PARAMETERS,
        **kwargs, "bid_code": bid_id
    })

    result = gql_endpoint(op).get("data").get(
        "transitionBidToProviderSelection")

    if result.get("success") is False:
        raise Exception("Bid " + bid_id + " could not be parametrized: " +
                        result.get("errors"))
    print("Parametrize bid " + bid_id + ": OK")

    return bid_id
Exemplo n.º 12
0
def get_candidates_for_bid(
        bid_id: str) -> List[helpling_schema.DecoratedPotentialCandidateEdge]:
    """
    Query the API for all (i.e. the first 1000) candidates for a given bid. The bid must have been parametrized already.
    Note that not all fields are actually requested from the backend.
    :param bid_id: Id of an already-parametrized bid
    :return: First 1000 candidates available for the bid
    """
    op = Operation(helpling_schema.Query)

    candidates = op.customer_bid(code=bid_id).potential_candidates(first=1000)

    candidates.edges.node.price_per_hour()

    provider = candidates.edges.node.provider
    provider.__fields__("id", "firstname", "shortname",
                        "default_profile_image", "pets", "windows", "ironing",
                        "ratings_received_count", "verification_level",
                        "documents", "performed_cleanings_count",
                        "language_skills", "instabook_enabled")
    provider.avg_rating.total()
    provider.experience.__fields__()
    provider.distance_to_bid(bid_code=bid_id)

    data = gql_endpoint(op)

    return (op + data).customer_bid.potential_candidates.edges
Exemplo n.º 13
0
def generateGQL(initViewer,currentUser,followingEndCursor,followerEndCursor):
    op = Operation(Query)

    if initViewer:
        viewer = op.viewer()
        viewer.login()
        viewer.isSiteAdmin()
        viewer.email()
        viewer.name()
        viewer.updatedAt()
        viewer.company()

    user = op.user(login=currentUser)
    if followingEndCursor == "":
        following = user.following(first=100)
    elif followingEndCursor == None:
        following = user.following(first=100)
    else:
        following = user.following(first=100,after=followingEndCursor)

    if followerEndCursor == "":
        followers = user.followers(first=100)
    elif followerEndCursor == None:
        followers = user.followers(first=100)
    else:
        followers = user.followers(first=100, after=followerEndCursor)

    initQueryNodes(following)
    initQueryNodes(followers)

    return op
Exemplo n.º 14
0
    def push_updates(self):
        """
        push update buffer to database in order to be rendered by the graphics

        :return:
        """
        times, updates = zip(*self._update_buffer)
        intersections, distances, directions = zip(*updates)
        print(times)
        print(intersections)

        op = Operation(schema.Mutation)
        update = op.push_update_buffer(times=times,
                                       intersections=intersections,
                                       distances=distances,
                                       directions=directions,
                                       search_algorithm=self._search_algorithm)

        update.time()
        new_car_loc = update.new_car_loc()
        new_car_loc.intersection()
        new_car_loc.distance()
        new_car_loc.direction()

        print(op)
        data = endpoint(op)
        result = op + data

        print(result)
        return result
Exemplo n.º 15
0
    def get_map(self):
        """ get the map from the server """
        op = Operation(schema.Query)
        search_tf = op.search_tf()

        road_graph = search_tf.road_graph()
        road_graph.name()

        connections = road_graph.connections()
        connections.index()
        connections.start()
        connections.end()
        connections.start_name()
        connections.end_name()
        connections.length()
        connections.direction()

        intersections = road_graph.intersections()
        intersections.index()
        intersections.name()
        intersections.x()
        intersections.y()
        intersections.connections()

        start_state = road_graph.start_state()
        start_state.last_intersection()
        start_state.distance_since()
        start_state.direction()

        data = endpoint(op)
        result = op + data

        self._road_graph = result.search_tf.road_graph
        return self._road_graph
Exemplo n.º 16
0
def fetch_gql_speech(speech_id):
    op = Operation(Query)
    speech = op.speech(filter=_SpeechFilter({'id': speech_id}))
    speech.id()
    speech.order_in_minutes()
    minutes = speech.belonged_to_minutes()
    minutes.id()
    minutes.name()
    minutes.ndl_min_id()
    member = speech.be_delivered_by_member()
    member.id()
    member.name()

    res = gql_client.endpoint(op)
    speech = (op + res).speech[0]
    minutes = speech.belonged_to_minutes
    member = speech.be_delivered_by_member

    speech_info = {'speech_id': speech.id}
    if minutes:
        speech_info['minutes_id'] = minutes.id
        speech_info['minutes_name'] = minutes.name
        speech_info['minutes_politylink_url'] = to_politylink_url(minutes.id)
        if minutes.ndl_min_id:
            speech_info[
                'speech_ndl_url'] = 'https://kokkai.ndl.go.jp/txt/{0}/{1}'.format(
                    minutes.ndl_min_id, speech.order_in_minutes)
    if member:
        speech_info['member_id'] = member.id
        speech_info['member_name'] = member.name
        speech_info['member_image_url'] = to_politylink_url(
            member.id, domain='image.politylink.jp')
        speech_info['member_politylink_url'] = to_politylink_url(member.id)
    return speech_info
Exemplo n.º 17
0
    def get_swaps_page(self, transactions_filter, skip):
        op = Operation(schema.Query)
        transactions = op.transactions(
            where=transactions_filter,
            skip=skip,
            first=self.page_size
        )
        transactions.block_number()
        transactions.swaps().log_index()
        transactions.swaps().pair().token0().symbol()
        transactions.swaps().pair().token1().symbol()
        transactions.swaps().amount0_in()
        transactions.swaps().amount1_in()
        transactions.swaps().amount0_out()
        transactions.swaps().amount1_out()
        transactions.swaps().amount_usd()

        while True:
            data = self.endpoint(op)
            if 'errors' not in data.keys():
                break
            print("Error getting data. Retrying in 2 secs.")
            sleep(2)

        query = op + data

        if hasattr(query, 'transactions'):
            return query.transactions
        return []
Exemplo n.º 18
0
def create_operation(owner, name, labels=(), issue_states=(), pr_states=()):
    op = Operation(schema.Query)

    repo = op.repository(owner=owner, name=name)

    repo.labels(first=100).nodes.__fields__(
        name=True,
        color=True,
    )
    repo.milestones(first=100).nodes.__fields__(
        id=True,
        state=True,
        due_on=True,
        title=True,
        description=True,
    )
    repo.projects(first=100).nodes.__fields__(
        id=True,
        number=True,
        name=True,
        state=True,
    )
    select_issues(repo, labels, issue_states)
    select_pull_requests(repo, labels, pr_states)
    return op
Exemplo n.º 19
0
    def schedule(self, for_week=None):
        op = Operation(schema.Query)
        season = op.seasons_connection(last=1)
        season.nodes.named_time_ranges_connection(last=25).nodes.__fields__('id', 'name', 'time', 'subseason',
                                                                            'duration_milliseconds')
        games = season.nodes.games_connection(last=80)
        games.nodes.time()
        games.nodes.named_time_range().id()
        games.nodes.home_team().__fields__('abbreviation', 'name', 'region_name', 'nickname')
        games.nodes.away_team().__fields__('abbreviation', 'name', 'region_name', 'nickname')
        games.nodes.status().__fields__('home_team_points', 'away_team_points', 'phase')
        games.nodes.availability().short_name()
        result = self._execute(op)

        weeks = {}
        season = result.seasons_connection.nodes[0]
        for week in season.named_time_ranges_connection.nodes:
            weeks[week.id] = (week, [])
        for game in season.games_connection.nodes:
            weeks[game.named_time_range.id][1].append(game)

        if for_week is not None:
            for week_id, (week, games) in weeks.items():
                if week.time < for_week < week.time + timedelta(milliseconds=week.duration_milliseconds):
                    return week, games
        return weeks
Exemplo n.º 20
0
    def standings(self):
        op = Operation(schema.Query)
        teams = op.teams_connection(first=8)
        division = teams.nodes.division()
        division.name()
        division.id()
        division.abbreviation()
        teams.nodes.abbreviation()
        teams.nodes.nickname()
        teams.nodes.region_name()
        season = teams.nodes.seasons_connection(last=1)
        standing = season.edges.standing()
        standing.__fields__()
        result = self._execute(op)

        standings = {}
        divs = {}
        for team in result.teams_connection.nodes:
            # Some hoop-jumping to use a single division object as the key and get things grouped nicely
            if team.division.id not in divs:
                divs[team.division.id] = team.division
            key = divs[team.division.id]
            if key not in standings:
                standings[key] = []
            standings[key].append(team)

        def standings_key(team):
            return team.seasons_connection.edges[0].standing.division_rank
        for div in standings:
            standings[div] = sorted(standings[div], key=standings_key)
        return standings
Exemplo n.º 21
0
 def get_metric_data(self, label: str, source_id: str) -> List[MetricData]:
     op = Operation(Query)
     fields = list(MetricData._ContainerTypeMeta__fields.keys())
     fields.remove("id")
     op.metric_data(source_id=source_id,
                    label=label).nodes().__fields__(*fields)
     return (op + self.run(op)).metric_data.nodes
Exemplo n.º 22
0
    def _get_orders_page(self, orders_filter, skip):
        op = Operation(schema.Query)
        orders = op.orders(where=orders_filter,
                           skip=skip,
                           first=self.page_size)
        orders.id()
        orders.order_id()
        orders.buy_token().symbol()
        orders.sell_token().symbol()
        orders.max_sell_amount()
        orders.price_numerator()
        orders.price_denominator()
        orders.owner().id()
        orders.from_epoch()
        orders.until_epoch()
        orders.cancel_epoch()
        orders.create_epoch()
        orders.delete_epoch()
        orders.from_batch_id()
        orders.until_batch_id()
        orders.bought_volume()
        orders.sold_volume()
        orders.tx_hash()

        data = self.http_endpoint(op)
        query = op + data
        return query.orders if hasattr(query, 'orders') else []
Exemplo n.º 23
0
 def remove_protection(self, protection_rule_id):
     op = Operation(schema.Mutation)
     op.delete_branch_protection_rule(input=schema.DeleteBranchProtectionRuleInput(
         branch_protection_rule_id=protection_rule_id
     ))
     if settings.apply:
         GitHubGraphQL().call(op)
Exemplo n.º 24
0
    async def listen_sync_update(self, callback):
        """Creates a subscription for Network Sync Updates."""

        op = Operation(mina_schema.subscription_type)
        op.new_sync_update()
        variables = {}
        query = bytes(op).decode("utf-8")
        await self._graphql_subscription(query, variables, callback)
Exemplo n.º 25
0
    def get_layers_as_feature_collection(self):
        layer_gw_op = Operation(schema.Query)
        gw_layer_op = layer_gw_op.get_layers()
        self.get_all_properties_as_feature_collection(gw_layer_op)
        query_plus_data = send_query(endpoint=self.endpoint,
                                     query=layer_gw_op,
                                     logger=self.logger)

        return query_plus_data.get_layers
Exemplo n.º 26
0
    def _retrieve(cls, fn, **params):
        op = Operation(schema.Query)

        fields = dict(getattr(schema.Query, fn).args)
        for p in params:
            if p != 'select' and p not in fields:
                raise ValueError("%s does not support the '%s' parameter" %
                                 (fn, p))

        if 'filter' in dict(getattr(schema.Query, fn).args):
            filter_fields = dict(getattr(
                schema.Query, fn).args)['filter'].type.__field_names__
            for f in params.get('filter', {}):
                if f not in filter_fields:
                    raise ValueError("%s does not support filtering on '%s'." %
                                     (fn, f))

        update_subfields(op, fn, params, query=schema.Query)
        logger.debug(op.__to_graphql__(auto_select_depth=1))

        from mage import endpoint
        result = endpoint(op.__to_graphql__(auto_select_depth=1))

        if 'errors' in result:
            for e in result['errors']:
                logger.error(e['message'])
                if e['message'] == 'Token has expired':
                    raise RuntimeError(
                        'Token expired.  Call mage.connect() again.')
        if 'data' in result and result['data']:
            data = getattr((op + result), fn)
            if getattr(schema.Query, fn).type == schema.AWSJSON:
                data = json.loads(data)
                items = data.get('items', [data])
            else:
                items = getattr(data, 'items', None)
                if items is None:
                    if hasattr(data, 'next_token'):
                        raise RuntimeError(
                            "'next_token' is present but 'items' is missing.")
                    else:
                        # usually results are like {'data': {'items': [something]}}
                        # but sometimes it is {'data': something}
                        # that case is covered here
                        items = [data]

            items = list(filter(None, items))
            next_token = getattr(data, 'next_token', None)
            if next_token:
                logger.debug("More data available")
            else:
                logger.debug("No More data")
            return ListObject(cls=cls,
                              fn=fn,
                              params=params,
                              items=items,
                              next_token=next_token)
Exemplo n.º 27
0
def build_merge(ids: List[str]):
    op = Operation(Mutation)

    for i, ident in enumerate(ids):
        op.merge_pull_request(
            input=MergePullRequestInput(pull_request_id=ident),
            __alias__=f'merge_{i}').pull_request.title()

    return op
Exemplo n.º 28
0
 def gq_repository(self) -> schema.Repository:
     op = Operation(schema.Query)
     r = op.repository(owner=self.organization.login, name=self.name)
     r.id()
     r.branch_protection_rules(first=100)
     r.branch_protection_rules.nodes.id()
     r.branch_protection_rules.nodes.pattern()
     data = GitHubGraphQL().call(op)
     return (op + data).repository
Exemplo n.º 29
0
 def new_tweet(self, content, tags=None):
     if tags is None:
         tags = []
     content = content.replace("#", "")
     op = Operation(Mutation)
     op.new_tweet(text=content, tags=tags)
     op.new_tweet.id()
     response = do_op(op, self.token)
     return response.new_tweet.id
Exemplo n.º 30
0
def test_create_graphql_query_programmatically():

    query = Operation(Query)
    query.missions()

    response = requests.post("https://api.spacex.land/graphql/",
                             json={'query': str(query)})
    assert response.status_code == 200
    assert len(response.json()['data']['missions']) == 10