Exemplo n.º 1
0
class Query(ObjectType):
    home = graphene.Field(Home, ident=String())
    homes = List(Home, archived=Int(default_value=0))

    def resolve_home(self, info, ident):
        doc_ref = db_firestore.get_document_ref(settings.collections.homes,
                                                ident)
        return Home(doc_ref.get().to_dict(), ident)

    def resolve_homes(self, info, archived):
        homes_ref = db.collection(homes_collection_name)
        docs = homes_ref.stream()
        homes = []
        for doc in docs:
            home_dict = doc.to_dict()
            # app.logger.info(home_dict)
            home = Home(home_dict, doc.id)
            if home.archived == archived:
                homes.append(home)
        return homes
Exemplo n.º 2
0
class CreateLink(Mutation):
    id = Int()
    url = String()
    description = String()
    posted_by = Field(UserType)

    class Arguments:
        url = String()
        description = String()

    def mutate(self, info, url, description):
        user = info.context.user or None

        link = Link(url=url, description=description, posted_by=user)
        link.save()

        return CreateLink(id=link.id,
                          url=link.url,
                          description=link.description,
                          posted_by=link.posted_by)
Exemplo n.º 3
0
class Query(object):
    """
    User queries.
    """
    users = List(UserType)
    user = Field(UserType, id=Int())

    @staticmethod
    def resolve_users(self, info, **kwargs):
        """
        Resolves all users.
        """
        return User.objects.all()

    @staticmethod
    def resolve_user(self, info, **kwargs):
        """
        Resolves a single user by ID.
        """
        return User.objects.get_by_id(**kwargs)
Exemplo n.º 4
0
class TestType(DjangoObjectType):
    name = String()
    minutes = Int()
    start_at = String()
    description = String()
    result = graphene.Field('tests.schema.TestResultType')

    class Meta:
        model = Test
        filter_fields = {
            'name': ['icontains'],
            'solved_tests__status': ['exact'],
            'status': ['exact']
        }
        interfaces = (graphene.Node, )

    @staticmethod
    def resolve_result(instance: Test, info):
        return TestResult.objects.filter(test=instance,
                                         user=info.context.user).first()
Exemplo n.º 5
0
        class CustomConnection(relay.Connection):
            class Meta:
                node = node_
                name = meta_name

            def __init__(self, *ar, **kw):
                super(CustomConnection, self).__init__(*ar, **kw)
                self._extra_kwargs = kwargs

            total_count = Int()

            def resolve_total_count(self, info, **params):
                if total_count_resolver:
                    return total_count_resolver(self, info,
                                                **self.hidden_kwargs)
                if isinstance(self.iterable, NodeSet):
                    return len(self.iterable.set_skip(0).set_limit(1))
                elif isinstance(self.iterable, (list, tuple)):
                    return len(list(self.iterable))
                return 0
Exemplo n.º 6
0
class StepNode(DjangoObjectType):
    class Meta:
        model = Step
        filter_fields = {
            'name': ['exact', 'icontains', 'istartswith'],
            'explanation': ['exact', 'icontains', 'istartswith'],
        }
        interfaces = (relay.Node, )

    comments = ConnectionField(CommentConnection)
    total_likes = Int(description="The amount of likes per each step")

    @staticmethod
    def resolve_comments(self, context, **kwargs):
        return self.comments.all()

    @staticmethod
    def resolve_total_likes(self, context, **kwargs):
        # This will return a total amount of likes per step
        return self.amount_of_likes
Exemplo n.º 7
0
    class Arguments:
        course_id = ID(name='id')
        course_type = CourseTypeEnum()
        academic_level = AcademicLevelEnum()
        title = String()
        description = String()
        instructor_id = ID(name='instructor')
        hourly_tuition = Decimal()
        total_tuition = Decimal()
        course_category_id = ID(name='courseCategory')

        # Logistical information
        room = String()
        day_of_week = DayOfWeekEnum()
        start_date = DateTime()
        end_date = DateTime()
        start_time = Time()
        end_time = Time()
        max_capacity = Int()
        is_confirmed = Boolean()
Exemplo n.º 8
0
class MapAttribute():

    map_id = Int()
    nside = Int()
    ordering = String()
    image = String()
    snr = Int()
    type = String()
    magnitude = String()
    filter = String()
    date = DateTime()
    flag_removed = Boolean()
    tag_id = Int()
    field_id = Int()
    table_id = Int()
Exemplo n.º 9
0
class FavoriteEntry(Action, Mutation):
    count = Int()

    @staticmethod
    @login_required
    def mutate(_root, info, pk):
        entry = Entry.objects_published.get(pk=pk)

        if entry.author.blocked.filter(pk=info.context.user.pk).exists():
            raise PermissionDenied(
                _("we couldn't handle your request. try again later."))

        if info.context.user.favorite_entries.filter(pk=pk).exists():
            info.context.user.favorite_entries.remove(entry)
            return FavoriteEntry(
                feedback=_("the entry has been removed from favorites"),
                count=entry.favorited_by.count())

        info.context.user.favorite_entries.add(entry)
        return FavoriteEntry(feedback=_("the entry has been favorited"),
                             count=entry.favorited_by.count())
Exemplo n.º 10
0
class ChampionMastery(RiotGrapheneObject):
    chestGranted = Boolean()
    championLevel = Int()
    championPoints = Int()
    championId = Int()
    championPointsUntilNextLevel = Int()
    lastPlayTime = Int()
    tokensEarned = Int()
    championPointsSinceLastLevel = Int()
    summonerId = String()

    summoner = Field(lambda: Summoner)

    def resolve_summoner(self, info):
        watcher: RiotWatcher = info.context

        summ = watcher.summoner.by_id(self.region, self.summonerId)

        return Summoner(self.region, summ)
Exemplo n.º 11
0
class FakeBranchProtectionRule(ObjectType):
    pattern = String()
    requiredStatusCheckContexts = List(String)
    requiresApprovingReviews = Boolean()
    requiresCodeOwnerReviews = Boolean()
    matchingRefs = Field(FakeMatchingRefs, first=Int())

    def resolve_pattern(parent, info):
        return parent.pattern

    def resolve_requiredStatusCheckContexts(parent, info):
        return parent.required_contexts

    def resolve_requiresApprovingReviews(parent, info):
        return parent.require_reviews

    def resolve_requiresCodeOwnerReviews(parent, info):
        return parent.require_codeowners_review

    def resolve_matchingRefs(parent, info, first=None):
        return parent
Exemplo n.º 12
0
class Employer(ObjectType):
    class Meta:
        interfaces = (relay.Node, )

    def __init__(self, model, *args, **kwargs):
        ObjectType.__init__(self, *args, **kwargs)
        self.model = model
        self.employer_data = self.model.get_employer_data()

    entity_id = Int()
    name = String()
    surname = String()

    def resolve_entity_id(self, info, **args):
        return int(self.employer_data["id"])

    def resolve_name(self, info, **args):
        return self.employer_data["name"]

    def resolve_surname(self, info, **args):
        return self.employer_data["surname"]
Exemplo n.º 13
0
    class query(ObjectType):
      entries = List(
        etyp,
        field = NonNull(Enum('field', emap)),
        query = NonNull(String),
        query_type = NonNull(Enum.from_enum(querytypes)),
        size = Int()
      )

      ids = List(
        etyp,
        ids = List(NonNull(String))
      )

      def resolve_ids(self, _, ids):
        return search.ids(elex, ids)

      def resolve_entries(self, _, field, query, query_type, size = 10):
        field = next(i for i in emap if i[1] == field)[0]
        query_type = querytypes(query_type).name
        return search.entries(elex, field, query, query_type, size)
Exemplo n.º 14
0
class Query(ObjectType):
    questions = Field(List(typeDefs.QuestionType),
                      limit=Int(required=False),
                      offset=Int(required=False))
    users = Field(List(typeDefs.UserType),
                  limit=Int(required=False),
                  offset=Int(required=False))

    question = Field(typeDefs.QuestionType, id=Int(required=True))
    user = Field(typeDefs.UserType, id=Int(required=True))

    resolve_questions = resolvers.resolve_all_questions
    resolve_users = resolvers.resolve_users

    resolve_question = resolvers.resolve_question
    resolve_user = resolvers.resolve_user
Exemplo n.º 15
0
def generate_type_dict(model):
    type_dict = {}
    for column in model.__table__.columns:
        if hasattr(model, 'private_fields') and column.name in model.private_fields:
            continue
        if column.type.python_type == int:
            type_dict[column.name] = Int()
        elif column.type.python_type == str:
            type_dict[column.name] = String()
        elif column.type.python_type == datetime.datetime:
            type_dict[column.name] = DateTime()
        elif column.type.python_type == datetime.date:
            type_dict[column.name] = Date()
        elif column.type.python_type == datetime.time:
            type_dict[column.name] = Time()
        elif column.type.python_type == bool:
            type_dict[column.name] = Boolean()
        elif column.type.python_type == decimal.Decimal:
            type_dict[column.name] = Float()
        else:
            raise Exception(f'Unknown column type {column.type.python_type}')
    return type_dict
Exemplo n.º 16
0
class AddPosition(Mutation):
    class Arguments:
        name = String()
        position_group = Int()
        position_capacity = Int()
        default_show = Boolean()
        one_position = Boolean()

    success = Boolean()
    entity_id = Int()

    @auth(["EDIT_POSITION"])
    def mutate(self,
               info,
               name=None,
               position_group=-1,
               position_capacity=-1,
               default_show=False,
               one_position=False,
               *args,
               **kwargs):
        if name is not None and len(name) > 0:
            pgm = PositionGroupModel(position_group)
            if pgm.exists():
                if position_capacity > 0:
                    if name is not None and len(name) > 0:
                        pm = PositionModel(None)
                        id = pm.add_position(name, position_capacity,
                                             position_group, default_show,
                                             one_position)
                        return AddPosition(success=True, entity_id=id)
                    else:
                        return AddPosition(success=False, entity_id=-1)
                else:
                    return AddPosition(success=False, entity_id=-1)
            else:
                return AddPosition(success=False, entity_id=-1)
        else:
            return AddPosition(success=False, entity_id=-1)
Exemplo n.º 17
0
class AcceptanceAttribute:
    acc_id = Int()
    date = String()
    time = String()
    pati_id = String()
    pati_sei = String()
    pati_mei = String()
    pati_sei_kana = String()
    pati_mei_kana = String()
    pati_birth = String()
    pati_sex = String()
    status = String()
    depart_code = String()
    depart_name = String()
    physic_code = String()
    physic_name = String()
    appoint_id = String()
    appoint_time = String()
    account_time = String()
    medi_contents = String()
    place = String()
    memo = String()
Exemplo n.º 18
0
class Alert(ObjectType):
    """ Dynamo Alert Class """
    message = String()
    project = String()
    organization = String()
    status = Int()

    def __init__(self, project_name, organization):
        """ Class constructor """
        self.message, self.project = "", ""
        self.organization, self.status = "", 0
        project = str(project_name)
        organization = str(organization)
        resp = alert_domain.get_company_alert(organization, project)
        if resp:
            self.message = resp[0]['message']
            self.project = resp[0]['project_name']
            self.organization = resp[0]['company_name']
            self.status = resp[0]['status_act']

    def resolve_message(self, info):
        """ Resolve message attribute """
        del info
        return self.message

    def resolve_project(self, info):
        """ Resolve project attribute """
        del info
        return self.project

    def resolve_organization(self, info):
        """ Resolve organization attribute """
        del info
        return self.organization

    def resolve_status(self, info):
        """ Resolve status attribute """
        del info
        return self.status
Exemplo n.º 19
0
class ResultMedia(ObjectType):

    id = ID
    gif_format = Field(MediaTypes)
    url = String()
    dims = List(Int)
    duration = Float()
    preview = String()
    size = Int()

    @classmethod
    def create_from_data(cls, data):
        parsed_data = {}
        filtered_data = remove_non_implemented_fields(cls, data)

        for key, value in filtered_data.items():
            if key == 'gif_format':
                parsed_data.update({key: value.lower() if isinstance(value, str) else None})
            else:
                parsed_data.update({key: value})

        return cls(**parsed_data)
Exemplo n.º 20
0
class Query(graphene.ObjectType):
    """Root query for the /graphql endpoint"""

    color_schemes = Field(NonNull(List(NonNull(ColorScheme))),
                          kind=Kind(),
                          rank=Int(),
                          name=String())

    def resolve_color_schemes(root, info, kind=None, rank=None, name=None):
        """Traverse Colorbrewer 2.0 data structure"""

        data = load(JSON_FILE)

        if name is None:
            schemes = []
            for key, value in data.items():
                scheme = ColorScheme(name=key,
                                     kind=parse_kind(value['type']),
                                     palettes=parse_palettes(value))
                schemes.append(scheme)
        else:
            # Select scheme by name
            schemes = [
                ColorScheme(name=name,
                            kind=parse_kind(data[name]['type']),
                            palettes=parse_palettes(data[name]))
            ]

        # Filter by scheme kind
        if kind is not None:
            schemes = [scheme for scheme in schemes if scheme.kind == kind]

        # Filter by number of levels in a palette
        if rank is not None:
            schemes = [
                scheme for scheme in schemes
                if rank in [palette.rank for palette in scheme.palettes]
            ]
        return schemes
Exemplo n.º 21
0
class Family(ObjectType):
    """Task definition, static fields"""
    id = ID(required=True)
    name = String(required=True)
    meta = Field(Meta)
    depth = Int()
    proxies = List(lambda: FamilyProxy,
                   description="""Associated cycle point proxies""",
                   args=proxy_args,
                   resolver=get_nodes_by_id)
    parents = List(lambda: Family,
                   description="""Family definition parent.""",
                   args=def_args,
                   resolver=get_nodes_by_id)
    child_tasks = List(Task,
                       description="""Descendedant definition tasks.""",
                       args=def_args,
                       resolver=get_nodes_by_id)
    child_families = List(lambda: Family,
                          description="""Descendedant desc families.""",
                          args=def_args,
                          resolver=get_nodes_by_id)
Exemplo n.º 22
0
class Reports:
    order_report = DjangoFilterConnectionField(OrderNode)
    spec_reports = DjangoFilterConnectionField(SpecNode)
    sales_by_date = Field(SaleSummary, days=Int())

    def resolve_sales_by_date(self, info, days=None):
        permits = Xpref.permits()
        ps = PrefSpec.sales()
        if days:
            today = jdatetime.date.today()
            start_date = today - jdatetime.timedelta(days)
            permits = permits.filter(perm_date__gte=start_date)
            ps = ps.filter(xpref_id__perm_date__gte=start_date)
        count = permits.count()
        qty = PrefSpec.sales_qty(ps)
        kw = PrefSpec.sales_kw(ps)
        amount = PrefSpec.sales_amount(ps)
        income = Payment.objects.filter(xpref_id__in=permits).aggregate(
            amount=Sum('amount'))['amount']
        income = income if income else 0
        if income:
            percent = 100 * income / amount
        else:
            percent = 0

        remaining = amount - income
        if remaining:
            percent_remaining = 100 * remaining / amount
        else:
            percent_remaining = 0

        return SaleSummary(count=count,
                           qty=qty,
                           kw=kw,
                           amount=amount,
                           income=AmountPercentField(amount=income,
                                                     percent=percent),
                           remaining=AmountPercentField(
                               amount=remaining, percent=percent_remaining))
Exemplo n.º 23
0
class FakeCommit(ObjectType):
    class Meta:
        # Graphql object type that defaults to the class name, but we require
        # 'Commit'.
        name = 'Commit'

    status = Field(FakeStatus)
    checkSuites = Field(FakeCheckSuites, first=Int())

    def resolve_status(parent, info):
        seen = set()
        result = []
        for status in parent._statuses:
            if status.context not in seen:
                seen.add(status.context)
                result.append(status)
        # Github returns None if there are no results
        return result or None

    def resolve_checkSuites(parent, info, first=None):
        # Tests only utilize one check suite so return all runs for that.
        return parent._check_runs
Exemplo n.º 24
0
class Job(ObjectType):
    class Meta:
        description = """Jobs."""

    id = ID(required=True)
    submit_num = Int()
    state = String()
    # name and cycle_point for filtering/sorting
    name = String(required=True)
    cycle_point = String(required=True)
    task_proxy = Field(lambda: TaskProxy,
                       description="""Associated Task Proxy""",
                       required=True,
                       resolver=get_node_by_id)
    submitted_time = String()
    started_time = String()
    finished_time = String()
    batch_sys_job_id = ID()
    batch_sys_name = String()
    env_script = String()
    err_script = String()
    exit_script = String()
    execution_time_limit = Float()
    host = String()
    init_script = String()
    job_log_dir = String()
    owner = String()
    post_script = String()
    pre_script = String()
    script = String()
    work_sub_dir = String()
    batch_sys_conf = List(String)
    environment = List(String)
    directives = List(String)
    param_env_tmpl = List(String)
    param_var = List(String)
    extra_logs = List(String)
    messages = List(String)
class CalculationQuery(ObjectType):
    calculation_list = None
    get_calculations = Field(List(CalculationType), id=Int())
    async def resolve_get_calculations(self, info, id=None):
        calculation_list = []

        query_args = []
        if id:
            query_args.append({"match": {"id": id}})

        if id:
            res = es.search(
                index="calculations",
                body={
                    "size": 50,
                    "query": {
                        "bool": {
                            "must": query_args
                        }
                    }
                }
            )
            for hit in res['hits']['hits']:
                calculation_list.append(hit['_source'])
        else:
            res = es.search(
                index="calculations",
                body={
                    "size": 50,
                    "query": {
                        "match_all": {}
                    }
                }
            )
            for hit in res['hits']['hits']:
                calculation_list.append(hit['_source'])

        return calculation_list
Exemplo n.º 26
0
class BasicTripTimeStats(ObjectType):
    median = Float()
    percentile = Float(percentile=Int(required=True))

    def resolve_median(parent, info):
        first_date = util.parse_date(parent["date_str"])
        trip_time_median = trip_times.get_cached_trip_times(parent['route_metrics'].agency_id, first_date, "median", parent["start_time"], parent["end_time"])
        return trip_time_median.get_value(parent["route_metrics"].route_id, parent["direction_id"], parent["start_stop_id"], parent["end_stop_id"])

    def resolve_percentile(parent, info, percentile):
        first_date = util.parse_date(parent["date_str"])
        trip_time_percentile = trip_times.get_cached_trip_times(parent['route_metrics'].agency_id, first_date, "p10-median-p90", parent["start_time"], parent["end_time"])
        percentiles_arr = trip_time_percentile.get_value(parent["route_metrics"].route_id, parent["direction_id"], parent["start_stop_id"], parent["end_stop_id"])
        if percentiles_arr is None:
            raise Exception(f"There is no cached data for stops: {parent['start_stop_id']}, {parent['end_stop_id']}.")
        if percentile == 10:
            return percentiles_arr[0]
        elif percentile == 50:
            return percentiles_arr[1]
        elif percentile == 90:
            return percentiles_arr[2]
        else:
            raise Exception(f"User requested a percentile other than [ 10 | 50 | 90 ].")
Exemplo n.º 27
0
class StreamStore(ObjectType):
    name = String()
    start = DateTime()
    end = DateTime()
    current = Boolean()
    renditions = List(StreamRendition)
    playlist = String(start=DateTime(), duration=Float())
    thumbnail = String(date=DateTime(), max_width=Int())

    def resolve_playlist(self, info, start=None, duration=60):
        wseStreamingUrl, wseApplication = itemgetter(
            'wseStreamingUrl', 'wseApplication')(self.metadata)
        store, start, end = (0, 0, 0)
        return urljoin(wseStreamingUrl, (
            '{appplication}/{store}/playlist.m3u8?DVR&wowzadvrplayliststart={start}&wowzadvrplaylistduration={end}'.format(
                appplication=wseApplication,
                store=store,
                start=start,
                end=end)
            ))

    def resolve_thumbnail(self, date, max_width):
        return ''
Exemplo n.º 28
0
def build_query_objs():
    queries = {}
    models = apps.get_app_config('geneticus').get_models()

    for model in models:
        model_name = model.__name__
        meta_class = create_model_object_meta(model)

        node = type(
            '{model_name}'.format(model_name=model_name), (DjangoObjectType, ),
            dict(
                Meta=meta_class,
                _id=Int(name='_id'),
                resolve__id=id_resolver,
            ))
        queries.update({model_name: PlainTextNode.Field(node)})
        queries.update({
            'all_{model_name}'.format(model_name=model_name):
            DjangoFilterConnectionField(
                node, filterset_class=create_model_in_filters(model))
        })
    queries['debug'] = Field(DjangoDebug, name='__debug')
    return queries
Exemplo n.º 29
0
    class Arguments:
        course_id = ID(name="id")
        course_type = CourseTypeEnum()
        academic_level = AcademicLevelEnum()
        title = String()
        description = String()
        instructor_id = ID(name="instructor")
        hourly_tuition = Decimal()
        total_tuition = Decimal()
        course_category_id = ID(name="courseCategory")

        course_link = String()
        course_link_description = String()

        google_class_code = String()

        # Logistical information
        room = String()
        start_date = DateTime()
        end_date = DateTime()
        max_capacity = Int()
        is_confirmed = Boolean()
        availabilities = List(CourseAvailabilityInput)
Exemplo n.º 30
0
class Query(ObjectType):

    user = Field(List(UserType), id=String())
    matchups = Field(List(Matchup), leagueId=String(), week=Int())
    rosters = Field(List(Roster), leagueId=String())

    def resolve_user(parent, info, id):
        user = User(id)
        league_info = user.get_all_leagues("nfl", 2020)
        info_list = []
        for i in league_info:
            info = UserType.from_json(i)
            info_list.append(info)

        return info_list

    def resolve_matchups(parent, info, leagueId, week):
        league = League(leagueId)
        leagueMatchups = league.get_matchups(week)
        match_list = []

        for i in leagueMatchups:
            matches = Matchup.from_json(i)
            match_list.append(matches)

        return match_list

    def resolve_rosters(parent, info, leagueId):
        league = League(leagueId)
        leagueRosters = league.get_rosters()
        roster_list = []

        for i in leagueRosters:
            rosters = Roster.from_json(i)
            roster_list.append(rosters)

        return roster_list