<commit_before>__author__ = '<NAME>'

from flask import abort, json, current_app
from flask.ext.restful import Resource, reqparse, marshal
from opencog.atomspace import Handle
from mappers import *
from flask.ext.restful.utils import cors

class AtomCollectionAPI(Resource):
    # This is because of https://github.com/twilio/flask-restful/issues/134
    @classmethod
    def new(cls, atomspace):
        cls.atomspace = atomspace
        return cls

    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('type', type=str, location='args', choices=types.__dict__.keys())
        self.reqparse.add_argument('name', type=str, location='args')
        self.reqparse.add_argument('callback', type=str, location='args')
        self.reqparse.add_argument('filterby', type=str, location='args',
                                   choices=['stirange', 'attentionalfocus'])
        self.reqparse.add_argument('stimin', type=int, location='args')
        self.reqparse.add_argument('stimax', type=int, location='args')
        self.reqparse.add_argument('tvStrengthMin', type=float, location='args')
        self.reqparse.add_argument('tvConfidenceMin', type=float, location='args')
        self.reqparse.add_argument('tvCountMin', type=float, location='args')
        self.reqparse.add_argument('includeIncoming', type=str, location='args',
                                   choices=['true', 'false', 'True', 'False', '0', '1'])
        self.reqparse.add_argument('includeOutgoing', type=str, location='args',
                                   choices=['true', 'false', 'True', 'False', '0', '1'])

        super(AtomCollectionAPI, self).__init__()

    # Set CORS headers to allow cross-origin access (https://github.com/twilio/flask-restful/pull/131):
    @cors.crossdomain(origin='*')
    def get(self, id=""):
        """
        Returns a list of atoms matching the specified criteria
        Uri:

        atoms/[id]
        (or)
        atoms?type=[type]&name=[name]&filterby=[filterby]&tvStrengthMin=[tvStrengthMin]
            &tvConfidenceMin=[tvConfidenceMin]&tvCountMin=[tvCountMin]&includeIncoming=[includeIncoming]
            &includeOutgoing=[includeOutgoing]&callback=[callback]

        :param id: (optional, int, to specifically request an atom by handle, can be combined with includeIncoming or
            includeOutgoing only; if specified, other query parameters will have no effect) Atom handle

        :param type: (optional) Atom type, see http://wiki.opencog.org/w/OpenCog_Atom_types
        :param name: (optional, string, not allowed for Link types) Atom name
        If neither type or name are provided, all atoms will be retrieved
        :param filterby: (optional, can't be combined with type or name) Allows certain predefined filters
          - The filter 'stirange' allows the additional parameters 'stimin' (required, int) and 'stimax' (optional, int)
            and returns the atoms in a given STI range
          - The filter 'attentionalfocus' (boolean) returns the atoms in the AttentionalFocus
        :param tvStrengthMin: (optional, float) Only return atoms with TruthValue strength greater than this amount
        :param tvConfidenceMin: (optional, float) Only return atoms with TruthValue confidence greater than this amount
        :param tvCountMin: (optional, float) Only return atoms with TruthValue count greater than this amount
        :param includeIncoming: (optional, boolean) Returns the conjunction of the set of atoms and their incoming sets
        :param includeOutgoing: (optional, boolean) Returns the conjunction of the set of atoms and their outgoing sets
            Useful in combination with includeIncoming.

        :param callback: (optional) JavaScript callback function for JSONP support

        :return result: Returns a JSON representation of an atom list.
        Example:

        {
          'result':
          {
            'complete': 'true',
            'skipped': 'false',
            'total': 10,
            'atoms':
              [
                { 'handle': 6,
                  'name': '',
                  'type': 'InheritanceLink',
                  'outgoing': [2, 1],
                  'incoming': [],
                  'truthvalue':
                    {
                      'type': 'simple',
                      'details':
                        {
                          'count': '0.4000000059604645',
                          'confidence': '0.0004997501382604241',
                          'strength': '0.5'
                        }
                    }
                  'attentionvalue':
                    {
                      'lti': 0,
                      'sti': 0,
                      'vlti': false
                    }
                },
                     ...
              ]
          }
        }
        """

        args = self.reqparse.parse_args()
        type = args.get('type')
        name = args.get('name')
        callback = args.get('callback')

        filter_by = args.get('filterby')
        sti_min = args.get('stimin')
        sti_max = args.get('stimax')

        tv_strength_min = args.get('tvStrengthMin')
        tv_confidence_min = args.get('tvConfidenceMin')
        tv_count_min = args.get('tvCountMin')

        include_incoming = args.get('includeIncoming')
        include_outgoing = args.get('includeOutgoing')

        if id != "":
            try:
                atom = self.atomspace[Handle(id)]
                atoms = [atom]
            except IndexError:
                # abort(404, 'Handle not found')
                atoms = []
        else:
            # First, check if there is a valid filter type, and give it precedence if it exists
            valid_filter = False
            if filter_by is not None:
                if filter_by == 'stirange':
                    if sti_min is not None:
                        valid_filter = True
                        atoms = self.atomspace.get_atoms_by_av(sti_min, sti_max)
                    else:
                        abort(400, 'Invalid request: stirange filter requires stimin parameter')
                elif filter_by == 'attentionalfocus':
                    valid_filter = True
                    atoms = self.atomspace.get_atoms_in_attentional_focus()<commit_msg>Fixes issue #502<commit_after>__author__ = '<NAME>'

from flask import abort, json, current_app
from flask.ext.restful import Resource, reqparse, marshal
from opencog.atomspace import Handle
from mappers import *
from flask.ext.restful.utils import cors

class AtomCollectionAPI(Resource):
    # This is because of https://github.com/twilio/flask-restful/issues/134
    @classmethod
    def new(cls, atomspace):
        cls.atomspace = atomspace
        return cls

    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('type', type=str, location='args', choices=types.__dict__.keys())
        self.reqparse.add_argument('name', type=str, location='args')
        self.reqparse.add_argument('callback', type=str, location='args')
        self.reqparse.add_argument('filterby', type=str, location='args',
                                   choices=['stirange', 'attentionalfocus'])
        self.reqparse.add_argument('stimin', type=int, location='args')
        self.reqparse.add_argument('stimax', type=int, location='args')
        self.reqparse.add_argument('tvStrengthMin', type=float, location='args')
        self.reqparse.add_argument('tvConfidenceMin', type=float, location='args')
        self.reqparse.add_argument('tvCountMin', type=float, location='args')
        self.reqparse.add_argument('includeIncoming', type=str, location='args',
                                   choices=['true', 'false', 'True', 'False', '0', '1'])
        self.reqparse.add_argument('includeOutgoing', type=str, location='args',
                                   choices=['true', 'false', 'True', 'False', '0', '1'])

        super(AtomCollectionAPI, self).__init__()

    # Set CORS headers to allow cross-origin access (https://github.com/twilio/flask-restful/pull/131):
    @cors.crossdomain(origin='*')
    def get(self, id=""):
        """
        Returns a list of atoms matching the specified criteria
        Uri:

        atoms/[id]
        (or)
        atoms?type=[type]&name=[name]&filterby=[filterby]&tvStrengthMin=[tvStrengthMin]
            &tvConfidenceMin=[tvConfidenceMin]&tvCountMin=[tvCountMin]&includeIncoming=[includeIncoming]
            &includeOutgoing=[includeOutgoing]&callback=[callback]

        :param id: (optional, int, to specifically request an atom by handle, can be combined with includeIncoming or
            includeOutgoing only; if specified, other query parameters will have no effect) Atom handle

        :param type: (optional) Atom type, see http://wiki.opencog.org/w/OpenCog_Atom_types
        :param name: (optional, string, not allowed for Link types) Atom name
        If neither type or name are provided, all atoms will be retrieved
        :param filterby: (optional, can't be combined with type or name) Allows certain predefined filters
          - The filter 'stirange' allows the additional parameters 'stimin' (required, int) and 'stimax' (optional, int)
            and returns the atoms in a given STI range
          - The filter 'attentionalfocus' (boolean) returns the atoms in the AttentionalFocus
        :param tvStrengthMin: (optional, float) Only return atoms with TruthValue strength greater than this amount
        :param tvConfidenceMin: (optional, float) Only return atoms with TruthValue confidence greater than this amount
        :param tvCountMin: (optional, float) Only return atoms with TruthValue count greater than this amount
        :param includeIncoming: (optional, boolean) Returns the conjunction of the set of atoms and their incoming sets
        :param includeOutgoing: (optional, boolean) Returns the conjunction of the set of atoms and their outgoing sets
            Useful in combination with includeIncoming.

        :param callback: (optional) JavaScript callback function for JSONP support

        :return result: Returns a JSON representation of an atom list.
        Example:

        {
          'result':
          {
            'complete': 'true',
            'skipped': 'false',
            'total': 10,
            'atoms':
              [
                { 'handle': 6,
                  'name': '',
                  'type': 'InheritanceLink',
                  'outgoing': [2, 1],
                  'incoming': [],
                  'truthvalue':
                    {
                      'type': 'simple',
                      'details':
                        {
                          'count': '0.4000000059604645',
                          'confidence': '0.0004997501382604241',
                          'strength': '0.5'
                        }
                    }
                  'attentionvalue':
                    {
                      'lti': 0,
                      'sti': 0,
                      'vlti': false
                    }
                },
                     ...
              ]
          }
        }
        """

        args = self.reqparse.parse_args()
        type = args.get('type')
        name = args.get('name')
        callback = args.get('callback')

        filter_by = args.get('filterby')
        sti_min = args.get('stimin')
        sti_max = args.get('stimax')

        tv_strength_min = args.get('tvStrengthMin')
        tv_confidence_min = args.get('tvConfidenceMin')
        tv_count_min = args.get('tvCountMin')

        include_incoming = args.get('includeIncoming')
        include_outgoing = args.get('includeOutgoing')

        if id != "":
            try:
                atom = self.atomspace[Handle(id)]
                atoms = [atom]
            except IndexError:
                atoms = []
                # abort(404, 'Handle not found')
        else:
            # First, check if there is a valid filter type, and give it precedence if it exists
            valid_filter = False
            if filter_by is not None:
                if filter_by == 'stirange':
                    if sti_min is not None:
                        valid_filter = True
                        atoms = self.atomspace.get_atoms_by_av(sti_min, sti_max)
                    else:
                        abort(400, 'Invalid request: stirange filter requires stimin parameter')
                elif filter_by == 'attentionalfocus':
                    valid_filter = True
                    atoms = self.atomspace.get_atoms_in_attentional_focus()
{'fraction_non_alphanumeric': 0.10295391886569516, 'fraction_numerical': 0.010003938558487593, 'mean_word_length': 1.9922224840914446, 'pattern_counts': {'":': 2, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 2, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5515852', 'n_tokens_mistral': 3493, 'n_tokens_neox': 3272, 'n_words': 905}